Skip to content

TML-3288: Index, check and policy SQL is written as a sql literal - #30550

Merged
wmadden-electric merged 244 commits into
mainfrom
tml-3288-sql-expression-places
Oct 8, 2026
Merged

wmadden-electric merged 244 commits into
mainfrom
tml-3288-sql-expression-places

Conversation

@wmadden-electric

@wmadden-electric wmadden-electric commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

Linked issue

Refs TML-3288, the third slice of the Linear project SQL expression literals. Records the decision as ADR 268.

Summary

Raw SQL in a Prisma 8 schema is now written one way everywhere: as a sql literal. Index predicates and expressions, full-text index predicates, check expressions and policy predicates take the same literal @default already took, and refuse a quoted string with a message that gives the rewrite.

At a glance

Before this PR, raw SQL outside @default was a quoted string full of \":

model Profile {
  id         String    @id @default(sql`gen_random_uuid()`)
  userId     String
  archivedAt DateTime?

  @@index([userId], where: "\"archivedAt\" IS NULL", name: "profile_user_active")
  @@check(expression: "char_length(\"userId\") > 0", name: "profile_user_id_present")
}

After it, every place takes the same sql literal as @default:

model Profile {
  id         String    @id @default(sql`gen_random_uuid()`)
  userId     String
  archivedAt DateTime?

  @@index([userId], where: sql`"archivedAt" IS NULL`, name: "profile_user_active")
  @@check(expression: sql`char_length("userId") > 0`, name: "profile_user_id_present")
}

policy_update profile_owner_write {
  target    = Profile
  roles     = [authenticated]
  using     = sql`"userId"::uuid = auth.uid()`
  withCheck = sql`"userId"::uuid = auth.uid()`
}

A quoted string in any of these places is refused, and the message gives the literal to write:

PSL_VALUE_TYPE_INCOMPATIBLE: Expected sql`...`; write sql`"archivedAt" IS NULL`

A codemod in the upgrade instructions rewrites an existing schema:

node scripts/rewrite-sql-strings.mjs '**/*.prisma'

Decision

Raw SQL is a value of one data type, sql/expression, and every place that holds raw SQL says it receives that type. The SQL family registers the type with the tag sql and declares that nothing converts into it. So the general rule that admits a written value, the one that refuses @default("abc") on an Int column, admits only a sql literal in these places and refuses a quoted string, a number or a boolean. There is no separate "strings not allowed" check, and Prisma never parses the SQL inside the literal.

The places are @@index(where:), @@index(expression:), @@fullTextIndex(where:), @@check(expression:), and a policy's using and withCheck. @default already took sql literals and keeps its own checks on the text (no ;, no SELECT, and so on); the other places check nothing, because a row-level-security predicate often holds EXISTS (SELECT ...).

ADR 268 records the decision and its rejected alternatives. ADRs 129, 231, 234, 236, 243, 244, 249, 254 and 262 are amended to match.

How it fits together

  1. A sql literal is a value of a data type. TML-3296: sql is the tag of the SQL family's data type sql/expression #30534 made sql/expression a data type the SQL family owns. TML-3367: Attribute arguments declare the data type they receive #30539 (shipped in rc.16) built dataTypeValue, an argument type that admits a written value by the conversion rule and reports a refusal at the value.
  2. Each place names the type it receives. indexModelSpec, checkModelSpec, postgresFullTextIndexSpec and the three policy specs now build dataTypeValue(SQL_EXPRESSION_DATA_TYPE_ID, ctx.dataTypes) from their spec context. For the policy predicates this needs the block spec context to carry the stack's data types: BlockSpecContext is now { symbols, dataTypes }, filled on every path that binds a block (the SQL and Mongo interpreters, the binder, the language server).
  3. The conversion rule does the refusing. A quoted string is a text value; sql/expression converts from nothing; the general refusal fires. Because the receiving type has a tag, the message adds the exact literal to write, when that literal would read back as the same text.
  4. The contract stores the canonical text. Reading a literal removes indentation shared by every line, blank lines at the start and end, carriage returns and whitespace-only lines. This PR fixes one detail of that rule from TML-3296: sql is the tag of the SQL family's data type sql/expression #30534, which removed only one blank line at each end and so was not stable when applied twice. Contracts do not change shape: Index.where, CheckConstraint.expression and the policy predicates stay strings. Every fixture in the repository emits an identical contract.json.
  5. Names do not change. Index, check and policy names end in a hash of their SQL, and that hash already ignores everything canonicalization removes. A user's raw SQL that was not canonical changes its stored text once, and so the storage hash once; what migration plan then does is in "Compatibility" below.
  6. Writing back reads back. contract infer and contract print write these places as sql literals. printSqlExpressionLiteral throws for text that would read back changed, so no printer can produce it by accident. contract infer prints a Prisma-named object with its canonical text (same name) and skips an object named with map: or @@map whose text would not read back, with a note saying how to recover; contract print refuses it.
  7. Tools learn the form together. The editor completes sql at every argument that receives sql/expression, including a policy's using, and colours the literal; @@check( completes to check(expression: sql`${1:expression}`). The Supabase pack contract, examples/supabase, every .prisma fixture, the docs and the prisma-8 skill references move to the new form in this PR.

Compatibility, migration and risk

  • Schema authors (breaking): a quoted string in the six places is refused. Run the codemod from upgrade-instructions/pending/sql-expression-literals-psl/app/, or rewrite by hand as each message says. The fragment describes the change from rc.16.
  • Stored text may change once. For a Prisma-named index, check or policy, one migration plan records the new text and has no operations. An index or check named with map: makes migration plan stop with a conflict that asks for a migration written with migration new, which has no operations. A policy named with @@map is dropped and created again, because migration plan allows destructive operations. A planner test pins each case.
  • Extension authors: BlockSpecContext.dataTypes is required, and interpretExtensionBlocks, createBinder, createSqlBinder and createMongoBinder take dataTypes. ControlDefaultRegistries is deleted; a spec reads ctx.defaultFunctionRegistry and ctx.dataTypes. The SQL attribute spec factories all take the context. canonicalizeTaggedLiteralBody is exported from @internal/framework-components/authoring only. The extension fragment has the details.
  • contract print refuses an exact-named index, check or policy whose SQL would not read back, with CONTRACT.PRINT_UNSUPPORTED.

Reviewer notes

  • Largest diffs: contract-psl/src/sql-attribute-specs.ts and interpreter.ts, target-postgres/src/core/authoring.ts (full-text index and policies), the infer and print code under psl-build/, psl-infer/ and psl-print/, and the rewritten .prisma fixtures.
  • Unrelated change, kept on purpose: .claude/scripts/enforce-tools.mjs blocks agent shells from running the full integration and end-to-end suites locally, as Will asked. It came in with commits 0e83ea5e3f and ff0a677271. The second also fixes the codemod (an unclosed backtick no longer stops it skipping later // comments) and edits ADR 129, ADR 268 and the Supabase skill reference, although its title names only the hook.
  • Line comments: a body whose last line ends in a -- comment renders valid DDL since TML-3287: Raw SQL ending in a line comment renders valid DDL #30546; the new CLI journey now includes such a body.
  • Three tarball tests cannot run on the author's machine (pnpm install in their scratch project refuses @vercel/detect-agent as a trust downgrade). CI is the check for them.
  • Project files: projects/sql-expression-literals/ holds the spec, design, plan, review reports and status. It is deleted at project close-out.

Behavior changes and evidence

  • The six places take sql literals and refuse other literals. Evidence: contract-psl/test/interpreter.sql-expression-places.test.ts, target-postgres/test/psl-full-text-index.test.ts, psl-policy-predicates.test.ts, and the guard sql-expression-places.test.ts, which fails if a raw-SQL argument is written with str().
  • Block specs receive the stack's data types, including block value completion and block keyword snippets. Evidence: psl-parser/test/block-spec-context.test.ts, language-server/test/block-spec-context.test.ts, and completion-provider.test.ts, where using = | in a policy_select block offers sql on the real Postgres stack.
  • Names do not change for canonical text. Evidence: target-postgres/test/sql-expression-wire-names.test.ts.
  • Infer and print write sql literals and never one that reads back changed. Evidence: psl-infer/infer-sql-expression-literals.test.ts, psl-print/refusals-sql-text.test.ts, test/migrations/sql-text-canonical-planner.test.ts, and the CLI journeys sql-expression-literals.e2e.test.ts, infer-roundtrip-fidelity* and sign-the-database.
  • The codemod. Evidence: scripts/codemods/rewrite-sql-strings.test.mjs (each position, both quote kinds, escapes, comments, literals inside strings, the byte-identical fragment copies).

Testing performed

On the final head:

  • pnpm build, pnpm typecheck, pnpm lint, pnpm lint:deps, pnpm lint:casts (no increase), pnpm lint:throws (no increase), pnpm lint:skills, pnpm lint:framework-vocabulary, pnpm lint:rules:footprint, pnpm check:error-reference, pnpm fixtures:check (no contract.json change), pnpm test:scripts, and pnpm check:upgrade-coverage --mode pr against the merge base.
  • The package test files each change touches, and these integration files alone: the sql-expression-literals CLI journey (now with texts ending in a -- comment), lsp-sql-completion-in-blocks, test/authoring/**, test/psl-print/**, infer-roundtrip-fidelity*, sign-the-database, and the expression-index and RLS journeys. The full integration and end-to-end suites run in CI and the merge queue.
  • Every test added in the last review round was shown to fail with its defect planted.
  • Manual QA: the slice 2b script in projects/sql-expression-literals/manual-qa.md reads each new message as a user would; its expected column now quotes the current messages.
  • Three rounds of architect and code review, with every finding fixed or answered: projects/sql-expression-literals/slice-reviews/2b/, 2b-round-2/ and 2b-round-3/.

Alternatives considered

  • Accept quoted strings beside sql literals. Rejected: two ways to write one value, and the escaped quotes stay.
  • A "tagged literal" argument kind with its own error for quoted strings. Rejected: it describes syntax, not types; the conversion rule already refuses a value of another type, with one mechanism for every tag.
  • Apply @default's checks on SQL text to every place. Rejected: they refuse valid row-level-security predicates such as EXISTS (SELECT ...).
  • A separate typing step for policy values in the family interpreter. Rejected: block specs already parse values with the same building blocks as attributes, so a second mechanism would duplicate it.
  • Print text that does not read back and let verification report it. Rejected: a printed schema must emit the contract it came from.
  • Prefixed tags such as pg.sql. Rejected in TML-3296: sql is the tag of the SQL family's data type sql/expression #30534: the stack already names the target.

Skill update

The prisma-8 skill references contract.md, queries-postgres.md and supabase.md write raw SQL as sql literals. The breaking change for schema authors, with the codemod, is in upgrade-instructions/pending/sql-expression-literals-psl/.

Checklist

  • All commits are signed off (git commit -s) per the DCO.
  • I read CONTRIBUTING.md and the change is scoped to one logical concern, apart from the hook change named above.
  • Tests are updated.
  • The PR title is in TML-NNNN: <sentence-case title> form.
  • The Skill update section above is filled in.

Agent: hammurabi-31 (taking over from charon-96 and marconi-29)

🤖 Generated with Claude Code

Spec, design, plan, decisions, research and the status file for resuming
the work. Raw SQL in a schema is a value of the data type sql/expression.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…d literal printer

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…on data type slice

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
The cast rule already keeps the sql/expression entry out of literal defaults. Also corrects the wrapNamespaceBlock line reference in the design (F09).

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
The code now reports only a single value written on a list column, which is a refusal about shape, not about type.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
A cast and a list cast that throw are PSL_INVALID_LITERAL. Every refusal row now asserts its whole message.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
It reads the canonical value through sqlTextFromCanonical, as the six places in slice 2b will. The reserved-name message names the tag through SQL_EXPRESSION_TAG.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…s user

lowerTaggedLiteral lowered nothing any more, and its refusal had the type of a default-function result. The sql/expression code moves out of data-type-default.ts, which holds no per-type code.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
The sqlExpressionDataType doc comment points at ADR 254. sqlTextReadsBack moves to slice 2b, next to its caller. The authoring entry exports only printTaggedLiteral from tagged-literal; each other function is added in the slice that first imports it from there.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
The code comment, the entry documentation the editor shows, and ADR 254 said "SQL text", which would admit a statement or a query. The extensions doc no longer teaches a view query as a sql literal or describes the removed prefixed tags.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…nd text

ADR 129 is retitled "Tagged literals write values of data types" and no longer says a tag names the pack that owns the text. ADR 254 states the prefix rule once, by the owner of the data type, and ADR 129 and the index link to it. The body is what is written between the quotes; the text is the canonical value. ADR 254 now says @default reports its cast-rule codes at the attribute. The error reference drops "a list holding another list", which PSL cannot write.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
They used pg.sql and sqlite.sql, which no longer exist, as the example of a valid dotted tag.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
assertNothingCastsFromSqlExpression throws CONTRACT.DATA_TYPE_CASTS_FROM_SQL_EXPRESSION for a cast or a list cast from sql/expression. The family instance runs it on every data type the stack registers, so an extension cannot turn a sql literal into a value of another type. runtimeError is exported from the shared codec entry so shared-plane code can raise the same kind of error as stack assembly.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
For Postgres with every shipped extension pack, and for SQLite: the stack registers the family objects themselves, and no registered data type casts from sql/expression.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Deleting the adapter authoring tests removed the only tests of the Postgres and SQLite number classifiers, the boolean reader, and JSON and numeric read and print. The cases move to the targets, which own the entries; only the cases about lowering keys are dropped.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
… has it and owns its change id

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…k lines at both ends, and a sql literal has two escapes

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…f data types

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…fusal messages

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…journey in a -- line comment

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…est that drives the language server in a Postgres project

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
@wmadden-electric
wmadden-electric added this pull request to the merge queue Oct 8, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Oct 8, 2026
Brings TML-3466, TML-3382, TML-3475, TML-3476, TML-3512 and the one-config-file project. No conflicts and no released fragment touched; the semantic clashes are fixed in the commits that follow.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…pect a policy drop to be widening

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
@wmadden-electric
wmadden-electric added this pull request to the merge queue Oct 8, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Oct 8, 2026
Main's TML-3431 stores a Postgres full-text index as data and lets it span several weighted fields. The conflicts keep main's structure and this branch's rule that raw SQL is a sql literal of the data type sql/expression.

- postgres/src/core/authoring.ts: main's multi-field @@fullTextIndex spec and lowering. The spec is a function of the spec context again, so where: receives dataTypeValue(SQL_EXPRESSION_DATA_TYPE_ID, ctx.dataTypes), and lowering stores where through sqlTextFromCanonical.
- postgres/src/core/psl-print/model-attributes.ts: main's shared naming and full-text branch. The read-back refusal for an index's SQL texts now runs before the full-text branch, so it also covers a full-text index's where.
- postgres/test/psl-full-text-index.test.ts: main's tests, with where written as a sql literal; this branch's refusal tests for a plain-string, number or boolean where are kept.
- postgres/test/migrations/full-text-index-planning.test.ts: both sides' imports, since both are used.
- postgres/README.md and skills/prisma-8/references/contract.md: main's prose and weighted example, plus this branch's partial-index example with a sql literal; the README keeps the paragraph that every raw-SQL argument takes a sql literal, and its expression-index example is a sql literal.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…:) as a name, not SQL

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
@wmadden-electric
wmadden-electric added this pull request to the merge queue Oct 8, 2026
Merged via the queue into main with commit 7ae50f1 Oct 8, 2026
24 checks passed
@wmadden-electric
wmadden-electric deleted the tml-3288-sql-expression-places branch October 8, 2026 17:01
opensource-fork-sync Bot pushed a commit to cla7aye15I4nd/opensource-prisma__orm that referenced this pull request Oct 9, 2026
…s in PSL (prisma#30558)

## At a glance

```ts
import { check, defineContract, field, model, policyUpdate, rlsEnabled, role, sql } from '@prisma/orm-postgres/contract-builder';

const owner = sql`"userId"::uuid = auth.uid()`;

const Post = model('Post', { fields: { /* id, userId, title, archivedAt */ } }).sql(({ cols, constraints }) => ({
  indexes: [
    constraints.index([cols.userId], {
      name: 'post_user_active',
      where: sql`
        "archivedAt" IS NULL
          AND "userId" <> ''
      `,
    }),
  ],
  checks: [check({ expression: sql`length("title") > 0`, name: 'post_title_nonempty' })],
}));

export const contract = defineContract({
  models: { Post },
  entities: [
    rlsEnabled(Post),
    policyUpdate(Post, {
      name: 'post_owner_write',
      roles: [role('authenticated')],
      using: owner,
      withCheck: sql`${owner} AND "archivedAt" IS NULL`,
    }),
  ],
});
```

Every field that holds raw SQL takes a `sql` value. `where:
'"archivedAt" IS NULL'` no longer compiles. The contract this emits is
byte for byte the contract the same schema emits when written in PSL:

```prisma
@@index([userId], where: sql`
  "archivedAt" IS NULL
    AND "userId" <> ''
`, name: "post_user_active")
```

## Decision

In the TypeScript contract builder, raw SQL is a `SqlExpression`, made
with the `sql` template tag. Every builder field that holds raw SQL
accepts only that type:

- `constraints.index(...)`: `where` and `expression`
- `check(...)`: `expression`
- `fullTextIndex(...)`: `where`
- `policySelect`, `policyInsert`, `policyUpdate`, `policyDelete`,
`policyAll`: `using` and `withCheck`
- `.default(...)`, which already took `sql` values

A string in any of them is a type error. This is the TypeScript half of
[ADR
268](docs/architecture%20docs/adrs/ADR%20268%20-%20Raw%20SQL%20is%20a%20value%20of%20the%20data%20type%20sql-expression.md);
prisma#30550 did the PSL half.

## Why

**Contracts hold SQL that Prisma does not parse.** An index's `where`,
an expression index, a CHECK constraint, a row-level-security policy's
`using` and `withCheck`, and a raw column default are SQL text. The
contract stores the text, and the migration planner places it inside
DDL, such as `CREATE INDEX … WHERE (<text>)`.

**PSL writes that SQL as a `sql` literal, and cleans up its text.**
Since prisma#30550, every one of those places in PSL takes a `` sql`...` ``
literal and nothing else. A literal may span several lines, so PSL
canonicalizes its text before storing it: it removes the indentation
shared by every line, drops blank lines at the start and end, and
removes carriage returns. The indented PSL above stores `"archivedAt" IS
NULL\n AND "userId" <> ''`.

**A TypeScript string does not get that clean-up.** A template string
keeps its indentation and its surrounding blank lines. So the same SQL,
written in PSL and in TypeScript, stored different text in
`contract.json`, and the two contracts had different storage hashes.
[ADR
129](docs/architecture%20docs/adrs/ADR%20129%20-%20Template-Tagged%20Literals%20for%20Extensions.md)
promises that PSL and TypeScript emit identical contracts for the same
schema; multi-line SQL broke that promise.

**The `sql` tag canonicalizes with the same function PSL uses.** ``
sql`...` `` returns a `SqlExpression` whose `text` is canonical. The
`SqlExpression` constructor canonicalizes too, so no way of making a
value skips it. A NUL character or a text over 64 KiB throws
`CONTRACT.SQL_EXPRESSION_INVALID`, with the same message PSL gives.

**`sql` values compose; other values do not.** TypeScript contracts
reuse a predicate across policies, as `owner` does above. The tag
accepts other `sql` values inside `${…}` and joins their text in. Each
later line of an inserted value takes the indentation of the template
line it sits on, so the joined text is what the author sees, and the
result is canonicalized once more as a whole. Anything else inside
`${…}`, such as a string or a number, throws
`CONTRACT.SQL_EXPRESSION_INTERPOLATION`. This differs from the query
lane's `db.raw.sql`, which binds `${…}` values as query parameters:
contract SQL becomes DDL, and DDL has no parameters.

**`.default()` keeps the checks that only defaults need.** A default
must not be `now()` or `autoincrement()` written as raw SQL, and must
not contain `;`, a comment, `$$` or `SELECT`, because of how defaults
are rendered and compared. Those checks used to live in the tag. The tag
now also serves policies, whose predicates often hold `EXISTS (SELECT
…)`, so the checks moved into `.default()`, which throws
`CONTRACT.DEFAULT_INVALID`.

**JavaScript that is not type-checked still gets a clear error.** When
the builder turns a model into contract storage, it reads each raw-SQL
field through `requireSqlExpression`. Anything that is not a `sql` value
throws `CONTRACT.ARGUMENT_INVALID`, naming the object and the field:
``Policy "post_owner_write" using must be a sql`...` value.`` An unnamed
index is named by its model (`Index on "Post" where`), and an unnamed
full-text index by its fields (`Full-text index on fields "title",
"body" where`).

**A value from a second copy of the package still works.**
`SqlExpression` is a class, so a hand-written `{ text: 'x' }` is not
assignable to it. The class carries a `Symbol.for` marker, so a value
made by another installed copy of the package is still recognized.
`readSqlExpression` rebuilds such a value with this copy's constructor,
so its text is canonicalized too, in every field and inside `${…}`.

**`contract print` and `contract infer` handle defaults whose text would
not read back.** A default whose string constant holds, for example, a
carriage return would change if printed as a `sql` literal and read
back. `contract print` refuses such a default, as it already refuses
such an index or policy. `contract infer` still prints it, because a
skipped default would be dropped by the next migration, and adds a note
to check its string constants.

The contract format does not change. The contract still stores the text
as a string; only the builder's field types change.

## What changes for users

- **TypeScript contract authors:** wrap raw SQL in `` sql`…` ``. The
upgrade instructions in
`upgrade-instructions/pending/sql-expression-literals-ts/app/` list
every field. A text that was not canonical before, such as an indented
multi-line template string, is stored differently once, so the storage
hash changes once; the instructions say to run `migration plan` once.
Index, check and policy names do not change.
- **Error codes:** `CONTRACT.DEFAULT_SQL_INTERPOLATION` is replaced by
`CONTRACT.SQL_EXPRESSION_INTERPOLATION`;
`CONTRACT.SQL_EXPRESSION_INVALID` is new. Both are in the error
reference.
- **Extension authors:** policy handles and descriptors hold
`SqlExpression`. `sql`, `SqlExpression`, `isSqlExpression`,
`readSqlExpression` and `requireSqlExpression` come from
`@internal/sql-contract/sql-expression`; the contract-builder facades
re-export `sql` and the `SqlExpression` type. The SQL family registers
`sql/expression` through one value, `sqlExpressionRegistration`. See
`upgrade-instructions/pending/sql-expression-literals-ts/extension/`.
- **Unchanged:** migration files keep taking strings (TML-3297, the next
slice, lets them take `sql` values too). The deprecated `.defaultSql()`
and `.default({ kind: 'function', expression })` still take a string and
store it without canonicalization; TML-3286 removes `.defaultSql()` at
8.0.0.

## Where to look

- `packages/2-sql/1-core/contract/src/sql-expression.ts`: the class, the
tag, `readSqlExpression` and `requireSqlExpression`.
- `packages/2-sql/2-authoring/contract-ts/src/contract-dsl.ts` and
`contract-lowering.ts`: the field types, `.default()`, and reading each
field. In `contract-lowering.ts`, a `sql` value is checked before a
deferred index expression's `render`, because `'render' in someString`
throws a `TypeError`.
- `packages/3-extensions/postgres/src/contract/rls.ts` and
`full-text-index.ts`;
`packages/3-targets/3-targets/postgres/src/core/authoring.ts`: policies
and full-text indexes.
- `test/integration/test/authoring/parity/sql-expressions/`: the same
schema in PSL and TypeScript, with indented multi-line text, tab
indentation, a backslash, an escaped backtick, an interpolated predicate
holding a `--` comment, a multi-line predicate interpolated into an
indented `withCheck`, a full-text index with several weight groups, and
a raw default. The test checks both emit the same `contract.json`.
- Docs: ADR 268 and ADRs 129, 234, 236, 243, 244 and 254, the error
reference, the contract-ts README, and the `prisma-8` skill reference
`contract.md`.
- `projects/sql-expression-literals/` holds the project's spec, design,
plan, reviews, manual QA and status. It is deleted at project close-out.

## Testing performed

- `pnpm build`, `pnpm typecheck`, `pnpm lint`, `pnpm lint:deps`, `pnpm
lint:casts`, `pnpm lint:throws`, `pnpm check:error-reference`, `pnpm
lint:framework-vocabulary`, `pnpm lint:skills`, `pnpm fixtures:check`
(no `contract.json` change in any existing fixture), `pnpm
test:scripts`, and `pnpm check:upgrade-coverage --mode pr` against the
merge base.
- `pnpm test:packages`: everything passes except three tarball tests,
which cannot install a package on the author's machine because the npm
registry refuses it; CI runs them.
- Integration files run one by one: `test/authoring/**` (including the
parity fixture), `test/sql-builder/**`, `test/psl-print/**`, the RLS
tests, and the SQL expression literals CLI journey. The full integration
suite runs in CI.
- Each new test was shown to fail when the behaviour it covers is
removed.
- Manual QA: the slice 3 script in
`projects/sql-expression-literals/manual-qa.md` reads every refusal
above as a user sees it, at run time and at compile time. The run of
2026-10-08 matches every expected result.
- Three rounds of design and code review; the reports are in
`projects/sql-expression-literals/slice-reviews/3/`, `3-round-2/` and
`3-round-3/`, and every finding is fixed.

## Skill update

The `prisma-8` skill reference `contract.md` writes TypeScript raw SQL
as `sql` values. The upgrade instructions for app and extension authors
are in `upgrade-instructions/pending/sql-expression-literals-ts/`.

## Linked issue

Refs [TML-3289](https://linear.app/prisma-company/issue/TML-3289), part
of the Linear project [SQL expression
literals](https://linear.app/prisma-company/project/sql-expression-literals-c8a6659e7f4c).

## Checklist

- [x] All commits are signed off (`git commit -s`) per the
[DCO](../CONTRIBUTING.md#developer-certificate-of-origin-dco).
- [x] I read [CONTRIBUTING.md](../CONTRIBUTING.md) and the change is
scoped to one logical concern.
- [x] Tests are updated.
- [x] The PR title is in `TML-NNNN: <sentence-case title>` form.
- [x] The **Skill update** section above is filled in.

## Alternatives considered

- **Accept strings beside `sql` values.** Rejected. There would be two
ways to write the same thing, and a string skips canonicalization, so
PSL and TypeScript would again store different text for multi-line SQL.
- **A plain object `{ text }` instead of a class.** Rejected. A
hand-written object would pass the type check without being
canonicalized, and `.default()` could not tell it from a JSON default
value.
- **Keep the default checks in the tag.** Rejected. The tag now serves
every place, and "no `SELECT`" would refuse valid policy predicates such
as `EXISTS (SELECT …)`.
- **Let `${…}` take strings and numbers.** Rejected. That is building
SQL by string concatenation, which the typed value exists to prevent,
and DDL has no parameters to bind them to.
- **Skip, in `contract infer`, a default whose text would not read back,
as for an index.** Rejected. A skipped default is dropped by the next
migration; printing it with a note keeps it and tells the user what to
check.

Agent: lagertha-65

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
opensource-fork-sync Bot pushed a commit to cla7aye15I4nd/opensource-prisma__orm that referenced this pull request Oct 12, 2026
## At a glance

The SQL expression literals project is finished. Raw SQL is one value
everywhere:

```prisma
@@check(expression: sql`
  owner_id > 0
    AND char_length(email) > 0
`, name: "profile_valid")
```

```ts
check({ expression: sql`owner_id > 0 AND char_length(email) > 0`, name: 'profile_valid' });
```

```ts
// generated migration.ts
checkExpression('profile_valid_5901ae2d', sql`owner_id > 0 AND char_length(email) > 0`)
```

This PR closes the project: it deletes
`projects/sql-expression-literals/`, after moving the decisions that
lived only there into ADR 268, and records two lessons from the project
in the team's Drive calibration.

## Decision

The project's transient files go. What must outlive them now lives in
ADRs, the subsystem docs, Drive calibration and Linear:

- **ADR 268** gains four alternatives that were recorded only in the
project's design notes: holding opaque SQL in DDL as the query AST's
`RawExpr`, migration functions that take only `sql` values, leaving
generated migration files on strings, and a public builder for `sql`
values from computed strings. Its status line now lists `sql` values in
generated migration files as built.
- **`drive/calibration/failure-modes.md`** gains F47 (a stack of PRs
outlives its base's squash merge, and the last PR passes 250 commits,
which the DCO check cannot read) and F48 (a new committed contract
fixture fails the planner golden test, which only the merge queue runs).
**`drive/calibration/dod.md`** adds the planner golden step to the slice
gate before queueing.
- **`projects/data-types-completion/design-notes.md`** pointed at this
project's design file; it now points at ADR 231, ADR 254 and TML-3367.

## Where each project decision lives

| Decision (project design notes) | Durable home |
| --- | --- |
| Every place that holds raw SQL takes a `sql` literal | ADR 268, ADR
129 |
| Plain strings are refused | ADR 268 |
| A `sql` literal is a value of the data type `sql/expression`; only
`@default` checks the text | ADR 268, ADR 254, ADR 129 |
| The SQL family defines and registers `sql/expression` (the notes'
first version said each target registers it; the family does) | ADR 268,
ADR 254 |
| The only tag is `sql` | ADR 268, ADR 129 |
| Specs name the data type an argument receives (`dataTypeValue`) | ADR
231, ADR 249, ADR 262 |
| The TypeScript builder takes `sql` values | ADR 268, ADR 129 |
| `contract infer` prints `sql` literals, and skips or notes text that
would not read back | ADR 129, ADR 268 |
| Opaque SQL is its own DDL value, `OpaqueSql` | Migration System
subsystem doc, "Opaque SQL in DDL"; ADR 268 (alternative) |
| Migration files write `sql` values when they read back unchanged | ADR
195 ("Recorded exception"), ADR 268, Migration System doc |
| Wire names keep line breaks in bodies with `--` | ADR 234 |
| One set of codes for cast-rule refusals | ADR 268, ADR 254 |
| The decision gets its own ADR | ADR 268 |
| The typed argument ships first, for the "Data types own column types"
project | Delivered as TML-3367; the default-function argument work is
TML-3389 |
| Grammar versus database values | ADR 231 |

## Project definition of done

- **Delivered:** all seven slices merged.

  | Slice | PR | Linear |
  | --- | --- | --- |
  | 2a | prisma#30534 | TML-3296 |
  | 2t | prisma#30539 | TML-3367 |
  | 1 | prisma#30546 | TML-3287 |
  | 4 | prisma#30554 | TML-3290 |
  | 2b | prisma#30550 | TML-3288 |
  | 3 | prisma#30558 | TML-3289 |
  | 5 | prisma#30677 | TML-3297 |

  Every Linear issue is Done.
- **Review and manual QA:** every slice that changed what a user sees
had design and code reviews, a fixes check, and a manual QA run.
- **Follow-ups filed:**
- TML-3554: two Postgres migration operations paste raw SQL into DDL as
strings.
  - TML-3555: a raw SQL column default cannot hold a `--` comment.

A gap found in QA, `now() - interval '1 day'` failing apply's default
check, is on TML-2362, which replaces that comparison. Two deferred
items need no ticket:
- `contract infer` and defaults that do not read back: slice 3 decided
and built it.
- A builder for `sql` values from computed strings: recorded in ADR 268
as not offered.
- **References:** nothing outside the deleted folder points into it.

## Testing performed

- `pnpm lint:docs`, `pnpm lint:legacy-name` and `pnpm
check:upgrade-coverage --mode pr` pass.
- This PR changes only docs, Drive calibration and the deleted project
folder.

## Linked issue

Closes out the Linear project [SQL expression
literals](https://linear.app/prisma-company/project/sql-expression-literals-c8a6659e7f4c)
(TML-3282).

## Skill update

n/a — docs and project files only.

## Checklist

- [x] All commits are signed off (`git commit -s`) per the
[DCO](../CONTRIBUTING.md#developer-certificate-of-origin-dco).
- [x] I read [CONTRIBUTING.md](../CONTRIBUTING.md) and the change is
scoped to one logical concern.
- [x] Tests are updated (n/a, docs only).
- [x] The PR title is in `TML-NNNN: <sentence-case title>` form.
- [x] The **Skill update** section above is filled in.

## Alternatives considered

- **Keep the project folder as a record.** Rejected: its spec, plan,
design and status describe a project that no longer exists, and the
decisions worth keeping now live in ADRs.
- **Move the design notes into `docs/` as they are.** Rejected: they are
a log written during the project, and each decision now has an ADR or
subsystem-doc home.

Agent: lagertha-65

🤖 Generated with [Claude Code](https://claude.com/claude-code)


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

* **Documentation**
* Clarified how migration functions and generated migration files
represent SQL, including how DDL is stored and the limits on creating
SQL values from computed strings.
* Updated slice planning guidance to require running the planner golden
test in write mode and reviewing recorded DDL when committed contract
manifests change.
* Added guidance for handling stacked pull requests that exceed the DCO
commit limit and contract-fixture changes that fail merge-queue golden
tests.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
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.

2 participants