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