Repository navigation
feat(sql): add referential actions for foreign keys - #168
Conversation
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
|
Note Reviews pausedIt 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 Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
WalkthroughAdds 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
Note 🎁 Summarized by CodeRabbit FreeYour 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 |
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
@prisma-next/runtime-executor
@prisma-next/sql-runtime
@prisma-next/integration-kysely
@prisma-next/extension-pgvector
@prisma-next/sql-orm-client
@prisma-next/contract-authoring
@prisma-next/contract-psl
@prisma-next/contract-ts
@prisma-next/ids
@prisma-next/cli
@prisma-next/emitter
@prisma-next/eslint-plugin
@prisma-next/vite-plugin-contract-emit
@prisma-next/sql-contract
@prisma-next/sql-errors
@prisma-next/sql-operations
@prisma-next/sql-schema-ir
@prisma-next/sql-contract-ts
@prisma-next/sql-contract-emitter
@prisma-next/family-sql
@prisma-next/sql-lane-query-builder
@prisma-next/sql-relational-core
@prisma-next/sql-lane
@prisma-next/target-postgres
@prisma-next/adapter-postgres
@prisma-next/driver-postgres
@prisma-next/postgres
@prisma-next/core-control-plane
@prisma-next/core-execution-plane
@prisma-next/contract
@prisma-next/operations
@prisma-next/plan
@prisma-next/utils
commit: |
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.
SummaryPR 168 adds Postgres referential actions ( Review scope: What looks solid
Blocking issues1) Spec vs ADR/implementation semantics: omission (“defaults to NO ACTION”) vs “don’t compare”
Why this blocks: it changes the contract’s authority. If omission means “default NO ACTION”, verification should fail against a DB FK with 2) Spec-required E2E coverage (DDL + runtime behavior) is missingThe spec and requirements require E2E tests that verify:
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 concerns1) Planner supports explicit
|
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 fitThis aligns well with the repo’s contract-first design:
End-to-end responsibility split (as implemented)
What looks solid
Design risks / clarifications needed1) Meaning of “omitted” referential actions (default vs “don’t care”)
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)
|
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).
closes TML-1905
Goal
Add
ON DELETE/ON UPDATEreferential 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
What changed and why
Contract layer
ReferentialActionunion type and optionalonDelete/onUpdatefields toForeignKeyForeignKeyOptionsnamed type to reduce inline duplication across factory and builder signaturesReferentialActionSchemaandForeignKeySchema, shared betweensql-contractandcontract-ts(deduplication)setNullon non-nullable columns andsetDefaulton non-nullable columns without a DEFAULT are rejected at contract validation timeIntrospection
referential_constraintsfordelete_rule/update_rulepg_catalog.pg_constraint.confkey[ordinal_position]instead ofconstraint_column_usage(which produced Cartesian products for multi-column FKs)NO ACTION(the database default) maps toundefinedin the sparse Schema IRMigration planner
buildForeignKeySqlemitsON DELETE/ON UPDATEclauses with runtime assertions for unknown action valuesSchema verification
verifyForeignKeyscompares referential actions after structural match, reporting both onDelete and onUpdate mismatches simultaneouslynoActionis normalized toundefinedbefore comparison, so explicitnoActionin a contract passes against a database using the defaultNO ACTIONCanonicalization
noActionis stripped during canonicalization for hash stability (explicitnoActionand omitted produce the samestorageHash)Docs & specs
Summary by CodeRabbit
New Features
Validation
Documentation
Tests