Skip to content

fix(fkeys): re-create fkeys from tables outside the load scope - #1783

Open
RegWin32 wants to merge 1 commit into
dimitri:mainfrom
RegWin32:fix/recreate-dependent-fkeys
Open

RegWin32 wants to merge 1 commit into
dimitri:mainfrom
RegWin32:fix/recreate-dependent-fkeys

Conversation

@RegWin32

@RegWin32 RegWin32 commented Nov 2, 2026

Copy link
Copy Markdown

Problem

When loading WITH data only, truncate into an existing schema with INCLUDING ONLY TABLE NAMES LIKE …, foreign keys that live on a table outside of the selection but reference a selected table are dropped before the load and never created again.

Example: orders.customer_id → customers.id, only customers is in the load. After the run, the foreign key on orders is gone. Foreign keys between two selected tables are created again as expected.

Seen with pgloader 3.6.9 (Debian bookworm), MSSQL → PostgreSQL. The code is the same on current main.

Cause

fetch-pgsql-catalog → list-missing-fk-deps collects those foreign keys into index-fk-deps of the referenced index. drop-pgsql-fkeys drops them (:append … :collect), but create-pgsql-fkeys used :do instead of :append for the inner loop, so the generated ALTER TABLE … ADD CONSTRAINT statements were discarded. They only showed up in the debug log as EXTRA FK DEPS!.

Fix

  • Collect the statements for index-fk-deps in create-pgsql-fkeys.
  • list-all-fkeys also pushes foreign keys between two selected tables into index-fk-deps, so skip those whose OID is already in a table fkey list (and dedupe across indexes) to avoid constraint already exists errors.

Note

The v4 (Clojure) implementation may have the same gap; I have not checked it.

In data only mode with an existing target schema, fetch-pgsql-catalog
collects foreign keys of tables outside of the load selection that
reference a loaded table into index-fk-deps. drop-pgsql-fkeys drops
them, but create-pgsql-fkeys used :do instead of :append for the inner
loop, so the generated statements were discarded and those foreign keys
were silently lost after the load.

Collect the statements, and skip fkeys already created from the table
fkey list (fkeys between two loaded tables are listed in both places).
@RegWin32
RegWin32 force-pushed the fix/recreate-dependent-fkeys branch from 9e620d5 to f89d4af Compare November 2, 2026 12:40
@RegWin32
RegWin32 marked this pull request as ready for review November 2, 2026 12:42

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant