#!/bin/bash # Reproduces every factual claim in # https://www.heatware.net/postgresql/stored-procedures-guide/ # # Creates ONE throwaway PostgreSQL cluster in a temp directory on port 55498, runs every # statement and error message quoted in the article against it, then stops the cluster and # deletes the directory. It does not touch any existing PostgreSQL installation, database, # data directory, role or configuration file. No DROP is issued against anything you own. # # Requires: initdb, pg_ctl, psql on PATH (PostgreSQL 11 or newer -- CREATE PROCEDURE # arrived in 11, and procedure transaction control with it). # Runtime: about 20 seconds. # Usage: bash verify-stored-procedures-guide.sh # # Tally convention: PASS/FAIL/SKIP count things this script EXECUTED. CONTENT counts # regression greps of the published article, which prove nothing on their own and are # skipped entirely when the article is not sitting next to the script. set -u PORT=55498 TMP="$(mktemp -d -t hw_w12_proc)" SOCK="$(mktemp -d /tmp/hw_w12_s.XXXXXX)" ART_CANDIDATES="stored-procedures-guide.html ./stored-procedures-guide.html" cleanup() { pg_ctl -D "$TMP/d" stop -m immediate >/dev/null 2>&1 rm -rf "$TMP" "$SOCK" } trap cleanup EXIT PASSES=0; FAILS=0; SKIPS=0; CONTENT=0 pass() { PASSES=$((PASSES+1)); printf 'PASS %s\n' "$1"; } fail() { FAILS=$((FAILS+1)); printf 'FAIL %s\n expected: %s\n actual: %s\n' "$1" "$2" "$3"; } skip() { SKIPS=$((SKIPS+1)); printf 'SKIP %s (needs %s)\n' "$1" "$2"; } cpass() { CONTENT=$((CONTENT+1)); printf 'CONTENT %s\n' "$1"; } check() { [ "$2" = "$3" ] && pass "$1" || fail "$1" "$2" "$3"; } contains(){ case "$3" in *"$2"*) pass "$1";; *) fail "$1" "text containing: $2" "$3";; esac; } for bin in initdb pg_ctl psql; do command -v "$bin" >/dev/null 2>&1 || { echo "SKIP everything (needs $bin on PATH)" echo; echo "PASS=0 FAIL=0 SKIP=1 CONTENT=0"; exit 0; } done initdb -D "$TMP/d" -U postgres --no-locale -E UTF8 >"$TMP/initdb.log" 2>&1 || { echo "SKIP everything (initdb failed; see $TMP/initdb.log)" echo; echo "PASS=0 FAIL=0 SKIP=1 CONTENT=0"; exit 0; } pg_ctl -D "$TMP/d" -o "-p $PORT -k $SOCK -c listen_addresses=127.0.0.1" -l "$TMP/pg.log" start >/dev/null 2>&1 UP=no for _ in 1 2 3 4 5 6 7 8 9 10; do psql -h 127.0.0.1 -p "$PORT" -U postgres -X -At -c 'SELECT 1' >/dev/null 2>&1 && { UP=yes; break; } sleep 1 done [ "$UP" = yes ] || { echo "SKIP everything (throwaway cluster did not start on port $PORT)" echo; echo "PASS=0 FAIL=0 SKIP=1 CONTENT=0"; exit 0; } H="-h 127.0.0.1 -p $PORT -U postgres -X" q() { psql $H -At -c "$1" 2>&1; } qf() { psql $H -At -f "$1" 2>&1; } SRV="$(q 'SELECT version();')" echo "server: $SRV" MAJ="$(q 'SHOW server_version_num;')" echo if [ "${MAJ:-0}" -lt 110000 ] 2>/dev/null; then echo "SKIP everything (CREATE PROCEDURE requires PostgreSQL 11+; this server is $MAJ)" echo; echo "PASS=0 FAIL=0 SKIP=1 CONTENT=0"; exit 0 fi q "CREATE TABLE t (id int primary key, n text);" >/dev/null q "CREATE TABLE t3 (id int);" >/dev/null # --------------------------------------------------------------------------- # 1. A FUNCTION cannot commit. # --------------------------------------------------------------------------- q "CREATE FUNCTION f_commit() RETURNS void LANGUAGE plpgsql AS \$\$ BEGIN INSERT INTO t VALUES (1,'a'); COMMIT; END \$\$;" >/dev/null OUT="$(q 'SELECT f_commit();')" contains "1a a FUNCTION that runs COMMIT fails" "invalid transaction termination" "$OUT" contains "1b ...and the error names the COMMIT line" "at COMMIT" "$OUT" check "1c the function's INSERT did not survive" "0" "$(q 'SELECT count(*) FROM t;')" # --------------------------------------------------------------------------- # 2. A PROCEDURE can commit and roll back inside its own body. # --------------------------------------------------------------------------- q "CREATE PROCEDURE p_commit() LANGUAGE plpgsql AS \$\$ BEGIN INSERT INTO t VALUES (2,'b'); COMMIT; INSERT INTO t VALUES (3,'c'); ROLLBACK; INSERT INTO t VALUES (4,'d'); COMMIT; END \$\$;" >/dev/null OUT="$(q 'CALL p_commit();')" check "2a CALL of a committing procedure succeeds" "CALL" "$OUT" check "2b the committed rows are 2 and 4" "2,4" "$(q "SELECT string_agg(id::text, ',' ORDER BY id) FROM t;")" check "2c the rolled-back row 3 is absent" "0" "$(q 'SELECT count(*) FROM t WHERE id = 3;')" # --------------------------------------------------------------------------- # 3. ...but not when the client already opened a transaction. # --------------------------------------------------------------------------- q "CREATE PROCEDURE p2() LANGUAGE plpgsql AS \$\$ BEGIN INSERT INTO t3 VALUES (99); COMMIT; END \$\$;" >/dev/null printf 'BEGIN;\nCALL p2();\nCOMMIT;\n' > "$TMP/tx.sql" OUT="$(qf "$TMP/tx.sql")" contains "3a CALL inside BEGIN...COMMIT gets the same error" "invalid transaction termination" "$OUT" check "3b nothing was written by the aborted CALL" "0" "$(q 'SELECT count(*) FROM t3;')" # --------------------------------------------------------------------------- # 4. An exception handler opens a subtransaction, which also blocks COMMIT. # --------------------------------------------------------------------------- q "CREATE PROCEDURE p5() LANGUAGE plpgsql AS \$\$ BEGIN BEGIN INSERT INTO t3 VALUES (9); COMMIT; EXCEPTION WHEN division_by_zero THEN RAISE NOTICE 'nope'; END; END \$\$;" >/dev/null contains "4a COMMIT inside an EXCEPTION block is refused" "cannot commit while a subtransaction is active" "$(q 'CALL p5();')" # --------------------------------------------------------------------------- # 5. Procedures have no RETURNS; output is via INOUT; they are not selectable. # --------------------------------------------------------------------------- OUT="$(q "CREATE PROCEDURE p_ret() RETURNS void LANGUAGE plpgsql AS \$\$ BEGIN END \$\$;")" contains "5a CREATE PROCEDURE ... RETURNS is a syntax error" "syntax error at or near" "$OUT" q "CREATE PROCEDURE p_sum(IN a int, IN b int, INOUT total int DEFAULT NULL) LANGUAGE plpgsql AS \$\$ BEGIN total := a + b; END \$\$;" >/dev/null check "5b an INOUT parameter carries the result out" "5" "$(q 'CALL p_sum(2,3);')" OUT="$(q 'SELECT p_sum(2,3);')" contains "5c SELECT on a procedure is refused" "is a procedure" "$OUT" contains "5d ...and PostgreSQL points you at CALL" "use CALL" "$OUT" # --------------------------------------------------------------------------- # 6. prokind distinguishes them. # --------------------------------------------------------------------------- check "6a pg_proc.prokind is 'f' for the function" "f" "$(q "SELECT prokind FROM pg_proc WHERE proname='f_commit';")" check "6b pg_proc.prokind is 'p' for the procedure" "p" "$(q "SELECT prokind FROM pg_proc WHERE proname='p_commit';")" # --------------------------------------------------------------------------- # 7. Transaction control costs you atomicity. # --------------------------------------------------------------------------- q "CREATE PROCEDURE p3() LANGUAGE plpgsql AS \$\$ BEGIN INSERT INTO t3 VALUES (1); COMMIT; INSERT INTO t3 VALUES (2); RAISE EXCEPTION 'boom'; END \$\$;" >/dev/null OUT="$(q 'CALL p3();')" contains "7a the procedure raises after its COMMIT" "boom" "$OUT" check "7b work before the COMMIT survived the error" "1" "$(q "SELECT string_agg(id::text, ',' ORDER BY id) FROM t3;")" # --------------------------------------------------------------------------- # 8. PL/pgSQL bodies are not compiled at CREATE time. # --------------------------------------------------------------------------- OUT="$(q "CREATE FUNCTION f_bad() RETURNS int LANGUAGE plpgsql AS \$\$ BEGIN RETURN (SELECT x FROM table_that_does_not_exist); END \$\$;")" check "8a a body referencing a missing table is accepted at CREATE" "CREATE FUNCTION" "$OUT" contains "8b ...and only fails when it is called" "does not exist" "$(q 'SELECT f_bad();')" # --------------------------------------------------------------------------- # 9. The old page's own example: parameter name shadowing a column. # --------------------------------------------------------------------------- q "CREATE TABLE payments(order_id int, status text); INSERT INTO payments VALUES (1,'pending'),(2,'pending'),(3,'pending');" >/dev/null q "CREATE FUNCTION pay(order_id INT) RETURNS void LANGUAGE plpgsql AS \$\$ BEGIN UPDATE payments SET status = 'confirmed' WHERE order_id = order_id; END \$\$;" >/dev/null OUT="$(q 'SELECT pay(1);')" contains "9a the ambiguous reference is rejected, not guessed" "column reference \"order_id\" is ambiguous" "$OUT" check "9b no payment row was modified" "0" "$(q "SELECT count(*) FROM payments WHERE status='confirmed';")" # --------------------------------------------------------------------------- # 10. Round trips, measured. 2000 statements rather than the article's 5000 so # this stays quick; the article's own figures are printed for comparison. # --------------------------------------------------------------------------- N=2000 q "CREATE TABLE bench(id int); CREATE PROCEDURE p_bench(n int) LANGUAGE plpgsql AS \$\$ BEGIN FOR i IN 1..n LOOP INSERT INTO bench VALUES (i); END LOOP; END \$\$;" >/dev/null { echo "BEGIN;"; i=1; while [ $i -le $N ]; do echo "INSERT INTO bench VALUES ($i);"; i=$((i+1)); done; echo "COMMIT;"; } > "$TMP/many.sql" now() { python3 -c 'import time;print(time.time())' 2>/dev/null || date +%s; } S=$(now); psql $H -q -f "$TMP/many.sql" >/dev/null 2>&1; E=$(now) A=$(awk "BEGIN{printf \"%.3f\", $E-$S}") q "DELETE FROM bench WHERE id IS NOT NULL OR id IS NULL;" >/dev/null S=$(now); psql $H -q -c "CALL p_bench($N);" >/dev/null 2>&1; E=$(now) B=$(awk "BEGIN{printf \"%.3f\", $E-$S}") S=$(now); psql $H -q -c "SELECT 1" >/dev/null 2>&1; E=$(now) C=$(awk "BEGIN{printf \"%.3f\", $E-$S}") echo " measured here: $N separate statements = ${A}s | one CALL = ${B}s | psql baseline = ${C}s" echo " article quoted (5000 statements, different run): 0.214-0.255s vs 0.056-0.059s, baseline 0.050s" check "10a all $N rows arrived via the single CALL" "$N" "$(q 'SELECT count(*) FROM bench;')" if awk "BEGIN{exit !($B < $A)}"; then pass "10b one CALL beat $N round trips (${B}s < ${A}s)" else fail "10b one CALL beat $N round trips" "CALL faster" "statements=${A}s CALL=${B}s" fi # --------------------------------------------------------------------------- # CONTENT: regression greps of the published article, if it is next to us. # These assert nothing about PostgreSQL; they only catch the article drifting # away from the behaviour above. Counted separately for that reason. # --------------------------------------------------------------------------- echo ART="" for c in $ART_CANDIDATES; do [ -f "$c" ] && { ART="$c"; break; }; done if [ -z "$ART" ]; then echo "CONTENT checks skipped (stored-procedures-guide.html is not in this directory --" echo " that is expected when you downloaded this script on its own)" else for s in "invalid transaction termination" \ "cannot commit while a subtransaction is active" \ "is a procedure" \ "column reference \"order_id\" is ambiguous" \ "INOUT total int"; do if grep -qF "$s" "$ART"; then cpass "article still contains: $s" else fail "article no longer contains: $s" "present" "absent"; fi done if grep -qF 'Nothing was precompiled' "$ART" && grep -qF 'it does not' "$ART"; then cpass "article still corrects, rather than repeats, the precompilation and autonomous-transaction claims" else fail "article lost its corrections of 'precompiled' / 'autonomous transactions'" "present" "absent" fi fi echo echo "PASS=$PASSES FAIL=$FAILS SKIP=$SKIPS CONTENT=$CONTENT" [ "$FAILS" -eq 0 ]