我经常使用 variable_conflict use_variable,到目前为止我从来没有遇到过任何问题。但是,它不适用于 的ON CONFLICT
子句UPSERT
。这是我的复制品:
CREATE TABLE test(id serial not null,
CONSTRAINT test_pk PRIMARY KEY(id),
category_id INT NOT NULL,
tname TEXT NOT NULL,
CONSTRAINT test_unq UNIQUE(category_id, tname),
some_info TEXT NOT NULL);
CREATE OR REPLACE FUNCTION insert_test(category_id INT, tname TEXT, some_info TEXT)
RETURNS void AS
$BODY$
#variable_conflict use_variable
DECLARE
resultId INTEGER;
BEGIN
INSERT INTO test(category_id, tname, some_info)
SELECT category_id, tname, some_info
ON CONFLICT(category_id, tname) DO NOTHING;
END
$BODY$
LANGUAGE plpgsql VOLATILE
COST 100;
SELECT insert_test(1, 'Colors', 'Blue');
ERROR: there is no unique or exclusion constraint matching the ON CONFLICT specification
CONTEXT: SQL statement "INSERT INTO test(category_id, tname, some_info)
SELECT category_id, tname, some_info
ON CONFLICT(category_id, tname) DO NOTHING"
没有 #variable_conflict use_variable 一切正常:
CREATE OR REPLACE FUNCTION insert_test2(p_category_id INT, p_tname TEXT, p_some_info TEXT)
RETURNS void AS
$BODY$
DECLARE
resultId INTEGER;
BEGIN
INSERT INTO test(category_id, tname, some_info)
SELECT p_category_id, p_tname, p_some_info
ON CONFLICT(category_id, tname) DO NOTHING;
END
$BODY$
LANGUAGE plpgsql VOLATILE
COST 100;
SELECT insert_test2(1, 'Colors', 'Blue');
SELECT insert_test2(2, 'Colors', 'Red');
我错过了什么?