Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to disable PostgreSQL triggers in one transaction only?

I need to temporary disable one PostgreSQL trigger in a transaction, but without hardlocking table. Does someone know if it is possible?

Something like this without locking table and disabling trigger outside of this transaction.

BEGIN TRANSACTION;

  ALTER TABLE foo DISABLE TRIGGER bar;

  -- DO SOME UPDATES ON foo
  UPDATE foo set field = 'value' where field = 'test';

  ALTER TABLE foo ENABLE TRIGGER bar;

COMMIT;
like image 681
gori Avatar asked Jun 09 '16 15:06

gori


People also ask

How do I temporarily disable trigger?

You can disable a trigger temporarily using the DISABLE TRIGGER statement. Disable trigger does not delete the trigger. The trigger exists in the current database but it doesn't fire. In the above syntax, trigger_name is the name of the trigger to be disabled under the schema_name schema.

How do I enable and disable triggers?

To enable a trigger, causes it to fire when any Transact-SQL statements on which it was originally programmed are run. Triggers are disabled by using DISABLE TRIGGER. DML triggers defined on tables can also be disabled or enabled by using ALTER TABLE.


2 Answers

To temporarily disable all triggers in a PostgreSQL session, use this:

SET session_replication_role = replica;

That disables all triggers for the current database session only. Useful for bulk operations, but remember to be careful to keep your database consistent.

To re-enable:

SET session_replication_role = DEFAULT;

Source: http://koo.fi/blog/2013/01/08/disable-postgresql-triggers-temporarily/

like image 129
Dave Avatar answered Sep 19 '22 11:09

Dave


You can disable all triggers in this table. It should look like this:

ALTER TABLE tblname DISABLE TRIGGER USER;
Your SQL;
ALTER TABLE tblname ENABLE TRIGGER USER;

For disabling a single trigger use this:

ALTER TABLE tblname DISABLE TRIGGER trigger_name;
Your SQL;
ALTER TABLE tblname ENABLE TRIGGER trigger_name;

You can read more about ALTER TABLE in documentation.

like image 22
Walerian Sobczak Avatar answered Sep 19 '22 11:09

Walerian Sobczak