Skip to content

Commit 7291c6f

Browse files
fix(driver-turso): the remote face gives a declared field's column the local face's DEFAULT (#37425)
<!-- claude-projects-attribution: {"github_login":"os-bill"} --> _Requested by **Bill** · [project thread](https://claude.ai/code/project/chan_016iMXWSZDzqWRWvWzdNo8wg?thread=cmsg_016iMXWSZDzqWRWvWzdNo8wg8ZBQe4UHadd2fGHGeWRW9V)_ repo:objectstack#5 · os-bill · session_01Utp6CbdHk3orAeensH6EzS Fixes #37345 Clause-②: yes (widening) Metadata-protocol: none (no key or value an author can write changes, and `defaultValue` means what it meant: the remote face now writes the column DEFAULT the local face already writes for the same declaration) ## 维护者速读 - 用户能看到什么变化:在托管的 Turso 环境里,给已有数据的对象新增一个"必填且带固定默认值"的字段,同步不再失败,老数据自动填上默认值;新建的表也和本地一样带上字段默认值。 - 为什么做:数据层同一驱动的本地与托管两种连接方式对同一字段定义给出不同结果,这次让托管一侧与本地一致。 - 出错会怎样:最坏情况是托管环境中某个对象的结构同步失败或建出的列默认值与本地不同,影响新增字段的那类同步;改动只在驱动建表语句里,可直接撤回。 - 要你做什么:无 ## What changes - **Remote face emits the declared column DEFAULT** (`packages/drivers/driver-turso/src/remote-transport.ts`, `columnDeclarationSQL`). Every `CREATE TABLE` and `ALTER TABLE … ADD COLUMN` this transport sends now carries ` DEFAULT …` for a field declaring a literal or `NOW()` `defaultValue`, nullable fields included, exactly where the local face's `createColumn` → `applyDeclaredColumnDefault` emits one (`sql-driver-column-creation.ts`, the unconditional emitter call at the end of `createColumn`; none on the multi-value short-circuit). So a `storage.notNull` field with a literal default, added to a populated table, is accepted remotely with its NOT NULL, as it is locally, and the existing rows take the default. - **One source in `driver-sql`, no third copy.** New exports: `emitsDeclaredColumnDefault` (the local predicate, already used by `createColumn`; the remote mirror `declaresEmittedColumnDefault` is deleted), `sqliteNowColumnDefaultSql` (the SQLite `NOW()` text, now what `nowColumnDefault`'s SQLite branch wraps in `knex.raw`, byte-identical) and `sqliteDeclaredColumnDefaultSql` (the DEFAULT text for a field, or `null`). The literal rendering still runs through knex on the local face (`col.defaultTo`); the shared renderer mirrors knex's SQLite output and a new test pins the two faces to one `dflt_value` per kind. - **Deliberate exception (scope amendment on the card): a `NOW()` DEFAULT on `ADD COLUMN` to a populated table is never emitted.** SQLite refuses a non-constant DEFAULT there; the local face sends it and fails the sync (#37413, the local defect and this face's `NOW()` half). The remote face keeps its earlier answer for that case: nullable is added with no DEFAULT, `storage.notNull` is refused. The populated-table probe now also fires when an added column declares a `NOW()` default (`addsRowSensitiveColumn`, was `addsNotNullColumn`); otherwise a sync adding only a nullable `NOW()` field would not know the table holds rows. - **A nullable field with a literal default, added to a populated remote table, now fills the existing rows with the default**, as on the local face (they read NULL before). Pinned by the parity test's populated case. - **Known limit, follow-up #37430:** the remote face cannot change a column DEFAULT once written. An edited or removed literal `defaultValue` gives `set_column_default` / `drop_column_default`, which `REMOTE_DRIFT_OP_ANSWERS` answers `needs-table-rebuild`, and the remote transport runs no rebuild; the stale DEFAULT stays and the finding stays reported. The changeset says so. - Docblocks: the recorded-asymmetry notes in `columnDeclarationSQL` and in `turso-remote-not-null.test.ts` case 5 are removed and replaced by the current contract and the `NOW()` pointer. ## Tests - `turso-remote-not-null.test.ts` case 5 inverted: a `storage.notNull` + literal default on a populated table gives one outcome on the local face and through `syncSchemasBatch` and `syncSchema` (notnull 1, the row reads the default, `tighten_not_null` empty, `detectManagedDrift` empty). The `NOW()` half is recorded, pointing at #37413: the local face refuses (nullable and `storage.notNull`); the remote face, through both doors, accepts nullable with no DEFAULT and refuses `storage.notNull`. - New `turso-remote-default-parity.test.ts` (#37345): per-kind reference (string, embedded quote, number, negative, integer, boolean both ways, date literal, select, `storage.notNull` literal, `NOW()` on datetime / date / time / text, and none for multi-value, `current_user`, object); the shared renderer gives each local `dflt_value`; `CREATE TABLE` parity and zero drift (read by both faces) through `syncSchemasBatch`, `syncSchema` and `initObjects`; `ADD COLUMN` to an empty table, `NOW()` included, same; `ADD COLUMN` to a populated table: every literal emitted and taken by the existing row, `NOW()` columns get none, zero drift. L1 rework added the renderer branches the first head left unpinned: `toggle`, the empty string, a JSON-typed column with a scalar literal (all in the per-kind set, so through every door and the drift read), and a boolean declaring the string `'false'` in its own describe (`'0'` on both faces and from the renderer, through all three doors; kept out of the drift reads, see Acceptance notes). <details><summary>Run readings</summary> - Targeted: `pnpm --filter @objectstack/driver-turso exec vitest run --maxWorkers=2 src/turso-remote-default-parity.test.ts src/turso-remote-not-null.test.ts` → Test Files 2 passed, Tests 29 passed. - `@objectstack/driver-turso` full suite (lock): Test Files 105 passed, 1 skipped; Tests 2671 passed, 36 skipped; VERDICT command-exit 0. - `@objectstack/driver-sql` full suite + `typecheck` of both packages (lock): Test Files 270 passed, 14 skipped; Tests 4551 passed, 265 skipped; both typechecks clean; VERDICT command-exit 0. - Ablation 1, remote DEFAULT emission removed (`columnDeclarationSQL` returns the declaration without ` DEFAULT …`, via `scripts/ablation-replace.mjs`, anchor 1 → 0, blob f571509 → bb885d44): 10 failed / 19 passed, the inverted case 5 red through both doors and every parity case red; restored, blob == HEAD, `git diff HEAD` empty. - Ablation 2, the populated-table `NOW()` withholding removed: 4 failed (parity populated case through both doors, case 5 `NOW()` record through both doors); restored, `git diff HEAD` empty. - Ablation 3, the probe trigger narrowed back to `storage.notNull` only: 2 failed (case 5 `NOW()` record through both doors); restored, `git diff HEAD` empty. - No `dist/` involved in ablations 1 to 3: the mutated file is `driver-turso` source, which the suite imports directly. - Rework head `f438ff8c`: targeted pair 32 passed. Ablation 4, the `toggle` branch of the shared renderer removed in `driver-sql` source (`ablation-replace.mjs --hold`, anchor 1 -> 0), `driver-sql` rebuilt, `ablation-dist-preflight.mjs` found the marker in `dist/`: 9 failed / 3 passed (the reference row and every door case). Restored (blob == HEAD, `git diff HEAD` empty), rebuilt, preflight `--absent` clean, targeted pair 32 passed again. </details> ## Acceptance notes - A test file over a shared harness: the remote/local harness is copied per file across the `turso-remote-*` suites (no shared harness file exists), so the new pins live in their own file, as the dispatch order names. - `NOW()` on a remote `CREATE TABLE` and on `ADD COLUMN` to an empty table now carries the expression DEFAULT, as locally; only the populated `ADD COLUMN` withholds it. The drift differ never acts on an expression DEFAULT, so neither shape reports drift. - A boolean field declaring the STRING default `'false'`: both faces write `'0'` (knex reads `'false'` as false), but the shared differ compares a string declaration as text and reports `set_column_default` drift on either face, which re-applying cannot settle. Pre-existing on the local face, not introduced here; reported to the seat with this round. - An existing remote table created before this change keeps no DEFAULT on its columns; the differ already leaves a column with no DEFAULT under a declared one alone, so nothing new is reported for those databases. ## Verification Read first: `packages/drivers/driver-turso/src/remote-transport.ts` `columnDeclarationSQL` and `addsRowSensitiveColumn` (the `NOW()` withholding and the probe trigger are the risk hunks); `packages/drivers/driver-sql/src/sql-driver-schema-sync.ts` `sqliteDeclaredColumnDefaultSql` / `sqliteNowColumnDefaultSql` (the `nowColumnDefault` SQLite branch must stay byte-identical). Two-minute check: `pnpm --filter @objectstack/driver-turso exec vitest run src/turso-remote-default-parity.test.ts src/turso-remote-not-null.test.ts` after building `@objectstack/driver-sql`; expect 29 passed. <details><summary>Local gates (os-dev scope: the derived list, CI runs the farm)</summary> - `node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack`: 72 families derived for this diff, run at `4084e2ee`. `--ran` with exit codes recorded: 72 derived, 69 run (all exit 0), 3 NOT MEASURED, 0 unrun. - NOT MEASURED: `check-plugin-teardown-shape.mjs --self-test` (reason: a shallow clone, its pinned fixture commit is unreachable), `check:dual-build-cjs-loads` and `check:lean-entry-closure` (reason: they read built output of packages this diff does not touch; not built locally). All three are left to CI. - After merging `origin/main` once (head `2687d387`; main brought one `packages/spec` constant): `driver-turso` closure rebuilt, `pnpm --filter @objectstack/spec check:generated` reported all 14 artifacts up to date, the targeted pair of files passed again (29 tests), and these were re-run on the final head with exit 0: `check:type-check-coverage`, `check:type-check-debt`, `check:driver-memory-census`, `check:platform-object-tenancy-census`, `check:system-context-census`, `check:nul-bytes`, `check:issue-citations`, `check:doc-authoring`. - No exported symbol was renamed or removed (three added), so the platform-checklist rename check does not apply. Rework head `f438ff8c` (changeset and one test file): the families that read those files re-run with exit 0: `check-adr-0087-registration --base origin/main`, `check-changeset-no-major --base origin/main`, `check-empty-changeset --base origin/main`, `check:changeset-gate-self-tests`, `check:issue-citations`, `check:doc-authoring`, `check:nul-bytes`, `check:cross-package-test-inputs`, `check:test-source-alias`, `check-closing-keyword-parity`, plus `check:type-check-coverage` and `check:type-check-debt`; `readClause2Line` on the changeset reads `yes` / `widening`. Full dogfood: not run (no `!` in the title and no `(narrowing)` arm). </details> 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- signed: repo:objectstack#5 · os-bill · session_01Utp6CbdHk3orAeensH6EzS --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 7d50dc8 commit 7291c6f

6 files changed

Lines changed: 444 additions & 76 deletions

File tree

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
---
2+
'@objectstack/driver-turso': patch
3+
'@objectstack/driver-sql': patch
4+
---
5+
6+
fix(driver-turso): the remote face gives a declared field's column the DEFAULT the local face gives it
7+
8+
Clause-②: yes (widening)
9+
Metadata-protocol: none (no key or value an author can write changes, and `defaultValue` means what it meant: the remote face now writes the column DEFAULT the local face already writes for the same declaration)
10+
11+
- **A `storage.notNull` field with a literal `defaultValue`, added to a table that already holds rows, now syncs on a hosted Turso/libSQL environment.** The remote face emitted no column DEFAULT for any field, so SQLite refused `ADD COLUMN … NOT NULL` there (`Cannot add a NOT NULL column with default value NULL`), and that object's whole sync failed through `syncSchema` and `syncSchemasBatch`; the local face accepted the same declaration. Both faces now add the column NOT NULL with the DEFAULT, and the existing rows take it.
12+
- **A fresh remote table carries the same column DEFAULTs as a fresh local one**, on `CREATE TABLE` and on `ADD COLUMN`, for every field that declares a literal or `NOW()` default, nullable fields included. A multi-value column, a runtime token other than `NOW()` (such as `current_user`) and an object default get none, as on the local face. The shared drift differ reads a remote column as no drift.
13+
- **A nullable field with a literal `defaultValue`, added to a remote table that already holds rows, now fills those rows with the default**, as on the local face; before, they read NULL.
14+
- **Known limit: the remote face cannot change a column DEFAULT once it has written one.** If an author later edits or removes a literal `defaultValue`, the drift differ reports it (`set_column_default` / `drop_column_default`), but on the remote face both need a table rebuild, which the remote transport does not run. The column keeps the old DEFAULT, so an insert that omits the field stores the old value, and the finding stays reported. Tracked in #37430.
15+
- **Not changed: a `NOW()` default on a column added to a table that already holds rows.** SQLite refuses a non-constant DEFAULT on that statement, so the remote face leaves it out and keeps its earlier answer: a nullable field is added with no DEFAULT, and a `storage.notNull` field is still refused. The local face currently refuses both; that defect is tracked separately.
16+
- New `@objectstack/driver-sql` exports for drivers that write SQLite DDL as text: `emitsDeclaredColumnDefault` (which fields get a column DEFAULT), `sqliteDeclaredColumnDefaultSql` (that DEFAULT's SQLite text, or `null`) and `sqliteNowColumnDefaultSql` (the SQLite `NOW()` expression for a column type, the one the knex path uses).

‎packages/drivers/driver-sql/src/index.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,10 @@ export { recoverUnencodedJsonText } from './unencoded-json-text.js';
2323
// face compiles SQL text with its own compiler, and must regroup by the same
2424
// rule the knex path does.
2525
export { FLAT_GROUP_MAX_MEMBERS, joinBalancedGroup } from './sql-driver-balanced-group.js';
26+
// [#37345] Which declared fields get a column DEFAULT, and that DEFAULT's SQLite
27+
// text. Exported because the Turso remote face writes its DDL as text, and must
28+
// give a column the DEFAULT the knex path gives it from the same rule.
29+
export { emitsDeclaredColumnDefault, sqliteDeclaredColumnDefaultSql, sqliteNowColumnDefaultSql } from './sql-driver-schema-sync.js';
2630
// [ADR-0155 D2, D4] Where a fixed-read leaf compiles and the predicates of its
2731
// fixed inner read. Exported because the Turso remote face compiles the leaf
2832
// with its own compiler, from the same walk and the same predicates.

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

Lines changed: 52 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2811,23 +2811,71 @@ export function nowColumnDefault(this: Pick<SchemaSyncHost, 'isMysql' | 'isPostg
28112811
if (type === 'datetime' && this.isMysql) return this.knex.fn.now(MYSQL_DATETIME_PRECISION);
28122812
return this.knex.fn.now();
28132813
}
2814+
return this.knex.raw(sqliteNowColumnDefaultSql(type));
2815+
}
2816+
2817+
/**
2818+
* [#37345] The SQLite `NOW()` column DEFAULT for a column of `type`, as SQL
2819+
* text: the SQLite branch of {@link nowColumnDefault}, which wraps it in
2820+
* `knex.raw`, and the one the Turso REMOTE face renders through
2821+
* {@link sqliteDeclaredColumnDefaultSql}. One string per type, so the two
2822+
* faces of that driver cannot write different `NOW()` defaults.
2823+
*/
2824+
export function sqliteNowColumnDefaultSql(type: string): string {
28142825
switch (type) {
2815-
case 'date': return this.knex.raw("(strftime('%Y-%m-%d', 'now'))");
2826+
case 'date': return "(strftime('%Y-%m-%d', 'now'))";
28162827
// The CASE trims a zero-millisecond `.000` so a defaulted row is
28172828
// byte-canonical ({@link canonicalTimeOfDay}) — `%f` alone would store
28182829
// `'01:55:08.000'` once in a thousand inserts, and that row would then
28192830
// miss an equality filter against the canonical `'01:55:08'`. SQLite
28202831
// fixes `'now'` per statement, so the three calls cannot straddle a
28212832
// millisecond boundary.
2822-
case 'time': return this.knex.raw(
2833+
case 'time': return (
28232834
"(case when strftime('%H:%M:%f', 'now') like '%.000' " +
2824-
"then strftime('%H:%M:%S', 'now') else strftime('%H:%M:%f', 'now') end)",
2835+
"then strftime('%H:%M:%S', 'now') else strftime('%H:%M:%f', 'now') end)"
28252836
);
28262837
// datetime (and any non-temporal field that opts into NOW()): canonical instant.
2827-
default: return this.knex.raw("(strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))");
2838+
default: return "(strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))";
28282839
}
28292840
}
28302841

2842+
/** [#37345] The field types `createColumn` builds through knex's `table.boolean`, whose DEFAULT knex spells `'1'` / `'0'`. */
2843+
const KNEX_BOOLEAN_COLUMN_TYPES: ReadonlySet<string> = new Set(['boolean', 'toggle']);
2844+
2845+
/**
2846+
* [#37345] The column DEFAULT {@link applyDeclaredColumnDefault} gives this
2847+
* field's column on SQLite, as the SQL text that follows `DEFAULT` — or
2848+
* `null` when it gives none. The Turso REMOTE face, which writes its DDL as
2849+
* text rather than through knex, renders a declared field's DEFAULT with this,
2850+
* so a remote table and a local one carry the same `dflt_value` for the same
2851+
* declaration and the shared drift differ reads them alike.
2852+
*
2853+
* Which fields get one is not decided here: {@link emitsDeclaredColumnDefault}
2854+
* (a literal or `NOW()`, never another runtime token, never an object) and the
2855+
* multi-value short-circuit `createColumn` takes before it reaches the
2856+
* emitter (a JSON column, no scalar DEFAULT) — the same two questions, asked
2857+
* in the same order. A `NOW()` default is {@link sqliteNowColumnDefaultSql},
2858+
* the string the local face's {@link nowColumnDefault} wraps.
2859+
*
2860+
* The literal is the one place this mirrors knex rather than sharing a
2861+
* function with it: the local face hands the value to `col.defaultTo`, and
2862+
* knex's SQLite column compiler renders it — `'1'` / `'0'` on a boolean
2863+
* column (the string `'false'` reading false), otherwise the value's
2864+
* `toString()` single-quoted with an embedded quote doubled (so a number is
2865+
* the quoted `'5'`). `turso-remote-default-parity.test.ts` holds the two
2866+
* faces to one `dflt_value` for each kind of default, so a knex upgrade that
2867+
* renders differently goes red there instead of forking the faces.
2868+
*/
2869+
export function sqliteDeclaredColumnDefaultSql(field: any): string | null {
2870+
if (!emitsDeclaredColumnDefault(field)) return null;
2871+
const type = String(field?.type || 'string');
2872+
if (isMultiValuedColumn(type, field)) return null;
2873+
const dv = field.defaultValue;
2874+
if (isNowDefaultValue(dv)) return sqliteNowColumnDefaultSql(type);
2875+
if (KNEX_BOOLEAN_COLUMN_TYPES.has(type)) return `'${dv === 'false' ? 0 : dv ? 1 : 0}'`;
2876+
return `'${String(dv).replace(/'/g, "''")}'`;
2877+
}
2878+
28312879
/**
28322880
* [#37258] Whether {@link applyDeclaredColumnDefault} gives this field's column
28332881
* a physical DEFAULT — asked by `createColumn` on `ALTER TABLE … ADD COLUMN`

‎packages/drivers/driver-turso/src/remote-transport.ts‎

Lines changed: 74 additions & 55 deletions
Original file line numberDiff line numberDiff line change
@@ -64,9 +64,14 @@ import {
6464
// local face (`SqlDriver.applyFilters`), `driver-memory` and `driver-mongodb`.
6565
import { findMisplacedReadableIds, readableIdsDriverRefusal } from '@objectstack/core';
6666
import { isComposedReadableIds, type FilterCondition } from '@objectstack/spec/data';
67-
// [#37281] The `defaultValue` token vocabulary, read by
68-
// `declaresEmittedColumnDefault` as the local face's DDL emitter reads it.
69-
import { isNowDefaultToken, isRuntimeDefaultToken } from '@objectstack/spec/data';
67+
// [#37345] A declared field's column DEFAULT, from the local face's own rule
68+
// and SQLite text: which fields get one (`emitsDeclaredColumnDefault`, the
69+
// question `SqlDriver.createColumn` asks) and what it says
70+
// (`sqliteDeclaredColumnDefaultSql`, the `dflt_value` the knex path writes).
71+
// ⛔ Never a copy of either in this file. See
72+
// {@link RemoteTransport.columnDeclarationSQL}.
73+
import { emitsDeclaredColumnDefault, sqliteDeclaredColumnDefaultSql } from '@objectstack/driver-sql';
74+
import { isNowDefaultToken } from '@objectstack/spec/data';
7075
// [ADR-0155 D2, D4] The fixed-read leaf: where it compiles and the predicates of
7176
// its fixed inner read, shared with the local face's compiler
7277
// (`SqlDriver#fixedReadLeafSubquery`), and the refusal every evaluator answers.
@@ -132,49 +137,40 @@ const BUILTIN_COLUMNS = new Set(['id', 'created_at', 'updated_at']);
132137
* (`driver-sql`'s `sql-driver.ts`) asks it — truthiness of `storage.notNull`,
133138
* whatever the field's type, `multiple: true` included, and never `required`.
134139
* See {@link RemoteTransport.columnDeclarationSQL}, the renderer that reads it,
135-
* and {@link addsNotNullColumn}, which decides whether a sync must ask if a
140+
* and {@link addsRowSensitiveColumn}, which decides whether a sync must ask if a
136141
* table holds rows.
137142
*/
138143
function declaresColumnNotNull(field: unknown): boolean {
139144
return Boolean((field as { storage?: { notNull?: unknown } } | null | undefined)?.storage?.notNull);
140145
}
141146

142-
/**
143-
* [#37281] Whether the field declares a column DEFAULT the local face emits
144-
* for it: a literal, or the `NOW()` token, never another runtime token
145-
* (`current_user`) and never an object. Asked exactly as the local face's
146-
* `emitsDeclaredColumnDefault` (`driver-sql`'s `sql-driver-schema-sync.ts`)
147-
* asks it, from the same two spec predicates in the same order;
148-
* `turso-remote-not-null.test.ts` holds the two faces to one answer for each
149-
* kind of default.
150-
*
151-
* This transport emits no declared DEFAULT itself. The question is asked so a
152-
* `storage.notNull` field carrying such a default keeps its NOT NULL on an
153-
* `ADD COLUMN` to a populated table, as on the local face, where the DEFAULT
154-
* fills the existing rows. See {@link RemoteTransport.columnDeclarationSQL}.
155-
*/
156-
function declaresEmittedColumnDefault(field: unknown): boolean {
157-
const dv = (field as { defaultValue?: unknown } | null | undefined)?.defaultValue;
158-
if (dv === undefined || dv === null) return false;
159-
if (isNowDefaultToken(dv)) return true;
160-
return !isRuntimeDefaultToken(dv) && typeof dv !== 'object';
161-
}
162-
163147
/**
164148
* [#37281] Whether the `ALTER TABLE … ADD COLUMN` statements a sync is about
165-
* to send for this table add a column declaring `storage.notNull`. Only then
166-
* does the sync ask whether the table holds a row
167-
* ({@link populatedTableProbe}), so a sync that adds no such column sends no
168-
* extra statement.
149+
* to send for this table add a column whose statement depends on whether the
150+
* table holds a row: one declaring `storage.notNull`, or [#37345] one whose
151+
* declared DEFAULT is the `NOW()` expression (withheld on a populated table,
152+
* see {@link RemoteTransport.columnDeclarationSQL}). Only then does the sync
153+
* ask whether the table holds a row ({@link populatedTableProbe}), so a sync
154+
* that adds no such column sends no extra statement.
169155
*/
170-
function addsNotNullColumn(fields: Record<string, any> | undefined, existingColumns: ReadonlySet<unknown>): boolean {
156+
function addsRowSensitiveColumn(fields: Record<string, any> | undefined, existingColumns: ReadonlySet<unknown>): boolean {
171157
return Object.entries(fields ?? {}).some(
172158
([name, field]) => !existingColumns.has(name)
173159
&& ((field as any)?.type || 'string') !== 'formula'
174-
&& declaresColumnNotNull(field),
160+
&& (declaresColumnNotNull(field) || declaresNowColumnDefault(field)),
175161
);
176162
}
177163

164+
/**
165+
* [#37345] Whether the column DEFAULT the local face gives this field is the
166+
* `NOW()` expression: a `NOW()` token the shared renderer emits at all (a
167+
* multi-value column gets no DEFAULT).
168+
*/
169+
function declaresNowColumnDefault(field: unknown): boolean {
170+
return isNowDefaultToken((field as { defaultValue?: unknown } | null | undefined)?.defaultValue)
171+
&& sqliteDeclaredColumnDefaultSql(field) !== null;
172+
}
173+
178174
/** [#37281] One row of the table, or none: whether it holds a row at all. */
179175
function populatedTableProbe(table: string): InStatement {
180176
return { sql: `SELECT 1 FROM "${table}" LIMIT 1`, args: [] };
@@ -2185,9 +2181,10 @@ export class RemoteTransport {
21852181
});
21862182
const existingColumns = new Set(columnsResult.rows.map((r: any) => r.name));
21872183
for (const c of existingColumns) materialized.add(String(c));
2188-
// [#37281] Asked only when an added column declares `storage.notNull`;
2189-
// see {@link columnDeclarationSQL} for what the answer changes.
2190-
const populated = addsNotNullColumn(objectDef.fields, existingColumns)
2184+
// [#37281] Asked only when an added column declares `storage.notNull`
2185+
// or [#37345] a `NOW()` DEFAULT; see {@link columnDeclarationSQL} for
2186+
// what the answer changes.
2187+
const populated = addsRowSensitiveColumn(objectDef.fields, existingColumns)
21912188
&& (await this.sendStatement(populatedTableProbe(tableName))).rows.length > 0;
21922189

21932190
for (const [name, field] of Object.entries(objectDef.fields)) {
@@ -2235,7 +2232,8 @@ export class RemoteTransport {
22352232
* network round-trips. The process may perform up to five batch calls: one
22362233
* to introspect existing tables, one to introspect the existing tables'
22372234
* columns together with the index names the database already carries, —
2238-
* only when an existing table is about to gain a `storage.notNull` column —
2235+
* only when an existing table is about to gain a `storage.notNull` column or a
2236+
* `NOW()` DEFAULT —
22392237
* one asking those tables whether they hold a row (#37281), one to apply DDL
22402238
* statements, and — only when an existing table is missing a declared index
22412239
* — one to retrofit those indexes. Once every declared column and index
@@ -2317,12 +2315,12 @@ export class RemoteTransport {
23172315
const columnsOf = existingSchemas.map((_, i) => new Set(introspection[i].rows.map((r: any) => r.name)));
23182316

23192317
// [#37281] Phase 2c, only when an existing table is about to gain a
2320-
// `storage.notNull` column: ONE read batch asking each such table
2318+
// `storage.notNull` column or [#37345] a `NOW()` DEFAULT: ONE read batch asking each such table
23212319
// whether it holds a row, as {@link syncSchema} asks it. No other sync
23222320
// pays it. See {@link columnDeclarationSQL} for what the answer changes.
23232321
const probed = existingSchemas
23242322
.map((_, i) => i)
2325-
.filter((i) => addsNotNullColumn((existingSchemas[i].schema as { fields?: Record<string, any> }).fields, columnsOf[i]));
2323+
.filter((i) => addsRowSensitiveColumn((existingSchemas[i].schema as { fields?: Record<string, any> }).fields, columnsOf[i]));
23262324
const populated = new Set<number>();
23272325
if (probed.length > 0) {
23282326
const probes = await this.sendBatch(probed.map((i) => populatedTableProbe(existingSchemas[i].object)), 'read');
@@ -2652,28 +2650,49 @@ export class RemoteTransport {
26522650
*
26532651
* Everywhere else the constraint stays: on `CREATE TABLE`, on an `ADD COLUMN`
26542652
* to an empty table (no row to hold a NULL), and for a field declaring a
2655-
* literal or `NOW()` `defaultValue` ({@link declaresEmittedColumnDefault}),
2656-
* which the local face emits as the column DEFAULT the existing rows take.
2657-
* Imposing NOT NULL on a column that already exists is not done here at all;
2658-
* that is `tighten_not_null`, and belongs to the migration path.
2659-
*
2660-
* ⚠️ That last case still differs between the faces, and it is a DEFAULT
2661-
* question, not a nullability one: this transport emits no declared column
2662-
* DEFAULT for any field, while `createColumn` emits a literal `defaultValue`
2663-
* (`applyDeclaredColumnDefault`). So a `storage.notNull` field that also
2664-
* declares a literal `defaultValue`, added to a populated table, is accepted
2665-
* locally (existing rows take the default) and refused here.
2666-
* `turso-remote-not-null.test.ts` records that asymmetry; closing it means
2667-
* deciding whether, and from which shared source, this face emits declared
2668-
* defaults. ⛔ Never drop the ` NOT NULL` for such a field to let the
2669-
* statement through: the local face keeps it, so the faces would fork on
2670-
* the column.
2653+
* literal or `NOW()` `defaultValue` (`emitsDeclaredColumnDefault`, the
2654+
* local face's own predicate, imported), which the local face emits as the
2655+
* column DEFAULT the existing rows take. Imposing NOT NULL on a column that
2656+
* already exists is not done here at all; that is `tighten_not_null`, and
2657+
* belongs to the migration path. ⛔ Never drop the ` NOT NULL` for such a
2658+
* field to let a statement through: the local face keeps it, so the faces
2659+
* would fork on the column.
2660+
*
2661+
* # The declared column DEFAULT (#37345)
2662+
*
2663+
* Last comes ` DEFAULT …`: the DEFAULT the local face's
2664+
* `applyDeclaredColumnDefault` gives the same field, rendered by
2665+
* `sqliteDeclaredColumnDefaultSql` from `driver-sql` — the same predicate
2666+
* (a literal or `NOW()`, never another runtime token, never an object, never
2667+
* a multi-value JSON column) and the same SQLite text, so a remote column
2668+
* and a local one carry one `dflt_value` and the shared drift differ, fed
2669+
* that value raw by the remote catalog read, reports neither. It is emitted
2670+
* for every field that declares one, nullable included, as `createColumn`
2671+
* emits it, on `CREATE TABLE` and on every `ADD COLUMN`. So a
2672+
* `storage.notNull` field with a literal default, added to a populated
2673+
* table, is accepted here as it is locally: the existing rows take the
2674+
* default. `turso-remote-not-null.test.ts` case 5 and
2675+
* `turso-remote-default-parity.test.ts` pin both faces to that one answer.
2676+
*
2677+
* ⚠️ One exception, deliberate: a `NOW()` default on an `ADD COLUMN` to a
2678+
* table that holds rows is NOT emitted. SQLite refuses a non-constant
2679+
* DEFAULT there (`Cannot add a column with non-constant default`), and the
2680+
* local face, which sends it, fails that object's whole sync on it — the
2681+
* defect #37413 records, with this face's `NOW()` half after it. ⛔ Never
2682+
* emit the `NOW()` expression on that statement: a nullable `NOW()` field
2683+
* added to a populated table is accepted on this face today, and the
2684+
* expression would break that sync on every hosted environment. Such a field
2685+
* keeps the answer it has always had here: nullable, added with no DEFAULT;
2686+
* `storage.notNull`, refused (`Cannot add a NOT NULL column with default
2687+
* value NULL`).
26712688
*/
26722689
private columnDeclarationSQL(field: any, tenantColumn: boolean = false, addedToPopulatedTable: boolean = false): string {
26732690
const colType = this.mapFieldTypeToSQL(field);
26742691
const notNull = declaresColumnNotNull(field)
2675-
&& !(addedToPopulatedTable && !declaresEmittedColumnDefault(field));
2676-
return notNull || tenantColumn ? `${colType} NOT NULL` : colType;
2692+
&& !(addedToPopulatedTable && !emitsDeclaredColumnDefault(field));
2693+
const declared = notNull || tenantColumn ? `${colType} NOT NULL` : colType;
2694+
const columnDefault = addedToPopulatedTable && declaresNowColumnDefault(field) ? null : sqliteDeclaredColumnDefaultSql(field);
2695+
return columnDefault === null ? declared : `${declared} DEFAULT ${columnDefault}`;
26772696
}
26782697

26792698
/**

0 commit comments

Comments
 (0)