Goal This query identifies triggers whose underlying function specifies a CONSTRAINT (or CONSTRAINT_NAME) option in a RAISE EXCEPTION ... USING clause, but constructs the constraint identifier without including either the name of the table to which the trigger is attached (trigger_table) or the built-in PL/pgSQL variable TG_TABLE_NAME (or TG_RELNAME). When a trigger simulates a table constraint by setting the PG_DIAG_CONSTRAINT_NAME diagnostic field via USING CONSTRAINT = ..., following a consistent naming convention that incorporates the table name (e.g., CONSTRAINT = TG_TABLE_NAME || '_<rule>' or CONSTRAINT = '<table_name>_<rule>') ensures that the simulated constraint name is globally unique across the schema and immediately traceable to the affected relation. A missing table reference typically indicates one of three issues:

  • The constraint name in the USING clause was misspelled or abbreviated inconsistently (for example, omitting part of a compound table name).

  • The trigger function was copy-pasted from another table without updating the hardcoded CONSTRAINT identifier.

  • A single trigger function is shared across multiple tables and hardcodes table-specific constraint names in conditional branches rather than constructing the constraint name dynamically via TG_TABLE_NAME.

Notes Queries the PostgreSQL system catalogs (pg_trigger, pg_proc, pg_class, pg_namespace) and information_schema.triggers. For each trigger, the query dynamically constructs a case-insensitive regular expression with a tempered greedy token that scans the entire expression assigned to CONSTRAINT (or CONSTRAINT_NAME) from the = sign up to the next USING option keyword (MESSAGE, DETAIL, HINT, ERRCODE, COLUMN, CONSTRAINT, DATATYPE, TABLE, SCHEMA) or the statement-terminating semicolon (;). The trigger is flagged if the assigned expression contains neither TG_TABLE_NAME, TG_RELNAME, nor the trigger's trigger_table string in any position (supporting plain literals, || string concatenation, and format() calls). In the returned routine definition, newline characters are replaced with HTML line break (<br>) tags for better readability in a web browser.
Type Problem detection Each row in the result could represent a flaw in the design
Reliability High Few or no false-positive results
License MIT (opens in new tab)
Data Source INFORMATION_SCHEMA+system catalog
SQL Query
WITH Tr AS (
    SELECT
        n.nspname AS trigger_schema,
        t.tgname AS trigger_name,
        em.text AS event_manipulation,        
        c.relname AS trigger_table, 
        np.nspname AS routine_schema,
        p.proname AS routine_name,
        p.prosrc AS routine_definition,
        (SELECT DISTINCT action_condition 
         FROM INFORMATION_SCHEMA.triggers AS it 
         WHERE it.trigger_schema = n.nspname 
           AND it.event_object_table = c.relname 
           AND it.trigger_name = t.tgname) AS action_condition,    
        CASE t.tgtype::integer & 1
            WHEN 1 THEN 'ROW'
            ELSE 'STATEMENT'
        END AS action_orientation,
        CASE t.tgtype::integer & 66
            WHEN 2 THEN 'BEFORE'
            WHEN 64 THEN 'INSTEAD OF'
            ELSE 'AFTER'
        END AS action_timing	
    FROM pg_namespace n,
        pg_class c,
        pg_trigger t,
        pg_proc p,
        pg_namespace np,
        (VALUES (4,'INSERT'), (8,'DELETE'), (16,'UPDATE'), (32,'TRUNCATE')) em(num, text)
    WHERE n.oid = c.relnamespace 
      AND c.oid = t.tgrelid 
      AND t.tgfoid = p.oid
      AND p.pronamespace = np.oid
      AND (t.tgtype::integer & em.num) <> 0 
      AND NOT t.tgisinternal 
      AND NOT pg_is_other_temp_schema(n.oid)
)
SELECT 
    trigger_schema, 
    trigger_table, 
    action_timing, 
    event_manipulation, 
    action_orientation, 
    action_condition, 
    routine_name, 
    regexp_replace(routine_definition, '[\r\n]', '<br>', 'g') AS routine_definition
FROM Tr
WHERE     
    routine_definition ~* (
        '\yRAISE[[:space:]]+EXCEPTION\y[^;]*\yCONSTRAINT(_NAME)?[[:space:]]*=(?:(?!(?:,[[:space:]]*\y(MESSAGE|DETAIL|HINT|ERRCODE|COLUMN|CONSTRAINT|DATATYPE|TABLE|SCHEMA)(_NAME)?[[:space:]]*=|\y(TG_TABLE_NAME|TG_RELNAME)\y|' || trigger_table || '))[^;])+(?:,[[:space:]]*\y(MESSAGE|DETAIL|HINT|ERRCODE|COLUMN|CONSTRAINT|DATATYPE|TABLE|SCHEMA)(_NAME)?[[:space:]]*=|;)'
    )
ORDER BY 
    trigger_schema, 
    trigger_table, 
    routine_name;

Fixing Suggestion

Construct the CONSTRAINT identifier dynamically using TG_TABLE_NAME (for example, CONSTRAINT = TG_TABLE_NAME || '_<rule_name>' or CONSTRAINT = 'chk_' || TG_TABLE_NAME || '_<rule_name>'), or update the hardcoded string literal so that it accurately includes the full table name (trigger_table).

Collections

This query belongs to the following collections:

Find problems automatically

Queries, that results point to problems in the database. Each query in the collection produces an initial assessment. However, a human reviewer has the final say as to whether there is a problem or not .

NameDescription
Find problems automaticallyQueries, that results point to problems in the database. Each query in the collection produces an initial assessment. However, a human reviewer has the final say as to whether there is a problem or not .

Categories

This query is classified under the following categories:

Triggers and rules

Queries of this category provide information about triggers and rules in a database.

NameDescription
Triggers and rulesQueries of this category provide information about triggers and rules in a database.