如何确保新记录包含引用数据库中当前存在的架构、表和列的值?
例如,给定一个表:
CREATE TEMP TABLE "column_reference" (
"gid" SERIAL PRIMARY KEY
, "val" INTEGER
, "schema" TEXT
, "table" TEXT
, "column" TEXT
);
如何确保SimultTable列存在?
我试过使用fkey来
information_schema.columns
,但是,当然,视图的外键是不允许的。从
columns
视图定义中还可以看出,我需要多个表才能获取架构、表和列名,因此无法为源表创建一个外键。我当前的解决方法是从
__columns
视图中手动创建一个information_schema.columns
表并引用它。考虑到我在这个时间点上对这个项目的控制,这是可行的,但是我正在寻找一个永久的、动态的解决方案。我可以使用不同的约束或方法吗?
最佳答案
可以创建检查所需内容的trigger function
,并将此函数与在插入或更新表之前触发的触发器关联:
这可能是触发函数:
CREATE FUNCTION column_reference_check()
RETURNS trigger
LANGUAGE 'plpgsql'
AS
$BODY$
begin
/* Check for the existence of the required column */
if EXISTS (
SELECT *
FROM information_schema.columns
WHERE
table_schema = new.schema
AND table_name = new.table
AND column_name = new.column )
then
/* Everything Ok */
return new ;
else
/* This is approx. what would happen if you had a constraint */
RAISE EXCEPTION 'Trying to insert non-matching (%, %, %)', new.schema, new.table, new.column ;
/* As an alternative, you could also just return NULL
As a result, the row is *not* inserted, but execution continues */
return NULL ;
end if ;
end ;
$BODY$;
要将此函数与触发器关联,可以使用:
CREATE TRIGGER column_reference_check_trg
BEFORE INSERT OR UPDATE OF "schema", "table", "column"
ON column_reference
FOR EACH ROW
EXECUTE PROCEDURE column_reference_check();
现在您可以尝试执行以下
INSERT
,这应该会成功:INSERT INTO column_reference
VALUES (2, 1, 'pg_catalog', 'pg_statistic', 'starelid');
但如果你试试这个:
INSERT INTO column_reference
VALUES (-1, 1, 'false_schema', 'false_table', 'false_column');
…有个例外:
ERROR: Trying to insert non-matching (false_schema, false_table, false_column)
CONTEXT: PL/pgSQL function column_reference_check() line 16 at RAISE
关于database - postgres 9.3+:约束以确保数据库中存在表和列,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42166958/