Bug: RLS Policies Generated Before Referenced Tables Exist
Bug: RLS Policies Generated Before Referenced Tables Exist
First, thank you for building pgschema. It’s been a really useful tool for managing PostgreSQL schemas as code.
I ran into an issue when working with RLS policies in a multi-table setup and wanted to share it in case it helps improve the tool.
Description
When generating a migration plan against an empty database, pgschema creates CREATE POLICY statements immediately after each table definition. This becomes a problem when a policy on one table references another table that hasn’t been created yet.
This looks like a statement ordering issue in the plan generator and will likely affect setups where RLS policies depend on other tables, which is quite common.
Steps to Reproduce
- Define two tables where Table A has an RLS policy that references Table B
- Run
pgschema planon an empty database - Apply the generated migration plan
Generated Plan (Problematic Order)
CREATE TABLE IF NOT EXISTS manager (
id SERIAL,
user_id uuid NOT NULL
);
CREATE POLICY employee_manager_select
ON manager FOR SELECT TO employee
USING (
id IN (
SELECT pam.manager_id
FROM project_manager pam
WHERE pam.project_id IN (
SELECT unnest(get_user_assigned_projects())
)
AND pam.is_deleted = false
)
);
CREATE TABLE IF NOT EXISTS project_manager (
id SERIAL,
project_id int NOT NULL,
manager_id int NOT NULL
);
Error
ERROR: relation "project_manager" does not exist (SQLSTATE 42P01)
Expected Behavior
The migration plan should be generated in a safe execution order so that all referenced objects exist before they are used. For example:
CREATE TABLE IF NOT EXISTS manager (...);
CREATE TABLE IF NOT EXISTS project_manager (...);
CREATE INDEX IF NOT EXISTS ...;
ALTER TABLE manager ENABLE ROW LEVEL SECURITY;
CREATE POLICY employee_manager_select
ON manager FOR SELECT TO employee
USING (...);
Why This Matters
RLS policies often rely on other tables for authorization logic. Creating policies immediately after each table makes it difficult to use pgschema in real-world scenarios without manually reordering statements.
Suggested Fix
It would help if the migration plan generator grouped statements into phases such as:
- Create all tables
- Create indexes
- Enable row-level security
- Create all policies after all tables exist
Environment
- pgschema version: 1.7.4
- PostgreSQL version: 17
- OS: macOS (Apple Silicon)
Thanks again for maintaining this project. Happy to help test any fixes if needed.
Thanks for the quick fix! Works perfectly now 🙌