Squeryl and PostgreSQL's autoincrement

删除回忆录丶 提交于 2020-01-05 07:11:24

问题


When I try to insert a new record in a PostgreSQL table using Squeryl's Table.insert, it fires this query:

insert into "users" ("id", "email", "fullname") values (nextval('"s_users_id"'),?,?)

This doesn't work, as I did not define a sequence and instead defined the id column to be "autoincrement":

CREATE TABLE Users (
    id BIGSERIAL,
    email varchar(255) NOT NULL,
    fullname varchar(255),
    PRIMARY KEY (id)
);

I read some old post in another forum about this issue, and I was wondering what the status is now. Are we discouraged to use autoincrement and define a sequence instead? Or is there a simple workaround to get this working?

Edit: In fact just now I see that the autoincrement itself creates a serial, but under another name: users_id_seq Is there a way to tell Squeryl to look under this name instead, or follow PostgreSQL's convention?


回答1:


You can declare name of the sequence:

 case class Author(id: Long, firstName: String)             

 val author = table[Author]

 on(author)(s => declare(
    s.id is(autoIncremented("your_seq_name"))
 ))

more information: http://squeryl.org/schema-definition.html




回答2:


There isn't a terribly clean way to do it right now, but it can be done. Just subclass PostgreSqlAdapter and override:

def createSequenceName(fmd: FieldMetaData)




回答3:


serial or bigserial will create a sequence in the background from which the values for the column are taken. So the insert is basically correct.

bigserial is just a shorthand for:

create sequence users_id_seq;
create table users (id bigint default nextval('users_id_seq'));

The only thing that seems wrong is that default name of the sequence for your id column would be users_id_seq, not s_users_id as used by your tool.

More details in the manual: http://www.postgresql.org/docs/current/static/datatype-numeric.html#DATATYPE-SERIAL

Edit:
One possible workaround if that tool assumes the wrong naming convention is to rename the generated sequence. As Postgres "knows" it belongs to the column things will still work.

ALTER SEQUENCE users_id_seq RENAME TO s_users_id;


来源:https://stackoverflow.com/questions/12794427/squeryl-and-postgresqls-autoincrement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!