| Goal | This query identifies trigger functions that compare the special trigger variables TG_TABLE_NAME or TG_RELNAME against hardcoded string literals (e.g., IF TG_TABLE_NAME = 'table_a' THEN ...). Branching on hardcoded table names inside a shared trigger function is a design and maintainability anti-pattern for several reasons:
|
|---|---|
| Notes | Queries the PostgreSQL system catalogs (pg_proc, pg_namespace, pg_type) to inspect the source code (prosrc) of user-defined trigger functions (typname = 'trigger'). The query uses a case-insensitive regular expression to detect comparisons where TG_TABLE_NAME or the legacy alias TG_RELNAME is compared against a string literal using =, <>, !=, or IN (...). In the returned routine source code, 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 |
|
Fixing Suggestion
Eliminate the hardcoded
TG_TABLE_NAME comparison: - If the trigger logic is identical across tables and only diagnostic strings (such as the
CONSTRAINTname) differ, construct the identifier dynamically (e.g.,CONSTRAINT = TG_TABLE_NAME || '_rule_suffix') or pass table-specific values as trigger arguments inCREATE TRIGGER ... EXECUTE FUNCTION fn_name('arg')and read them viaTG_ARGV[0]. - If the tables require distinct business rules, split the shared routine into separate, dedicated trigger functions for each 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 .
| Name | Description |
|---|---|
| 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 . |
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.
| Name | Description |
|---|---|
| Triggers and rules | Queries of this category provide information about triggers and rules in a database. |