postgresql Postgres:获取FOR EACH STATEMENT触发器中更新的列列表

kxeu7u2r  于 2024-01-07  发布在  PostgreSQL
关注(0)|答案(1)|浏览(158)

我们有一个昂贵的AFTER UPDATE...FOR EACH STATEMENT触发器函数,用于填充tsvector列进行搜索。
有一个列的子集是可搜索的,并且是tsvector生成的一部分。
既然我们不能在CREATE TRIGGER中为语句级触发器指定列列表,那么有没有一种方法可以找出针对当前UPDATE语句更新的列,以便我们仅在其中一个可搜索列更新时重新生成tsvector
编辑:UPDATE语句可以一次性更新1或50K行。
编辑2:似乎是以下问题的重复。我将保持这个打开一段时间,只是在任何新的功能被添加到Postgres后。
https://dba.stackexchange.com/questions/290005/how-to-select-sub-object-with-given-keys-from-jsonb

sg3maiej

sg3maiej1#

要使用转换表检查PostgreSQL触发器中的特定列是否发生了更改,您可以遍历每对新旧行,并使用IS DISTINCT FROM运算符比较相关列的值。下面是一个如何在触发器函数中完成此操作的简化示例:

FOR row_old, row_new IN
    SELECT old.*, new.*
    FROM old_table AS old
    JOIN new_table AS new ON old.primary_key = new.primary_key
LOOP
    -- Check if any of the relevant columns have changed
    IF row_old.searchable_column1 IS DISTINCT FROM row_new.searchable_column1
       OR row_old.searchable_column2 IS DISTINCT FROM row_new.searchable_column2
       -- Add more columns as needed
    THEN
        -- Perform tsvector update logic here
    END IF;
END LOOP;

字符串

使用触发器

CREATE OR REPLACE FUNCTION my_trigger_function()
RETURNS TRIGGER AS $$
DECLARE
    row_old RECORD;
    row_new RECORD;
    is_changed BOOLEAN;
BEGIN
    -- Iterate over each pair of old and new rows
    FOR row_old, row_new IN
        SELECT * FROM old_table
        JOIN new_table ON old_table.primary_key = new_table.primary_key
    LOOP
        -- Check if any of the relevant columns have changed
        is_changed := row_old.searchable_column1 IS DISTINCT FROM row_new.searchable_column1
                   OR row_old.searchable_column2 IS DISTINCT FROM row_new.searchable_column2
                   -- Add more columns as needed
                   ;

        -- Update tsvector if there is a change in relevant columns
        IF is_changed THEN
            -- Perform tsvector update logic here
        END IF;
    END LOOP;

    RETURN NULL;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER my_trigger
AFTER UPDATE ON my_table
REFERENCING OLD TABLE AS old_table NEW TABLE AS new_table
FOR EACH STATEMENT
EXECUTE FUNCTION my_trigger_function();

相关问题