@jskit-ai/database-runtime-mysql 0.1.261 → 0.1.263

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/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ # Changelog
2
+
3
+ ## Unreleased
4
+
5
+ - **Breaking.** `introspectCrudTableSnapshot` is removed from `./shared` and from the MySQL driver capability (`runtime.database.driver`), which now holds only `DIALECT_ID`: nothing used it since CRUD generation was removed. A table's foreign keys come from `listForeignKeys` in `@jskit-ai/database-runtime/server/foreignKeyMigrations`.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jskit-ai/database-runtime-mysql",
3
- "version": "0.1.261",
3
+ "version": "0.1.263",
4
4
  "type": "module",
5
5
  "scripts": {
6
6
  "test": "jskit test"
@@ -55,7 +55,7 @@
55
55
  }
56
56
  },
57
57
  "peerDependencies": {
58
- "@jskit-ai/database-runtime": "0.1.263",
59
- "@jskit-ai/kernel": "0.2.14"
58
+ "@jskit-ai/database-runtime": "0.1.265",
59
+ "@jskit-ai/kernel": "0.2.16"
60
60
  }
61
61
  }
@@ -9,7 +9,7 @@
9
9
  "test": "jskit test --databases"
10
10
  },
11
11
  "dependencies": {
12
- "@jskit-ai/database-runtime": "0.1.263",
13
- "@jskit-ai/database-runtime-mysql": "0.1.261"
12
+ "@jskit-ai/database-runtime": "0.1.265",
13
+ "@jskit-ai/database-runtime-mysql": "0.1.263"
14
14
  }
15
15
  }
@@ -1,5 +1,5 @@
1
1
  import { defineProvider } from "@jskit-ai/kernel/shared/capabilities";
2
- import { DIALECT_ID, introspectCrudTableSnapshot } from "../../shared/index.js";
2
+ import { DIALECT_ID } from "../../shared/index.js";
3
3
 
4
4
  const MysqlDatabaseDriverProvider = defineProvider({
5
5
  id: "runtime.database.driver.mysql",
@@ -8,7 +8,7 @@ const MysqlDatabaseDriverProvider = defineProvider({
8
8
  },
9
9
  setup() {
10
10
  return {
11
- driver: Object.freeze({ DIALECT_ID, introspectCrudTableSnapshot })
11
+ driver: Object.freeze({ DIALECT_ID })
12
12
  };
13
13
  }
14
14
  });
@@ -1,2 +1 @@
1
1
  export { DIALECT_ID } from "./dialect.js";
2
- export { introspectCrudTableSnapshot } from "./introspectCrudTable.js";
@@ -28,6 +28,5 @@ test("server provider module exports the declarative mysql driver provider", ()
28
28
 
29
29
  test("shared entrypoint exports mysql dialect helpers", () => {
30
30
  assert.equal(sharedApi.DIALECT_ID, "mysql2");
31
- assert.equal(typeof sharedApi.introspectCrudTableSnapshot, "function");
32
31
  assert.equal(typeof sharedApi.MysqlDatabaseDriverProvider, "undefined");
33
32
  });
@@ -4,7 +4,8 @@ import knex from "knex";
4
4
  import {
5
5
  addMissingForeignKey,
6
6
  dropForeignKeyIfPresent,
7
- hasForeignKey
7
+ hasForeignKey,
8
+ listForeignKeys
8
9
  } from "@jskit-ai/database-runtime/server/foreignKeyMigrations";
9
10
 
10
11
  const KEY = { tableName: "children", columnName: "parent_id", parentTable: "parents" };
@@ -29,6 +30,21 @@ test("dropForeignKeyIfPresent drops a MySQL key by the name the database holds",
29
30
  table.foreign("parent_id", "children_parent_custom_fk").references("id").inTable("parents");
30
31
  });
31
32
 
33
+ await db.schema.createTable("pairs", (table) => {
34
+ table.integer("a").unsigned();
35
+ table.integer("b").unsigned();
36
+ table.primary(["a", "b"]);
37
+ });
38
+ await db.schema.createTable("pair_links", (table) => {
39
+ table.integer("pair_b").unsigned();
40
+ table.integer("pair_a").unsigned();
41
+ table.foreign(["pair_b", "pair_a"], "pair_links_pair_fk").references(["a", "b"]).inTable("pairs");
42
+ });
43
+ assert.deepEqual(await listForeignKeys(db), [
44
+ { name: "children_parent_custom_fk", tableName: "children", columns: ["parent_id"], referencedTableName: "parents", referencedColumns: ["id"] },
45
+ { name: "pair_links_pair_fk", tableName: "pair_links", columns: ["pair_b", "pair_a"], referencedTableName: "pairs", referencedColumns: ["a", "b"] }
46
+ ]);
47
+
32
48
  assert.equal(await hasForeignKey(db, KEY), true);
33
49
  assert.equal(await addMissingForeignKey(db, KEY), false);
34
50
  assert.equal(await dropForeignKeyIfPresent(db, KEY), true);
@@ -233,6 +233,8 @@ test("jskit test --databases gives each test file running at once its own restor
233
233
  await writeFile(path.join(appRoot, "test", "a.test.js"), FIXTURE_TEST("a", "b"));
234
234
  await writeFile(path.join(appRoot, "test", "b.test.js"), FIXTURE_TEST("b", "a"));
235
235
  // The fixture's own node_modules (its snapshot cache goes there), resolving JSKIT's packages from this repository.
236
+ // The whole scope is fine: the run checks a package's declared foreign keys only where its table exists, and only
237
+ // the fixture's books migration runs here.
236
238
  await mkdir(path.join(appRoot, "node_modules"));
237
239
  await symlink(path.join(REPO_ROOT, "node_modules", "@jskit-ai"), path.join(appRoot, "node_modules", "@jskit-ai"), "dir");
238
240
 
@@ -244,6 +246,7 @@ test("jskit test --databases gives each test file running at once its own restor
244
246
  const { stderr } = await execFileAsync(process.execPath, [JSKIT_CLI, "test", "--databases"], { cwd: appRoot, env });
245
247
  assert.match(stderr, /jskit test: 2 test database\(s\) from .+_cli ready in \d+ms: 1 migrations replayed once/u);
246
248
  assert.match(stderr, /jskit test: 2 test file\(s\) at a time \(test databases\)\./u);
249
+ assert.match(stderr, /; foreign keys: 0 declared, all in the database \([1-9]\d* JSKIT package table\(s\) the database does not have are not checked\)/u);
247
250
  const seen = await Promise.all(["a", "b"].map(async (file) => JSON.parse(await readFile(path.join(appRoot, `seen-${file}.json`), "utf8"))));
248
251
  assert.deepEqual(seen.map(({ db }) => db).sort(), [name, `${name}_1`]);
249
252
  const connection = { host: server.host, port: String(server.port), user: server.user,
@@ -1,642 +0,0 @@
1
- import { normalizeText } from "@jskit-ai/kernel/shared/support/normalize";
2
- import { toCamelCase } from "@jskit-ai/kernel/shared/support/stringCase";
3
-
4
- const BOOLEAN_TINYINT_PATTERN = /^tinyint\(1\)/;
5
- const CURRENT_TIMESTAMP_EXPRESSION_PATTERN = /^current_timestamp(?:\((\d*)\))?$/i;
6
- const ON_UPDATE_CURRENT_TIMESTAMP_PATTERN =
7
- /(?:^|\s)on\s+update\s+(current_timestamp(?:\((\d*)\))?)(?:\s|$)/i;
8
- const TABLE_NAME_PATTERN = /^[A-Za-z0-9_]+$/;
9
- const TEMPORAL_DATA_TYPES = new Set(["datetime", "timestamp"]);
10
-
11
- function requireKnexRaw(knex) {
12
- // readable-check: allow method-probe - input validation: the application passes its own Knex instance
13
- if (!knex || typeof knex.raw !== "function") {
14
- throw new TypeError("introspectCrudTableSnapshot requires knex with raw().");
15
- }
16
- }
17
-
18
- function requireTableName(value) {
19
- const tableName = normalizeText(value);
20
- if (!tableName) {
21
- throw new TypeError("introspectCrudTableSnapshot requires tableName.");
22
- }
23
- if (!TABLE_NAME_PATTERN.test(tableName)) {
24
- throw new Error(`Invalid table name "${tableName}". Use letters, numbers, and underscore only.`);
25
- }
26
-
27
- return tableName;
28
- }
29
-
30
- function normalizeRows(rawResult) {
31
- if (Array.isArray(rawResult)) {
32
- if (rawResult.length > 0 && Array.isArray(rawResult[0])) {
33
- return rawResult[0];
34
- }
35
- return rawResult;
36
- }
37
- if (rawResult && typeof rawResult === "object" && Array.isArray(rawResult.rows)) {
38
- return rawResult.rows;
39
- }
40
- return [];
41
- }
42
-
43
- function normalizeDbSchemaName(rows = []) {
44
- const firstRow = Array.isArray(rows) ? rows[0] : null;
45
- const schemaName = normalizeText(firstRow?.schemaName || firstRow?.schema_name || "");
46
- if (!schemaName) {
47
- throw new Error("Could not resolve current database schema name.");
48
- }
49
-
50
- return schemaName;
51
- }
52
-
53
- function toBoolean(value) {
54
- if (typeof value === "boolean") {
55
- return value;
56
- }
57
- if (typeof value === "number") {
58
- return value !== 0;
59
- }
60
- const text = normalizeText(value).toLowerCase();
61
- return text === "1" || text === "true" || text === "yes" || text === "y";
62
- }
63
-
64
- function toNullableNumber(value) {
65
- if (value == null) {
66
- return null;
67
- }
68
- const parsed = Number.parseInt(String(value), 10);
69
- return Number.isFinite(parsed) ? parsed : null;
70
- }
71
-
72
- function normalizeColumnDefault(value) {
73
- if (value == null) {
74
- return null;
75
- }
76
-
77
- const normalized = normalizeText(value).toLowerCase();
78
- if (normalized === "null") {
79
- return null;
80
- }
81
-
82
- return value;
83
- }
84
-
85
- function normalizeCurrentTimestampExpression(value) {
86
- const match = normalizeText(value).match(CURRENT_TIMESTAMP_EXPRESSION_PATTERN);
87
- if (!match) {
88
- return null;
89
- }
90
-
91
- const precision =
92
- match[1] == null || match[1] === ""
93
- ? null
94
- : Number.parseInt(match[1], 10);
95
- if (precision != null && (!Number.isInteger(precision) || precision < 0 || precision > 6)) {
96
- return null;
97
- }
98
-
99
- return Object.freeze({
100
- kind: "current_timestamp",
101
- precision
102
- });
103
- }
104
-
105
- function normalizeOnUpdateExpression(value) {
106
- const match = normalizeText(value).match(ON_UPDATE_CURRENT_TIMESTAMP_PATTERN);
107
- return match ? normalizeCurrentTimestampExpression(match[1]) : null;
108
- }
109
-
110
- function parseEnumValues(columnType = "") {
111
- const source = normalizeText(columnType);
112
- if (!source.toLowerCase().startsWith("enum(") || !source.endsWith(")")) {
113
- return Object.freeze([]);
114
- }
115
-
116
- const body = source.slice(5, -1);
117
- const values = [];
118
- const pattern = /'((?:\\'|[^'])*)'/g;
119
- let match = null;
120
- while ((match = pattern.exec(body)) != null) {
121
- values.push(match[1].replace(/\\'/g, "'"));
122
- }
123
- return Object.freeze(values);
124
- }
125
-
126
- function resolveTypeKind(column) {
127
- const dataType = normalizeText(column?.dataType).toLowerCase();
128
- const columnType = normalizeText(column?.columnType).toLowerCase();
129
-
130
- if (
131
- dataType === "varchar" ||
132
- dataType === "char" ||
133
- dataType === "text" ||
134
- dataType === "tinytext" ||
135
- dataType === "mediumtext" ||
136
- dataType === "longtext" ||
137
- dataType === "enum" ||
138
- dataType === "set"
139
- ) {
140
- return "string";
141
- }
142
-
143
- if (
144
- dataType === "int" ||
145
- dataType === "integer" ||
146
- dataType === "smallint" ||
147
- dataType === "mediumint" ||
148
- dataType === "bigint"
149
- ) {
150
- return "integer";
151
- }
152
-
153
- if (dataType === "tinyint") {
154
- if (BOOLEAN_TINYINT_PATTERN.test(columnType)) {
155
- return "boolean";
156
- }
157
- return "integer";
158
- }
159
-
160
- if (
161
- dataType === "decimal" ||
162
- dataType === "numeric" ||
163
- dataType === "float" ||
164
- dataType === "double" ||
165
- dataType === "real"
166
- ) {
167
- return "number";
168
- }
169
-
170
- if (dataType === "boolean" || dataType === "bool") {
171
- return "boolean";
172
- }
173
-
174
- if (dataType === "datetime" || dataType === "timestamp") {
175
- return "datetime";
176
- }
177
- if (dataType === "date") {
178
- return "date";
179
- }
180
- if (dataType === "time") {
181
- return "time";
182
- }
183
- if (dataType === "json") {
184
- return "json";
185
- }
186
-
187
- throw new Error(
188
- `Unsupported MySQL column type "${dataType}" for column "${String(column?.name || "")}".`
189
- );
190
- }
191
-
192
- function normalizeColumn(row = {}) {
193
- const name = normalizeText(row.columnName || row.column_name);
194
- if (!name) {
195
- throw new Error("MySQL introspection returned a column without column name.");
196
- }
197
-
198
- const dataType = normalizeText(row.dataType || row.data_type).toLowerCase();
199
- const columnType = normalizeText(row.columnType || row.column_type);
200
- const columnTypeLower = columnType.toLowerCase();
201
- const nullable = normalizeText(row.isNullable || row.is_nullable).toUpperCase() === "YES";
202
- const rawDefaultValue = Object.prototype.hasOwnProperty.call(row, "columnDefault")
203
- ? row.columnDefault
204
- : Object.prototype.hasOwnProperty.call(row, "column_default")
205
- ? row.column_default
206
- : null;
207
- const defaultValue = normalizeColumnDefault(rawDefaultValue);
208
- const hasDefault = defaultValue != null;
209
- const extra = normalizeText(row.extra).toLowerCase();
210
- const autoIncrement = extra.includes("auto_increment");
211
- const unsigned = columnTypeLower.includes("unsigned");
212
- const enumValues = parseEnumValues(columnType);
213
- const supportsTemporalExpressions = TEMPORAL_DATA_TYPES.has(dataType);
214
-
215
- const normalized = Object.freeze({
216
- name,
217
- key: toCamelCase(name),
218
- dataType,
219
- columnType,
220
- extra,
221
- typeKind: resolveTypeKind({
222
- name,
223
- dataType,
224
- columnType
225
- }),
226
- nullable,
227
- defaultValue,
228
- defaultExpression: supportsTemporalExpressions
229
- ? normalizeCurrentTimestampExpression(defaultValue)
230
- : null,
231
- hasDefault,
232
- autoIncrement,
233
- onUpdateExpression: supportsTemporalExpressions
234
- ? normalizeOnUpdateExpression(extra)
235
- : null,
236
- unsigned,
237
- maxLength: toNullableNumber(row.characterMaximumLength ?? row.character_maximum_length),
238
- numericPrecision: toNullableNumber(row.numericPrecision ?? row.numeric_precision),
239
- numericScale: toNullableNumber(row.numericScale ?? row.numeric_scale),
240
- datetimePrecision: toNullableNumber(row.datetimePrecision ?? row.datetime_precision),
241
- characterSetName: normalizeText(row.characterSetName ?? row.character_set_name),
242
- collationName: normalizeText(row.collationName ?? row.collation_name),
243
- ordinalPosition: toNullableNumber(row.ordinalPosition ?? row.ordinal_position),
244
- enumValues
245
- });
246
-
247
- return normalized;
248
- }
249
-
250
- function normalizePrimaryKeyColumns(rows = []) {
251
- return Object.freeze(
252
- rows
253
- .map((row) => normalizeText(row.columnName || row.column_name))
254
- .filter(Boolean)
255
- );
256
- }
257
-
258
- function normalizePrimaryKeyColumnsByTable(rows = []) {
259
- const grouped = new Map();
260
-
261
- for (const row of Array.isArray(rows) ? rows : []) {
262
- const tableName = normalizeText(row.tableName || row.table_name);
263
- const columnName = normalizeText(row.columnName || row.column_name);
264
- if (!tableName || !columnName) {
265
- continue;
266
- }
267
-
268
- const columns = grouped.get(tableName) || [];
269
- columns.push({
270
- name: columnName,
271
- order: toNullableNumber(row.ordinalPosition ?? row.ordinal_position) || 0
272
- });
273
- grouped.set(tableName, columns);
274
- }
275
-
276
- return new Map(
277
- [...grouped.entries()].map(([tableName, columns]) => [
278
- tableName,
279
- Object.freeze(
280
- columns
281
- .sort((left, right) => left.order - right.order)
282
- .map((column) => column.name)
283
- )
284
- ])
285
- );
286
- }
287
-
288
- function normalizeIndexes(rows = []) {
289
- const byName = new Map();
290
-
291
- for (const row of Array.isArray(rows) ? rows : []) {
292
- const indexName = normalizeText(row.indexName || row.index_name);
293
- const columnName = normalizeText(row.columnName || row.column_name);
294
- if (!indexName || !columnName) {
295
- continue;
296
- }
297
-
298
- const seqInIndex = toNullableNumber(row.seqInIndex ?? row.seq_in_index) || 0;
299
- const nonUnique = toBoolean(row.nonUnique ?? row.non_unique);
300
- const indexType = normalizeText(row.indexType || row.index_type).toUpperCase();
301
- const existing = byName.get(indexName) || {
302
- name: indexName,
303
- unique: !nonUnique,
304
- indexType,
305
- columns: []
306
- };
307
- existing.columns.push({
308
- name: columnName,
309
- order: seqInIndex
310
- });
311
- byName.set(indexName, existing);
312
- }
313
-
314
- return Object.freeze(
315
- [...byName.values()]
316
- .map((index) =>
317
- Object.freeze({
318
- name: index.name,
319
- unique: index.unique,
320
- indexType: index.indexType,
321
- columns: Object.freeze(
322
- index.columns
323
- .sort((left, right) => left.order - right.order)
324
- .map((column) => column.name)
325
- )
326
- })
327
- )
328
- .sort((left, right) => left.name.localeCompare(right.name))
329
- );
330
- }
331
-
332
- function normalizeForeignKeys(rows = []) {
333
- const grouped = new Map();
334
-
335
- for (const row of Array.isArray(rows) ? rows : []) {
336
- const name = normalizeText(row.constraintName || row.constraint_name);
337
- const columnName = normalizeText(row.columnName || row.column_name);
338
- const referencedTableName = normalizeText(row.referencedTableName || row.referenced_table_name);
339
- const referencedColumnName = normalizeText(row.referencedColumnName || row.referenced_column_name);
340
- if (!name || !columnName || !referencedTableName || !referencedColumnName) {
341
- continue;
342
- }
343
-
344
- const ordinalPosition = toNullableNumber(row.ordinalPosition ?? row.ordinal_position) || 0;
345
- const updateRule = normalizeText(row.updateRule || row.update_rule).toUpperCase();
346
- const deleteRule = normalizeText(row.deleteRule || row.delete_rule).toUpperCase();
347
- const existing = grouped.get(name) || {
348
- name,
349
- referencedTableName,
350
- updateRule,
351
- deleteRule,
352
- columns: []
353
- };
354
-
355
- existing.columns.push({
356
- name: columnName,
357
- referencedName: referencedColumnName,
358
- order: ordinalPosition
359
- });
360
- grouped.set(name, existing);
361
- }
362
-
363
- return Object.freeze(
364
- [...grouped.values()]
365
- .map((foreignKey) =>
366
- Object.freeze({
367
- name: foreignKey.name,
368
- referencedTableName: foreignKey.referencedTableName,
369
- updateRule: foreignKey.updateRule,
370
- deleteRule: foreignKey.deleteRule,
371
- columns: Object.freeze(
372
- foreignKey.columns
373
- .sort((left, right) => left.order - right.order)
374
- .map((column) =>
375
- Object.freeze({
376
- name: column.name,
377
- referencedName: column.referencedName
378
- })
379
- )
380
- )
381
- })
382
- )
383
- .sort((left, right) => left.name.localeCompare(right.name))
384
- );
385
- }
386
-
387
- function normalizeCheckConstraints(rows = []) {
388
- return Object.freeze(
389
- (Array.isArray(rows) ? rows : [])
390
- .map((row) => {
391
- const name = normalizeText(row.constraintName || row.constraint_name);
392
- const clause = normalizeText(row.checkClause || row.check_clause);
393
- if (!name || !clause) {
394
- return null;
395
- }
396
-
397
- return Object.freeze({
398
- name,
399
- clause
400
- });
401
- })
402
- .filter(Boolean)
403
- .sort((left, right) => left.name.localeCompare(right.name))
404
- );
405
- }
406
-
407
- function requireIdColumn(columns, idColumn) {
408
- const normalizedIdColumn = normalizeText(idColumn) || "id";
409
- const idSpec = columns.find((column) => column.name === normalizedIdColumn) || null;
410
- if (!idSpec) {
411
- throw new Error(`Could not find id column "${normalizedIdColumn}" in table.`);
412
- }
413
- if (idSpec.typeKind !== "integer") {
414
- throw new Error(`Id column "${normalizedIdColumn}" must use an integer type.`);
415
- }
416
- if (idSpec.nullable) {
417
- throw new Error(`Id column "${normalizedIdColumn}" must be not-null.`);
418
- }
419
- if (!idSpec.autoIncrement && !idSpec.hasDefault) {
420
- throw new Error(
421
- `Id column "${normalizedIdColumn}" must be auto_increment or have a database default.`
422
- );
423
- }
424
-
425
- return normalizedIdColumn;
426
- }
427
-
428
- function requirePrimaryKeyContainsId(primaryKeyColumns, idColumn) {
429
- if (!Array.isArray(primaryKeyColumns) || !primaryKeyColumns.includes(idColumn)) {
430
- throw new Error(`Primary key must include id column "${idColumn}".`);
431
- }
432
- if (primaryKeyColumns.length !== 1 || primaryKeyColumns[0] !== idColumn) {
433
- throw new Error(
434
- `Composite primary keys are not supported for CRUD generation. Primary key must be only "${idColumn}".`
435
- );
436
- }
437
- }
438
-
439
- function requireSupportedForeignKeys(foreignKeys, primaryKeyColumnsByTable) {
440
- for (const foreignKey of foreignKeys) {
441
- const columns = Array.isArray(foreignKey?.columns) ? foreignKey.columns : [];
442
- if (columns.length !== 1) {
443
- throw new Error(
444
- `CRUD generation supports only single-column foreign keys. Constraint "${foreignKey.name}" has ${columns.length} columns.`
445
- );
446
- }
447
-
448
- const targetTable = normalizeText(foreignKey.referencedTableName);
449
- const targetColumn = normalizeText(columns[0]?.referencedName);
450
- const targetPrimaryKey = primaryKeyColumnsByTable.get(targetTable) || [];
451
- if (targetPrimaryKey.length !== 1) {
452
- const actual = targetPrimaryKey.length > 0 ? targetPrimaryKey.join(", ") : "none";
453
- throw new Error(
454
- `CRUD foreign key "${foreignKey.name}" targets table "${targetTable}", whose primary key is not single-column (found: ${actual}).`
455
- );
456
- }
457
- if (targetColumn !== targetPrimaryKey[0]) {
458
- throw new Error(
459
- `CRUD foreign key "${foreignKey.name}" must target the primary key "${targetTable}.${targetPrimaryKey[0]}", not "${targetTable}.${targetColumn}".`
460
- );
461
- }
462
- }
463
- }
464
-
465
- async function introspectCrudTableSnapshot(knex, { tableName = "", idColumn = "id" } = {}) {
466
- requireKnexRaw(knex);
467
- const resolvedTableName = requireTableName(tableName);
468
-
469
- const schemaRows = normalizeRows(await knex.raw("SELECT DATABASE() AS schemaName"));
470
- const schemaName = normalizeDbSchemaName(schemaRows);
471
-
472
- const tableRows = normalizeRows(
473
- await knex.raw(
474
- `
475
- SELECT
476
- t.table_collation AS tableCollation
477
- FROM information_schema.tables t
478
- WHERE t.table_schema = ?
479
- AND t.table_name = ?
480
- LIMIT 1
481
- `,
482
- [schemaName, resolvedTableName]
483
- )
484
- );
485
-
486
- const columnRows = normalizeRows(
487
- await knex.raw(
488
- `
489
- SELECT
490
- c.column_name AS columnName,
491
- c.data_type AS dataType,
492
- c.column_type AS columnType,
493
- c.is_nullable AS isNullable,
494
- c.column_default AS columnDefault,
495
- c.extra AS extra,
496
- c.character_maximum_length AS characterMaximumLength,
497
- c.character_set_name AS characterSetName,
498
- c.collation_name AS collationName,
499
- c.numeric_precision AS numericPrecision,
500
- c.numeric_scale AS numericScale,
501
- c.datetime_precision AS datetimePrecision,
502
- c.ordinal_position AS ordinalPosition
503
- FROM information_schema.columns c
504
- WHERE c.table_schema = ?
505
- AND c.table_name = ?
506
- ORDER BY c.ordinal_position ASC
507
- `,
508
- [schemaName, resolvedTableName]
509
- )
510
- );
511
- if (columnRows.length < 1) {
512
- throw new Error(`Could not introspect table "${resolvedTableName}" in schema "${schemaName}".`);
513
- }
514
-
515
- const primaryRows = normalizeRows(
516
- await knex.raw(
517
- `
518
- SELECT
519
- k.column_name AS columnName,
520
- k.ordinal_position AS ordinalPosition
521
- FROM information_schema.table_constraints t
522
- JOIN information_schema.key_column_usage k
523
- ON k.constraint_name = t.constraint_name
524
- AND k.table_schema = t.table_schema
525
- AND k.table_name = t.table_name
526
- WHERE t.table_schema = ?
527
- AND t.table_name = ?
528
- AND t.constraint_type = 'PRIMARY KEY'
529
- ORDER BY k.ordinal_position ASC
530
- `,
531
- [schemaName, resolvedTableName]
532
- )
533
- );
534
-
535
- const indexRows = normalizeRows(
536
- await knex.raw(
537
- `
538
- SELECT
539
- s.index_name AS indexName,
540
- s.non_unique AS nonUnique,
541
- s.index_type AS indexType,
542
- s.column_name AS columnName,
543
- s.seq_in_index AS seqInIndex
544
- FROM information_schema.statistics s
545
- WHERE s.table_schema = ?
546
- AND s.table_name = ?
547
- AND s.index_name <> 'PRIMARY'
548
- ORDER BY s.index_name ASC, s.seq_in_index ASC
549
- `,
550
- [schemaName, resolvedTableName]
551
- )
552
- );
553
-
554
- const foreignKeyRows = normalizeRows(
555
- await knex.raw(
556
- `
557
- SELECT
558
- rc.constraint_name AS constraintName,
559
- k.column_name AS columnName,
560
- k.referenced_table_name AS referencedTableName,
561
- k.referenced_column_name AS referencedColumnName,
562
- k.ordinal_position AS ordinalPosition,
563
- rc.update_rule AS updateRule,
564
- rc.delete_rule AS deleteRule
565
- FROM information_schema.referential_constraints rc
566
- JOIN information_schema.key_column_usage k
567
- ON k.constraint_name = rc.constraint_name
568
- AND k.constraint_schema = rc.constraint_schema
569
- AND k.table_name = rc.table_name
570
- WHERE rc.constraint_schema = ?
571
- AND rc.table_name = ?
572
- ORDER BY rc.constraint_name ASC, k.ordinal_position ASC
573
- `,
574
- [schemaName, resolvedTableName]
575
- )
576
- );
577
-
578
- const schemaPrimaryKeyRows = normalizeRows(
579
- await knex.raw(
580
- `
581
- SELECT
582
- s.table_name AS tableName,
583
- s.column_name AS columnName,
584
- s.seq_in_index AS ordinalPosition
585
- FROM information_schema.statistics s
586
- WHERE s.table_schema = ?
587
- AND s.index_name = 'PRIMARY'
588
- ORDER BY s.table_name ASC, s.seq_in_index ASC
589
- `,
590
- [schemaName]
591
- )
592
- );
593
-
594
- const checkConstraintRows = normalizeRows(
595
- await knex.raw(
596
- `
597
- SELECT
598
- tc.constraint_name AS constraintName,
599
- cc.check_clause AS checkClause
600
- FROM information_schema.table_constraints tc
601
- JOIN information_schema.check_constraints cc
602
- ON cc.constraint_schema = tc.constraint_schema
603
- AND cc.constraint_name = tc.constraint_name
604
- WHERE tc.table_schema = ?
605
- AND tc.table_name = ?
606
- AND tc.constraint_type = 'CHECK'
607
- ORDER BY tc.constraint_name ASC
608
- `,
609
- [schemaName, resolvedTableName]
610
- )
611
- );
612
-
613
- const columns = Object.freeze(columnRows.map((row) => normalizeColumn(row)));
614
- const resolvedIdColumn = requireIdColumn(columns, idColumn);
615
- const primaryKeyColumns = normalizePrimaryKeyColumns(primaryRows);
616
- requirePrimaryKeyContainsId(primaryKeyColumns, resolvedIdColumn);
617
- const foreignKeys = normalizeForeignKeys(foreignKeyRows);
618
- requireSupportedForeignKeys(
619
- foreignKeys,
620
- normalizePrimaryKeyColumnsByTable(schemaPrimaryKeyRows)
621
- );
622
- const firstTableRow = Array.isArray(tableRows) ? tableRows[0] : null;
623
-
624
- const snapshot = Object.freeze({
625
- dialect: "mysql2",
626
- schemaName,
627
- tableName: resolvedTableName,
628
- tableCollation: normalizeText(firstTableRow?.tableCollation || firstTableRow?.table_collation),
629
- idColumn: resolvedIdColumn,
630
- primaryKeyColumns,
631
- hasWorkspaceIdColumn: columns.some((column) => column.name === "workspace_id"),
632
- hasUserIdColumn: columns.some((column) => column.name === "user_id"),
633
- columns,
634
- indexes: normalizeIndexes(indexRows),
635
- foreignKeys,
636
- checkConstraints: normalizeCheckConstraints(checkConstraintRows)
637
- });
638
-
639
- return snapshot;
640
- }
641
-
642
- export { introspectCrudTableSnapshot };
@@ -1,568 +0,0 @@
1
- import assert from "node:assert/strict";
2
- import test from "node:test";
3
-
4
- import { introspectCrudTableSnapshot } from "../src/shared/introspectCrudTable.js";
5
-
6
- function createKnexRawDouble({
7
- schemaName = "appdb",
8
- tableCollation = "utf8mb4_general_ci",
9
- columns = [],
10
- primaryKeyColumns = [],
11
- indexes = [],
12
- foreignKeys = [],
13
- primaryKeysByTable = {},
14
- checkConstraints = []
15
- } = {}) {
16
- const calls = [];
17
-
18
- const knex = {
19
- async raw(sql, bindings = []) {
20
- const normalizedSql = String(sql || "").toLowerCase();
21
- calls.push({
22
- sql: normalizedSql,
23
- bindings: Array.isArray(bindings) ? [...bindings] : []
24
- });
25
-
26
- if (normalizedSql.includes("select database() as schemaname")) {
27
- return [[{ schemaName }], []];
28
- }
29
- if (normalizedSql.includes("from information_schema.tables")) {
30
- return [[{ tableCollation }], []];
31
- }
32
- if (normalizedSql.includes("from information_schema.columns")) {
33
- return [[...columns], []];
34
- }
35
- if (normalizedSql.includes("information_schema.check_constraints")) {
36
- return [[...checkConstraints], []];
37
- }
38
- if (normalizedSql.includes("from information_schema.table_constraints")) {
39
- return [[...primaryKeyColumns], []];
40
- }
41
- if (
42
- normalizedSql.includes("from information_schema.statistics") &&
43
- normalizedSql.includes("s.index_name = 'primary'")
44
- ) {
45
- return [
46
- Object.entries(primaryKeysByTable).flatMap(([tableName, columnNames]) =>
47
- columnNames.map((columnName, index) => ({
48
- tableName,
49
- columnName,
50
- ordinalPosition: index + 1
51
- }))
52
- ),
53
- []
54
- ];
55
- }
56
- if (normalizedSql.includes("from information_schema.statistics")) {
57
- return [[...indexes], []];
58
- }
59
- if (normalizedSql.includes("from information_schema.referential_constraints")) {
60
- return [[...foreignKeys], []];
61
- }
62
-
63
- throw new Error(`Unexpected SQL in test double: ${normalizedSql}`);
64
- }
65
- };
66
-
67
- return {
68
- knex,
69
- calls
70
- };
71
- }
72
-
73
- test("introspectCrudTableSnapshot maps MySQL table metadata to normalized snapshot", async () => {
74
- const { knex } = createKnexRawDouble({
75
- columns: [
76
- {
77
- columnName: "id",
78
- dataType: "int",
79
- columnType: "int unsigned",
80
- isNullable: "NO",
81
- columnDefault: null,
82
- extra: "auto_increment",
83
- characterMaximumLength: null,
84
- characterSetName: null,
85
- collationName: null,
86
- numericPrecision: 10,
87
- numericScale: 0,
88
- datetimePrecision: null,
89
- ordinalPosition: 1
90
- },
91
- {
92
- columnName: "workspace_id",
93
- dataType: "int",
94
- columnType: "int unsigned",
95
- isNullable: "YES",
96
- columnDefault: "NULL",
97
- extra: "",
98
- characterMaximumLength: null,
99
- characterSetName: null,
100
- collationName: null,
101
- numericPrecision: 10,
102
- numericScale: 0,
103
- datetimePrecision: null,
104
- ordinalPosition: 2
105
- },
106
- {
107
- columnName: "user_id",
108
- dataType: "int",
109
- columnType: "int unsigned",
110
- isNullable: "YES",
111
- columnDefault: "NULL",
112
- extra: "",
113
- characterMaximumLength: null,
114
- characterSetName: null,
115
- collationName: null,
116
- numericPrecision: 10,
117
- numericScale: 0,
118
- datetimePrecision: null,
119
- ordinalPosition: 3
120
- },
121
- {
122
- columnName: "first_name",
123
- dataType: "varchar",
124
- columnType: "varchar(160)",
125
- isNullable: "NO",
126
- columnDefault: null,
127
- extra: "",
128
- characterMaximumLength: 160,
129
- characterSetName: "utf8mb4",
130
- collationName: "utf8mb4_general_ci",
131
- numericPrecision: null,
132
- numericScale: null,
133
- datetimePrecision: null,
134
- ordinalPosition: 4
135
- },
136
- {
137
- columnName: "vip",
138
- dataType: "tinyint",
139
- columnType: "tinyint(1)",
140
- isNullable: "NO",
141
- columnDefault: "0",
142
- extra: "",
143
- characterMaximumLength: null,
144
- characterSetName: null,
145
- collationName: null,
146
- numericPrecision: 3,
147
- numericScale: 0,
148
- datetimePrecision: null,
149
- ordinalPosition: 5
150
- },
151
- {
152
- columnName: "contact_tier",
153
- dataType: "enum",
154
- columnType: "enum('VIP','New')",
155
- isNullable: "NO",
156
- columnDefault: "VIP",
157
- extra: "",
158
- characterMaximumLength: null,
159
- characterSetName: "utf8mb4",
160
- collationName: "utf8mb4_general_ci",
161
- numericPrecision: null,
162
- numericScale: null,
163
- datetimePrecision: null,
164
- ordinalPosition: 6
165
- },
166
- {
167
- columnName: "updated_at",
168
- dataType: "datetime",
169
- columnType: "datetime(3)",
170
- isNullable: "NO",
171
- columnDefault: "CURRENT_TIMESTAMP(3)",
172
- extra: "DEFAULT_GENERATED on update CURRENT_TIMESTAMP(3)",
173
- characterMaximumLength: null,
174
- characterSetName: null,
175
- collationName: null,
176
- numericPrecision: null,
177
- numericScale: null,
178
- datetimePrecision: 3,
179
- ordinalPosition: 7
180
- },
181
- {
182
- columnName: "settings_json",
183
- dataType: "longtext",
184
- columnType: "longtext",
185
- isNullable: "YES",
186
- columnDefault: null,
187
- extra: "",
188
- characterMaximumLength: null,
189
- characterSetName: "utf8mb4",
190
- collationName: "utf8mb4_bin",
191
- numericPrecision: null,
192
- numericScale: null,
193
- datetimePrecision: null,
194
- ordinalPosition: 8
195
- }
196
- ],
197
- primaryKeyColumns: [{ columnName: "id" }],
198
- indexes: [
199
- {
200
- indexName: "idx_contacts_first_name",
201
- nonUnique: 1,
202
- columnName: "first_name",
203
- seqInIndex: 1
204
- },
205
- {
206
- indexName: "uq_contacts_vip",
207
- nonUnique: 0,
208
- columnName: "vip",
209
- seqInIndex: 1
210
- }
211
- ],
212
- foreignKeys: [
213
- {
214
- constraintName: "contacts_workspace_id_foreign",
215
- columnName: "workspace_id",
216
- referencedTableName: "workspaces",
217
- referencedColumnName: "id",
218
- ordinalPosition: 1,
219
- updateRule: "CASCADE",
220
- deleteRule: "SET NULL"
221
- }
222
- ],
223
- primaryKeysByTable: {
224
- contacts: ["id"],
225
- workspaces: ["id"]
226
- },
227
- checkConstraints: [
228
- {
229
- constraintName: "settings_json",
230
- checkClause: "json_valid(`settings_json`)"
231
- }
232
- ]
233
- });
234
-
235
- const snapshot = await introspectCrudTableSnapshot(knex, {
236
- tableName: "contacts",
237
- idColumn: "id"
238
- });
239
-
240
- assert.equal(snapshot.dialect, "mysql2");
241
- assert.equal(snapshot.tableName, "contacts");
242
- assert.equal(snapshot.tableCollation, "utf8mb4_general_ci");
243
- assert.equal(snapshot.idColumn, "id");
244
- assert.deepEqual(snapshot.primaryKeyColumns, ["id"]);
245
- assert.equal(snapshot.hasWorkspaceIdColumn, true);
246
- assert.equal(snapshot.hasUserIdColumn, true);
247
-
248
- const firstName = snapshot.columns.find((column) => column.name === "first_name");
249
- assert.ok(firstName);
250
- assert.equal(firstName.key, "firstName");
251
- assert.equal(firstName.typeKind, "string");
252
- assert.equal(firstName.maxLength, 160);
253
-
254
- const workspaceId = snapshot.columns.find((column) => column.name === "workspace_id");
255
- assert.ok(workspaceId);
256
- assert.equal(workspaceId.hasDefault, false);
257
-
258
- const vip = snapshot.columns.find((column) => column.name === "vip");
259
- assert.ok(vip);
260
- assert.equal(vip.typeKind, "boolean");
261
- assert.equal(vip.hasDefault, true);
262
-
263
- const contactTier = snapshot.columns.find((column) => column.name === "contact_tier");
264
- assert.ok(contactTier);
265
- assert.deepEqual(contactTier.enumValues, ["VIP", "New"]);
266
-
267
- const settingsJson = snapshot.columns.find((column) => column.name === "settings_json");
268
- assert.ok(settingsJson);
269
- assert.equal(settingsJson.characterSetName, "utf8mb4");
270
- assert.equal(settingsJson.collationName, "utf8mb4_bin");
271
-
272
- const updatedAt = snapshot.columns.find((column) => column.name === "updated_at");
273
- assert.deepEqual(updatedAt.defaultExpression, {
274
- kind: "current_timestamp",
275
- precision: 3
276
- });
277
- assert.deepEqual(updatedAt.onUpdateExpression, {
278
- kind: "current_timestamp",
279
- precision: 3
280
- });
281
-
282
- assert.deepEqual(snapshot.indexes, [
283
- {
284
- name: "idx_contacts_first_name",
285
- unique: false,
286
- indexType: "",
287
- columns: ["first_name"]
288
- },
289
- {
290
- name: "uq_contacts_vip",
291
- unique: true,
292
- indexType: "",
293
- columns: ["vip"]
294
- }
295
- ]);
296
- assert.deepEqual(snapshot.foreignKeys, [
297
- {
298
- name: "contacts_workspace_id_foreign",
299
- referencedTableName: "workspaces",
300
- updateRule: "CASCADE",
301
- deleteRule: "SET NULL",
302
- columns: [
303
- {
304
- name: "workspace_id",
305
- referencedName: "id"
306
- }
307
- ]
308
- }
309
- ]);
310
- assert.deepEqual(snapshot.checkConstraints, [
311
- {
312
- name: "settings_json",
313
- clause: "json_valid(`settings_json`)"
314
- }
315
- ]);
316
- });
317
-
318
- test("introspectCrudTableSnapshot rejects unsupported column types", async () => {
319
- const { knex } = createKnexRawDouble({
320
- columns: [
321
- {
322
- columnName: "id",
323
- dataType: "int",
324
- columnType: "int unsigned",
325
- isNullable: "NO",
326
- columnDefault: null,
327
- extra: "auto_increment",
328
- characterMaximumLength: null,
329
- characterSetName: null,
330
- collationName: null,
331
- numericPrecision: 10,
332
- numericScale: 0,
333
- datetimePrecision: null,
334
- ordinalPosition: 1
335
- },
336
- {
337
- columnName: "location",
338
- dataType: "point",
339
- columnType: "point",
340
- isNullable: "YES",
341
- columnDefault: null,
342
- extra: "",
343
- characterMaximumLength: null,
344
- characterSetName: null,
345
- collationName: null,
346
- numericPrecision: null,
347
- numericScale: null,
348
- datetimePrecision: null,
349
- ordinalPosition: 2
350
- }
351
- ],
352
- primaryKeyColumns: [{ columnName: "id" }]
353
- });
354
-
355
- await assert.rejects(
356
- () => introspectCrudTableSnapshot(knex, { tableName: "contacts" }),
357
- /Unsupported MySQL column type "point"/
358
- );
359
- });
360
-
361
- test("introspectCrudTableSnapshot rejects when primary key does not include id column", async () => {
362
- const { knex } = createKnexRawDouble({
363
- columns: [
364
- {
365
- columnName: "id",
366
- dataType: "int",
367
- columnType: "int unsigned",
368
- isNullable: "NO",
369
- columnDefault: null,
370
- extra: "auto_increment",
371
- characterMaximumLength: null,
372
- characterSetName: null,
373
- collationName: null,
374
- numericPrecision: 10,
375
- numericScale: 0,
376
- datetimePrecision: null,
377
- ordinalPosition: 1
378
- }
379
- ],
380
- primaryKeyColumns: [{ columnName: "other_id" }]
381
- });
382
-
383
- await assert.rejects(
384
- () => introspectCrudTableSnapshot(knex, { tableName: "contacts" }),
385
- /Primary key must include id column "id"/
386
- );
387
- });
388
-
389
- test("introspectCrudTableSnapshot classifies only allowlisted temporal defaults as SQL expressions", async () => {
390
- const { knex } = createKnexRawDouble({
391
- columns: [
392
- ...validIdColumns(),
393
- {
394
- columnName: "label",
395
- dataType: "varchar",
396
- columnType: "varchar(190)",
397
- isNullable: "NO",
398
- columnDefault: "CURRENT_TIMESTAMP(3)",
399
- extra: "",
400
- characterMaximumLength: 190,
401
- characterSetName: "utf8mb4",
402
- collationName: "utf8mb4_general_ci",
403
- ordinalPosition: 2
404
- },
405
- {
406
- columnName: "created_at",
407
- dataType: "datetime",
408
- columnType: "datetime",
409
- isNullable: "NO",
410
- columnDefault: "CURRENT_TIMESTAMP()",
411
- extra: "",
412
- datetimePrecision: 0,
413
- ordinalPosition: 3
414
- }
415
- ],
416
- primaryKeyColumns: [{ columnName: "id" }]
417
- });
418
-
419
- const snapshot = await introspectCrudTableSnapshot(knex, {
420
- tableName: "labels"
421
- });
422
- const label = snapshot.columns.find((column) => column.name === "label");
423
-
424
- assert.equal(label.defaultValue, "CURRENT_TIMESTAMP(3)");
425
- assert.equal(label.defaultExpression, null);
426
- assert.equal(label.onUpdateExpression, null);
427
- assert.deepEqual(
428
- snapshot.columns.find((column) => column.name === "created_at").defaultExpression,
429
- {
430
- kind: "current_timestamp",
431
- precision: null
432
- }
433
- );
434
- });
435
-
436
- function validIdColumns(extraColumns = []) {
437
- return [
438
- {
439
- columnName: "id",
440
- dataType: "bigint",
441
- columnType: "bigint unsigned",
442
- isNullable: "NO",
443
- columnDefault: null,
444
- extra: "auto_increment",
445
- numericPrecision: 20,
446
- numericScale: 0,
447
- ordinalPosition: 1
448
- },
449
- ...extraColumns
450
- ];
451
- }
452
-
453
- test("introspectCrudTableSnapshot rejects composite foreign keys", async () => {
454
- const { knex } = createKnexRawDouble({
455
- columns: validIdColumns([
456
- {
457
- columnName: "workspace_id",
458
- dataType: "bigint",
459
- columnType: "bigint unsigned",
460
- isNullable: "NO",
461
- extra: "",
462
- ordinalPosition: 2
463
- },
464
- {
465
- columnName: "parent_id",
466
- dataType: "bigint",
467
- columnType: "bigint unsigned",
468
- isNullable: "NO",
469
- extra: "",
470
- ordinalPosition: 3
471
- }
472
- ]),
473
- primaryKeyColumns: [{ columnName: "id" }],
474
- foreignKeys: [
475
- {
476
- constraintName: "items_parent_foreign",
477
- columnName: "workspace_id",
478
- referencedTableName: "parents",
479
- referencedColumnName: "workspace_id",
480
- ordinalPosition: 1
481
- },
482
- {
483
- constraintName: "items_parent_foreign",
484
- columnName: "parent_id",
485
- referencedTableName: "parents",
486
- referencedColumnName: "id",
487
- ordinalPosition: 2
488
- }
489
- ],
490
- primaryKeysByTable: {
491
- items: ["id"],
492
- parents: ["id"]
493
- }
494
- });
495
-
496
- await assert.rejects(
497
- () => introspectCrudTableSnapshot(knex, { tableName: "items" }),
498
- /supports only single-column foreign keys.*2 columns/
499
- );
500
- });
501
-
502
- test("introspectCrudTableSnapshot rejects foreign keys to non-primary business keys", async () => {
503
- const { knex } = createKnexRawDouble({
504
- columns: validIdColumns([
505
- {
506
- columnName: "workspace_slug",
507
- dataType: "varchar",
508
- columnType: "varchar(190)",
509
- isNullable: "NO",
510
- extra: "",
511
- ordinalPosition: 2
512
- }
513
- ]),
514
- primaryKeyColumns: [{ columnName: "id" }],
515
- foreignKeys: [
516
- {
517
- constraintName: "items_workspace_slug_foreign",
518
- columnName: "workspace_slug",
519
- referencedTableName: "workspaces",
520
- referencedColumnName: "slug",
521
- ordinalPosition: 1
522
- }
523
- ],
524
- primaryKeysByTable: {
525
- items: ["id"],
526
- workspaces: ["id"]
527
- }
528
- });
529
-
530
- await assert.rejects(
531
- () => introspectCrudTableSnapshot(knex, { tableName: "items" }),
532
- /must target the primary key "workspaces.id", not "workspaces.slug"/
533
- );
534
- });
535
-
536
- test("introspectCrudTableSnapshot rejects foreign keys to composite primary keys", async () => {
537
- const { knex } = createKnexRawDouble({
538
- columns: validIdColumns([
539
- {
540
- columnName: "parent_id",
541
- dataType: "bigint",
542
- columnType: "bigint unsigned",
543
- isNullable: "NO",
544
- extra: "",
545
- ordinalPosition: 2
546
- }
547
- ]),
548
- primaryKeyColumns: [{ columnName: "id" }],
549
- foreignKeys: [
550
- {
551
- constraintName: "items_parent_foreign",
552
- columnName: "parent_id",
553
- referencedTableName: "parents",
554
- referencedColumnName: "id",
555
- ordinalPosition: 1
556
- }
557
- ],
558
- primaryKeysByTable: {
559
- items: ["id"],
560
- parents: ["workspace_id", "id"]
561
- }
562
- });
563
-
564
- await assert.rejects(
565
- () => introspectCrudTableSnapshot(knex, { tableName: "items" }),
566
- /primary key is not single-column.*workspace_id, id/
567
- );
568
- });