Question

I have this table:

case class CityRow(id: Long = 0, name: Option[String])

class City(tag: Tag) extends RichTable[CityRow](tag, "city") {
  def * = (id, name) <>(CityRow.tupled, CityRow.unapply)

  def ? = (id.?, name).shaped.<>({
    r => import r._; _1.map(_ => CityRow.tupled((_1.get, _2)))
  }, (_: Any) => throw new Exception("Inserting into ? projection not supported."))

  override val id: Column[Long] = column[Long]("id", O.AutoInc, O.PrimaryKey)

  val name: Column[Option[String]] = column[Option[String]]("name", O.Default("no_name")
}

What I would like to achieve is insert a row using the default value for name and return the id, looking on the slick documentation I saw this:

val userId = (users returning users.map(_.id)) += User(None, "Stefan", "Zeiger")

and this:

coffees.map(c => (c.name, c.supID, c.price)) += ("Colombian_Decaf", 101, 8.99)

and they indeed work singularly, what I want though is a mix of the two, I tried this:

(tableReference returning tableReference.map(_.id)) += (CityRow(name = None))

But an exception is thrown saying that name cannot be null:

PSQLException: : ERROR: null value in column "name" violates not-null constraint
Detail: Failing row contains (64, null).  (QueryExecutorImpl.java:2103)

What I did to make it work was this:

case class CityRow(id: Long = 0, name: Option[String] = "no_name")

What I don't understand is whether this is the correct way of specifying defaults, and if so what if I use a function like this in the future:

coffees.map(c => (c.name, c.supID, c.price)) += ("Colombian_Decaf", 101, 8.99)

Will I have to specify the default value also on the field using O.Default?

Was it helpful?

Solution

O.Default is only used for DDL generation. The default in the case class is used when constructing an instance. If you use DDL generation and want it in your instances you need to specify it in both places.

val name: Column[Option[String]] is wrong. It should be val name: Column[String], because as postgres tells you name is not nullable: ERROR: null value in column "name" violates not-null constraint.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top