Skip to content

TML-3386: SQL data types declare their names, parameters and texts once - #30547

Merged
wmadden-electric merged 204 commits into
mainfrom
tml-3386-data-types-declare-names
Oct 6, 2026
Merged

wmadden-electric merged 204 commits into
mainfrom
tml-3386-data-types-declare-names

Conversation

@wmadden-electric

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

Copy link
Copy Markdown
Contributor

Slice 1 of the project "Data types own column types" (Linear TML-3386). It also carries the project documents that planning PR #30518 proposed, which is closed in favour of this one.

At a glance

A Postgres data type now declares, in one place, how the database writes it, how the catalog reports it, which parameters it takes, and their normal form:

export const pgNumeric = sqlDataType('pg/numeric', {
  params: pgNumericParams,                       // precision 1 to 1000, scale -1000 to 1000
  texts: [
    writtenAndCatalog('numeric'),
    written('numeric({precision})'),
    writtenAndCatalog('numeric({precision},{scale})'),
    claimsOnly('decimal'),
    claimsOnly('decimal({precision})'),
    claimsOnly('decimal({precision},{scale})'),
  ],
  normalize: (params) =>
    params.precision !== undefined && params.scale === undefined ? { ...params, scale: 0 } : params,
  casts: { [pgInt2.id]: asNumeralText, [pgInt4.id]: asNumeralText, [pgInt8.id]: unchanged },
});

A type constructor names the codec and maps its arguments onto the data type's parameters. It carries no type name and no bounds of its own:

Numeric: {
  kind: 'typeConstructor',
  inferred: true,
  args: [
    { kind: 'number', name: 'precision', integer: true, optional: true },
    { kind: 'number', name: 'scale', integer: true, optional: true },
  ],
  output: { codecId: 'pg/numeric@1', typeParams: { precision: { kind: 'arg', index: 0 }, scale: { kind: 'arg', index: 1 } } },
},

Everything that used to compute or copy a column's type name now reads the declaration: the contract writers, both migration planners, the ALTER COLUMN TYPE postcheck, the Postgres parameter casts, and the Prisma 7 reader.

The decision

Every fact about a SQL database type is declared once, on the data type, by the package that owns it (a target such as Postgres, or an extension such as pgvector). Every copy of those facts is deleted. contract.json does not change in this slice: the column still stores nativeType, but that string is now written from the declaration, and a test proves the DDL of every committed contract is byte-identical.

Before this change the name of a column's database type was written or computed in eight places that disagreed: codec targetTypes, the nativeType() codec hook, the expandNativeType control hooks, a type metadata registry, the adapters' normalizeNativeType, the constructor templates' nativeType, hand-written descriptors, and the Prisma 7 binding. Adding a type meant editing several tables, extension types were invisible to contract infer, and db verify compared strings.

What the declaration holds

  • Texts. Each text is marked written (a migration writes it), catalog (the database reports it), both, or neither (it only recognises a reported type). numeric(10) is written as numeric(10) but reported as numeric(10,0), so pg/numeric declares both texts. Placeholders such as {precision} name a parameter; only integers may be substituted.
  • Parameters and bounds. params is an arktype object schema and is the only place a bound is written. pg/numeric allows a negative scale, as Postgres 15 does. A codec's paramsSchema is its data type's params, referenced, never restated. Constructor and preset arguments lost their minimum and maximum; PSL reports a violation at the argument with PSL_INVALID_ATTRIBUTE_ARGUMENT, and a TypeScript contract refuses it when it is built with CONTRACT.TYPE_PARAMS_INVALID.
  • Normal form. normalize gives the parameters the catalog compares by: numeric(10) becomes { precision: 10, scale: 0 }; char becomes { length: 1 }. Writing uses the raw parameters, so migration SQL is unchanged.
  • Kinds. pg/enum declares claimsKind: 'enum' and a render hook that quotes the type name, instead of texts.
  • Casts stay exactly as they were.

The Postgres target declares every Postgres type, pgvector declares vector({length}), postgis declares geometry and geometry(Geometry,{srid}). SQLite declares text, integer, real, blob and two new types, character and character varying, which the sql/char@1 and sql/varchar@1 codecs now name on SQLite. Mongo data types declare the BSON types they are stored as with mongoDataType.

Who declares and who reads

  • Targets declare. The Postgres and SQLite targets register their data types for both migrations and the runtime, and contribute the PSL entries for them. A target contributes the constructors that are also TypeScript type.* helpers (BigIntNumber, UnboundedInt, pg.enum). It defines its PSL-only constructors (postgresPslTypeConstructors, sqlitePslTypeConstructors), and its adapter contributes those, so the TypeScript builder's type.* helpers do not change.
  • Readers. Both planners write a column type with renderSqlTypeName. SERIAL, identity values, JSON defaults and the safe-widening table are keyed by data type id. The Postgres SQL renderer casts a parameter to the type's base name: $1::integer becomes $1::int4, and a varchar(255) column casts as character varying with no length, because an explicit cast with a length would truncate.
  • Assembly checks. A stack is refused when a constructor names a codec no component registers, maps an argument onto a parameter its data type does not declare, or marks two constructors of one data type inferred; when two data types' claiming texts would both match one reported type; and when a codec represents a data type that is not a SQL column type. The last two checks run when the SQL family is created, so CLI commands report them and the language server does not. The SQL family's own data type, sql/expression, is the type of a written SQL expression and no column has it.
  • Deleted. targetTypes, targetTypesFor, byTargetType, the nativeType() hook and nativeTypeFor, every expandNativeType hook, buildNativeTypeExpander, typeMetadataRegistry, normalizeNativeType, validateScalarTypeCodecIds, assertSafeNativeType and CONTRACT.NATIVE_TYPE_INVALID. ADR 171 is superseded by ADR 254.

Behaviour changes to know about

  • Columns that use a types {} alias are written like any column of the aliased type. A types { Id = Uuid } alias used to write "uuid", quoted, which Postgres rejects. Now it writes uuid. No committed migration contains such a column.
  • The check after ALTER COLUMN TYPE compares the database's reported type with the name Postgres prints for the new type. For an enum that means "UserRole" quoted and user_role not, whether or not the column goes through an alias. Before, a mixed-case enum name reached through an alias failed this check. Slice 3 replaces the text comparison with a type identity check.
  • Verify reads a column's type in the form the catalog prints. A Numeric(10) column is compared as numeric(10,0), which is what Postgres reports, so it now applies and verifies clean.
  • A NOT NULL list column added to a non-empty table gets the temporary default '{}' instead of '', which Postgres refused for an array.
  • The migration marker's invariants column binds pg/text@1 as a list instead of pg/text-array@1, which is never written. DDL and stored rows are identical, so a signed database still verifies.
  • A TypeScript contract must list the extensions whose codecs it uses (or pass their data types), because the column's type name now comes from the codec's data type. defineContract builds the lookups from the target and the listed extensions.
  • A runtime adapter refuses a codec whose data type is not registered when it is built, rather than on the first query.
  • A placeholder value written into a type name must be an integer. Rendering refuses anything else, so a data type's parameters can never carry text into DDL.
  • contract infer and the PSL printer write a namespaced constructor with no arguments with parentheses, postgis.Geometry(), because the reader treats a dotted name without them as a scalar type. srid is optional now, so this case can occur. Names without a namespace are unchanged.
  • Two Mongo PSL messages no longer name the BSON type. The deprecated scalar name warning (PSL_DEPRECATED_SCALAR_NAME) and the earlier-name hint for an unresolved type used to say use "X" (stored as BSON string). They now say use "X".
  • One place checks column parameters. Building a contract validates every column's parameters against its data type and raises CONTRACT.TYPE_PARAMS_INVALID; no column helper checks on its own. PSL reports the same violation at the argument, and the type.* helpers keep CONTRACT.ARGUMENT_INVALID.

Upgrading

Two entries under upgrade-instructions/pending/data-types-declare-names/, both validated by execution against the base commit:

  • extension/instructions.md: replace dataType(id) with sqlDataType or mongoDataType declarations; delete targetTypes and the rendering hooks; point the codec's paramsSchema at the data type; drop nativeType and bounds from constructor templates; pass dataTypes from runtime descriptors; expect $1::int4 in logged SQL.
  • app/instructions.md: list the extensions a TypeScript contract uses; re-emit SQLite contracts, whose contract.d.ts gains aggregate rows for the two character codecs; column parameter errors are now CONTRACT.TYPE_PARAMS_INVALID and are raised when the contract is built.

Proof

  • A golden planner test plans every committed SQL contract plus two fixture contracts with every parameter shape from an empty schema and compares the operations byte for byte with main's planner. It commits one SHA-256 per contract in test/integration/test/planner-golden/manifest.json, hashed from recordings made with main's planner; only the two fixture contracts keep their full planner output for review. Of 344 contracts, 341 plan identically; two differ only by the typeRef quoting fix and one only by the planner's error code for an unregistered codec.
  • Per package, a test lists every registered data type and asserts its declaration; every bound is tested at its edges; normalize applied twice equals once.
  • pnpm fixtures:check shows no contract change. The framework vocabulary count fell from 272 to 262.
  • The Postgres runtime bundle grows about 1.6% (size-limit report), because the data type declarations now reach the runtime for parameter casts. Mongo grows 0.16%.

What later slices do

Slice 2 (TML-3388) makes contract.json store dataType instead of nativeType and ships the upgrade script. Slice 3 (TML-3387) wires resolveReportedSqlType, which this slice defines and unit-tests, into introspection, verify and infer. Slice 4 (TML-3389) types written values outside defaults.

Alternatives considered

  • Keep nativeType strings and normalise them on read. Rejected in the design: it keeps eight sources and cannot recognise an extension's type.
  • A side registry of codecs for the planner so SQLite need not register sql/char@1 and sql/varchar@1. Rejected: a second source for which codecs a target has. The cost accepted instead is two aggregate rows in each SQLite contract.d.ts.
  • Writing the normalised parameters (numeric(10,0) for Numeric(10)). Rejected: it would change migration SQL for existing columns.

Project files: projects/data-types-completion/ (spec, design, plan, decision record, slice plan and in-loop review log).

Agent: thranduil-81, minerva-41

wmadden-electric and others added 30 commits September 27, 2026 11:49
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…m the contract

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…d contracts

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…ript

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…ssion settles

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…and infer failure

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

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…their decisions

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

A new integration test plans every committed Postgres and SQLite contract from an empty database and compares the planner operations with a golden file. The goldens are recorded from the planner as it is before any data type changes. A contract in a format the validator refuses today is recorded as unreadable so the set left out is committed and reviewed with the rest.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
`DataType` and `DataTypeSpec` gain an optional `params`, an arktype object schema of the type parameters, and `dataType()` carries it through. A type without `params` has none. The SQL data type module builds on it to validate and render type parameters.

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

New entry point `@internal/sql-contract/data-type`. `sqlDataType` declares a SQL data type with the texts a migration writes and the catalog prints, a parameter schema, a normal form, and either texts or a kind claim with `render` and `fromReported`; it refuses a declaration that breaks a rule. `renderSqlTypeName` writes the name for raw parameters, `renderSqlCatalogText` prints the catalog text for the normal form, `sqlBaseName` gives the name with no parameters, `dataTypeParams` keeps the keys the type declares, and `resolveReportedSqlType` recognises a reported type from every claiming text or kind claim in a list of data types.

Parameters that fail the schema, or a parameter set no text takes, raise the structured error `CONTRACT.TYPE_PARAMS_INVALID`, added to the error reference. The public packages that mirror the sql-contract entry points gain the matching export.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…sembly order

DataTypeLookup gains all(), which returns every assembled type in the order the stack assembled them: contributor by contributor, each in its own order. The resolver of reported SQL types and the assembly check for colliding claims need the whole list, which get and has cannot give.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…ext rules

A kind claim is now checked like a text claim: resolveReportedSqlType validates the parameters fromReported reads against the type's schema, returns nothing when they fail, and returns their normal form. sqlBaseName validates the parameters it passes to render, so an enum with no typeName fails with CONTRACT.TYPE_PARAMS_INVALID instead of a TypeError.

A declared text may no longer contain a double quote, and a display must write every placeholder exactly as its text does. Text preparation removes a space after an opening bracket or a comma when a double quote follows it, as it does before any other character.

The error reference names the catalog case and sqlBaseName.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
The planner golden test selected contracts by file name, so it missed 40 committed SQL contracts, among them the 35 Prisma 7 reader fixtures named expected-contract.json. It now reads every tracked JSON file and keeps those whose top level names the SQL family and the Postgres or SQLite target.

An extension pack that lives inside an example and cannot be imported here is listed in the golden under extensionsNotLoaded instead of under extensions. Any other pack the test does not know fails the test. A contract the planner refuses with a structured error is recorded with that error, as a contract the validator refuses already is.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…now finds

Recorded from the planner as it is on this branch, which no dispatch has changed yet: 40 new goldens for the contracts the file-name selection missed, and nine existing goldens that now list their example-local packs under extensionsNotLoaded.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…n type shape

No committed contract held a numeric column with a precision and no scale, a char, bit or varchar column with no length, several SQLite codecs, or a typeRef alias of a type written with no parameters. These are the shapes where writing a column type from its data type can go wrong, so the planner golden test could not see such a change.

Two TypeScript contracts under test/planner-golden/fixtures fill the gap: one for Postgres with pgvector and postgis, one for SQLite. Each has one column per codec in every parameter shape a contract can hold today, list columns on Postgres, and typeRef aliases. They are emitted by emit-fixture-configs like the other generated fixtures, so fixtures:check holds them fixed.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Recorded from the planner as it is on this branch, which no dispatch has changed yet. The Postgres golden shows the typeRef columns of uuid and of char with no length written as quoted names, which is the one DDL change this project makes.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
A codec-instance entry in types needs typeParams, so the uuid and char aliases carry an empty object; the emitted contract is unchanged. A type-only import of postgis geojson lets the declaration of the exported contract name the geometry value type.

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]>
…arameters and normal form

Each pg/* data type is now a SQL data type: the texts a migration writes and the catalog reports, the texts that only claim a reported type, its parameter schema with the bounds PostgreSQL enforces, and its normal form. pg/enum claims the enum kind, renders its type name quoted at the first dot, and reads a reported enum as its name, qualified outside public.

Every Postgres codec now uses its data type's parameter schema, so a bound is written once. The bounds change where the old schemas differed: char and varchar lengths stop at 10485760, bit and varbit lengths at 83886080, a numeric scale stops at 1000 and needs a precision, and an enum type name must not be empty. pg/unboundedint@1 now takes the numeric parameters too. postgresCodec takes the data type instead of its id and gives the adapted codec the data type's schema, not the template's.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…e from

pg.enum's PSL path reads only typeParams from columnFromEntity; the type name comes from the pg/enum data type. The Mongo collection validator reads BSON types from the data type a codec represents.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…ixes round 4

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

deriveJsonSchema and derivePolymorphicJsonSchema take a required MongoTypeLookups after their fields, and the optional codecLookup argument moves into it. The entry mongo-derive-json-schema-takes-lookups says so, with a call before and after.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…n's rule numbers

The scenario A comment slice 1 rewrote also loses its project ids.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
… the codec lookup

buildSqlContractFromDefinition already requires both lookups, so the branches that skipped encoding a default or checking enum members without a codec lookup were dead. columnCodec, codecForDefault, encodeColumnDefault, encodeEnumMembers and checkMemberValues now require it, and a column default is always encoded through a codec.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Main brought TML-3409 and TML-3443. The SQLite schema diff keeps slice 1's imports, which no longer need ifDefined, and adds main's SQLITE_NOW_EXPRESSION.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
… every data type in its table

Design 13.8 states the rule for the whole Prisma 7 table and says where an exception would be listed. The slice 3 outline names the Prisma 7 reader, and deferred.md records rewording the inferred mark's documentation so it names no single reader.

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

pgIsTextLikeNativeType and SERIAL_FAMILY_TYPES read type text a migration author may write by hand, and no design section replaces them. They leave the slice 3 grep row, and deferred.md records why the walker cannot read a data type for every column.

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

Main's new now() plan-diff tests pass the SQLite test components, so the planner can find the column's codec, and its new marker-read tests build the Postgres control adapter with the data type lookup it now requires.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Each inventory header says it was made on 2026-09-29 for planning pull request #30518 and that its raw outputs were not kept, without the local paths or the commit not on main. The slice plan says the review artefacts are local. Design 3.1 names the PSL-only constructor sets and the targets' own sets, and 3.2 names the runtime adapter's create(stack).

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…n outside assembly

"Assembly is strict" becomes "Checks on the assembled stack", because items 8 to 10 run when the SQL family creates its control instance. The one link to the heading follows.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…d the constructor-set nouns

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

TML-3409 makes a SQLite now() default store strftime('%Y-%m-%dT%H:%M:%fZ','now'), so examples/prisma-8-demo-sqlite plans differently. Its new recording on this branch is byte-identical to main's planner output, recorded in a separate checkout of main as before. The only differences from main's planner remain the typeRef quoting fix and the unregistered-codec error code.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…h the target

The Temporal guard and the precision-bound tests check only target facts, so they move from the Postgres adapter to the target and import from ../src/core. The adapter's authoring-contribution tests move to its descriptor-meta test, as SQLite has them. Six hand-built unions in the target's tests become postgresPslTypeConstructors. The 556 test titles of the affected files are the same before and after.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
@wmadden-electric
wmadden-electric changed the base branch from data-types-completion to main October 6, 2026 08:11
@wmadden-electric
wmadden-electric added this pull request to the merge queue Oct 6, 2026
Merged via the queue into main with commit cff8545 Oct 6, 2026
25 checks passed
@wmadden-electric
wmadden-electric deleted the tml-3386-data-types-declare-names branch October 6, 2026 08:34
wmadden pushed a commit that referenced this pull request Oct 6, 2026
…e contract (#30617)

On `main`, the planner golden test fails:

```text
FAIL test/planner-golden/planner-ddl-golden.test.ts > records exactly the committed contracts in the manifest
-   "packages/3-extensions/sql-orm-client/test/fixtures/polymorphism/generated/contract.json",
```

This pull request adds that contract's entry to
`test/integration/test/planner-golden/manifest.json`, recorded with
`main`'s planner. With it, the golden test passes on `main` (696 tests).

The golden test came with TML-3386 (#30547). It requires one manifest
entry for every committed SQL contract. TML-3403 (#30560) committed this
contract after that. Its merge queue run skipped the integration tests,
so the missing entry was not caught.

Refs: TML-3386

Agent: minerva-41


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

## Summary by CodeRabbit

* **Tests**
* Expanded regression coverage for generated polymorphism contract
output, helping verify that planner results remain consistent.

<!-- 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