Goal This query identifies data-modifying user-defined routines (functions, procedures, and trigger functions) where audit or actor columns and variables (such as looja, registreerija, viimane_muutja, kustutaja, arhiveerija, kinnitaja, sisestaja, created_by, updated_by, modified_by, deleted_by, approved_by, etc.) are assigned or compared against hardcoded numeric or string literals instead of dynamically determined user identifiers. Hardcoding actor identifiers inside database routines is a serious security, data integrity, and maintainability flaw:

  • Compromised audit trails and accountability: Every record created, modified, approved, or archived by the routine is attributed to a fixed placeholder user (e.g., 1 or 'admin'), making it impossible to trace who actually performed the action.

  • Environment fragility and foreign key failures: Hardcoded surrogate Ids (such as 1) may not exist in all environments (development, staging, production), may belong to a completely different user, or may cause foreign key constraint violations if that user account is removed or changed.

Notes Refers to the column pg_proc.prokind and thus works starting from PostgreSQL 11. The query inspects user-defined functions, procedures, and trigger functions (prokind IN ('f', 'p')) from pg_catalog.pg_proc and pg_catalog.pg_namespace, excluding system schemas, postgres-owned non-public schemas, extension-owned routines, and helper routines. First, SQL line and block comments are stripped from pg_get_functiondef(p.oid) so that commented-out code does not cause false positives, and routines are filtered to those performing DML (INSERT INTO, UPDATE ... SET, DELETE FROM, MERGE INTO) or modifying NEW.<column> inside a trigger function. An identifier regex matches Estonian and English audit/actor names while explicitly excluding timestamps, statuses, roles, and type attributes (such as _aeg, _time, _date, _roll, _staatus, _seisund, _liik, _type). The query flags a routine if any actor identifier receives a hardcoded numeric or string literal (with optional parentheses and type casts) via:

  • Direct assignments or comparisons (= or :=), including UPDATE ... SET and trigger assignments (NEW.<col> := ...).

  • Fallback defaults in COALESCE(..., <literal>).

  • Routine parameter DEFAULT values inspected via pg_get_function_arguments(p.oid).

  • Positional INSERT INTO ... (<columns>) VALUES (...) or INSERT INTO ... (<columns>) SELECT ... statements, using a character-level window-function parser that tracks single-quote state and parenthesis nesting depth to accurately match each actor column's ordinal position with its corresponding value expression.



For better readability in a web browser, < characters are escaped (&lt;) and newline characters are replaced with HTML line break (<br>) tags. Routine parameters are included alongside the schema and routine name to uniquely identify overloaded routines.
Type Problem detection Each row in the result could represent a flaw in the design
Reliability Medium Medium number of false-positive results
License MIT (opens in new tab)
Data Source INFORMATION_SCHEMA+system catalog
SQL Query
WITH patterns AS (
    SELECT
        
        '\y(?![[:alnum:]_]*(?:_aeg|_time|_timestamp|_date|_kpv|_kuupaev|_roll|_role|_seisund|_staatus|_status|_liik|_tyyp|_tüüp|_type)(?:_|\y))[[:alnum:]_]*(?:looja|registreerija|muutja|uuendaja|kustutaja|arhiveerija|kinnitaja|sisestaja|tühistaja|tyhistaja|algataja|koostaja|lõpetaja|lopetaja|aktiveerija|creator|created_by|updated_by|modified_by|modifier|deleted_by|deleter|archived_by|archiver|approved_by|approver|inserted_by|changed_by|registered_by|cancelled_by|canceled_by|closed_by)(?:_id|_kood|_code|_nr|_number|_nimi|_name|_e_meil|_email|_e_post|_kasutajanimi|_username|_login)?\y' AS actor_pat,
        
        '(?:\([[:space:]]*)*(?:-?[0-9]+(?:\.[0-9]+)?|''[^'']+'')(?:[[:space:]]*\))*(?:[[:space:]]*::[[:space:]]*[[:alnum:]_." ]+(?:\([0-9,[:space:]]+\))?)*(?:[[:space:]]*\))*' AS lit_pat
),

routines_base AS (
    SELECT 
        p.oid AS routine_oid,
        n.nspname AS routine_schema, 
        p.proname AS routine_name, 
        CASE 
            WHEN p.prokind IN ('f', 'p') THEN pg_get_function_identity_arguments(p.oid) 
        END AS parameters,
        CASE 
            WHEN p.prokind IN ('f', 'p') THEN pg_get_function_arguments(p.oid) 
        END AS full_arguments,
        CASE 
            WHEN pt.typname = 'trigger' THEN 'TRIGGER FUNCTION'
            WHEN p.prokind = 'f' THEN 'FUNCTION'
            WHEN p.prokind = 'p' THEN 'PROCEDURE'
        END AS routine_type,
        
        CASE 
            WHEN p.prokind IN ('f', 'p') THEN pg_get_functiondef(p.oid) 
            ELSE NULL 
        END AS raw_src
    FROM pg_catalog.pg_proc p
    INNER JOIN pg_catalog.pg_namespace n ON p.pronamespace = n.oid
    LEFT JOIN pg_catalog.pg_type pt ON pt.oid = p.prorettype
    WHERE p.prokind IN ('f', 'p')
      AND p.proname NOT IN (
          'f_assume_you_must_use_files', 
          'f_check_format_comma_separated_list', 
          'f_check_password', 
          'f_default_value_with_no_match'
      )
      AND n.nspname NOT IN (
          SELECT schema_name
          FROM INFORMATION_SCHEMA.schemata
          WHERE schema_name <> 'public' 
            AND schema_owner = 'postgres' 
            AND schema_name IS NOT NULL
      )
      AND NOT EXISTS (
          SELECT 1
          FROM pg_catalog.pg_depend d 
          INNER JOIN pg_catalog.pg_extension e ON d.refobjid = e.oid
          WHERE d.objid = p.oid
      )
),

dml_actor_routines AS (
    SELECT 
        r.*,
        c.clean_src
    FROM routines_base r
    CROSS JOIN LATERAL (
        
        SELECT regexp_replace(r.raw_src, '(--[^\n\r]*)|(/\*[\w\W]*?\*/)', ' ', 'g') AS clean_src
    ) c
    CROSS JOIN patterns pat
    WHERE 
        
        (
            c.clean_src ~* '\y(INSERT[[:space:]]+INTO|UPDATE[[:space:]]+(?:ONLY[[:space:]]+)?[[:alnum:]_."]+(?:[[:space:]]+(?:AS[[:space:]]+)?[[:alnum:]_"]+)?[[:space:]]+SET|DELETE[[:space:]]+FROM|MERGE[[:space:]]+INTO)\y'
            OR (r.routine_type = 'TRIGGER FUNCTION' AND c.clean_src ~* '\yNEW\.[[:alnum:]_]+[[:space:]]*:?=')
        )
        
        AND c.clean_src ~* pat.actor_pat
)

SELECT 
    r.routine_schema,
    r.routine_name,
    r.parameters,
    r.routine_type,
    regexp_replace(
        regexp_replace(r.raw_src, '<', '&lt;', 'g'),
        '[\r\n]', '<br>', 'g'
    ) AS routine_src
FROM dml_actor_routines r
CROSS JOIN patterns pat
WHERE 
    
    r.clean_src ~* (
        '(?:\y(?:NEW|OLD)\.)?"?' || pat.actor_pat || '"?[[:space:]]*:?=[[:space:]]*' || pat.lit_pat || '[[:space:]]*(?:,|;|\y(?:WHERE|FROM|RETURNING|AND|OR|THEN|ELSE|END)\y|\))'
    )
    
    OR 
    
    
    r.clean_src ~* (
        '(?:\y(?:NEW|OLD)\.)?"?' || pat.actor_pat || '"?[[:space:]]*:?=[[:space:]]*coalesce[[:space:]]*\([^,;()]+,[[:space:]]*' || pat.lit_pat || '[[:space:]]*\)'
    )
    
    OR 
    
    
    r.full_arguments ~* (
        pat.actor_pat || '[[:space:]]+[[:alnum:]_." ]+(?:\([0-9,[:space:]]+\))?[[:space:]]+DEFAULT[[:space:]]+' || pat.lit_pat
    )
    
    OR 
    
    
    EXISTS (
        SELECT 1
        FROM regexp_matches(
            r.clean_src,
            '\yINSERT[[:space:]]+INTO[[:space:]]+(?:[[:alnum:]_."]+\.)?[[:alnum:]_"]+[[:space:]]*\(([^()]+)\)[[:space:]]*(VALUES|SELECT)\y((?:''[^'']*''|[^;])+)',
            'gi'
        ) WITH ORDINALITY AS ins(m, stmt_id)
        CROSS JOIN LATERAL (
            SELECT 
                trim(both ' "' from col_raw) AS col_name,
                col_pos::int AS col_pos
            FROM unnest(string_to_array(ins.m[1], ',')) WITH ORDINALITY AS cols(col_raw, col_pos)
            WHERE trim(both ' "' from col_raw) ~* pat.actor_pat
        ) target_cols
        CROSS JOIN LATERAL (
            WITH chars AS (
                SELECT c, pos::int AS pos
                FROM regexp_split_to_table(ins.m[3], '') WITH ORDINALITY AS t(c, pos)
            ),
            quote_state AS (
                SELECT 
                    c, 
                    pos,
                    (sum(CASE WHEN c = '''' THEN 1 ELSE 0 END) OVER (ORDER BY pos) % 2) AS in_quote
                FROM chars
            ),
            depth_state AS (
                SELECT 
                    c, 
                    pos, 
                    in_quote,
                    sum(CASE WHEN in_quote = 0 AND c = '(' THEN 1 WHEN in_quote = 0 AND c = ')' THEN -1 ELSE 0 END) OVER (ORDER BY pos) AS paren_depth
                FROM quote_state
            ),
            prev_depth_state AS (
                SELECT
                    c,
                    pos,
                    in_quote,
                    paren_depth,
                    COALESCE(lag(paren_depth) OVER (ORDER BY pos), 0) AS prev_depth
                FROM depth_state
            ),
            bounds AS (
                SELECT MIN(pos) AS stop_pos
                FROM prev_depth_state
                WHERE in_quote = 0
                  AND (
                      paren_depth < 0
                      OR (
                          paren_depth = 0 
                          AND upper(ins.m[2]) = 'SELECT'
                          AND (pos = 1 OR substring(ins.m[3] FROM pos - 1 FOR 1) !~ '[[:alnum:]_]')
                          AND substring(ins.m[3] FROM pos) ~* '^(FROM|WHERE|GROUP|HAVING|WINDOW|UNION|INTERSECT|EXCEPT|ORDER|LIMIT|OFFSET|FETCH|FOR|ON|RETURNING)\y'
                      )
                      OR (
                          paren_depth = 0 
                          AND upper(ins.m[2]) = 'VALUES'
                          AND prev_depth = 0
                          AND (pos = 1 OR substring(ins.m[3] FROM pos - 1 FOR 1) !~ '[[:alnum:]_]')
                          AND substring(ins.m[3] FROM pos) ~* '^(RETURNING|ON)\y'
                      )
                  )
            ),
            scoped_chars AS (
                SELECT 
                    p.c,
                    p.pos,
                    p.in_quote,
                    p.paren_depth,
                    p.prev_depth,
                    sum(CASE WHEN upper(ins.m[2]) = 'VALUES' AND p.in_quote = 0 AND p.c = '(' AND p.prev_depth = 0 THEN 1 ELSE 0 END) OVER (ORDER BY p.pos) AS tuple_num,
                    CASE 
                        WHEN p.in_quote = 0 AND p.c = ',' AND p.paren_depth = (CASE WHEN upper(ins.m[2]) = 'VALUES' THEN 1 ELSE 0 END) THEN 1 
                        ELSE 0 
                    END AS is_sep
                FROM prev_depth_state p
                CROSS JOIN bounds b
                WHERE p.pos < COALESCE(b.stop_pos, length(ins.m[3]) + 1)
            ),
            indexed_chars AS (
                SELECT
                    c,
                    pos,
                    in_quote,
                    paren_depth,
                    prev_depth,
                    tuple_num,
                    is_sep,
                    1 + sum(is_sep) OVER (PARTITION BY tuple_num ORDER BY pos) AS expr_pos
                FROM scoped_chars
            ),
            exprs AS (
                SELECT 
                    tuple_num,
                    expr_pos,
                    regexp_replace(trim(string_agg(c, '' ORDER BY pos)), '^(DISTINCT|ALL)[[:space:]]+', '', 'i') AS expr_val
                FROM indexed_chars
                WHERE is_sep = 0
                  AND (
                      upper(ins.m[2]) = 'SELECT'
                      OR (
                          tuple_num >= 1 
                          AND paren_depth >= 1 
                          AND NOT (in_quote = 0 AND c = '(' AND prev_depth = 0)
                      )
                  )
                GROUP BY tuple_num, expr_pos
            )
            SELECT 1
            FROM exprs
            WHERE exprs.expr_pos = target_cols.col_pos
              AND (
                  exprs.expr_val ~* ('^' || pat.lit_pat || '(?:[[:space:]]+AS[[:space:]]+"?[[:alnum:]_]+"?)?$')
                  OR exprs.expr_val ~* ('^coalesce[[:space:]]*\([^,;()]+,[[:space:]]*' || pat.lit_pat || '[[:space:]]*\)(?:[[:space:]]+AS[[:space:]]+"?[[:alnum:]_]+"?)?$')
              )
        )
    )
ORDER BY r.routine_schema, r.routine_name, r.parameters;

Fixing Suggestion

Remove all hardcoded numeric and string literals for actor/audit attributes and resolve the acting user dynamically:

  • Pass the caller's identifier (such as an email address, username, or user ID) as an explicit, mandatory input parameter to the routine without a hardcoded DEFAULT value, and look up the corresponding actor ID from the user/employee table (e.g., using SELECT ... FOR SHARE).

  • Alternatively, if database sessions or connection pools establish the caller's identity at the database level, derive the actor using PostgreSQL session functions (CURRENT_USER, SESSION_USER) or custom transaction/session settings (e.g., current_setting('app.current_user_id', true)).

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:

Result quality depends on names

Queries of this category use names (for instance, column names) to try to guess the meaning of a database object. Thus, the goodness of names determines the number of false positive and false negative results.

User-defined routines

Queries of this category provide information about the user-defined routines

NameDescription
Result quality depends on namesQueries of this category use names (for instance, column names) to try to guess the meaning of a database object. Thus, the goodness of names determines the number of false positive and false negative results.
User-defined routinesQueries of this category provide information about the user-defined routines