A call such as SELECT * FROM sd_api.read_marker(); can look reassuring. The function name is schema-qualified. The returned marker is plausible. Inside a SECURITY DEFINER function, current_user reports the expected owner. Yet none of those facts, individually or together, proves that an unqualified quota reference inside the PL/pgSQL body resolved to sd_data.quota.
That distinction matters because PostgreSQL resolves unqualified relation names through search_path, with special treatment for the session temporary schema. PostgreSQL's own CREATE FUNCTION guidance explicitly warns that a security-definer function can be diverted to a temporary table when its path is not made safe; the search_path documentation separately specifies that an omitted pg_temp is implicitly searched first for relations and types.
This article defines a bounded qualification for that exact problem. The declared baseline is PostgreSQL 18.7 and psql 18.7; PostgreSQL 18.7 was released on November 12, 2026. The fixture uses a non-superuser function owner, real unprivileged caller connections, harmless same-shaped marker tables, independent relation-OID oracles, and tableoid returned from the function.
Everything below is EXPECTED / NOT EXECUTED. No fabricated terminal transcript is presented. PostgreSQL 18 documentation and the cited Refonte Learning program material were checked November 28, 2026. A later execution must record its actual server and client builds and retain any disagreement with these expectations rather than rewriting the oracle after seeing results.
Define the relation-binding acceptance contract
The application contract is deliberately narrow: the no-argument function sd_api.read_marker() is expected to read exactly row id = 1 from sd_data.quota. That row must identify itself with literal marker TRUSTED, and its tableoid must equal an independently recorded OID for the qualified relation sd_data.quota. PostgreSQL documents tableoid as the OID of the table containing a returned row and notes that it can be joined to pg_class to identify that table.
The same invocation must execute with current_user = sd_owner, while the authenticated caller remains session_user = sd_caller. The caller must be admitted to execute the function but denied direct SELECT on the trusted table. sd_outsider must be able to connect and resolve the API schema yet receive 42501 when actually attempting to execute the function. PostgreSQL distinguishes EXECUTE on functions, USAGE/CREATE on schemas, SELECT on tables and TEMPORARY on databases as separate privileges.
That creates three release outcomes. ACCEPT means the entire declared bounded contract is observed under the required baseline and all ten cases plus admission probes are complete. REPAIR means the configuration or privileges demonstrably allow the function to use a wrong source relation. HOLD means the required table is absent, the environment is outside the baseline, a prerequisite is missing, or evidence is incomplete.
A negative control is evidence about a boundary; it is never approval of an unsafe configuration. The function should also appear in the application's explicit dependency inventory and migration plan, a concern adjacent to database integration and migration planning, rather than being treated as an isolated SQL object.
Separate caller identity, function authority and admission
session_user and current_user answer different questions. PostgreSQL defines session_user as the role that initiated the connection, while current_user is the effective identity used for permission checks; current_user changes while a SECURITY DEFINER function executes. Therefore the expected identity sequence is:
Before the call: session_user = sd_caller, current_user = sd_caller.
Inside the function: session_user = sd_caller, current_user = sd_owner.
After return: both are again sd_caller.
The runtime identity principle is similar to the need to validate the actual application role, but this qualification asks a different question. A correct effective role does not prove a correct relation.
SECURITY DEFINER supplies the owner's database authority, not superuser authority. The fixture therefore makes sd_owner explicitly NOSUPERUSER, NOCREATEDB, NOCREATEROLE, NOREPLICATION and NOBYPASSRLS. The owner can read only relations for which its ownership or grants actually allow access. PostgreSQL's CREATE FUNCTION documentation states that security-definer functions execute with the privileges of their owner.
Admission is independent of that authority. sd_caller requires schema USAGE on sd_api and EXECUTE on sd_api.read_marker(). It does not receive direct table SELECT. sd_outsider receives CONNECT to the case database and USAGE on sd_api, but not function EXECUTE. Because PostgreSQL grants EXECUTE on new functions to PUBLIC by default, the fixture creates the function and revokes that default before granting the caller inside the same transaction, as PostgreSQL specifically recommends for security-definer functions.
This is a runtime lookup test, not a repetition of creation-time ACL-template analysis. Existing object permissions are normalized explicitly so a default privilege inherited from the bootstrap environment cannot silently satisfy a prerequisite.
Build the owned fixture before the first call
Use a fresh disposable PostgreSQL instance and exactly ten databases:
sd_case_r01
sd_case_r02
sd_case_r03
sd_case_r04
sd_case_r05
sd_case_r06
sd_case_r07
sd_case_r08
sd_case_r09
sd_case_r10Roles are cluster-wide and created once. The following bootstrap is EXPECTED / NOT EXECUTED and assumes connection as an authorized local provisioning role capable of role and database creation. Credentials are supplied through normal local PostgreSQL connection mechanisms, never embedded here.
CREATE ROLE sd_owner
NOLOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE
NOREPLICATION NOBYPASSRLS;
CREATE ROLE sd_caller
LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE
NOREPLICATION NOBYPASSRLS;
CREATE ROLE sd_outsider
LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE
NOREPLICATION NOBYPASSRLS;For each named database, provision it with a known owner and normalize database-level defaults:
CREATE DATABASE sd_case_r01 OWNER sd_owner;
REVOKE ALL ON DATABASE sd_case_r01 FROM PUBLIC;
GRANT CONNECT, TEMPORARY ON DATABASE sd_case_r01 TO sd_caller;
GRANT CONNECT ON DATABASE sd_case_r01 TO sd_outsider;
GRANT TEMPORARY ON DATABASE sd_case_r01 TO sd_owner;Repeat the same database grants for R02 through R10. TEMPORARY is the database privilege that allows temporary-table creation.
Inside every case database, the provisioning session creates two trusted schemas while executing as sd_owner, then creates the caller-owned comparison schema while executing as sd_caller:
BEGIN;
SET LOCAL ROLE sd_owner;
CREATE SCHEMA sd_api AUTHORIZATION sd_owner;
CREATE SCHEMA sd_data AUTHORIZATION sd_owner;
REVOKE ALL ON SCHEMA sd_api, sd_data FROM PUBLIC;
GRANT USAGE ON SCHEMA sd_api, sd_data TO sd_caller;
GRANT USAGE ON SCHEMA sd_api TO sd_outsider;
RESET ROLE;
SET LOCAL ROLE sd_caller;
CREATE SCHEMA sd_caller_space AUTHORIZATION sd_caller;
REVOKE ALL ON SCHEMA sd_caller_space FROM PUBLIC;
GRANT USAGE ON SCHEMA sd_caller_space TO sd_owner;
COMMIT;PostgreSQL requires USAGE to access objects through another schema and CREATE to create objects there; that separation is central to the fixture.
Where present, the trusted relation is created as sd_owner:
CREATE TABLE sd_data.quota (
id integer PRIMARY KEY,
marker text NOT NULL
);
INSERT INTO sd_data.quota(id, marker)
VALUES (1, 'TRUSTED');Where a permanent shadow is declared, sd_caller creates:
CREATE TABLE sd_caller_space.quota (
id integer PRIMARY KEY,
marker text NOT NULL
);
INSERT INTO sd_caller_space.quota(id, marker)
VALUES (1, 'CALLER');
GRANT SELECT ON sd_caller_space.quota TO sd_owner;R08 and R09 deliberately omit sd_data.quota. No case admits RLS, partitions, views, sequences, additional overloads or other same-named fixture objects.
Make the permission prerequisites observable
Every lookup case is valid only when the permissions needed to expose the intended resolution behavior have been admitted independently. A failure caused by sd_owner lacking SELECT on a shadow is not proof that PostgreSQL chose the trusted table; it can merely mask the lookup.
Record the expected privileges with catalog-backed checks:
SELECT
pg_catalog.has_schema_privilege(
'sd_caller', 'sd_api', 'USAGE'
) AS caller_api_usage,
pg_catalog.has_schema_privilege(
'sd_caller', 'sd_data', 'USAGE'
) AS caller_data_usage,
pg_catalog.has_schema_privilege(
'sd_caller', 'sd_data', 'CREATE'
) AS caller_data_create,
pg_catalog.has_schema_privilege(
'sd_owner', 'sd_caller_space', 'USAGE'
) AS owner_shadow_schema_usage;Expected values are true, true, false, true. Privilege inquiry functions are documented as evaluating effective privileges, which means role memberships and PUBLIC grants must be considered rather than reading only one ACL array.
The caller must create any temporary shadow in the same fresh backend that will make the first function call:
CREATE TEMP TABLE quota (
id integer PRIMARY KEY,
marker text NOT NULL
);
INSERT INTO pg_temp.quota(id, marker)
VALUES (1, 'TEMP');
GRANT SELECT ON pg_temp.quota TO sd_owner;The test deliberately grants the definer access to each shadow. Otherwise an insufficient_privilege error could replace the relation-resolution evidence the case is designed to obtain.
Declare the ten expected cases before execution
The oracle is fixed before any call. Every row in this table is EXPECTED / NOT EXECUTED. In every case the tested statement is exactly:
SELECT * FROM sd_api.read_marker();“None” means no function-local SET search_path clause. The trusted table exists except in R08 and R09. Every declared shadow is created and granted before that fresh caller backend's first function invocation.
ID | Body relation | Function search_path | Caller search_path | Shadows | Expected source |
R01 | quota | None | sd_data, pg_temp | None | TRUSTED |
R02 | quota | None | sd_caller_space, sd_data, pg_temp | Permanent | CALLER |
R03 | quota | sd_data | sd_caller_space, sd_data, pg_temp | Permanent + temporary | TEMP |
R04 | quota | pg_catalog, pg_temp, sd_data | sd_data, pg_temp | Temporary | TEMP |
R05 | quota | pg_catalog, sd_data, pg_temp | sd_caller_space, sd_data, pg_temp | Permanent + temporary | TRUSTED |
R06 | quota | pg_catalog, sd_caller_space, sd_data, pg_temp | sd_data, pg_temp | Permanent + temporary | CALLER |
R07 | sd_data.quota | None | sd_caller_space, pg_temp, sd_data | Permanent + temporary | TRUSTED |
R08 | quota | pg_catalog, sd_data, pg_temp | sd_caller_space, sd_data, pg_temp | Permanent + temporary; trusted absent | TEMP |
R09 | sd_data.quota | pg_catalog, sd_data, pg_temp | sd_caller_space, sd_data, pg_temp | Permanent + temporary; trusted absent | ERROR 42P01 |
R10 | sd_data.quota | pg_catalog, sd_data, pg_temp | sd_caller_space, pg_temp, sd_data | Permanent + temporary | TRUSTED |
The documentation supplies the resolution rules behind these predictions. Unqualified relation names take the first matching relation in the effective path. A temporary schema that exists but is omitted from search_path is implicitly searched first for relation and type names; when pg_temp is listed explicitly, its listed position controls its priority. Nonexistent or unusable path schemas are ignored.
The case ledger therefore distinguishes three evidence classes:
Evidence class | Meaning here |
DOCUMENTED CONTRACT | PostgreSQL manual behavior for SECURITY DEFINER, search_path, pg_temp, privileges, PL/pgSQL first execution and tableoid. |
DERIVED EXPECTATION | R01–R10 outcomes inferred before execution by applying those documented rules to this fixture. |
OBSERVED RESULT | Reserved for a later real run; none is supplied by this article. |
R08 and R09 deserve particular discipline. Their expected fallback and expected failure are derived predictions, not claims that such output has been observed.
Keep expected source identity independent of returned values
For every nonerror case, expect exactly one row. Its expected literal marker is the source label, and effective_role is sd_owner. But the acceptance oracle must not derive the expected OID from what the function returns.
For permanent relations, record the qualified identity before invocation:
SELECT
c.oid,
n.nspname,
c.relname,
c.relowner,
c.relpersistence
FROM pg_catalog.pg_class AS c
JOIN pg_catalog.pg_namespace AS n
ON n.oid OPERATOR(pg_catalog.=) c.relnamespace
WHERE n.nspname OPERATOR(pg_catalog.=) 'sd_data'
AND c.relname OPERATOR(pg_catalog.=) 'quota';Record the caller-owned counterpart independently in the same way with n.nspname = 'sd_caller_space'.
For the temporary relation, use the backend's temporary namespace rather than an unqualified lookup:
SELECT
c.oid,
n.nspname,
c.relname,
c.relowner,
c.relpersistence
FROM pg_catalog.pg_class AS c
JOIN pg_catalog.pg_namespace AS n
ON n.oid OPERATOR(pg_catalog.=) c.relnamespace
WHERE n.oid OPERATOR(pg_catalog.=) pg_catalog.pg_my_temp_schema()
AND c.relname OPERATOR(pg_catalog.=) 'quota';pg_my_temp_schema() returns the current session's temporary-schema OID, or zero when the session has no temporary schema. R09 expects 42P01, PostgreSQL's undefined_table SQLSTATE, specifically while resolving the required qualified body reference.
Record the function and its actual source relation
R10 is the reviewed template. It is independently authored and EXPECTED / NOT EXECUTED:
CREATE FUNCTION sd_api.read_marker()
RETURNS TABLE (
source_oid pg_catalog.oid,
source_marker pg_catalog.text,
effective_role pg_catalog.name,
active_path pg_catalog.text,
resolved_path pg_catalog.name[]
)
LANGUAGE plpgsql SECURITY DEFINER PARALLEL UNSAFE
SET search_path = pg_catalog, sd_data, pg_temp
AS $body$
BEGIN
RETURN QUERY
SELECT q.tableoid, q.marker, current_user,
pg_catalog.current_setting('search_path'),
pg_catalog.current_schemas(true)
FROM sd_data.quota AS q
WHERE q.id OPERATOR(pg_catalog.=) 1;
END;
$body$;Only two dimensions vary among cases: the body relation is either quota or sd_data.quota, and the function receives the exact path shown in the manifest or no function-local path at all. There are no argument overloads and no body-level SET commands.
A function-level SET applies the configuration parameter on entry and restores its prior value on function exit. PostgreSQL also notes that an ordinary SET issued in the body could override that restoration behavior; this fixture contains no such command.
Create each function while acting as sd_owner, then revoke default execution and grant only sd_caller, all within one transaction:
BEGIN;
SET LOCAL ROLE sd_owner;
-- CREATE FUNCTION variant for this manifest row appears here.
REVOKE ALL ON FUNCTION sd_api.read_marker() FROM PUBLIC;
GRANT EXECUTE ON FUNCTION sd_api.read_marker() TO sd_caller;
COMMIT;Before invocation, inspect the exact no-argument function:
SELECT
n.nspname AS function_schema,
p.proname,
pg_catalog.pg_get_userbyid(p.proowner) AS owner_name,
l.lanname AS language_name,
p.prosecdef,
p.proconfig,
p.proacl,
pg_catalog.pg_get_functiondef(p.oid) AS reconstructed_definition
FROM pg_catalog.pg_proc AS p
JOIN pg_catalog.pg_namespace AS n
ON n.oid OPERATOR(pg_catalog.=) p.pronamespace
JOIN pg_catalog.pg_language AS l
ON l.oid OPERATOR(pg_catalog.=) p.prolang
WHERE p.oid OPERATOR(pg_catalog.=)
'sd_api.read_marker()'::pg_catalog.regprocedure;pg_proc exposes function namespace, owner, language, prosecdef, local configuration in proconfig and privileges in proacl. pg_get_functiondef() reconstructs a creation command; preserve the separately authored source because reconstruction is not the original submitted text.
This distinction parallels the need to validate the actual schema: two relations can have identical column shapes and still be different database objects. Here, structural equivalence is intentionally not the test.
Capture temporary identity in the caller's backend
Temporary identity cannot be borrowed from an administrator's separate connection. Temporary schemas are session-specific, and pg_my_temp_schema() identifies the current backend's namespace.
After creating pg_temp.quota but before calling the function, record:
SELECT
pg_catalog.pg_backend_pid() AS backend_pid,
pg_catalog.current_database() AS database_name,
session_user,
current_user,
pg_catalog.pg_my_temp_schema() AS temp_schema_oid;Then map its relation OID:
SELECT
c.oid AS expected_temp_oid,
n.nspname AS actual_temp_schema,
pg_catalog.pg_get_userbyid(c.relowner) AS relation_owner,
c.relpersistence
FROM pg_catalog.pg_class AS c
JOIN pg_catalog.pg_namespace AS n
ON n.oid OPERATOR(pg_catalog.=) c.relnamespace
WHERE c.relnamespace OPERATOR(pg_catalog.=)
pg_catalog.pg_my_temp_schema()
AND c.relname OPERATOR(pg_catalog.=) 'quota';After a successful call, join its returned source_oid back to pg_class and pg_namespace. A literal TEMP, CALLER or TRUSTED is useful diagnostic redundancy, but the independently mapped OID plus tableoid is the stronger identity evidence. active_path and resolved_path explain the environment; neither proves which relation supplied the row.
Challenge the inherited caller path
R01 and R02 isolate caller-path inheritance.
For R01, connect as the real sd_caller to sd_case_r01 in a fresh backend, isolate psql from startup files, set the declared caller path, then make the first invocation:
psql -X --set=ON_ERROR_STOP=on \
--dbname=sd_case_r01 \
--username=sd_callerSET search_path = sd_data, pg_temp;
SELECT
session_user,
current_user,
pg_catalog.current_setting('search_path'),
pg_catalog.current_schemas(true);
SELECT * FROM sd_api.read_marker();R01 has no shadow and no function-local path. Its expected source is therefore sd_data.quota. That establishes a baseline, not safety: a configuration that works only because no conflicting object exists is not yet hardened.
R02 changes only the conditions relevant to inherited resolution. Before the fresh caller backend's first function call, sd_caller_space.quota already exists with marker CALLER, and sd_owner has USAGE on that schema plus SELECT on that table.
SET search_path = sd_caller_space, sd_data, pg_temp;
SELECT * FROM sd_api.read_marker();Because the function has no local search_path, its unqualified quota is expected to resolve under the inherited path. sd_caller_space precedes sd_data, and the definer has the permissions needed to use it. The expected returned tableoid is therefore the independently recorded OID of sd_caller_space.quota, while effective_role still reports sd_owner. PostgreSQL's path rules make first-match resolution the operative contract.
This is the key separation: the outer call remains schema-qualified as sd_api.read_marker(), yet qualification of the function name says nothing about unqualified relation tokens inside its body.
The caller's lack of direct SELECT on sd_data.quota also does not constrain the definer to that table. Once execution is admitted, relation permission checks inside a security-definer function use the effective definer identity. If that identity can read the caller-owned shadow, a denied direct read of the trusted table is perfectly compatible with a successful read from the wrong relation.
Expose implicit temporary-schema precedence
R03 and R04 distinguish an omitted pg_temp from an explicitly placed pg_temp.
R03 defines:
SET search_path = sd_dataon the function itself. At first glance that appears to pin lookup to the trusted schema. It does not explicitly place the temporary schema anywhere. PostgreSQL documents that an existing session temporary schema is implicitly searched first for relation and data-type names when pg_temp is omitted. PostgreSQL's security-definer guidance makes the same practical point: specifying only the trusted schema can still leave a function vulnerable to a temporary table masking its intended relation.
Accordingly, R03's temporary quota is expected to win even though sd_data is the only written path entry:
Documented relation priority:
implicit pg_temp → sd_data
Expected source:
TEMPR04 removes any ambiguity about intent:
SET search_path = pg_catalog, pg_temp, sd_dataIts temporary table is now explicitly before sd_data, so TEMP is again the derived expectation. The two cases should reconcile to the temporary relation OID independently captured from that caller backend.
Both cases require GRANT SELECT ON pg_temp.quota TO sd_owner; otherwise an owner-permission failure could obscure whether the temporary name actually won resolution.
Do not generalize this result to all object classes. PostgreSQL explicitly states that the implicit temporary schema is searched for relation and type names but not for function or operator names. This article excludes function/operator shadowing and deliberately qualifies its comparison operator as OPERATOR(pg_catalog.=).
Test path repair and the trust behind its schemas
R05 introduces the conventional relation-path repair:
SET search_path = pg_catalog, sd_data, pg_tempBoth a permanent caller shadow and a temporary shadow exist. Because sd_data.quota exists and sd_data precedes explicit pg_temp, while sd_caller_space is absent from the function-local path, the expected source is TRUSTED. PostgreSQL recommends excluding schemas writable by untrusted users and placing the temporary schema last for security-definer functions.
R06 demonstrates why “the function has its own search path” is not sufficient evidence. Its function path is:
SET search_path =
pg_catalog, sd_caller_space, sd_data, pg_tempThe caller-owned permanent shadow is readable by sd_owner, so the expected source is CALLER. The outer caller path is irrelevant to this comparison; the dangerous namespace has been pinned into the function's own configuration.
The expected OID comparison is therefore:
Case | Expected returned tableoid |
R05 | OID independently recorded for sd_data.quota |
R06 | OID independently recorded for sd_caller_space.quota |
A pinned path is configuration. Whether that configuration is trustworthy depends on who can create objects in every searched namespace. PostgreSQL's schema documentation warns that adding a schema to search_path effectively trusts users who have CREATE privilege there, because they can create objects that may be selected by unqualified names.
Verify who can create objects in every searched schema
Do not infer trust from names such as sd_data or app_private. Query effective privileges:
SELECT
pg_catalog.has_schema_privilege(
'sd_caller', 'sd_api', 'CREATE'
) AS caller_create_api,
pg_catalog.has_schema_privilege(
'sd_caller', 'sd_data', 'CREATE'
) AS caller_create_data,
pg_catalog.has_schema_privilege(
'sd_caller', 'sd_caller_space', 'CREATE'
) AS caller_create_shadow,
pg_catalog.has_schema_privilege(
'sd_owner', 'sd_caller_space', 'USAGE'
) AS owner_usage_shadow;Expected values are:
false
false
true
trueAlso record schema ownership:
SELECT
n.nspname,
pg_catalog.pg_get_userbyid(n.nspowner) AS owner_name
FROM pg_catalog.pg_namespace AS n
WHERE n.nspname IN ('sd_api', 'sd_data', 'sd_caller_space')
ORDER BY n.nspname;These effective checks naturally include privilege contributions from memberships and PUBLIC; PostgreSQL privileges are additive, so inspecting only a direct grant to one role is insufficient.
This article does not repeat the separate creation-time question of whose template supplied an object's initial ACL; use the creator-specific default privileges workflow for that boundary.
If the caller unexpectedly can create in sd_data, or the owner cannot search/read the comparison schema required by R06, the case prerequisite has failed. Mark that run HOLD rather than converting an unexercised attack surface into a pass.
Bind the required relation explicitly
R07 changes the body itself:
FROM sd_data.quota AS qand deliberately gives the function no local search_path. The fresh caller backend still has both permanent and temporary quota shadows and uses:
SET search_path = sd_caller_space, pg_temp, sd_data;For the required relation, the schema-qualified body reference does not ask path lookup to choose among quota objects. PostgreSQL's schema documentation describes explicit schema qualification as the mechanism for addressing an object in a particular schema. Therefore the derived expectation is the independently recorded OID of sd_data.quota, marker TRUSTED, and effective role sd_owner.
That conclusion is intentionally bounded: this required relation is explicitly addressed. It does not prove that every other reference in an arbitrary stored function is safe.
The fixture removes several unrelated variables so the evidence remains interpretable. Returned types are written as pg_catalog.oid, pg_catalog.text and pg_catalog.name; helper functions are explicitly qualified with pg_catalog; the equality operator is written OPERATOR(pg_catalog.=). No dynamic SQL appears. There are no overloaded versions of sd_api.read_marker().
Those choices should not be misread as a universal recommendation to omit function-local path controls. A production function can reference types, operators, functions or additional relations that have their own lookup rules. The acceptance statement for R07 is only that the required table token sd_data.quota cannot fall through to a same-named relation in another schema through ordinary relation search_path resolution.
PL/pgSQL adds another reason for the fresh-session discipline. PostgreSQL documents that embedded SQL commands are parsed and analyzed as they are first reached and may subsequently reuse prepared statements. This qualification therefore constructs all relevant objects before first invocation and explicitly excludes warmed-plan and cache-invalidation behavior.
Remove the required table and test the failure boundary
R08 and R09 ask a separate question: what happens when the intended relation does not exist before the first invocation?
In both databases, keep the sd_data schema and its declared permissions but do not create sd_data.quota. Preserve both comparison shadows and construct the temporary one before the function call.
R08 uses an unqualified body:
FROM quota AS qwith:
SET search_path = pg_catalog, sd_data, pg_tempsd_data is searched before pg_temp, but there is no matching quota in sd_data. PostgreSQL's first-match path rule therefore permits lookup to continue to the later temporary namespace, where quota exists. The derived expectation is consequently TEMP.
That is not a contradiction of the recommended trusted-schema-before-pg_temp configuration. That recommendation protects an existing intended object from being masked by a later temporary relation. R08 instead demonstrates the missing-dependency boundary: when the earlier schema contains no matching relation, later searched schemas remain candidates.
R09 keeps the same function-local path but uses:
FROM sd_data.quota AS qBecause the qualified relation is absent, there is no alternate unqualified lookup to continue. The expected result is 42P01, undefined_table. PostgreSQL's error-code appendix defines that SQLSTATE.
PL/pgSQL's first-execution behavior is important here: embedded SQL is analyzed when first reached, and a missing relation may therefore surface at execution of that statement rather than as a result from another table. This experiment does not warm the function and then drop a relation, does not perform concurrent DDL, and does not investigate plan invalidation.
Neither R08's expected fallback nor R09's expected error authorizes release with a missing required dependency. Both are controls describing behavior under a known-invalid application state.
Attribute the error to the intended statement
For R09, error identity must be stronger than “the command failed.” Preserve:
database name and pg_backend_pid();
session_user and pre-call current_user;
the exact submitted statement: SELECT * FROM sd_api.read_marker();
SQLSTATE immediately after the failure;
psql's available error context;
evidence that the function itself exists;
evidence that caller EXECUTE and sd_api USAGE are admitted;
independent evidence that sd_data.quota is absent.
PostgreSQL defines 42P01 as undefined_table; 42501 is insufficient_privilege. They are not interchangeable acceptance signals.
A psql expected-error fragment can capture the result without disabling fatal handling for the remainder of the script:
\echo 'STATEMENT=SELECT FROM sd_api.read_marker();'
\set ON_ERROR_STOP off
SELECT FROM sd_api.read_marker();
\set got_sqlstate :SQLSTATE
\errverbose
\set ON_ERROR_STOP on
SELECT :'got_sqlstate' = '42P01' AS expected_error \gset
\if :expected_error
\echo 'EXPECTED_ERROR_ACKNOWLEDGED'
\else
\echo 'UNEXPECTED_SQLSTATE=' :got_sqlstate
\quit 3
\endifpsql exposes the SQLSTATE associated with the most recent failed query, and ON_ERROR_STOP causes noninteractive processing to terminate rather than silently continue after ordinary errors; PostgreSQL documents exit status 3 for that stop condition.
Do not require an object-name diagnostic field that PostgreSQL does not promise for every error. Conversely, syntax errors, authentication failures, timeouts or unrelated 42501 errors do not substitute for the expected failure at the qualified body relation.
Supply a complete runner and admission ledger
A later run should be source-controlled and divided into provisioning, per-case caller execution and cleanup. Use psql -X so neither system nor personal startup files alter the session. PostgreSQL documents -X/--no-psqlrc for startup-file isolation and notes that -c no longer implies it.
A minimal driver can use authorized local connection variables:
#!/usr/bin/env bash
set -euo pipefail
: "${PGHOST:?set PGHOST}"
: "${PGPORT:?set PGPORT}"
: "${PGUSER:?set authorized provisioning PGUSER}"
PSQL=(psql -X --set=ON_ERROR_STOP=on)
psql --version
"${PSQL[@]}" --dbname=postgres \
-c "SHOW server_version;" \
-c "SELECT current_setting('server_version_num');"
sha256sum bootstrap_roles.sql bootstrap_case.sql run_case.sql \
> fixture-source.sha256The case generator must contain the declared manifest, not infer expected results from runtime output. One defensible shell representation is:
case "$CASE_ID" in
R01) BODY='quota'; FPATH=''; \
CPATH='sd_data, pg_temp'; PERM=0; TEMP=0; TRUSTED=1 ;;
R02) BODY='quota'; FPATH=''; \
CPATH='sd_caller_space, sd_data, pg_temp'; PERM=1; TEMP=0; TRUSTED=1 ;;
R03) BODY='quota'; FPATH='sd_data'; \
CPATH='sd_caller_space, sd_data, pg_temp'; PERM=1; TEMP=1; TRUSTED=1 ;;
R04) BODY='quota'; FPATH='pg_catalog, pg_temp, sd_data'; \
CPATH='sd_data, pg_temp'; PERM=0; TEMP=1; TRUSTED=1 ;;
R05) BODY='quota'; FPATH='pg_catalog, sd_data, pg_temp'; \
CPATH='sd_caller_space, sd_data, pg_temp'; PERM=1; TEMP=1; TRUSTED=1 ;;
R06) BODY='quota'; FPATH='pg_catalog, sd_caller_space, sd_data, pg_temp'; \
CPATH='sd_data, pg_temp'; PERM=1; TEMP=1; TRUSTED=1 ;;
R07) BODY='sd_data.quota'; FPATH=''; \
CPATH='sd_caller_space, pg_temp, sd_data'; PERM=1; TEMP=1; TRUSTED=1 ;;
R08) BODY='quota'; FPATH='pg_catalog, sd_data, pg_temp'; \
CPATH='sd_caller_space, sd_data, pg_temp'; PERM=1; TEMP=1; TRUSTED=0 ;;
R09) BODY='sd_data.quota'; FPATH='pg_catalog, sd_data, pg_temp'; \
CPATH='sd_caller_space, sd_data, pg_temp'; PERM=1; TEMP=1; TRUSTED=0 ;;
R10) BODY='sd_data.quota'; FPATH='pg_catalog, sd_data, pg_temp'; \
CPATH='sd_caller_space, pg_temp, sd_data'; PERM=1; TEMP=1; TRUSTED=1 ;;
*) echo "unknown case" >&2; exit 2 ;;
esacThe function DDL can be emitted from those hard-coded manifest values during provisioning. Do not accept externally supplied relation or path strings into that generator.
The actual caller script records pre-call state, creates the declared temporary relation where required, grants sd_owner access, records its OID, and only then invokes the function:
\set ON_ERROR_STOP on
SELECT
pg_catalog.current_database() AS database_name,
pg_catalog.pg_backend_pid() AS backend_pid,
session_user,
current_user;
SET search_path = sd_caller_space, pg_temp, sd_data;
-- Only in TEMP=1 cases:
CREATE TEMP TABLE quota (
id integer PRIMARY KEY,
marker text NOT NULL
);
INSERT INTO pg_temp.quota VALUES (1, 'TEMP');
GRANT SELECT ON pg_temp.quota TO sd_owner;
SELECT
c.oid,
n.nspname,
c.relname,
c.relpersistence
FROM pg_catalog.pg_class AS c
JOIN pg_catalog.pg_namespace AS n
ON n.oid OPERATOR(pg_catalog.=) c.relnamespace
WHERE c.relnamespace OPERATOR(pg_catalog.=)
pg_catalog.pg_my_temp_schema()
AND c.relname OPERATOR(pg_catalog.=) 'quota';
SELECT * FROM sd_api.read_marker();
SELECT session_user, current_user,
pg_catalog.current_setting('search_path');The runner ledger should contain exactly one R01–R10 record and these mandatory prerequisites:
Probe | Required evidence | Decision effect |
A_ROLE | Real caller connection; role flags; no owner membership | Missing/mismatched → HOLD |
A_EXECUTE | Caller admitted; actual outsider call denied 42501 | Wrong admission → REPAIR/HOLD |
A_DIRECT | Caller direct trusted-table SELECT denied 42501 where relation exists | Unexpected direct access → REPAIR |
A_TRUST | Caller cannot CREATE in sd_api or sd_data | Writable trusted schema → REPAIR |
A_SHADOW_READ | Definer has USAGE/SELECT needed for declared shadows | Missing prerequisite → HOLD |
A_VERSION | Actual server and psql builds recorded and equal declared baseline | Mismatch → HOLD |
For every case, record expected source, independently obtained source OID, actual returned tableoid, marker, effective role, raw and resolved paths, database name, backend PID, SQLSTATE, process status and fixture-source digest. No observed results are supplied here.
Handle expected negatives without concealing unrelated failures
Expected denial probes need the same treatment as R09: temporarily disable ON_ERROR_STOP for one precisely identified statement, save :SQLSTATE immediately, restore fatal handling, and fail the harness if the code differs.
For example, the outsider probe is executed from an actual sd_outsider connection:
\set ON_ERROR_STOP off
SELECT * FROM sd_api.read_marker();
\set got_sqlstate :SQLSTATE
\errverbose
\set ON_ERROR_STOP on
SELECT :'got_sqlstate' = '42501' AS expected_denial \gset
\if :expected_denial
\echo 'A_EXECUTE outsider denial acknowledged'
\else
\quit 3
\endifA direct caller table test uses the same pattern against:
SELECT * FROM sd_data.quota;in relation-present cases.
For trusted-schema creation, test the real privilege boundary without leaving an object:
BEGIN;
\set ON_ERROR_STOP off
CREATE TABLE sd_data.__sd_create_probe(id integer);
\set got_sqlstate :SQLSTATE
\errverbose
\set ON_ERROR_STOP on
ROLLBACK;
SELECT :'got_sqlstate' = '42501' AS expected_denial \gset
\if :expected_denial
\echo 'A_TRUST denial acknowledged'
\else
\quit 3
\endifPostgreSQL assigns 42501 to insufficient privilege. Ordinary script failures remain fatal. The tested function is not wrapped in an elevated PL/pgSQL exception handler, because that would alter the evidence boundary.
A harness that acknowledges an expected negative but then terminates before R10 is incomplete. Likewise, a log missing one case ID, a missing source-OID oracle or a skipped admission probe is HOLD, not “mostly passed.”
Apply the combined repair and recheck boundaries
R10 combines both controls:
Body: sd_data.quota
Function path: pg_catalog, sd_data, pg_temp
Caller path: sd_caller_space, pg_temp, sd_data
Shadows: permanent + temporaryBoth shadows are reintroduced before a fresh first invocation. The expected result remains the OID independently recorded for sd_data.quota, marker TRUSTED, and effective_role = sd_owner.
The caller's outer path should be captured before the invocation and again afterward. Because the function's SET search_path is function-local, PostgreSQL specifies that the previous parameter value is restored when the function exits, absent a body-level ordinary SET; this fixture contains none. Therefore R10 requires the caller's path and effective identity to be restored after return.
Restrictive execution is part of the combined repair as well:
REVOKE ALL ON FUNCTION sd_api.read_marker() FROM PUBLIC;
GRANT EXECUTE ON FUNCTION sd_api.read_marker() TO sd_caller;and the trusted schemas must remain non-writable by the caller. A correct relation reference does not justify broad EXECUTE or schema-creation rights.
If repair uses CREATE OR REPLACE FUNCTION, capture ownership, ACL, prosecdef and proconfig before and after. The replacement statement should explicitly restate SECURITY DEFINER and the desired function-local path rather than assuming every omitted property will end in the reviewed state. After replacement, requery pg_proc and reconstruct the definition for comparison. PostgreSQL documents prosecdef, proconfig and proacl as distinct catalog attributes.
The accepted conclusion remains bounded. It does not validate dynamic SQL, function/operator lookup, overload selection, RLS behavior, every relation in a larger body, pooled-session history, cache invalidation or future schema changes. A successful negative control only demonstrates that the test harness can expose that condition; it does not make the negative configuration an acceptable application policy.
Make release and recovery decisions from complete evidence
The release rule should be mechanical enough that reviewers cannot reinterpret a surprising result into a pass after execution.
Evidence | Decision | Required action |
All R01–R10 match the predeclared oracle; all admission probes pass; actual server/client are 18.7; R10 returns trusted OID/marker with correct role and restoration | ACCEPT | Approve only the declared bounded relation-binding contract |
Any present-table case resolves to a wrong shadow because of inherited or function-local path configuration | REPAIR | Qualify the required relation and/or repair function path and searched-schema permissions; rerun all cases fresh |
Caller or PUBLIC has unintended EXECUTE; caller can create in a trusted searched schema | REPAIR | Tighten function/schema privileges and rerun |
Required relation absent | HOLD | Restore the reviewed dependency; do not accept fallback or expected error as application readiness |
Server or psql version differs from declared baseline | HOLD | Re-establish the baseline or create and review a new oracle for the actual version |
A prerequisite, expected denial, source OID, case ID or log segment is missing | HOLD | Complete evidence before release |
Result disagrees with the documented/derived expectation | HOLD | Preserve evidence and investigate; do not revise the expectation retroactively |
Application owners should own the declaration that sd_api.read_marker() depends on sd_data.quota and what marker semantics constitute correctness. Database owners should own the reviewed function definition, function ownership/ACLs and schema/table permissions. Release reviewers should own evidence completeness, baseline verification and the ACCEPT/REPAIR/HOLD decision. These responsibilities fit naturally into broader practices for automating database administration, but automation must preserve rather than weaken the evidence boundaries.
Recovery is similarly bounded. Restore the approved table and function definitions through the authorized migration owner, then repeat qualification in fresh caller sessions. Do not infer historical application impact merely because a validation case demonstrates that fallback could occur; historical impact requires separate evidence such as deployment records, application logs and database audit data.
Before cleanup, preserve external logs, case ledgers, source digests and reviewed SQL outside the disposable databases. Then confirm the database identities and owners:
SELECT
datname,
pg_catalog.pg_get_userbyid(datdba) AS database_owner
FROM pg_catalog.pg_database
WHERE datname IN (
'sd_case_r01','sd_case_r02','sd_case_r03','sd_case_r04','sd_case_r05',
'sd_case_r06','sd_case_r07','sd_case_r08','sd_case_r09','sd_case_r10'
)
ORDER BY datname;Only after caller sessions are closed should the provisioning account remove exactly those named fixtures:
DROP DATABASE sd_case_r01;
DROP DATABASE sd_case_r02;
DROP DATABASE sd_case_r03;
DROP DATABASE sd_case_r04;
DROP DATABASE sd_case_r05;
DROP DATABASE sd_case_r06;
DROP DATABASE sd_case_r07;
DROP DATABASE sd_case_r08;
DROP DATABASE sd_case_r09;
DROP DATABASE sd_case_r10;Then, if those roles were created solely for this isolated environment and no dependencies remain:
DROP ROLE sd_outsider;
DROP ROLE sd_caller;
DROP ROLE sd_owner;Cleanup cannot undo effects in a production system; this laboratory is intentionally disposable. Requalify after a function-definition change, owner or ACL change, searched-schema permission change, required-table replacement, or server-version change because any of those can invalidate part of the accepted evidence.
Build database validation skills with Refonte Learning Database Administrator Essentials
The core discipline in this exercise is broader than one PostgreSQL feature: state the dependency explicitly, distinguish authenticated identity from effective authority, make permission prerequisites observable, obtain evidence independently from the system under test, and make release decisions from a predeclared contract rather than from plausible-looking output.
Refonte Learning's Database Administrator Essentials page, checked November 28, 2026, describes a three-month program with an expected commitment of 12–14 hours per week and recommends basic programming knowledge. Its published topics include database fundamentals, advanced SQL, optimization, security and access control, migration and integration, backup and recovery, monitoring, and cloud database administration; the cloud path names AWS RDS, Azure SQL and Google Cloud Spanner. The page also lists an educational mentor, a Potential Internship, and Training Certificate plus Certificate of Internship upon completion.
Those confirmed administration and security topics align with the habits used here. The page does not establish that this specific PostgreSQL SECURITY DEFINER, search_path, tableoid or ten-case laboratory is taught, so no such claim is made. Readers seeking a structured database-administration foundation can review the program while treating this qualification workflow as an independent PostgreSQL engineering exercise.
