How to create a trigger function dynamically in pgsql?

我怕爱的太早我们不能终老 提交于 2021-02-07 15:00:10

问题


I want to write a pgsql function to create trigger dynamically. For example, a trigger to count insertions in each table. I've tried EXECUTE like this:

CREATE FUNCTION trigen(tbl text) RETURNS void AS $$
BEGIN
    EXECUTE format(
    'CREATE FUNCTION %s_insertCnt() RETURNS TRIGGER AS $$
    BEGIN
        UPDATE insertions SET n = n + 1 WHERE tablename = %s;
    END
    $$ LANGUAGE plpgsql', tbl, quote_nullable(tbl));

    EXECUTE format('CREATE TRIGGER %s_inCnt BEFORE INSERT ON %s
    FOR EACH ROW EXECUTE PROCEDURE %s_insertCnt();', tbl, tbl, tbl);
END
$$ LANGUAGE plpgsql

But this approach doesn't work. A lot of syntax error occurred when I import this code. It seems that EXECUTE cannot execute a function creation.

What else can I do to create trigger functions dynamically?


回答1:


The two $$ sections were getting confused. By using the $name$ syntax instead you can separate these.

Also the trigger was missing a RETURN.

CREATE OR REPLACE FUNCTION trigen(tbl text) RETURNS void AS $T1$
BEGIN
    EXECUTE format(
    'CREATE FUNCTION %s_insertCnt() RETURNS TRIGGER AS $T2$
    BEGIN
        UPDATE insertions SET n = n + 1 WHERE tablename = %s;
        RETURN NEW;
    END
    $T2$ LANGUAGE plpgsql', tbl, quote_nullable(tbl));

    EXECUTE format('CREATE TRIGGER %s_inCnt BEFORE INSERT ON %s
    FOR EACH ROW EXECUTE PROCEDURE %s_insertCnt();', tbl, tbl, tbl);
    END
$T1$ LANGUAGE plpgsql;


来源:https://stackoverflow.com/questions/31508409/how-to-create-a-trigger-function-dynamically-in-pgsql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!