deferable 最初在 postgresql 中延迟
我在两个表上有一个循环外键,所以我使用 deferrable 最初延迟如下:
uni=# create table vorlesungen (vnr integer primary key, gelesenvon integer);
NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "vorlesungen_pkey" for table "vorlesungen"
CREATE TABLE
uni=# create table professoren (pnr integer primary key, lieblingsvo integer);
NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "professoren_pkey" for table "professoren"
CREATE TABLE
uni=# alter table professoren add constraint vfk foreign key (lieblingsvo) references vorlesungen (vnr) deferrable initially deferred;
ALTER TABLE
uni=# alter table vorlesungen add constraint pfk foreign key (gelesenvon) references professoren (pnr) deferrable initially deferred;
ALTER TABLE
到目前为止一切顺利。 但现在当我想插入到表中时,我遇到了外键违规,尽管我最初指定了可延迟:
uni=# insert into vorlesungen values (1, 1);
ERROR: insert or update on table "vorlesungen" violates foreign key constraint "pfk"
DETAIL: Key (gelesenvon)=(1) is not present in table "professoren".
uni=# insert into professoren values (1, 1);
ERROR: insert or update on table "professoren" violates foreign key constraint "vfk"
DETAIL: Key (lieblingsvo)=(1) is not present in table "vorlesungen".
问题是什么?
I have a cyclic foreign keys on 2 tables, so i use deferrable initially deferred as below:
uni=# create table vorlesungen (vnr integer primary key, gelesenvon integer);
NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "vorlesungen_pkey" for table "vorlesungen"
CREATE TABLE
uni=# create table professoren (pnr integer primary key, lieblingsvo integer);
NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "professoren_pkey" for table "professoren"
CREATE TABLE
uni=# alter table professoren add constraint vfk foreign key (lieblingsvo) references vorlesungen (vnr) deferrable initially deferred;
ALTER TABLE
uni=# alter table vorlesungen add constraint pfk foreign key (gelesenvon) references professoren (pnr) deferrable initially deferred;
ALTER TABLE
so far so good.
but now when i want to insert into the tables, i get foreign key violations, although i specified deferrable initially deferred:
uni=# insert into vorlesungen values (1, 1);
ERROR: insert or update on table "vorlesungen" violates foreign key constraint "pfk"
DETAIL: Key (gelesenvon)=(1) is not present in table "professoren".
uni=# insert into professoren values (1, 1);
ERROR: insert or update on table "professoren" violates foreign key constraint "vfk"
DETAIL: Key (lieblingsvo)=(1) is not present in table "vorlesungen".
whats the problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您是否在之前明确开启交易
插入?如果不使用 BEGIN,则每个插入都是一个独立的事务,因此在每个命令末尾强制使用外键。
Are you explicitly opening a transaction before the
INSERTs? If you do not use BEGIN, each insert is an independent transaction, therefore enforcing the foreign keys at the end of each command.