← 中文资源

简体中文版本

对表达式索引做 upsert

ON CONFLICT 的冲突目标必须与唯一表达式索引逐字一致:写 (lower(email)) 才能推断命中,只写列名会报错;EXCLUDED 还能顺带刷新大小写。

阅读英文原文

实现说明

一个文件里不止一条语句:INSERT / UPDATE / CREATE,users、set 都在涉及之列。 逐子句看,这些语句使用了:upsert 守卫(ON CONFLICT/MERGE)把插入或更新合并成一条原子语句;RETURNING 把受影响的行交回调用方;必填列上的 NOT NULL 限定;强制行身份的 PRIMARY KEY;把重复值挡在外面的 UNIQUE 约束;自动算列值的 GENERATED ALWAYS/GENERATED BY 子句。

常见问题

这里涉及哪些关系(表/CTE)?

users、set——名字即引用,连接不在流程里。

核心语句

INSERT INTO users (email) VALUES ('[email protected]')
ON CONFLICT (lower(email)) DO UPDATE SET email = EXCLUDED.email
RETURNING user_id, email;
INSERT INTO users (email) VALUES ('[email protected]')
ON CONFLICT (lower(email)) DO UPDATE SET email = EXCLUDED.email
RETURNING user_id, email;
CREATE TABLE users (
    user_id int GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    email   text NOT NULL
);

代码示例

-- upsert against the unique expression index: conflict target must
-- repeat the exact expression, not the bare column
CREATE TABLE users (
    user_id int GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    email   text NOT NULL
);
CREATE UNIQUE INDEX users_email_lower_key ON users (lower(email));

INSERT INTO users (email) VALUES ('[email protected]')
ON CONFLICT (lower(email)) DO UPDATE SET email = EXCLUDED.email
RETURNING user_id, email;

-- bare column names cannot infer the expression index and fail with
-- "there is no unique or exclusion constraint matching the ON CONFLICT specification"
-- INSERT INTO users (email) VALUES ('[email protected]')
-- ON CONFLICT (email) DO NOTHING;

-- a case variant hits the conflict target: EXCLUDED.email writes the new casing back into the row
INSERT INTO users (email) VALUES ('[email protected]')
ON CONFLICT (lower(email)) DO UPDATE SET email = EXCLUDED.email
RETURNING user_id, email;