3

I have an existing schema in my postgres and I want to use Slick, how can I enforce this id column to use postgres sequence in Slick?

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

This is my existing schema:

create table users (
  id                 bigint not null,
  ...
)
create sequence users_seq;
2
  • 2
    A serial column is using a sequence. So I'm not sure what you are asking. Commented May 21, 2014 at 6:01
  • I mean I want to use Slick to read my current existing schema which uses sequence and bigint. Commented May 21, 2014 at 13:16

1 Answer 1

3

As said by @a_horse_with_no_name, a serial Column is using a sequence. In Slick you simply need to define your column with AutoInc, in your case:

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

On the PostgreSQL side when defining a Serial column you simply get back an Int column with Default Value: nextval('user_id_seq'::regclass), which is the sequence used to increment the value.

There's no need to manually create a sequence in your schema code:

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]

Edit after comment:

I ran your sql statement adding the table alter for the sequence:

create table users (
  id                 bigint not null
);

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

On my database now I have a table with a column id of type Int and as default value the sequence: nextval('users_seq'::regclass). This is the same thing I wrote before, you have a table with a sequence that is applied to the id column, the slick code doesn't change too, you can try running this on a local database.

Note that your sql statement is wrong, you do create a sequence but it's not assigned to any column, you either have to use the alter or directly add a column with the sequence as shown here. Hope this was clearer.

P.s. One thing I'm not completely sure about is that BigInt Postgres fields are mapped to Scala Long, but probably with the sequence it doesn't matter, not sure though, for consistency I always map them to Long.

Sign up to request clarification or add additional context in comments.

1 Comment

I mean I want to use Slick to read my current existing schema which uses sequence and bigint. I updated the question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.