我正在尝试在包含对两列复合的唯一约束的表上的函数内使用UPSERT语法,但是我收到一条错误,指出“没有与ON CONFLICT规范匹配的唯一或排除约束”。< / p>
奇怪的是,同一个查询在函数外部工作正常!
所以,假设我有一张下表:
CREATE TABLE IF NOT EXISTS test (
id SERIAL,
col1 VARCHAR NOT NULL,
col2 VARCHAR NOT NULL,
UNIQUE(col1, col2)
);
现在我可以像这样插入(并且它可以正常工作):
INSERT INTO test(col1, col2) VALUES('val1', 'val2')
ON CONFLICT (col1, col2) DO NOTHING
RETURNING id;
-- Output: id integer
1
所以现在我想在函数中使用这个查询:
CREATE OR REPLACE FUNCTION test_func(col1 VARCHAR, col2 VARCHAR)
RETURNS INTEGER AS $$
#variable_conflict use_variable
DECLARE
rowid INTEGER;
BEGIN
INSERT INTO test(col1, col2) VALUES(col1, col2)
ON CONFLICT (col1, col2) DO NOTHING
RETURNING id INTO rowid;
RETURN rowid;
END;
$$ LANGUAGE PLPGSQL;
但是当我调用该函数时,我得到错误:
SELECT test_func('val1', 'val2');
ERROR: there is no unique or exclusion constraint matching the ON CONFLICT specification
CONTEXT: SQL statement "INSERT INTO test(col1, col2) VALUES(col1, col2)
ON CONFLICT (col1, col2) DO NOTHING
RETURNING id"
PL/pgSQL function test_func(character varying,character varying) line 6 at SQL statement
********** Error **********
ERROR: there is no unique or exclusion constraint matching the ON CONFLICT specification
SQL state: 42P10
Context: SQL statement "INSERT INTO test(col1, col2) VALUES(col1, col2)
ON CONFLICT (col1, col2) DO NOTHING
RETURNING id"
PL/pgSQL function test_func(character varying,character varying) line 6 at SQL statement
有什么问题?