您可以創建一個trigger function
,檢查你想要的東西,而這個函數與被INSERT或表格的更新之前發射的扳機相關聯:
這可能是你的觸發功能:
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