How do I temporarily disable triggers in PostgreSQL?

后端 未结 6 668
我在风中等你
我在风中等你 2020-12-04 07:37

I\'m bulk loading data and can re-calculate all trigger modifications much more cheaply after the fact than on a row-by-row basis.

How can I temporarily disable all

6条回答
  •  醉梦人生
    2020-12-04 08:33

    SET session_replication_role = replica; 
    

    It doesn't work with PostgreSQL 9.4 on my Linux machine if i change a table through table editor in pgAdmin and works if i change table through ordinary query. Manual changes in pg_trigger table also don't work without server restart but dynamic query like on postgresql.nabble.com ENABLE / DISABLE ALL TRIGGERS IN DATABASE works. It could be useful when you need some tuning.

    For example if you have tables in a particular namespace it could be:

    create or replace function disable_triggers(a boolean, nsp character varying) returns void as
    $$
    declare 
    act character varying;
    r record;
    begin
        if(a is true) then
            act = 'disable';
        else
            act = 'enable';
        end if;
    
        for r in select c.relname from pg_namespace n
            join pg_class c on c.relnamespace = n.oid and c.relhastriggers = true
            where n.nspname = nsp
        loop
            execute format('alter table %I %s trigger all', r.relname, act); 
        end loop;
    end;
    $$
    language plpgsql;
    

    If you want to disable all triggers with certain trigger function it could be:

    create or replace function disable_trigger_func(a boolean, f character varying) returns void as
    $$
    declare 
    act character varying;
    r record;
    begin
        if(a is true) then
            act = 'disable';
        else
            act = 'enable';
        end if;
    
        for r in select c.relname from pg_proc p 
            join pg_trigger t on t.tgfoid = p.oid
            join pg_class c on c.oid = t.tgrelid
            where p.proname = f
        loop
            execute format('alter table %I %s trigger all', r.relname, act); 
        end loop;
    end;
    $$
    language plpgsql;
    

    PostgreSQL documentation for system catalogs


    There are another control options of trigger firing process:

    ALTER TABLE ... ENABLE REPLICA TRIGGER ... - trigger will fire in replica mode only.

    ALTER TABLE ... ENABLE ALWAYS TRIGGER ... - trigger will fire always (obviously)

提交回复
热议问题