Security Barrier Views Block Leaky Pushdown
Attach WITH (security_barrier = true) to PostgreSQL views so outer non-leakproof predicates cannot run ahead of row-hiding WHERE filters.
Code
CREATE TEMP TABLE employee_pay (
emp_id integer PRIMARY KEY,
department text NOT NULL,
salary integer NOT NULL
);
INSERT INTO employee_pay VALUES
(1, 'eng', 180000),
(2, 'sales', 120000),
(3, 'exec', 450000);
-- Plain view lets the planner pull up the subquery and reorder predicates by cost
CREATE TEMP VIEW v_non_exec_open AS
SELECT emp_id, department, salary
FROM employee_pay
WHERE department <> 'exec';
-- security_barrier enforces the view filter before any non-leakproof outer predicate
CREATE TEMP VIEW v_non_exec_safe
WITH (security_barrier = true) AS
SELECT emp_id, department, salary
FROM employee_pay
WHERE department <> 'exec';
-- Non-LEAKPROOF helper: dividing by (450000 - amt) raises division_by_zero on exec rows
CREATE OR REPLACE FUNCTION pg_temp.low_cost_ratio(amt integer)
RETURNS boolean
LANGUAGE plpgsql
IMMUTABLE
COST 0.0001 AS $$
BEGIN
RETURN (1000000 / (450000 - amt)) > 0;
END;
$$;
-- Compare plans: v_non_exec_open pulls up into one scan; v_non_exec_safe keeps a barrier
EXPLAIN (COSTS OFF)
SELECT emp_id, salary FROM v_non_exec_open WHERE pg_temp.low_cost_ratio(salary);
EXPLAIN (COSTS OFF)
SELECT emp_id, salary FROM v_non_exec_safe WHERE pg_temp.low_cost_ratio(salary);
-- Safe view filters department <> 'exec' first so row 3 never hits division by zero
SELECT emp_id, department, salary
FROM v_non_exec_safe
WHERE pg_temp.low_cost_ratio(salary)
ORDER BY emp_id;Execution summary — Security Barrier Views Block Leaky Pushdown
The file runs SELECT / INSERT / CREATE / EXPLAIN statements, touching employee_pay, v_non_exec_open and v_non_exec_safe.
employee_pay sets up ephemeral session-only storage inline within this example script so prior schema preparation is skipped and rows clean up automatically at close.
Clause by clause, expect: a WHERE clause constraining which rows the statement operates on; an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity.
Using it
Setup is internal: the session-local tables it queries (employee_pay) are made by the file, so a single complete run against a scratch database suffices.
Key statements
CREATE TEMP VIEW v_non_exec_safe
WITH (security_barrier = true) AS
SELECT emp_id, department, salary
FROM employee_pay
WHERE department <> 'exec';
CREATE TEMP VIEW v_non_exec_open AS
SELECT emp_id, department, salary
FROM employee_pay
WHERE department <> 'exec';
SELECT emp_id, department, salary
FROM v_non_exec_safe
WHERE pg_temp.low_cost_ratio(salary)
ORDER BY emp_id;
Interactive Tools for This Topic
FAQ
- Which tables appear in this script?
- `employee_pay`, `v_non_exec_open`, `v_non_exec_safe`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.