Documentation

Docs / Reference

ADR 0062 - Diesel models read at link time from retained sources

Status: Accepted (delegated review, 2026-11-16)

Diesel 2.x models (docs/contract/claims/diesel-models.md, plan the T018 task record (internal) "ORMs in the other first-tier languages"). Written for the whole task: discovery, the token lexer, provenance, node shapes, row and assumption ids and the oracle are fixed by the task file's claim contract, the investigation results and Revision 1 (2026-11-15); steps DB2-DB4 implement the rest and add their implementation notes here.

Context

A Diesel project states its database schema in a Rust file that diesel print-schema writes from a live database and that diesel.toml names ([print_schema] file, and [print_schema.<name>] file for each further configuration): diesel::table! blocks with the Diesel SQL type of every column (Int4, Nullable<Text>, Timestamptz), the primary-key list, diesel::joinable! lines for single-column foreign keys, diesel::allow_tables_to_appear_in_same_query!, and a sql_types module for custom types. A configured patch_file is applied after generation, so a generated file can hold hand-written lines. The corpus (rust-lang/crates.io at 4e6ac5a, diesel 2.3.14) has one configured file (36 tables, 209 columns, 33 joinable!, a 25-line patch), one unconfigured and stale schema.rs in the worker crate, and 293 up.sql/down.sql migration directories.

Diesel compiles against any table! the developer writes (a subset of columns, a view declared as a table, an imaginary primary key, a joinable! with no constraint behind it). The investigation's oracle (the repository's migrations applied to a scratch Postgres 17, catalog compared) found every such case on hand-written lines and zero disagreements on lines print-schema wrote. What print-schema writes is a closed function of the catalog (diesel_cli 2.3.14, cited in the task file); reading a generated line back inverts it.

The Rust extractor keeps no macro token trees (ADR 0060: it returns at every macro_invocation outside the sqlx gate), and on a cache hit there is no tree, so the facts cannot come from today's cached Rust facts.

Options considered

  1. Link time over the retained sources, with a small token lexer (Prisma, ADR 0057; the SQL migration reader, ADR 0047). The scanner retains the normalized bytes of every UTF-8 file on fresh and warm runs (internal/index/index.go, internal/scan/scan.go), including .rs, diesel.toml, Cargo.toml, Cargo.lock and the patch file.
  2. A cached payload from the Rust extractor (the route of ADRs 0059 and 0060): widen facts.RustFacts with table! token trees, gated to Diesel files, with an aggregate extractor version bump.
  3. tree-sitter at link time over the configured files: a second parse path outside the bounded workers, rejected by ADR 0059.
  4. Read the migrations instead through the SQL migration reader: measured in the investigation (open point O1): every table ends partial because of the reader's may-fail cascade.

Decision

Option 1. The Diesel front end (internal/extract/models/diesel) reads, at link time, the schema files discovery names, from the retained sources. No cached payload, no Rust extractor change, no aggregate extractor version bump (model records are link-time and uncached, as in ADR 0057; a warm index relinks). If a later unit finds a reason to cache, the bump is the next free extractors-N at merge.

Why link time fits here where ADRs 0059 and 0060 rejected it: the input is one or two declarative files per repository, named by diesel.toml, not arbitrary code; the facts need no owner or scope from the extractor; and the grammar is a token-tree subset.

The token lexer

lexer.go lexes every Rust token so that a form outside the contract is seen and refused instead of breaking the file: identifiers (Unicode letters included) and raw identifiers (r#type, stored without the prefix with a raw flag), ->, :: and => joined and every other punctuation character single (so >> closes two generics), string literals with escapes decoded (normal, raw with hashes, byte and C strings, line continuations, CRLF folded), integer and float literals with suffixes, character and byte literals, lifetimes, plain line and nested block comments (dropped), and doc comments (///, /** */, //!, /*! */) kept as tokens because they are attributes. A character no Rust token starts with is an Other token: the item holding it is unread. An unterminated literal or comment, an invalid escape, text that is not UTF-8, or an unbalanced delimiter refuses the whole file (one schema_model_unread marker; every definition in it is row D). Tokens are grouped into token trees as Rust macros see them.

The lexer is not a Rust parser. The item reader (items.go) recognises, at the file level and inside inline mod name { ... } blocks: table!, diesel::table! and ::diesel::table! (any delimiter), joinable! and allow_tables_to_appear_in_same_query! (bare or diesel:: qualified), structs (for the sql_types module's #[diesel(postgres_type(...))], mysql_type and sqlite_type attributes), use declarations, inner attributes, and everything else as an "other" item (row D).

The table! reader follows diesel_table_macro_syntax 0.3.0 (lib.rs:33-176): leading use declarations, outer attributes (docs; the first #[sql_name = "..."], r# stripped from its value), name or schema.name, an optional key list, the column block, each column [#[attr]]* name -> TypePath with the first #[sql_name] and #[max_length = <int>] read; columns split at commas outside generic angle brackets. A shape syn refuses (a keyword as a name, a missing ->, a type that cannot start a type path, a non-string sql_name, a non-integer max_length, tokens after the column block, ...) is a DI-P1 syntax failure, because diesel_derives turns every parse error into "invalid table! syntax" (lib.rs:1450-1462). A shape syn may accept but the reader does not model (a lifetime, const or associated-type argument, a qualified self type, an attribute on a use, another table or column attribute) is unread: D for the table or for the column's facts other than its name. After parsing, the compile-time checks of diesel_derives 2.3.10 apply (table.rs:9-140): more than 128 columns, no key list and no id column, a key naming no column, a column named like its table, two columns of one Rust name, and two table! of one Rust name in one module (both fail). The 16/32/64-column limits depend on crate features and are not modelled.

Discovery (row DI-K1)

Provenance (row DI-G1)

A configured file is generated when its first line is print-schema's header // @generated automatically by Diesel CLI.; within it, the lines the configured patch_file adds are hand-written. diesel_cli applies the patch with the diffy crate (0.4.x), whose search is patch(1)'s without fuzz; Graphvein has the patched file, so each hunk's new side is located exactly, at the only matching position, and the location is checked by applying the patch forward to the text it implies (step DB2 notes below). A missing, unreadable or non-unified patch, or a hunk that cannot be located, makes the whole file hand-written; a hunk that removes lines in a table! block (other than blank and comment lines and column lines it adds back under the same name) makes every fact of that table other than its table and column names unknown (task Revision 1 addendum 2, O-a). A configured file without the header, and every unconfigured file, is hand-written.

Node shapes and claims

Model-defined table and column nodes (source: "model", tool: "diesel") with contains and foreign_key edges in the T018c2 record shape plus the T018g0 kit (ADR 0058), group key models/diesel/<schema file>, so the Schema view shows them through T018f's model source group without view changes. Database facts come only from generated lines: base-table kind, primary key, complete column set, nullability (outermost Nullable), the Postgres type in format_type spelling (DI-C2's closed list, sql_types structs through DI-S1), and a foreign key per generated joinable! to the parent's single generated primary-key column (foreign_keys never complete; actions and names unknown). Hand-written lines claim names only and, with generated lines, carry the declared Diesel type (Nullable<Int4>) as a Rust-side annotation with no claims entry (Revision 1 O5). Types whose modifiers print-schema drops (Numeric, Time, Timestamp, Timestamptz, Interval, ...) are claimed as the type family with modifiers unknown through the kit's SetTypeFamily of ADR 0065 (Revision 1 O4); the declared Diesel type is the kit's tool_type (SetToolType). MySQL enum/set structs stay unknown (their labels are no kit modifier, so no family is claimed). Postgres facts are verification: "oracle"; MySQL and SQLite facts are mapped from diesel_cli's own mapping source.

Rows and assumptions

Rows (14, the task file's claim contract): DI-K1 scope, DI-G1 provenance, DI-T1 tables, DI-C1 columns, DI-C2 types, DI-S1 custom SQL types, DI-J1 joinable!, DI-J2 allow_tables_to_appear_in_same_query! (no fact), DI-P1 provable failures (schema_model_import_failure), DI-U1 the migrations marker, DI-U2 unconfigured schema.rs (names only, O2), DI-V the assumptions, and D. Assumptions: DI-V1 pins, DI-V2 the generated file is current, DI-V3 no domains (narrowed by O4), DI-V4 dialect from the workspace features, DI-V5 the generating section as it stands, DI-V6 diesel_cli rules (verified at 2.3.14 and, before merge, 2.4.0), DI-V7 unconfigured and possibly stale, DI-V8 a pin newer than the verified diesel_cli versions (Revision 1 addendum 4; listed with DI-V6 for such a pin, its text names the verified versions). Discovery attaches DI-V1, DI-V4 (when the dialect is known) and DI-V5 (configured) or DI-V7 (unconfigured); DI-G1 and the type rows add the rest.

Oracle

The repository's own up.sql migrations applied in Diesel's order (version = name up to the first _, dashes removed, sorted as strings; metadata.toml run_in_transaction = false honoured) to a scratch Postgres 17 through scripts/cloud-postgres.sh, then a catalog dump; every claimed fact compared, differences that the patch explains classified as repository drift, any other difference a precision stop. Probe DDL with a print-schema emulation covers forms the corpus does not use, as a test of the mapping table only. No diesel_cli build.

As built: scripts/oracle/diesel_catalog.sh (bash 3.2, psql only; never run by CI) writes one JSON dump per preset, --corpus (the migrations) or --fixture (diesel_fixture.sql, the database the fixture's Postgres schema files describe, and diesel_probe.sql); the catalog query is diesel_catalog.sql. TestDieselOracle emulates print-schema over the probe's information_schema in Go and compares the claim pass of each run with its catalog, types in format_type's spelling exactly, and checks that every form labelled oracle was compared. Its probe found two forms print-schema writes that the DB3 rules spelled wrongly: sql_types structs with schema = "pg_catalog" (tsvector, tsquery, xml, varbit, point; now the name alone) and diesel_cli 2.3's schema-qualified #[sql_name] on a renamed table of a schema section (now D). diesel_cli 2.4.0 was checked against the cited rules (docs/extract/schema-diesel.md "diesel_cli 2.4.0"); a newer pin lists DI-V8 ("Rules verified at diesel_cli 2.3.14 and 2.4.0: ...", which replaced DB4's diagnostic). Step DB5 added the type-family comparison: a family agrees when the catalog type's base name (format_type(atttypid, NULL)) is the family and the modifiers it lists unknown are not asserted; the probe compares every family form (oracleForms).

Revision 2 (independent review, decisions)

Fewer or weaker claims only, except where the oracle compared the form:

Revision 2 addendum

The diesel_cli that wrote a file is not the diesel library pin: a project can bump diesel to 2.1 or later without re-running print-schema, leaving 2.0 output. A1's 2.0 rules are therefore keyed to the file, not the pin (fewer claims only): a generated file is diesel_cli 2.1 or later output only when it shows output 2.0.1 never writes, a #[max_length = n] on a generated column or a /// doc comment on a generated table or column other than 2.0.1's generated text (2.0.1 inference.rs:198-224 writes only that text and reads no database comment; 2.1.1 writes database comments, pg.rs:74-149). Otherwise Varchar and Varbit without #[max_length] are their families, no joinable! is a foreign key and DI-V9 (now "Older diesel_cli output") is listed, whatever the pin; a proven file lists DI-V9 only for a pin below 2.3.14 or not proven. A patch-added #[max_length] and a #[doc] attribute prove nothing. Options considered: #[max_length] alone (the requested minimum; on crates.io, which has none, it withholds all 29 foreign keys and turns 38 Varchar types into families) and adding the database-comment proof (crates.io's with_docs = true output carries database comments, so its coverage is unchanged). Chosen: both. Other 2.1-only output (a MySQL mysql_type struct, non-default custom_type_derives) is not used. Rows DI-G1 (the proof), DI-C2 and DI-J1 (the 2.0 rules) changed; provesCLI21 in records.go.

Revision 2 addendum 2

No SQLite file can show 2.1 output (no lengths, no comments), so the addendum withheld every SQLite joinable!. The diesel_cli 2.0.1 and 2.1.1 sources show the SQLite joinable! set is the same in both: each loads one single-column constraint per PRAGMA foreign_key_list row (2.0.1 sqlite.rs:65-108, 2.1.1 sqlite.rs:57-88), so a composite key's rows share a table pair and the duplicate-pair filter drops them in both (2.0.1 foreign_keys.rs:16-26, :40; 2.1.1 :13-23, :38), and the self-reference, outside-the-output and single-primary-key filters and get_primary_keys are the same. Options considered: keep withholding (safe, but no SQLite project ever gets a foreign key), or exempt SQLite from DI-J1's 2.0 rule. Chosen: the exemption; a SQLite generated joinable! is claimed under the 2.1 rules whatever the writer, DI-V9 is still listed. Rows DI-G1 (claim cell names the exception) and DI-J1 changed; readJoinable in joins.go. The shape-by-shape comparison is in the task file's "Revision 2 addendum 2".

Consequences

Known gaps

Implementation notes

Records

Discovery, lexer and item reader

Provenance, contract table and companion crates

Review notes (delegated review, 2026-11-16)

Report a problem with this pageSource: docs/adr/0062-diesel-models.md