Skip to content

Auto-generated migrations have problems with the down migration #14800

@gbelther

Description

@gbelther

Describe the Bug

Auto-generated down migrations for PostgreSQL produce SQL that fails due to incorrect drop order. Constraints and indexes referencing the dropped table are attempted after the DROP TABLE, causing foreign key dependency errors.

Example from generated down function:
export async function down({ db, payload, req }: MigrateDownArgs): Promise {
await db.execute(sql`
ALTER TABLE "store" DISABLE ROW LEVEL SECURITY;
DROP TABLE "store" CASCADE;
ALTER TABLE "payload_locked_documents_rels" DROP CONSTRAINT "payload_locked_documents_rels_store_fk";

DROP INDEX "payload_locked_documents_rels_store_id_idx";
ALTER TABLE "payload_locked_documents_rels" DROP COLUMN "store_id";`)
}

The DROP TABLE "store" CASCADE succeeds, but subsequent constraint/index drops on payload_locked_documents_rels fail because the dependency analysis is wrong post-drop.

Full migration code: https://github.com/gbelther/payload-migrations

Environment Info

Payload: 3.65.0
DB: PostgreSQL v18 (latest)
Adapter: @payloadcms/db-postgres

Basically, the auto-generated SQL migration tries to drop the constraint and index after dropping the table. The full code is here.

This causes an error on down migration. As this code is auto generated, I believe this is a bug.

Link to the code that reproduces this issue

https://github.com/gbelther/payload-migrations

Reproduction Steps

  1. Generate a migration that drops a collection with relationships (e.g., via schema change creating a "store" table with rels).
  2. Run payload migrate (up succeeds).
  3. Run payload migrate:down → fails with FK constraint error.

Which area(s) are affected? (Select all that apply)

db: postgres

Environment Info

"@payloadcms/next": "3.65.0",
    "@payloadcms/richtext-lexical": "3.65.0",
    "@payloadcms/ui": "3.65.0",
    "cross-env": "^7.0.3",
    "dotenv": "16.4.7",
    "graphql": "^16.8.1",
    "next": "15.4.7",
    "payload": "3.65.0",
    "react": "19.1.0",
    "react-dom": "19.1.0",
    "sharp": "0.34.2",
    "@payloadcms/db-postgres": "3.65.0"

Metadata

Metadata

Assignees

No one assigned

    Labels

    status: needs-triagePossible bug which hasn't been reproduced yet

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions