@xubylele/schema-forge 1.5.0 → 1.5.1

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.
Files changed (3) hide show
  1. package/README.md +2 -0
  2. package/dist/cli.js +2072 -51
  3. package/package.json +3 -3
package/dist/cli.js CHANGED
@@ -6,6 +6,13 @@ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
6
  var __getOwnPropNames = Object.getOwnPropertyNames;
7
7
  var __getProtoOf = Object.getPrototypeOf;
8
8
  var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __esm = (fn, res) => function __init() {
10
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
11
+ };
12
+ var __export = (target, all) => {
13
+ for (var name in all)
14
+ __defProp(target, name, { get: all[name], enumerable: true });
15
+ };
9
16
  var __copyProps = (to, from, except, desc) => {
10
17
  if (from && typeof from === "object" || typeof from === "function") {
11
18
  for (let key of __getOwnPropNames(from))
@@ -23,13 +30,2027 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
23
30
  mod
24
31
  ));
25
32
 
33
+ // node_modules/@xubylele/schema-forge-core/dist/core/parser.js
34
+ function parseSchema(source) {
35
+ const lines = source.split("\n");
36
+ const tables = {};
37
+ let currentLine = 0;
38
+ const validBaseColumnTypes = /* @__PURE__ */ new Set([
39
+ "uuid",
40
+ "varchar",
41
+ "text",
42
+ "int",
43
+ "bigint",
44
+ "boolean",
45
+ "timestamptz",
46
+ "date"
47
+ ]);
48
+ function normalizeColumnType3(type) {
49
+ return type.toLowerCase().trim().replace(/\s+/g, " ").replace(/\s*\(\s*/g, "(").replace(/\s*,\s*/g, ",").replace(/\s*\)\s*/g, ")");
50
+ }
51
+ function isValidColumnType2(type) {
52
+ const normalizedType = normalizeColumnType3(type);
53
+ if (validBaseColumnTypes.has(normalizedType)) {
54
+ return true;
55
+ }
56
+ return /^varchar\(\d+\)$/.test(normalizedType) || /^numeric\(\d+,\d+\)$/.test(normalizedType);
57
+ }
58
+ function cleanLine(line) {
59
+ const commentIndex = line.search(/(?:\/\/|#)/);
60
+ if (commentIndex !== -1) {
61
+ line = line.substring(0, commentIndex);
62
+ }
63
+ return line.trim();
64
+ }
65
+ function parseForeignKey(fkRef, lineNum) {
66
+ const parts = fkRef.split(".");
67
+ if (parts.length !== 2 || !parts[0] || !parts[1]) {
68
+ throw new Error(`Line ${lineNum}: Invalid foreign key format '${fkRef}'. Expected format: table.column`);
69
+ }
70
+ return {
71
+ table: parts[0],
72
+ column: parts[1]
73
+ };
74
+ }
75
+ function parseColumn(line, lineNum) {
76
+ const tokens = line.split(/\s+/).filter((t) => t.length > 0);
77
+ const modifiers = /* @__PURE__ */ new Set(["pk", "unique", "nullable", "default", "fk"]);
78
+ if (tokens.length < 2) {
79
+ throw new Error(`Line ${lineNum}: Invalid column definition. Expected: <name> <type> [modifiers...]`);
80
+ }
81
+ const colName = tokens[0];
82
+ const colType = normalizeColumnType3(tokens[1]);
83
+ if (!isValidColumnType2(colType)) {
84
+ throw new Error(`Line ${lineNum}: Invalid column type '${tokens[1]}'. Valid types: ${Array.from(validBaseColumnTypes).join(", ")}, varchar(n), numeric(p,s)`);
85
+ }
86
+ const column = {
87
+ name: colName,
88
+ type: colType,
89
+ nullable: true
90
+ };
91
+ let i = 2;
92
+ while (i < tokens.length) {
93
+ const modifier = tokens[i];
94
+ switch (modifier) {
95
+ case "pk":
96
+ column.primaryKey = true;
97
+ i++;
98
+ break;
99
+ case "unique":
100
+ column.unique = true;
101
+ i++;
102
+ break;
103
+ case "nullable":
104
+ column.nullable = true;
105
+ i++;
106
+ break;
107
+ case "not":
108
+ if (tokens[i + 1] !== "null") {
109
+ throw new Error(`Line ${lineNum}: Unknown modifier 'not'`);
110
+ }
111
+ column.nullable = false;
112
+ i += 2;
113
+ break;
114
+ case "default":
115
+ i++;
116
+ if (i >= tokens.length) {
117
+ throw new Error(`Line ${lineNum}: 'default' modifier requires a value`);
118
+ }
119
+ {
120
+ const defaultTokens = [];
121
+ while (i < tokens.length && !modifiers.has(tokens[i])) {
122
+ defaultTokens.push(tokens[i]);
123
+ i++;
124
+ }
125
+ if (defaultTokens.length === 0) {
126
+ throw new Error(`Line ${lineNum}: 'default' modifier requires a value`);
127
+ }
128
+ column.default = defaultTokens.join(" ");
129
+ }
130
+ break;
131
+ case "fk":
132
+ i++;
133
+ if (i >= tokens.length) {
134
+ throw new Error(`Line ${lineNum}: 'fk' modifier requires a table.column reference`);
135
+ }
136
+ column.foreignKey = parseForeignKey(tokens[i], lineNum);
137
+ i++;
138
+ break;
139
+ default:
140
+ throw new Error(`Line ${lineNum}: Unknown modifier '${modifier}'`);
141
+ }
142
+ }
143
+ return column;
144
+ }
145
+ function parseTableBlock(startLine) {
146
+ const firstLine = cleanLine(lines[startLine]);
147
+ const match = firstLine.match(/^table\s+(\w+)\s*\{?\s*$/);
148
+ if (!match) {
149
+ throw new Error(`Line ${startLine + 1}: Invalid table definition. Expected: table <name> {`);
150
+ }
151
+ const tableName = match[1];
152
+ if (tables[tableName]) {
153
+ throw new Error(`Line ${startLine + 1}: Duplicate table definition '${tableName}'`);
154
+ }
155
+ const columns = [];
156
+ let lineIdx = startLine + 1;
157
+ let foundClosingBrace = false;
158
+ while (lineIdx < lines.length) {
159
+ const cleaned = cleanLine(lines[lineIdx]);
160
+ if (!cleaned) {
161
+ lineIdx++;
162
+ continue;
163
+ }
164
+ if (cleaned === "}") {
165
+ foundClosingBrace = true;
166
+ break;
167
+ }
168
+ try {
169
+ const column = parseColumn(cleaned, lineIdx + 1);
170
+ columns.push(column);
171
+ } catch (error2) {
172
+ throw error2;
173
+ }
174
+ lineIdx++;
175
+ }
176
+ if (!foundClosingBrace) {
177
+ throw new Error(`Line ${startLine + 1}: Table '${tableName}' block not closed (missing '}')`);
178
+ }
179
+ const primaryKeyColumn = columns.find((column) => column.primaryKey)?.name ?? null;
180
+ tables[tableName] = {
181
+ name: tableName,
182
+ columns,
183
+ ...primaryKeyColumn !== null && { primaryKey: primaryKeyColumn }
184
+ };
185
+ return lineIdx;
186
+ }
187
+ while (currentLine < lines.length) {
188
+ const cleaned = cleanLine(lines[currentLine]);
189
+ if (!cleaned) {
190
+ currentLine++;
191
+ continue;
192
+ }
193
+ if (cleaned.startsWith("table ")) {
194
+ currentLine = parseTableBlock(currentLine);
195
+ } else {
196
+ throw new Error(`Line ${currentLine + 1}: Unexpected content '${cleaned}'. Expected table definition.`);
197
+ }
198
+ currentLine++;
199
+ }
200
+ return { tables };
201
+ }
202
+ var init_parser = __esm({
203
+ "node_modules/@xubylele/schema-forge-core/dist/core/parser.js"() {
204
+ "use strict";
205
+ }
206
+ });
207
+
208
+ // node_modules/@xubylele/schema-forge-core/dist/core/normalize.js
209
+ function normalizeIdent(input) {
210
+ return input.trim().toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/_+/g, "_").replace(/^_+|_+$/g, "");
211
+ }
212
+ function pkName(table) {
213
+ return `pk_${normalizeIdent(table)}`;
214
+ }
215
+ function uqName(table, column) {
216
+ return `uq_${normalizeIdent(table)}_${normalizeIdent(column)}`;
217
+ }
218
+ function legacyPkName(table) {
219
+ return `${normalizeIdent(table)}_pkey`;
220
+ }
221
+ function legacyUqName(table, column) {
222
+ return `${normalizeIdent(table)}_${normalizeIdent(column)}_key`;
223
+ }
224
+ function normalizeSpacesOutsideQuotes(value) {
225
+ let result = "";
226
+ let inSingleQuote = false;
227
+ let inDoubleQuote = false;
228
+ let pendingSpace = false;
229
+ for (const char of value) {
230
+ if (char === "'" && !inDoubleQuote) {
231
+ if (pendingSpace && result.length > 0 && result[result.length - 1] !== " ") {
232
+ result += " ";
233
+ }
234
+ pendingSpace = false;
235
+ inSingleQuote = !inSingleQuote;
236
+ result += char;
237
+ continue;
238
+ }
239
+ if (char === '"' && !inSingleQuote) {
240
+ if (pendingSpace && result.length > 0 && result[result.length - 1] !== " ") {
241
+ result += " ";
242
+ }
243
+ pendingSpace = false;
244
+ inDoubleQuote = !inDoubleQuote;
245
+ result += char;
246
+ continue;
247
+ }
248
+ if (!inSingleQuote && !inDoubleQuote && /\s/.test(char)) {
249
+ pendingSpace = true;
250
+ continue;
251
+ }
252
+ if (pendingSpace && result.length > 0 && result[result.length - 1] !== " ") {
253
+ result += " ";
254
+ }
255
+ pendingSpace = false;
256
+ result += char;
257
+ }
258
+ return result.trim();
259
+ }
260
+ function normalizeKnownFunctionsOutsideQuotes(value) {
261
+ let result = "";
262
+ let inSingleQuote = false;
263
+ let inDoubleQuote = false;
264
+ let buffer = "";
265
+ function flushBuffer() {
266
+ if (!buffer) {
267
+ return;
268
+ }
269
+ result += buffer.replace(/\bnow\s*\(\s*\)/gi, "now()").replace(/\bgen_random_uuid\s*\(\s*\)/gi, "gen_random_uuid()");
270
+ buffer = "";
271
+ }
272
+ for (const char of value) {
273
+ if (char === "'" && !inDoubleQuote) {
274
+ flushBuffer();
275
+ inSingleQuote = !inSingleQuote;
276
+ result += char;
277
+ continue;
278
+ }
279
+ if (char === '"' && !inSingleQuote) {
280
+ flushBuffer();
281
+ inDoubleQuote = !inDoubleQuote;
282
+ result += char;
283
+ continue;
284
+ }
285
+ if (inSingleQuote || inDoubleQuote) {
286
+ result += char;
287
+ continue;
288
+ }
289
+ buffer += char;
290
+ }
291
+ flushBuffer();
292
+ return result;
293
+ }
294
+ function normalizePunctuationOutsideQuotes(value) {
295
+ let result = "";
296
+ let inSingleQuote = false;
297
+ let inDoubleQuote = false;
298
+ for (let index = 0; index < value.length; index++) {
299
+ const char = value[index];
300
+ if (char === "'" && !inDoubleQuote) {
301
+ inSingleQuote = !inSingleQuote;
302
+ result += char;
303
+ continue;
304
+ }
305
+ if (char === '"' && !inSingleQuote) {
306
+ inDoubleQuote = !inDoubleQuote;
307
+ result += char;
308
+ continue;
309
+ }
310
+ if (!inSingleQuote && !inDoubleQuote && (char === "(" || char === ")")) {
311
+ while (result.endsWith(" ")) {
312
+ result = result.slice(0, -1);
313
+ }
314
+ result += char;
315
+ let lookahead = index + 1;
316
+ while (lookahead < value.length && value[lookahead] === " ") {
317
+ lookahead++;
318
+ }
319
+ index = lookahead - 1;
320
+ continue;
321
+ }
322
+ if (!inSingleQuote && !inDoubleQuote && char === ",") {
323
+ while (result.endsWith(" ")) {
324
+ result = result.slice(0, -1);
325
+ }
326
+ result += ", ";
327
+ let lookahead = index + 1;
328
+ while (lookahead < value.length && value[lookahead] === " ") {
329
+ lookahead++;
330
+ }
331
+ index = lookahead - 1;
332
+ continue;
333
+ }
334
+ result += char;
335
+ }
336
+ return result;
337
+ }
338
+ function normalizeDefault(expr) {
339
+ if (expr === void 0 || expr === null) {
340
+ return null;
341
+ }
342
+ const trimmed = expr.trim();
343
+ if (trimmed.length === 0) {
344
+ return null;
345
+ }
346
+ const normalizedSpacing = normalizeSpacesOutsideQuotes(trimmed);
347
+ const normalizedPunctuation = normalizePunctuationOutsideQuotes(normalizedSpacing);
348
+ return normalizeKnownFunctionsOutsideQuotes(normalizedPunctuation);
349
+ }
350
+ var init_normalize = __esm({
351
+ "node_modules/@xubylele/schema-forge-core/dist/core/normalize.js"() {
352
+ "use strict";
353
+ }
354
+ });
355
+
356
+ // node_modules/@xubylele/schema-forge-core/dist/core/diff.js
357
+ function getTableNamesFromState(state) {
358
+ return new Set(Object.keys(state.tables));
359
+ }
360
+ function getTableNamesFromSchema(schema) {
361
+ return new Set(Object.keys(schema.tables));
362
+ }
363
+ function getColumnNamesFromState(stateColumns) {
364
+ return new Set(Object.keys(stateColumns));
365
+ }
366
+ function getColumnNamesFromSchema(dbColumns) {
367
+ return new Set(dbColumns.map((column) => column.name));
368
+ }
369
+ function getSortedNames(names) {
370
+ return Array.from(names).sort((a, b) => a.localeCompare(b));
371
+ }
372
+ function normalizeColumnType(type) {
373
+ return type.toLowerCase().trim().replace(/\s+/g, " ").replace(/\s*\(\s*/g, "(").replace(/\s*,\s*/g, ",").replace(/\s*\)\s*/g, ")");
374
+ }
375
+ function resolveStatePrimaryKey(table) {
376
+ return table.primaryKey ?? Object.entries(table.columns).find(([, column]) => column.primaryKey)?.[0] ?? null;
377
+ }
378
+ function resolveSchemaPrimaryKey(table) {
379
+ return table.primaryKey ?? table.columns.find((column) => column.primaryKey)?.name ?? null;
380
+ }
381
+ function normalizeNullable(nullable) {
382
+ return nullable ?? true;
383
+ }
384
+ function diffSchemas(oldState, newSchema) {
385
+ const operations = [];
386
+ const oldTableNames = getTableNamesFromState(oldState);
387
+ const newTableNames = getTableNamesFromSchema(newSchema);
388
+ const sortedNewTableNames = getSortedNames(newTableNames);
389
+ const sortedOldTableNames = getSortedNames(oldTableNames);
390
+ for (const tableName of sortedNewTableNames) {
391
+ if (!oldTableNames.has(tableName)) {
392
+ operations.push({
393
+ kind: "create_table",
394
+ table: newSchema.tables[tableName]
395
+ });
396
+ }
397
+ }
398
+ const commonTableNames = sortedNewTableNames.filter((tableName) => oldTableNames.has(tableName));
399
+ for (const tableName of commonTableNames) {
400
+ const newTable = newSchema.tables[tableName];
401
+ const oldTable = oldState.tables[tableName];
402
+ if (!newTable || !oldTable) {
403
+ continue;
404
+ }
405
+ for (const column of newTable.columns) {
406
+ const previousColumn = oldTable.columns[column.name];
407
+ if (!previousColumn) {
408
+ continue;
409
+ }
410
+ const previousType = normalizeColumnType(previousColumn.type);
411
+ const currentType = normalizeColumnType(column.type);
412
+ if (previousType !== currentType) {
413
+ operations.push({
414
+ kind: "column_type_changed",
415
+ tableName,
416
+ columnName: column.name,
417
+ fromType: previousColumn.type,
418
+ toType: column.type
419
+ });
420
+ }
421
+ }
422
+ }
423
+ for (const tableName of commonTableNames) {
424
+ const newTable = newSchema.tables[tableName];
425
+ const oldTable = oldState.tables[tableName];
426
+ if (!newTable || !oldTable) {
427
+ continue;
428
+ }
429
+ const previousPrimaryKey = resolveStatePrimaryKey(oldTable);
430
+ const currentPrimaryKey = resolveSchemaPrimaryKey(newTable);
431
+ if (previousPrimaryKey !== null && previousPrimaryKey !== currentPrimaryKey) {
432
+ operations.push({
433
+ kind: "drop_primary_key_constraint",
434
+ tableName
435
+ });
436
+ }
437
+ }
438
+ for (const tableName of commonTableNames) {
439
+ const newTable = newSchema.tables[tableName];
440
+ const oldTable = oldState.tables[tableName];
441
+ if (!newTable || !oldTable) {
442
+ continue;
443
+ }
444
+ for (const column of newTable.columns) {
445
+ const previousColumn = oldTable.columns[column.name];
446
+ if (!previousColumn) {
447
+ continue;
448
+ }
449
+ const previousUnique = previousColumn.unique ?? false;
450
+ const currentUnique = column.unique ?? false;
451
+ if (previousUnique !== currentUnique) {
452
+ operations.push({
453
+ kind: "column_unique_changed",
454
+ tableName,
455
+ columnName: column.name,
456
+ from: previousUnique,
457
+ to: currentUnique
458
+ });
459
+ }
460
+ }
461
+ }
462
+ for (const tableName of commonTableNames) {
463
+ const newTable = newSchema.tables[tableName];
464
+ const oldTable = oldState.tables[tableName];
465
+ if (!newTable || !oldTable) {
466
+ continue;
467
+ }
468
+ for (const column of newTable.columns) {
469
+ const previousColumn = oldTable.columns[column.name];
470
+ if (!previousColumn) {
471
+ continue;
472
+ }
473
+ const previousNullable = normalizeNullable(previousColumn.nullable);
474
+ const currentNullable = normalizeNullable(column.nullable);
475
+ if (previousNullable !== currentNullable) {
476
+ operations.push({
477
+ kind: "column_nullability_changed",
478
+ tableName,
479
+ columnName: column.name,
480
+ from: previousNullable,
481
+ to: currentNullable
482
+ });
483
+ }
484
+ }
485
+ }
486
+ for (const tableName of commonTableNames) {
487
+ const newTable = newSchema.tables[tableName];
488
+ const oldTable = oldState.tables[tableName];
489
+ if (!newTable || !oldTable) {
490
+ continue;
491
+ }
492
+ for (const column of newTable.columns) {
493
+ const previousColumn = oldTable.columns[column.name];
494
+ if (!previousColumn) {
495
+ continue;
496
+ }
497
+ const previousDefault = normalizeDefault(previousColumn.default);
498
+ const currentDefault = normalizeDefault(column.default);
499
+ if (previousDefault !== currentDefault) {
500
+ operations.push({
501
+ kind: "column_default_changed",
502
+ tableName,
503
+ columnName: column.name,
504
+ fromDefault: previousDefault,
505
+ toDefault: currentDefault
506
+ });
507
+ }
508
+ }
509
+ }
510
+ for (const tableName of commonTableNames) {
511
+ const newTable = newSchema.tables[tableName];
512
+ const oldTable = oldState.tables[tableName];
513
+ if (!newTable || !oldTable) {
514
+ continue;
515
+ }
516
+ const oldColumnNames = getColumnNamesFromState(oldTable.columns);
517
+ for (const column of newTable.columns) {
518
+ if (!oldColumnNames.has(column.name)) {
519
+ operations.push({
520
+ kind: "add_column",
521
+ tableName,
522
+ column
523
+ });
524
+ }
525
+ }
526
+ }
527
+ for (const tableName of commonTableNames) {
528
+ const newTable = newSchema.tables[tableName];
529
+ const oldTable = oldState.tables[tableName];
530
+ if (!newTable || !oldTable) {
531
+ continue;
532
+ }
533
+ const previousPrimaryKey = resolveStatePrimaryKey(oldTable);
534
+ const currentPrimaryKey = resolveSchemaPrimaryKey(newTable);
535
+ if (currentPrimaryKey !== null && previousPrimaryKey !== currentPrimaryKey) {
536
+ operations.push({
537
+ kind: "add_primary_key_constraint",
538
+ tableName,
539
+ columnName: currentPrimaryKey
540
+ });
541
+ }
542
+ }
543
+ for (const tableName of commonTableNames) {
544
+ const newTable = newSchema.tables[tableName];
545
+ const oldTable = oldState.tables[tableName];
546
+ if (!newTable || !oldTable) {
547
+ continue;
548
+ }
549
+ const newColumnNames = getColumnNamesFromSchema(newTable.columns);
550
+ for (const columnName of Object.keys(oldTable.columns)) {
551
+ if (!newColumnNames.has(columnName)) {
552
+ operations.push({
553
+ kind: "drop_column",
554
+ tableName,
555
+ columnName
556
+ });
557
+ }
558
+ }
559
+ }
560
+ for (const tableName of sortedOldTableNames) {
561
+ if (!newTableNames.has(tableName)) {
562
+ operations.push({
563
+ kind: "drop_table",
564
+ tableName
565
+ });
566
+ }
567
+ }
568
+ return { operations };
569
+ }
570
+ var init_diff = __esm({
571
+ "node_modules/@xubylele/schema-forge-core/dist/core/diff.js"() {
572
+ "use strict";
573
+ init_normalize();
574
+ }
575
+ });
576
+
577
+ // node_modules/@xubylele/schema-forge-core/dist/core/validator.js
578
+ function isValidColumnType(type) {
579
+ const normalizedType = type.toLowerCase().trim().replace(/\s+/g, " ").replace(/\s*\(\s*/g, "(").replace(/\s*,\s*/g, ",").replace(/\s*\)\s*/g, ")");
580
+ if (VALID_BASE_COLUMN_TYPES.includes(normalizedType)) {
581
+ return true;
582
+ }
583
+ return /^varchar\(\d+\)$/.test(normalizedType) || /^numeric\(\d+,\d+\)$/.test(normalizedType);
584
+ }
585
+ function validateSchema(schema) {
586
+ validateDuplicateTables(schema);
587
+ for (const tableName in schema.tables) {
588
+ const table = schema.tables[tableName];
589
+ validateTableColumns(tableName, table, schema.tables);
590
+ }
591
+ }
592
+ function validateDuplicateTables(schema) {
593
+ const tableNames = Object.keys(schema.tables);
594
+ const seen = /* @__PURE__ */ new Set();
595
+ for (const tableName of tableNames) {
596
+ if (seen.has(tableName)) {
597
+ throw new Error(`Duplicate table: '${tableName}'`);
598
+ }
599
+ seen.add(tableName);
600
+ }
601
+ }
602
+ function validateTableColumns(tableName, table, allTables) {
603
+ const columnNames = /* @__PURE__ */ new Set();
604
+ const primaryKeyColumns = [];
605
+ for (const column of table.columns) {
606
+ if (columnNames.has(column.name)) {
607
+ throw new Error(`Table '${tableName}': duplicate column '${column.name}'`);
608
+ }
609
+ columnNames.add(column.name);
610
+ if (column.primaryKey) {
611
+ primaryKeyColumns.push(column.name);
612
+ }
613
+ if (!isValidColumnType(column.type)) {
614
+ throw new Error(`Table '${tableName}', column '${column.name}': type '${column.type}' is not valid. Supported types: ${VALID_BASE_COLUMN_TYPES.join(", ")}, varchar(n), numeric(p,s)`);
615
+ }
616
+ if (column.foreignKey) {
617
+ const fkTable = column.foreignKey.table;
618
+ const fkColumn = column.foreignKey.column;
619
+ if (!allTables[fkTable]) {
620
+ throw new Error(`Table '${tableName}', column '${column.name}': referenced table '${fkTable}' does not exist`);
621
+ }
622
+ const referencedTable = allTables[fkTable];
623
+ const columnExists = referencedTable.columns.some((col) => col.name === fkColumn);
624
+ if (!columnExists) {
625
+ throw new Error(`Table '${tableName}', column '${column.name}': table '${fkTable}' does not have column '${fkColumn}'`);
626
+ }
627
+ }
628
+ }
629
+ if (primaryKeyColumns.length > 1) {
630
+ throw new Error(`Table '${tableName}': can only have one primary key (found ${primaryKeyColumns.length})`);
631
+ }
632
+ const normalizedPrimaryKey = table.primaryKey ?? primaryKeyColumns[0] ?? null;
633
+ if (table.primaryKey && !columnNames.has(table.primaryKey)) {
634
+ throw new Error(`Table '${tableName}': primary key column '${table.primaryKey}' does not exist`);
635
+ }
636
+ if (table.primaryKey && primaryKeyColumns.length === 1 && primaryKeyColumns[0] !== table.primaryKey) {
637
+ throw new Error(`Table '${tableName}': column-level primary key '${primaryKeyColumns[0]}' does not match table primary key '${table.primaryKey}'`);
638
+ }
639
+ if (normalizedPrimaryKey) {
640
+ const pkMatches = table.columns.filter((column) => column.name === normalizedPrimaryKey);
641
+ if (pkMatches.length !== 1) {
642
+ throw new Error(`Table '${tableName}': primary key column '${normalizedPrimaryKey}' is invalid`);
643
+ }
644
+ }
645
+ }
646
+ var VALID_BASE_COLUMN_TYPES;
647
+ var init_validator = __esm({
648
+ "node_modules/@xubylele/schema-forge-core/dist/core/validator.js"() {
649
+ "use strict";
650
+ VALID_BASE_COLUMN_TYPES = [
651
+ "uuid",
652
+ "varchar",
653
+ "text",
654
+ "int",
655
+ "bigint",
656
+ "boolean",
657
+ "timestamptz",
658
+ "date"
659
+ ];
660
+ }
661
+ });
662
+
663
+ // node_modules/@xubylele/schema-forge-core/dist/core/validate.js
664
+ function normalizeColumnType2(type) {
665
+ return type.toLowerCase().trim().replace(/\s+/g, " ").replace(/\s*\(\s*/g, "(").replace(/\s*,\s*/g, ",").replace(/\s*\)\s*/g, ")");
666
+ }
667
+ function parseVarcharLength(type) {
668
+ const match = normalizeColumnType2(type).match(/^varchar\((\d+)\)$/);
669
+ return match ? Number(match[1]) : null;
670
+ }
671
+ function parseNumericType(type) {
672
+ const match = normalizeColumnType2(type).match(/^numeric\((\d+),(\d+)\)$/);
673
+ if (!match) {
674
+ return null;
675
+ }
676
+ return {
677
+ precision: Number(match[1]),
678
+ scale: Number(match[2])
679
+ };
680
+ }
681
+ function classifyTypeChange(from, to) {
682
+ const fromType = normalizeColumnType2(from);
683
+ const toType = normalizeColumnType2(to);
684
+ const uuidInvolved = fromType === "uuid" || toType === "uuid";
685
+ if (uuidInvolved && fromType !== toType) {
686
+ return {
687
+ severity: "error",
688
+ message: `Type changed from ${fromType} to ${toType} (likely incompatible cast)`
689
+ };
690
+ }
691
+ if (fromType === "int" && toType === "bigint") {
692
+ return {
693
+ severity: "warning",
694
+ message: "Type widened from int to bigint"
695
+ };
696
+ }
697
+ if (fromType === "bigint" && toType === "int") {
698
+ return {
699
+ severity: "error",
700
+ message: "Type narrowed from bigint to int (likely incompatible cast)"
701
+ };
702
+ }
703
+ if (fromType === "text" && parseVarcharLength(toType) !== null) {
704
+ return {
705
+ severity: "error",
706
+ message: `Type changed from text to ${toType} (may truncate existing values)`
707
+ };
708
+ }
709
+ if (parseVarcharLength(fromType) !== null && toType === "text") {
710
+ return {
711
+ severity: "warning",
712
+ message: "Type widened from varchar(n) to text"
713
+ };
714
+ }
715
+ const fromVarcharLength = parseVarcharLength(fromType);
716
+ const toVarcharLength = parseVarcharLength(toType);
717
+ if (fromVarcharLength !== null && toVarcharLength !== null) {
718
+ if (toVarcharLength >= fromVarcharLength) {
719
+ return {
720
+ severity: "warning",
721
+ message: `Type widened from varchar(${fromVarcharLength}) to varchar(${toVarcharLength})`
722
+ };
723
+ }
724
+ return {
725
+ severity: "error",
726
+ message: `Type narrowed from varchar(${fromVarcharLength}) to varchar(${toVarcharLength})`
727
+ };
728
+ }
729
+ const fromNumeric = parseNumericType(fromType);
730
+ const toNumeric = parseNumericType(toType);
731
+ if (fromNumeric && toNumeric && fromNumeric.scale === toNumeric.scale) {
732
+ if (toNumeric.precision >= fromNumeric.precision) {
733
+ return {
734
+ severity: "warning",
735
+ message: `Type widened from numeric(${fromNumeric.precision},${fromNumeric.scale}) to numeric(${toNumeric.precision},${toNumeric.scale})`
736
+ };
737
+ }
738
+ return {
739
+ severity: "error",
740
+ message: `Type narrowed from numeric(${fromNumeric.precision},${fromNumeric.scale}) to numeric(${toNumeric.precision},${toNumeric.scale})`
741
+ };
742
+ }
743
+ return {
744
+ severity: "warning",
745
+ message: `Type changed from ${fromType} to ${toType} (compatibility unknown)`
746
+ };
747
+ }
748
+ function validateSchemaChanges(previousState, currentSchema) {
749
+ const findings = [];
750
+ const diff = diffSchemas(previousState, currentSchema);
751
+ for (const operation of diff.operations) {
752
+ switch (operation.kind) {
753
+ case "drop_table":
754
+ findings.push({
755
+ severity: "error",
756
+ code: "DROP_TABLE",
757
+ table: operation.tableName,
758
+ message: "Table removed"
759
+ });
760
+ break;
761
+ case "drop_column":
762
+ findings.push({
763
+ severity: "error",
764
+ code: "DROP_COLUMN",
765
+ table: operation.tableName,
766
+ column: operation.columnName,
767
+ message: "Column removed"
768
+ });
769
+ break;
770
+ case "column_type_changed": {
771
+ const classification = classifyTypeChange(operation.fromType, operation.toType);
772
+ findings.push({
773
+ severity: classification.severity,
774
+ code: "ALTER_COLUMN_TYPE",
775
+ table: operation.tableName,
776
+ column: operation.columnName,
777
+ from: normalizeColumnType2(operation.fromType),
778
+ to: normalizeColumnType2(operation.toType),
779
+ message: classification.message
780
+ });
781
+ break;
782
+ }
783
+ case "column_nullability_changed":
784
+ if (operation.from && !operation.to) {
785
+ findings.push({
786
+ severity: "warning",
787
+ code: "SET_NOT_NULL",
788
+ table: operation.tableName,
789
+ column: operation.columnName,
790
+ message: "Column changed to NOT NULL (may fail if data contains NULLs)"
791
+ });
792
+ }
793
+ break;
794
+ default:
795
+ break;
796
+ }
797
+ }
798
+ return findings;
799
+ }
800
+ function toValidationReport(findings) {
801
+ const errors = findings.filter((finding) => finding.severity === "error");
802
+ const warnings = findings.filter((finding) => finding.severity === "warning");
803
+ return {
804
+ hasErrors: errors.length > 0,
805
+ hasWarnings: warnings.length > 0,
806
+ errors: errors.map(({ severity, ...finding }) => finding),
807
+ warnings: warnings.map(({ severity, ...finding }) => finding)
808
+ };
809
+ }
810
+ var init_validate = __esm({
811
+ "node_modules/@xubylele/schema-forge-core/dist/core/validate.js"() {
812
+ "use strict";
813
+ init_diff();
814
+ }
815
+ });
816
+
817
+ // node_modules/@xubylele/schema-forge-core/dist/core/fs.js
818
+ async function ensureDir2(dirPath) {
819
+ try {
820
+ await import_fs2.promises.mkdir(dirPath, { recursive: true });
821
+ } catch (error2) {
822
+ throw new Error(`Failed to create directory ${dirPath}: ${error2}`);
823
+ }
824
+ }
825
+ async function fileExists2(filePath) {
826
+ try {
827
+ await import_fs2.promises.access(filePath);
828
+ return true;
829
+ } catch {
830
+ return false;
831
+ }
832
+ }
833
+ async function readTextFile2(filePath) {
834
+ try {
835
+ return await import_fs2.promises.readFile(filePath, "utf-8");
836
+ } catch (error2) {
837
+ throw new Error(`Failed to read file ${filePath}: ${error2}`);
838
+ }
839
+ }
840
+ async function writeTextFile2(filePath, content) {
841
+ try {
842
+ const dir = import_path3.default.dirname(filePath);
843
+ await ensureDir2(dir);
844
+ await import_fs2.promises.writeFile(filePath, content, "utf-8");
845
+ } catch (error2) {
846
+ throw new Error(`Failed to write file ${filePath}: ${error2}`);
847
+ }
848
+ }
849
+ async function readJsonFile2(filePath, fallback) {
850
+ try {
851
+ const exists = await fileExists2(filePath);
852
+ if (!exists) {
853
+ return fallback;
854
+ }
855
+ const content = await readTextFile2(filePath);
856
+ return JSON.parse(content);
857
+ } catch (error2) {
858
+ throw new Error(`Failed to read JSON file ${filePath}: ${error2}`);
859
+ }
860
+ }
861
+ async function writeJsonFile2(filePath, data) {
862
+ try {
863
+ const content = JSON.stringify(data, null, 2);
864
+ await writeTextFile2(filePath, content);
865
+ } catch (error2) {
866
+ throw new Error(`Failed to write JSON file ${filePath}: ${error2}`);
867
+ }
868
+ }
869
+ async function findFiles(dirPath, pattern) {
870
+ const results = [];
871
+ try {
872
+ const items = await import_fs2.promises.readdir(dirPath, { withFileTypes: true });
873
+ for (const item of items) {
874
+ const fullPath = import_path3.default.join(dirPath, item.name);
875
+ if (item.isDirectory()) {
876
+ const subResults = await findFiles(fullPath, pattern);
877
+ results.push(...subResults);
878
+ } else if (item.isFile() && pattern.test(item.name)) {
879
+ results.push(fullPath);
880
+ }
881
+ }
882
+ } catch (error2) {
883
+ throw new Error(`Failed to find files in ${dirPath}: ${error2}`);
884
+ }
885
+ return results;
886
+ }
887
+ var import_fs2, import_path3;
888
+ var init_fs = __esm({
889
+ "node_modules/@xubylele/schema-forge-core/dist/core/fs.js"() {
890
+ "use strict";
891
+ import_fs2 = require("fs");
892
+ import_path3 = __toESM(require("path"), 1);
893
+ }
894
+ });
895
+
896
+ // node_modules/@xubylele/schema-forge-core/dist/core/state-manager.js
897
+ async function schemaToState(schema) {
898
+ const tables = {};
899
+ for (const [tableName, table] of Object.entries(schema.tables)) {
900
+ const columns = {};
901
+ const primaryKeyColumn = table.primaryKey ?? table.columns.find((column) => column.primaryKey)?.name ?? null;
902
+ for (const column of table.columns) {
903
+ columns[column.name] = {
904
+ type: column.type,
905
+ ...column.primaryKey !== void 0 && { primaryKey: column.primaryKey },
906
+ ...column.unique !== void 0 && { unique: column.unique },
907
+ nullable: column.nullable ?? true,
908
+ ...column.default !== void 0 && { default: column.default },
909
+ ...column.foreignKey !== void 0 && { foreignKey: column.foreignKey }
910
+ };
911
+ }
912
+ tables[tableName] = {
913
+ columns,
914
+ ...primaryKeyColumn !== null && { primaryKey: primaryKeyColumn }
915
+ };
916
+ }
917
+ return {
918
+ version: 1,
919
+ tables
920
+ };
921
+ }
922
+ async function loadState(statePath) {
923
+ return await readJsonFile2(statePath, { version: 1, tables: {} });
924
+ }
925
+ async function saveState(statePath, state) {
926
+ const dirPath = import_path4.default.dirname(statePath);
927
+ await ensureDir2(dirPath);
928
+ await writeJsonFile2(statePath, state);
929
+ }
930
+ var import_path4;
931
+ var init_state_manager = __esm({
932
+ "node_modules/@xubylele/schema-forge-core/dist/core/state-manager.js"() {
933
+ "use strict";
934
+ import_path4 = __toESM(require("path"), 1);
935
+ init_fs();
936
+ }
937
+ });
938
+
939
+ // node_modules/@xubylele/schema-forge-core/dist/generator/sql-generator.js
940
+ function generateSql(diff, provider, sqlConfig) {
941
+ const statements = [];
942
+ for (const operation of diff.operations) {
943
+ const sql = generateOperation(operation, provider, sqlConfig);
944
+ if (sql) {
945
+ statements.push(sql);
946
+ }
947
+ }
948
+ return statements.join("\n\n");
949
+ }
950
+ function generateOperation(operation, provider, sqlConfig) {
951
+ switch (operation.kind) {
952
+ case "create_table":
953
+ return generateCreateTable(operation.table, provider, sqlConfig);
954
+ case "drop_table":
955
+ return generateDropTable(operation.tableName);
956
+ case "column_type_changed":
957
+ return generateAlterColumnType(operation.tableName, operation.columnName, operation.toType);
958
+ case "column_nullability_changed":
959
+ return generateAlterColumnNullability(operation.tableName, operation.columnName, operation.to);
960
+ case "add_column":
961
+ return generateAddColumn(operation.tableName, operation.column, provider, sqlConfig);
962
+ case "column_default_changed":
963
+ return generateAlterColumnDefault(operation.tableName, operation.columnName, operation.toDefault);
964
+ case "drop_column":
965
+ return generateDropColumn(operation.tableName, operation.columnName);
966
+ case "column_unique_changed":
967
+ return operation.to ? generateAddUniqueConstraint(operation.tableName, operation.columnName) : generateDropUniqueConstraint(operation.tableName, operation.columnName);
968
+ case "drop_primary_key_constraint":
969
+ return generateDropPrimaryKeyConstraint(operation.tableName);
970
+ case "add_primary_key_constraint":
971
+ return generateAddPrimaryKeyConstraint(operation.tableName, operation.columnName);
972
+ }
973
+ }
974
+ function generateCreateTable(table, provider, sqlConfig) {
975
+ const columnDefs = table.columns.map((col) => generateColumnDefinition(col, provider, sqlConfig));
976
+ const lines = ["CREATE TABLE " + table.name + " ("];
977
+ columnDefs.forEach((colDef, index) => {
978
+ const isLast = index === columnDefs.length - 1;
979
+ lines.push(" " + colDef + (isLast ? "" : ","));
980
+ });
981
+ lines.push(");");
982
+ return lines.join("\n");
983
+ }
984
+ function generateColumnDefinition(column, provider, sqlConfig) {
985
+ const parts = [column.name, column.type];
986
+ if (column.foreignKey) {
987
+ parts.push(`references ${column.foreignKey.table}(${column.foreignKey.column})`);
988
+ }
989
+ if (column.primaryKey) {
990
+ parts.push("primary key");
991
+ }
992
+ if (column.unique) {
993
+ parts.push("unique");
994
+ }
995
+ if (column.nullable === false) {
996
+ parts.push("not null");
997
+ }
998
+ if (column.default !== void 0) {
999
+ parts.push("default " + column.default);
1000
+ } else if (column.type === "uuid" && column.primaryKey && provider === "supabase") {
1001
+ parts.push("default gen_random_uuid()");
1002
+ }
1003
+ return parts.join(" ");
1004
+ }
1005
+ function generateDropTable(tableName) {
1006
+ return `DROP TABLE ${tableName};`;
1007
+ }
1008
+ function generateAddColumn(tableName, column, provider, sqlConfig) {
1009
+ const colDef = generateColumnDefinition(column, provider, sqlConfig);
1010
+ return `ALTER TABLE ${tableName} ADD COLUMN ${colDef};`;
1011
+ }
1012
+ function generateDropColumn(tableName, columnName) {
1013
+ return `ALTER TABLE ${tableName} DROP COLUMN ${columnName};`;
1014
+ }
1015
+ function generateAlterColumnType(tableName, columnName, newType) {
1016
+ return `ALTER TABLE ${tableName} ALTER COLUMN ${columnName} TYPE ${newType} USING ${columnName}::${newType};`;
1017
+ }
1018
+ function generateAddUniqueConstraint(tableName, columnName) {
1019
+ const deterministicConstraintName = uqName(tableName, columnName);
1020
+ return `ALTER TABLE ${tableName} ADD CONSTRAINT ${deterministicConstraintName} UNIQUE (${columnName});`;
1021
+ }
1022
+ function generateDropUniqueConstraint(tableName, columnName) {
1023
+ const deterministicConstraintName = uqName(tableName, columnName);
1024
+ const fallbackConstraintName = legacyUqName(tableName, columnName);
1025
+ return generateDropConstraintStatements(tableName, [deterministicConstraintName, fallbackConstraintName]);
1026
+ }
1027
+ function generateDropPrimaryKeyConstraint(tableName) {
1028
+ const deterministicConstraintName = pkName(tableName);
1029
+ const fallbackConstraintName = legacyPkName(tableName);
1030
+ return generateDropConstraintStatements(tableName, [deterministicConstraintName, fallbackConstraintName]);
1031
+ }
1032
+ function generateAddPrimaryKeyConstraint(tableName, columnName) {
1033
+ const deterministicConstraintName = pkName(tableName);
1034
+ return `ALTER TABLE ${tableName} ADD CONSTRAINT ${deterministicConstraintName} PRIMARY KEY (${columnName});`;
1035
+ }
1036
+ function generateDropConstraintStatements(tableName, constraintNames) {
1037
+ const uniqueConstraintNames = Array.from(new Set(constraintNames));
1038
+ return uniqueConstraintNames.map((constraintName) => `ALTER TABLE ${tableName} DROP CONSTRAINT IF EXISTS ${constraintName};`).join("\n");
1039
+ }
1040
+ function generateAlterColumnDefault(tableName, columnName, newDefault) {
1041
+ if (newDefault === null) {
1042
+ return `ALTER TABLE ${tableName} ALTER COLUMN ${columnName} DROP DEFAULT;`;
1043
+ }
1044
+ return `ALTER TABLE ${tableName} ALTER COLUMN ${columnName} SET DEFAULT ${newDefault};`;
1045
+ }
1046
+ function generateAlterColumnNullability(tableName, columnName, toNullable) {
1047
+ if (toNullable) {
1048
+ return `ALTER TABLE ${tableName} ALTER COLUMN ${columnName} DROP NOT NULL;`;
1049
+ }
1050
+ return `ALTER TABLE ${tableName} ALTER COLUMN ${columnName} SET NOT NULL;`;
1051
+ }
1052
+ var init_sql_generator = __esm({
1053
+ "node_modules/@xubylele/schema-forge-core/dist/generator/sql-generator.js"() {
1054
+ "use strict";
1055
+ init_normalize();
1056
+ }
1057
+ });
1058
+
1059
+ // node_modules/@xubylele/schema-forge-core/dist/core/sql/split-statements.js
1060
+ function splitSqlStatements(sql) {
1061
+ const statements = [];
1062
+ let current = "";
1063
+ let inSingleQuote = false;
1064
+ let inDoubleQuote = false;
1065
+ let inLineComment = false;
1066
+ let inBlockComment = false;
1067
+ let dollarTag = null;
1068
+ let index = 0;
1069
+ while (index < sql.length) {
1070
+ const char = sql[index];
1071
+ const next = index + 1 < sql.length ? sql[index + 1] : "";
1072
+ if (inLineComment) {
1073
+ current += char;
1074
+ if (char === "\n") {
1075
+ inLineComment = false;
1076
+ }
1077
+ index++;
1078
+ continue;
1079
+ }
1080
+ if (inBlockComment) {
1081
+ current += char;
1082
+ if (char === "*" && next === "/") {
1083
+ current += next;
1084
+ inBlockComment = false;
1085
+ index += 2;
1086
+ continue;
1087
+ }
1088
+ index++;
1089
+ continue;
1090
+ }
1091
+ if (!inSingleQuote && !inDoubleQuote && dollarTag === null) {
1092
+ if (char === "-" && next === "-") {
1093
+ current += char + next;
1094
+ inLineComment = true;
1095
+ index += 2;
1096
+ continue;
1097
+ }
1098
+ if (char === "/" && next === "*") {
1099
+ current += char + next;
1100
+ inBlockComment = true;
1101
+ index += 2;
1102
+ continue;
1103
+ }
1104
+ }
1105
+ if (!inDoubleQuote && dollarTag === null && char === "'") {
1106
+ current += char;
1107
+ if (inSingleQuote && next === "'") {
1108
+ current += next;
1109
+ index += 2;
1110
+ continue;
1111
+ }
1112
+ inSingleQuote = !inSingleQuote;
1113
+ index++;
1114
+ continue;
1115
+ }
1116
+ if (!inSingleQuote && dollarTag === null && char === '"') {
1117
+ current += char;
1118
+ if (inDoubleQuote && next === '"') {
1119
+ current += next;
1120
+ index += 2;
1121
+ continue;
1122
+ }
1123
+ inDoubleQuote = !inDoubleQuote;
1124
+ index++;
1125
+ continue;
1126
+ }
1127
+ if (!inSingleQuote && !inDoubleQuote) {
1128
+ if (dollarTag === null && char === "$") {
1129
+ const remainder = sql.slice(index);
1130
+ const match = remainder.match(/^\$[a-zA-Z_][a-zA-Z0-9_]*\$|^\$\$/);
1131
+ if (match) {
1132
+ dollarTag = match[0];
1133
+ current += match[0];
1134
+ index += match[0].length;
1135
+ continue;
1136
+ }
1137
+ }
1138
+ if (dollarTag !== null && sql.startsWith(dollarTag, index)) {
1139
+ current += dollarTag;
1140
+ index += dollarTag.length;
1141
+ dollarTag = null;
1142
+ continue;
1143
+ }
1144
+ }
1145
+ if (!inSingleQuote && !inDoubleQuote && dollarTag === null && char === ";") {
1146
+ if (current.trim().length > 0) {
1147
+ statements.push(current.trim());
1148
+ }
1149
+ current = "";
1150
+ index++;
1151
+ continue;
1152
+ }
1153
+ current += char;
1154
+ index++;
1155
+ }
1156
+ if (current.trim().length > 0) {
1157
+ statements.push(current.trim());
1158
+ }
1159
+ return statements;
1160
+ }
1161
+ var init_split_statements = __esm({
1162
+ "node_modules/@xubylele/schema-forge-core/dist/core/sql/split-statements.js"() {
1163
+ "use strict";
1164
+ }
1165
+ });
1166
+
1167
+ // node_modules/@xubylele/schema-forge-core/dist/core/sql/parse-migration.js
1168
+ function normalizeSqlType(type) {
1169
+ return type.trim().toLowerCase().replace(/\s+/g, " ").replace(/\s*\(\s*/g, "(").replace(/\s*,\s*/g, ",").replace(/\s*\)\s*/g, ")");
1170
+ }
1171
+ function unquoteIdentifier(value) {
1172
+ const trimmed = value.trim();
1173
+ if (trimmed.startsWith('"') && trimmed.endsWith('"') && trimmed.length >= 2) {
1174
+ return trimmed.slice(1, -1).replace(/""/g, '"');
1175
+ }
1176
+ return trimmed;
1177
+ }
1178
+ function normalizeIdentifier(identifier) {
1179
+ const parts = identifier.trim().split(".").map((part) => unquoteIdentifier(part)).filter((part) => part.length > 0);
1180
+ const leaf = parts.length > 0 ? parts[parts.length - 1] : identifier.trim();
1181
+ return leaf.toLowerCase();
1182
+ }
1183
+ function removeSqlComments(statement) {
1184
+ let result = "";
1185
+ let inSingleQuote = false;
1186
+ let inDoubleQuote = false;
1187
+ let inLineComment = false;
1188
+ let inBlockComment = false;
1189
+ for (let index = 0; index < statement.length; index++) {
1190
+ const char = statement[index];
1191
+ const next = index + 1 < statement.length ? statement[index + 1] : "";
1192
+ if (inLineComment) {
1193
+ if (char === "\n") {
1194
+ inLineComment = false;
1195
+ result += char;
1196
+ }
1197
+ continue;
1198
+ }
1199
+ if (inBlockComment) {
1200
+ if (char === "*" && next === "/") {
1201
+ inBlockComment = false;
1202
+ index++;
1203
+ }
1204
+ continue;
1205
+ }
1206
+ if (!inSingleQuote && !inDoubleQuote) {
1207
+ if (char === "-" && next === "-") {
1208
+ inLineComment = true;
1209
+ index++;
1210
+ continue;
1211
+ }
1212
+ if (char === "/" && next === "*") {
1213
+ inBlockComment = true;
1214
+ index++;
1215
+ continue;
1216
+ }
1217
+ }
1218
+ if (char === "'" && !inDoubleQuote) {
1219
+ if (inSingleQuote && next === "'") {
1220
+ result += "''";
1221
+ index++;
1222
+ continue;
1223
+ }
1224
+ inSingleQuote = !inSingleQuote;
1225
+ result += char;
1226
+ continue;
1227
+ }
1228
+ if (char === '"' && !inSingleQuote) {
1229
+ if (inDoubleQuote && next === '"') {
1230
+ result += '""';
1231
+ index++;
1232
+ continue;
1233
+ }
1234
+ inDoubleQuote = !inDoubleQuote;
1235
+ result += char;
1236
+ continue;
1237
+ }
1238
+ result += char;
1239
+ }
1240
+ return result.trim();
1241
+ }
1242
+ function splitTopLevelComma(input) {
1243
+ const parts = [];
1244
+ let current = "";
1245
+ let depth = 0;
1246
+ let inSingleQuote = false;
1247
+ let inDoubleQuote = false;
1248
+ for (let index = 0; index < input.length; index++) {
1249
+ const char = input[index];
1250
+ const next = index + 1 < input.length ? input[index + 1] : "";
1251
+ if (char === "'" && !inDoubleQuote) {
1252
+ current += char;
1253
+ if (inSingleQuote && next === "'") {
1254
+ current += next;
1255
+ index++;
1256
+ continue;
1257
+ }
1258
+ inSingleQuote = !inSingleQuote;
1259
+ continue;
1260
+ }
1261
+ if (char === '"' && !inSingleQuote) {
1262
+ current += char;
1263
+ if (inDoubleQuote && next === '"') {
1264
+ current += next;
1265
+ index++;
1266
+ continue;
1267
+ }
1268
+ inDoubleQuote = !inDoubleQuote;
1269
+ continue;
1270
+ }
1271
+ if (!inSingleQuote && !inDoubleQuote) {
1272
+ if (char === "(") {
1273
+ depth++;
1274
+ } else if (char === ")") {
1275
+ depth = Math.max(0, depth - 1);
1276
+ } else if (char === "," && depth === 0) {
1277
+ const segment = current.trim();
1278
+ if (segment.length > 0) {
1279
+ parts.push(segment);
1280
+ }
1281
+ current = "";
1282
+ continue;
1283
+ }
1284
+ }
1285
+ current += char;
1286
+ }
1287
+ const tail = current.trim();
1288
+ if (tail.length > 0) {
1289
+ parts.push(tail);
1290
+ }
1291
+ return parts;
1292
+ }
1293
+ function tokenize(segment) {
1294
+ const tokens = [];
1295
+ let current = "";
1296
+ let depth = 0;
1297
+ let inSingleQuote = false;
1298
+ let inDoubleQuote = false;
1299
+ for (let index = 0; index < segment.length; index++) {
1300
+ const char = segment[index];
1301
+ const next = index + 1 < segment.length ? segment[index + 1] : "";
1302
+ if (char === "'" && !inDoubleQuote) {
1303
+ current += char;
1304
+ if (inSingleQuote && next === "'") {
1305
+ current += next;
1306
+ index++;
1307
+ continue;
1308
+ }
1309
+ inSingleQuote = !inSingleQuote;
1310
+ continue;
1311
+ }
1312
+ if (char === '"' && !inSingleQuote) {
1313
+ current += char;
1314
+ if (inDoubleQuote && next === '"') {
1315
+ current += next;
1316
+ index++;
1317
+ continue;
1318
+ }
1319
+ inDoubleQuote = !inDoubleQuote;
1320
+ continue;
1321
+ }
1322
+ if (!inSingleQuote && !inDoubleQuote) {
1323
+ if (char === "(") {
1324
+ depth++;
1325
+ } else if (char === ")") {
1326
+ depth = Math.max(0, depth - 1);
1327
+ }
1328
+ if (/\s/.test(char) && depth === 0) {
1329
+ if (current.length > 0) {
1330
+ tokens.push(current);
1331
+ current = "";
1332
+ }
1333
+ continue;
1334
+ }
1335
+ }
1336
+ current += char;
1337
+ }
1338
+ if (current.length > 0) {
1339
+ tokens.push(current);
1340
+ }
1341
+ return tokens;
1342
+ }
1343
+ function parseColumnDefinition(segment) {
1344
+ const tokens = tokenize(segment);
1345
+ if (tokens.length < 2) {
1346
+ return null;
1347
+ }
1348
+ const name = normalizeIdentifier(tokens[0]);
1349
+ let cursor = 1;
1350
+ const typeTokens = [];
1351
+ while (cursor < tokens.length) {
1352
+ const lower = tokens[cursor].toLowerCase();
1353
+ if (COLUMN_CONSTRAINT_KEYWORDS.has(lower)) {
1354
+ break;
1355
+ }
1356
+ typeTokens.push(tokens[cursor]);
1357
+ cursor++;
1358
+ }
1359
+ if (typeTokens.length === 0) {
1360
+ return null;
1361
+ }
1362
+ const parsed = {
1363
+ name,
1364
+ type: normalizeSqlType(typeTokens.join(" ")),
1365
+ nullable: true
1366
+ };
1367
+ while (cursor < tokens.length) {
1368
+ const lower = tokens[cursor].toLowerCase();
1369
+ if (lower === "primary" && tokens[cursor + 1]?.toLowerCase() === "key") {
1370
+ parsed.primaryKey = true;
1371
+ parsed.nullable = false;
1372
+ cursor += 2;
1373
+ continue;
1374
+ }
1375
+ if (lower === "unique") {
1376
+ parsed.unique = true;
1377
+ cursor++;
1378
+ continue;
1379
+ }
1380
+ if (lower === "not" && tokens[cursor + 1]?.toLowerCase() === "null") {
1381
+ parsed.nullable = false;
1382
+ cursor += 2;
1383
+ continue;
1384
+ }
1385
+ if (lower === "null") {
1386
+ parsed.nullable = true;
1387
+ cursor++;
1388
+ continue;
1389
+ }
1390
+ if (lower === "default") {
1391
+ cursor++;
1392
+ const defaultTokens = [];
1393
+ while (cursor < tokens.length) {
1394
+ const probe = tokens[cursor].toLowerCase();
1395
+ if (probe === "constraint" || probe === "references" || probe === "check" || probe === "not" && tokens[cursor + 1]?.toLowerCase() === "null" || probe === "null" || probe === "unique" || probe === "primary" && tokens[cursor + 1]?.toLowerCase() === "key") {
1396
+ break;
1397
+ }
1398
+ defaultTokens.push(tokens[cursor]);
1399
+ cursor++;
1400
+ }
1401
+ parsed.default = normalizeDefault(defaultTokens.join(" "));
1402
+ continue;
1403
+ }
1404
+ cursor++;
1405
+ }
1406
+ return parsed;
1407
+ }
1408
+ function parseCreateTableConstraint(segment) {
1409
+ const normalized = segment.trim().replace(/\s+/g, " ");
1410
+ const constraintMatch = normalized.match(/^constraint\s+([^\s]+)\s+(primary\s+key|unique)\s*\((.+)\)$/i);
1411
+ if (constraintMatch) {
1412
+ const [, rawName, kind, rawColumns] = constraintMatch;
1413
+ const columns = splitTopLevelComma(rawColumns).map((item) => normalizeIdentifier(item));
1414
+ if (kind.toLowerCase().includes("primary")) {
1415
+ return { type: "PRIMARY_KEY", name: normalizeIdentifier(rawName), columns };
1416
+ }
1417
+ return { type: "UNIQUE", name: normalizeIdentifier(rawName), columns };
1418
+ }
1419
+ const barePk = normalized.match(/^primary\s+key\s*\((.+)\)$/i);
1420
+ if (barePk) {
1421
+ const columns = splitTopLevelComma(barePk[1]).map((item) => normalizeIdentifier(item));
1422
+ return { type: "PRIMARY_KEY", columns };
1423
+ }
1424
+ const bareUnique = normalized.match(/^unique\s*\((.+)\)$/i);
1425
+ if (bareUnique) {
1426
+ const columns = splitTopLevelComma(bareUnique[1]).map((item) => normalizeIdentifier(item));
1427
+ return { type: "UNIQUE", columns };
1428
+ }
1429
+ return null;
1430
+ }
1431
+ function parseAlterTablePrefix(stmt) {
1432
+ const match = stmt.match(/^alter\s+table\s+(?:if\s+exists\s+)?(?:only\s+)?(.+)$/i);
1433
+ if (!match) {
1434
+ return null;
1435
+ }
1436
+ const remainder = match[1].trim();
1437
+ const tokens = tokenize(remainder);
1438
+ if (tokens.length < 2) {
1439
+ return null;
1440
+ }
1441
+ const tableToken = tokens[0];
1442
+ const table = normalizeIdentifier(tableToken);
1443
+ const rest = remainder.slice(tableToken.length).trim();
1444
+ return { table, rest };
1445
+ }
1446
+ function parseCreateTable(stmt) {
1447
+ const match = stmt.match(/^create\s+table\s+(?:if\s+not\s+exists\s+)?(.+?)\s*\((.*)\)$/is);
1448
+ if (!match) {
1449
+ return null;
1450
+ }
1451
+ const table = normalizeIdentifier(match[1]);
1452
+ const body = match[2];
1453
+ const segments = splitTopLevelComma(body);
1454
+ const columns = [];
1455
+ const constraints = [];
1456
+ for (const segment of segments) {
1457
+ const constraint = parseCreateTableConstraint(segment);
1458
+ if (constraint) {
1459
+ constraints.push(constraint);
1460
+ continue;
1461
+ }
1462
+ const column = parseColumnDefinition(segment);
1463
+ if (column) {
1464
+ columns.push(column);
1465
+ }
1466
+ }
1467
+ return {
1468
+ kind: "CREATE_TABLE",
1469
+ table,
1470
+ columns,
1471
+ constraints
1472
+ };
1473
+ }
1474
+ function parseAlterTableAddColumn(stmt) {
1475
+ const prefix = parseAlterTablePrefix(stmt);
1476
+ if (!prefix) {
1477
+ return null;
1478
+ }
1479
+ const match = prefix.rest.match(/^add\s+column\s+(?:if\s+not\s+exists\s+)?(.+)$/i);
1480
+ if (!match) {
1481
+ return null;
1482
+ }
1483
+ const column = parseColumnDefinition(match[1]);
1484
+ if (!column) {
1485
+ return null;
1486
+ }
1487
+ return { kind: "ADD_COLUMN", table: prefix.table, column };
1488
+ }
1489
+ function parseAlterColumnType(stmt) {
1490
+ const prefix = parseAlterTablePrefix(stmt);
1491
+ if (!prefix) {
1492
+ return null;
1493
+ }
1494
+ const match = prefix.rest.match(/^alter\s+column\s+([^\s]+)\s+type\s+(.+)$/i);
1495
+ if (!match) {
1496
+ return null;
1497
+ }
1498
+ const column = normalizeIdentifier(match[1]);
1499
+ const toType = normalizeSqlType(match[2].replace(/\s+using\s+[\s\S]*$/i, "").trim());
1500
+ return {
1501
+ kind: "ALTER_COLUMN_TYPE",
1502
+ table: prefix.table,
1503
+ column,
1504
+ toType
1505
+ };
1506
+ }
1507
+ function parseSetDropNotNull(stmt) {
1508
+ const prefix = parseAlterTablePrefix(stmt);
1509
+ if (!prefix) {
1510
+ return null;
1511
+ }
1512
+ const setMatch = prefix.rest.match(/^alter\s+column\s+([^\s]+)\s+set\s+not\s+null$/i);
1513
+ if (setMatch) {
1514
+ return {
1515
+ kind: "SET_NOT_NULL",
1516
+ table: prefix.table,
1517
+ column: normalizeIdentifier(setMatch[1])
1518
+ };
1519
+ }
1520
+ const dropMatch = prefix.rest.match(/^alter\s+column\s+([^\s]+)\s+drop\s+not\s+null$/i);
1521
+ if (dropMatch) {
1522
+ return {
1523
+ kind: "DROP_NOT_NULL",
1524
+ table: prefix.table,
1525
+ column: normalizeIdentifier(dropMatch[1])
1526
+ };
1527
+ }
1528
+ return null;
1529
+ }
1530
+ function parseSetDropDefault(stmt) {
1531
+ const prefix = parseAlterTablePrefix(stmt);
1532
+ if (!prefix) {
1533
+ return null;
1534
+ }
1535
+ const setMatch = prefix.rest.match(/^alter\s+column\s+([^\s]+)\s+set\s+default\s+(.+)$/i);
1536
+ if (setMatch) {
1537
+ return {
1538
+ kind: "SET_DEFAULT",
1539
+ table: prefix.table,
1540
+ column: normalizeIdentifier(setMatch[1]),
1541
+ expr: normalizeDefault(setMatch[2].trim()) ?? setMatch[2].trim()
1542
+ };
1543
+ }
1544
+ const dropMatch = prefix.rest.match(/^alter\s+column\s+([^\s]+)\s+drop\s+default$/i);
1545
+ if (dropMatch) {
1546
+ return {
1547
+ kind: "DROP_DEFAULT",
1548
+ table: prefix.table,
1549
+ column: normalizeIdentifier(dropMatch[1])
1550
+ };
1551
+ }
1552
+ return null;
1553
+ }
1554
+ function parseAddDropConstraint(stmt) {
1555
+ const prefix = parseAlterTablePrefix(stmt);
1556
+ if (!prefix) {
1557
+ return null;
1558
+ }
1559
+ const addMatch = prefix.rest.match(/^add\s+constraint\s+([^\s]+)\s+(primary\s+key|unique)\s*\((.+)\)$/i);
1560
+ if (addMatch) {
1561
+ const [, rawName, kind, rawColumns] = addMatch;
1562
+ const columns = splitTopLevelComma(rawColumns).map((item) => normalizeIdentifier(item));
1563
+ const constraint = kind.toLowerCase().includes("primary") ? { type: "PRIMARY_KEY", name: normalizeIdentifier(rawName), columns } : { type: "UNIQUE", name: normalizeIdentifier(rawName), columns };
1564
+ return {
1565
+ kind: "ADD_CONSTRAINT",
1566
+ table: prefix.table,
1567
+ constraint
1568
+ };
1569
+ }
1570
+ const dropMatch = prefix.rest.match(/^drop\s+constraint\s+(?:if\s+exists\s+)?([^\s]+)(?:\s+cascade)?$/i);
1571
+ if (dropMatch) {
1572
+ return {
1573
+ kind: "DROP_CONSTRAINT",
1574
+ table: prefix.table,
1575
+ name: normalizeIdentifier(dropMatch[1])
1576
+ };
1577
+ }
1578
+ return null;
1579
+ }
1580
+ function parseDropColumn(stmt) {
1581
+ const prefix = parseAlterTablePrefix(stmt);
1582
+ if (!prefix) {
1583
+ return null;
1584
+ }
1585
+ const match = prefix.rest.match(/^drop\s+column\s+(?:if\s+exists\s+)?([^\s]+)(?:\s+cascade)?$/i);
1586
+ if (!match) {
1587
+ return null;
1588
+ }
1589
+ return {
1590
+ kind: "DROP_COLUMN",
1591
+ table: prefix.table,
1592
+ column: normalizeIdentifier(match[1])
1593
+ };
1594
+ }
1595
+ function parseDropTable(stmt) {
1596
+ const match = stmt.match(/^drop\s+table\s+(?:if\s+exists\s+)?([^\s]+)(?:\s+cascade)?$/i);
1597
+ if (!match) {
1598
+ return null;
1599
+ }
1600
+ return {
1601
+ kind: "DROP_TABLE",
1602
+ table: normalizeIdentifier(match[1])
1603
+ };
1604
+ }
1605
+ function parseMigrationSql(sql) {
1606
+ const statements = splitSqlStatements(sql);
1607
+ const ops = [];
1608
+ const warnings = [];
1609
+ for (const raw of statements) {
1610
+ const stmt = removeSqlComments(raw).trim();
1611
+ if (!stmt) {
1612
+ continue;
1613
+ }
1614
+ let parsed = null;
1615
+ for (const parseFn of PARSERS) {
1616
+ parsed = parseFn(stmt);
1617
+ if (parsed) {
1618
+ break;
1619
+ }
1620
+ }
1621
+ if (parsed) {
1622
+ ops.push(parsed);
1623
+ } else {
1624
+ warnings.push({
1625
+ statement: stmt,
1626
+ reason: "Unsupported or unrecognized statement"
1627
+ });
1628
+ }
1629
+ }
1630
+ return { ops, warnings };
1631
+ }
1632
+ var COLUMN_CONSTRAINT_KEYWORDS, PARSERS;
1633
+ var init_parse_migration = __esm({
1634
+ "node_modules/@xubylele/schema-forge-core/dist/core/sql/parse-migration.js"() {
1635
+ "use strict";
1636
+ init_normalize();
1637
+ init_split_statements();
1638
+ COLUMN_CONSTRAINT_KEYWORDS = /* @__PURE__ */ new Set([
1639
+ "primary",
1640
+ "unique",
1641
+ "not",
1642
+ "null",
1643
+ "default",
1644
+ "constraint",
1645
+ "references",
1646
+ "check"
1647
+ ]);
1648
+ PARSERS = [
1649
+ parseCreateTable,
1650
+ parseAlterTableAddColumn,
1651
+ parseAlterColumnType,
1652
+ parseSetDropNotNull,
1653
+ parseSetDropDefault,
1654
+ parseAddDropConstraint,
1655
+ parseDropColumn,
1656
+ parseDropTable
1657
+ ];
1658
+ }
1659
+ });
1660
+
1661
+ // node_modules/@xubylele/schema-forge-core/dist/core/sql/apply-ops.js
1662
+ function toSchemaColumn(column) {
1663
+ return {
1664
+ name: column.name,
1665
+ type: column.type,
1666
+ nullable: column.nullable,
1667
+ ...column.default !== void 0 ? { default: column.default } : {},
1668
+ ...column.unique !== void 0 ? { unique: column.unique } : {},
1669
+ ...column.primaryKey !== void 0 ? { primaryKey: column.primaryKey } : {}
1670
+ };
1671
+ }
1672
+ function applySingleColumnConstraint(table, constraint) {
1673
+ if (constraint.columns.length !== 1) {
1674
+ return false;
1675
+ }
1676
+ const targetColumn = table.columns.find((column) => column.name === constraint.columns[0]);
1677
+ if (!targetColumn) {
1678
+ return false;
1679
+ }
1680
+ if (constraint.type === "PRIMARY_KEY") {
1681
+ table.primaryKey = targetColumn.name;
1682
+ targetColumn.primaryKey = true;
1683
+ targetColumn.nullable = false;
1684
+ return true;
1685
+ }
1686
+ targetColumn.unique = true;
1687
+ return true;
1688
+ }
1689
+ function clearConstraintByName(table, name) {
1690
+ if (name.endsWith("_pkey") || name.startsWith("pk_")) {
1691
+ if (table.primaryKey) {
1692
+ const pkColumn = table.columns.find((column) => column.name === table.primaryKey);
1693
+ if (pkColumn) {
1694
+ pkColumn.primaryKey = false;
1695
+ }
1696
+ table.primaryKey = null;
1697
+ }
1698
+ return;
1699
+ }
1700
+ if (name.endsWith("_key") || name.startsWith("uq_")) {
1701
+ for (const column of table.columns) {
1702
+ if (column.unique) {
1703
+ column.unique = false;
1704
+ }
1705
+ }
1706
+ }
1707
+ }
1708
+ function getOrCreateTable(tables, name) {
1709
+ if (!tables[name]) {
1710
+ tables[name] = { name, columns: [] };
1711
+ }
1712
+ return tables[name];
1713
+ }
1714
+ function applySqlOps(ops) {
1715
+ const tables = {};
1716
+ const warnings = [];
1717
+ for (const op of ops) {
1718
+ switch (op.kind) {
1719
+ case "CREATE_TABLE": {
1720
+ const table = {
1721
+ name: op.table,
1722
+ columns: op.columns.map(toSchemaColumn)
1723
+ };
1724
+ for (const column of table.columns) {
1725
+ if (column.primaryKey) {
1726
+ table.primaryKey = column.name;
1727
+ }
1728
+ }
1729
+ for (const constraint of op.constraints) {
1730
+ const applied = applySingleColumnConstraint(table, constraint);
1731
+ if (!applied) {
1732
+ warnings.push({
1733
+ statement: `CREATE TABLE ${op.table}`,
1734
+ reason: `Constraint ${constraint.type}${constraint.name ? ` (${constraint.name})` : ""} is unsupported for schema reconstruction`
1735
+ });
1736
+ }
1737
+ }
1738
+ tables[op.table] = table;
1739
+ break;
1740
+ }
1741
+ case "ADD_COLUMN": {
1742
+ const table = getOrCreateTable(tables, op.table);
1743
+ table.columns = table.columns.filter((column) => column.name !== op.column.name);
1744
+ table.columns.push(toSchemaColumn(op.column));
1745
+ if (op.column.primaryKey) {
1746
+ table.primaryKey = op.column.name;
1747
+ }
1748
+ break;
1749
+ }
1750
+ case "ALTER_COLUMN_TYPE": {
1751
+ const table = tables[op.table];
1752
+ if (!table) {
1753
+ break;
1754
+ }
1755
+ const column = table.columns.find((item) => item.name === op.column);
1756
+ if (column) {
1757
+ column.type = op.toType;
1758
+ }
1759
+ break;
1760
+ }
1761
+ case "SET_NOT_NULL": {
1762
+ const table = tables[op.table];
1763
+ const column = table?.columns.find((item) => item.name === op.column);
1764
+ if (column) {
1765
+ column.nullable = false;
1766
+ }
1767
+ break;
1768
+ }
1769
+ case "DROP_NOT_NULL": {
1770
+ const table = tables[op.table];
1771
+ const column = table?.columns.find((item) => item.name === op.column);
1772
+ if (column) {
1773
+ column.nullable = true;
1774
+ }
1775
+ break;
1776
+ }
1777
+ case "SET_DEFAULT": {
1778
+ const table = tables[op.table];
1779
+ const column = table?.columns.find((item) => item.name === op.column);
1780
+ if (column) {
1781
+ column.default = op.expr;
1782
+ }
1783
+ break;
1784
+ }
1785
+ case "DROP_DEFAULT": {
1786
+ const table = tables[op.table];
1787
+ const column = table?.columns.find((item) => item.name === op.column);
1788
+ if (column) {
1789
+ column.default = null;
1790
+ }
1791
+ break;
1792
+ }
1793
+ case "ADD_CONSTRAINT": {
1794
+ const table = tables[op.table];
1795
+ if (!table) {
1796
+ break;
1797
+ }
1798
+ const applied = applySingleColumnConstraint(table, op.constraint);
1799
+ if (!applied) {
1800
+ warnings.push({
1801
+ statement: `ALTER TABLE ${op.table} ADD CONSTRAINT ${op.constraint.name ?? "<unnamed>"}`,
1802
+ reason: `Constraint ${op.constraint.type} is unsupported for schema reconstruction`
1803
+ });
1804
+ }
1805
+ break;
1806
+ }
1807
+ case "DROP_CONSTRAINT": {
1808
+ const table = tables[op.table];
1809
+ if (!table) {
1810
+ break;
1811
+ }
1812
+ clearConstraintByName(table, op.name);
1813
+ break;
1814
+ }
1815
+ case "DROP_COLUMN": {
1816
+ const table = tables[op.table];
1817
+ if (!table) {
1818
+ break;
1819
+ }
1820
+ table.columns = table.columns.filter((column) => column.name !== op.column);
1821
+ if (table.primaryKey === op.column) {
1822
+ table.primaryKey = null;
1823
+ }
1824
+ break;
1825
+ }
1826
+ case "DROP_TABLE": {
1827
+ delete tables[op.table];
1828
+ break;
1829
+ }
1830
+ }
1831
+ }
1832
+ const schema = { tables };
1833
+ return { schema, warnings };
1834
+ }
1835
+ var init_apply_ops = __esm({
1836
+ "node_modules/@xubylele/schema-forge-core/dist/core/sql/apply-ops.js"() {
1837
+ "use strict";
1838
+ }
1839
+ });
1840
+
1841
+ // node_modules/@xubylele/schema-forge-core/dist/core/sql/schema-to-dsl.js
1842
+ function renderColumn(column) {
1843
+ const parts = [column.name, column.type];
1844
+ if (column.primaryKey) {
1845
+ parts.push("pk");
1846
+ }
1847
+ if (column.unique) {
1848
+ parts.push("unique");
1849
+ }
1850
+ if (column.nullable === false && !column.primaryKey) {
1851
+ parts.push("not null");
1852
+ }
1853
+ if (column.default !== void 0 && column.default !== null) {
1854
+ parts.push(`default ${column.default}`);
1855
+ }
1856
+ return ` ${parts.join(" ")}`;
1857
+ }
1858
+ function schemaToDsl(schema) {
1859
+ const tableNames = Object.keys(schema.tables).sort((left, right) => left.localeCompare(right));
1860
+ const blocks = tableNames.map((tableName) => {
1861
+ const table = schema.tables[tableName];
1862
+ const lines = [`table ${table.name} {`];
1863
+ for (const column of table.columns) {
1864
+ lines.push(renderColumn(column));
1865
+ }
1866
+ lines.push("}");
1867
+ return lines.join("\n");
1868
+ });
1869
+ if (blocks.length === 0) {
1870
+ return "# SchemaForge schema definition\n";
1871
+ }
1872
+ return `# SchemaForge schema definition
1873
+
1874
+ ${blocks.join("\n\n")}
1875
+ `;
1876
+ }
1877
+ var init_schema_to_dsl = __esm({
1878
+ "node_modules/@xubylele/schema-forge-core/dist/core/sql/schema-to-dsl.js"() {
1879
+ "use strict";
1880
+ }
1881
+ });
1882
+
1883
+ // node_modules/@xubylele/schema-forge-core/dist/core/sql/load-migrations.js
1884
+ async function loadMigrationSqlInput(inputPath) {
1885
+ const stats = await import_fs4.promises.stat(inputPath);
1886
+ if (stats.isFile()) {
1887
+ if (!inputPath.toLowerCase().endsWith(".sql")) {
1888
+ throw new Error(`Input file must be a .sql file: ${inputPath}`);
1889
+ }
1890
+ return [{ filePath: inputPath, sql: await readTextFile2(inputPath) }];
1891
+ }
1892
+ if (!stats.isDirectory()) {
1893
+ throw new Error(`Input path must be a .sql file or directory: ${inputPath}`);
1894
+ }
1895
+ const sqlFiles = await findFiles(inputPath, /\.sql$/i);
1896
+ sqlFiles.sort((left, right) => import_path5.default.basename(left).localeCompare(import_path5.default.basename(right)));
1897
+ const result = [];
1898
+ for (const filePath of sqlFiles) {
1899
+ result.push({
1900
+ filePath,
1901
+ sql: await readTextFile2(filePath)
1902
+ });
1903
+ }
1904
+ return result;
1905
+ }
1906
+ var import_fs4, import_path5;
1907
+ var init_load_migrations = __esm({
1908
+ "node_modules/@xubylele/schema-forge-core/dist/core/sql/load-migrations.js"() {
1909
+ "use strict";
1910
+ import_fs4 = require("fs");
1911
+ import_path5 = __toESM(require("path"), 1);
1912
+ init_fs();
1913
+ }
1914
+ });
1915
+
1916
+ // node_modules/@xubylele/schema-forge-core/dist/core/paths.js
1917
+ function getProjectRoot2(cwd = process.cwd()) {
1918
+ return cwd;
1919
+ }
1920
+ function getSchemaForgeDir2(root) {
1921
+ return import_path6.default.join(root, "schemaforge");
1922
+ }
1923
+ function getSchemaFilePath2(root, config) {
1924
+ const schemaForgeDir = getSchemaForgeDir2(root);
1925
+ const fileName = config?.schemaFile || "schema.sf";
1926
+ return import_path6.default.join(schemaForgeDir, fileName);
1927
+ }
1928
+ function getConfigPath2(root) {
1929
+ const schemaForgeDir = getSchemaForgeDir2(root);
1930
+ return import_path6.default.join(schemaForgeDir, "config.json");
1931
+ }
1932
+ function getStatePath2(root, config) {
1933
+ const schemaForgeDir = getSchemaForgeDir2(root);
1934
+ const fileName = config?.stateFile || "state.json";
1935
+ return import_path6.default.join(schemaForgeDir, fileName);
1936
+ }
1937
+ var import_path6;
1938
+ var init_paths = __esm({
1939
+ "node_modules/@xubylele/schema-forge-core/dist/core/paths.js"() {
1940
+ "use strict";
1941
+ import_path6 = __toESM(require("path"), 1);
1942
+ }
1943
+ });
1944
+
1945
+ // node_modules/@xubylele/schema-forge-core/dist/core/utils.js
1946
+ function nowTimestamp() {
1947
+ const date = /* @__PURE__ */ new Date();
1948
+ const pad = (value) => String(value).padStart(2, "0");
1949
+ return String(date.getFullYear()) + pad(date.getMonth() + 1) + pad(date.getDate()) + pad(date.getHours()) + pad(date.getMinutes()) + pad(date.getSeconds());
1950
+ }
1951
+ function slugifyName(name) {
1952
+ return name.trim().toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "migration";
1953
+ }
1954
+ var init_utils = __esm({
1955
+ "node_modules/@xubylele/schema-forge-core/dist/core/utils.js"() {
1956
+ "use strict";
1957
+ }
1958
+ });
1959
+
1960
+ // node_modules/@xubylele/schema-forge-core/dist/core/errors.js
1961
+ var SchemaValidationError;
1962
+ var init_errors = __esm({
1963
+ "node_modules/@xubylele/schema-forge-core/dist/core/errors.js"() {
1964
+ "use strict";
1965
+ SchemaValidationError = class extends Error {
1966
+ constructor(message) {
1967
+ super(message);
1968
+ this.name = "SchemaValidationError";
1969
+ }
1970
+ };
1971
+ }
1972
+ });
1973
+
1974
+ // node_modules/@xubylele/schema-forge-core/dist/index.js
1975
+ var dist_exports = {};
1976
+ __export(dist_exports, {
1977
+ SchemaValidationError: () => SchemaValidationError,
1978
+ applySqlOps: () => applySqlOps,
1979
+ diffSchemas: () => diffSchemas,
1980
+ ensureDir: () => ensureDir2,
1981
+ fileExists: () => fileExists2,
1982
+ findFiles: () => findFiles,
1983
+ generateSql: () => generateSql,
1984
+ getColumnNamesFromSchema: () => getColumnNamesFromSchema,
1985
+ getColumnNamesFromState: () => getColumnNamesFromState,
1986
+ getConfigPath: () => getConfigPath2,
1987
+ getProjectRoot: () => getProjectRoot2,
1988
+ getSchemaFilePath: () => getSchemaFilePath2,
1989
+ getSchemaForgeDir: () => getSchemaForgeDir2,
1990
+ getStatePath: () => getStatePath2,
1991
+ getTableNamesFromSchema: () => getTableNamesFromSchema,
1992
+ getTableNamesFromState: () => getTableNamesFromState,
1993
+ legacyPkName: () => legacyPkName,
1994
+ legacyUqName: () => legacyUqName,
1995
+ loadMigrationSqlInput: () => loadMigrationSqlInput,
1996
+ loadState: () => loadState,
1997
+ normalizeDefault: () => normalizeDefault,
1998
+ normalizeIdent: () => normalizeIdent,
1999
+ nowTimestamp: () => nowTimestamp,
2000
+ parseAddDropConstraint: () => parseAddDropConstraint,
2001
+ parseAlterColumnType: () => parseAlterColumnType,
2002
+ parseAlterTableAddColumn: () => parseAlterTableAddColumn,
2003
+ parseCreateTable: () => parseCreateTable,
2004
+ parseDropColumn: () => parseDropColumn,
2005
+ parseDropTable: () => parseDropTable,
2006
+ parseMigrationSql: () => parseMigrationSql,
2007
+ parseSchema: () => parseSchema,
2008
+ parseSetDropDefault: () => parseSetDropDefault,
2009
+ parseSetDropNotNull: () => parseSetDropNotNull,
2010
+ pkName: () => pkName,
2011
+ readJsonFile: () => readJsonFile2,
2012
+ readTextFile: () => readTextFile2,
2013
+ saveState: () => saveState,
2014
+ schemaToDsl: () => schemaToDsl,
2015
+ schemaToState: () => schemaToState,
2016
+ slugifyName: () => slugifyName,
2017
+ splitSqlStatements: () => splitSqlStatements,
2018
+ toValidationReport: () => toValidationReport,
2019
+ uqName: () => uqName,
2020
+ validateSchema: () => validateSchema,
2021
+ validateSchemaChanges: () => validateSchemaChanges,
2022
+ writeJsonFile: () => writeJsonFile2,
2023
+ writeTextFile: () => writeTextFile2
2024
+ });
2025
+ var init_dist = __esm({
2026
+ "node_modules/@xubylele/schema-forge-core/dist/index.js"() {
2027
+ "use strict";
2028
+ init_parser();
2029
+ init_diff();
2030
+ init_validator();
2031
+ init_validate();
2032
+ init_state_manager();
2033
+ init_sql_generator();
2034
+ init_parse_migration();
2035
+ init_apply_ops();
2036
+ init_schema_to_dsl();
2037
+ init_load_migrations();
2038
+ init_split_statements();
2039
+ init_fs();
2040
+ init_normalize();
2041
+ init_paths();
2042
+ init_utils();
2043
+ init_errors();
2044
+ }
2045
+ });
2046
+
26
2047
  // src/cli.ts
27
2048
  var import_commander6 = require("commander");
28
2049
 
29
2050
  // package.json
30
2051
  var package_default = {
31
2052
  name: "@xubylele/schema-forge",
32
- version: "1.5.0",
2053
+ version: "1.5.1",
33
2054
  description: "Universal migration generator from schema DSL",
34
2055
  main: "dist/cli.js",
35
2056
  type: "commonjs",
@@ -69,7 +2090,6 @@ var package_default = {
69
2090
  node: ">=18.0.0"
70
2091
  },
71
2092
  dependencies: {
72
- "@xubylele/schema-forge-core": "^1.0.4",
73
2093
  boxen: "^8.0.1",
74
2094
  chalk: "^5.6.2",
75
2095
  commander: "^14.0.3"
@@ -77,6 +2097,7 @@ var package_default = {
77
2097
  devDependencies: {
78
2098
  "@changesets/cli": "^2.29.8",
79
2099
  "@types/node": "^25.2.3",
2100
+ "@xubylele/schema-forge-core": "^1.0.5",
80
2101
  "ts-node": "^10.9.2",
81
2102
  tsup: "^8.5.1",
82
2103
  typescript: "^5.9.3",
@@ -86,7 +2107,7 @@ var package_default = {
86
2107
 
87
2108
  // src/commands/diff.ts
88
2109
  var import_commander = require("commander");
89
- var import_path3 = __toESM(require("path"));
2110
+ var import_path7 = __toESM(require("path"));
90
2111
 
91
2112
  // src/core/fs.ts
92
2113
  var import_fs = require("fs");
@@ -179,59 +2200,59 @@ function resolveProvider(provider) {
179
2200
  var corePromise;
180
2201
  async function loadCore() {
181
2202
  if (!corePromise) {
182
- corePromise = import("@xubylele/schema-forge-core");
2203
+ corePromise = Promise.resolve().then(() => (init_dist(), dist_exports));
183
2204
  }
184
2205
  return corePromise;
185
2206
  }
186
- async function parseSchema(source) {
2207
+ async function parseSchema2(source) {
187
2208
  const core = await loadCore();
188
2209
  return core.parseSchema(source);
189
2210
  }
190
- async function validateSchema(schema) {
2211
+ async function validateSchema2(schema) {
191
2212
  const core = await loadCore();
192
2213
  core.validateSchema(schema);
193
2214
  }
194
- async function diffSchemas(previousState, currentSchema) {
2215
+ async function diffSchemas2(previousState, currentSchema) {
195
2216
  const core = await loadCore();
196
2217
  return core.diffSchemas(previousState, currentSchema);
197
2218
  }
198
- async function generateSql(diff, provider, config) {
2219
+ async function generateSql2(diff, provider, config) {
199
2220
  const core = await loadCore();
200
2221
  return core.generateSql(diff, provider, config);
201
2222
  }
202
- async function schemaToState(schema) {
2223
+ async function schemaToState2(schema) {
203
2224
  const core = await loadCore();
204
2225
  return core.schemaToState(schema);
205
2226
  }
206
- async function loadState(statePath) {
2227
+ async function loadState2(statePath) {
207
2228
  const core = await loadCore();
208
2229
  return core.loadState(statePath);
209
2230
  }
210
- async function saveState(statePath, state) {
2231
+ async function saveState2(statePath, state) {
211
2232
  const core = await loadCore();
212
2233
  return core.saveState(statePath, state);
213
2234
  }
214
- async function validateSchemaChanges(previousState, currentSchema) {
2235
+ async function validateSchemaChanges2(previousState, currentSchema) {
215
2236
  const core = await loadCore();
216
2237
  return core.validateSchemaChanges(previousState, currentSchema);
217
2238
  }
218
- async function toValidationReport(findings) {
2239
+ async function toValidationReport2(findings) {
219
2240
  const core = await loadCore();
220
2241
  return core.toValidationReport(findings);
221
2242
  }
222
- async function parseMigrationSql(sql) {
2243
+ async function parseMigrationSql2(sql) {
223
2244
  const core = await loadCore();
224
2245
  return core.parseMigrationSql(sql);
225
2246
  }
226
- async function applySqlOps(ops) {
2247
+ async function applySqlOps2(ops) {
227
2248
  const core = await loadCore();
228
2249
  return core.applySqlOps(ops);
229
2250
  }
230
- async function schemaToDsl(schema) {
2251
+ async function schemaToDsl2(schema) {
231
2252
  const core = await loadCore();
232
2253
  return core.schemaToDsl(schema);
233
2254
  }
234
- async function loadMigrationSqlInput(inputPath) {
2255
+ async function loadMigrationSqlInput2(inputPath) {
235
2256
  const core = await loadCore();
236
2257
  return core.loadMigrationSqlInput(inputPath);
237
2258
  }
@@ -288,7 +2309,7 @@ function error(message) {
288
2309
  // src/commands/diff.ts
289
2310
  var REQUIRED_CONFIG_FIELDS = ["schemaFile", "stateFile"];
290
2311
  function resolveConfigPath(root, targetPath) {
291
- return import_path3.default.isAbsolute(targetPath) ? targetPath : import_path3.default.join(root, targetPath);
2312
+ return import_path7.default.isAbsolute(targetPath) ? targetPath : import_path7.default.join(root, targetPath);
292
2313
  }
293
2314
  async function runDiff() {
294
2315
  const root = getProjectRoot();
@@ -307,36 +2328,36 @@ async function runDiff() {
307
2328
  const statePath = resolveConfigPath(root, config.stateFile);
308
2329
  const { provider } = resolveProvider(config.provider);
309
2330
  const schemaSource = await readTextFile(schemaPath);
310
- const schema = await parseSchema(schemaSource);
2331
+ const schema = await parseSchema2(schemaSource);
311
2332
  try {
312
- await validateSchema(schema);
2333
+ await validateSchema2(schema);
313
2334
  } catch (error2) {
314
2335
  if (error2 instanceof Error) {
315
2336
  throw await createSchemaValidationError(error2.message);
316
2337
  }
317
2338
  throw error2;
318
2339
  }
319
- const previousState = await loadState(statePath);
320
- const diff = await diffSchemas(previousState, schema);
2340
+ const previousState = await loadState2(statePath);
2341
+ const diff = await diffSchemas2(previousState, schema);
321
2342
  if (diff.operations.length === 0) {
322
2343
  success("No changes detected");
323
2344
  return;
324
2345
  }
325
- const sql = await generateSql(diff, provider, config.sql);
2346
+ const sql = await generateSql2(diff, provider, config.sql);
326
2347
  console.log(sql);
327
2348
  }
328
2349
 
329
2350
  // src/commands/generate.ts
330
2351
  var import_commander2 = require("commander");
331
- var import_path4 = __toESM(require("path"));
2352
+ var import_path8 = __toESM(require("path"));
332
2353
 
333
2354
  // src/core/utils.ts
334
- function nowTimestamp() {
2355
+ function nowTimestamp2() {
335
2356
  const date = /* @__PURE__ */ new Date();
336
2357
  const pad = (value) => String(value).padStart(2, "0");
337
2358
  return String(date.getFullYear()) + pad(date.getMonth() + 1) + pad(date.getDate()) + pad(date.getHours()) + pad(date.getMinutes()) + pad(date.getSeconds());
338
2359
  }
339
- function slugifyName(name) {
2360
+ function slugifyName2(name) {
340
2361
  return name.trim().toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "migration";
341
2362
  }
342
2363
 
@@ -347,7 +2368,7 @@ var REQUIRED_CONFIG_FIELDS2 = [
347
2368
  "outputDir"
348
2369
  ];
349
2370
  function resolveConfigPath2(root, targetPath) {
350
- return import_path4.default.isAbsolute(targetPath) ? targetPath : import_path4.default.join(root, targetPath);
2371
+ return import_path8.default.isAbsolute(targetPath) ? targetPath : import_path8.default.join(root, targetPath);
351
2372
  }
352
2373
  async function runGenerate(options) {
353
2374
  const root = getProjectRoot();
@@ -371,58 +2392,58 @@ async function runGenerate(options) {
371
2392
  }
372
2393
  info("Generating SQL...");
373
2394
  const schemaSource = await readTextFile(schemaPath);
374
- const schema = await parseSchema(schemaSource);
2395
+ const schema = await parseSchema2(schemaSource);
375
2396
  try {
376
- await validateSchema(schema);
2397
+ await validateSchema2(schema);
377
2398
  } catch (error2) {
378
2399
  if (error2 instanceof Error) {
379
2400
  throw await createSchemaValidationError(error2.message);
380
2401
  }
381
2402
  throw error2;
382
2403
  }
383
- const previousState = await loadState(statePath);
384
- const diff = await diffSchemas(previousState, schema);
2404
+ const previousState = await loadState2(statePath);
2405
+ const diff = await diffSchemas2(previousState, schema);
385
2406
  if (diff.operations.length === 0) {
386
2407
  info("No changes detected");
387
2408
  return;
388
2409
  }
389
- const sql = await generateSql(diff, provider, config.sql);
390
- const timestamp = nowTimestamp();
391
- const slug = slugifyName(options.name ?? "migration");
2410
+ const sql = await generateSql2(diff, provider, config.sql);
2411
+ const timestamp = nowTimestamp2();
2412
+ const slug = slugifyName2(options.name ?? "migration");
392
2413
  const fileName = `${timestamp}-${slug}.sql`;
393
2414
  await ensureDir(outputDir);
394
- const migrationPath = import_path4.default.join(outputDir, fileName);
2415
+ const migrationPath = import_path8.default.join(outputDir, fileName);
395
2416
  await writeTextFile(migrationPath, sql + "\n");
396
- const nextState = await schemaToState(schema);
397
- await saveState(statePath, nextState);
2417
+ const nextState = await schemaToState2(schema);
2418
+ await saveState2(statePath, nextState);
398
2419
  success(`SQL generated successfully: ${migrationPath}`);
399
2420
  }
400
2421
 
401
2422
  // src/commands/import.ts
402
2423
  var import_commander3 = require("commander");
403
- var import_path5 = __toESM(require("path"));
2424
+ var import_path9 = __toESM(require("path"));
404
2425
  function resolveConfigPath3(root, targetPath) {
405
- return import_path5.default.isAbsolute(targetPath) ? targetPath : import_path5.default.join(root, targetPath);
2426
+ return import_path9.default.isAbsolute(targetPath) ? targetPath : import_path9.default.join(root, targetPath);
406
2427
  }
407
2428
  async function runImport(inputPath, options = {}) {
408
2429
  const root = getProjectRoot();
409
2430
  const absoluteInputPath = resolveConfigPath3(root, inputPath);
410
- const inputs = await loadMigrationSqlInput(absoluteInputPath);
2431
+ const inputs = await loadMigrationSqlInput2(absoluteInputPath);
411
2432
  if (inputs.length === 0) {
412
2433
  throw new Error(`No .sql migration files found in: ${absoluteInputPath}`);
413
2434
  }
414
2435
  const allOps = [];
415
2436
  const parseWarnings = [];
416
2437
  for (const input of inputs) {
417
- const result = await parseMigrationSql(input.sql);
2438
+ const result = await parseMigrationSql2(input.sql);
418
2439
  allOps.push(...result.ops);
419
2440
  parseWarnings.push(...result.warnings.map((item) => ({
420
- statement: `[${import_path5.default.basename(input.filePath)}] ${item.statement}`,
2441
+ statement: `[${import_path9.default.basename(input.filePath)}] ${item.statement}`,
421
2442
  reason: item.reason
422
2443
  })));
423
2444
  }
424
- const applied = await applySqlOps(allOps);
425
- const dsl = await schemaToDsl(applied.schema);
2445
+ const applied = await applySqlOps2(allOps);
2446
+ const dsl = await schemaToDsl2(applied.schema);
426
2447
  let targetPath = options.out;
427
2448
  if (!targetPath) {
428
2449
  const configPath = getConfigPath(root);
@@ -515,10 +2536,10 @@ table users {
515
2536
 
516
2537
  // src/commands/validate.ts
517
2538
  var import_commander5 = require("commander");
518
- var import_path6 = __toESM(require("path"));
2539
+ var import_path10 = __toESM(require("path"));
519
2540
  var REQUIRED_CONFIG_FIELDS3 = ["schemaFile", "stateFile"];
520
2541
  function resolveConfigPath4(root, targetPath) {
521
- return import_path6.default.isAbsolute(targetPath) ? targetPath : import_path6.default.join(root, targetPath);
2542
+ return import_path10.default.isAbsolute(targetPath) ? targetPath : import_path10.default.join(root, targetPath);
522
2543
  }
523
2544
  async function runValidate(options = {}) {
524
2545
  const root = getProjectRoot();
@@ -536,18 +2557,18 @@ async function runValidate(options = {}) {
536
2557
  const schemaPath = resolveConfigPath4(root, config.schemaFile);
537
2558
  const statePath = resolveConfigPath4(root, config.stateFile);
538
2559
  const schemaSource = await readTextFile(schemaPath);
539
- const schema = await parseSchema(schemaSource);
2560
+ const schema = await parseSchema2(schemaSource);
540
2561
  try {
541
- await validateSchema(schema);
2562
+ await validateSchema2(schema);
542
2563
  } catch (error2) {
543
2564
  if (error2 instanceof Error) {
544
2565
  throw await createSchemaValidationError(error2.message);
545
2566
  }
546
2567
  throw error2;
547
2568
  }
548
- const previousState = await loadState(statePath);
549
- const findings = await validateSchemaChanges(previousState, schema);
550
- const report = await toValidationReport(findings);
2569
+ const previousState = await loadState2(statePath);
2570
+ const findings = await validateSchemaChanges2(previousState, schema);
2571
+ const report = await toValidationReport2(findings);
551
2572
  if (options.json) {
552
2573
  console.log(JSON.stringify(report, null, 2));
553
2574
  process.exitCode = report.hasErrors ? 1 : 0;