20

My googling-fu is failing me. How to know if a PostgreSQL trigger is disabled or not?

THelper
  • 15,333
  • 6
  • 64
  • 104
Hao
  • 8,047
  • 18
  • 63
  • 92

4 Answers4

23

The SQL below will do the work. It displays all triggers in your current database.

SELECT pg_namespace.nspname, pg_class.relname, pg_trigger.*
FROM pg_trigger
JOIN pg_class ON pg_trigger.tgrelid = pg_class.oid
JOIN pg_namespace ON pg_namespace.oid = pg_class.relnamespace  

If tgenabled is 'D', the trigger is disabled. All other values (documented here) indicate, that it is enabled in some way.

BTW. If you want to check the triggers for a specific table, the query is a bit shorter:

SELECT * FROM pg_trigger
WHERE tgrelid = 'your_schema.your_table'::regclass

The cast to the regclass type gets you from qualified table name to OID (object id) the easy way.

pmenke
  • 93
  • 1
  • 5
tolgayilmaz
  • 3,987
  • 2
  • 19
  • 19
17

It's my first day with postresql, but I think you can check the trigger state via pg_trigger system table: http://www.postgresql.org/docs/current/static/catalog-pg-trigger.html

The columns you will need are tgrelid and tgenabled.

nhahtdh
  • 55,989
  • 15
  • 126
  • 162
Rafael
  • 18,349
  • 5
  • 58
  • 67
7
SELECT EXISTS (
    SELECT  tgenabled
    FROM    pg_trigger
    WHERE   tgname='your_unique_trigger_name' AND
            tgenabled != 'D'
);

If you know the trigger name is unique the above will return true (t) if the your_unique_trigger_name trigger is enabled:

 exists
--------
 t
(1 row)

If disabled it would return false (f).

Pocketsand
  • 1,261
  • 10
  • 15
0

Starting from @tolgayilmaz reply I created a simply function to be used around my project

CREATE OR REPLACE FUNCTION trigger_exists_on_table(schema_name text, table_name text, trigger_name text)
RETURNS boolean AS
$body$
declare
    _sql text;
    _boolean_exists boolean;
begin
    _sql := format('
        SELECT EXISTS (
            SELECT 1
            FROM pg_trigger
            WHERE tgrelid = ''%s.%s''::regclass AND tgname = ''%s'' AND tgenabled != ''D''
        )
    ', schema_name, table_name, trigger_name);

    execute _sql into _boolean_exists;

    return _boolean_exists;
end
$body$
LANGUAGE plpgsql;
Deviling Master
  • 3,033
  • 5
  • 34
  • 59