Skip to content

Commit fe7fb7e

Browse files
committed
refactor(driver-sql): move the declared column DEFAULT emission out of sql-driver.ts into sql-driver-schema-sync.ts
Cut 19 of the sql-driver.ts split. The bodies of nowColumnDefault and applyDeclaredColumnDefault move unedited into the existing seam module, through SchemaSyncHost, which already listed every member they read. The class keeps both methods as delegating stubs. MYSQL_DATETIME_PRECISION and isNowDefaultValue gain export in place; isRuntimeDefaultToken is now read only by the module. sql-driver.ts: 18,447 -> 18,406 lines. Co-authored-by: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01FEkQ5m67V6oBcEqg8yLDKL
1 parent 4049efa commit fe7fb7e

2 files changed

Lines changed: 107 additions & 66 deletions

File tree

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

Lines changed: 84 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,19 @@
119119
* reference counts from `sql-driver.ts`, as before. `sql-driver.ts` no longer
120120
* reads `fieldHasColumn` as a value.
121121
*
122+
* [#25521 cut 19] The declared column DEFAULT emission joined them the same
123+
* way: `nowColumnDefault`, the driver-native DEFAULT for a `defaultValue:
124+
* 'NOW()'` field on each dialect, and `applyDeclaredColumnDefault`, which
125+
* decides what a field's `defaultValue` becomes in DDL and calls it. The SQLite
126+
* rebuild above already reached both through the host; `createColumn` and
127+
* `createAuditTimestampColumn`, which call them too, stay in the class, and so
128+
* do both methods. `SchemaSyncHost` already listed every member these bodies
129+
* read. The module-level declarations they read are imported from where they
130+
* are declared: `MYSQL_DATETIME_PRECISION` and `isNowDefaultValue` (which now
131+
* carry `export`) from `sql-driver.ts`, which still reads both, and
132+
* `isRuntimeDefaultToken` from `@objectstack/spec/data`, which `sql-driver.ts`
133+
* no longer reads.
134+
*
122135
* A MOVE, not a redesign. Each function below is the body of the `SqlDriver`
123136
* method of the same name as it stood, re-indented one level and otherwise
124137
* unedited: the same dialect statements, the same rebuild procedure, the same
@@ -149,15 +162,16 @@
149162
*/
150163

151164
import { isUniqueViolationError } from '@objectstack/types';
165+
import type { Knex } from 'knex';
152166
import { StorageNameMapping } from '@objectstack/spec/system';
153167
import { carriesNullSafeTenantKeyPart, ceremonyOwnedDropFinding, describeMissingIndexColumns, diffManagedIndexes, diffManagedTable, diffUnbuildableIndexes, driftKey, expectedIndexes, fieldHasColumn, GLOBAL_TENANT, indexedKeyColumns, isCeremonyOwnedColumnDrop, isIndexDriftOp, legacyUniqueReplacements, normalizeDeclaredIndex, type DeclaredIndexInput, type DriftOp, type ManagedDriftEntry, type PendingSchemaWork, type PhysicalColumn } from './schema-drift.js';
154168
import { isJsonColumnType, mediaColumnMoveDialect, mediaColumnMovePlan, type MediaColumnMovePlan, type MediaColumnMoveRefusal, type MediaColumnMoveScan } from './media-column-move.js';
155169
import { StandardErrorCode } from '@objectstack/spec/api';
156170
import { recoverUnencodedJsonText } from './unencoded-json-text.js';
157171
import { aggregandColumnClass } from '@objectstack/core';
158-
import { FILE_REFERENCE_TYPES, NUMERIC_VALUE_TYPES, parseAutonumberFormat, resolveAutonumberFormat, type AutonumberToken } from '@objectstack/spec/data';
172+
import { FILE_REFERENCE_TYPES, isRuntimeDefaultToken, NUMERIC_VALUE_TYPES, parseAutonumberFormat, resolveAutonumberFormat, type AutonumberToken } from '@objectstack/spec/data';
159173
import { formatAttribute, undeliveredStorageAttributes, type UndeliveredAttribute } from './builtin-column-collision.js';
160-
import { AUDIT_TIMESTAMP_COLUMNS, declaredValueShapes, type IntrospectedColumn, isMultiValuedColumn, LOCK_WAIT_REFUSAL, NUMERIC_SCALAR_TYPES, type SqlDriver, SQLITE_NON_TEMPORAL_TEXT_REFS, SQLITE_TIME_EXPR_REFS } from './sql-driver.js';
174+
import { AUDIT_TIMESTAMP_COLUMNS, declaredValueShapes, type IntrospectedColumn, isMultiValuedColumn, isNowDefaultValue, LOCK_WAIT_REFUSAL, MYSQL_DATETIME_PRECISION, NUMERIC_SCALAR_TYPES, type SqlDriver, SQLITE_NON_TEMPORAL_TEXT_REFS, SQLITE_TIME_EXPR_REFS } from './sql-driver.js';
161175

162176
/**
163177
* The `SqlDriver` members the functions below read — every one of them, and
@@ -2064,3 +2078,71 @@ export async function previewTimeConvergence(this: Pick<SchemaSyncHost, 'isMysql
20642078
return [];
20652079
}
20662080
}
2081+
2082+
/** The body of `SqlDriver#nowColumnDefault`; the method's docblock there is its contract. */
2083+
export function nowColumnDefault(this: Pick<SchemaSyncHost, 'isMysql' | 'isPostgres' | 'isSqlite' | 'knex'>, type: string): Knex.Raw {
2084+
if (!this.isSqlite) {
2085+
// A `time` column deserves the same reasoning on the native dialects
2086+
// (#3994): `knex.fn.now()` compiles to CURRENT_TIMESTAMP, which a TIME
2087+
// column resolves in the SERVER's timezone on Postgres and the INSERTING
2088+
// session's timezone on MySQL — measured as three different wall clocks
2089+
// for one instant across the three dialects. Pin the default to the UTC
2090+
// time-of-day, matching what the driver's own writes and the SQLite
2091+
// branch below produce. (MySQL 8.0 additionally REJECTS a plain
2092+
// CURRENT_TIMESTAMP default on a TIME column — only the parenthesised
2093+
// expression form, MySQL 8.0.13+/MariaDB 10.2+, is legal there at all.)
2094+
if (type === 'time') {
2095+
if (this.isMysql) return this.knex.raw('(cast(utc_timestamp(3) as time(3)))');
2096+
if (this.isPostgres) return this.knex.raw("(timezone('utc', now())::time(3))");
2097+
}
2098+
// `date` has the same two problems one type over (#4022): a bare
2099+
// CURRENT_TIMESTAMP default resolves the calendar day in the SERVER's
2100+
// timezone on Postgres (measured: a UTC-12 server records YESTERDAY),
2101+
// and MySQL 8.0 rejects it on a DATE column outright (MariaDB is merely
2102+
// permissive; the driver's UTC-pinned session masked the semantic half
2103+
// there). Same fix as `time`: an expression default reading the UTC
2104+
// clock, which is also what `formatInput`'s NOW() safety-net and the
2105+
// SQLite branch below store.
2106+
if (type === 'date') {
2107+
if (this.isMysql) return this.knex.raw('(cast(utc_timestamp() as date))');
2108+
if (this.isPostgres) return this.knex.raw("(timezone('utc', now())::date)");
2109+
}
2110+
// `datetime` on MySQL (#21241): the column is `DATETIME(n)` (see
2111+
// `createColumn`), and MySQL REFUSES a `CURRENT_TIMESTAMP` default whose
2112+
// precision differs from its column's — the whole `CREATE TABLE` fails
2113+
// with "Invalid default value". The bare `knex.fn.now()` below is
2114+
// precision 0, so the default carries the column's precision from the
2115+
// one source both read. Postgres keeps the bare form: its `timestamptz`
2116+
// takes `CURRENT_TIMESTAMP` at microsecond precision, measured accepted.
2117+
if (type === 'datetime' && this.isMysql) return this.knex.fn.now(MYSQL_DATETIME_PRECISION);
2118+
return this.knex.fn.now();
2119+
}
2120+
switch (type) {
2121+
case 'date': return this.knex.raw("(strftime('%Y-%m-%d', 'now'))");
2122+
// The CASE trims a zero-millisecond `.000` so a defaulted row is
2123+
// byte-canonical ({@link canonicalTimeOfDay}) — `%f` alone would store
2124+
// `'01:55:08.000'` once in a thousand inserts, and that row would then
2125+
// miss an equality filter against the canonical `'01:55:08'`. SQLite
2126+
// fixes `'now'` per statement, so the three calls cannot straddle a
2127+
// millisecond boundary.
2128+
case 'time': return this.knex.raw(
2129+
"(case when strftime('%H:%M:%f', 'now') like '%.000' " +
2130+
"then strftime('%H:%M:%S', 'now') else strftime('%H:%M:%f', 'now') end)",
2131+
);
2132+
// datetime (and any non-temporal field that opts into NOW()): canonical instant.
2133+
default: return this.knex.raw("(strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))");
2134+
}
2135+
}
2136+
2137+
/** The body of `SqlDriver#applyDeclaredColumnDefault`; the method's docblock there is its contract. */
2138+
export function applyDeclaredColumnDefault(this: Pick<SchemaSyncHost, 'nowColumnDefault'>, col: Knex.ColumnBuilder, field: any, type: string): void {
2139+
const dv = field?.defaultValue;
2140+
if (dv === undefined || dv === null) return;
2141+
if (isNowDefaultValue(dv)) {
2142+
col.defaultTo(this.nowColumnDefault(type));
2143+
return;
2144+
}
2145+
if (isRuntimeDefaultToken(dv)) return;
2146+
if (typeof dv === 'object') return;
2147+
col.defaultTo(dv as any);
2148+
}

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

Lines changed: 23 additions & 64 deletions
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ import {
5555
// list of its own — which `defaultValue`s are instructions rather than literals,
5656
// so the engine and this driver can never disagree about what may become a
5757
// physical column DEFAULT.
58-
import { isNowDefaultToken, isRuntimeDefaultToken } from '@objectstack/spec/data';
58+
import { isNowDefaultToken } from '@objectstack/spec/data';
5959
// [#5702] The retired filter operators and the prescription each refusal
6060
// prints. Read from the spec rather than restated here for the reason the
6161
// #5701 table itself gives: five refusal sites that each write their own
@@ -168,7 +168,9 @@ import {
168168
// federated registration `registerExternalObject`.
169169
// [#25521 cut 18] And the deferred-DDL previews (`previewDeferredSchemaWork`, `previewDatetimeConvergence`,
170170
// `previewTimeConvergence`): the read-only plan of what the deferred schema sync would do.
171-
import { applyDriftOpInPlace, applyIndexDriftOp, applyMigrationEntries, applyNullSafeUniquePreflight, backfillCanonicalDatetimes, backfillCanonicalJsonEncoding, backfillCanonicalTimes, convergeJsonColumn, countNonTemporalTextRows, createNullSafeUniqueIndex, detectManagedDrift, detectTableDrift, detectTableIndexDrift, ensureRotation, legacyMysqlTimeColumns, legacyMysqlTimestampColumns, planMediaColumnMove, previewDatetimeConvergence, previewDeferredSchemaWork, previewTimeConvergence, rebuildSqliteTablePatched, reconcileAndWarnDrift, registerExternalObject, restoreBareIndexAfterFailedTighten, rotationColumnList, rotationShardKey, runWideningAlters, syncDeclaredIndexes, warnBuiltinColumnCollisions } from './sql-driver-schema-sync.js';
171+
// [#25521 cut 19] And the declared column DEFAULT emission (`nowColumnDefault`, `applyDeclaredColumnDefault`):
172+
// what a field's `defaultValue` becomes in the DDL of a fresh or rebuilt column.
173+
import { applyDeclaredColumnDefault, applyDriftOpInPlace, applyIndexDriftOp, applyMigrationEntries, applyNullSafeUniquePreflight, backfillCanonicalDatetimes, backfillCanonicalJsonEncoding, backfillCanonicalTimes, convergeJsonColumn, countNonTemporalTextRows, createNullSafeUniqueIndex, detectManagedDrift, detectTableDrift, detectTableIndexDrift, ensureRotation, legacyMysqlTimeColumns, legacyMysqlTimestampColumns, nowColumnDefault, planMediaColumnMove, previewDatetimeConvergence, previewDeferredSchemaWork, previewTimeConvergence, rebuildSqliteTablePatched, reconcileAndWarnDrift, registerExternalObject, restoreBareIndexAfterFailedTighten, rotationColumnList, rotationShardKey, runWideningAlters, syncDeclaredIndexes, warnBuiltinColumnCollisions } from './sql-driver-schema-sync.js';
172174
// [#25521 cut 11] The autonumber sequence path (`getNextSequenceValue`, `fillAutoNumberFields`,
173175
// `issueAutonumbers`, `maxAutonumberCounter`, and the #5495 collision re-seed `collidingAutoNumberReservations`
174176
// and `resyncSequenceToDataMax`); the methods of the same names below hand each body the members it reads
@@ -482,7 +484,7 @@ export const AUDIT_TIMESTAMP_COLUMNS = ['created_at', 'updated_at'] as const;
482484
* datetime field (`sys_activity.timestamp`, `sys_presence.last_seen`) was
483485
* never created, and its data door answered `500`.
484486
*/
485-
const MYSQL_DATETIME_PRECISION = 3;
487+
export const MYSQL_DATETIME_PRECISION = 3;
486488

487489
/**
488490
* Read-side repair for the builtin audit timestamps on SQLite.
@@ -572,7 +574,7 @@ function presentAuditTimestampOutput(value: unknown): unknown {
572574
* itself lives in `@objectstack/spec/data` so the engine's insert-time
573575
* resolution and this driver's DDL read one set (#4560).
574576
*/
575-
const isNowDefaultValue = isNowDefaultToken;
577+
export const isNowDefaultValue = isNowDefaultToken;
576578

577579
/**
578580
* Read-side normalization for user-declared `Field.datetime` columns on SQLite.
@@ -15474,57 +15476,18 @@ export class SqlDriver implements IDataDriver {
1547415476
* reads are uniform without a schema migration.
1547515477
*/
1547615478
protected nowColumnDefault(type: string): Knex.Raw {
15477-
if (!this.isSqlite) {
15478-
// A `time` column deserves the same reasoning on the native dialects
15479-
// (#3994): `knex.fn.now()` compiles to CURRENT_TIMESTAMP, which a TIME
15480-
// column resolves in the SERVER's timezone on Postgres and the INSERTING
15481-
// session's timezone on MySQL — measured as three different wall clocks
15482-
// for one instant across the three dialects. Pin the default to the UTC
15483-
// time-of-day, matching what the driver's own writes and the SQLite
15484-
// branch below produce. (MySQL 8.0 additionally REJECTS a plain
15485-
// CURRENT_TIMESTAMP default on a TIME column — only the parenthesised
15486-
// expression form, MySQL 8.0.13+/MariaDB 10.2+, is legal there at all.)
15487-
if (type === 'time') {
15488-
if (this.isMysql) return this.knex.raw('(cast(utc_timestamp(3) as time(3)))');
15489-
if (this.isPostgres) return this.knex.raw("(timezone('utc', now())::time(3))");
15490-
}
15491-
// `date` has the same two problems one type over (#4022): a bare
15492-
// CURRENT_TIMESTAMP default resolves the calendar day in the SERVER's
15493-
// timezone on Postgres (measured: a UTC-12 server records YESTERDAY),
15494-
// and MySQL 8.0 rejects it on a DATE column outright (MariaDB is merely
15495-
// permissive; the driver's UTC-pinned session masked the semantic half
15496-
// there). Same fix as `time`: an expression default reading the UTC
15497-
// clock, which is also what `formatInput`'s NOW() safety-net and the
15498-
// SQLite branch below store.
15499-
if (type === 'date') {
15500-
if (this.isMysql) return this.knex.raw('(cast(utc_timestamp() as date))');
15501-
if (this.isPostgres) return this.knex.raw("(timezone('utc', now())::date)");
15502-
}
15503-
// `datetime` on MySQL (#21241): the column is `DATETIME(n)` (see
15504-
// `createColumn`), and MySQL REFUSES a `CURRENT_TIMESTAMP` default whose
15505-
// precision differs from its column's — the whole `CREATE TABLE` fails
15506-
// with "Invalid default value". The bare `knex.fn.now()` below is
15507-
// precision 0, so the default carries the column's precision from the
15508-
// one source both read. Postgres keeps the bare form: its `timestamptz`
15509-
// takes `CURRENT_TIMESTAMP` at microsecond precision, measured accepted.
15510-
if (type === 'datetime' && this.isMysql) return this.knex.fn.now(MYSQL_DATETIME_PRECISION);
15511-
return this.knex.fn.now();
15512-
}
15513-
switch (type) {
15514-
case 'date': return this.knex.raw("(strftime('%Y-%m-%d', 'now'))");
15515-
// The CASE trims a zero-millisecond `.000` so a defaulted row is
15516-
// byte-canonical ({@link canonicalTimeOfDay}) — `%f` alone would store
15517-
// `'01:55:08.000'` once in a thousand inserts, and that row would then
15518-
// miss an equality filter against the canonical `'01:55:08'`. SQLite
15519-
// fixes `'now'` per statement, so the three calls cannot straddle a
15520-
// millisecond boundary.
15521-
case 'time': return this.knex.raw(
15522-
"(case when strftime('%H:%M:%f', 'now') like '%.000' " +
15523-
"then strftime('%H:%M:%S', 'now') else strftime('%H:%M:%f', 'now') end)",
15524-
);
15525-
// datetime (and any non-temporal field that opts into NOW()): canonical instant.
15526-
default: return this.knex.raw("(strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))");
15527-
}
15479+
// [#25521 cut 19] The body moved to `sql-driver-schema-sync.ts` (see `SchemaSyncHost`).
15480+
const readIsMysql = () => this.isMysql;
15481+
const readIsPostgres = () => this.isPostgres;
15482+
const readIsSqlite = () => this.isSqlite;
15483+
const readKnex = () => this.knex;
15484+
const host: ThisParameterType<typeof nowColumnDefault> = {
15485+
get isMysql() { return readIsMysql(); },
15486+
get isPostgres() { return readIsPostgres(); },
15487+
get isSqlite() { return readIsSqlite(); },
15488+
get knex() { return readKnex(); },
15489+
};
15490+
return nowColumnDefault.call(host, type);
1552815491
}
1552915492

1553015493
/**
@@ -17380,15 +17343,11 @@ export class SqlDriver implements IDataDriver {
1738017343
* `sql-driver-option-default-ddl.test.ts`.
1738117344
*/
1738217345
protected applyDeclaredColumnDefault(col: Knex.ColumnBuilder, field: any, type: string): void {
17383-
const dv = field?.defaultValue;
17384-
if (dv === undefined || dv === null) return;
17385-
if (isNowDefaultValue(dv)) {
17386-
col.defaultTo(this.nowColumnDefault(type));
17387-
return;
17388-
}
17389-
if (isRuntimeDefaultToken(dv)) return;
17390-
if (typeof dv === 'object') return;
17391-
col.defaultTo(dv as any);
17346+
// [#25521 cut 19] The body moved to `sql-driver-schema-sync.ts` (see `SchemaSyncHost`).
17347+
const host: ThisParameterType<typeof applyDeclaredColumnDefault> = {
17348+
nowColumnDefault: (...a) => this.nowColumnDefault(...a),
17349+
};
17350+
return applyDeclaredColumnDefault.call(host, col, field, type);
1739217351
}
1739317352

1739417353
// ── Database helpers ────────────────────────────────────────────────────────

0 commit comments

Comments
 (0)