@objectstack/driver-sql 10.0.0 → 10.2.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
  }
@@ -1063,6 +1180,10 @@ var SqlDriver = class {
1063
1180
  await this.ensureDatabaseExists();
1064
1181
  for (const obj of objects) {
1065
1182
  const tableName = import_system.StorageNameMapping.resolveTableName(obj);
1183
+ this.managedObjectFields.set(tableName, obj.fields ?? {});
1184
+ if (Array.isArray(obj.indexes)) {
1185
+ this.managedObjectIndexes.set(tableName, obj.indexes);
1186
+ }
1066
1187
  const jsonCols = [];
1067
1188
  const booleanCols = [];
1068
1189
  const numericCols = [];
@@ -1155,7 +1276,266 @@ var SqlDriver = class {
1155
1276
  const physicalColumns = new Set(Object.keys(colInfo));
1156
1277
  await this.syncDeclaredIndexes(tableName, declaredIndexes, physicalColumns);
1157
1278
  }
1279
+ if (exists) {
1280
+ await this.reconcileAndWarnDrift(tableName, obj.fields ?? {});
1281
+ }
1282
+ }
1283
+ }
1284
+ // ── Managed-schema drift & reconcile (#2186) ───────────────────────────────
1285
+ /** Canonical dialect name for the drift differ. */
1286
+ get dialectName() {
1287
+ if (this.isSqlite) return "sqlite";
1288
+ if (this.isPostgres) return "postgres";
1289
+ if (this.isMysql) return "mysql";
1290
+ return "unknown";
1291
+ }
1292
+ /** True only when running under `NODE_ENV=production` — auto-DDL is force-disabled there. */
1293
+ isProductionEnv() {
1294
+ try {
1295
+ return (process.env.NODE_ENV ?? "").toLowerCase() === "production";
1296
+ } catch {
1297
+ return false;
1298
+ }
1299
+ }
1300
+ /** Diff one table's metadata fields against its physical columns. */
1301
+ async detectTableDrift(tableName, fields) {
1302
+ const cols = await this.introspectColumns(tableName);
1303
+ const physical = cols.map((c) => ({
1304
+ name: c.name,
1305
+ type: c.type,
1306
+ nullable: c.nullable,
1307
+ maxLength: c.maxLength
1308
+ }));
1309
+ return diffManagedTable({ table: tableName, fields, columns: physical, dialect: this.dialectName });
1310
+ }
1311
+ /**
1312
+ * Detect every managed-schema divergence between metadata and the physical
1313
+ * database. Metadata is the source of truth. Returns one entry per drift,
1314
+ * sorted by table then column. Used by `os migrate` (P3) and tests.
1315
+ *
1316
+ * @param objects optional explicit object list; defaults to whatever
1317
+ * `initObjects` last synced (captured in {@link managedObjectFields}).
1318
+ */
1319
+ async detectManagedDrift(objects) {
1320
+ const tables = /* @__PURE__ */ new Map();
1321
+ if (objects) {
1322
+ for (const o of objects) tables.set(import_system.StorageNameMapping.resolveTableName(o), o.fields ?? {});
1323
+ } else {
1324
+ for (const [t, f] of this.managedObjectFields) tables.set(t, f);
1325
+ }
1326
+ const out = [];
1327
+ for (const [tableName, fields] of tables) {
1328
+ if (!await this.knex.schema.hasTable(tableName)) continue;
1329
+ out.push(...await this.detectTableDrift(tableName, fields));
1330
+ }
1331
+ out.sort((a, b) => a.table === b.table ? (a.column ?? "").localeCompare(b.column ?? "") : a.table.localeCompare(b.table));
1332
+ return out;
1333
+ }
1334
+ /**
1335
+ * Boot-time per-table drift handling (P1 + P2): detect divergence, in dev
1336
+ * auto-reconcile the *safe* (loosening) subset when `autoMigrate==='safe'`,
1337
+ * then WARN once per remaining divergence with an actionable hint.
1338
+ */
1339
+ async reconcileAndWarnDrift(tableName, fields) {
1340
+ let drift;
1341
+ try {
1342
+ drift = await this.detectTableDrift(tableName, fields);
1343
+ } catch (e) {
1344
+ this.logger.warn(`[schema-drift] could not introspect '${tableName}' for drift detection`, e?.message ?? e);
1345
+ return;
1346
+ }
1347
+ if (drift.length === 0) return;
1348
+ const autoOn = this.autoMigrate === "safe" && this.schemaMode === "managed";
1349
+ if (autoOn && this.isProductionEnv()) {
1350
+ this.logger.warn(
1351
+ `[schema-drift] autoMigrate='safe' is ignored under NODE_ENV=production \u2014 schema is never auto-altered in production. Run 'os migrate' deliberately.`
1352
+ );
1353
+ } else if (autoOn) {
1354
+ const safe = drift.filter((d) => d.category === "safe");
1355
+ if (safe.length > 0) {
1356
+ try {
1357
+ const { applied } = await this.applyMigrationEntries(safe, { allowDestructive: false });
1358
+ for (const d of applied) {
1359
+ (this.logger.info ?? this.logger.warn)(`[schema-drift] auto-reconciled ${d.op.type} on ${d.table}.${d.column}`);
1360
+ }
1361
+ drift = await this.detectTableDrift(tableName, fields);
1362
+ } catch (e) {
1363
+ this.logger.warn(`[schema-drift] dev auto-reconcile failed for '${tableName}' \u2014 falling back to warning`, e?.message ?? e);
1364
+ }
1365
+ }
1366
+ }
1367
+ for (const d of drift) {
1368
+ const k = driftKey(d);
1369
+ if (this.driftWarned.has(k)) continue;
1370
+ this.driftWarned.add(k);
1371
+ this.logger.warn(`[schema-drift] ${d.message}`);
1372
+ }
1373
+ }
1374
+ /**
1375
+ * Apply a set of drift entries to the physical schema. Destructive entries
1376
+ * are skipped unless `allowDestructive` is set. Postgres/MySQL alter columns
1377
+ * in place; SQLite (which cannot alter constraints in place) rebuilds each
1378
+ * affected table (copy → swap) applying only the requested edits.
1379
+ *
1380
+ * @returns the entries actually applied and those skipped (e.g. destructive
1381
+ * without `allowDestructive`, or unsupported on the dialect).
1382
+ */
1383
+ async applyMigrationEntries(entries, opts = {}) {
1384
+ this.assertSchemaMutable("reconcileManagedSchema");
1385
+ const allowDestructive = opts.allowDestructive === true;
1386
+ const applied = [];
1387
+ const skipped = [];
1388
+ const candidates = entries.filter((d) => {
1389
+ if (d.category === "destructive" && !allowDestructive) {
1390
+ skipped.push(d);
1391
+ return false;
1392
+ }
1393
+ return true;
1394
+ });
1395
+ if (candidates.length === 0) return { applied, skipped };
1396
+ const byTable = /* @__PURE__ */ new Map();
1397
+ for (const d of candidates) {
1398
+ (byTable.get(d.table) ?? byTable.set(d.table, []).get(d.table)).push(d);
1158
1399
  }
1400
+ for (const [table, ents] of byTable) {
1401
+ try {
1402
+ if (this.isSqlite) {
1403
+ await this.rebuildSqliteTablePatched(table, ents);
1404
+ applied.push(...ents);
1405
+ } else {
1406
+ for (const d of ents) {
1407
+ const ok = await this.applyDriftOpInPlace(d.op);
1408
+ (ok ? applied : skipped).push(d);
1409
+ }
1410
+ }
1411
+ } catch (e) {
1412
+ this.logger.warn(`[schema-drift] failed to reconcile '${table}'`, e?.message ?? e);
1413
+ for (const d of ents) if (!applied.includes(d)) skipped.push(d);
1414
+ }
1415
+ }
1416
+ return { applied, skipped };
1417
+ }
1418
+ /** Apply a single drift op in place (Postgres / MySQL). Returns false if unsupported. */
1419
+ async applyDriftOpInPlace(op) {
1420
+ const { table, column } = op;
1421
+ if (this.isPostgres) {
1422
+ switch (op.type) {
1423
+ case "relax_not_null":
1424
+ await this.knex.raw("ALTER TABLE ?? ALTER COLUMN ?? DROP NOT NULL", [table, column]);
1425
+ return true;
1426
+ case "tighten_not_null":
1427
+ await this.knex.raw("ALTER TABLE ?? ALTER COLUMN ?? SET NOT NULL", [table, column]);
1428
+ return true;
1429
+ case "widen_varchar":
1430
+ case "narrow_varchar":
1431
+ await this.knex.raw(`ALTER TABLE ?? ALTER COLUMN ?? TYPE varchar(${op.to})`, [table, column]);
1432
+ return true;
1433
+ case "drop_column":
1434
+ await this.knex.raw("ALTER TABLE ?? DROP COLUMN ??", [table, column]);
1435
+ return true;
1436
+ }
1437
+ }
1438
+ if (this.isMysql) {
1439
+ const info = await this.knex(table).columnInfo();
1440
+ const ci = info?.[column];
1441
+ const colType = ci?.type ? /char/i.test(ci.type) && ci.maxLength ? `${ci.type}(${ci.maxLength})` : ci.type : void 0;
1442
+ switch (op.type) {
1443
+ case "relax_not_null":
1444
+ if (!colType) return false;
1445
+ await this.knex.raw(`ALTER TABLE ?? MODIFY ?? ${colType} NULL`, [table, column]);
1446
+ return true;
1447
+ case "tighten_not_null":
1448
+ if (!colType) return false;
1449
+ await this.knex.raw(`ALTER TABLE ?? MODIFY ?? ${colType} NOT NULL`, [table, column]);
1450
+ return true;
1451
+ case "widen_varchar":
1452
+ case "narrow_varchar":
1453
+ await this.knex.raw(`ALTER TABLE ?? MODIFY ?? varchar(${op.to})`, [table, column]);
1454
+ return true;
1455
+ case "drop_column":
1456
+ await this.knex.raw("ALTER TABLE ?? DROP COLUMN ??", [table, column]);
1457
+ return true;
1458
+ }
1459
+ }
1460
+ this.logger.warn(`[schema-drift] ${op.type} on ${table}.${column} is unsupported on dialect '${this.dialectName}' \u2014 skipped`);
1461
+ return false;
1462
+ }
1463
+ /**
1464
+ * Rebuild a SQLite table applying a set of column edits (relax/tighten NOT
1465
+ * NULL, drop column), preserving all other columns and their data. Follows
1466
+ * the official SQLite procedure: create patched table → copy → drop → rename.
1467
+ * varchar widen/narrow are no-ops on SQLite (dynamic typing) and ignored.
1468
+ *
1469
+ * Unique field-level constraints and declared indexes are recreated from
1470
+ * metadata afterwards (the source of truth). DB-level foreign keys declared
1471
+ * by `lookup` fields are not re-added (ObjectStack enforces relationships at
1472
+ * the application layer, not via SQLite FK constraints).
1473
+ */
1474
+ async rebuildSqliteTablePatched(table, ents) {
1475
+ const relax = /* @__PURE__ */ new Set();
1476
+ const tighten = /* @__PURE__ */ new Set();
1477
+ const drop = /* @__PURE__ */ new Set();
1478
+ for (const e of ents) {
1479
+ if (e.op.type === "relax_not_null") relax.add(e.op.column);
1480
+ else if (e.op.type === "tighten_not_null") tighten.add(e.op.column);
1481
+ else if (e.op.type === "drop_column") drop.add(e.op.column);
1482
+ }
1483
+ const physical = await this.introspectColumns(table);
1484
+ const kept = physical.filter((c) => !drop.has(c.name));
1485
+ const keptNames = kept.map((c) => c.name);
1486
+ const fields = this.managedObjectFields.get(table) ?? {};
1487
+ const tmp = `__os_mig_${table}`;
1488
+ await this.knex.raw("PRAGMA foreign_keys = OFF");
1489
+ try {
1490
+ await this.knex.transaction(async (trx) => {
1491
+ await trx.schema.dropTableIfExists(tmp);
1492
+ await trx.schema.createTable(tmp, (t) => {
1493
+ for (const c of kept) {
1494
+ const col = this.buildRebuiltColumn(t, c);
1495
+ if (!col) continue;
1496
+ const nullable = relax.has(c.name) ? true : tighten.has(c.name) ? false : c.nullable;
1497
+ if (!nullable && c.name !== "id") col.notNullable();
1498
+ if (c.name === "created_at" || c.name === "updated_at") col.defaultTo(this.knex.fn.now());
1499
+ }
1500
+ });
1501
+ const colList = keptNames.map((n) => `"${n}"`).join(", ");
1502
+ await trx.raw(`INSERT INTO "${tmp}" (${colList}) SELECT ${colList} FROM "${table}"`);
1503
+ await trx.schema.dropTable(table);
1504
+ await trx.schema.renameTable(tmp, table);
1505
+ });
1506
+ } finally {
1507
+ await this.knex.raw("PRAGMA foreign_keys = ON");
1508
+ }
1509
+ try {
1510
+ const keptSet = new Set(keptNames);
1511
+ for (const [name, field] of Object.entries(fields)) {
1512
+ if (field?.unique && keptSet.has(name)) {
1513
+ const idx = `uniq_${table}_${name}`;
1514
+ await this.knex.raw("CREATE UNIQUE INDEX IF NOT EXISTS ?? ON ?? (??)", [idx, table, name]);
1515
+ }
1516
+ }
1517
+ const declared = this.managedObjectIndexes.get(table);
1518
+ if (Array.isArray(declared) && declared.length > 0) {
1519
+ await this.syncDeclaredIndexes(table, declared, keptSet);
1520
+ }
1521
+ } catch (e) {
1522
+ this.logger.warn(`[schema-drift] could not fully recreate indexes for '${table}' after rebuild`, e?.message ?? e);
1523
+ }
1524
+ }
1525
+ /** Map an introspected SQLite column to a knex builder for the rebuilt table. */
1526
+ buildRebuiltColumn(t, c) {
1527
+ if (c.name === "id") return t.string("id").primary();
1528
+ const ty = (c.type || "text").toLowerCase();
1529
+ if (ty.includes("int")) return t.integer(c.name);
1530
+ if (/(real|floa|doub|num|dec)/.test(ty)) return t.float(c.name);
1531
+ if (ty.includes("bool")) return t.boolean(c.name);
1532
+ if (ty.includes("datetime") || ty.includes("timestamp")) return t.timestamp(c.name);
1533
+ if (ty === "date") return t.date(c.name);
1534
+ if (ty === "time") return t.time(c.name);
1535
+ if (ty.includes("json")) return t.json(c.name);
1536
+ if (ty.includes("blob") || ty.includes("binary")) return t.binary(c.name);
1537
+ if (ty.includes("text")) return t.text(c.name);
1538
+ return t.string(c.name);
1159
1539
  }
1160
1540
  /**
1161
1541
  * Build a deterministic index name for a declared index so repeated
@@ -2224,6 +2604,10 @@ var index_default = {
2224
2604
  };
2225
2605
  // Annotate the CommonJS export names for ESM import in node:
2226
2606
  0 && (module.exports = {
2227
- SqlDriver
2607
+ BUILTIN_COLUMNS,
2608
+ SqlDriver,
2609
+ diffManagedTable,
2610
+ driftKey,
2611
+ fieldHasColumn
2228
2612
  });
2229
2613
  //# sourceMappingURL=index.js.map