PL/pgSQL, user functions and triggers

SynergyDB stores user functions written in LANGUAGE sql or LANGUAGE plpgsql, runs DO blocks, and fires row-level triggers. There are three separate execution paths, and each supports a different subset of PL/pgSQL:

Path Used for Code
Inline UDF evaluation a function whose body is a single expression, called anywhere an expression is allowed try_eval_udf in src/query/engine.rs
PL/pgSQL interpreter multi-statement function bodies called from a FROM-less SELECT, column defaults, PERFORM, set-returning functions in FROM, and DO blocks src/query/plpgsql.rs, PlpgsqlInterpreter
Trigger body lowering the function a trigger calls src/query/triggers.rs, parse_trigger_body

(source: src/query/engine.rs, try_eval_udf, try_execute_plpgsql_select, exec_do_block, fire_before_row_triggers; src/query/plpgsql.rs, PlpgsqlInterpreter; src/query/triggers.rs, parse_trigger_body)

Procedures are not executed: CREATE PROCEDURE is accepted and ignored and there is no CALL. See Statements.

CREATE FUNCTION

Part Behaviour
Name schema prefix stripped; stored at __catalog__:function:{lower-case name}
Overloading none; functions are keyed by name only, so a second signature replaces or collides with the first
OR REPLACE replaces; without it an existing name gives function "x" already exists (42723)
Parameter modes IN, OUT, INOUT, VARIADIC all treated as IN
Parameter DEFAULT ignored; a missing argument is NULL
RETURNS type, RETURNS SETOF type, RETURNS TABLE (...) supported
LANGUAGE sql (the default) or plpgsql; any other language gives an "unsupported" error
IMMUTABLE, STABLE, VOLATILE, STRICT, SECURITY DEFINER, COST, ROWS, SET ..., PARALLEL parsed and skipped
DROP FUNCTION name(...) removes by name; the argument list is not used to pick an overload

(source: src/query/sql/parser.rs, parse_create_function, parse_function_param; src/query/engine.rs, execute_create_function)

Because STRICT is skipped, a function called with a NULL argument still runs its body. Not verified: no test covers a STRICT function. (source: src/query/sql/parser.rs, parse_create_function)

Tests: test_udf_create_or_replace, test_udf_drop_function, functions_triggers_and_views_are_visible; feature matrix scenarios function-sql, function-plpgsql.

Calling a function

Single-expression bodies

try_eval_udf handles two body shapes:

  • LANGUAGE sql whose body is exactly one SELECT <expr>
  • LANGUAGE plpgsql whose body is exactly BEGIN RETURN <expr>; END

Arguments are substituted and the expression is evaluated in place, so such functions work in a select list, in WHERE, in ORDER BY and in defaults. The result is coerced to the declared return type; an integer return type rounds a fractional result. A SETOF function called in a scalar position gives an "unsupported" error. (source: src/query/engine.rs, try_eval_udf, coerce_udf_result)

Tests: test_udf_sql_scalar_in_select, test_udf_sql_scalar_in_where_and_select, test_udf_plpgsql_simple_return.

Multi-statement bodies

A PL/pgSQL body is "complex" when it contains DECLARE, LOOP, WHILE, FOR, RAISE, EXCEPTION, PERFORM, EXECUTE, GET DIAGNOSTICS, RETURN QUERY, SELECT ... INTO, or more than one statement. (source: src/query/engine.rs, is_complex_plpgsql_body) A complex body runs in the interpreter only from these places:

Call site Path
SELECT f(args) with no FROM clause try_execute_plpgsql_select, run_complex_plpgsql_call
A column default such as DEFAULT f() eval_deferred_default
PERFORM f(args) inside another PL/pgSQL body interpreter
A SETOF or RETURNS TABLE function in FROM, SELECT * FROM f(args) try_execute_plpgsql_setof; output columns from columns_for_setof_return

(source: src/query/engine.rs, try_execute_plpgsql_select, run_complex_plpgsql_call, eval_deferred_default, try_execute_plpgsql_setof, columns_for_setof_return)

Any other call of a complex function, for example SELECT f(col) FROM t or WHERE f(col), goes to try_eval_udf, which does not accept the body and returns an "unsupported" error. Not verified: no test calls a complex function once per row. (source: src/query/engine.rs, try_eval_udf, is_complex_plpgsql_body)

The PL/pgSQL interpreter

parse_plpgsql_body turns the body into a list of PlpgsqlStmt values and PlpgsqlInterpreter runs them. Comments are removed first. (source: src/query/plpgsql.rs, parse_plpgsql_body, PlpgsqlStmt, PlpgsqlInterpreter)

Supported statements

Statement Notes
DECLARE with CONSTANT and initial values
var := expr only :=; var = expr is not an assignment
RETURN expr, RETURN QUERY query, RETURN QUERY EXECUTE sql USING ...  
SELECT ... INTO [STRICT] target target may be plain variables or a record; values are bound as text
PERFORM query  
INSERT, UPDATE, DELETE, WITH ... run as SQL
EXECUTE sql [INTO var] [USING args] dynamic SQL
IF ... ELSIF ... ELSE ... END IF  
LOOP, WHILE, FOR i IN [REVERSE] a..b [BY n]  
FOR rec IN query LOOP record fields keep their column types
FOREACH x IN ARRAY arr rewritten to unnest; SLICE gives an "unsupported" error
EXIT, CONTINUE with optional label and WHEN  
<<label>> blocks, nested BEGIN ... EXCEPTION WHEN ... END  
NULL;  
GET DIAGNOSTICS var = ROW_COUNT row count of the last DML the interpreter ran; other items give NULL
RAISE level 'fmt', args [USING ERRCODE = ...] see below
any other statement sent to the engine as SQL

(source: src/query/plpgsql.rs, parse_plpgsql_body, PlpgsqlInterpreter)

The interpreter stops nesting at depth 128 and stops any loop after 1,000,000 iterations. (source: src/query/plpgsql.rs, MAX_DEPTH, MAX_LOOP_ITERS)

Not supported

CASE statements (the CASE expression works inside SQL), RETURN NEXT, = as assignment, cursor statements (OPEN, FETCH, CLOSE), ASSERT, and %TYPE / %ROWTYPE declarations as real type references. (source: src/query/plpgsql.rs, parse_plpgsql_body)

How variables reach SQL

Local variables are substituted into each SQL statement as literals by a whole-word text replacement. A local that has the same name as a column or table used in the statement is replaced there too, where PostgreSQL would report the name as ambiguous. Prefixing locals (for example v_total) avoids the problem. (source: src/query/plpgsql.rs, rewrite_local_refs)

RAISE

Level Effect
EXCEPTION (the default) aborts with message ERROR <text> (<code>); the code is P0001 unless USING ERRCODE sets it
WARNING, NOTICE, INFO, LOG, DEBUG written to the server log only

% placeholders are filled from the arguments. Of the USING options only ERRCODE is read; MESSAGE, DETAIL and HINT are ignored. (source: src/query/plpgsql.rs, PlpgsqlInterpreter, RAISE handling)

No RAISE message reaches the client as a notice: the engine's send_notice writes it to the log with tracing::info!, and the PostgreSQL handler never sends a NoticeResponse (see PostgreSQL protocol). (source: src/query/engine.rs, PlpgsqlEngine::send_notice)

A RAISE EXCEPTION error is a QueryExecution error that carries its code only in the text, and the PostgreSQL handler maps that kind to XX000. A client therefore sees XX000, not P0001 or the ERRCODE given. (source: src/protocol/postgres/mod.rs, PostgresHandler::error_to_sqlstate)

EXCEPTION blocks

A WHEN clause is matched against a SQLSTATE derived from the error text:

Error text contains Derived SQLSTATE
a five-character code in parentheses, such as (P0001) that code
unique 23505
division by zero 22012
already exists 42P07 for a relation, table or index; 42P06 schema; 42P04 database; 42723 function; 42701 column; otherwise 42710
null value 23502
anything else P0001

(source: src/query/plpgsql.rs, extract_sqlstate, sqlstate_to_name)

Foreign key and CHECK violations are not recognised, so WHEN foreign_key_violation and WHEN check_violation never match; they fall through to WHEN OTHERS or propagate. Not verified: no test covers these handlers. (source: src/query/plpgsql.rs, extract_sqlstate)

There is no subtransaction around a block with an EXCEPTION clause. Writes made inside the block before the error stay in place when the handler runs, where PostgreSQL rolls them back. SQLERRM and SQLSTATE are not set inside the handler. (source: src/query/plpgsql.rs, PlpgsqlInterpreter, exception handling)

Interpreter tests: test_udf_plpgsql_declare_assign_return, test_udf_plpgsql_while_loop, test_udf_plpgsql_for_range_loop, test_udf_plpgsql_raise, test_udf_plpgsql_if_elsif_else, test_udf_plpgsql_exception_handler, test_udf_plpgsql_perform, test_udf_plpgsql_select_into, test_udf_plpgsql_dynamic_execute, test_udf_plpgsql_return_query, test_plpgsql_body_comments, plpgsql_comment_before_return_and_timestamp_id; in src/query/engine_plpgsql_locals_tests.rs: declare_defaults_assignment_and_if, assign_to_undeclared_local_errors, execute_string_containing_using_and_into.

DO blocks

DO [LANGUAGE plpgsql] $$ ... $$ runs the body once in the interpreter. (source: src/query/engine.rs, LogicalPlan::DoBlock arm, exec_do_block)

Errors are handled differently from PostgreSQL:

Situation Result
Body runs without error success
Interpreter raises an "unsupported" or parse error while running error logged, block reports success; statements before the failure have already run
Any other runtime error (constraint violation, RAISE EXCEPTION) the DO statement fails
Interpreter cannot parse the body falls back to the trigger-body parser (below)
Neither parser accepts the body block does nothing, logs a warning and reports success

(source: src/query/engine.rs, exec_do_block)

In the trigger-parser fallback each statement that fails is logged and skipped, and an IF whose condition cannot be evaluated takes the THEN branch. A migration script that uses an unsupported construct can therefore report success after running only part of its body. (source: src/query/engine.rs, exec_do_block)

flowchart TD A["DO block"] --> B{"interpreter parses body?"} B -- yes --> C["run in PlpgsqlInterpreter"] C --> D{"error kind"} D -- none --> OK["success"] D -- "unsupported or parse" --> L["log, report success"] D -- other --> F["statement fails"] B -- no --> E{"trigger parser accepts?"} E -- yes --> G["run statements, skip and log failures"] G --> OK E -- no --> W["warn, do nothing, report success"]

(source: src/query/engine.rs, exec_do_block)

Test: audit_hash_chain_trigger_with_declare_locals (src/query/engine_plpgsql_locals_tests.rs). Not verified: no test covers the success-after-unsupported path.

Triggers

CREATE TRIGGER

Clause Behaviour
BEFORE, AFTER supported
INSTEAD OF rejected as unsupported
INSERT, UPDATE, UPDATE OF col, ..., DELETE, joined with OR supported
TRUNCATE rejected as unsupported
FOR EACH ROW supported; the default when FOR EACH is omitted
FOR EACH STATEMENT accepted and stored, never fired
WHEN (condition) supported; the trigger fires only when the condition is TRUE
REFERENCING OLD TABLE AS ... NEW TABLE AS ... parsed and ignored
FROM referenced_table, DEFERRABLE (constraint trigger options) rejected as unsupported
EXECUTE FUNCTION f(args) or EXECUTE PROCEDURE f(args) supported; the arguments are ignored

(source: src/query/sql/parser.rs, parse_create_trigger; src/query/engine.rs, execute_create_trigger)

CREATE TRIGGER fails if the function does not exist. Triggers are stored in __catalog__:triggers:{table} and fire in name order, as in PostgreSQL. (source: src/query/engine.rs, execute_create_trigger) DROP TABLE removes the table's triggers (test: test_drop_table_drops_triggers_and_drop_type_composite). CREATE CONSTRAINT TRIGGER and ALTER TABLE ... ENABLE / DISABLE TRIGGER are covered in Statements.

Not wired: statement-level triggers. fire_before_row_triggers and fire_after_row_triggers skip every trigger whose for_each_row is false, and no other code fires them. The comment in parse_create_trigger says "the engine fires them once per statement", which the engine code does not do. (source: src/query/engine.rs, fire_before_row_triggers, fire_after_row_triggers; src/query/sql/parser.rs, parse_create_trigger)

Firing

sequenceDiagram participant S as "INSERT, UPDATE or DELETE" participant B as "BEFORE ROW triggers" participant W as "constraint checks and write" participant A as "AFTER ROW triggers" S->>B: each row, in trigger name order B-->>S: "RETURN NULL skips the row" B->>W: "modified NEW row" W->>A: row written A-->>S: "return value ignored"

(source: src/query/engine.rs, fire_before_row_triggers, fire_after_row_triggers)

  • A BEFORE trigger that returns NULL skips the row. A BEFORE trigger that changes NEW passes the changed row to the next trigger and then to the write. (source: src/query/engine.rs, fire_before_row_triggers)
  • The return value of an AFTER trigger is ignored. (source: src/query/engine.rs, fire_after_row_triggers)
  • UPDATE OF cols fires only when the value of one of the listed columns differs between OLD and NEW. PostgreSQL instead fires when a listed column appears in the statement's SET list, even if the value does not change. A listed column that the table does not have makes the trigger fire. (source: src/query/engine.rs, trigger_update_of_fires)
  • WHEN is evaluated against OLD and NEW and fires only on TRUE. (source: src/query/engine.rs, eval_trigger_when)
  • Triggers that cause further triggers stop at a nesting depth of 16. Every 4 levels the trigger body moves to a thread with a larger stack. (source: src/query/engine.rs, TRIGGER_MAX_DEPTH, TRIGGER_STACK_HOP)

What a trigger function may contain

Trigger functions do not use the interpreter. parse_trigger_body lowers the body into a small set of TriggerStmt forms:

Supported in trigger bodies Notes
RETURN NEW, RETURN OLD, RETURN NULL any other RETURN is an error; reaching the end without RETURN means RETURN NEW
NEW.col := expr or NEW.col = expr quoted column names allowed
INSERT, UPDATE, DELETE, WITH ... NEW.x and OLD.x are substituted as literals; the statement runs through the normal path, so constraints and nested triggers apply
SELECT ... INTO NEW.col, OLD.col or a local  
IF ... ELSIF ... ELSE ... END IF  
DECLARE locals and assignment to them  
LANGUAGE sql bodies  

(source: src/query/triggers.rs, parse_trigger_body, TriggerStmt; src/query/engine.rs, substitute_trigger_refs)

These give an explicit "unsupported" error when the trigger function is parsed: PERFORM, RAISE, LOOP, WHILE, FOR, EXECUTE, CASE, nested BEGIN blocks, GET DIAGNOSTICS, ASSERT and NULL;. (source: src/query/triggers.rs, classify_simple_statement)

The special variables TG_OP, TG_TABLE_NAME, TG_WHEN, TG_LEVEL and TG_ARGV are not provided, so one function cannot branch on the event that fired it. (source: src/query/triggers.rs, parse_trigger_body; no reference to TG_ in src/query)

On the PostgreSQL wire, SET session_replication_role = replica (which pg_dump output uses to load data) is stored but does not turn triggers off; see Session settings. (source: src/query/engine.rs, fire_before_row_triggers)

Trigger tests: test_trigger_before_insert_sets_new_col, test_trigger_after_insert_denorm_counter, test_trigger_before_insert_return_null_skips, test_trigger_when_condition_gates, test_trigger_drop_stops_firing, test_trigger_before_update_and_delete, test_trigger_fire_order_by_name, test_trigger_recursion_guard, test_trigger_unsupported_construct_errors, test_trigger_assigns_quoted_new_column, test_trigger_instead_of_rejected, test_trigger_missing_function_errors, test_drop_table_drops_triggers_and_drop_type_composite, test_bug9_update_after_trigger_nested_dml_same_row_no_deadlock, audit_hash_chain_trigger_with_declare_locals; feature matrix scenario trigger-before-insert.

Parsed but not executed

Construct What happens
CREATE PROCEDURE, CALL procedure ignored; no CALL (see Statements)
FOR EACH STATEMENT triggers stored, never fired
REFERENCING transition tables ignored
Trigger function arguments ignored
Function attributes (STRICT, SECURITY DEFINER, volatility, SET) ignored
Parameter modes and defaults all IN; defaults ignored
RAISE NOTICE and lower levels server log only
RAISE ... USING MESSAGE / DETAIL / HINT ignored
DO bodies with unsupported constructs partial run, reported as success

(source: src/query/sql/parser.rs, parse_create_function, parse_create_trigger; src/query/engine.rs, fire_before_row_triggers, exec_do_block; src/query/plpgsql.rs, PlpgsqlInterpreter)

Functions and triggers are listed in pg_proc, pg_trigger, information_schema.routines and information_schema.triggers on the PostgreSQL wire; see System catalogs.