Skip to content

Commit b572420

Browse files
fix(driver-sql): a column's literal DEFAULT follows the field's declaration on an existing table (#36564)
<!-- claude-projects-attribution: {"github_login":"os-warren"} --> _Requested by **Warren** · [project thread](https://claude.ai/code/project/chan_01U5RdnAAmkSQmZbqh6FtqZ8?thread=cmsg_01U5RdnAAmkSQmZbqh6FtqZ8Jy8bxCRdEndf2kW8g6WXtd)_ Fixes #36245 Clause-②: no Metadata-protocol: none ## 维护者速读 - 字段删掉或改掉默认值后,老数据库的这一列也跟着改:开发环境重启、发布对象、制品启动、执行迁移命令时自动修好;生产环境普通启动只报出、不改。 - 属于数据层的修复,也是给通知偏好「摘要」字段拆掉临时补丁铺路。 - 修错了只影响以后不填该字段的新记录存什么,已有记录一行不改;改动可直接回退。 - 要你做的一件事:定夺通知偏好那个临时补丁现在拆还是等生产启动也能自动改列再拆(见下方 Acceptance notes,席位会转决策)。 ## What changes `createColumn` emits a field's literal `defaultValue` as the column `DEFAULT` once, when it builds the column; the additive sync never revisits an existing column, and the differ read `defaultValue` only for runtime tokens (#4560). So a table an earlier release created kept the old `DEFAULT` after the field dropped or changed it, and `detectManagedDrift` answered `[]`. - `schema-drift.ts`: `diffManagedTable` gains a literal-default arm. A column carrying a literal `DEFAULT` under a field that declares none reports `drop_column_default`; a literal that differs from the declared one reports the new op `set_column_default`. Both `safe`, kind `default_mismatch`, message ending with the shared `SAFE_COLUMN_REMEDY`. Judged only where `createColumn` itself emits a literal: tokens, object defaults, multi-value columns and physical *expressions* (`NOW()` defaults, sequences) are never touched, and a temporal literal is never compared (the dialect renders it its own way). Two pure helpers say what a physical `DEFAULT` is (`physicalDefaultLiteral`) and when it already matches (`physicalLiteralMatches`); the spellings they read were measured on SQLite, Postgres 16 and MariaDB 10.11. - `sql-driver-schema-sync.ts`: `applyDriftOpInPlace` applies `set_column_default` with `ALTER TABLE … ALTER COLUMN … SET DEFAULT` on Postgres and MySQL (the MODIFY-free form, like `drop_column_default`), reading the declared literal at apply time and inlining it as the client escapes it; the SQLite rebuild honours it (it already re-emits every column's declared default). - `driver-turso`: `REMOTE_DRIFT_OP_ANSWERS` answers `set_column_default` as `needs-table-rebuild`, as it does `drop_column_default`. Who applies the entries is unchanged: dev auto-reconcile, a publish of the object (`applyPublishedColumnChanges`, which takes every `safe` column entry), the artifact-pinned boot and `os migrate apply`. A plain production boot alters no existing column and logs the entry. ## Tests `src/sql-driver-36245-stale-literal-default.test.ts`, through `declareDialectCell` on every cell: - §1 (no server): 20 physical spellings read as literal / none / expression; 13 literal-vs-declared pairs. - §2 per dialect, two boots over one database: the removed default stores NULL on an unset insert after the second boot; the changed literal stores the new value; the kept default is stored and never reported; a row stored before keeps its value; with no auto-reconcile both entries are reported `safe` and `applyMigrationEntries` applies them. <details><summary>Readings (head 3862c8b unless noted)</summary> - Premise on main d463c46, two `SqlDriver` boots over one database, `digest` dropping `defaultValue: 'none'` and `changed` going `'a'` to `'b'`: SQLite file, Postgres 16, MariaDB 10.11, with and without `autoMigrate: 'safe'` — every cell stored `digest: "none"`, `changed: "a"`, and `detectManagedDrift` answered `[]`. - Same probe on the fix: `drift=[set_column_default changed, drop_column_default digest]` without auto-reconcile; with it, `digest: null`, `changed: "b"`, `drift=[]` on all three. - False-positive sweep on the fix: a table built by `initObjects` with 27 fields carrying string / quoted / empty / number / decimal / negative / boolean / select / text / date / time / datetime / `NOW()` / json / multi-value / `current_user` / URL-with-parentheses defaults reports no default entry on SQLite, Postgres or MariaDB. - New file, all three cells (`OS_TEST_POSTGRES_URL`, `OS_TEST_MYSQL_URL` set): 39/39 passed. - `pnpm --filter @objectstack/driver-sql test` (SQLite cells): Test Files 269 passed, 13 skipped; Tests 4539 passed, 262 skipped. With a live Postgres too: 4 failures, all the three-way timezone-skew guards (this local server runs in UTC; CI's is not), none in a default or drift suite. - `pnpm --filter @objectstack/driver-sql typecheck`, `pnpm --filter @objectstack/driver-turso typecheck`: exit 0. `pnpm --filter @objectstack/driver-turso test`: 103 files passed, 2647 tests passed. - Ablation 1, the drop arm disabled (`if (dv === undefined || dv === null)` → `if (false as boolean)`), committed fix first, on-disk mutation proven by `scripts/ablation-replace.mjs` (anchor 1 → 0, blob c1c48d2 → cb129bf6): 5 of the §2 cases red (`expected 'none' to be null`, the drift list missing `digest`), restored blob == HEAD. - Ablation 2, a kept literal read as different (`return true` → `return false` on the text compare; blob c1c48d2 → 36666e6a): 9 red, including the kept-default assertion `detectManagedDrift(...) toEqual([])` on every cell; restored blob == HEAD. </details> ## Acceptance notes - **The #35123 stopgap hook is NOT removed in this PR**, against the card's "remove that hook and its pin in the same PR", which also allows "a follow-up named here". Measured reason: the repair reaches a database through dev auto-reconcile, a publish, the artifact-pinned boot or `os migrate apply`; a plain production boot never alters an existing column (`reconcileAndWarnDrift`: "schema is never auto-altered in production"). `sys_notification_preference` is a service's own object, so no publish or package install applies it either. Removing the hook now would bring back, on every upgraded production database where nobody runs `os migrate apply`, the silent digest opt-out ruling 7073270426 rejected; the only new thing is that the boot now logs the entry. Upgraded production databases get this fix through `os migrate apply`, or through any of the drift-applying paths above (dev auto-reconcile, a publish, the artifact-pinned boot). The hook's removal, and repointing its comment, are carried by follow-up #36570 (Blocked-by this PR). - A hand-set literal `DEFAULT` on a column whose field declares none is now reported and, through the doors above, dropped — the card's ruling reverses the old "a hand-edited DEFAULT is a DBA's business" note on `FieldDef.defaultValue`, rewritten here. - Not covered, same family: a field that GAINS a `defaultValue` after its table exists (the column has no `DEFAULT`; restating one is outside the ruling's two verbs, and on MySQL a TEXT column cannot carry it); a `NOW()` default the field no longer declares (a physical expression, never touched); a temporal literal that changed (never compared). MySQL 8 reports a string literal bare; a bare all-capitals or multi-word value is read as an expression and left alone. MySQL 8 itself was not measured here (MariaDB 10.11 was); CI's live MySQL cell runs the new file. ## Verification Two minutes: `OS_TEST_POSTGRES_URL=… pnpm --filter @objectstack/driver-sql exec vitest run src/sql-driver-36245-stale-literal-default.test.ts` — expect 39 passed with both live URLs set, 35 on SQLite alone with the two live cells reported NOT RUN by name. Read first: `packages/drivers/driver-sql/src/schema-drift.ts` (the literal-default arm in `diffManagedTable` and `physicalDefaultLiteral`, where a misread spelling would drop a DEFAULT nobody asked to drop), then `setDeclaredColumnDefault` in `sql-driver-schema-sync.ts` (the inlined literal). --- _Generated by [Claude Code](https://claude.ai/code/session_01JQwxbY6wSVQZ9QBM4hLeYw)_ <!-- signed: repo:objectstack#1 · os-warren · session_01JQwxbY6wSVQZ9QBM4hLeYw --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 06c3e5a commit b572420

6 files changed

Lines changed: 444 additions & 20 deletions

File tree

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
---
2+
'@objectstack/driver-sql': patch
3+
'@objectstack/driver-turso': patch
4+
---
5+
6+
Clause-②: no
7+
Metadata-protocol: none
8+
9+
A column's literal DEFAULT now follows the field's declaration on a table an earlier release created, not only on a fresh database. When a field drops its literal `defaultValue`, schema drift reports the column's leftover DEFAULT (`drop_column_default`); when the declared literal changes, it reports the old one (`set_column_default`). Both are `safe`: dev auto-reconcile, a publish of the object, the artifact-pinned boot and `os migrate apply` apply them, in place on PostgreSQL and MySQL and by the table rebuild on SQLite. Before, the table kept the old DEFAULT, every insert that left the field unset stored the old value where a new database stored the declared one (or nothing), and `os migrate plan` showed nothing. Stored rows are never rewritten, and a DEFAULT that is an expression (a `NOW()` default, a sequence) is left alone. A plain production boot still alters no existing column: it logs the entry, and `os migrate apply` applies it.

‎packages/drivers/driver-sql/src/schema-drift.ts‎

Lines changed: 192 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ import { createHash } from 'node:crypto';
3232

3333
import {
3434
isAppResolvedDefaultToken,
35+
isRuntimeDefaultToken as isRuntimeDefaultValue,
3536
isUniqueDeclared,
3637
STRUCTURED_JSON_TYPES,
3738
FILE_REFERENCE_TYPES,
@@ -149,18 +150,36 @@ export type DriftOp =
149150
| { type: 'narrow_varchar'; table: string; column: string; to: number; from?: number }
150151
| { type: 'drop_column'; table: string; column: string }
151152
/**
152-
* Strip a column DEFAULT metadata never asked for (#4560).
153+
* Strip a column DEFAULT the metadata does not declare.
153154
*
154-
* Today's only source is a `defaultValue` runtime token that a pre-fix build
155-
* emitted as a literal (`DEFAULT 'current_user'`), so every insert that
156-
* omitted the field got the token's own spelling instead of the engine's
157-
* deliberate "leave it unset". Dropping it cannot fail and cannot lose data —
158-
* stored rows keep whatever they hold; only FUTURE omitted inserts change,
159-
* from a bogus literal to NULL. Rows already carrying the bogus value are NOT
160-
* rewritten: they stay visible to the dangling-reference audit (#4551), whose
161-
* standing rule is report, never rewrite.
155+
* Two sources. (1) A `defaultValue` runtime token that a pre-fix build
156+
* emitted as a literal (`DEFAULT 'current_user'`, #4560), so every insert
157+
* that omitted the field got the token's own spelling instead of the
158+
* engine's deliberate "leave it unset". (2) [#36245] A literal `defaultValue`
159+
* the field no longer declares: the table was created while it did, so the
160+
* column still carries it, and every insert that omits the field keeps
161+
* storing the old default where a fresh database stores NULL.
162+
*
163+
* Dropping it cannot fail and cannot lose data — stored rows keep whatever
164+
* they hold; only FUTURE omitted inserts change, to NULL. Rows already
165+
* carrying the old value are NOT rewritten: for (1) they stay visible to the
166+
* dangling-reference audit (#4551), whose standing rule is report, never
167+
* rewrite; for (2) a stored value is indistinguishable from one a writer
168+
* chose, and converting it is the owning object's call.
162169
*/
163170
| { type: 'drop_column_default'; table: string; column: string }
171+
/**
172+
* [#36245] Restate a column DEFAULT whose declared literal changed: the
173+
* column carries the literal an earlier declaration gave it, so every insert
174+
* that omits the field stores the OLD value where a fresh database stores
175+
* the new one. The value is the declaration's (`defaultValue`, read when the
176+
* op is applied), emitted as `createColumn` emits it.
177+
*
178+
* `safe` for the reason `drop_column_default` is: the statement cannot fail
179+
* on existing rows and rewrites none of them; only FUTURE omitted inserts
180+
* change.
181+
*/
182+
| { type: 'set_column_default'; table: string; column: string }
164183
/**
165184
* REPORT ONLY (#11535). The column's base type diverges from the one the
166185
* declaration materialises, and **the platform deliberately does not change
@@ -509,14 +528,15 @@ const DESTRUCTIVE_COLUMN_REMEDY = {
509528

510529
/**
511530
* The remedy sentence each `safe` COLUMN entry of a declared field
512-
* (`widen_date_to_datetime`, `widen_varchar`, `drop_column_default`) ends
531+
* (`widen_date_to_datetime`, `widen_varchar`, `drop_column_default`,
532+
* `set_column_default`) ends
513533
* with, naming the act per object kind as the `relax_not_null` message does.
514534
* A publish applies these entries (`applyPublishedColumnChanges`) only for an
515535
* object authored in this environment: a publish of a package object is
516536
* refused (`NOT_OVERRIDABLE`), and a managed install of the package has no
517537
* door for them (`relaxDeclaredNotNull` applies the declared NOT NULL relax
518538
* only). So for a package object the sentence names `os migrate apply` alone.
519-
* Spelled once, here, so the three messages cannot drift apart.
539+
* Spelled once, here, so the messages cannot drift apart.
520540
*/
521541
const SAFE_COLUMN_REMEDY =
522542
'For an object authored in this environment, publishing the object applies it; for an object a package ' +
@@ -845,15 +865,111 @@ export interface FieldDef {
845865
/** ADR-0113: the explicit physical constraint — nullability drift reads THIS, not `required`. */
846866
storage?: { notNull?: boolean };
847867
/**
848-
* The declared default. Only consulted for the runtime-token dimension
868+
* The declared default, read on two dimensions. (1) The runtime-token one
849869
* (#4560): a token is an instruction, so it must never appear as a physical
850-
* column DEFAULT. Literal defaults are deliberately NOT diffed — a hand-edited
851-
* DEFAULT on a column is a DBA's business, and reporting every one of them
852-
* would drown the plan the same way undeclared indexes would.
870+
* column DEFAULT. (2) [#36245] The literal one: the column's literal DEFAULT
871+
* follows the declaration — dropped when the field declares none, restated
872+
* when the declared literal differs — so a fresh database and one an earlier
873+
* release created store the same thing for an insert that omits the field
874+
* ({@link physicalDefaultLiteral} says which physical DEFAULTs are literals;
875+
* an expression such as a `NOW()` default is never touched).
853876
*/
854877
defaultValue?: unknown;
855878
}
856879

880+
/**
881+
* [#36245] What a physical column DEFAULT is, read from the raw,
882+
* dialect-decorated text `columnInfo()` reports. MEASURED spellings
883+
* (SQLite / Postgres 16 / MariaDB 10.11, on columns `createColumn` built):
884+
*
885+
* - a string `'none'` · `'none'::character varying` · `'none'` (MySQL 8
886+
* reports it bare, `none`); an embedded quote is doubled (`'it''s'`);
887+
* - a number `'42'` · `'42'::numeric` or a bare `5` · `42.000…` (decimal);
888+
* - a boolean `'1'` / `'0'` · `true` / `false` · `1` / `0`;
889+
* - an expression `strftime(…)` · `CURRENT_TIMESTAMP` · `current_timestamp(3)`.
890+
*
891+
* `{ kind: 'literal', text }` carries the literal with its quoting and cast
892+
* removed; `none` is no DEFAULT (or an explicit NULL); `expression` is
893+
* anything else — a function call, a keyword, a cast over something that is
894+
* not a quoted literal — and is never acted on: this module cannot tell a
895+
* platform `NOW()` default from a DBA's sequence.
896+
*/
897+
export type PhysicalDefault =
898+
| { kind: 'none' }
899+
| { kind: 'literal'; text: string }
900+
| { kind: 'expression' };
901+
902+
const BARE_NUMBER = /^[+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?$/;
903+
const EXPRESSION_KEYWORD = /^(current_timestamp|current_date|current_time|localtimestamp|localtime|now|sysdate|uuid|gen_random_uuid|nextval)\b/i;
904+
const TRAILING_CAST = /^::\s*[A-Za-z_][\w\s"]*(\(\s*\d+(\s*,\s*\d+)?\s*\))?(\[\])?$/;
905+
906+
/** See {@link PhysicalDefault}. */
907+
export function physicalDefaultLiteral(raw: unknown): PhysicalDefault {
908+
if (raw === null || raw === undefined) return { kind: 'none' };
909+
if (typeof raw === 'number' || typeof raw === 'bigint') return { kind: 'literal', text: String(raw) };
910+
if (typeof raw === 'boolean') return { kind: 'literal', text: raw ? 'true' : 'false' };
911+
if (typeof raw !== 'string') return { kind: 'expression' };
912+
let s = raw.trim();
913+
// Postgres spells a negative number `(-5)` or `'-5'::integer`.
914+
const paren = /^\(\s*([+-]?[\d.eE+-]+)\s*\)$/.exec(s);
915+
if (paren && BARE_NUMBER.test(paren[1])) s = paren[1];
916+
if (s === '') return { kind: 'expression' };
917+
if (/^null(\s*::.*)?$/i.test(s)) return { kind: 'none' };
918+
if (s.startsWith("'")) {
919+
// One quoted literal, `''` an embedded quote, then nothing or one cast.
920+
let i = 1;
921+
let text = '';
922+
for (;;) {
923+
if (i >= s.length) return { kind: 'expression' };
924+
const ch = s[i];
925+
if (ch === "'") {
926+
if (s[i + 1] === "'") { text += "'"; i += 2; continue; }
927+
break;
928+
}
929+
text += ch;
930+
i += 1;
931+
}
932+
const rest = s.slice(i + 1).trim();
933+
if (rest === '' || TRAILING_CAST.test(rest)) return { kind: 'literal', text };
934+
return { kind: 'expression' };
935+
}
936+
if (BARE_NUMBER.test(s)) return { kind: 'literal', text: s };
937+
if (/^(true|false)$/i.test(s)) return { kind: 'literal', text: s.toLowerCase() };
938+
if (s.includes('(') || EXPRESSION_KEYWORD.test(s)) return { kind: 'expression' };
939+
// MySQL 8 reports a string literal bare; anything else bare is a keyword
940+
// this module does not know, which is not worth guessing at.
941+
return /\s/.test(s) || /^[A-Z_]+$/.test(s) ? { kind: 'expression' } : { kind: 'literal', text: s };
942+
}
943+
944+
/**
945+
* [#36245] Does a physical literal DEFAULT already say what `declared` says?
946+
* Answers `true` / `false`, or `null` when this module cannot judge the pair
947+
* (a temporal literal, whose physical spelling is the dialect's own rendering
948+
* of the instant) — and an unjudgeable pair is never reported.
949+
*
950+
* Numbers compare by value (`'42'`, `42`, `42.000…` are one default), booleans
951+
* by truth (`'1'`, `true`, `1`), everything else as text.
952+
*/
953+
export function physicalLiteralMatches(text: string, declared: string | number | boolean, fieldType: string | undefined): boolean | null {
954+
if (typeof declared === 'boolean') {
955+
const t = text.toLowerCase();
956+
if (t === '1' || t === 'true' || t === 't') return declared === true;
957+
if (t === '0' || t === 'false' || t === 'f') return declared === false;
958+
return false;
959+
}
960+
if (text === String(declared)) return true;
961+
const type = String(fieldType ?? '');
962+
if (type === 'date' || type === 'datetime' || type === 'time') return null;
963+
const asNumber = typeof declared === 'number' ? declared : (BARE_NUMBER.test(declared.trim()) ? Number(declared) : NaN);
964+
if (Number.isFinite(asNumber) && BARE_NUMBER.test(text)) return Number(text) === asNumber;
965+
return false;
966+
}
967+
968+
/** A literal DEFAULT as the drift message shows it: single-quoted, an embedded quote doubled. */
969+
function quoteDefaultForMessage(text: string): string {
970+
return `'${text.replace(/'/g, "''")}'`;
971+
}
972+
857973
/**
858974
* Does the physical column DEFAULT literally spell out `token`?
859975
*
@@ -1354,6 +1470,67 @@ export function diffManagedTable(args: {
13541470
});
13551471
}
13561472

1473+
// ── literal column DEFAULT (#36245) ──────────
1474+
// The column's literal DEFAULT follows the declaration. A table an earlier
1475+
// release created keeps the DEFAULT that release's declaration gave it —
1476+
// the additive sync never revisits an existing column — so an insert that
1477+
// omits the field stores the OLD default on that database and the declared
1478+
// one (or NULL) on a fresh one, and nothing said so. Two arms: the field
1479+
// declares no default any more (drop it), or a different literal (restate
1480+
// it). Detected here rather than fixed inline so it travels the same
1481+
// plan/apply road as every other divergence; `safe`, as the token arm above
1482+
// is: the statement cannot fail on existing rows and rewrites none.
1483+
//
1484+
// Judged only where `createColumn` would have emitted a literal itself: a
1485+
// token (`NOW()` has its own expression, the app-resolved ones the arm
1486+
// above), an object, a multi-value column (no scalar DEFAULT at all) and a
1487+
// physical EXPRESSION are left alone, and so is a column with no DEFAULT
1488+
// under a declared one (on MySQL a TEXT column cannot carry the literal).
1489+
{
1490+
const dv = field.defaultValue;
1491+
const physical = physicalDefaultLiteral(col.defaultValue);
1492+
const multiValue = isMultiValueField({ type: String(field.type ?? ''), multiple: field.multiple === true });
1493+
if (physical.kind === 'literal' && !multiValue) {
1494+
if (dv === undefined || dv === null) {
1495+
out.push({
1496+
kind: 'default_mismatch',
1497+
remoteName: table,
1498+
table,
1499+
column: fieldName,
1500+
expected: '(no column default)',
1501+
actual: `DEFAULT ${quoteDefaultForMessage(physical.text)}`,
1502+
severity: 'warning',
1503+
category: 'safe',
1504+
op: { type: 'drop_column_default', table, column: fieldName },
1505+
message:
1506+
`${table}.${fieldName}: the column carries DEFAULT ${quoteDefaultForMessage(physical.text)}, but the field ` +
1507+
`declares no default — every insert that omits the field stores that value here, where a new ` +
1508+
`database stores nothing. Dropping the default is non-destructive and rewrites no stored row. ` +
1509+
SAFE_COLUMN_REMEDY,
1510+
});
1511+
} else if ((typeof dv === 'string' || typeof dv === 'number' || typeof dv === 'boolean') && !isRuntimeDefaultValue(dv)) {
1512+
if (physicalLiteralMatches(physical.text, dv, field.type) === false) {
1513+
out.push({
1514+
kind: 'default_mismatch',
1515+
remoteName: table,
1516+
table,
1517+
column: fieldName,
1518+
expected: `DEFAULT ${quoteDefaultForMessage(String(dv))}`,
1519+
actual: `DEFAULT ${quoteDefaultForMessage(physical.text)}`,
1520+
severity: 'warning',
1521+
category: 'safe',
1522+
op: { type: 'set_column_default', table, column: fieldName },
1523+
message:
1524+
`${table}.${fieldName}: the column carries DEFAULT ${quoteDefaultForMessage(physical.text)}, but the field ` +
1525+
`declares ${quoteDefaultForMessage(String(dv))} — every insert that omits the field stores the old value ` +
1526+
`here, where a new database stores the declared one. Restating the default is non-destructive and ` +
1527+
`rewrites no stored row. ${SAFE_COLUMN_REMEDY}`,
1528+
});
1529+
}
1530+
}
1531+
}
1532+
}
1533+
13571534
// ── base type: a multi-value field over a stale textual column (#11535) ──
13581535
//
13591536
// `createColumn` materialises a multi-value field as `table.json(name)` —

0 commit comments

Comments
 (0)