plpgsql_check is a linter tool (does source code static analyze) for the PostgreSQL language plpgsql (the native language for PostgreSQL store procedures).
plpgsql_check is a linter tool (does source code static analyze) for the PostgreSQL language plpgsql (the native language for PostgreSQL store procedures).
This extension is a full linter for plpgsql for PostgreSQL. It leverages only the internal PostgreSQL parser/evaluator so you see exactly the errors would occur at runtime. Furthermore, it parses the SQL inside your routines and finds errors not usually found during the "CREATE PROCEDURE/FUNCTION" command. You can control the levels of many warnings and hints. Finally, you can add PRAGMA type markers to turn off/on many aspects allowing you to hide messages you already know about, or to remind you to come back for deeper cleaning later.
I founded this project, because I wanted to publish the code I wrote for the two years, when I tried to write enhanced checking for PostgreSQL upstream. It was not fully successful - integration into upstream requires some larger plpgsql refactoring. But the code is fully functional and can be used in production (and it is used in production). So, I created this extension to be available for all plpgsql developers.
If you want to join our group to help the further development of this extension, register yourself at that postgresql extension hacking google group.
I invite any ideas, patches, bugreports.
PostgreSQL 14 - 19 are supported.
The SQL statements inside PL/pgSQL functions are checked by the validator for semantic errors. These errors can be found by calling the plpgsql_check_function:
postgres=# CREATE EXTENSION plpgsql_check;
LOAD
postgres=# CREATE TABLE t1(a int, b int);
CREATE TABLE
postgres=#
CREATE OR REPLACE FUNCTION public.f1()
RETURNS void
LANGUAGE plpgsql
AS $function$
DECLARE r record;
BEGIN
FOR r IN SELECT * FROM t1
LOOP
RAISE NOTICE '%', r.c; -- there is bug - table t1 missing "c" column
END LOOP;
END;
$function$;
CREATE FUNCTION
postgres=# select f1(); -- execution doesn't find a bug due to empty table t1
f1
────
(1 row)
postgres=# \\x
Expanded display is on.
postgres=# select * from plpgsql_check_function_tb('f1()');
─[ RECORD 1 ]───────────────────────────
functionid │ f1
lineno │ 6
statement │ RAISE
sqlstate │ 42703
message │ record "r" has no field "c"
detail │ [null]
hint │ [null]
level │ error
position │ 0
query │ [null]
postgres=# \sf+ f1
CREATE OR REPLACE FUNCTION public.f1()
RETURNS void
LANGUAGE plpgsql
1 AS $function$
2 DECLARE r record;
3 BEGIN
4 FOR r IN SELECT * FROM t1
5 LOOP
6 RAISE NOTICE '%', r.c; -- there is bug - table t1 missing "c" column
7 END LOOP;
8 END;
9 $function$Function plpgsql_check_function() has three possible output formats: text, json or xml
select * from plpgsql_check_function('f1()', fatal_errors := false);
plpgsql_check_function
------------------------------------------------------------------------
error:42703:4:SQL statement:column "c" of relation "t1" does not exist
Query: update t1 set c = 30
-- ^
error:42P01:7:RAISE:missing FROM-clause entry for table "r"
Query: SELECT r.c
-- ^
error:42601:7:RAISE:too few parameters specified for RAISE
(7 rows)
postgres=# select * from plpgsql_check_function('fx()', format:='xml');
plpgsql_check_function
────────────────────────────────────────────────────────────────
↵
↵
error ↵
42P01 ↵
relation "foo111" does not exist ↵
RETURN ↵
SELECT (select a from foo111)↵
↵
(1 row)You can set level of warnings via function's parameters:
funcoid oid - function name or function signature - functions require a function specification.
Any function in PostgreSQL can be specified by Oid or by name or by signature. When
you know oid or complete function's signature, you can use a regprocedure type parameter
like 'fx()'::regprocedure or 16799::regprocedure. Possible alternative is using
a name only, when function's name is unique - like 'fx'. When the name is not unique
or the function doesn't exists it raises a error.relid DEFAULT 0 - oid of relation assigned with trigger function. It is necessary to check
any trigger function. You are sending the table in that the trigger operates on.
fatal_errors boolean DEFAULT true - stop on first error (prevents massive error reports)
other_warnings boolean DEFAULT true - show warnings like different attributes number
in assignment on left and right side, variable overlaps function's parameter, unused
variables, unwanted casting, etc.
extra_warnings boolean DEFAULT true - show warnings like missing RETURN,
shadowed variables, dead code, never read (unused) function's parameter,
unmodified variables, modified auto variables, etc.
performance_warnings boolean DEFAULT false - performance related warnings like
declared type with type modifier, casting, implicit casts in where clause (can be
the reason why an index is not used), etc.
security_warnings boolean DEFAULT false - security related checks like SQL injection
vulnerability detection
compatibility_warnings boolean DEFAULT false - compatibility related checks like obsolete explicit
setting internal cursor names in refcursor's or cursor's variables.
anyelementtype regtype DEFAULT 'int' - an actual type to be used when testing the anyelement type
anyenumtype regtype DEFAULT '-' - an actual type to be used when testing the anyenum type
anyrangetype regtype DEFAULT 'int4range' - an actual type to be used when testing the anyrange type
anycompatibletype DEFAULT 'int' - an actual type to be used when testing the anycompatible type
anycompatiblerangetype DEFAULT 'int4range' - an actual range type to be used when testing the anycompatible range type
without_warnings DEFAULT false - disable all warnings (Ignores all xxxx_warning parameters, a quick override)
all_warnings DEFAULT false - enable all warnings (Ignores other xxx_warning parameters, a quick positive)
newtable DEFAULT NULL, oldtable DEFAULT NULL - the names of NEW or OLD transition
tables. These parameters are required when transition tables are used in trigger functions.
use_incomment_options DEFAULT true - when it is true, then in-comment options are active
incomment_options_usage_warning DEFAULT false - when it is true, then the warning is raised when
in-comment option is used.
constant_tracing boolean DEFAULT true - when it is true, then the variable that holds
some constant content, can be used like constant (it is work only in some simple cases,
and the content of variable should not be ambiguous).
pragmas text[] DEFAULT NULL - list of pragmas that are applied before the check is
started. Any pragma supported by the plpgsql_check_pragma function can be used here.
The main usage is passing the table pragmas generated by the function
plpgsql_make_pragma (see the section "Table pragmas generator").
When you want to check any trigger, you have to enter a relation that will be used together with trigger function
CREATE TABLE bar(a int, b int);
postgres=# \sf+ foo_trg
CREATE OR REPLACE FUNCTION public.foo_trg()
RETURNS trigger
LANGUAGE plpgsql
1 AS $function$
2 BEGIN
3 NEW.c := NEW.a + NEW.b;
4 RETURN NEW;
5 END;
6 $function$Missing relation specification
postgres=# select * from plpgsql_check_function('foo_trg()');
ERROR: missing trigger relation
HINT: Trigger relation oid must be validCorrect trigger checking (with specified relation)
postgres=# select * from plpgsql_check_function('foo_trg()', 'bar');
plpgsql_check_function
--------------------------------------------------------
error:42703:3:assignment:record "new" has no field "c"
(1 row)For triggers with transitive tables you can set the oldtable and newtable parameters:
create or replace function footab_trig_func()
returns trigger as $$
declare x int;
begin
if false then
-- should be ok;
select count(*) from newtab into x;
-- should fail;
select count(*) from newtab where d = 10 into x;
end if;
return null;
end;
$$ language plpgsql;
select * from plpgsql_check_function('footab_trig_func','footab', newtable := 'newtab');plpgsql_check allows persistent setting written in comments. These options are taken from function's source code before checking. The syntax is:
@plpgsql_check_option: optioname [=] value [, optname [=] value ...]The settings from comment options has top high priority, but generally it can be disabled
by option use_incomment_options to false.
Example:
create or replace function fx(anyelement)
returns text as $$
begin
/*
* rewrite default polymorphic type to text
* @plpgsql_check_options: anyelementtype = text
*/
return $1;
end;
$$ language plpgsql;You can use the plpgsql_check_function for mass checking of functions/procedures and mass checking of triggers. Please, test following queries:
-- check all nontrigger plpgsql functions
SELECT p.oid, p.proname, plpgsql_check_function(p.oid)
FROM pg_catalog.pg_namespace n
JOIN pg_catalog.pg_proc p ON pronamespace = n.oid
JOIN pg_catalog.pg_language l ON p.prolang = l.oid
WHERE l.lanname = 'plpgsql' AND p.prorettype <> 2279;or
-- check all trigger plpgsql functions
SELECT p.proname, tgrelid::regclass, cf.*
FROM pg_proc p
JOIN pg_trigger t ON t.tgfoid = p.oid
JOIN pg_language l ON p.prolang = l.oid
JOIN pg_namespace n ON p.pronamespace = n.oid,
LATERAL plpgsql_check_function(p.oid, t.tgrelid, oldtable=>t.tgoldtable, newtable=>t.tgnewtable) cf
WHERE n.nspname = 'public' and l.lanname = 'plpgsql';or
-- check all plpgsql functions (functions or trigger functions with defined triggers)
SELECT
(pcf).functionid::regprocedure, (pcf).lineno, (pcf).statement,
(pcf).sqlstate, (pcf).message, (pcf).detail, (pcf).hint, (pcf).level,
(pcf)."position", (pcf).query, (pcf).context
FROM
(
SELECT
plpgsql_check_function_tb(pg_proc.oid, COALESCE(pg_trigger.tgrelid, 0),
oldtable=>pg_trigger.tgoldtable,
newtable=>pg_trigger.tgnewtable) AS pcf
FROM pg_proc
LEFT JOINNo open issues yet, or sync has not completed.