实现说明
一个文件里不止一条语句:INSERT / UPDATE / CREATE,devices、set 都在涉及之列。
真正干活的子句:upsert 守卫(ON CONFLICT/MERGE)把插入或更新合并成一条原子语句;RETURNING 把受影响的行交回调用方;必填列上的 NOT NULL 限定;强制行身份的 PRIMARY KEY;把重复值挡在外面的 UNIQUE 约束;自动算列值的 GENERATED ALWAYS/GENERATED BY 子句。
常见问题
这段 SQL 涉及哪些关系?
devices、set——直接引用,无需连接。
核心语句
INSERT INTO devices (serial) VALUES ('SN-100')
ON CONFLICT (serial) DO UPDATE SET serial = EXCLUDED.serial
RETURNING id;
CREATE TABLE devices (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
serial text NOT NULL
);
INSERT INTO devices (serial) VALUES ('SN-100')
ON CONFLICT (serial) DO NOTHING;
代码示例
CREATE TABLE devices (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
serial text NOT NULL
);
-- a plain index cannot arbitrate conflicts
CREATE INDEX devices_serial_idx ON devices (serial);
-- fails with: there is no unique or exclusion constraint matching the
-- ON CONFLICT specification
INSERT INTO devices (serial) VALUES ('SN-100')
ON CONFLICT (serial) DO NOTHING;
-- swap the plain index for a unique one; the same upsert now works
DROP INDEX devices_serial_idx;
CREATE UNIQUE INDEX devices_serial_uidx ON devices (serial);
INSERT INTO devices (serial) VALUES ('SN-100') RETURNING id;
INSERT INTO devices (serial) VALUES ('SN-100')
ON CONFLICT (serial) DO UPDATE SET serial = EXCLUDED.serial
RETURNING id;