Skip to content
This repository was archived by the owner on Nov 25, 2026. It is now read-only.

feat(sql): add referential actions for foreign keys - #168

Merged
jkomyno merged 22 commits into
mainfrom
feat/referential-actions
Feb 26, 2026
Merged

jkomyno merged 22 commits into
mainfrom
feat/referential-actions

Conversation

@jkomyno

@jkomyno jkomyno commented Feb 20, 2026 •

Copy link
Copy Markdown
Contributor

closes TML-1905

Goal

Add ON DELETE / ON UPDATE referential action support to Prisma Next's foreign key model, covering the full contract-first lifecycle: authoring → emission → introspection → verification → DDL generation.

This builds on the FK constraint and index configuration feature and supports all five PostgreSQL referential actions: noAction, restrict, cascade, setNull, setDefault.

Before / After

// BEFORE — foreign keys had no action configuration
createTable('post')
  .column('userId', { type: pg.int4() })
  .foreignKey(['userId'], { table: 'user', columns: ['id'] })
// AFTER — onDelete and onUpdate are first-class options
createTable('post')
  .column('userId', { type: pg.int4() })
  .foreignKey(['userId'], { table: 'user', columns: ['id'] }, {
    onDelete: 'cascade',
    onUpdate: 'restrict',
  })

What changed and why

Contract layer

  • Added ReferentialAction union type and optional onDelete/onUpdate fields to ForeignKey
  • Extracted ForeignKeyOptions named type to reduce inline duplication across factory and builder signatures
  • Extended Arktype structural validation with ReferentialActionSchema and ForeignKeySchema, shared between sql-contract and contract-ts (deduplication)
  • Added semantic validation: setNull on non-nullable columns and setDefault on non-nullable columns without a DEFAULT are rejected at contract validation time

Introspection

  • Extended Postgres FK query to join referential_constraints for delete_rule/update_rule
  • Fixed composite FK introspection to use pg_catalog.pg_constraint.confkey[ordinal_position] instead of constraint_column_usage (which produced Cartesian products for multi-column FKs)
  • NO ACTION (the database default) maps to undefined in the sparse Schema IR

Migration planner

  • buildForeignKeySql emits ON DELETE / ON UPDATE clauses with runtime assertions for unknown action values
  • FK action mismatches are classified as non-additive conflicts (the init planner correctly reports them instead of silently ignoring)

Schema verification

  • verifyForeignKeys compares referential actions after structural match, reporting both onDelete and onUpdate mismatches simultaneously
  • noAction is normalized to undefined before comparison, so explicit noAction in a contract passes against a database using the default NO ACTION

Canonicalization

  • noAction is stripped during canonicalization for hash stability (explicit noAction and omitted produce the same storageHash)

Docs & specs

  • ADR 162 documents the referential actions design
  • Package READMEs updated with referential actions documentation
  • Agent-OS spec and requirements added

Summary by CodeRabbit

  • New Features

    • PostgreSQL referential actions for foreign keys (ON DELETE/ON UPDATE): CASCADE, RESTRICT, SET NULL, SET DEFAULT, NO ACTION; planner emits matching DDL and introspection reports actions.
    • Global foreignKeys config to control emitting FK constraints and backing indexes.
    • Builder API accepts per-FK options to declare onDelete/onUpdate.
  • Validation

    • Runtime/schema verification now checks referential-action mismatches and rejects incompatible configurations with readable errors.
  • Documentation

    • Added specs, ADR, planning and README updates.
  • Tests

    • Extensive unit, integration and E2E coverage for referential actions and verification.

jkomyno and others added 14 commits February 20, 2026 02:51
Introduce ADR 162 documenting the design for onDelete/onUpdate
referential actions on foreign keys. Paired with a detailed spec
and task breakdown for Postgres-only implementation.

Referential actions extend the contract IR, builder, validator,
planner DDL emission, introspection, and schema verification.
All new fields are optional — existing contracts are unaffected.

Co-authored-by: Cursor <[email protected]>
Introduce ReferentialAction union type ('noAction' | 'restrict' |
'cascade' | 'setNull' | 'setDefault') and add optional onDelete/
onUpdate fields to ForeignKey in the contract IR.

Extend the fk() factory to accept either a string name (backward-
compatible) or an options object with name, onDelete, onUpdate.
Extend the Arktype ForeignKeySchema validator to accept the new
optional fields. Export ReferentialAction from the types barrel.

Co-authored-by: Cursor <[email protected]>
Add onDelete and onUpdate fields to ForeignKeyDef and update the
TableBuilder.foreignKey() method to accept an options object as the
third parameter (backward-compatible with string name).

Propagate referential actions through the contract builder transform
so they appear in the emitted contract JSON.

Co-authored-by: Cursor <[email protected]>
Add SqlReferentialAction type and optional onDelete/onUpdate fields
to SqlForeignKeyIR in the schema IR.

Extend the Postgres control adapter FK query to join
information_schema.referential_constraints and read delete_rule
and update_rule. Map Postgres rule names to camelCase values.
NO ACTION is omitted (undefined) since it is the database default.

Co-authored-by: Cursor <[email protected]>
Extend buildForeignKeyOperations() to append referential action
clauses when onDelete or onUpdate is specified on a foreign key.

Maps camelCase action names to SQL keywords (e.g. cascade -> CASCADE,
setNull -> SET NULL). When both are undefined, no clauses are
appended, preserving backward compatibility.

Includes 13 unit tests covering all ReferentialAction values and
combinations for the DDL emission matrix.

Co-authored-by: Cursor <[email protected]>
Extend verifyForeignKeys() to compare onDelete and onUpdate when the
contract FK specifies them. A mismatch produces a foreign_key_mismatch
issue with a descriptive message. When the contract omits referential
actions, the verifier does not compare them (undefined = don't care).

Update test helpers to support referential action fields on FK
definitions for both contract and schema IR.

Co-authored-by: Cursor <[email protected]>
…le FK columns

Add validateStorageSemantics() that checks semantic constraints beyond
structural schema validation. Currently rejects setNull referential
action (onDelete or onUpdate) when the FK column is NOT NULL, since
the database would fail at runtime.

setDefault validation is deferred as optional hardening.

Co-authored-by: Cursor <[email protected]>
Document ReferentialAction type, fk() factory options, semantic
validation, planner DDL emission, and schema verification in the
sql-contract, target-postgres, and family-sql package READMEs.
Link to ADR 162 where relevant.

Co-authored-by: Cursor <[email protected]>
… and missing FK schema fields

The contract-authoring package (framework domain) was importing
ReferentialAction from sql-contract (sql domain), violating the
architecture's cross-domain rules. Define the type locally instead.

Also add onDelete/onUpdate to the ForeignKeySchema in sql-contract-ts
so that the Arktype validator accepts the extended ForeignKey type.

Co-authored-by: Cursor <[email protected]>
Two tests were timing out at the default 100ms under Node.js 24:
- 'handles connection errors gracefully' (DNS resolution to invalid host)
- 'emits stable fingerprint for literal-only differences' (DB operations)

Both now use timeouts.databaseOperation (5s) matching sibling tests.

Co-authored-by: Cursor <[email protected]>
Cover the full introspection-and-verification flow against a real
Postgres database:
- Introspect ON DELETE CASCADE / ON UPDATE RESTRICT
- Introspect ON DELETE SET NULL / ON UPDATE CASCADE
- Verify NO ACTION is omitted (sparse IR)
- Schema verification passes when contract and DB actions match
- Schema verification detects onDelete / onUpdate mismatches
- Contract without referential actions skips comparison (ok=true)

Also unskip the FK mismatch test that was blocked on the builder
implementation (foreignKey() is no longer a no-op).

Co-authored-by: Cursor <[email protected]>
Fixes bugs and improves robustness across the referential actions implementation:

- Fix noAction verification false mismatch (normalize noAction ↔ undefined)
- Fix composite FK introspection Cartesian product (use pg_catalog positional pairing)
- Wire validateStorageSemantics into validateContract pipeline
- Set indexOrConstraint on FK action mismatch issues for correct planner conflict classification
- Add setDefault validation for non-nullable columns without DEFAULT
- Tighten PG_REFERENTIAL_ACTION_MAP keys to PgReferentialActionRule union type
- Add runtime assertions in buildForeignKeySql and mapReferentialAction
- Add onDelete/onUpdate to BuildStorageTable type
- Deduplicate Arktype schemas between sql-contract and contract-ts
- Extract ForeignKeyOptions named type for FK option signatures
- Migrate table-builder foreignKey() to use ifDefined
- Strip noAction during canonicalization for hash stability
- Report both onDelete and onUpdate mismatches simultaneously
@linear

linear Bot commented Feb 20, 2026

Copy link
Copy Markdown

@coderabbitai

coderabbitai Bot commented Feb 20, 2026 •

Copy link
Copy Markdown
Contributor

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

Walkthrough

Adds Postgres-first support for configurable foreign-key referential actions (onDelete/onUpdate): types, builder/factory APIs, canonicalization, semantic validators, planner DDL emission, introspection mapping, verification checks, tests, and docs.

Changes

Cohort / File(s) Summary
Planning & Architecture
agent-os/specs/2026-02-20-postgres-referential-actions/planning/requirements.md, agent-os/specs/2026-02-20-postgres-referential-actions/spec.md, agent-os/specs/2026-02-20-postgres-referential-actions/tasks.md, docs/architecture/adrs/ADR 162 - Referential actions for foreign keys.md
New planning, spec, tasks and ADR describing scope, API shape, canonicalization rules, planner/introspection behavior, testing strategy, and acceptance criteria (Postgres-first).
Core types & IR
packages/1-framework/2-authoring/contract/src/builder-state.ts, packages/2-sql/1-core/contract/src/types.ts, packages/2-sql/1-core/schema-ir/src/types.ts
Add ReferentialAction and ForeignKeyOptions; extend ForeignKey/SqlForeignKeyIR to optionally include onDelete and onUpdate.
Public exports & README
packages/1-framework/2-authoring/contract/src/index.ts, packages/2-sql/1-core/contract/src/exports/types.ts, packages/2-sql/1-core/contract/README.md, packages/2-sql/1-core/schema-ir/src/exports/types.ts
Export new types (ForeignKeyOptions, ReferentialAction, ForeignKeysConfig) and update README docs to describe foreignKeys config and referential actions.
Builder & Factory APIs
packages/1-framework/2-authoring/contract/src/table-builder.ts, packages/2-sql/1-core/contract/src/factories.ts, packages/2-sql/2-authoring/contract-ts/src/contract-builder.ts, packages/2-sql/2-authoring/contract-ts/src/contract.ts
Extend foreignKey builder and fk factory to accept options with onDelete/onUpdate and propagate them into the built contract/storage; adjust FK schema usage.
Validation & Semantic checks
packages/1-framework/1-core/migration/control-plane/src/emission/canonicalization.ts, packages/2-sql/1-core/contract/src/validators.ts, packages/2-sql/1-core/contract/src/validate.ts
Omit 'noAction' in canonicalization for hash stability; add ReferentialActionSchema and validateStorageSemantics to detect runtime-invalid FK action combinations and invoke semantic checks during contract validation.
Schema verification
packages/2-sql/3-tooling/family/src/core/schema-verify/verify-helpers.ts, packages/2-sql/3-tooling/family/test/schema-verify.helpers.ts, packages/2-sql/3-tooling/family/test/schema-verify.referential-actions.test.ts
Compare referential actions during verification (normalize noAction as absent), emit foreign_key_mismatch on differences, and add unit tests for match/mismatch/omission scenarios.
Postgres planner & DDL
packages/3-targets/3-targets/postgres/src/core/migrations/planner.ts, packages/3-targets/3-targets/postgres/test/migrations/planner.referential-actions.test.ts, packages/3-targets/3-targets/postgres/README.md
Introduce buildForeignKeySql and REFERENTIAL_ACTION_SQL mapping to emit ON DELETE/ON UPDATE clauses; add planner tests and update Postgres README.
Postgres introspection (control-adapter)
packages/3-targets/6-adapters/postgres/src/core/control-adapter.ts, packages/3-targets/6-adapters/postgres/test/control-adapter.test.ts
Extend introspection query to return delete_rule/update_rule, map DB rules to canonical SqlReferentialAction, and expose onDelete/onUpdate in introspected FK IR; add tests.
Contract & tooling tests
packages/1-framework/2-authoring/contract/test/table-builder.test.ts, packages/2-sql/1-core/contract/test/factories.test.ts, packages/2-sql/1-core/contract/test/validators.test.ts
Add unit tests validating builder/factory propagation of referential actions and validator + semantic check coverage for action-related constraints.
End-to-end integration tests
test/integration/test/referential-actions.integration.test.ts, test/integration/test/family.schema-verify.integration.test.ts, test/integration/test/family.introspect.integration.test.ts, test/integration/test/runtime.test.ts
Add comprehensive E2E integration suite for introspection, verification, and mismatch detection; un-skip and adapt existing integration tests and adjust timeouts/resource handling.
Test infra & minor docs
packages/2-sql/3-tooling/family/README.md, packages/2-sql/3-tooling/family/src/core/schema-verify/verify-helpers.ts, packages/2-sql/3-tooling/family/test/...
Document verifier behavior for foreignKeys config and referential action checks; update test helpers to accept onDelete/onUpdate and adjust verification test helpers.
Canonicalization detail
packages/1-framework/1-core/migration/control-plane/src/emission/canonicalization.ts
Strip onDelete/onUpdate when value is 'noAction' in omitDefaults to keep contract hashes stable.

Note

🎁 Summarized by CodeRabbit Free

Your organization is on the Free plan. CodeRabbit will generate a high-level summary and a walkthrough for each pull request. For a comprehensive line-by-line review, please upgrade your subscription to CodeRabbit Pro by visiting https://app.coderabbit.ai/login.

Comment @coderabbitai help to get the list of available commands and usage tips.

Merge main into the referential-actions branch, combining:
- Per-FK constraint/index booleans (from main) with onDelete/onUpdate
  referential actions (from this branch)
- ForeignKey type now includes both constraint/index and onDelete/onUpdate
- Updated fk() factory and TableBuilder.foreignKey() to accept combined opts
- Fixed auto-merge artifacts: redundant type modifiers, misplaced schema
  fields, stale foreignKeys contract config
- Updated test expectations to include applyFkDefaults() output
@pkg-pr-new

pkg-pr-new Bot commented Feb 25, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

@prisma-next/runtime-executor

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/runtime-executor@168

@prisma-next/sql-runtime

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-runtime@168

@prisma-next/integration-kysely

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/integration-kysely@168

@prisma-next/extension-pgvector

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/extension-pgvector@168

@prisma-next/sql-orm-client

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-orm-client@168

@prisma-next/contract-authoring

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/contract-authoring@168

@prisma-next/contract-psl

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/contract-psl@168

@prisma-next/contract-ts

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/contract-ts@168

@prisma-next/ids

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/ids@168

@prisma-next/cli

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/cli@168

@prisma-next/emitter

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/emitter@168

@prisma-next/eslint-plugin

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/eslint-plugin@168

@prisma-next/vite-plugin-contract-emit

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/vite-plugin-contract-emit@168

@prisma-next/sql-contract

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-contract@168

@prisma-next/sql-errors

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-errors@168

@prisma-next/sql-operations

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-operations@168

@prisma-next/sql-schema-ir

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-schema-ir@168

@prisma-next/sql-contract-ts

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-contract-ts@168

@prisma-next/sql-contract-emitter

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-contract-emitter@168

@prisma-next/family-sql

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/family-sql@168

@prisma-next/sql-lane-query-builder

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-lane-query-builder@168

@prisma-next/sql-relational-core

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-relational-core@168

@prisma-next/sql-lane

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-lane@168

@prisma-next/target-postgres

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/target-postgres@168

@prisma-next/adapter-postgres

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/adapter-postgres@168

@prisma-next/driver-postgres

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/driver-postgres@168

@prisma-next/postgres

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/postgres@168

@prisma-next/core-control-plane

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/core-control-plane@168

@prisma-next/core-execution-plane

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/core-execution-plane@168

@prisma-next/contract

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/contract@168

@prisma-next/operations

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/operations@168

@prisma-next/plan

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/plan@168

@prisma-next/utils

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/utils@168

commit: 1c28090

The test used onDelete: 'setNull' on a NOT NULL column, which is now
correctly rejected by validateStorageSemantics before schemaVerify runs.
Switch to onDelete: 'cascade' so the contract passes semantic validation
and the test can exercise the onUpdate mismatch path.
@jkomyno
jkomyno requested a review from wmadden February 25, 2026 15:31
@wmadden

wmadden commented Feb 25, 2026

Copy link
Copy Markdown
Contributor

Summary

PR 168 adds Postgres referential actions (ON DELETE / ON UPDATE) as first-class foreign-key attributes across contract typing/validation, authoring builders, Postgres introspection, schema verification, and Postgres migration DDL generation.

Review scope: origin/main...HEAD at 60f69d5a.

What looks solid

  • Contract & schema typing: ReferentialAction in the contract and SqlReferentialAction in schema IR are explicit unions, with optional onDelete/onUpdate on FK shapes (contract types, schema IR).
  • Structural validation: Arktype schema includes both onDelete and onUpdate (validators).
  • Authoring API ergonomics: .foreignKey(..., opts?) supports string (name) and options-object overload, carrying onDelete/onUpdate (builder; tests).
  • Introspection correctness: composite-FK positional pairing is handled via pg_constraint.confkey[kcu.ordinal_position], and referential actions are joined in from information_schema.referential_constraints (adapter query).
  • Semantic validation: rejects setNull on NOT NULL FK columns and setDefault on NOT NULL FK columns without DEFAULT (semantics; invoked during validation at validateContract).
  • Planner DDL mapping is explicit: a single mapping table plus conditional clause emission (planner; unit tests).

Blocking issues

1) Spec vs ADR/implementation semantics: omission (“defaults to NO ACTION”) vs “don’t compare”

  • Spec: frames omission as defaulting to Postgres NO ACTION (spec) and includes explicit noAction → ON DELETE NO ACTION rows in the DDL expectation table (spec).
  • ADR 162: explicitly chooses verifier semantics where omission means “don’t compare” (ADR).
  • Implementation + tests:
    • verifier only compares when contract explicitly specifies actions (verify helper; locked in by unit tests and integration).
    • canonicalization strips onDelete/onUpdate: 'noAction' for hash stability (canonicalization), which makes explicit noAction not durable in canonical emitted artifacts.

Why this blocks: it changes the contract’s authority. If omission means “default NO ACTION”, verification should fail against a DB FK with CASCADE/RESTRICT/.... If omission means “don’t care”, the spec should say so and acceptance criteria should not imply a defaulted, authoritative value.

2) Spec-required E2E coverage (DDL + runtime behavior) is missing

The spec and requirements require E2E tests that verify:

  • generated DDL contains correct clauses, and
  • runtime behavior matches the action semantics (cascade deletes, restrict errors, set-null, set-default, update cascades) (spec; requirements).

The current suite has strong unit (planner DDL) and integration (introspection + schema verification) coverage, but does not assert the DB-side behavioral outcomes for the referential-action matrix.

Non-blocking concerns

1) Planner supports explicit noAction, but canonicalization strips it

  • Planner will emit ON DELETE NO ACTION when onDelete: 'noAction' is present (planner; unit test).
  • Canonicalization strips explicit noAction (canonicalization).

If the expected workflow is “emit canonical contract.json → plan migrations from that”, then explicit noAction may be effectively unreachable. That’s fine if noAction is treated as an authoring-only alias, but it should be explicitly documented (and the spec’s “explicit noAction emits explicit DDL” table row should be revisited).

2) Spec/PR body mention “global foreignKeys config”, but the authoring API present is foreignKeyDefaults(...)

The branch uses foreignKeyDefaults({ constraint, index }) in the contract-ts builder and integration tests (builder; integration). The spec prerequisites describe global foreignKeys.constraints/indexes config (spec).

Not a blocker for referential actions themselves, but it’s worth aligning wording and examples to the actual API names used on this branch.

Nits (optional)

  • None.

Acceptance-criteria traceability

From spec acceptance criteria:

  1. ForeignKey IR type includes optional onDelete and onUpdate
  1. .foreignKey() builder accepts onDelete and onUpdate
  1. Postgres planner emits ON DELETE / ON UPDATE in DDL when specified
  1. Unit tests cover referential actions
  1. Introspection populates referential actions; verification compares them
  1. E2E verifies generated DDL and runtime behavior

@wmadden

wmadden commented Feb 25, 2026

Copy link
Copy Markdown
Contributor

System Design Review — PR 168: Referential actions for foreign keys (re-evaluation)

Scope

This review focuses on the cross-layer design: contract authoring/validation → canonicalization/hashing → schema IR + introspection → verification → Postgres DDL generation.

Architecture fit

This aligns well with the repo’s contract-first design:

  • Contract-first: actions are explicit contract fields (ForeignKey.onDelete/onUpdate), not inferred.
  • Feedback before execution: semantic validation rejects known-impossible configurations early (validateStorageSemantics).
  • Thin core, fat targets: mapping to Postgres ON DELETE/ON UPDATE is in the Postgres target planner, while schema/contract stay in SQL-family core.

End-to-end responsibility split (as implemented)

  • Contract typing + structural validation:

    • ReferentialAction + optional FK fields in SQL contract types (types, Arktype schema).
    • Schema IR adds SqlReferentialAction and optional onDelete/onUpdate (schema IR).
  • Authoring surfaces:

    • Framework table builder accepts the third-arg overload (string name OR options object) and stores onDelete/onUpdate (table builder).
  • Validation:

    • Semantic validation for setNull/setDefault constraints lives in sql-contract validators and is invoked during contract validation (validators, validateContract).
  • Canonicalization / hash stability:

    • Canonicalization strips explicit noAction for hash stability (canonicalization).
  • Target-specific (Postgres):

    • Introspection reads delete_rule/update_rule via information_schema.referential_constraints and maps rules into schema IR while omitting NO ACTION to keep IR sparse (introspection query, mapping).
    • DDL generation appends ON DELETE / ON UPDATE clauses when present (planner).
  • Verification:

    • Schema verification compares referential actions only when the contract explicitly specifies them (verifier).

What looks solid

  • Correct composite-FK introspection approach: positional pairing via pg_catalog.pg_constraint.confkey[kcu.ordinal_position] avoids the multi-column Cartesian-product bug (query).
  • Strong early feedback: semantic validation for setNull/setDefault catches invalid setups before planning/applying (validators).
  • Single, explicit mapping tables:
    • Postgres planner mapping (ReferentialAction → SQL keyword) is a simple, auditable table (planner).
    • Postgres introspection mapping (delete_rule/update_rule → IR) is likewise explicit and throws on unknown rules (adapter).

Design risks / clarifications needed

1) Meaning of “omitted” referential actions (default vs “don’t care”)

  • The spec states omission “defaults to undefined (Postgres default: NO ACTION)” (spec).
  • ADR 162 explicitly chooses verification semantics where omission means “don’t compare” (ADR).
  • The verifier matches the ADR: it only compares when the contract specifies onDelete/onUpdate (verifier).

This is a legitimate design choice, but it’s currently under-documented in the spec (and it materially changes what “contract-first” means for actions).

2) noAction round-tripping vs canonicalization + sparse IR

The system currently treats noAction as “default-equivalent” in multiple places:

  • Canonicalization strips onDelete/onUpdate: 'noAction' (canonicalization).
  • Introspection omits NO ACTION by returning undefined for the schema IR (adapter).

That’s defensible (keeps IR sparse and hashes stable), but it implies noAction is effectively an authoring-time alias, not a durable, emitted artifact value. If that’s intended, it should be documented as such in the spec and in the planner expectations.

3) E2E/runtime behavior testing is still missing relative to spec

The spec and requirements call for E2E coverage that verifies:

  • the generated migration plan contains the expected ON DELETE / ON UPDATE clauses, and
  • the database actually enforces cascade/restrict/set-null/set-default behaviors at runtime (spec, requirements).

The current change set has strong unit + integration tests for DDL text and introspection/verification, but does not include an end-to-end runtime-behavior test harness for the action matrix.

Overall assessment

The layering is good and the implementation is coherent across contract → IR → introspection → verification → DDL. The remaining work is primarily semantic/documentation convergence (default vs “don’t care” + noAction as alias) and closing the spec-mandated E2E/runtime behavior gaps so the lifecycle is truly “complete.”

jkomyno and others added 4 commits February 25, 2026 20:21
Address wmadden's PR #168 review feedback:

- Clarify that omission means "don't compare" for verification, not
  "defaults to NO ACTION". The ADR and implementation already follow
  this semantic; the spec lagged behind.
- Document `noAction` as an authoring-time alias stripped during
  canonicalization — it never appears in canonical contract.json.
- Fix API naming: use `foreignKeyDefaults()` instead of
  "global foreignKeys.constraints / foreignKeys.indexes".
- Add notes column to DDL expectations table explaining the noAction
  row only applies pre-canonicalization.
… actions

Address wmadden's PR #168 review feedback (blocking issue #2):

- Add DDL generation test: verifies the planner outputs ON DELETE CASCADE
  and ON UPDATE RESTRICT clauses when planning from a contract with
  referential actions against an empty database.
- Add runtime behavior tests for all five ON DELETE actions:
  CASCADE (removes children), RESTRICT (blocks delete), SET NULL
  (nullifies FK), SET DEFAULT (applies default), NO ACTION (blocks).
- Add ON UPDATE CASCADE test: propagates PK changes to children.

These tests close the spec-mandated E2E coverage gap for the referential
action matrix (spec lines 158-203, acceptance criteria #5-#6).

@wmadden wmadden left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good @jkomyno , you addressed all the blocking issues in my review 💯

@jkomyno
jkomyno merged commit 5226dca into main Feb 26, 2026
11 checks passed
@jkomyno
jkomyno deleted the feat/referential-actions branch February 26, 2026 15:25
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants