【问题标题】:Slick use Postgres Sequence instead of serialSlick 使用 Postgres 序列而不是串行
【发布时间】:2014-05-21 03:23:03
【问题描述】:

我的 postgres 中有一个现有的架构,并且我想使用 Slick,如何强制此 id 列在 Slick 中使用 postgres 序列?

class User(id: Int, first: String, last: String)

class Users(tag: Tag) extends Table[Int](tag, "users") {
  def id = column[Int]("id", O PrimaryKey)
  def * = id
}
val users = TableQuery[Users]

val usersSequence = Sequence[Int]("users_seq") start 1 inc 1

这是我现有的架构:

create table users (
  id                 bigint not null,
  ...
)
create sequence users_seq;

【问题讨论】:

  • A serialis 使用序列。所以我不确定你在问什么。
  • 我的意思是我想使用 Slick 来读取我当前使用序列和 bigint 的现有架构。

标签: postgresql scala slick


【解决方案1】:

正如@a_horse_with_no_name 所说,串行列正在使用序列。在Slick 中,您只需使用AutoInc 定义您的列,在您的情况下:

def id = column[Int]("id", O.AutoInc, O.PrimaryKey)

PostgreSQL 一侧定义Serial 列时,您只需返回带有Default Value: nextval('user_id_seq'::regclass)Int 列,这是用于递增值的序列。

无需在架构代码中手动创建序列:

class User(id: Int, first: String, last: String)

class Users(tag: Tag) extends Table[Int](tag, "users") {
  def id = column[Int]("id", O.AutoInc, O.PrimaryKey)
  def * = id
}

val users = TableQuery[Users]

评论后编辑:

我运行了你的 sql 语句,为序列添加了表 alter:

create table users (
  id                 bigint not null
);

create sequence users_seq;
alter table users alter column id set default nextval('users_seq');

现在在我的数据库中,我有一个表,其中包含 id 类型的 Int 列,默认值是序列:nextval('users_seq'::regclass)。这和我之前写的一样,你有一个表,它有一个应用于 id 列的序列,slick 代码也没有改变,你可以尝试在本地数据库上运行它。

请注意,您的 sql 语句是错误的,您确实创建了一个序列但它没有分配给任何列,您必须使用 alter 或直接添加具有序列的列,如 here 所示。希望这更清楚。

附:我不完全确定的一件事是 BigInt Postgres 字段映射到 Scala Long,但可能顺序无关紧要,但不确定,为了保持一致性,我总是将它们映射到 Long

【讨论】:

  • 我的意思是我想使用 Slick 来读取我当前使用序列和 bigint 的现有模式。我更新了问题。
猜你喜欢
  • 2019-11-29
  • 1970-01-01
  • 2017-03-09
  • 2017-05-25
  • 2015-07-24
  • 2021-12-11
  • 2015-11-24
  • 2012-08-25
  • 2011-01-06
相关资源
最近更新 更多