具有排除约束的Postgres UPSERT

时间:2020-07-13 18:39:03

标签: sql postgresql

给出下表:

create table some_table
(
    id                 uuid      default uuid_generate_v4() not null,
    last_modified_date timestamp default now()              not null,
    foreign_key        text,
    start              integer,
    end                integer,
    constraint some_table_pkey
        primary key (id),
    constraint some_table_foreign_key_fkey
        foreign key (foreign_key) references foreign_table
);

然后我添加了以下约束:

CREATE INDEX some_table_foreign_key_idx
    ON some_table (foreign_key);

ALTER table some_table
    ADD CONSTRAINT some_table_start_check
        check (start > 0);

ALTER TABLE some_table
    add CONSTRAINT some_table_check
        check (end >= start);

ALTER TABLE some_table
    ADD CONSTRAINT unique_interval_to_foreign_key_constraint
        EXCLUDE USING gist
        (foreign_key WITH =,
         int4range(start, end, '[]') WITH &&
        );

像这样生成表:

+--------------------------------------+-------+-----+--------------------+--------------------------------------+
| id                                   | start | end | last_modified_date | foreign_key                          |
+--------------------------------------+-------+-----+--------------------+--------------------------------------+
| 04ef8258-917c-46d6-8db4-9c704d3f4fbd | 10    | 20  | timestampA         | 04ef8258-917c-46d6-8db3-9c704d3f4fbd |
+--------------------------------------+-------+-----+--------------------+--------------------------------------+
| 04ef8258-917c-46d6-8db5-9c704d3f4fbd | 40    | 60  | timestampB         | 04ef8258-917c-46d6-8db3-9c704d3f4fbd |
+--------------------------------------+-------+-----+--------------------+--------------------------------------+

我如何INSERT记录到该表中?

我尝试了什么?

INSERT INTO some_table (foreign_key, start, end) 
VALUES (`04ef8258-917c-46d6-8db3-9c704d3f4fbd`,  70, 80) 
ON CONFLICT (foreign_key, start, end) 
   DO UPDATE SET last_modified_date=NOW() RETURNING id;

我收到以下错误:

UnableToExecuteStatementException:org.postgresql.util.PSQLException:错误:ON CONFLICT DO UPDATE需要推理规范或约束名称

0 个答案:

没有答案