pgschema icon indicating copy to clipboard operation
pgschema copied to clipboard

issue on pgplex/pgschema — constraint ordering bug

Open pranavks608 opened this issue 3 months ago • 1 comments

Title: DROP CONSTRAINT generated after DROP TABLE/COLUMN — causes foreign key dependency failure

Description: When generating a migration plan that involves dropping both a table/column and its associated foreign key constraints, pgschema outputs the DDL statements in incorrect order:

  1. DROP TABLE / DROP COLUMN (generated first)
  2. DROP CONSTRAINT (generated after)

This causes execution failure because the foreign key constraint still references the table/column being dropped.

Expected Behavior: DROP CONSTRAINT statements should be generated before any DROP TABLE or DROP COLUMN statements that depend on them, respecting foreign key dependency ordering.

Steps to Reproduce: Given an existing database with: CREATE TABLE products ( id SERIAL PRIMARY KEY, name VARCHAR(255) ); CREATE TABLE orders ( id SERIAL PRIMARY KEY, product_id INTEGER REFERENCES products(id) );

And a desired state schema.sql that removes the products table and the product_id column: CREATE TABLE orders ( id SERIAL PRIMARY KEY );

Running: pgschema plan --host localhost --db testdb --user postgres
--schema public --file schema.sql --output-sql migration.sql

Produces (incorrect order): ALTER TABLE orders DROP COLUMN product_id; DROP TABLE products; ALTER TABLE orders DROP CONSTRAINT orders_product_id_fkey;

Expected (correct order): ALTER TABLE orders DROP CONSTRAINT orders_product_id_fkey; ALTER TABLE orders DROP COLUMN product_id; DROP TABLE products;

Impact: The generated migration SQL fails when executed against the database due to dependency violations.

pranavks608 avatar Aug 10 '26 05:08 pranavks608

This should have been fixed in main.

tianzhou avatar Aug 14 '26 09:08 tianzhou