Self-referencing FK to a non-PK UNIQUE constraint is always inlined in `CREATE TABLE`, breaking `dump`/`plan` ("no unique constraint matching given keys") — PR #533 does not cover this path
First off, thanks for the quick fix on #532 via PR #533 — much appreciated.
This is a follow-up to #532 / PR #533. That PR fixed constraint ordering in internal/diff's diff-generation path (the steps emitted when diffing two live states). It does not fix the failure originally reported in #532 for the dump → plan --file workflow (dump once, --file desired-state applied against a target). I re-tested against a real schema with a build from main (post-#533, commit reachable as v1.12.3-0.20260806153347-...) and the exact same error still occurs:
Error: failed to apply desired state: failed to apply schema SQL to temporary schema pgschema_tmp_...:
ERROR: there is no unique constraint matching given keys for referenced table "parent_orgs" (SQLSTATE 42830)
Root cause (found in source)
internal/diff/table.go, function shouldDeferConstraint:
func shouldDeferConstraint(table *ir.Table, constraint *ir.Constraint, currentKey string, createdTables map[string]bool, existingTables map[string]bool) bool {
if constraint == nil || constraint.Type != ir.ConstraintTypeForeignKey {
return false
}
refSchema := constraint.ReferencedSchema
if refSchema == "" {
refSchema = table.Schema
}
if constraint.ReferencedTable == "" {
return false
}
refKey := fmt.Sprintf("%s.%s", refSchema, constraint.ReferencedTable)
if refKey == currentKey {
return false // <-- self-referencing FK is NEVER deferred
}
...
}
For a self-referencing foreign key (a table with an FK column pointing back at itself), this function always returns false (i.e. "safe to inline in CREATE TABLE"), because the referenced table trivially exists — it's the same table currently being created. But it never checks whether the FK's target is the table's primary key (fine, created inline) or a separate UNIQUE constraint/index (not fine).
Looking at generateCreateTablesSQL (same file), the per-table sequence is:
for _, table := range tables {
sql, tableDeferred := generateTableSQL(table, ...) // CREATE TABLE, with inline FKs decided by shouldDeferConstraint
collector.collect(context, sql)
...
generateCreateIndexesSQL(indexes, targetSchema, collector) // indexes/UNIQUE come AFTER CREATE TABLE
...
}
So when a self-referencing FK targets a non-PK UNIQUE index/constraint on the same table, the FK is inlined inside CREATE TABLE (because shouldDeferConstraint said "don't defer"), but the UNIQUE index it depends on is only created afterward via generateCreateIndexesSQL — the FK statement runs first and fails.
How pg_dump avoids this entire class of bug
pg_dump never inlines any foreign key inside CREATE TABLE, self-referencing or not. It always: (1) emits bare CREATE TABLE (columns only), (2) emits all indexes/UNIQUE/PRIMARY KEY constraints, (3) emits every FK as a separate ALTER TABLE ... ADD CONSTRAINT ... FOREIGN KEY at the end, ordered via a real dependency graph (pg_depend) rather than by table-existence checks. Because FKs are always deferred to a later ALTER TABLE, pg_dump structurally cannot hit this ordering hazard — there's no "should I inline or defer" decision to get wrong.
pgschema's more declarative "inline when possible" strategy reintroduces exactly this hazard, and the self-referencing case is the one spot where the current heuristic (referenced-table-exists) is not sufficient — it needs to also check whether the FK targets the PK vs. a separately-created UNIQUE object.
Suggested fix
In shouldDeferConstraint, don't short-circuit return false when refKey == currentKey. Instead, check whether the constraint's referenced columns match the table's primary key:
- If yes → safe to inline (PK is always created as part of
CREATE TABLE). - If no (targets a separate
UNIQUEconstraint or index) → defer, same as the cross-table case, so it's emitted viagenerateDeferredConstraintsSQLaftergenerateCreateIndexesSQLhas run for that table.
Minimal repro
CREATE TABLE parent_orgs (
id bigint PRIMARY KEY,
external_key uuid NOT NULL,
migrated_from_external_key uuid,
CONSTRAINT fk_self_migrated_from
FOREIGN KEY (migrated_from_external_key) REFERENCES parent_orgs (external_key)
);
CREATE UNIQUE INDEX parent_orgs_external_key_key ON parent_orgs (external_key);
pgschema dump --schema public ...a database with this structure (or hand-write the file above as the "desired state").pgschema plan --schema public --file schema.sql ...against any target (default embedded plan DB) fails while applying the desired state, with the SQLSTATE 42830 error shown above.
This reproduces with the self-reference on the same table, which is the case not covered by #533 (that PR addressed cross-table topological ordering of already-existing-table constraints, not the inline-vs-defer decision for self-referencing FKs during initial table creation).