Repository navigation
TML-2861: emit ::jsonb / ::json cast on Postgres JSON column defaults - #763
Conversation
The Postgres planner's `renderDefaultLiteral` had explicit handling for jsonb / json column defaults: it emitted `'<json>'::jsonb` (or `::json`) so the cast was part of the DDL, not relying on Postgres's implicit text → jsonb coercion at default-evaluation time. The slice-4 lowering refactor moved default rendering into `DdlColumnDefaultVisitor.literal` on the adapter renderer — and that visitor saw only the `LiteralColumnDefault` node, with no column-type context, so it couldn't make the cast decision. Emitted DDL silently dropped the cast. Postgres accepts both forms (the implicit coercion fires at default-eval time, so tables still work), but the form change is user-visible in emitted `migration.ts` and was an unintended slice-4 substrate gap surfaced by the e2e `ddl.test.ts` snapshot in PR #760. Fix: - Widen `DdlColumnDefaultVisitor<R>` (`relational-core/ast/ddl-types.ts`) to take a `DdlColumnRenderContext` second arg. Today the context carries only the parent column's `nativeType`; the field is named so additional context can join without re-shaping the interface. - `DdlColumnDefault.accept(visitor, ctx)` and both concrete subclasses' `accept` overrides forward the ctx to the visitor methods. - The Postgres adapter renderer's `defaultVisitor.literal` uses `ctx.nativeType` to decide: jsonb → append `::jsonb`; json → append `::json`; everything else stays cast-free. `renderColumn` passes `{ nativeType: column.type }` to `accept`. - The SQLite adapter renderer's `defaultVisitor` accepts the new ctx and ignores it — SQLite has no jsonb / json column type so the cast decision doesn't apply, but the visitor interface requires it for cross-dialect symmetry. - Restore the e2e `ddl.test.ts` snapshot to include the `::jsonb` casts on the `metadata` and `tags` columns. The cosmetic `NOT NULL DEFAULT (...)` column-clause ordering (introduced by #751) stays — that's a separate cosmetic change with no semantic implication. Tests: - 4 new regression-pin tests in `ddl-create-table-lowering.test.ts`: `::jsonb` on jsonb-column literal defaults, `::json` on json-column literal defaults, no cast on non-JSON column types (text/int/bool/null/ even array-shaped values on non-JSON columns), no cast on jsonb-column function defaults (a `DEFAULT (jsonb_build_object(...))` already returns jsonb; the cast is only needed for string-shaped JSON literals). - Existing "escapes single quotes in JSON-object literal defaults" test strengthened to assert the full form with cast (was using `toContain` against a substring that happened to be a prefix of the new output — the test passed silently, hiding the regression). Verification (worktree-local): - `@prisma-next/sql-relational-core` test: 331/331. - `@prisma-next/target-postgres` test: 272/272. - `@prisma-next/adapter-postgres` test: 571/575 (4 expected-fail; the 4 new tests count toward the 571). - `@prisma-next/target-sqlite` test: 111/111. - `@prisma-next/adapter-sqlite` test: 178/178. - `@prisma-next/e2e-tests` framework test: 105/105 (with the updated snapshot — casts restored). - `pnpm lint:deps`: clean. - `pnpm fixtures:check`: clean (no extension-migration drift). Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
…t-cast Signed-off-by: Will Madden <[email protected]> # Conflicts: # test/e2e/framework/test/ddl.test.ts
|
Warning Review limit reached
More reviews will be available in 25 minutes and 21 seconds. Learn how PR review limits work. Your organization has run out of usage credits. Purchase more in the billing tab. ⌛ How to resolve this issue?After more reviews become available, a review can be triggered using the We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans include higher PR review limits than trial, open-source, and free plans. In all cases, reviews become available again over time. During sustained high-volume PR review activity, CodeRabbit may temporarily slow when the next review becomes available. Please see our Fair Usage Limits Policy for further information. ℹ️ Review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yml Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (1)
📝 WalkthroughWalkthroughThe PR extends the column default visitor pattern to thread render-time context (native type information) through the visitor chain. PostgreSQL uses this context to conditionally emit explicit type casts for quoted-literal defaults on non-text-like columns, while SQLite adapts to the new interface. E2E tests confirm the new DDL output includes appropriate type casts. ChangesColumn Default Visitor Context and Type Casting
🎯 3 (Moderate) | ⏱️ ~22 minutes
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
@prisma-next/extension-author-tools
@prisma-next/mongo-runtime
@prisma-next/family-mongo
@prisma-next/sql-runtime
@prisma-next/family-sql
@prisma-next/extension-arktype-json
@prisma-next/middleware-cache
@prisma-next/mongo
@prisma-next/extension-paradedb
@prisma-next/extension-pgvector
@prisma-next/extension-postgis
@prisma-next/postgres
@prisma-next/sql-orm-client
@prisma-next/sqlite
@prisma-next/extension-supabase
@prisma-next/target-mongo
@prisma-next/adapter-mongo
@prisma-next/driver-mongo
@prisma-next/contract
@prisma-next/utils
@prisma-next/config
@prisma-next/errors
@prisma-next/framework-components
@prisma-next/operations
@prisma-next/ts-render
@prisma-next/contract-authoring
@prisma-next/ids
@prisma-next/psl-parser
@prisma-next/psl-printer
@prisma-next/cli
@prisma-next/cli-telemetry
@prisma-next/emitter
@prisma-next/migration-tools
prisma-next
@prisma-next/vite-plugin-contract-emit
@prisma-next/mongo-codec
@prisma-next/mongo-contract
@prisma-next/mongo-value
@prisma-next/mongo-contract-psl
@prisma-next/mongo-contract-ts
@prisma-next/mongo-emitter
@prisma-next/mongo-schema-ir
@prisma-next/mongo-query-ast
@prisma-next/mongo-orm
@prisma-next/mongo-query-builder
@prisma-next/mongo-lowering
@prisma-next/mongo-wire
@prisma-next/sql-contract-emitter
@prisma-next/sql-contract-psl
@prisma-next/sql-contract-ts
@prisma-next/sql-lane-query-builder
@prisma-next/sql-relational-core
@prisma-next/sql-builder
@prisma-next/sql-contract
@prisma-next/sql-errors
@prisma-next/sql-operations
@prisma-next/sql-schema-ir
@prisma-next/target-postgres
@prisma-next/target-sqlite
@prisma-next/adapter-postgres
@prisma-next/adapter-sqlite
@prisma-next/driver-postgres
@prisma-next/driver-sqlite
commit: |
size-limit report 📦
|
::jsonb / ::json cast on Postgres JSON column defaults
| // JSON object/array literal → explicit `::<jsonb|json>` cast so the | ||
| // emitted DDL matches the column type without relying on Postgres's | ||
| // implicit text → jsonb coercion at default-evaluation time. Matches | ||
| // the pre-#751 planner-side `renderDefaultLiteral` behaviour for | ||
| // jsonb / json columns. For other columns whose underlying value is | ||
| // an object/array, fall back to a quoted literal — the column type | ||
| // decides. |
There was a problem hiding this comment.
No transient project references in code
| const json = `'${escapeLiteral(JSON.stringify(value))}'`; | ||
| if (ctx.nativeType === 'jsonb' || ctx.nativeType === 'json') { | ||
| return `DEFAULT ${json}::${ctx.nativeType}`; | ||
| } | ||
| return `DEFAULT ${json}`; |
There was a problem hiding this comment.
Why does JSON, specifically, need special handling? Won't this cast be required for any native type that isn't a string, boolean or simple number?
Two review findings on the earlier commit, both addressed here. Generalize the cast rule (review at line 110). The earlier change special-cased `jsonb` / `json`. But the same logic applies to ANY non-text column type whose implicit text → target coercion is missing or fragile — uuid, tstzrange, date, timestamptz, citext, enums, user-defined types, geometry/geography, array types. The generalized shape: any string-shaped literal default (a string, or a JSON object / array serialised as JSON) emits an explicit `::<nativeType>` cast, UNLESS the column type is text-shaped (text / varchar / character / char and their parameterised forms), where the cast would be a no-op. Numeric, boolean, and null literals are typed by Postgres directly (no `text` indirection) so they need no cast. Drop the transient project attribution (review at line 105). The earlier comment said "Matches the pre-#751 planner-side `renderDefaultLiteral` behaviour for jsonb / json columns" — that's prose attribution to a prior change, exactly the pattern the `no-transient-project-ids-in-code` rule names as forbidden ("post-M2 follow-up", "out of scope per the spec", "deferred per project plan"). Rewritten to describe what the code does, without referring to historical state. Same applies to the test names — dropped the `(TML-2861)` decorations; tests now name the behaviour they pin (per the rule's "name the property the test pins" guidance). Test coverage expanded to match the generalized rule: - string literal on `uuid` / `tstzrange` / `date` columns gets an explicit `::<nativeType>` cast (the non-trivial cases the original jsonb/json fix missed). - string literal on text-shaped columns (`text`, `varchar(N)`, `character varying(N)`, `char(N)`, `character(N)`) stays cast-free. - numeric / boolean / null literals stay cast-free regardless of column type (including null on a non-text column). - function defaults stay cast-free — a `DEFAULT (expr)` already returns the column type. The existing jsonb-with-quoted-JSON test stays as before — `jsonb` is non-text, so the generalized rule still emits `::jsonb`. The e2e `ddl.test.ts` snapshot gains a `::timestamptz` cast on the `scheduled_at` column (string literal on a non-text column); all other snapshot lines are unchanged. Verification (worktree-local): - `@prisma-next/sql-relational-core` test: 331/331. - `@prisma-next/target-postgres` test: 272/272. - `@prisma-next/adapter-postgres` test: passes (intermittent Test/Hook-timed-out-in-100ms environmental flakes on parallel runs surfaced 3-6 failures across two runs — different tests each time, all timeouts, none related to this diff). - `@prisma-next/target-sqlite` test: 111/111. - `@prisma-next/adapter-sqlite` test: 178/178. - `pnpm lint:deps`: clean. - `pnpm fixtures:check`: clean. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
|
Honest answer: the rule is Concrete proposal:
Allowlist: Filing as a follow-up ticket unless you want it bundled — small script, easy either way. |
…pt signature
`DdlColumnDefault.accept` now requires a `DdlColumnRenderContext` second
argument; the in-package visitor test was on the old one-arg signature
and broke `pnpm typecheck` on CI. Pass `{ nativeType: 'text' }` (any
text-shaped type works — the test asserts the visitor dispatches, not
the renderer output).
Co-Authored-By: Claude Opus 4.8 <[email protected]>
Signed-off-by: Will Madden <[email protected]>
At a glance
A Postgres
jsonbcolumn with a JSON-object default. Before this PR, the migration planner emits:After:
The difference is the
::jsonbcast on the default literal. Same change applies tojsoncolumns (emits::json); non-JSON column types are unaffected.Why it matters
Without the cast, Postgres infers the literal's type as
textat parse time, then applies an implicittext → jsonbcoercion at default-evaluation time (every time a row is inserted without ametadatavalue). Two consequences:::jsonbcast pins the intent.jsonb/json(because Postgres special-cases them), but the same pattern breaks for types likexmlor user-defined types where no implicit cast exists. Emitting the explicit cast is the form that generalises.This is a one-line shift in emitted DDL, not a behaviour change at the table level — existing tables continue to work, the implicit coercion still fires for them. The fix is about the form of newly-emitted migration files.
The decision
The renderer that turns the DDL AST into SQL strings runs per-column-default, dispatched through a visitor. Today the visitor signature is:
literalreceives the default value but not the column it belongs to — so it can't see that the parent column's type isjsonband therefore can't decide to emit the cast.The chosen fix: widen the visitor with a render-context second argument that carries the parent column's native type.
DdlColumnDefault.accept(visitor, ctx)and both concrete subclasses (LiteralColumnDefault,FunctionColumnDefault) forward the context.The Postgres adapter's
renderColumnalready hascolumn.typein scope at the call site, so passing it through is a one-line change:The Postgres
defaultVisitor.literalthen keys offctx.nativeTypefor the cast decision; the SQLite visitor accepts the context and ignores it (SQLite has nojsonb/jsontypes).What changed
relational-core/src/ast/ddl-types.ts— introducesDdlColumnRenderContext, widens the visitor interface andDdlColumnDefault.acceptsignature, forwards the context from both concrete*ColumnDefault.acceptoverrides.packages/3-targets/6-adapters/postgres/src/core/ddl-renderer.ts) —defaultVisitor.literalusesctx.nativeTypeto decide:jsonb→ append::jsonb;json→ append::json; everything else stays cast-free.renderColumnpasses the context toaccept.packages/3-targets/6-adapters/sqlite/src/core/ddl-renderer.ts) — visitor signatures take and ignore the new context;renderColumnpasses{ nativeType: column.type }for symmetry.ddl.test.tssnapshot —metadataandtagscolumns now include the::jsonbcast.The user-facing
lit(value)builder is unchanged. The pairing of value + column happens at render time, where the column type lives, rather than upstream where users hand-writelit(...)calls.Test coverage
Four new regression-pin tests in
ddl-create-table-lowering.test.ts:jsonb-column literal default emits::jsonb.json-column literal default emits::json.text/int/bool/null, and an array-shaped value on atextcolumn (the renderer keys off the column's nativeType, not the value shape).jsonb-column function defaults stay cast-free — aDEFAULT (jsonb_build_object(...))already returnsjsonb; the cast is only relevant for string-shaped JSON literals.One existing test was strengthened: "escapes single quotes in JSON-object literal defaults" used
toContainagainst a substring that was a prefix of the new output, so it passed silently without the cast. Now it asserts the full form with cast.Verification
@prisma-next/sql-relational-coretest@prisma-next/target-postgrestest@prisma-next/adapter-postgrestest@prisma-next/target-sqlitetest@prisma-next/adapter-sqlitetest@prisma-next/e2e-testsframework testpnpm lint:depspnpm fixtures:checkScope
5 files,
+127 / −28. One framework substrate file (the visitor interface); two adapter renderers; one new-tests file; one e2e snapshot.Alternatives considered
JsonbColumnDefault,JsonColumnDefault). The visitor would gainjsonbLiteral/jsonLiteralmethods. Rejected because the choice of node kind would have to be made upstream — but the natural choice point islit(value)in user code, which has no column-type context. Pushing the decision into the planner's*Spec → DdlColumnmapping would work, but at the cost of fragmenting the literal AST surface for a dispatch the renderer is the natural home for.renderColumnafter the visitor returns, by inspecting the rendered string. Rejected because the visitor already encapsulates the "how to render a default" logic; reaching into its output from outside breaks that encapsulation, and parsing rendered SQL to decide whether to append a suffix is the kind of thing that bites you later.Linear
Closes TML-2861. Surfaced during PR #760's e2e snapshot review.
🤖 Generated with Claude Code
Summary by CodeRabbit
::jsonb,::timestamptz) for non-text-shaped column types in generated schemas. Type casts are omitted for text-shaped types and for numeric/boolean/null literal defaults.