{"id":13705757,"url":"https://github.com/okbob/plpgsql_check","last_synced_at":"2026-02-18T07:10:17.235Z","repository":{"id":12763843,"uuid":"15437182","full_name":"okbob/plpgsql_check","owner":"okbob","description":"plpgsql_check is a linter tool (does source code static analyze) for the PostgreSQL language plpgsql (the native language for PostgreSQL store procedures).","archived":false,"fork":false,"pushed_at":"2026-02-13T13:41:22.000Z","size":2016,"stargazers_count":738,"open_issues_count":3,"forks_count":56,"subscribers_count":26,"default_branch":"master","last_synced_at":"2026-02-13T19:17:41.369Z","etag":null,"topics":["c","extension","function-plpgsql","linter","pldbgapi","plpgsql","postgresql","postgresql-extension","profiler","stored-procedures"],"latest_commit_sha":null,"homepage":"https://groups.google.com/forum/#!forum/postgresql-extensions-hacking","language":"C","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"other","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/okbob.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2013-12-25T15:44:18.000Z","updated_at":"2026-02-13T13:41:26.000Z","dependencies_parsed_at":"2025-12-30T14:01:10.274Z","dependency_job_id":null,"html_url":"https://github.com/okbob/plpgsql_check","commit_stats":{"total_commits":706,"total_committers":18,"mean_commits":39.22222222222222,"dds":0.1841359773371105,"last_synced_commit":"3c9678a9fa8d0254c0b24599033181eff72e3958"},"previous_names":[],"tags_count":107,"template":false,"template_full_name":null,"purl":"pkg:github/okbob/plpgsql_check","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/okbob%2Fplpgsql_check","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/okbob%2Fplpgsql_check/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/okbob%2Fplpgsql_check/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/okbob%2Fplpgsql_check/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/okbob","download_url":"https://codeload.github.com/okbob/plpgsql_check/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/okbob%2Fplpgsql_check/sbom","scorecard":{"id":703931,"data":{"date":"2025-08-11","repo":{"name":"github.com/okbob/plpgsql_check","commit":"442c5bcbbb8c393b940fa411f529a81076fd0fad"},"scorecard":{"version":"v5.2.1-40-gf6ed084d","commit":"f6ed084d17c9236477efd66e5b258b9d4cc7b389"},"score":4.3,"checks":[{"name":"Maintained","score":10,"reason":"11 commit(s) and 3 issue activity found in the last 90 days -- score normalized to 10","details":null,"documentation":{"short":"Determines if the project is \"actively maintained\".","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#maintained"}},{"name":"Dangerous-Workflow","score":10,"reason":"no dangerous workflow patterns detected","details":null,"documentation":{"short":"Determines if the project's GitHub Action workflows avoid dangerous patterns.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#dangerous-workflow"}},{"name":"Code-Review","score":0,"reason":"Found 0/28 approved changesets -- score normalized to 0","details":null,"documentation":{"short":"Determines if the project requires human code review before pull requests (aka merge requests) are merged.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#code-review"}},{"name":"Packaging","score":-1,"reason":"packaging workflow not detected","details":["Warn: no GitHub/GitLab publishing workflow detected."],"documentation":{"short":"Determines if the project is published as a package that others can easily download, install, easily update, and uninstall.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#packaging"}},{"name":"Pinned-Dependencies","score":0,"reason":"dependency not pinned by hash detected -- score normalized to 0","details":["Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/main.yml:20: update your workflow using https://app.stepsecurity.io/secureworkflow/okbob/plpgsql_check/main.yml/master?enable=pin","Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/release.yml:15: update your workflow using https://app.stepsecurity.io/secureworkflow/okbob/plpgsql_check/release.yml/master?enable=pin","Info:   0 out of   2 GitHub-owned GitHubAction dependencies pinned"],"documentation":{"short":"Determines if the project has declared and pinned the dependencies of its build process.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#pinned-dependencies"}},{"name":"Binary-Artifacts","score":10,"reason":"no binaries found in the repo","details":null,"documentation":{"short":"Determines if the project has generated executable (binary) artifacts in the source repository.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#binary-artifacts"}},{"name":"Token-Permissions","score":0,"reason":"detected GitHub workflow tokens with excessive permissions","details":["Warn: no topLevel permission defined: .github/workflows/main.yml:1","Warn: no topLevel permission defined: .github/workflows/release.yml:1","Info: no jobLevel write permissions found"],"documentation":{"short":"Determines if the project's workflows follow the principle of least privilege.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#token-permissions"}},{"name":"CII-Best-Practices","score":0,"reason":"no effort to earn an OpenSSF best practices badge detected","details":null,"documentation":{"short":"Determines if the project has an OpenSSF (formerly CII) Best Practices Badge.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#cii-best-practices"}},{"name":"Security-Policy","score":0,"reason":"security policy file not detected","details":["Warn: no security policy file detected","Warn: no security file to analyze","Warn: no security file to analyze","Warn: no security file to analyze"],"documentation":{"short":"Determines if the project has published a security policy.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#security-policy"}},{"name":"License","score":9,"reason":"license file detected","details":["Info: project has a license file: LICENSE:0","Warn: project license file does not contain an FSF or OSI license."],"documentation":{"short":"Determines if the project has defined a license.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#license"}},{"name":"Fuzzing","score":0,"reason":"project is not fuzzed","details":["Warn: no fuzzer integrations found"],"documentation":{"short":"Determines if the project uses fuzzing.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#fuzzing"}},{"name":"Vulnerabilities","score":10,"reason":"0 existing vulnerabilities detected","details":null,"documentation":{"short":"Determines if the project has open, known unfixed vulnerabilities.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#vulnerabilities"}},{"name":"Signed-Releases","score":-1,"reason":"no releases found","details":null,"documentation":{"short":"Determines if the project cryptographically signs release artifacts.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#signed-releases"}},{"name":"Branch-Protection","score":0,"reason":"branch protection not enabled on development/release branches","details":["Warn: branch protection not enabled for branch 'master'"],"documentation":{"short":"Determines if the default and release branches are protected with GitHub's branch protection settings.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#branch-protection"}},{"name":"SAST","score":0,"reason":"SAST tool is not run on all commits -- score normalized to 0","details":["Warn: 0 commits out of 3 are checked with a SAST tool"],"documentation":{"short":"Determines if the project uses static code analysis.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#sast"}}]},"last_synced_at":"2025-08-22T05:56:17.093Z","repository_id":12763843,"created_at":"2025-08-22T05:56:17.093Z","updated_at":"2025-08-22T05:56:17.093Z"},"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":29571926,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-02-18T06:19:27.422Z","status":"ssl_error","status_checked_at":"2026-02-18T06:18:44.348Z","response_time":162,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.6:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["c","extension","function-plpgsql","linter","pldbgapi","plpgsql","postgresql","postgresql-extension","profiler","stored-procedures"],"created_at":"2024-08-02T22:00:47.456Z","updated_at":"2026-02-18T07:10:17.219Z","avatar_url":"https://github.com/okbob.png","language":"C","readme":"[![Stand With Ukraine](https://raw.githubusercontent.com/vshymanskyy/StandWithUkraine/main/banner2-direct.svg)](https://stand-with-ukraine.pp.ua)\n\nplpgsql_check\n=============\n\nThis extension is a full linter for plpgsql for PostgreSQL.  It leverages only the internal \nPostgreSQL parser/evaluator so you see exactly the errors would occur at runtime.\nFurthermore, it parses the SQL inside your routines and finds errors not usually found during\nthe \"CREATE PROCEDURE/FUNCTION\" command.  You can control the levels of many warnings and hints.\nFinally, you can add PRAGMA type markers to turn off/on many aspects allowing you to hide\nmessages you already know about, or to remind you to come back for deeper cleaning later.\n\nI founded this project, because I wanted to publish the code I wrote for the  two years,\nwhen I tried to write enhanced checking for PostgreSQL upstream. It was not fully\nsuccessful - integration into upstream requires some larger plpgsql refactoring.\nBut the code is fully functional and can be used in production (and it is used in production).\nSo, I created this extension to be available for all plpgsql developers.\n\nIf if you want to join our group to help the further development of this extension, register\nyourself at that [postgresql extension hacking](https://groups.google.com/forum/#!forum/postgresql-extensions-hacking)\ngoogle group.\n\n# Features\n\n* checks fields of referenced database objects and types inside embedded SQL\n* validates you are using the correct types for function parameters\n* identifies unused variables and function arguments, unmodified OUT arguments\n* partial detection of dead code (code after an RETURN command)\n* detection of missing RETURN command in function (common after exception handlers, complex logic)\n* tries to identify unwanted hidden casts, which can be a performance issue like unused indexes\n* ability to collect relations and functions used by function\n* ability to check EXECUTE statements against SQL injection vulnerability\n\nI invite any ideas, patches, bugreports.\n\nPostgreSQL PostgreSQL 14 - 18 are supported.\n\nThe SQL statements inside PL/pgSQL functions are checked by the validator for semantic errors. These errors\ncan be found by calling the plpgsql_check_function:\n\n# Active mode\n\n    postgres=# CREATE EXTENSION plpgsql_check;\n    LOAD\n    postgres=# CREATE TABLE t1(a int, b int);\n    CREATE TABLE\n\n    postgres=#\n    CREATE OR REPLACE FUNCTION public.f1()\n    RETURNS void\n    LANGUAGE plpgsql\n    AS $function$\n    DECLARE r record;\n    BEGIN\n      FOR r IN SELECT * FROM t1\n      LOOP\n        RAISE NOTICE '%', r.c; -- there is bug - table t1 missing \"c\" column\n      END LOOP;\n    END;\n    $function$;\n\n    CREATE FUNCTION\n\n    postgres=# select f1(); -- execution doesn't find a bug due to empty table t1\n      f1 \n     ────\n       \n     (1 row)\n\n    postgres=# \\x\n    Expanded display is on.\n    postgres=# select * from plpgsql_check_function_tb('f1()');\n    ─[ RECORD 1 ]───────────────────────────\n    functionid │ f1\n    lineno     │ 6\n    statement  │ RAISE\n    sqlstate   │ 42703\n    message    │ record \"r\" has no field \"c\"\n    detail     │ [null]\n    hint       │ [null]\n    level      │ error\n    position   │ 0\n    query      │ [null]\n\n    postgres=# \\sf+ f1\n        CREATE OR REPLACE FUNCTION public.f1()\n         RETURNS void\n         LANGUAGE plpgsql\n    1       AS $function$\n    2       DECLARE r record;\n    3       BEGIN\n    4         FOR r IN SELECT * FROM t1\n    5         LOOP\n    6           RAISE NOTICE '%', r.c; -- there is bug - table t1 missing \"c\" column\n    7         END LOOP;\n    8       END;\n    9       $function$\n\n\nFunction plpgsql_check_function() has three possible output formats: text, json or xml\n\n    select * from plpgsql_check_function('f1()', fatal_errors := false);\n                             plpgsql_check_function                         \n    ------------------------------------------------------------------------\n     error:42703:4:SQL statement:column \"c\" of relation \"t1\" does not exist\n     Query: update t1 set c = 30\n     --                   ^\n     error:42P01:7:RAISE:missing FROM-clause entry for table \"r\"\n     Query: SELECT r.c\n     --            ^\n     error:42601:7:RAISE:too few parameters specified for RAISE\n    (7 rows)\n\n    postgres=# select * from plpgsql_check_function('fx()', format:='xml');\n                     plpgsql_check_function                     \n    ────────────────────────────────────────────────────────────────\n     \u003cFunction oid=\"16400\"\u003e                                        ↵\n       \u003cIssue\u003e                                                     ↵\n         \u003cLevel\u003eerror\u003c/level\u003e                                      ↵\n         \u003cSqlstate\u003e42P01\u003c/Sqlstate\u003e                                ↵\n         \u003cMessage\u003erelation \"foo111\" does not exist\u003c/Message\u003e       ↵\n         \u003cStmt lineno=\"3\"\u003eRETURN\u003c/Stmt\u003e                            ↵\n         \u003cQuery position=\"23\"\u003eSELECT (select a from foo111)\u003c/Query\u003e↵\n       \u003c/Issue\u003e                                                    ↵\n      \u003c/Function\u003e\n     (1 row)\n\n## Arguments\n\nYou can set level of warnings via function's parameters:\n            \n### Mandatory argument\n\n* `funcoid oid` - function name or function signature - functions require a function specification.\n  Any function in PostgreSQL can be specified by Oid or by name or by signature. When\n  you know oid or complete function's signature, you can use a regprocedure type parameter\n  like `'fx()'::regprocedure` or `16799::regprocedure`. Possible alternative is using\n  a name only, when function's name is unique - like `'fx'`. When the name is not unique\n  or the function doesn't exists it raises a error.\n\n### Optional arguments\n\n* `relid DEFAULT 0` - oid of relation assigned with trigger function. It is necessary to check\n   any trigger function.  You are sending the table in that the trigger operates on.\n\n* `fatal_errors boolean DEFAULT true` - stop on first error (prevents massive error reports)\n\n* `other_warnings boolean DEFAULT true` - show warnings like different attributes number\n  in assignmenet on left and right side, variable overlaps function's parameter, unused\n  variables, unwanted casting, etc.\n\n* `extra_warnings boolean DEFAULT true` - show warnings like missing `RETURN`,\n  shadowed variables, dead code, never read (unused) function's parameter,\n  unmodified variables, modified auto variables, etc.\n\n* `performance_warnings boolean DEFAULT false` - performance related warnings like\n  declared type with type modifier, casting, implicit casts in where clause (can be\n  the reason why an index is not used), etc.\n\n* `security_warnings boolean DEFAULT false` - security related checks like SQL injection\n  vulnerability detection\n\n* `compatibility_warnings boolean DEFAULT false` - compatibility related checks like obsolete explicit\n  setting internal cursor names in refcursor's or cursor's variables.\n\n* `anyelementtype regtype DEFAULT 'int'` - an actual type to be used when testing the anyelement type\n\n* `anyenumtype regtype DEFAULT '-'` - an actual type to be used when testing the anyenum type\n\n* `anyrangetype regtype DEFAULT 'int4range'` - an actual type to be used when testing the anyrange type\n\n* `anycompatibletype DEFAULT 'int'` - an actual type to be used when testing the anycompatible type\n\n* `anycompatiblerangetype DEFAULT 'int4range'` - an actual range type to be used when testing the anycompatible range type\n\n* `without_warnings DEFAULT false` - disable all warnings (Ignores all xxxx_warning parameters, a quick override)\n\n* `all_warnings DEFAULT false` - enable all warnings (Ignores other xxx_warning parameters, a quick positive)\n\n* `newtable DEFAULT NULL`, `oldtable DEFAULT NULL` - the names of NEW or OLD transition\n   tables. These parameters are required when transition tables are used in trigger functions.\n\n* `use_incomment_options DEFAULT true` - when it is true, then in-comment options are active\n\n* `incomment_options_usage_warning DEFAULT false` - when it is true, then the warning is raised when\n   in-comment option is used.\n\n* `constant_tracing boolean DEFAULT true` - when it is true, then the variable that holds\n   some constant content, can be used like constant (it is work only in some simple cases,\n   and the content of variable should not be ambigonuous).\n\n## Triggers\n\nWhen you want to check any trigger, you have to enter a relation that will be\nused together with trigger function\n\n    CREATE TABLE bar(a int, b int);\n\n    postgres=# \\sf+ foo_trg\n        CREATE OR REPLACE FUNCTION public.foo_trg()\n             RETURNS trigger\n             LANGUAGE plpgsql\n    1       AS $function$\n    2       BEGIN\n    3         NEW.c := NEW.a + NEW.b;\n    4         RETURN NEW;\n    5       END;\n    6       $function$\n\nMissing relation specification\n\n    postgres=# select * from plpgsql_check_function('foo_trg()');\n    ERROR:  missing trigger relation\n    HINT:  Trigger relation oid must be valid\n\nCorrect trigger checking (with specified relation)\n\n    postgres=# select * from plpgsql_check_function('foo_trg()', 'bar');\n                     plpgsql_check_function                 \n    --------------------------------------------------------\n     error:42703:3:assignment:record \"new\" has no field \"c\"\n    (1 row)\n\nFor triggers with transitive tables you can set the `oldtable` and `newtable` parameters:\n\n    create or replace function footab_trig_func()\n    returns trigger as $$\n    declare x int;\n    begin\n      if false then\n        -- should be ok;\n        select count(*) from newtab into x; \n\n        -- should fail;\n        select count(*) from newtab where d = 10 into x;\n      end if;\n      return null;\n    end;\n    $$ language plpgsql;\n\n    select * from plpgsql_check_function('footab_trig_func','footab', newtable := 'newtab');\n\n\n## In-comment options\n\nplpgsql_check allows persistent setting written in comments. These options are taken from\nfunction's source code before checking. The syntax is:\n\n    @plpgsql_check_option: optioname [=] value [, optname [=] value ...]\n\nThe settings from comment options has top high priority, but generally it can be disabled\nby option `use_incomment_options` to `false`.\n\nExample:\n\n    create or replace function fx(anyelement)\n    returns text as $$\n    begin\n      /*\n       * rewrite default polymorphic type to text\n       * @plpgsql_check_options: anyelementtype = text\n       */\n      return $1;\n    end;\n    $$ language plpgsql;\n\n\n## Checking all of your code\n\nYou can use the plpgsql_check_function for mass checking of functions/procedures and mass checking\nof triggers. Please, test following queries:\n\n    -- check all nontrigger plpgsql functions\n    SELECT p.oid, p.proname, plpgsql_check_function(p.oid)\n       FROM pg_catalog.pg_namespace n\n       JOIN pg_catalog.pg_proc p ON pronamespace = n.oid\n       JOIN pg_catalog.pg_language l ON p.prolang = l.oid\n      WHERE l.lanname = 'plpgsql' AND p.prorettype \u003c\u003e 2279;\n\nor\n\n    -- check all trigger plpgsql functions\n    SELECT p.proname, tgrelid::regclass, cf.*\n       FROM pg_proc p\n            JOIN pg_trigger t ON t.tgfoid = p.oid \n            JOIN pg_language l ON p.prolang = l.oid\n            JOIN pg_namespace n ON p.pronamespace = n.oid,\n            LATERAL plpgsql_check_function(p.oid, t.tgrelid, oldtable=\u003et.tgoldtable, newtable=\u003et.tgnewtable) cf\n      WHERE n.nspname = 'public' and l.lanname = 'plpgsql';\n\nor\n\n    -- check all plpgsql functions (functions or trigger functions with defined triggers)\n    SELECT\n        (pcf).functionid::regprocedure, (pcf).lineno, (pcf).statement,\n        (pcf).sqlstate, (pcf).message, (pcf).detail, (pcf).hint, (pcf).level,\n        (pcf).\"position\", (pcf).query, (pcf).context\n    FROM\n    (\n        SELECT\n            plpgsql_check_function_tb(pg_proc.oid, COALESCE(pg_trigger.tgrelid, 0),\n                                      oldtable=\u003epg_trigger.tgoldtable,\n                                      newtable=\u003epg_trigger.tgnewtable) AS pcf\n        FROM pg_proc\n        LEFT JOIN pg_trigger\n            ON (pg_trigger.tgfoid = pg_proc.oid)\n        WHERE\n            prolang = (SELECT lang.oid FROM pg_language lang WHERE lang.lanname = 'plpgsql') AND\n            pronamespace \u003c\u003e (SELECT nsp.oid FROM pg_namespace nsp WHERE nsp.nspname = 'pg_catalog') AND\n            -- ignore unused triggers\n            (pg_proc.prorettype \u003c\u003e (SELECT typ.oid FROM pg_type typ WHERE typ.typname = 'trigger') OR\n             pg_trigger.tgfoid IS NOT NULL)\n        OFFSET 0\n    ) ss\n    ORDER BY (pcf).functionid::regprocedure::text, (pcf).lineno;\n\n# Passive mode (only recommended for development or preproduction)\n\nFunctions can be checked upon execution - plpgsql_check module must be loaded (via postgresql.conf).\n\n## Configuration Settings\n\n    plpgsql_check.mode = [ disabled | by_function | fresh_start | every_start ]\n    plpgsql_check.fatal_errors = [ yes | no ]\n\n    plpgsql_check.show_nonperformance_warnings = false\n    plpgsql_check.show_performance_warnings = false\n\nDefault mode is \u003ci\u003eby_function\u003c/i\u003e, that means that the enhanced check is done only in\nactive mode - by calling the \u003ci\u003eplpgsql_check_function\u003c/i\u003e. `fresh_start` means cold start (first the function is called).\n\nYou can enable passive mode by\n\n    load 'plpgsql'; -- 1.1 and higher doesn't need it\n    load 'plpgsql_check';\n    set plpgsql_check.mode = 'every_start';  -- This scans all code before it is executed\n\n    SELECT fx(10); -- run functions - function is checked before runtime starts it\n\n# Compatibility warnings\n\n## Assigning string to refcursor variable\n\nPostgreSQL cursor's and refcursor's variables are enhanced string variables that holds\nunique name of related portal (internal structure of Postgres that is used for cursor's\nimplementation). Until PostgreSQL 16, the the portal had same name like name of cursor\nvariable. PostgreSQL 16 and higher change this mechanism and by default related portal\nwill be named by some unique name. It solves some issues with cursors in nested blocks\nor when cursor is used in recursive called function.\n\nWith mentioned change, the refcursor's variable should to take value from another\nrefcursor variable or from some cursor variable (when cursor is opened).\n\n    -- obsolete pattern\n    DECLARE\n      cur CURSOR FOR SELECT 1;\n      rcur refcursor;\n    BEGIN\n      rcur := 'cur';\n      OPEN cur;\n      ...\n\n    -- new pattern\n    DECLARE\n      cur CURSOR FOR SELECT 1;\n      rcur refcursor;\n    BEGIN\n      OPEN cur;\n      rcur := cur;\n      ...\n\nWhen `compatibility_warnings` flag is active, then `plpgsql_check` try to identify\nsome fishy assigning to refcursor's variable or returning of refcursor's values:\n\n    CREATE OR REPLACE FUNCTION public.foo()\n     RETURNS refcursor\n    AS $$\n    declare\n       c cursor for select 1;\n       r refcursor;\n    begin\n      open c;\n      r := 'c';\n      return r;\n    end;\n    $$ LANGUAGE plpgsql;\n\n    select * from plpgsql_check_function('foo', extra_warnings =\u003efalse, compatibility_warnings =\u003e true);\n    ┌───────────────────────────────────────────────────────────────────────────────────┐\n    │                              plpgsql_check_function                               │\n    ╞═══════════════════════════════════════════════════════════════════════════════════╡\n    │ compatibility:00000:6:assignment:obsolete setting of refcursor or cursor variable │\n    │ Detail: Internal name of cursor should not be specified by users.                 │\n    │ Context: at assignment to variable \"r\" declared on line 3                         │\n    └───────────────────────────────────────────────────────────────────────────────────┘\n    (3 rows)\n\n# Limits\n\n\u003ci\u003eplpgsql_check\u003c/i\u003e should find almost all errors on really static code. When developers use\nPLpgSQL's dynamic features like dynamic SQL or record data type, then false positives are\npossible. These should be rare - in well written code - and then the affected function\nshould be redesigned or plpgsql_check should be disabled for this function.\n\n    CREATE OR REPLACE FUNCTION f1()\n    RETURNS void AS $$\n    DECLARE r record;\n    BEGIN\n      FOR r IN EXECUTE 'SELECT * FROM t1'\n      LOOP\n        RAISE NOTICE '%', r.c;\n      END LOOP;\n    END;\n    $$ LANGUAGE plpgsql SET plpgsql.enable_check TO false;\n\n\u003ci\u003eA usage of plpgsql_check adds a small overhead (when passive mode is enabled) and you should use\nthat setting only in development or preproduction environments.\u003c/i\u003e\n\n## Dynamic SQL\n\nThis module doesn't check queries that are assembled in runtime. It is not possible\nto identify results of dynamic queries - so \u003ci\u003eplpgsql_check\u003c/i\u003e cannot to set correct type to record\nvariables and cannot to check a dependent SQLs and expressions. \n\nWhen type of record's variable is not know, you can assign it explicitly with pragma `type`:\n\n    DECLARE r record;\n    BEGIN\n      EXECUTE format('SELECT * FROM %I', _tablename) INTO r;\n      PERFORM plpgsql_check_pragma('type: r (id int, processed bool)');\n      IF NOT r.processed THEN\n        ...\n\n\u003cb\u003e\nAttention: The SQL injection check can detect only some SQL injection vulnerabilities. This tool\ncannot be used for security audit! Some issues will not be detected. This check can raise false\nalarms too - probably when variable is sanitized by other command or when the value is of some composite\ntype.\n\u003c/b\u003e\n\n## Refcursors\n\n\u003ci\u003eplpgsql_check\u003c/i\u003e cannot be used to detect structure of referenced cursors. A reference on cursor\nin PLpgSQL is implemented as name of global cursor. In check time, the name is not known (not in\nall possibilities), and global cursor doesn't exist. It is a significant issue for any static analysis.\nPLpgSQL cannot know how to set the correct type for the record variables and cannot to check the dependent \nSQL statements and expressions. A solution is the same for dynamic SQL. Don't use record variable\nas target when you use \u003ci\u003erefcursor\u003c/i\u003e type or disable \u003ci\u003eplpgsql_check\u003c/i\u003e for these functions.\n\n    CREATE OR REPLACE FUNCTION foo(refcur_var refcursor)\n    RETURNS void AS $$\n    DECLARE\n      rec_var record;\n    BEGIN\n      FETCH refcur_var INTO rec_var; -- this is STOP for plpgsql_check\n      RAISE NOTICE '%', rec_var;     -- record rec_var is not assigned yet error\n\nIn this case a record type should not be used (use known rowtype instead):\n\n    CREATE OR REPLACE FUNCTION foo(refcur_var refcursor)\n    RETURNS void AS $$\n    DECLARE\n      rec_var some_rowtype;\n    BEGIN\n      FETCH refcur_var INTO rec_var;\n      RAISE NOTICE '%', rec_var;\n\n## Temporary tables\n\n\u003ci\u003eplpgsql_check\u003c/i\u003e cannot verify queries over temporary tables that are created in plpgsql's function\nruntime. For this use case it is necessary to create a fake temp table or disable \u003ci\u003eplpgsql_check\u003c/i\u003e for this\nfunction.\n\nIn reality temp tables are stored in own (per user) schema with higher priority than persistent\ntables. So you can do (with following trick safetly):\n\n    CREATE OR REPLACE FUNCTION public.disable_dml()\n    RETURNS trigger\n    LANGUAGE plpgsql AS $function$\n    BEGIN\n      RAISE EXCEPTION SQLSTATE '42P01'\n         USING message = format('this instance of %I table doesn''t allow any DML operation', TG_TABLE_NAME),\n               hint = format('you should use \"CREATE TEMP TABLE %1$I(LIKE %1$I INCLUDING ALL);\" statement',\n                             TG_TABLE_NAME);\n      RETURN NULL;\n    END;\n    $function$;\n    \n    CREATE TABLE foo(a int, b int); -- doesn't hold data, ever\n    CREATE TRIGGER foo_disable_dml\n       BEFORE INSERT OR UPDATE OR DELETE ON foo\n       EXECUTE PROCEDURE disable_dml();\n\n    postgres=# INSERT INTO  foo VALUES(10,20);\n    ERROR:  this instance of foo table doesn't allow any DML operation\n    HINT:  you should to run \"CREATE TEMP TABLE foo(LIKE foo INCLUDING ALL);\" statement\n    postgres=# \n    \n    CREATE TABLE\n    postgres=# INSERT INTO  foo VALUES(10,20);\n    INSERT 0 1\n\nThis trick emulates GLOBAL TEMP tables partially and it allows a statical validation.\nOther possibility is using a [template foreign data wrapper] (https://github.com/okbob/template_fdw)\n\nYou can use pragma `table` and create ephemeral table:\n\n    BEGIN\n       CREATE TEMP TABLE xxx(a int);\n       PERFORM plpgsql_check_pragma('table: xxx(a int)');\n       INSERT INTO xxx VALUES(10);\n       PERFORM plpgsql_check_pragma('table: [pg_temp].zzz(like schemaname.table1 including all)');\n       ...\n\n\n# Dependency list\n\nA function \u003ci\u003eplpgsql_show_dependency_tb\u003c/i\u003e will show all functions, operators and relations used\ninside processed function:\n\n    postgres=# select * from plpgsql_show_dependency_tb('testfunc(int,float)');\n    ┌──────────┬───────┬────────┬─────────┬────────────────────────────┐\n    │   type   │  oid  │ schema │  name   │           params           │\n    ╞══════════╪═══════╪════════╪═════════╪════════════════════════════╡\n    │ FUNCTION │ 36008 │ public │ myfunc1 │ (integer,double precision) │\n    │ FUNCTION │ 35999 │ public │ myfunc2 │ (integer,double precision) │\n    │ OPERATOR │ 36007 │ public │ **      │ (integer,integer)          │\n    │ RELATION │ 36005 │ public │ myview  │                            │\n    │ RELATION │ 36002 │ public │ mytable │                            │\n    └──────────┴───────┴────────┴─────────┴────────────────────────────┘\n    (4 rows)\n\nOptional arguments of \u003ci\u003eplpgsql_show_dependency_tb\u003c/i\u003e are `relid`, `anyelementtype`, `enumtype`,\n`anyrangetype`, `anycompatibletype` and `anycompatiblerangetype`.\n\n# Profiler\n\nThe plpgsql_check contains simple profiler of plpgsql functions and procedures. It can work with/without\naccess to shared memory. It depends on `shared_preload_libraries` config. When plpgsql_check is initialized\nby `shared_preload_libraries`, then it can allocate shared memory, and function's profiles are stored there.\nWhen plpgsql_check cannot to allocate shared memory, the profile is stored in session memory.\n\nDue to dependencies, `shared_preload_libraries` should to contain `plpgsql` first\n\n    postgres=# show shared_preload_libraries ;\n    ┌──────────────────────────┐\n    │ shared_preload_libraries │\n    ╞══════════════════════════╡\n    │ plpgsql,plpgsql_check    │\n    └──────────────────────────┘\n    (1 row)\n\nThe profiler is active when GUC `plpgsql_check.profiler` is on. The profiler doesn't require shared memory,\nbut if there is not enough shared memory, then the profiler is limited just to active session.\nThe profiler can be activated by calling function `plpgsql_check_profiler(true)` and disabled\nby calling same function with `false` argument (or with literals `on`, `off`).\n\nThe plpgsql_check should be initialized before any plpgsql function is executed. Only\nearly initialization ensures correct work of profiler and tracer. When you doesn't use\n`shared_preloaded_libraries`, you can use command `load 'plpgsql_check'` instead.\n\nWhen plpgsql_check is initialized by `shared_preload_libraries`, another GUC is\navailable to configure the amount of shared memory used by the profiler:\n`plpgsql_check.profiler_max_shared_chunks`.  This defines the maximum number of\nstatements chunk that can be stored in shared memory.  For each plpgsql\nfunction (or procedure), the whole content is split into chunks of 30\nstatements.  If needed, multiple chunks can be used to store the whole content\nof a single function.  A single chunk is 1704 bytes.  The default value for\nthis GUC is 15000, which should be enough for big projects containing hundreds\nof thousands of statements in plpgsql, and will consume about 24MB of memory.\nIf your project doesn't require that much number of chunks, you can set this\nparameter to a smaller number in order to decrease the memory usage.  The\nminimum value is 50 (which should consume about 83kB of memory), and the\nmaximum value is 100000 (which should consume about 163MB of memory).  Changing\nthis parameter requires a PostgreSQL restart.\n\nThe profiler will also retrieve the query identifier for each instruction that\ncontains an expression or optimizable statement.  Note that this requires\npg_stat_statements, or another similar third-party extension), to be installed.\nThere are some limitations to the query identifier retrieval:\n\n* if a plpgsql expression contains underlying statements, only the top level\n  query identifier will be retrieved\n* the profiler doesn't compute query identifier by itself but relies on\n  external extension, such as pg_stat_statements, for that.  It means that\n  depending on the external extension behavior, you may not be able to see a\n  query identifier for some statements.  That's for instance the case with DDL\n  statements, as pg_stat_statements doesn't expose the query identifier for\n  such queries.\n* a query identifier is retrieved only for instructions containing\n  expressions.  This means that plpgsql_profiler_function_tb() function can\n  report less query identifier than instructions on a single line.\n\nAttention: An update of shared profiles can decrease performance on servers under higher load.\n\nThe profile can be displayed by function `plpgsql_profiler_function_tb`:\n\n    postgres=# select lineno, avg_time, source from plpgsql_profiler_function_tb('fx(int)');\n    ┌────────┬──────────┬───────────────────────────────────────────────────────────────────┐\n    │ lineno │ avg_time │                              source                               │\n    ╞════════╪══════════╪═══════════════════════════════════════════════════════════════════╡\n    │      1 │          │                                                                   │\n    │      2 │          │ declare result int = 0;                                           │\n    │      3 │    0.075 │ begin                                                             │\n    │      4 │    0.202 │   for i in 1..$1 loop                                             │\n    │      5 │    0.005 │     select result + i into result; select result + i into result; │\n    │      6 │          │   end loop;                                                       │\n    │      7 │        0 │   return result;                                                  │\n    │      8 │          │ end;                                                              │\n    └────────┴──────────┴───────────────────────────────────────────────────────────────────┘\n    (9 rows)\n\nThe times in the result are in miliseconds.\n\nThe profile per statements (not per line) can be displayed by function plpgsql_profiler_function_statements_tb:\n\n            CREATE OR REPLACE FUNCTION public.fx1(a integer)\n             RETURNS integer\n             LANGUAGE plpgsql\n    1       AS $function$\n    2       begin\n    3         if a \u003e 10 then\n    4           raise notice 'ahoj';\n    5           return -1;\n    6         else\n    7           raise notice 'nazdar';\n    8           return 1;\n    9         end if;\n    10      end;\n    11      $function$\n\n    postgres=# select stmtid, parent_stmtid, parent_note, lineno, exec_stmts, stmtname\n                 from plpgsql_profiler_function_statements_tb('fx1');\n    ┌────────┬───────────────┬─────────────┬────────┬────────────┬─────────────────┐\n    │ stmtid │ parent_stmtid │ parent_note │ lineno │ exec_stmts │    stmtname     │\n    ╞════════╪═══════════════╪═════════════╪════════╪════════════╪═════════════════╡\n    │      0 │             ∅ │ ∅           │      2 │          0 │ statement block │\n    │      1 │             0 │ body        │      3 │          0 │ IF              │\n    │      2 │             1 │ then body   │      4 │          0 │ RAISE           │\n    │      3 │             1 │ then body   │      5 │          0 │ RETURN          │\n    │      4 │             1 │ else body   │      7 │          0 │ RAISE           │\n    │      5 │             1 │ else body   │      8 │          0 │ RETURN          │\n    └────────┴───────────────┴─────────────┴────────┴────────────┴─────────────────┘\n    (6 rows)\n\nAll stored profiles can be displayed by calling function `plpgsql_profiler_functions_all`:\n\n    postgres=# select * from plpgsql_profiler_functions_all();\n    ┌───────────────────────┬────────────┬────────────┬──────────┬─────────────┬──────────┬──────────┐\n    │        funcoid        │ exec_count │ total_time │ avg_time │ stddev_time │ min_time │ max_time │\n    ╞═══════════════════════╪════════════╪════════════╪══════════╪═════════════╪══════════╪══════════╡\n    │ fxx(double precision) │          1 │       0.01 │     0.01 │        0.00 │     0.01 │     0.01 │\n    └───────────────────────┴────────────┴────────────┴──────────┴─────────────┴──────────┴──────────┘\n    (1 row)\n\n\nThere are two functions for cleaning stored profiles: `plpgsql_profiler_reset_all()` and\n`plpgsql_profiler_reset(regprocedure)`.\n\n## Coverage metrics\n\nplpgsql_check provides two functions:\n\n* `plpgsql_coverage_statements(name)`\n* `plpgsql_coverage_branches(name)`\n\n## Note\n\nThere is another very good PLpgSQL profiler - https://github.com/glynastill/plprofiler\n\nMy extension is designed to be simple for use and practical. Nothing more or less.\n\nplprofiler is more complex. It builds call graphs and from this graph it can create\nflame graph of execution times.\n\nBoth extensions can be used together with the builtin PostgreSQL's feature - tracking functions.\n\n    set track_functions to 'pl';\n    ...\n    select * from pg_stat_user_functions;\n\n# Tracer\n\nplpgsql_check provides a tracing possibility - in this mode you can see notices on\nstart or end functions (terse and default verbosity) and start or end statements\n(verbose verbosity). For default and verbose verbosity the content of function arguments\nis displayed. The content of related variables are displayed when verbosity is verbose.\n\n    postgres=# do $$ begin perform fx(10,null, 'now', e'stěhule'); end; $$;\n    NOTICE:  #0 -\u003e\u003e start of inline_code_block (Oid=0)\n    NOTICE:  #2   -\u003e\u003e start of function fx(integer,integer,date,text) (Oid=16405)\n    NOTICE:  #2        call by inline_code_block line 1 at PERFORM\n    NOTICE:  #2       \"a\" =\u003e '10', \"b\" =\u003e null, \"c\" =\u003e '2020-08-03', \"d\" =\u003e 'stěhule'\n    NOTICE:  #4     -\u003e\u003e start of function fx(integer) (Oid=16404)\n    NOTICE:  #4          call by fx(integer,integer,date,text) line 1 at PERFORM\n    NOTICE:  #4         \"a\" =\u003e '10'\n    NOTICE:  #4     \u003c\u003c- end of function fx (elapsed time=0.098 ms)\n    NOTICE:  #2   \u003c\u003c- end of function fx (elapsed time=0.399 ms)\n    NOTICE:  #0 \u003c\u003c- end of block (elapsed time=0.754 ms)\n\nThe number after `#` is a execution frame counter (this number is related to depth of error context stack).\nIt allows to pair start and end of function. Attention - the initial depth of error context stack can be different\nin dependency on environment (and used protocol).\n\nTracing is enabled by setting `plpgsql_check.tracer` to `on`. Attention - enabling this behaviour\nhas significant negative impact on performance (unlike the profiler). You can set a level for output used by\ntracer `plpgsql_check.tracer_errlevel` (default is `notice`). The output content is limited by length\nspecified by `plpgsql_check.tracer_variable_max_length` configuration variable. The tracer can be activated\nby calling function `plpgsql_check_tracer(true)` and disabled by calling same function with `false` argument\n(or with literals `on`, `off`).\n\nFirst, the usage of tracer should be explicitly enabled by superuser by setting `set plpgsql_check.enable_tracer to on;`\nor `plpgsql_check.enable_tracer to on` in `postgresql.conf`. This is a security safeguard. The tracer shows content of\nplpgsql's variables, and then some security sensitive information can be displayed to an unprivileged user (when he runs\nsecurity definer function). Second, the extension `plpgsql_check` should be loaded. It can be done by execution of some\n`plpgsql_check` function or explicitly by command `load 'plpgsql_check';`. You can use configuration's option\n`shared_preload_libraries`, `local_preload_libraries` or `session_preload_libraries`.\n\nIn terse verbose mode the output is reduced:\n\n    postgres=# set plpgsql_check.tracer_verbosity TO terse;\n    SET\n    postgres=# do $$ begin perform fx(10,null, 'now', e'stěhule'); end; $$;\n    NOTICE:  #0 start of inline code block (oid=0)\n    NOTICE:  #2 start of fx (oid=16405)\n    NOTICE:  #4 start of fx (oid=16404)\n    NOTICE:  #4 end of fx\n    NOTICE:  #2 end of fx\n    NOTICE:  #0 end of inline code block\n\nIn verbose mode the output is extended about statement details:\n\n    postgres=# do $$ begin perform fx(10,null, 'now', e'stěhule'); end; $$;\n    NOTICE:  #0            -\u003e\u003e start of block inline_code_block (oid=0)\n    NOTICE:  #0.1       1  --\u003e start of PERFORM\n    NOTICE:  #2              -\u003e\u003e start of function fx(integer,integer,date,text) (oid=16405)\n    NOTICE:  #2                   call by inline_code_block line 1 at PERFORM\n    NOTICE:  #2                  \"a\" =\u003e '10', \"b\" =\u003e null, \"c\" =\u003e '2020-08-04', \"d\" =\u003e 'stěhule'\n    NOTICE:  #2.1       1    --\u003e start of PERFORM\n    NOTICE:  #2.1                \"a\" =\u003e '10'\n    NOTICE:  #4                -\u003e\u003e start of function fx(integer) (oid=16404)\n    NOTICE:  #4                     call by fx(integer,integer,date,text) line 1 at PERFORM\n    NOTICE:  #4                    \"a\" =\u003e '10'\n    NOTICE:  #4.1       6      --\u003e start of assignment\n    NOTICE:  #4.1                  \"a\" =\u003e '10', \"b\" =\u003e '20'\n    NOTICE:  #4.1              \u003c-- end of assignment (elapsed time=0.076 ms)\n    NOTICE:  #4.1                  \"res\" =\u003e '130'\n    NOTICE:  #4.2       7      --\u003e start of RETURN\n    NOTICE:  #4.2                  \"res\" =\u003e '130'\n    NOTICE:  #4.2              \u003c-- end of RETURN (elapsed time=0.054 ms)\n    NOTICE:  #4                \u003c\u003c- end of function fx (elapsed time=0.373 ms)\n    NOTICE:  #2.1            \u003c-- end of PERFORM (elapsed time=0.589 ms)\n    NOTICE:  #2              \u003c\u003c- end of function fx (elapsed time=0.727 ms)\n    NOTICE:  #0.1          \u003c-- end of PERFORM (elapsed time=1.147 ms)\n    NOTICE:  #0            \u003c\u003c- end of block (elapsed time=1.286 ms)\n\nA special feature of tracer is tracing of the `ASSERT` statement when `plpgsql_check.trace_assert` is `on`. When\n`plpgsql_check.trace_assert_verbosity` is `DEFAULT`, then all function's or procedure's variables are\ndisplayed when assert expression is false. When this configuration is `VERBOSE` then all variables\nfrom all plpgsql frames are displayed. This behaviour is independent on `plpgsql.check_asserts` value.\nIt can be used, although the assertions are disabled in plpgsql runtime.\n\n    postgres=# set plpgsql_check.tracer to off;\n    postgres=# set plpgsql_check.trace_assert_verbosity TO verbose;\n\n    postgres=# do $$ begin perform fx(10,null, 'now', e'stěhule'); end; $$;\n    NOTICE:  #4 PLpgSQL assert expression (false) on line 12 of fx(integer) is false\n    NOTICE:   \"a\" =\u003e '10', \"res\" =\u003e null, \"b\" =\u003e '20'\n    NOTICE:  #2 PL/pgSQL function fx(integer,integer,date,text) line 1 at PERFORM\n    NOTICE:   \"a\" =\u003e '10', \"b\" =\u003e null, \"c\" =\u003e '2020-08-05', \"d\" =\u003e 'stěhule'\n    NOTICE:  #0 PL/pgSQL function inline_code_block line 1 at PERFORM\n    ERROR:  assertion failed\n    CONTEXT:  PL/pgSQL function fx(integer) line 12 at ASSERT\n    SQL statement \"SELECT fx(a)\"\n    PL/pgSQL function fx(integer,integer,date,text) line 1 at PERFORM\n    SQL statement \"SELECT fx(10,null, 'now', e'stěhule')\"\n    PL/pgSQL function inline_code_block line 1 at PERFORM\n\n    postgres=# set plpgsql.check_asserts to off;\n    SET\n    postgres=# do $$ begin perform fx(10,null, 'now', e'stěhule'); end; $$;\n    NOTICE:  #4 PLpgSQL assert expression (false) on line 12 of fx(integer) is false\n    NOTICE:   \"a\" =\u003e '10', \"res\" =\u003e null, \"b\" =\u003e '20'\n    NOTICE:  #2 PL/pgSQL function fx(integer,integer,date,text) line 1 at PERFORM\n    NOTICE:   \"a\" =\u003e '10', \"b\" =\u003e null, \"c\" =\u003e '2020-08-05', \"d\" =\u003e 'stěhule'\n    NOTICE:  #0 PL/pgSQL function inline_code_block line 1 at PERFORM\n    DO\n\nTracer can show usage of subtransaction buffer id (`nxids`). The displayed `tnl` number\nis transaction nesting level number (for plpgsql it depends on deep of blocks with\nexception's handlers).\n\n## Detection of unclosed cursors\n\nPLpgSQL's cursors are just names of SQL cursors. The life cycle of SQL cursors is not\njoined with scope of related plpgsql's cursor variable. SQL cursors are cloased by self\nat transaction end, but for long transaction and too much opened cursors it can be too late.\nIt is better to close cursor explicitly when cursor is not necessary (by CLOSE statement).\nWithout it the significant memory issues are possible.\n\nWhen OPEN statement try to use cursor that is not closed yet, the warning is raised.\nThis feature can be disabled by setting `plpgsql_check.cursors_leaks to off`. This check\nis not active, when routine is called recusively \n\nThe unclosed cursors can be checked immediately when function is finished. This check is\ndisabled by default, and should be enabled by `plpgsql_check.strict_cursors_leaks to on`.\n\nAny unclosed cursor is reported once.\n\n## Using with plugin_debugger\n\nIf you use `plugin_debugger` (plpgsql debugger) together with `plpgsql_check`, then\n`plpgsql_check` should be initialized after `plugin_debugger` (because `plugin_debugger`\ndoesn't support the sharing of PL/pgSQL's debug API). For example (`postgresql.conf`):\n\n    shared_preload_libraries = 'plugin_debugger,plpgsql,plpgsql_check'\n\n\n## Attention - SECURITY\n\nTracer prints content of variables or function arguments. For security definer function, this\ncontent can hold security sensitive data. This is reason why tracer is disabled by default and should\nbe enabled only with super user rights `plpgsql_check.enable_tracer`.\n\n# Pragma\n\nYou can configure plpgsql_check behaviour inside a checked function with \"pragma\" function. This\nis a analogy of PL/SQL or ADA language of PRAGMA feature. PLpgSQL doesn't support PRAGMA, but\nplpgsql_check detects function named `plpgsql_check_pragma` and takes options from the parameters of\nthis function. These plpgsql_check options are valid to the end of this group of statements.\n\n    CREATE OR REPLACE FUNCTION test()\n    RETURNS void AS $$\n    BEGIN\n      ...\n      -- for following statements disable check\n      PERFORM plpgsql_check_pragma('disable:check');\n      ...\n      -- enable check again\n      PERFORM plpgsql_check_pragma('enable:check');\n      ...\n    END;\n    $$ LANGUAGE plpgsql;\n\nThe function `plpgsql_check_pragma` is immutable function that returns one. It is defined\nby `plpgsql_check` extension. You can declare alternative `plpgsql_check_pragma` function\nlike:\n\n    CREATE OR REPLACE FUNCTION plpgsql_check_pragma(VARIADIC args[])\n    RETURNS int AS $$\n    SELECT 1\n    $$ LANGUAGE sql IMMUTABLE;\n\nUsing pragma function in declaration part of top block sets options on function level too.\n\n    CREATE OR REPLACE FUNCTION test()\n    RETURNS void AS $$\n    DECLARE\n      aux int := plpgsql_check_pragma('disable:extra_warnings');\n      ...\n\n\nShorter syntax for pragma is supported too:\n\n    CREATE OR REPLACE FUNCTION test()\n    RETURNS void AS $$\n    DECLARE r record;\n    BEGIN\n      PERFORM 'PRAGMA:TYPE:r (a int, b int)';\n      PERFORM 'PRAGMA:TABLE: x (like pg_class)';\n      ...\n\n## Supported pragmas\n\n* `echo:str` - print string (for testing). Inside string, there can be used \"variables\": @@id, @@name, @@signature\n\n* `status:check`,`status:tracer`, `status:other_warnings`, `status:performance_warnings`, `status:extra_warnings`,`status:security_warnings`\n  This outputs the current value (e.g. other_warnings enabled)\n\n* `enable:check`,`enable:tracer`, `enable:other_warnings`, `enable:performance_warnings`, `enable:extra_warnings`,`enable:security_warnings`\n\n* `disable:check`,`disable:tracer`, `disable:other_warnings`, `disable:performance_warnings`, `disable:extra_warnings`,`disable:security_warnings`\n  This can be used to disable the Hint in returning from an anyelement function.  Just put the pragma before the RETURN statement.\n  \n* `type:varname typename` or `type:varname (fieldname type, ...)` - set type to variable of record type\n\n* `table: name (column_name type, ...)` or `table: name (like tablename)` - create ephemeral temporary table (if you want to specify schema, then only `pg_temp` schema is allowed.\n\n* `sequence: name` - create ephemeral temporary sequence\n\n* `assert-schema: varname` - check-time assertation - ensure so schema specified by variable is valid\n\n* `assert-table: [ varname_schema, ] , varname` - ensure so table name specified by variables (by constant tracing) is valid\n\n* `assert-column: [varname_schema, ], varname_table , varname` - ensure so column spefified by variables is valid\n\nPragmas `enable:tracer` and `disable:tracer`are active for Postgres 12 and higher\n\n# Update\n\nplpgsql_check doesn't support update (of plpgsql_check). You should to drop this\nbefore install new version of this extension.\n\n# Compilation\n\nYou need a development environment for PostgreSQL extensions:\n\n    make clean\n    make install\n\nresult:\n\n    [pavel@localhost plpgsql_check]$ make USE_PGXS=1 clean\n    rm -f plpgsql_check.so   libplpgsql_check.a  libplpgsql_check.pc\n    rm -f plpgsql_check.o\n    rm -rf results/ regression.diffs regression.out tmp_check/ log/\n    [pavel@localhost plpgsql_check]$ make USE_PGXS=1 all\n    clang -O2 -Wall -Wmissing-prototypes -Wpointer-arith -Wdeclaration-after-statement -Wendif-labels -Wmissing-format-attribute -Wformat-security -fno-strict-aliasing -fwrapv -fpic -I/usr/local/pgsql/lib/pgxs/src/makefiles/../../src/pl/plpgsql/src -I. -I./ -I/usr/local/pgsql/include/server -I/usr/local/pgsql/include/internal -D_GNU_SOURCE   -c -o plpgsql_check.o plpgsql_check.c\n    clang -O2 -Wall -Wmissing-prototypes -Wpointer-arith -Wdeclaration-after-statement -Wendif-labels -Wmissing-format-attribute -Wformat-security -fno-strict-aliasing -fwrapv -fpic -I/usr/local/pgsql/lib/pgxs/src/makefiles/../../src/pl/plpgsql/src -shared -o plpgsql_check.so plpgsql_check.o -L/usr/local/pgsql/lib -Wl,--as-needed -Wl,-rpath,'/usr/local/pgsql/lib',--enable-new-dtags  \n    [pavel@localhost plpgsql_check]$ su root\n    Password: *******\n    [root@localhost plpgsql_check]# make USE_PGXS=1 install\n    /usr/bin/mkdir -p '/usr/local/pgsql/lib'\n    /usr/bin/mkdir -p '/usr/local/pgsql/share/extension'\n    /usr/bin/mkdir -p '/usr/local/pgsql/share/extension'\n    /usr/bin/install -c -m 755  plpgsql_check.so '/usr/local/pgsql/lib/plpgsql_check.so'\n    /usr/bin/install -c -m 644 plpgsql_check.control '/usr/local/pgsql/share/extension/'\n    /usr/bin/install -c -m 644 plpgsql_check--0.9.sql '/usr/local/pgsql/share/extension/'\n    [root@localhost plpgsql_check]# exit\n    [pavel@localhost plpgsql_check]$ make USE_PGXS=1 installcheck\n    /usr/local/pgsql/lib/pgxs/src/makefiles/../../src/test/regress/pg_regress --inputdir=./ --psqldir='/usr/local/pgsql/bin'    --dbname=pl_regression --load-language=plpgsql --dbname=contrib_regression plpgsql_check_passive plpgsql_check_active plpgsql_check_active-9.5\n    (using postmaster on Unix socket, default port)\n    ============== dropping database \"contrib_regression\" ==============\n    DROP DATABASE\n    ============== creating database \"contrib_regression\" ==============\n    CREATE DATABASE\n    ALTER DATABASE\n    ============== installing plpgsql                     ==============\n    CREATE LANGUAGE\n    ============== running regression test queries        ==============\n    test plpgsql_check_passive    ... ok\n    test plpgsql_check_active     ... ok\n    test plpgsql_check_active-9.5 ... ok\n    \n    =====================\n     All 3 tests passed. \n    =====================\n\n## Compilation for PostgresPro\n\n`plpgsql_check` requires some unpublished patches to successufully compiled and used with PostgresPro. Use\n`plpgsql_check` from PostgresPro repository.\n\n## Compilation on Ubuntu\n\nSometimes successful compilation can require libicu-dev package (PostgreSQL 10 and higher - when pg was compiled with\nICU support)\n\n    sudo apt install libicu-dev\n\n## Compilation plpgsql_check on Windows\n\nYou can check precompiled dll libraries http://okbob.blogspot.cz/2015/02/plpgsqlcheck-is-available-for-microsoft.html,\nhttp://okbob.blogspot.com/2023/10/compiled-dll-of-plpgsqlcheck-254-and.html\n\nor compile by self:\n\n1. Download and install PostgreSQL for Win32 from http://www.enterprisedb.com\n2. Download and install Microsoft Visual C++ Express\n3. Read tutorial http://blog.2ndquadrant.com/compiling-postgresql-extensions-visual-studio-windows\n4. Build plpgsql_check.dll\n5. Install plugin\n  1. copy `plpgsql_check.dll` to `PostgreSQL\\14\\lib`\n  2. copy `plpgsql_check.control` and `plpgsql_check--2.1.sql` to `PostgreSQL\\14\\share\\extension`\n\n## Meson build\n\n1. `meson setup build`\n2. `cd build`\n3. `ninja`\n4. `ninja install`\n5. optionaly `ninja bindist`\n\n## Checked on\n\n* gcc on Linux (against all supported PostgreSQL)\n* clang 3.4 on Linux (against PostgreSQL 10)\n* for success regress tests the PostgreSQL 10 or higher is required\n\nCompilation against PostgreSQL 10 requires libICU!\n\n# Licence\n\nCopyright (c) Pavel Stehule (pavel.stehule@gmail.com)\n\n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included in\n all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n THE SOFTWARE.\n\n# Note\n\nIf you like it, send a postcard to address\n\n    Pavel Stehule\n    Skalice 12\n    256 01 Benesov u Prahy\n    Czech Republic\n\n\nI invite any questions, comments, bug reports, patches on mail address pavel.stehule@gmail.com\n","funding_links":[],"categories":["C","Compiled list","Extensions"],"sub_categories":["plv8:"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fokbob%2Fplpgsql_check","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fokbob%2Fplpgsql_check","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fokbob%2Fplpgsql_check/lists"}