Ruby 使用DataMapper和旧版PostgreSQL db自动增加密钥
我有一个现有的PostgreSQL数据库,我想用Ruby DataMapper访问它。我已经根据现有的数据库模式创建了模型,但是主键不是自动递增的 我的模型是这样的:Ruby 使用DataMapper和旧版PostgreSQL db自动增加密钥,ruby,postgresql,doctrine,datamapper,Ruby,Postgresql,Doctrine,Datamapper,我有一个现有的PostgreSQL数据库,我想用Ruby DataMapper访问它。我已经根据现有的数据库模式创建了模型,但是主键不是自动递增的 我的模型是这样的: class Company include DataMapper::Resource property :id, Serial property :name, String end SELECT NEXTVAL('"production"."sequence_id_seq"') INSERT INTO "prod
class Company
include DataMapper::Resource
property :id, Serial
property :name, String
end
SELECT NEXTVAL('"production"."sequence_id_seq"')
INSERT INTO "production"."companies" ("name", "id") VALUES ('Acme Inc.', 40711)
CREATE TABLE production.companies
(
id bigint NOT NULL,
"name" character varying(255) NOT NULL,
CONSTRAINT companies_pkey PRIMARY KEY (id),
)
WITH (
OIDS=FALSE
);
将id
定义为Serial
没有效果:当我创建实例时,由于违反了NOTNULL约束,我得到了一个DataObjects::IntegrityError
数据库与PHP/Doctrine应用程序共享,因此我无法更改模式。PHP应用程序使用序列创建主键,如下所示:
class Company
include DataMapper::Resource
property :id, Serial
property :name, String
end
SELECT NEXTVAL('"production"."sequence_id_seq"')
INSERT INTO "production"."companies" ("name", "id") VALUES ('Acme Inc.', 40711)
CREATE TABLE production.companies
(
id bigint NOT NULL,
"name" character varying(255) NOT NULL,
CONSTRAINT companies_pkey PRIMARY KEY (id),
)
WITH (
OIDS=FALSE
);
该表如下所示:
class Company
include DataMapper::Resource
property :id, Serial
property :name, String
end
SELECT NEXTVAL('"production"."sequence_id_seq"')
INSERT INTO "production"."companies" ("name", "id") VALUES ('Acme Inc.', 40711)
CREATE TABLE production.companies
(
id bigint NOT NULL,
"name" character varying(255) NOT NULL,
CONSTRAINT companies_pkey PRIMARY KEY (id),
)
WITH (
OIDS=FALSE
);
这是等效的条令模式定义:
CompanyOrm:
tableName: companies
columns:
id:
type: integer(8)
unsigned: 1
primary: true
sequence: sequence_id
name:
type: string(255)
notnull: true
如何使用DataMapper重新创建该行为?或者有什么其他(更好的)解决方案可以在这种情况下创建自动递增键?您可以在表达式中使用
nextval()
函数获取并使用下一个序列值作为id
:
INSERT INTO "production"."companies" ("name", "id")
VALUES ('Acme Inc.', nextval('production.sequence_id_seq') )
我对DataMapper了解不够,无法说明是否有可能在插入中使用函数,但也许可以通过定义自己的函数(而不是串行)来实现这一点
或者,您可以更改表,使行默认为使用序列,这不应破坏与手动使用相同序列的任何内容的兼容性:
ALTER TABLE production.companies
ALTER COLUMN id SET DEFAULT nextval('production.sequence_id_seq');