如果列值为“无",则使用 slick 插入默认值 [英] Inserting default values if column value is 'None' using slick

查看:54
本文介绍了如果列值为“无",则使用 slick 插入默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题很简单.

我在 CREATE TABLE 语句中有一个 seqNum: Double 列,它是 NOT NULL DEFAULT 1 ,如下所示:

I have a column seqNum: Double which is NOT NULL DEFAULT 1 in CREATE TABLE statement as follows:

CREATE TABLE some_table
(
    ...
    seq_num DECIMAL(18,10) NOT NULL DEFAULT 1,
    ...
);

用户可以从 UI 输入或不输入 seqNum 的值.所以接受 PLAY 的形式是这样的:

User can enter a value for seqNum or not from UI. So the accepting PLAY form is like:

case class SomeCaseClass(..., seqNum: Option[Double], ...)
val secForm = Form(mapping(
    ...
    "seqNum" -> optional(of[Double]),
    ...
  )(SomeCaseClass.apply)(SomeCaseClass.unapply))

圆滑的表架构 &对象看起来像这样:

The slick Table Schema & Objects looks like this:

case class SomeSection (
   ...
   seqNum: Option[Double],
   ...
)
class SomeSections(tag: Tag) extends Table[SomeSection](tag, "some_table") {
  def * = (
      ...
      seqNum.?,
      ...
    ) <> (SomeSection.tupled, SomeSection.unapply _)

  ...
  def seqNum = column[Double]("seq_num", O.NotNull, O.Default(1))
  ...
}
object SomeSections {

  val someSections = TableQuery[SomeSections]
  val autoInc = someSections returning someSections.map(_.sectionId)

  def insert(s: someSection)(implicit session: Session) = {
     autoInc.insert(s)
  }
}

当我从 UI 发送 seqNum 时,一切正常,但是当 None 存在时,它会中断说 cannot insert NULL in NOT NULL 列 这是正确的.这个问题解释了原因.

When I'm sending seqNum from UI, everything is works fine but when None is there, it breaks saying that cannot insert NULL in NOT NULL column which is correct. This question explains why.

但是如何使用 slick 解决这个问题?不明白我应该在哪里检查 None?我正在创建 &将 SomeSection 的对象发送到 SomeSections 对象的 insert 方法.

But how to solve this problem using slick? Can't understand where should I check about None? I'm creating & sending an object of SomeSection to insert method of SomeSections Object.

如果重要的话,我正在使用 sql-server.

I'm using sql-server, if it matters.

推荐答案

使用默认值要求根本不插入值,而不是插入 NULL.这意味着您将需要一个自定义投影来插入.

Using the default requires not inserting the value at all rather than inserting NULL. This means you will need a custom projection to insert to.

people.map(_.name).insert("Chris") 将对所有其他字段使用默认值.scala 的本机元组转换和 case 类转换的局限性可能会使这有点麻烦.Slick 的 HLists、Shapeless、Scala Records 或 Scala XR 之类的东西可以提供帮助,但目前并非微不足道或非常具有实验性.

people.map(_.name).insert("Chris") will use defaults for all other fields. The limitations of scala's native tuple transformations and case class transformations can make this a bit of a hassle. Things like Slick's HLists, Shapeless, Scala Records or Scala XR can help, but are not trivial or very experimental at the moment.

这篇关于如果列值为“无",则使用 slick 插入默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆