Skip to content

[BUG] Policy ordering: policy created before referenced table exists #266

@ChielTimmermans

Description

@ChielTimmermans

Describe the bug**

When generating a migration diff, a policy that references another table in its USING clause is ordered before the referenced table is created, causing the migration to fail.

Expected behavior**

The diff generator should analyze policy USING and WITH CHECK clauses for table references and order statements so that:

  1. All tables referenced by a policy are created first
  2. The policy is created after its dependent tables exist

Correct ordering would be:

  1. CREATE TABLE tenant.projects
  2. CREATE TABLE tenant.project_members
  3. CREATE POLICY project_members_org_policy

To Reproduce

Given a schema with:

  1. Table tenant.project_members with a row-level security policy:
CREATE POLICY project_members_org_policy ON tenant.project_members
   AS PERMISSIVE
   FOR ALL
   TO fun_fundament_api
   USING (EXISTS (
     SELECT 1 FROM projects
     WHERE projects.id = project_members.project_id
     AND projects.organization_id = current_setting('app.current_organization_id')::uuid
));
  1. Table tenant.projects (referenced by the policy above)

Observed Behavior

The generated migration orders statements as:

  1. CREATE TABLE tenant.project_members
  2. CREATE POLICY project_members_org_policy (fails - references tenant.projects which doesn't exist yet)
  3. ... other statements ...
  4. CREATE TABLE tenant.projects

Context

pg-schema-diff version: v1.0.5
pg-schema-diff usage: LIBRARY
Postgres version: 18

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions