使用默认值插入并获取ID



我有这个表:

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")
}

我想要实现的是使用默认值为name插入一行并返回id,查看我看到的光滑文档:

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

和this:

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

,他们确实工作奇异,我想要的是两者的混合,我尝试了这个:

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

但是会抛出一个异常,表示name不能为空:

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

我是这样做的:

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

我不明白的是这是否是指定默认值的正确方式,如果是,如果我将来使用这样的函数该怎么办:

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

我是否必须在使用O.Default的字段上指定默认值?

Default仅用于生成DDL。在构造实例时使用case类中的默认值。如果您使用DDL生成并希望在实例中使用它,则需要在两个位置指定它。

val name: Column[Option[String]]错误。它应该是val name: Column[String],因为postgres告诉你的名字是不可空的:ERROR: null value in column "name" violates not-null constraint .

最新更新