@objectstack/driver-sql 10.0.0 → 10.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -30,8 +30,12 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
30
30
  // src/index.ts
31
31
  var index_exports = {};
32
32
  __export(index_exports, {
33
+ BUILTIN_COLUMNS: () => BUILTIN_COLUMNS,
33
34
  SqlDriver: () => SqlDriver,
34
- default: () => index_default
35
+ default: () => index_default,
36
+ diffManagedTable: () => diffManagedTable,
37
+ driftKey: () => driftKey,
38
+ fieldHasColumn: () => fieldHasColumn
35
39
  });
36
40
  module.exports = __toCommonJS(index_exports);
37
41
 
@@ -39,6 +43,108 @@ module.exports = __toCommonJS(index_exports);
39
43
  var import_data = require("@objectstack/spec/data");
40
44
  var import_system = require("@objectstack/spec/system");
41
45
  var import_shared = require("@objectstack/spec/shared");
46
+
47
+ // src/schema-drift.ts
48
+ var BUILTIN_COLUMNS = /* @__PURE__ */ new Set(["id", "created_at", "updated_at"]);
49
+ function fieldHasColumn(field) {
50
+ if (field?.multiple) return true;
51
+ return (field?.type ?? "string") !== "formula";
52
+ }
53
+ function enforcesVarcharLength(dialect) {
54
+ return dialect === "postgres" || dialect === "mysql";
55
+ }
56
+ function diffManagedTable(args) {
57
+ const { table, fields, columns, dialect } = args;
58
+ const out = [];
59
+ const columnsByName = new Map(columns.map((c) => [c.name, c]));
60
+ const expectedColumns = /* @__PURE__ */ new Set();
61
+ for (const [fieldName, field] of Object.entries(fields ?? {})) {
62
+ if (BUILTIN_COLUMNS.has(fieldName)) continue;
63
+ if (!fieldHasColumn(field)) continue;
64
+ expectedColumns.add(fieldName);
65
+ const col = columnsByName.get(fieldName);
66
+ if (!col) continue;
67
+ const expectNullable = field.required !== true;
68
+ if (expectNullable && !col.nullable) {
69
+ out.push({
70
+ kind: "nullability_mismatch",
71
+ remoteName: table,
72
+ table,
73
+ column: fieldName,
74
+ expected: "NULL",
75
+ actual: "NOT NULL",
76
+ severity: "warning",
77
+ category: "safe",
78
+ op: { type: "relax_not_null", table, column: fieldName },
79
+ message: `${table}.${fieldName}: metadata is optional but the column is NOT NULL \u2014 writes that omit it fail. Run "os migrate" to relax it.`
80
+ });
81
+ } else if (!expectNullable && col.nullable) {
82
+ out.push({
83
+ kind: "nullability_mismatch",
84
+ remoteName: table,
85
+ table,
86
+ column: fieldName,
87
+ expected: "NOT NULL",
88
+ actual: "NULL",
89
+ severity: "error",
90
+ category: "destructive",
91
+ op: { type: "tighten_not_null", table, column: fieldName },
92
+ message: `${table}.${fieldName}: metadata is required but the column is nullable \u2014 existing nulls must be backfilled. Run "os migrate apply --allow-destructive".`
93
+ });
94
+ }
95
+ if (enforcesVarcharLength(dialect) && typeof field.maxLength === "number" && typeof col.maxLength === "number" && field.maxLength !== col.maxLength) {
96
+ if (field.maxLength > col.maxLength) {
97
+ out.push({
98
+ kind: "type_mismatch",
99
+ remoteName: table,
100
+ table,
101
+ column: fieldName,
102
+ expected: `varchar(${field.maxLength})`,
103
+ actual: `varchar(${col.maxLength})`,
104
+ severity: "warning",
105
+ category: "safe",
106
+ op: { type: "widen_varchar", table, column: fieldName, to: field.maxLength, from: col.maxLength },
107
+ message: `${table}.${fieldName}: metadata allows ${field.maxLength} chars but the column caps at ${col.maxLength} \u2014 widen via "os migrate".`
108
+ });
109
+ } else {
110
+ out.push({
111
+ kind: "type_mismatch",
112
+ remoteName: table,
113
+ table,
114
+ column: fieldName,
115
+ expected: `varchar(${field.maxLength})`,
116
+ actual: `varchar(${col.maxLength})`,
117
+ severity: "error",
118
+ category: "destructive",
119
+ op: { type: "narrow_varchar", table, column: fieldName, to: field.maxLength, from: col.maxLength },
120
+ message: `${table}.${fieldName}: metadata caps at ${field.maxLength} chars but the column allows ${col.maxLength} \u2014 narrowing may truncate. "os migrate apply --allow-destructive".`
121
+ });
122
+ }
123
+ }
124
+ }
125
+ for (const col of columns) {
126
+ if (BUILTIN_COLUMNS.has(col.name)) continue;
127
+ if (expectedColumns.has(col.name)) continue;
128
+ out.push({
129
+ kind: "unmapped_column",
130
+ remoteName: table,
131
+ table,
132
+ column: col.name,
133
+ expected: "(absent)",
134
+ actual: col.type,
135
+ severity: "warning",
136
+ category: "destructive",
137
+ op: { type: "drop_column", table, column: col.name },
138
+ message: `${table}.${col.name}: column exists in the database but not in metadata (orphaned) \u2014 "os migrate apply --allow-destructive" to drop it.`
139
+ });
140
+ }
141
+ return out;
142
+ }
143
+ function driftKey(d) {
144
+ return `${d.table}.${d.column ?? ""}:${d.kind}`;
145
+ }
146
+
147
+ // src/sql-driver.ts
42
148
  var import_knex = __toESM(require("knex"));
43
149
  var import_nanoid = require("nanoid");
44
150
  var import_node_crypto = require("crypto");
@@ -152,8 +258,19 @@ var SqlDriver = class {
152
258
  this.logger = {
153
259
  warn: (msg, meta) => console.warn(msg, meta ?? "")
154
260
  };
155
- const { schemaMode, ...knexConfig } = config;
261
+ /**
262
+ * Metadata field defs for every table this driver manages, captured during
263
+ * `initObjects` (tableName → fields). The source of truth that
264
+ * {@link detectManagedDrift} diffs the physical schema against.
265
+ */
266
+ this.managedObjectFields = /* @__PURE__ */ new Map();
267
+ /** Declared indexes per managed table (tableName → indexes[]), captured in `initObjects`. Used to recreate indexes after a SQLite table rebuild. */
268
+ this.managedObjectIndexes = /* @__PURE__ */ new Map();
269
+ /** De-dup set for boot-time drift warnings (keyed by {@link driftKey}). */
270
+ this.driftWarned = /* @__PURE__ */ new Set();
271
+ const { schemaMode, autoMigrate, ...knexConfig } = config;
156
272
  this.schemaMode = schemaMode ?? "managed";
273
+ this.autoMigrate = autoMigrate ?? "off";
157
274
  this.config = knexConfig;
158
275
  this.knex = (0, import_knex.default)(knexConfig);
159
276
  }
@@ -971,6 +1088,37 @@ var SqlDriver = class {
971
1088
  this.assertSchemaMutable("dropTable");
972
1089
  await this.knex.schema.dropTableIfExists(object);
973
1090
  }
1091
+ /**
1092
+ * Resolve the per-table tenant-isolation column for a schema, honoring an
1093
+ * explicit tenancy opt-out. Single source of truth for both {@link initObjects}
1094
+ * and {@link registerExternalObject} (they previously inlined this logic and
1095
+ * drifted).
1096
+ *
1097
+ * Precedence:
1098
+ * 1. `tenancy.enabled === false` → `null` (NO driver-level org scope), even
1099
+ * when the object carries an `organization_id` column. Platform-global
1100
+ * objects (e.g. `sys_license`) keep an optional, often-NULL org FK but must
1101
+ * NOT be tenant-scoped: otherwise an authenticated caller's active-org
1102
+ * `DriverOptions.tenantId` injects `WHERE organization_id = <org>` and every
1103
+ * NULL-org / cross-org row silently disappears (the platform admin then
1104
+ * reads zero licenses while an unscoped/anonymous read still sees them).
1105
+ * The declarative branch below already respected `enabled !== false`; the
1106
+ * implicit `organization_id` fallback did not — this closes that gap.
1107
+ * 2. Declared `tenancy.tenantField` (when that field exists on the object).
1108
+ * 3. Implicit `organization_id` column detection (legacy objects whose
1109
+ * multi-tenant column was injected by the kernel without a spec migration).
1110
+ */
1111
+ computeTenantField(schema) {
1112
+ const tenancyDecl = schema?.tenancy;
1113
+ if (tenancyDecl?.enabled === false) return null;
1114
+ const fields = schema?.fields;
1115
+ if (tenancyDecl?.tenantField) {
1116
+ const declared = String(tenancyDecl.tenantField);
1117
+ if (fields && Object.prototype.hasOwnProperty.call(fields, declared)) return declared;
1118
+ }
1119
+ if (fields && Object.prototype.hasOwnProperty.call(fields, "organization_id")) return "organization_id";
1120
+ return null;
1121
+ }
974
1122
  /**
975
1123
  * Batch-initialise tables from an array of object definitions.
976
1124
  */
@@ -1022,18 +1170,7 @@ var SqlDriver = class {
1022
1170
  const dateCols = [];
1023
1171
  const datetimeCols = [];
1024
1172
  const autoNumberCols = [];
1025
- const tenancyDecl = schema?.tenancy;
1026
- let tenantField = null;
1027
- if (tenancyDecl && tenancyDecl.enabled !== false && tenancyDecl.tenantField) {
1028
- const declared = String(tenancyDecl.tenantField);
1029
- if (schema.fields && Object.prototype.hasOwnProperty.call(schema.fields, declared)) {
1030
- tenantField = declared;
1031
- }
1032
- }
1033
- if (!tenantField) {
1034
- const hasOrgField = !!(schema.fields && Object.prototype.hasOwnProperty.call(schema.fields, "organization_id"));
1035
- tenantField = hasOrgField ? "organization_id" : null;
1036
- }
1173
+ const tenantField = this.computeTenantField(schema);
1037
1174
  if (schema.fields) {
1038
1175
  for (const [name, field] of Object.entries(schema.fields)) {
1039
1176
  const type = field.type || "string";
@@ -1063,22 +1200,15 @@ var SqlDriver = class {
1063
1200
  await this.ensureDatabaseExists();
1064
1201
  for (const obj of objects) {
1065
1202
  const tableName = import_system.StorageNameMapping.resolveTableName(obj);
1203
+ this.managedObjectFields.set(tableName, obj.fields ?? {});
1204
+ if (Array.isArray(obj.indexes)) {
1205
+ this.managedObjectIndexes.set(tableName, obj.indexes);
1206
+ }
1066
1207
  const jsonCols = [];
1067
1208
  const booleanCols = [];
1068
1209
  const numericCols = [];
1069
1210
  const autoNumberCols = [];
1070
- const tenancyDecl = obj?.tenancy;
1071
- let tenantField = null;
1072
- if (tenancyDecl && tenancyDecl.enabled !== false && tenancyDecl.tenantField) {
1073
- const declared = String(tenancyDecl.tenantField);
1074
- if (obj.fields && Object.prototype.hasOwnProperty.call(obj.fields, declared)) {
1075
- tenantField = declared;
1076
- }
1077
- }
1078
- if (!tenantField) {
1079
- const hasOrgField = !!(obj.fields && Object.prototype.hasOwnProperty.call(obj.fields, "organization_id"));
1080
- tenantField = hasOrgField ? "organization_id" : null;
1081
- }
1211
+ const tenantField = this.computeTenantField(obj);
1082
1212
  if (obj.fields) {
1083
1213
  for (const [name, field] of Object.entries(obj.fields)) {
1084
1214
  const type = field.type || "string";
@@ -1155,7 +1285,266 @@ var SqlDriver = class {
1155
1285
  const physicalColumns = new Set(Object.keys(colInfo));
1156
1286
  await this.syncDeclaredIndexes(tableName, declaredIndexes, physicalColumns);
1157
1287
  }
1288
+ if (exists) {
1289
+ await this.reconcileAndWarnDrift(tableName, obj.fields ?? {});
1290
+ }
1291
+ }
1292
+ }
1293
+ // ── Managed-schema drift & reconcile (#2186) ───────────────────────────────
1294
+ /** Canonical dialect name for the drift differ. */
1295
+ get dialectName() {
1296
+ if (this.isSqlite) return "sqlite";
1297
+ if (this.isPostgres) return "postgres";
1298
+ if (this.isMysql) return "mysql";
1299
+ return "unknown";
1300
+ }
1301
+ /** True only when running under `NODE_ENV=production` — auto-DDL is force-disabled there. */
1302
+ isProductionEnv() {
1303
+ try {
1304
+ return (process.env.NODE_ENV ?? "").toLowerCase() === "production";
1305
+ } catch {
1306
+ return false;
1307
+ }
1308
+ }
1309
+ /** Diff one table's metadata fields against its physical columns. */
1310
+ async detectTableDrift(tableName, fields) {
1311
+ const cols = await this.introspectColumns(tableName);
1312
+ const physical = cols.map((c) => ({
1313
+ name: c.name,
1314
+ type: c.type,
1315
+ nullable: c.nullable,
1316
+ maxLength: c.maxLength
1317
+ }));
1318
+ return diffManagedTable({ table: tableName, fields, columns: physical, dialect: this.dialectName });
1319
+ }
1320
+ /**
1321
+ * Detect every managed-schema divergence between metadata and the physical
1322
+ * database. Metadata is the source of truth. Returns one entry per drift,
1323
+ * sorted by table then column. Used by `os migrate` (P3) and tests.
1324
+ *
1325
+ * @param objects optional explicit object list; defaults to whatever
1326
+ * `initObjects` last synced (captured in {@link managedObjectFields}).
1327
+ */
1328
+ async detectManagedDrift(objects) {
1329
+ const tables = /* @__PURE__ */ new Map();
1330
+ if (objects) {
1331
+ for (const o of objects) tables.set(import_system.StorageNameMapping.resolveTableName(o), o.fields ?? {});
1332
+ } else {
1333
+ for (const [t, f] of this.managedObjectFields) tables.set(t, f);
1334
+ }
1335
+ const out = [];
1336
+ for (const [tableName, fields] of tables) {
1337
+ if (!await this.knex.schema.hasTable(tableName)) continue;
1338
+ out.push(...await this.detectTableDrift(tableName, fields));
1339
+ }
1340
+ out.sort((a, b) => a.table === b.table ? (a.column ?? "").localeCompare(b.column ?? "") : a.table.localeCompare(b.table));
1341
+ return out;
1342
+ }
1343
+ /**
1344
+ * Boot-time per-table drift handling (P1 + P2): detect divergence, in dev
1345
+ * auto-reconcile the *safe* (loosening) subset when `autoMigrate==='safe'`,
1346
+ * then WARN once per remaining divergence with an actionable hint.
1347
+ */
1348
+ async reconcileAndWarnDrift(tableName, fields) {
1349
+ let drift;
1350
+ try {
1351
+ drift = await this.detectTableDrift(tableName, fields);
1352
+ } catch (e) {
1353
+ this.logger.warn(`[schema-drift] could not introspect '${tableName}' for drift detection`, e?.message ?? e);
1354
+ return;
1355
+ }
1356
+ if (drift.length === 0) return;
1357
+ const autoOn = this.autoMigrate === "safe" && this.schemaMode === "managed";
1358
+ if (autoOn && this.isProductionEnv()) {
1359
+ this.logger.warn(
1360
+ `[schema-drift] autoMigrate='safe' is ignored under NODE_ENV=production \u2014 schema is never auto-altered in production. Run 'os migrate' deliberately.`
1361
+ );
1362
+ } else if (autoOn) {
1363
+ const safe = drift.filter((d) => d.category === "safe");
1364
+ if (safe.length > 0) {
1365
+ try {
1366
+ const { applied } = await this.applyMigrationEntries(safe, { allowDestructive: false });
1367
+ for (const d of applied) {
1368
+ (this.logger.info ?? this.logger.warn)(`[schema-drift] auto-reconciled ${d.op.type} on ${d.table}.${d.column}`);
1369
+ }
1370
+ drift = await this.detectTableDrift(tableName, fields);
1371
+ } catch (e) {
1372
+ this.logger.warn(`[schema-drift] dev auto-reconcile failed for '${tableName}' \u2014 falling back to warning`, e?.message ?? e);
1373
+ }
1374
+ }
1158
1375
  }
1376
+ for (const d of drift) {
1377
+ const k = driftKey(d);
1378
+ if (this.driftWarned.has(k)) continue;
1379
+ this.driftWarned.add(k);
1380
+ this.logger.warn(`[schema-drift] ${d.message}`);
1381
+ }
1382
+ }
1383
+ /**
1384
+ * Apply a set of drift entries to the physical schema. Destructive entries
1385
+ * are skipped unless `allowDestructive` is set. Postgres/MySQL alter columns
1386
+ * in place; SQLite (which cannot alter constraints in place) rebuilds each
1387
+ * affected table (copy → swap) applying only the requested edits.
1388
+ *
1389
+ * @returns the entries actually applied and those skipped (e.g. destructive
1390
+ * without `allowDestructive`, or unsupported on the dialect).
1391
+ */
1392
+ async applyMigrationEntries(entries, opts = {}) {
1393
+ this.assertSchemaMutable("reconcileManagedSchema");
1394
+ const allowDestructive = opts.allowDestructive === true;
1395
+ const applied = [];
1396
+ const skipped = [];
1397
+ const candidates = entries.filter((d) => {
1398
+ if (d.category === "destructive" && !allowDestructive) {
1399
+ skipped.push(d);
1400
+ return false;
1401
+ }
1402
+ return true;
1403
+ });
1404
+ if (candidates.length === 0) return { applied, skipped };
1405
+ const byTable = /* @__PURE__ */ new Map();
1406
+ for (const d of candidates) {
1407
+ (byTable.get(d.table) ?? byTable.set(d.table, []).get(d.table)).push(d);
1408
+ }
1409
+ for (const [table, ents] of byTable) {
1410
+ try {
1411
+ if (this.isSqlite) {
1412
+ await this.rebuildSqliteTablePatched(table, ents);
1413
+ applied.push(...ents);
1414
+ } else {
1415
+ for (const d of ents) {
1416
+ const ok = await this.applyDriftOpInPlace(d.op);
1417
+ (ok ? applied : skipped).push(d);
1418
+ }
1419
+ }
1420
+ } catch (e) {
1421
+ this.logger.warn(`[schema-drift] failed to reconcile '${table}'`, e?.message ?? e);
1422
+ for (const d of ents) if (!applied.includes(d)) skipped.push(d);
1423
+ }
1424
+ }
1425
+ return { applied, skipped };
1426
+ }
1427
+ /** Apply a single drift op in place (Postgres / MySQL). Returns false if unsupported. */
1428
+ async applyDriftOpInPlace(op) {
1429
+ const { table, column } = op;
1430
+ if (this.isPostgres) {
1431
+ switch (op.type) {
1432
+ case "relax_not_null":
1433
+ await this.knex.raw("ALTER TABLE ?? ALTER COLUMN ?? DROP NOT NULL", [table, column]);
1434
+ return true;
1435
+ case "tighten_not_null":
1436
+ await this.knex.raw("ALTER TABLE ?? ALTER COLUMN ?? SET NOT NULL", [table, column]);
1437
+ return true;
1438
+ case "widen_varchar":
1439
+ case "narrow_varchar":
1440
+ await this.knex.raw(`ALTER TABLE ?? ALTER COLUMN ?? TYPE varchar(${op.to})`, [table, column]);
1441
+ return true;
1442
+ case "drop_column":
1443
+ await this.knex.raw("ALTER TABLE ?? DROP COLUMN ??", [table, column]);
1444
+ return true;
1445
+ }
1446
+ }
1447
+ if (this.isMysql) {
1448
+ const info = await this.knex(table).columnInfo();
1449
+ const ci = info?.[column];
1450
+ const colType = ci?.type ? /char/i.test(ci.type) && ci.maxLength ? `${ci.type}(${ci.maxLength})` : ci.type : void 0;
1451
+ switch (op.type) {
1452
+ case "relax_not_null":
1453
+ if (!colType) return false;
1454
+ await this.knex.raw(`ALTER TABLE ?? MODIFY ?? ${colType} NULL`, [table, column]);
1455
+ return true;
1456
+ case "tighten_not_null":
1457
+ if (!colType) return false;
1458
+ await this.knex.raw(`ALTER TABLE ?? MODIFY ?? ${colType} NOT NULL`, [table, column]);
1459
+ return true;
1460
+ case "widen_varchar":
1461
+ case "narrow_varchar":
1462
+ await this.knex.raw(`ALTER TABLE ?? MODIFY ?? varchar(${op.to})`, [table, column]);
1463
+ return true;
1464
+ case "drop_column":
1465
+ await this.knex.raw("ALTER TABLE ?? DROP COLUMN ??", [table, column]);
1466
+ return true;
1467
+ }
1468
+ }
1469
+ this.logger.warn(`[schema-drift] ${op.type} on ${table}.${column} is unsupported on dialect '${this.dialectName}' \u2014 skipped`);
1470
+ return false;
1471
+ }
1472
+ /**
1473
+ * Rebuild a SQLite table applying a set of column edits (relax/tighten NOT
1474
+ * NULL, drop column), preserving all other columns and their data. Follows
1475
+ * the official SQLite procedure: create patched table → copy → drop → rename.
1476
+ * varchar widen/narrow are no-ops on SQLite (dynamic typing) and ignored.
1477
+ *
1478
+ * Unique field-level constraints and declared indexes are recreated from
1479
+ * metadata afterwards (the source of truth). DB-level foreign keys declared
1480
+ * by `lookup` fields are not re-added (ObjectStack enforces relationships at
1481
+ * the application layer, not via SQLite FK constraints).
1482
+ */
1483
+ async rebuildSqliteTablePatched(table, ents) {
1484
+ const relax = /* @__PURE__ */ new Set();
1485
+ const tighten = /* @__PURE__ */ new Set();
1486
+ const drop = /* @__PURE__ */ new Set();
1487
+ for (const e of ents) {
1488
+ if (e.op.type === "relax_not_null") relax.add(e.op.column);
1489
+ else if (e.op.type === "tighten_not_null") tighten.add(e.op.column);
1490
+ else if (e.op.type === "drop_column") drop.add(e.op.column);
1491
+ }
1492
+ const physical = await this.introspectColumns(table);
1493
+ const kept = physical.filter((c) => !drop.has(c.name));
1494
+ const keptNames = kept.map((c) => c.name);
1495
+ const fields = this.managedObjectFields.get(table) ?? {};
1496
+ const tmp = `__os_mig_${table}`;
1497
+ await this.knex.raw("PRAGMA foreign_keys = OFF");
1498
+ try {
1499
+ await this.knex.transaction(async (trx) => {
1500
+ await trx.schema.dropTableIfExists(tmp);
1501
+ await trx.schema.createTable(tmp, (t) => {
1502
+ for (const c of kept) {
1503
+ const col = this.buildRebuiltColumn(t, c);
1504
+ if (!col) continue;
1505
+ const nullable = relax.has(c.name) ? true : tighten.has(c.name) ? false : c.nullable;
1506
+ if (!nullable && c.name !== "id") col.notNullable();
1507
+ if (c.name === "created_at" || c.name === "updated_at") col.defaultTo(this.knex.fn.now());
1508
+ }
1509
+ });
1510
+ const colList = keptNames.map((n) => `"${n}"`).join(", ");
1511
+ await trx.raw(`INSERT INTO "${tmp}" (${colList}) SELECT ${colList} FROM "${table}"`);
1512
+ await trx.schema.dropTable(table);
1513
+ await trx.schema.renameTable(tmp, table);
1514
+ });
1515
+ } finally {
1516
+ await this.knex.raw("PRAGMA foreign_keys = ON");
1517
+ }
1518
+ try {
1519
+ const keptSet = new Set(keptNames);
1520
+ for (const [name, field] of Object.entries(fields)) {
1521
+ if (field?.unique && keptSet.has(name)) {
1522
+ const idx = `uniq_${table}_${name}`;
1523
+ await this.knex.raw("CREATE UNIQUE INDEX IF NOT EXISTS ?? ON ?? (??)", [idx, table, name]);
1524
+ }
1525
+ }
1526
+ const declared = this.managedObjectIndexes.get(table);
1527
+ if (Array.isArray(declared) && declared.length > 0) {
1528
+ await this.syncDeclaredIndexes(table, declared, keptSet);
1529
+ }
1530
+ } catch (e) {
1531
+ this.logger.warn(`[schema-drift] could not fully recreate indexes for '${table}' after rebuild`, e?.message ?? e);
1532
+ }
1533
+ }
1534
+ /** Map an introspected SQLite column to a knex builder for the rebuilt table. */
1535
+ buildRebuiltColumn(t, c) {
1536
+ if (c.name === "id") return t.string("id").primary();
1537
+ const ty = (c.type || "text").toLowerCase();
1538
+ if (ty.includes("int")) return t.integer(c.name);
1539
+ if (/(real|floa|doub|num|dec)/.test(ty)) return t.float(c.name);
1540
+ if (ty.includes("bool")) return t.boolean(c.name);
1541
+ if (ty.includes("datetime") || ty.includes("timestamp")) return t.timestamp(c.name);
1542
+ if (ty === "date") return t.date(c.name);
1543
+ if (ty === "time") return t.time(c.name);
1544
+ if (ty.includes("json")) return t.json(c.name);
1545
+ if (ty.includes("blob") || ty.includes("binary")) return t.binary(c.name);
1546
+ if (ty.includes("text")) return t.text(c.name);
1547
+ return t.string(c.name);
1159
1548
  }
1160
1549
  /**
1161
1550
  * Build a deterministic index name for a declared index so repeated
@@ -2224,6 +2613,10 @@ var index_default = {
2224
2613
  };
2225
2614
  // Annotate the CommonJS export names for ESM import in node:
2226
2615
  0 && (module.exports = {
2227
- SqlDriver
2616
+ BUILTIN_COLUMNS,
2617
+ SqlDriver,
2618
+ diffManagedTable,
2619
+ driftKey,
2620
+ fieldHasColumn
2228
2621
  });
2229
2622
  //# sourceMappingURL=index.js.map