Play Slick 2.1.0 This DBMS allows only a single AutoInc column to be returned from an INSERT
Asked Answered
F

1

7

In the following code I can insert my records just fine. But I would really like to get back the ID of the inserted value so that I can then return the object as part of my response.

def postEntry = DBAction { request =>
  request.body.asJson.map {json =>
    json.validate[(String, Long, String)].map {
      case (name, age, lang) => {
        implicit val session = request.dbSession
        val something = Entries += Entry(None, name, age, lang)
        Ok("Hello!!!: " + something)
      }
    }.recoverTotal {
    e => BadRequest("Detected error: " + JsError.toFlatJson(e))
    }
   }.getOrElse {
   BadRequest("Expecting Json data")
  }
}

So I tried changing the insert to:

 val something = (Entries returning Entries.map(_.id)) += Entry(None, name, age, lang)

But I get the following exception:

SlickException: This DBMS allows only a single AutoInc column to be returned from an INSERT

There is a note about it here: http://slick.typesafe.com/doc/2.1.0/queries.html

"Note that many database systems only allow a single column to be returned which must be the table’s auto-incrementing primary key. If you ask for other columns a SlickException is thrown at runtime (unless the database actually supports it)."

But it doesn't say how to just request the ID column.

Faints answered 29/8, 2014 at 21:4 Comment(2)
Doesn't Entries have a primary key? I don't think your id column is the one, you are passing None into Entry which makes me think that it's optional.Drown
Thanks! You made me think about my mapping and I went back and checked it out. I managed to roll back my primary key def and auto increment def on the Table mapping.Faints
F
7

Ende Nue above gave me the hint to find the problem. I needed to have the column marked primary key and auto increment in the table definition.

class Entries(tag: Tag) extends Table[Entry](tag, "entries") {

  def id = column[Option[Long]]("id", O.PrimaryKey, O.AutoInc)
  def name = column[String]("name")
  def age = column[Long]("age")
  def lang = column[String]("lang")

  def * = (id, name, age, lang).shaped <> ((Entry.apply _)tupled, Entry.unapply _)
}

O.PrimaryKey, O.AutoInc

Faints answered 29/8, 2014 at 22:3 Comment(2)
This still doesnt solve my problem. Did this solution fixed the error for you?Hoffer
This is a better overview of the problem github.com/slick/slick/issues/1561Capablanca

© 2022 - 2024 — McMap. All rights reserved.