metal-orm 1.0.45 → 1.0.47

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 (63) hide show
  1. package/dist/index.cjs +1092 -323
  2. package/dist/index.cjs.map +1 -1
  3. package/dist/index.d.cts +99 -9
  4. package/dist/index.d.ts +99 -9
  5. package/dist/index.js +1087 -323
  6. package/dist/index.js.map +1 -1
  7. package/package.json +1 -1
  8. package/scripts/generate-entities.mjs +36 -9
  9. package/src/codegen/typescript.ts +22 -10
  10. package/src/core/ast/adapters.ts +2 -1
  11. package/src/core/ast/expression-builders.ts +13 -0
  12. package/src/core/ast/expression-nodes.ts +25 -5
  13. package/src/core/ast/expression-visitor.ts +5 -0
  14. package/src/core/ast/query.ts +9 -1
  15. package/src/core/ddl/dialects/base-schema-dialect.ts +2 -1
  16. package/src/core/ddl/dialects/mssql-schema-dialect.ts +10 -23
  17. package/src/core/ddl/dialects/mysql-schema-dialect.ts +10 -24
  18. package/src/core/ddl/dialects/postgres-schema-dialect.ts +10 -23
  19. package/src/core/ddl/dialects/render-reference.test.ts +2 -1
  20. package/src/core/ddl/dialects/sqlite-schema-dialect.ts +9 -23
  21. package/src/core/ddl/introspect/catalogs/index.ts +4 -1
  22. package/src/core/ddl/introspect/catalogs/mssql.ts +126 -0
  23. package/src/core/ddl/introspect/catalogs/mysql.ts +89 -0
  24. package/src/core/ddl/introspect/catalogs/postgres.ts +2 -1
  25. package/src/core/ddl/introspect/catalogs/sqlite.ts +47 -0
  26. package/src/core/ddl/introspect/functions/mssql.ts +84 -0
  27. package/src/core/ddl/introspect/mssql.ts +471 -194
  28. package/src/core/ddl/introspect/mysql.ts +336 -125
  29. package/src/core/ddl/introspect/postgres.ts +45 -5
  30. package/src/core/ddl/introspect/run-select.ts +3 -8
  31. package/src/core/ddl/introspect/sqlite.ts +113 -59
  32. package/src/core/ddl/schema-dialect.ts +2 -1
  33. package/src/core/ddl/schema-diff.ts +2 -1
  34. package/src/core/ddl/schema-generator.ts +2 -1
  35. package/src/core/ddl/schema-types.ts +3 -1
  36. package/src/core/ddl/sql-writing.ts +2 -1
  37. package/src/core/dialect/abstract.ts +12 -1
  38. package/src/core/dialect/mssql/index.ts +4 -10
  39. package/src/core/functions/datetime.ts +2 -1
  40. package/src/core/functions/numeric.ts +2 -1
  41. package/src/core/functions/text.ts +2 -1
  42. package/src/decorators/{column.ts → column-decorator.ts} +4 -1
  43. package/src/decorators/index.ts +1 -1
  44. package/src/index.ts +2 -1
  45. package/src/orm/entity-metadata.ts +2 -1
  46. package/src/orm/lazy-batch.ts +2 -1
  47. package/src/orm/orm-session.ts +2 -1
  48. package/src/query-builder/column-selector.ts +2 -1
  49. package/src/query-builder/delete.ts +2 -1
  50. package/src/query-builder/insert.ts +2 -1
  51. package/src/query-builder/query-ast-service.ts +4 -3
  52. package/src/query-builder/relation-projection-helper.ts +2 -1
  53. package/src/query-builder/relation-service.ts +2 -1
  54. package/src/query-builder/select/predicate-facet.ts +2 -1
  55. package/src/query-builder/select/projection-facet.ts +2 -1
  56. package/src/query-builder/select-helpers.ts +2 -1
  57. package/src/query-builder/select-query-state.ts +2 -0
  58. package/src/query-builder/select.ts +2 -1
  59. package/src/query-builder/update.ts +2 -1
  60. package/src/schema/{column.ts → column-types.ts} +317 -290
  61. package/src/schema/table-guards.ts +1 -1
  62. package/src/schema/table.ts +1 -1
  63. package/src/schema/types.ts +10 -8
package/dist/index.cjs CHANGED
@@ -2,8 +2,8 @@ var __defProp = Object.defineProperty;
2
2
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
3
  var __getOwnPropNames = Object.getOwnPropertyNames;
4
4
  var __hasOwnProp = Object.prototype.hasOwnProperty;
5
- var __esm = (fn4, res) => function __init() {
6
- return fn4 && (res = (0, fn4[__getOwnPropNames(fn4)[0]])(fn4 = 0)), res;
5
+ var __esm = (fn5, res) => function __init() {
6
+ return fn5 && (res = (0, fn5[__getOwnPropNames(fn5)[0]])(fn5 = 0)), res;
7
7
  };
8
8
  var __export = (target, all) => {
9
9
  for (var name in all)
@@ -64,6 +64,7 @@ __export(index_exports, {
64
64
  PostgresDialect: () => PostgresDialect,
65
65
  PrimaryKey: () => PrimaryKey,
66
66
  RelationKinds: () => RelationKinds,
67
+ STANDARD_COLUMN_TYPES: () => STANDARD_COLUMN_TYPES,
67
68
  SelectQueryBuilder: () => SelectQueryBuilder,
68
69
  SqlServerDialect: () => SqlServerDialect,
69
70
  SqliteDialect: () => SqliteDialect,
@@ -85,6 +86,7 @@ __export(index_exports, {
85
86
  between: () => between,
86
87
  bootstrapEntities: () => bootstrapEntities,
87
88
  caseWhen: () => caseWhen,
89
+ cast: () => cast,
88
90
  ceil: () => ceil,
89
91
  ceiling: () => ceiling,
90
92
  char: () => char,
@@ -152,6 +154,7 @@ __export(index_exports, {
152
154
  instr: () => instr,
153
155
  introspectSchema: () => introspectSchema,
154
156
  isCaseExpressionNode: () => isCaseExpressionNode,
157
+ isCastExpressionNode: () => isCastExpressionNode,
155
158
  isExpressionSelectionNode: () => isExpressionSelectionNode,
156
159
  isFunctionNode: () => isFunctionNode,
157
160
  isNotNull: () => isNotNull,
@@ -186,6 +189,7 @@ __export(index_exports, {
186
189
  month: () => month,
187
190
  mul: () => mul,
188
191
  neq: () => neq,
192
+ normalizeColumnType: () => normalizeColumnType,
189
193
  notBetween: () => notBetween,
190
194
  notExists: () => notExists,
191
195
  notInList: () => notInList,
@@ -207,6 +211,7 @@ __export(index_exports, {
207
211
  registerOperandDispatcher: () => registerOperandDispatcher,
208
212
  registerSchemaIntrospector: () => registerSchemaIntrospector,
209
213
  renderColumnDefinition: () => renderColumnDefinition,
214
+ renderTypeWithArgs: () => renderTypeWithArgs,
210
215
  repeat: () => repeat,
211
216
  replace: () => replace,
212
217
  right: () => right,
@@ -326,7 +331,38 @@ function getColumn(table, key) {
326
331
  return col2;
327
332
  }
328
333
 
329
- // src/schema/column.ts
334
+ // src/schema/column-types.ts
335
+ var STANDARD_COLUMN_TYPES = [
336
+ "INT",
337
+ "INTEGER",
338
+ "BIGINT",
339
+ "VARCHAR",
340
+ "TEXT",
341
+ "JSON",
342
+ "ENUM",
343
+ "DECIMAL",
344
+ "FLOAT",
345
+ "DOUBLE",
346
+ "UUID",
347
+ "BINARY",
348
+ "VARBINARY",
349
+ "BLOB",
350
+ "DATE",
351
+ "DATETIME",
352
+ "TIMESTAMP",
353
+ "TIMESTAMPTZ",
354
+ "BOOLEAN"
355
+ ];
356
+ var STANDARD_TYPE_SET = new Set(STANDARD_COLUMN_TYPES.map((t) => t.toLowerCase()));
357
+ var normalizeColumnType = (type) => {
358
+ if (typeof type !== "string") return type;
359
+ const lower2 = type.toLowerCase();
360
+ return STANDARD_TYPE_SET.has(lower2) ? lower2 : type;
361
+ };
362
+ var renderTypeWithArgs = (sqlType, args) => {
363
+ if (!args || args.length === 0) return sqlType;
364
+ return `${sqlType}(${args.join(", ")})`;
365
+ };
330
366
  var col = {
331
367
  /**
332
368
  * Creates an integer column definition
@@ -386,7 +422,10 @@ var col = {
386
422
  /**
387
423
  * Creates a Postgres bytea column definition
388
424
  */
389
- bytea: () => ({ name: "", type: "BYTEA" }),
425
+ bytea: () => ({
426
+ name: "",
427
+ type: "BYTEA"
428
+ }),
390
429
  /**
391
430
  * Creates a timestamp column definition
392
431
  */
@@ -418,6 +457,17 @@ var col = {
418
457
  * @param values - Enum values
419
458
  */
420
459
  enum: (values) => ({ name: "", type: "ENUM", args: values }),
460
+ /**
461
+ * Creates a column definition with a custom SQL type.
462
+ * Useful for dialect-specific types without polluting the standard set.
463
+ */
464
+ custom: (type, opts = {}) => ({
465
+ name: "",
466
+ type,
467
+ args: opts.args,
468
+ tsType: opts.tsType,
469
+ dialectTypes: opts.dialect ? { [opts.dialect]: type } : void 0
470
+ }),
421
471
  /**
422
472
  * Marks a column definition as a primary key
423
473
  * @param def - Column definition to modify
@@ -527,7 +577,9 @@ var operandTypes = /* @__PURE__ */ new Set([
527
577
  "JsonPath",
528
578
  "ScalarSubquery",
529
579
  "CaseExpression",
530
- "WindowFunction"
580
+ "Cast",
581
+ "WindowFunction",
582
+ "ArithmeticExpression"
531
583
  ]);
532
584
  var hasTypeProperty = (value) => typeof value === "object" && value !== null && "type" in value;
533
585
  var isOperandNode = (node) => {
@@ -536,8 +588,9 @@ var isOperandNode = (node) => {
536
588
  };
537
589
  var isFunctionNode = (node) => isOperandNode(node) && node.type === "Function";
538
590
  var isCaseExpressionNode = (node) => isOperandNode(node) && node.type === "CaseExpression";
591
+ var isCastExpressionNode = (node) => isOperandNode(node) && node.type === "Cast";
539
592
  var isWindowFunctionNode = (node) => isOperandNode(node) && node.type === "WindowFunction";
540
- var isExpressionSelectionNode = (node) => isFunctionNode(node) || isCaseExpressionNode(node) || isWindowFunctionNode(node);
593
+ var isExpressionSelectionNode = (node) => isFunctionNode(node) || isCaseExpressionNode(node) || isCastExpressionNode(node) || isWindowFunctionNode(node);
541
594
 
542
595
  // src/core/ast/expression-builders.ts
543
596
  var isLiteralValue = (value) => value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean";
@@ -673,6 +726,11 @@ var caseWhen = (conditions, elseValue) => ({
673
726
  })),
674
727
  else: elseValue !== void 0 ? toOperand(elseValue) : void 0
675
728
  });
729
+ var cast = (expression, castType) => ({
730
+ type: "Cast",
731
+ expression: toOperand(expression),
732
+ castType
733
+ });
676
734
  var exists = (subquery) => ({
677
735
  type: "ExistsExpression",
678
736
  operator: "EXISTS",
@@ -930,6 +988,9 @@ var visitOperand = (node, visitor) => {
930
988
  case "AliasRef":
931
989
  if (visitor.visitAliasRef) return visitor.visitAliasRef(node);
932
990
  break;
991
+ case "Cast":
992
+ if (visitor.visitCast) return visitor.visitCast(node);
993
+ break;
933
994
  default:
934
995
  break;
935
996
  }
@@ -1456,6 +1517,10 @@ var Dialect = class _Dialect {
1456
1517
  parts.push("END");
1457
1518
  return parts.join(" ");
1458
1519
  });
1520
+ this.registerOperandCompiler("Cast", (node, ctx) => {
1521
+ const value = this.compileOperand(node.expression, ctx);
1522
+ return `CAST(${value} AS ${node.castType})`;
1523
+ });
1459
1524
  this.registerOperandCompiler("WindowFunction", (node, ctx) => {
1460
1525
  let result = `${node.name}(`;
1461
1526
  if (node.args.length > 0) {
@@ -1482,6 +1547,11 @@ var Dialect = class _Dialect {
1482
1547
  result += ")";
1483
1548
  return result;
1484
1549
  });
1550
+ this.registerOperandCompiler("ArithmeticExpression", (node, ctx) => {
1551
+ const left2 = this.compileOperand(node.left, ctx);
1552
+ const right2 = this.compileOperand(node.right, ctx);
1553
+ return `(${left2} ${node.operator} ${right2})`;
1554
+ });
1485
1555
  }
1486
1556
  // Default fallback, should be overridden by dialects if supported
1487
1557
  compileJsonPath(_node) {
@@ -1514,13 +1584,13 @@ var FunctionTableFormatter = class {
1514
1584
  * @param dialect - The dialect instance for compiling operands.
1515
1585
  * @returns SQL function table expression (e.g., "LATERAL schema.func(args) WITH ORDINALITY AS alias(col1, col2)").
1516
1586
  */
1517
- static format(fn4, ctx, dialect) {
1518
- const schemaPart = this.formatSchema(fn4, dialect);
1519
- const args = this.formatArgs(fn4, ctx, dialect);
1520
- const base = this.formatBase(fn4, schemaPart, args, dialect);
1521
- const lateral = this.formatLateral(fn4);
1522
- const alias = this.formatAlias(fn4, dialect);
1523
- const colAliases = this.formatColumnAliases(fn4, dialect);
1587
+ static format(fn5, ctx, dialect) {
1588
+ const schemaPart = this.formatSchema(fn5, dialect);
1589
+ const args = this.formatArgs(fn5, ctx, dialect);
1590
+ const base = this.formatBase(fn5, schemaPart, args, dialect);
1591
+ const lateral = this.formatLateral(fn5);
1592
+ const alias = this.formatAlias(fn5, dialect);
1593
+ const colAliases = this.formatColumnAliases(fn5, dialect);
1524
1594
  return `${lateral}${base}${alias}${colAliases}`;
1525
1595
  }
1526
1596
  /**
@@ -1530,9 +1600,9 @@ var FunctionTableFormatter = class {
1530
1600
  * @returns Schema prefix (e.g., "schema.") or empty string.
1531
1601
  * @internal
1532
1602
  */
1533
- static formatSchema(fn4, dialect) {
1534
- if (!fn4.schema) return "";
1535
- const quoted = dialect ? dialect.quoteIdentifier(fn4.schema) : fn4.schema;
1603
+ static formatSchema(fn5, dialect) {
1604
+ if (!fn5.schema) return "";
1605
+ const quoted = dialect ? dialect.quoteIdentifier(fn5.schema) : fn5.schema;
1536
1606
  return `${quoted}.`;
1537
1607
  }
1538
1608
  /**
@@ -1543,8 +1613,8 @@ var FunctionTableFormatter = class {
1543
1613
  * @returns Comma-separated function arguments.
1544
1614
  * @internal
1545
1615
  */
1546
- static formatArgs(fn4, ctx, dialect) {
1547
- return (fn4.args || []).map((a) => {
1616
+ static formatArgs(fn5, ctx, dialect) {
1617
+ return (fn5.args || []).map((a) => {
1548
1618
  if (ctx && dialect) {
1549
1619
  return dialect.compileOperand(a, ctx);
1550
1620
  }
@@ -1560,9 +1630,9 @@ var FunctionTableFormatter = class {
1560
1630
  * @returns Base function call expression (e.g., "schema.func(args) WITH ORDINALITY").
1561
1631
  * @internal
1562
1632
  */
1563
- static formatBase(fn4, schemaPart, args, dialect) {
1564
- const ordinality = fn4.withOrdinality ? " WITH ORDINALITY" : "";
1565
- const quoted = dialect ? dialect.quoteIdentifier(fn4.name) : fn4.name;
1633
+ static formatBase(fn5, schemaPart, args, dialect) {
1634
+ const ordinality = fn5.withOrdinality ? " WITH ORDINALITY" : "";
1635
+ const quoted = dialect ? dialect.quoteIdentifier(fn5.name) : fn5.name;
1566
1636
  return `${schemaPart}${quoted}(${args})${ordinality}`;
1567
1637
  }
1568
1638
  /**
@@ -1571,8 +1641,8 @@ var FunctionTableFormatter = class {
1571
1641
  * @returns "LATERAL " or empty string.
1572
1642
  * @internal
1573
1643
  */
1574
- static formatLateral(fn4) {
1575
- return fn4.lateral ? "LATERAL " : "";
1644
+ static formatLateral(fn5) {
1645
+ return fn5.lateral ? "LATERAL " : "";
1576
1646
  }
1577
1647
  /**
1578
1648
  * Formats the table alias for the function table.
@@ -1581,9 +1651,9 @@ var FunctionTableFormatter = class {
1581
1651
  * @returns " AS alias" or empty string.
1582
1652
  * @internal
1583
1653
  */
1584
- static formatAlias(fn4, dialect) {
1585
- if (!fn4.alias) return "";
1586
- const quoted = dialect ? dialect.quoteIdentifier(fn4.alias) : fn4.alias;
1654
+ static formatAlias(fn5, dialect) {
1655
+ if (!fn5.alias) return "";
1656
+ const quoted = dialect ? dialect.quoteIdentifier(fn5.alias) : fn5.alias;
1587
1657
  return ` AS ${quoted}`;
1588
1658
  }
1589
1659
  /**
@@ -1593,9 +1663,9 @@ var FunctionTableFormatter = class {
1593
1663
  * @returns "(col1, col2, ...)" or empty string.
1594
1664
  * @internal
1595
1665
  */
1596
- static formatColumnAliases(fn4, dialect) {
1597
- if (!fn4.columnAliases || !fn4.columnAliases.length) return "";
1598
- const aliases = fn4.columnAliases.map((col2) => dialect ? dialect.quoteIdentifier(col2) : col2).join(", ");
1666
+ static formatColumnAliases(fn5, dialect) {
1667
+ if (!fn5.columnAliases || !fn5.columnAliases.length) return "";
1668
+ const aliases = fn5.columnAliases.map((col2) => dialect ? dialect.quoteIdentifier(col2) : col2).join(", ");
1599
1669
  return `(${aliases})`;
1600
1670
  }
1601
1671
  };
@@ -1863,8 +1933,8 @@ var SqlDialectBase = class extends Dialect {
1863
1933
  }
1864
1934
  return this.compileTableSource(tableSource);
1865
1935
  }
1866
- compileFunctionTable(fn4, ctx) {
1867
- return FunctionTableFormatter.format(fn4, ctx, this);
1936
+ compileFunctionTable(fn5, ctx) {
1937
+ return FunctionTableFormatter.format(fn5, ctx, this);
1868
1938
  }
1869
1939
  compileDerivedTable(table, ctx) {
1870
1940
  if (!table.alias) {
@@ -2488,16 +2558,7 @@ var SqlServerDialect = class extends SqlDialectBase {
2488
2558
  }
2489
2559
  compileSelectCoreForMssql(ast, ctx) {
2490
2560
  const columns = ast.columns.map((c) => {
2491
- let expr = "";
2492
- if (c.type === "Function") {
2493
- expr = this.compileOperand(c, ctx);
2494
- } else if (c.type === "Column") {
2495
- expr = `${this.quoteIdentifier(c.table)}.${this.quoteIdentifier(c.name)}`;
2496
- } else if (c.type === "ScalarSubquery") {
2497
- expr = this.compileOperand(c, ctx);
2498
- } else if (c.type === "WindowFunction") {
2499
- expr = this.compileOperand(c, ctx);
2500
- }
2561
+ const expr = c.type === "Column" ? `${this.quoteIdentifier(c.table)}.${this.quoteIdentifier(c.name)}` : this.compileOperand(c, ctx);
2501
2562
  if (c.alias) {
2502
2563
  if (c.alias.includes("(")) return c.alias;
2503
2564
  return `${expr} AS ${this.quoteIdentifier(c.alias)}`;
@@ -6771,15 +6832,11 @@ var PgReferentialConstraints = defineTable(
6771
6832
  async function runSelect(qb, ctx) {
6772
6833
  const ast = qb.getAST();
6773
6834
  const compiled = ctx.dialect.compileSelect(ast);
6774
- const results = await ctx.executor.executeSql(compiled.sql, compiled.params);
6775
- const [first] = results;
6776
- return toRows(first);
6835
+ return await queryRows(ctx.executor, compiled.sql, compiled.params);
6777
6836
  }
6778
6837
  async function runSelectNode(ast, ctx) {
6779
6838
  const compiled = ctx.dialect.compileSelect(ast);
6780
- const results = await ctx.executor.executeSql(compiled.sql, compiled.params);
6781
- const [first] = results;
6782
- return toRows(first);
6839
+ return await queryRows(ctx.executor, compiled.sql, compiled.params);
6783
6840
  }
6784
6841
 
6785
6842
  // src/core/ddl/introspect/postgres.ts
@@ -6804,6 +6861,32 @@ var postgresIntrospector = {
6804
6861
  ordinal_position: PgInformationSchemaColumns.columns.ordinal_position
6805
6862
  }).where(eq(PgInformationSchemaColumns.columns.table_schema, schema)).orderBy(PgInformationSchemaColumns.columns.table_name).orderBy(PgInformationSchemaColumns.columns.ordinal_position);
6806
6863
  const columnRows = await runSelect(qbColumns, ctx);
6864
+ const columnCommentRows = await queryRows(
6865
+ ctx.executor,
6866
+ `
6867
+ SELECT
6868
+ ns.nspname AS table_schema,
6869
+ cls.relname AS table_name,
6870
+ att.attname AS column_name,
6871
+ pg_catalog.col_description(cls.oid, att.attnum) AS description
6872
+ FROM pg_catalog.pg_attribute att
6873
+ JOIN pg_catalog.pg_class cls ON cls.oid = att.attrelid
6874
+ JOIN pg_catalog.pg_namespace ns ON ns.oid = cls.relnamespace
6875
+ WHERE ns.nspname = $1
6876
+ AND att.attnum > 0
6877
+ AND NOT att.attisdropped
6878
+ `,
6879
+ [schema]
6880
+ );
6881
+ const columnComments = /* @__PURE__ */ new Map();
6882
+ columnCommentRows.forEach((r) => {
6883
+ if (!shouldIncludeTable(r.table_name, options)) return;
6884
+ if (!r.description) return;
6885
+ const key = `${r.table_schema}.${r.table_name}.${r.column_name}`;
6886
+ const trimmed = r.description.trim();
6887
+ if (!trimmed) return;
6888
+ columnComments.set(key, trimmed);
6889
+ });
6807
6890
  const qbPk = new SelectQueryBuilder(PgKeyColumnUsage).select({
6808
6891
  table_schema: PgKeyColumnUsage.columns.table_schema,
6809
6892
  table_name: PgKeyColumnUsage.columns.table_name,
@@ -6831,7 +6914,9 @@ var postgresIntrospector = {
6831
6914
  constraint_name: PgKeyColumnUsage.columns.constraint_name,
6832
6915
  foreign_table_schema: PgConstraintColumnUsage.columns.table_schema,
6833
6916
  foreign_table_name: PgConstraintColumnUsage.columns.table_name,
6834
- foreign_column_name: PgConstraintColumnUsage.columns.column_name
6917
+ foreign_column_name: PgConstraintColumnUsage.columns.column_name,
6918
+ delete_rule: PgReferentialConstraints.columns.delete_rule,
6919
+ update_rule: PgReferentialConstraints.columns.update_rule
6835
6920
  }).innerJoin(PgTableConstraints, eq(PgTableConstraints.columns.constraint_name, PgKeyColumnUsage.columns.constraint_name)).innerJoin(PgConstraintColumnUsage, eq(PgConstraintColumnUsage.columns.constraint_name, PgTableConstraints.columns.constraint_name)).innerJoin(PgReferentialConstraints, eq(PgReferentialConstraints.columns.constraint_name, PgTableConstraints.columns.constraint_name)).where(eq(PgTableConstraints.columns.constraint_type, "FOREIGN KEY")).where(eq(PgKeyColumnUsage.columns.table_schema, schema));
6836
6921
  const fkRows = await runSelect(qbFk, ctx);
6837
6922
  const fkMap = /* @__PURE__ */ new Map();
@@ -6841,8 +6926,8 @@ var postgresIntrospector = {
6841
6926
  existing.push({
6842
6927
  table: `${r.foreign_table_schema}.${r.foreign_table_name}`,
6843
6928
  column: r.foreign_column_name,
6844
- onDelete: void 0,
6845
- onUpdate: void 0
6929
+ onDelete: r.delete_rule,
6930
+ onUpdate: r.update_rule
6846
6931
  });
6847
6932
  fkMap.set(key, existing);
6848
6933
  }
@@ -6946,12 +7031,15 @@ var postgresIntrospector = {
6946
7031
  });
6947
7032
  }
6948
7033
  const cols = tablesByKey.get(key);
7034
+ const commentKey = `${r.table_schema}.${r.table_name}.${r.column_name}`;
7035
+ const columnComment = columnComments.get(commentKey);
6949
7036
  const fk = fkMap.get(`${r.table_schema}.${r.table_name}.${r.column_name}`)?.[0];
6950
7037
  const column = {
6951
7038
  name: r.column_name,
6952
7039
  type: r.data_type,
6953
7040
  notNull: r.is_nullable === "NO",
6954
7041
  default: r.column_default ?? void 0,
7042
+ comment: columnComment ?? void 0,
6955
7043
  references: fk ? {
6956
7044
  table: fk.table,
6957
7045
  column: fk.column,
@@ -6979,32 +7067,252 @@ var postgresIntrospector = {
6979
7067
  }
6980
7068
  };
6981
7069
 
7070
+ // src/core/ddl/introspect/catalogs/mysql.ts
7071
+ var INFORMATION_SCHEMA = "information_schema";
7072
+ var InformationSchemaTables = defineTable(
7073
+ "tables",
7074
+ {
7075
+ table_schema: col.varchar(255),
7076
+ table_name: col.varchar(255),
7077
+ table_comment: col.varchar(1024)
7078
+ },
7079
+ {},
7080
+ void 0,
7081
+ { schema: INFORMATION_SCHEMA }
7082
+ );
7083
+ var InformationSchemaColumns = defineTable(
7084
+ "columns",
7085
+ {
7086
+ table_schema: col.varchar(255),
7087
+ table_name: col.varchar(255),
7088
+ column_name: col.varchar(255),
7089
+ column_type: col.varchar(255),
7090
+ data_type: col.varchar(255),
7091
+ is_nullable: col.varchar(3),
7092
+ column_default: col.varchar(1024),
7093
+ extra: col.varchar(255),
7094
+ column_comment: col.varchar(1024),
7095
+ ordinal_position: col.int()
7096
+ },
7097
+ {},
7098
+ void 0,
7099
+ { schema: INFORMATION_SCHEMA }
7100
+ );
7101
+ var InformationSchemaKeyColumnUsage = defineTable(
7102
+ "key_column_usage",
7103
+ {
7104
+ constraint_schema: col.varchar(255),
7105
+ constraint_name: col.varchar(255),
7106
+ table_schema: col.varchar(255),
7107
+ table_name: col.varchar(255),
7108
+ column_name: col.varchar(255),
7109
+ ordinal_position: col.int(),
7110
+ referenced_table_schema: col.varchar(255),
7111
+ referenced_table_name: col.varchar(255),
7112
+ referenced_column_name: col.varchar(255)
7113
+ },
7114
+ {},
7115
+ void 0,
7116
+ { schema: INFORMATION_SCHEMA }
7117
+ );
7118
+ var InformationSchemaReferentialConstraints = defineTable(
7119
+ "referential_constraints",
7120
+ {
7121
+ constraint_schema: col.varchar(255),
7122
+ constraint_name: col.varchar(255),
7123
+ delete_rule: col.varchar(255),
7124
+ update_rule: col.varchar(255)
7125
+ },
7126
+ {},
7127
+ void 0,
7128
+ { schema: INFORMATION_SCHEMA }
7129
+ );
7130
+ var InformationSchemaStatistics = defineTable(
7131
+ "statistics",
7132
+ {
7133
+ table_schema: col.varchar(255),
7134
+ table_name: col.varchar(255),
7135
+ index_name: col.varchar(255),
7136
+ non_unique: col.int(),
7137
+ column_name: col.varchar(255),
7138
+ seq_in_index: col.int()
7139
+ },
7140
+ {},
7141
+ void 0,
7142
+ { schema: INFORMATION_SCHEMA }
7143
+ );
7144
+
6982
7145
  // src/core/ddl/introspect/mysql.ts
7146
+ var tableNode = (table, alias) => ({
7147
+ type: "Table",
7148
+ name: table.name,
7149
+ schema: table.schema,
7150
+ alias
7151
+ });
7152
+ var columnNode = (table, name, alias) => ({
7153
+ type: "Column",
7154
+ table,
7155
+ name,
7156
+ alias
7157
+ });
7158
+ var combineConditions = (...expressions) => {
7159
+ const filtered = expressions.filter(Boolean);
7160
+ if (!filtered.length) return void 0;
7161
+ if (filtered.length === 1) return filtered[0];
7162
+ return and(...filtered);
7163
+ };
7164
+ var databaseFunction = {
7165
+ type: "Function",
7166
+ name: "DATABASE",
7167
+ fn: "DATABASE",
7168
+ args: []
7169
+ };
6983
7170
  var mysqlIntrospector = {
6984
7171
  async introspect(ctx, options) {
6985
7172
  const schema = options.schema;
6986
- const filterClause = schema ? "table_schema = ?" : "table_schema = database()";
6987
- const params = schema ? [schema] : [];
6988
- const columnRows = await queryRows(
6989
- ctx.executor,
6990
- `
6991
- SELECT table_schema, table_name, column_name, data_type, is_nullable, column_default, extra
6992
- FROM information_schema.columns
6993
- WHERE ${filterClause}
6994
- ORDER BY table_name, ordinal_position
6995
- `,
6996
- params
6997
- );
6998
- const pkRows = await queryRows(
6999
- ctx.executor,
7000
- `
7001
- SELECT table_schema, table_name, column_name
7002
- FROM information_schema.key_column_usage
7003
- WHERE constraint_name = 'PRIMARY' AND ${filterClause}
7004
- ORDER BY ordinal_position
7005
- `,
7006
- params
7007
- );
7173
+ const buildSchemaCondition = (alias) => schema ? eq(columnNode(alias, "table_schema"), schema) : eq(columnNode(alias, "table_schema"), databaseFunction);
7174
+ const tablesQuery = {
7175
+ type: "SelectQuery",
7176
+ from: tableNode(InformationSchemaTables, "t"),
7177
+ columns: [
7178
+ columnNode("t", "table_schema"),
7179
+ columnNode("t", "table_name"),
7180
+ columnNode("t", "table_comment")
7181
+ ],
7182
+ joins: [],
7183
+ where: buildSchemaCondition("t")
7184
+ };
7185
+ const columnsQuery = {
7186
+ type: "SelectQuery",
7187
+ from: tableNode(InformationSchemaColumns, "c"),
7188
+ columns: [
7189
+ columnNode("c", "table_schema"),
7190
+ columnNode("c", "table_name"),
7191
+ columnNode("c", "column_name"),
7192
+ columnNode("c", "column_type"),
7193
+ columnNode("c", "data_type"),
7194
+ columnNode("c", "is_nullable"),
7195
+ columnNode("c", "column_default"),
7196
+ columnNode("c", "extra"),
7197
+ columnNode("c", "column_comment")
7198
+ ],
7199
+ joins: [],
7200
+ where: buildSchemaCondition("c"),
7201
+ orderBy: [
7202
+ {
7203
+ type: "OrderBy",
7204
+ term: columnNode("c", "table_name"),
7205
+ direction: "ASC"
7206
+ },
7207
+ {
7208
+ type: "OrderBy",
7209
+ term: columnNode("c", "ordinal_position"),
7210
+ direction: "ASC"
7211
+ }
7212
+ ]
7213
+ };
7214
+ const pkQuery = {
7215
+ type: "SelectQuery",
7216
+ from: tableNode(InformationSchemaKeyColumnUsage, "kcu"),
7217
+ columns: [
7218
+ columnNode("kcu", "table_schema"),
7219
+ columnNode("kcu", "table_name"),
7220
+ columnNode("kcu", "column_name")
7221
+ ],
7222
+ joins: [],
7223
+ where: combineConditions(
7224
+ eq(columnNode("kcu", "constraint_name"), "PRIMARY"),
7225
+ buildSchemaCondition("kcu")
7226
+ ),
7227
+ orderBy: [
7228
+ {
7229
+ type: "OrderBy",
7230
+ term: columnNode("kcu", "ordinal_position"),
7231
+ direction: "ASC"
7232
+ }
7233
+ ]
7234
+ };
7235
+ const fkQuery = {
7236
+ type: "SelectQuery",
7237
+ from: tableNode(InformationSchemaKeyColumnUsage, "kcu"),
7238
+ columns: [
7239
+ columnNode("kcu", "table_schema"),
7240
+ columnNode("kcu", "table_name"),
7241
+ columnNode("kcu", "column_name"),
7242
+ columnNode("kcu", "constraint_name"),
7243
+ columnNode("kcu", "referenced_table_schema"),
7244
+ columnNode("kcu", "referenced_table_name"),
7245
+ columnNode("kcu", "referenced_column_name"),
7246
+ columnNode("rc", "delete_rule"),
7247
+ columnNode("rc", "update_rule")
7248
+ ],
7249
+ joins: [
7250
+ {
7251
+ type: "Join",
7252
+ kind: "INNER",
7253
+ table: tableNode(InformationSchemaReferentialConstraints, "rc"),
7254
+ condition: and(
7255
+ eq({ table: "rc", name: "constraint_schema" }, { table: "kcu", name: "constraint_schema" }),
7256
+ eq({ table: "rc", name: "constraint_name" }, { table: "kcu", name: "constraint_name" })
7257
+ )
7258
+ }
7259
+ ],
7260
+ where: combineConditions(
7261
+ isNotNull(columnNode("kcu", "referenced_table_name")),
7262
+ buildSchemaCondition("kcu")
7263
+ ),
7264
+ orderBy: [
7265
+ {
7266
+ type: "OrderBy",
7267
+ term: columnNode("kcu", "table_name"),
7268
+ direction: "ASC"
7269
+ },
7270
+ {
7271
+ type: "OrderBy",
7272
+ term: columnNode("kcu", "ordinal_position"),
7273
+ direction: "ASC"
7274
+ }
7275
+ ]
7276
+ };
7277
+ const indexQuery = {
7278
+ type: "SelectQuery",
7279
+ from: tableNode(InformationSchemaStatistics, "stats"),
7280
+ columns: [
7281
+ columnNode("stats", "table_schema"),
7282
+ columnNode("stats", "table_name"),
7283
+ columnNode("stats", "index_name"),
7284
+ columnNode("stats", "non_unique"),
7285
+ {
7286
+ ...groupConcat(columnNode("stats", "column_name"), {
7287
+ orderBy: [{ column: columnNode("stats", "seq_in_index") }]
7288
+ }),
7289
+ alias: "cols"
7290
+ }
7291
+ ],
7292
+ joins: [],
7293
+ where: combineConditions(
7294
+ neq(columnNode("stats", "index_name"), "PRIMARY"),
7295
+ buildSchemaCondition("stats")
7296
+ ),
7297
+ groupBy: [
7298
+ columnNode("stats", "table_schema"),
7299
+ columnNode("stats", "table_name"),
7300
+ columnNode("stats", "index_name"),
7301
+ columnNode("stats", "non_unique")
7302
+ ]
7303
+ };
7304
+ const tableRows = await runSelectNode(tablesQuery, ctx);
7305
+ const columnRows = await runSelectNode(columnsQuery, ctx);
7306
+ const pkRows = await runSelectNode(pkQuery, ctx);
7307
+ const fkRows = await runSelectNode(fkQuery, ctx);
7308
+ const indexRows = await runSelectNode(indexQuery, ctx);
7309
+ const tableComments = /* @__PURE__ */ new Map();
7310
+ tableRows.forEach((r) => {
7311
+ const key = `${r.table_schema}.${r.table_name}`;
7312
+ if (r.table_comment) {
7313
+ tableComments.set(key, r.table_comment);
7314
+ }
7315
+ });
7008
7316
  const pkMap = /* @__PURE__ */ new Map();
7009
7317
  pkRows.forEach((r) => {
7010
7318
  const key = `${r.table_schema}.${r.table_name}`;
@@ -7012,21 +7320,19 @@ var mysqlIntrospector = {
7012
7320
  list.push(r.column_name);
7013
7321
  pkMap.set(key, list);
7014
7322
  });
7015
- const indexRows = await queryRows(
7016
- ctx.executor,
7017
- `
7018
- SELECT
7019
- table_schema,
7020
- table_name,
7021
- index_name,
7022
- non_unique,
7023
- GROUP_CONCAT(column_name ORDER BY seq_in_index) AS cols
7024
- FROM information_schema.statistics
7025
- WHERE ${filterClause} AND index_name <> 'PRIMARY'
7026
- GROUP BY table_schema, table_name, index_name, non_unique
7027
- `,
7028
- params
7029
- );
7323
+ const fkMap = /* @__PURE__ */ new Map();
7324
+ fkRows.forEach((r) => {
7325
+ const key = `${r.table_schema}.${r.table_name}.${r.column_name}`;
7326
+ const list = fkMap.get(key) || [];
7327
+ list.push({
7328
+ table: `${r.referenced_table_schema}.${r.referenced_table_name}`,
7329
+ column: r.referenced_column_name,
7330
+ onDelete: r.delete_rule,
7331
+ onUpdate: r.update_rule,
7332
+ name: r.constraint_name
7333
+ });
7334
+ fkMap.set(key, list);
7335
+ });
7030
7336
  const tablesByKey = /* @__PURE__ */ new Map();
7031
7337
  columnRows.forEach((r) => {
7032
7338
  const key = `${r.table_schema}.${r.table_name}`;
@@ -7037,18 +7343,32 @@ var mysqlIntrospector = {
7037
7343
  schema: r.table_schema,
7038
7344
  columns: [],
7039
7345
  primaryKey: pkMap.get(key) || [],
7040
- indexes: []
7346
+ indexes: [],
7347
+ comment: tableComments.get(key) || void 0
7041
7348
  });
7042
7349
  }
7043
- const cols = tablesByKey.get(key);
7350
+ const table = tablesByKey.get(key);
7351
+ const columnType = r.column_type || r.data_type;
7352
+ const comment = r.column_comment?.trim() ? r.column_comment : void 0;
7044
7353
  const column = {
7045
7354
  name: r.column_name,
7046
- type: r.data_type,
7355
+ type: columnType,
7047
7356
  notNull: r.is_nullable === "NO",
7048
7357
  default: r.column_default ?? void 0,
7049
- autoIncrement: typeof r.extra === "string" && r.extra.includes("auto_increment")
7358
+ autoIncrement: typeof r.extra === "string" && r.extra.includes("auto_increment"),
7359
+ comment
7050
7360
  };
7051
- cols.columns.push(column);
7361
+ const fk = fkMap.get(`${key}.${r.column_name}`)?.[0];
7362
+ if (fk) {
7363
+ column.references = {
7364
+ table: fk.table,
7365
+ column: fk.column,
7366
+ onDelete: fk.onDelete,
7367
+ onUpdate: fk.onUpdate,
7368
+ name: fk.name
7369
+ };
7370
+ }
7371
+ table.columns.push(column);
7052
7372
  });
7053
7373
  indexRows.forEach((r) => {
7054
7374
  const key = `${r.table_schema}.${r.table_name}`;
@@ -7076,43 +7396,79 @@ var toReferentialAction = (value) => {
7076
7396
  }
7077
7397
  return void 0;
7078
7398
  };
7079
- var escapeSingleQuotes = (name) => name.replace(/'/g, "''");
7399
+ var columnNode2 = (table, name, alias) => ({
7400
+ type: "Column",
7401
+ table,
7402
+ name,
7403
+ alias
7404
+ });
7405
+ var buildPragmaQuery = (name, table, alias, columnAliases) => ({
7406
+ type: "SelectQuery",
7407
+ from: fnTable(name, [valueToOperand(table)], alias, { columnAliases }),
7408
+ columns: columnAliases.map((column) => columnNode2(alias, column)),
7409
+ joins: []
7410
+ });
7411
+ var runPragma = async (name, table, alias, columnAliases, ctx) => {
7412
+ const query = buildPragmaQuery(name, table, alias, columnAliases);
7413
+ return await runSelectNode(query, ctx);
7414
+ };
7080
7415
  var sqliteIntrospector = {
7081
- /**
7082
- * Introspects the SQLite database schema by querying sqlite_master and various PRAGMAs.
7083
- * @param ctx - The database execution context containing the DbExecutor.
7084
- * @param options - Options controlling which tables and schemas to include.
7085
- * @returns A promise that resolves to the introspected DatabaseSchema.
7086
- */
7087
7416
  async introspect(ctx, options) {
7417
+ const alias = "sqlite_master";
7418
+ const tablesQuery = {
7419
+ type: "SelectQuery",
7420
+ from: { type: "Table", name: "sqlite_master" },
7421
+ columns: [columnNode2(alias, "name")],
7422
+ joins: [],
7423
+ where: and(
7424
+ eq(columnNode2(alias, "type"), "table"),
7425
+ notLike(columnNode2(alias, "name"), "sqlite_%")
7426
+ )
7427
+ };
7428
+ const tableRows = await runSelectNode(tablesQuery, ctx);
7088
7429
  const tables = [];
7089
- const tableRows = await queryRows(
7090
- ctx.executor,
7091
- `SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%';`
7092
- );
7093
7430
  for (const row of tableRows) {
7094
- const name = row.name;
7095
- if (!shouldIncludeTable(name, options)) continue;
7096
- const table = { name, columns: [], primaryKey: [], indexes: [] };
7097
- const cols = await queryRows(ctx.executor, `PRAGMA table_info('${escapeSingleQuotes(name)}');`);
7098
- cols.forEach((c) => {
7099
- table.columns.push({
7100
- name: c.name,
7101
- type: c.type,
7102
- notNull: c.notnull === 1,
7103
- default: c.dflt_value ?? void 0,
7431
+ const tableName = row.name;
7432
+ if (!shouldIncludeTable(tableName, options)) continue;
7433
+ const tableInfo = await runPragma(
7434
+ "pragma_table_info",
7435
+ tableName,
7436
+ "ti",
7437
+ ["cid", "name", "type", "notnull", "dflt_value", "pk"],
7438
+ ctx
7439
+ );
7440
+ const foreignKeys = await runPragma(
7441
+ "pragma_foreign_key_list",
7442
+ tableName,
7443
+ "fk",
7444
+ ["id", "seq", "table", "from", "to", "on_update", "on_delete", "match"],
7445
+ ctx
7446
+ );
7447
+ const indexList = await runPragma(
7448
+ "pragma_index_list",
7449
+ tableName,
7450
+ "idx",
7451
+ ["seq", "name", "unique"],
7452
+ ctx
7453
+ );
7454
+ const tableEntry = { name: tableName, columns: [], primaryKey: [], indexes: [] };
7455
+ tableInfo.forEach((info) => {
7456
+ tableEntry.columns.push({
7457
+ name: info.name,
7458
+ type: info.type,
7459
+ notNull: info.notnull === 1,
7460
+ default: info.dflt_value ?? void 0,
7104
7461
  autoIncrement: false
7105
7462
  });
7106
- if (c.pk && c.pk > 0) {
7107
- table.primaryKey = table.primaryKey || [];
7108
- table.primaryKey.push(c.name);
7463
+ if (info.pk && info.pk > 0) {
7464
+ tableEntry.primaryKey = tableEntry.primaryKey || [];
7465
+ tableEntry.primaryKey.push(info.name);
7109
7466
  }
7110
7467
  });
7111
- const fkRows = await queryRows(ctx.executor, `PRAGMA foreign_key_list('${escapeSingleQuotes(name)}');`);
7112
- fkRows.forEach((fk) => {
7113
- const col2 = table.columns.find((c) => c.name === fk.from);
7114
- if (col2) {
7115
- col2.references = {
7468
+ foreignKeys.forEach((fk) => {
7469
+ const column = tableEntry.columns.find((col2) => col2.name === fk.from);
7470
+ if (column) {
7471
+ column.references = {
7116
7472
  table: fk.table,
7117
7473
  column: fk.to,
7118
7474
  onDelete: toReferentialAction(fk.on_delete),
@@ -7120,72 +7476,529 @@ var sqliteIntrospector = {
7120
7476
  };
7121
7477
  }
7122
7478
  });
7123
- const idxList = await queryRows(ctx.executor, `PRAGMA index_list('${escapeSingleQuotes(name)}');`);
7124
- for (const idx of idxList) {
7125
- const idxName = idx.name;
7126
- const columnsInfo = await queryRows(ctx.executor, `PRAGMA index_info('${escapeSingleQuotes(idxName)}');`);
7479
+ for (const idx of indexList) {
7480
+ if (!idx.name) continue;
7481
+ const indexColumns = await runPragma(
7482
+ "pragma_index_info",
7483
+ idx.name,
7484
+ "info",
7485
+ ["seqno", "cid", "name"],
7486
+ ctx
7487
+ );
7127
7488
  const idxEntry = {
7128
- name: idxName,
7129
- columns: columnsInfo.map((ci) => ({ column: ci.name })),
7489
+ name: idx.name,
7490
+ columns: indexColumns.map((col2) => ({ column: col2.name })),
7130
7491
  unique: idx.unique === 1
7131
7492
  };
7132
- table.indexes.push(idxEntry);
7493
+ tableEntry.indexes.push(idxEntry);
7133
7494
  }
7134
- tables.push(table);
7495
+ tables.push(tableEntry);
7135
7496
  }
7136
7497
  return { tables };
7137
7498
  }
7138
7499
  };
7139
7500
 
7501
+ // src/core/ddl/introspect/catalogs/mssql.ts
7502
+ var SysColumns = defineTable(
7503
+ "columns",
7504
+ {
7505
+ object_id: col.int(),
7506
+ name: col.varchar(255),
7507
+ column_id: col.int(),
7508
+ max_length: col.int(),
7509
+ precision: col.int(),
7510
+ scale: col.int(),
7511
+ is_nullable: col.boolean(),
7512
+ is_identity: col.boolean(),
7513
+ default_object_id: col.int(),
7514
+ user_type_id: col.int()
7515
+ },
7516
+ {},
7517
+ void 0,
7518
+ { schema: "sys" }
7519
+ );
7520
+ var SysTables = defineTable(
7521
+ "tables",
7522
+ {
7523
+ object_id: col.int(),
7524
+ name: col.varchar(255),
7525
+ schema_id: col.int(),
7526
+ is_ms_shipped: col.boolean()
7527
+ },
7528
+ {},
7529
+ void 0,
7530
+ { schema: "sys" }
7531
+ );
7532
+ var SysSchemas = defineTable(
7533
+ "schemas",
7534
+ {
7535
+ schema_id: col.int(),
7536
+ name: col.varchar(255)
7537
+ },
7538
+ {},
7539
+ void 0,
7540
+ { schema: "sys" }
7541
+ );
7542
+ var SysTypes = defineTable(
7543
+ "types",
7544
+ {
7545
+ user_type_id: col.int(),
7546
+ name: col.varchar(255)
7547
+ },
7548
+ {},
7549
+ void 0,
7550
+ { schema: "sys" }
7551
+ );
7552
+ var SysIndexes = defineTable(
7553
+ "indexes",
7554
+ {
7555
+ object_id: col.int(),
7556
+ index_id: col.int(),
7557
+ name: col.varchar(255),
7558
+ is_primary_key: col.boolean(),
7559
+ is_unique: col.boolean(),
7560
+ has_filter: col.boolean(),
7561
+ filter_definition: col.varchar(1024),
7562
+ is_hypothetical: col.boolean()
7563
+ },
7564
+ {},
7565
+ void 0,
7566
+ { schema: "sys" }
7567
+ );
7568
+ var SysIndexColumns = defineTable(
7569
+ "index_columns",
7570
+ {
7571
+ object_id: col.int(),
7572
+ index_id: col.int(),
7573
+ column_id: col.int(),
7574
+ key_ordinal: col.int()
7575
+ },
7576
+ {},
7577
+ void 0,
7578
+ { schema: "sys" }
7579
+ );
7580
+ var SysForeignKeys = defineTable(
7581
+ "foreign_keys",
7582
+ {
7583
+ object_id: col.int(),
7584
+ name: col.varchar(255),
7585
+ delete_referential_action_desc: col.varchar(64),
7586
+ update_referential_action_desc: col.varchar(64)
7587
+ },
7588
+ {},
7589
+ void 0,
7590
+ { schema: "sys" }
7591
+ );
7592
+ var SysForeignKeyColumns = defineTable(
7593
+ "foreign_key_columns",
7594
+ {
7595
+ constraint_object_id: col.int(),
7596
+ parent_object_id: col.int(),
7597
+ parent_column_id: col.int(),
7598
+ referenced_object_id: col.int(),
7599
+ referenced_column_id: col.int(),
7600
+ constraint_column_id: col.int()
7601
+ },
7602
+ {},
7603
+ void 0,
7604
+ { schema: "sys" }
7605
+ );
7606
+
7607
+ // src/core/functions/text.ts
7608
+ var isColumnDef = (val) => !!val && typeof val === "object" && "type" in val && "name" in val;
7609
+ var toOperand2 = (input) => {
7610
+ if (isOperandNode(input)) return input;
7611
+ if (isColumnDef(input)) return columnOperand(input);
7612
+ return valueToOperand(input);
7613
+ };
7614
+ var fn = (key, args) => ({
7615
+ type: "Function",
7616
+ name: key,
7617
+ fn: key,
7618
+ args: args.map(toOperand2)
7619
+ });
7620
+ var lower = (value) => fn("LOWER", [value]);
7621
+ var upper = (value) => fn("UPPER", [value]);
7622
+ var ascii = (value) => fn("ASCII", [value]);
7623
+ var char = (...codes) => {
7624
+ if (codes.length === 0) throw new Error("char() expects at least 1 argument");
7625
+ return fn("CHAR", codes);
7626
+ };
7627
+ var charLength = (value) => fn("CHAR_LENGTH", [value]);
7628
+ var length = (value) => fn("LENGTH", [value]);
7629
+ var trim = (value, chars) => chars === void 0 ? fn("TRIM", [value]) : fn("TRIM", [value, chars]);
7630
+ var ltrim = (value) => fn("LTRIM", [value]);
7631
+ var rtrim = (value) => fn("RTRIM", [value]);
7632
+ var concat = (...args) => {
7633
+ if (args.length < 2) throw new Error("concat() expects at least 2 arguments");
7634
+ return fn("CONCAT", args);
7635
+ };
7636
+ var concatWs = (separator, ...args) => {
7637
+ if (args.length < 1) throw new Error("concatWs() expects at least 2 arguments including the separator");
7638
+ return fn("CONCAT_WS", [separator, ...args]);
7639
+ };
7640
+ var substr = (value, start, length2) => length2 === void 0 ? fn("SUBSTR", [value, start]) : fn("SUBSTR", [value, start, length2]);
7641
+ var left = (value, len) => fn("LEFT", [value, len]);
7642
+ var right = (value, len) => fn("RIGHT", [value, len]);
7643
+ var position = (substring, value) => fn("POSITION", [substring, value]);
7644
+ var instr = (value, substring) => fn("INSTR", [value, substring]);
7645
+ var locate = (substring, value, start) => start === void 0 ? fn("LOCATE", [substring, value]) : fn("LOCATE", [substring, value, start]);
7646
+ var replace = (value, search, replacement) => fn("REPLACE", [value, search, replacement]);
7647
+ var repeat = (value, count2) => fn("REPEAT", [value, count2]);
7648
+ var lpad = (value, len, pad) => fn("LPAD", [value, len, pad]);
7649
+ var rpad = (value, len, pad) => fn("RPAD", [value, len, pad]);
7650
+ var space = (count2) => fn("SPACE", [count2]);
7651
+
7652
+ // src/core/ddl/introspect/functions/mssql.ts
7653
+ var isColumnReference = (value) => typeof value === "object" && value !== null && !("type" in value) && "name" in value && typeof value.name === "string";
7654
+ var toOperandNode2 = (value) => {
7655
+ if (isOperandNode(value)) return value;
7656
+ if (isColumnReference(value)) return columnOperand(value);
7657
+ return valueToOperand(value);
7658
+ };
7659
+ var fn2 = (name, args) => ({
7660
+ type: "Function",
7661
+ name,
7662
+ fn: name,
7663
+ args: args.map((arg) => toOperandNode2(arg))
7664
+ });
7665
+ var CHAR_TYPES = ["varchar", "char", "varbinary", "binary", "nvarchar", "nchar"];
7666
+ var DECIMAL_TYPES = ["decimal", "numeric"];
7667
+ var objectDefinition = (objectId) => fn2("OBJECT_DEFINITION", [objectId]);
7668
+ var buildMssqlDataType = (typeName, maxLength, precision, scale) => {
7669
+ const typeOperand = toOperandNode2(typeName);
7670
+ const maxLenOperand = toOperandNode2(maxLength);
7671
+ const precisionOperand = toOperandNode2(precision);
7672
+ const scaleOperand = toOperandNode2(scale);
7673
+ const typeLower = lower(typeOperand);
7674
+ const lengthCase = caseWhen(
7675
+ [
7676
+ {
7677
+ when: eq(maxLenOperand, -1),
7678
+ then: "max"
7679
+ },
7680
+ {
7681
+ when: inList(typeLower, ["nvarchar", "nchar"]),
7682
+ then: cast(div(maxLenOperand, 2), "varchar(10)")
7683
+ }
7684
+ ],
7685
+ cast(maxLenOperand, "varchar(10)")
7686
+ );
7687
+ const charSuffix = concat("(", lengthCase, ")");
7688
+ const decimalSuffix = concat(
7689
+ "(",
7690
+ cast(precisionOperand, "varchar(10)"),
7691
+ ",",
7692
+ cast(scaleOperand, "varchar(10)"),
7693
+ ")"
7694
+ );
7695
+ const suffix = caseWhen(
7696
+ [
7697
+ { when: inList(typeLower, CHAR_TYPES), then: charSuffix },
7698
+ { when: inList(typeLower, DECIMAL_TYPES), then: decimalSuffix }
7699
+ ],
7700
+ ""
7701
+ );
7702
+ return concat(typeLower, suffix);
7703
+ };
7704
+
7140
7705
  // src/core/ddl/introspect/mssql.ts
7706
+ var normalizeReferentialAction = (value) => {
7707
+ if (!value) return void 0;
7708
+ const normalized = value.replace(/_/g, " ").toUpperCase();
7709
+ const allowed = ["NO ACTION", "RESTRICT", "CASCADE", "SET NULL", "SET DEFAULT"];
7710
+ return allowed.includes(normalized) ? normalized : void 0;
7711
+ };
7712
+ var tableNode2 = (table, alias) => ({
7713
+ type: "Table",
7714
+ name: table.name,
7715
+ schema: table.schema,
7716
+ alias
7717
+ });
7718
+ var columnNode3 = (table, name, alias) => ({
7719
+ type: "Column",
7720
+ table,
7721
+ name,
7722
+ alias
7723
+ });
7724
+ var combineConditions2 = (...expressions) => {
7725
+ const filtered = expressions.filter(Boolean);
7726
+ if (!filtered.length) return void 0;
7727
+ if (filtered.length === 1) return filtered[0];
7728
+ return and(...filtered);
7729
+ };
7141
7730
  var mssqlIntrospector = {
7142
- /**
7143
- * Introspects the MSSQL database schema.
7144
- * @param ctx - The introspection context containing the database executor.
7145
- * @param options - Options for introspection, such as schema filter.
7146
- * @returns A promise that resolves to the introspected database schema.
7147
- */
7148
7731
  async introspect(ctx, options) {
7149
7732
  const schema = options.schema;
7150
- const filterSchema = schema ? "sch.name = @p1" : "1=1";
7151
- const params = schema ? [schema] : [];
7152
- const columnRows = await queryRows(
7153
- ctx.executor,
7154
- `
7155
- SELECT
7156
- sch.name AS table_schema,
7157
- t.name AS table_name,
7158
- c.name AS column_name,
7159
- ty.name AS data_type,
7160
- c.is_nullable,
7161
- c.is_identity,
7162
- object_definition(c.default_object_id) AS column_default
7163
- FROM sys.columns c
7164
- JOIN sys.tables t ON t.object_id = c.object_id
7165
- JOIN sys.schemas sch ON sch.schema_id = t.schema_id
7166
- JOIN sys.types ty ON ty.user_type_id = c.user_type_id
7167
- WHERE t.is_ms_shipped = 0 AND ${filterSchema}
7168
- `,
7169
- params
7170
- );
7171
- const pkRows = await queryRows(
7172
- ctx.executor,
7173
- `
7174
- SELECT
7175
- sch.name AS table_schema,
7176
- t.name AS table_name,
7177
- c.name AS column_name,
7178
- ic.key_ordinal
7179
- FROM sys.indexes i
7180
- JOIN sys.index_columns ic ON ic.object_id = i.object_id AND ic.index_id = i.index_id
7181
- JOIN sys.columns c ON c.object_id = ic.object_id AND c.column_id = ic.column_id
7182
- JOIN sys.tables t ON t.object_id = i.object_id
7183
- JOIN sys.schemas sch ON sch.schema_id = t.schema_id
7184
- WHERE i.is_primary_key = 1 AND ${filterSchema}
7185
- ORDER BY ic.key_ordinal
7186
- `,
7187
- params
7733
+ const schemaCondition = schema ? eq(columnNode3("sch", "name"), schema) : void 0;
7734
+ const dataTypeExpression = buildMssqlDataType(
7735
+ { table: "ty", name: "name" },
7736
+ { table: "c", name: "max_length" },
7737
+ { table: "c", name: "precision" },
7738
+ { table: "c", name: "scale" }
7188
7739
  );
7740
+ const defaultExpression = objectDefinition({ table: "c", name: "default_object_id" });
7741
+ const columnsQuery = {
7742
+ type: "SelectQuery",
7743
+ from: tableNode2(SysColumns, "c"),
7744
+ columns: [
7745
+ columnNode3("sch", "name", "table_schema"),
7746
+ columnNode3("t", "name", "table_name"),
7747
+ columnNode3("c", "name", "column_name"),
7748
+ { ...dataTypeExpression, alias: "data_type" },
7749
+ columnNode3("c", "is_nullable"),
7750
+ columnNode3("c", "is_identity"),
7751
+ { ...defaultExpression, alias: "column_default" }
7752
+ ],
7753
+ joins: [
7754
+ {
7755
+ type: "Join",
7756
+ kind: "INNER",
7757
+ table: tableNode2(SysTables, "t"),
7758
+ condition: eq({ table: "t", name: "object_id" }, { table: "c", name: "object_id" })
7759
+ },
7760
+ {
7761
+ type: "Join",
7762
+ kind: "INNER",
7763
+ table: tableNode2(SysSchemas, "sch"),
7764
+ condition: eq({ table: "sch", name: "schema_id" }, { table: "t", name: "schema_id" })
7765
+ },
7766
+ {
7767
+ type: "Join",
7768
+ kind: "INNER",
7769
+ table: tableNode2(SysTypes, "ty"),
7770
+ condition: eq({ table: "ty", name: "user_type_id" }, { table: "c", name: "user_type_id" })
7771
+ }
7772
+ ],
7773
+ where: combineConditions2(
7774
+ eq({ table: "t", name: "is_ms_shipped" }, 0),
7775
+ schemaCondition
7776
+ )
7777
+ };
7778
+ const pkQuery = {
7779
+ type: "SelectQuery",
7780
+ from: tableNode2(SysIndexes, "i"),
7781
+ columns: [
7782
+ columnNode3("sch", "name", "table_schema"),
7783
+ columnNode3("t", "name", "table_name"),
7784
+ columnNode3("c", "name", "column_name"),
7785
+ columnNode3("ic", "key_ordinal", "key_ordinal")
7786
+ ],
7787
+ joins: [
7788
+ {
7789
+ type: "Join",
7790
+ kind: "INNER",
7791
+ table: tableNode2(SysIndexColumns, "ic"),
7792
+ condition: and(
7793
+ eq({ table: "ic", name: "object_id" }, { table: "i", name: "object_id" }),
7794
+ eq({ table: "ic", name: "index_id" }, { table: "i", name: "index_id" })
7795
+ )
7796
+ },
7797
+ {
7798
+ type: "Join",
7799
+ kind: "INNER",
7800
+ table: tableNode2(SysColumns, "c"),
7801
+ condition: and(
7802
+ eq({ table: "c", name: "object_id" }, { table: "ic", name: "object_id" }),
7803
+ eq({ table: "c", name: "column_id" }, { table: "ic", name: "column_id" })
7804
+ )
7805
+ },
7806
+ {
7807
+ type: "Join",
7808
+ kind: "INNER",
7809
+ table: tableNode2(SysTables, "t"),
7810
+ condition: eq({ table: "t", name: "object_id" }, { table: "i", name: "object_id" })
7811
+ },
7812
+ {
7813
+ type: "Join",
7814
+ kind: "INNER",
7815
+ table: tableNode2(SysSchemas, "sch"),
7816
+ condition: eq({ table: "sch", name: "schema_id" }, { table: "t", name: "schema_id" })
7817
+ }
7818
+ ],
7819
+ where: combineConditions2(
7820
+ eq({ table: "i", name: "is_primary_key" }, 1),
7821
+ schemaCondition
7822
+ ),
7823
+ orderBy: [
7824
+ {
7825
+ type: "OrderBy",
7826
+ term: columnNode3("ic", "key_ordinal"),
7827
+ direction: "ASC"
7828
+ }
7829
+ ]
7830
+ };
7831
+ const fkQuery = {
7832
+ type: "SelectQuery",
7833
+ from: tableNode2(SysForeignKeyColumns, "fkc"),
7834
+ columns: [
7835
+ columnNode3("sch", "name", "table_schema"),
7836
+ columnNode3("t", "name", "table_name"),
7837
+ columnNode3("c", "name", "column_name"),
7838
+ columnNode3("fk", "name", "constraint_name"),
7839
+ columnNode3("rsch", "name", "referenced_schema"),
7840
+ columnNode3("rt", "name", "referenced_table"),
7841
+ columnNode3("rc", "name", "referenced_column"),
7842
+ columnNode3("fk", "delete_referential_action_desc", "delete_rule"),
7843
+ columnNode3("fk", "update_referential_action_desc", "update_rule")
7844
+ ],
7845
+ joins: [
7846
+ {
7847
+ type: "Join",
7848
+ kind: "INNER",
7849
+ table: tableNode2(SysForeignKeys, "fk"),
7850
+ condition: eq({ table: "fk", name: "object_id" }, { table: "fkc", name: "constraint_object_id" })
7851
+ },
7852
+ {
7853
+ type: "Join",
7854
+ kind: "INNER",
7855
+ table: tableNode2(SysTables, "t"),
7856
+ condition: eq({ table: "t", name: "object_id" }, { table: "fkc", name: "parent_object_id" })
7857
+ },
7858
+ {
7859
+ type: "Join",
7860
+ kind: "INNER",
7861
+ table: tableNode2(SysSchemas, "sch"),
7862
+ condition: eq({ table: "sch", name: "schema_id" }, { table: "t", name: "schema_id" })
7863
+ },
7864
+ {
7865
+ type: "Join",
7866
+ kind: "INNER",
7867
+ table: tableNode2(SysColumns, "c"),
7868
+ condition: and(
7869
+ eq({ table: "c", name: "object_id" }, { table: "fkc", name: "parent_object_id" }),
7870
+ eq({ table: "c", name: "column_id" }, { table: "fkc", name: "parent_column_id" })
7871
+ )
7872
+ },
7873
+ {
7874
+ type: "Join",
7875
+ kind: "INNER",
7876
+ table: tableNode2(SysTables, "rt"),
7877
+ condition: eq({ table: "rt", name: "object_id" }, { table: "fkc", name: "referenced_object_id" })
7878
+ },
7879
+ {
7880
+ type: "Join",
7881
+ kind: "INNER",
7882
+ table: tableNode2(SysSchemas, "rsch"),
7883
+ condition: eq({ table: "rsch", name: "schema_id" }, { table: "rt", name: "schema_id" })
7884
+ },
7885
+ {
7886
+ type: "Join",
7887
+ kind: "INNER",
7888
+ table: tableNode2(SysColumns, "rc"),
7889
+ condition: and(
7890
+ eq({ table: "rc", name: "object_id" }, { table: "fkc", name: "referenced_object_id" }),
7891
+ eq({ table: "rc", name: "column_id" }, { table: "fkc", name: "referenced_column_id" })
7892
+ )
7893
+ }
7894
+ ],
7895
+ where: combineConditions2(
7896
+ eq({ table: "t", name: "is_ms_shipped" }, 0),
7897
+ schemaCondition
7898
+ ),
7899
+ orderBy: [
7900
+ {
7901
+ type: "OrderBy",
7902
+ term: columnNode3("fk", "name"),
7903
+ direction: "ASC"
7904
+ },
7905
+ {
7906
+ type: "OrderBy",
7907
+ term: columnNode3("fkc", "constraint_column_id"),
7908
+ direction: "ASC"
7909
+ }
7910
+ ]
7911
+ };
7912
+ const indexQuery = {
7913
+ type: "SelectQuery",
7914
+ from: tableNode2(SysIndexes, "i"),
7915
+ columns: [
7916
+ columnNode3("sch", "name", "table_schema"),
7917
+ columnNode3("t", "name", "table_name"),
7918
+ columnNode3("i", "name", "index_name"),
7919
+ columnNode3("i", "is_unique"),
7920
+ columnNode3("i", "has_filter"),
7921
+ columnNode3("i", "filter_definition")
7922
+ ],
7923
+ joins: [
7924
+ {
7925
+ type: "Join",
7926
+ kind: "INNER",
7927
+ table: tableNode2(SysTables, "t"),
7928
+ condition: eq({ table: "t", name: "object_id" }, { table: "i", name: "object_id" })
7929
+ },
7930
+ {
7931
+ type: "Join",
7932
+ kind: "INNER",
7933
+ table: tableNode2(SysSchemas, "sch"),
7934
+ condition: eq({ table: "sch", name: "schema_id" }, { table: "t", name: "schema_id" })
7935
+ }
7936
+ ],
7937
+ where: combineConditions2(
7938
+ eq({ table: "i", name: "is_primary_key" }, 0),
7939
+ eq({ table: "i", name: "is_hypothetical" }, 0),
7940
+ schemaCondition
7941
+ )
7942
+ };
7943
+ const indexColumnsQuery = {
7944
+ type: "SelectQuery",
7945
+ from: tableNode2(SysIndexColumns, "ic"),
7946
+ columns: [
7947
+ columnNode3("sch", "name", "table_schema"),
7948
+ columnNode3("t", "name", "table_name"),
7949
+ columnNode3("i", "name", "index_name"),
7950
+ columnNode3("c", "name", "column_name"),
7951
+ columnNode3("ic", "key_ordinal", "key_ordinal")
7952
+ ],
7953
+ joins: [
7954
+ {
7955
+ type: "Join",
7956
+ kind: "INNER",
7957
+ table: tableNode2(SysIndexes, "i"),
7958
+ condition: and(
7959
+ eq({ table: "ic", name: "object_id" }, { table: "i", name: "object_id" }),
7960
+ eq({ table: "ic", name: "index_id" }, { table: "i", name: "index_id" })
7961
+ )
7962
+ },
7963
+ {
7964
+ type: "Join",
7965
+ kind: "INNER",
7966
+ table: tableNode2(SysColumns, "c"),
7967
+ condition: and(
7968
+ eq({ table: "c", name: "object_id" }, { table: "ic", name: "object_id" }),
7969
+ eq({ table: "c", name: "column_id" }, { table: "ic", name: "column_id" })
7970
+ )
7971
+ },
7972
+ {
7973
+ type: "Join",
7974
+ kind: "INNER",
7975
+ table: tableNode2(SysTables, "t"),
7976
+ condition: eq({ table: "t", name: "object_id" }, { table: "i", name: "object_id" })
7977
+ },
7978
+ {
7979
+ type: "Join",
7980
+ kind: "INNER",
7981
+ table: tableNode2(SysSchemas, "sch"),
7982
+ condition: eq({ table: "sch", name: "schema_id" }, { table: "t", name: "schema_id" })
7983
+ }
7984
+ ],
7985
+ where: combineConditions2(
7986
+ eq({ table: "i", name: "is_primary_key" }, 0),
7987
+ schemaCondition
7988
+ ),
7989
+ orderBy: [
7990
+ {
7991
+ type: "OrderBy",
7992
+ term: columnNode3("ic", "key_ordinal"),
7993
+ direction: "ASC"
7994
+ }
7995
+ ]
7996
+ };
7997
+ const columnRows = await runSelectNode(columnsQuery, ctx);
7998
+ const pkRows = await runSelectNode(pkQuery, ctx);
7999
+ const fkRows = await runSelectNode(fkQuery, ctx);
8000
+ const indexRows = await runSelectNode(indexQuery, ctx);
8001
+ const indexColsRows = await runSelectNode(indexColumnsQuery, ctx);
7189
8002
  const pkMap = /* @__PURE__ */ new Map();
7190
8003
  pkRows.forEach((r) => {
7191
8004
  const key = `${r.table_schema}.${r.table_name}`;
@@ -7193,42 +8006,19 @@ var mssqlIntrospector = {
7193
8006
  list.push(r.column_name);
7194
8007
  pkMap.set(key, list);
7195
8008
  });
7196
- const indexRows = await queryRows(
7197
- ctx.executor,
7198
- `
7199
- SELECT
7200
- sch.name AS table_schema,
7201
- t.name AS table_name,
7202
- i.name AS index_name,
7203
- i.is_unique,
7204
- i.has_filter,
7205
- i.filter_definition
7206
- FROM sys.indexes i
7207
- JOIN sys.tables t ON t.object_id = i.object_id
7208
- JOIN sys.schemas sch ON sch.schema_id = t.schema_id
7209
- WHERE i.is_primary_key = 0 AND i.is_hypothetical = 0 AND ${filterSchema}
7210
- `,
7211
- params
7212
- );
7213
- const indexColsRows = await queryRows(
7214
- ctx.executor,
7215
- `
7216
- SELECT
7217
- sch.name AS table_schema,
7218
- t.name AS table_name,
7219
- i.name AS index_name,
7220
- c.name AS column_name,
7221
- ic.key_ordinal
7222
- FROM sys.index_columns ic
7223
- JOIN sys.indexes i ON i.object_id = ic.object_id AND i.index_id = ic.index_id
7224
- JOIN sys.columns c ON c.object_id = ic.object_id AND c.column_id = ic.column_id
7225
- JOIN sys.tables t ON t.object_id = i.object_id
7226
- JOIN sys.schemas sch ON sch.schema_id = t.schema_id
7227
- WHERE i.is_primary_key = 0 AND ${filterSchema}
7228
- ORDER BY ic.key_ordinal
7229
- `,
7230
- params
7231
- );
8009
+ const fkMap = /* @__PURE__ */ new Map();
8010
+ fkRows.forEach((r) => {
8011
+ const key = `${r.table_schema}.${r.table_name}.${r.column_name}`;
8012
+ const list = fkMap.get(key) || [];
8013
+ list.push({
8014
+ table: `${r.referenced_schema}.${r.referenced_table}`,
8015
+ column: r.referenced_column,
8016
+ onDelete: normalizeReferentialAction(r.delete_rule),
8017
+ onUpdate: normalizeReferentialAction(r.update_rule),
8018
+ name: r.constraint_name
8019
+ });
8020
+ fkMap.set(key, list);
8021
+ });
7232
8022
  const indexColumnsMap = /* @__PURE__ */ new Map();
7233
8023
  indexColsRows.forEach((r) => {
7234
8024
  const key = `${r.table_schema}.${r.table_name}.${r.index_name}`;
@@ -7249,7 +8039,7 @@ var mssqlIntrospector = {
7249
8039
  indexes: []
7250
8040
  });
7251
8041
  }
7252
- const t = tablesByKey.get(key);
8042
+ const table = tablesByKey.get(key);
7253
8043
  const column = {
7254
8044
  name: r.column_name,
7255
8045
  type: r.data_type,
@@ -7257,7 +8047,17 @@ var mssqlIntrospector = {
7257
8047
  default: r.column_default ?? void 0,
7258
8048
  autoIncrement: !!r.is_identity
7259
8049
  };
7260
- t.columns.push(column);
8050
+ const fk = fkMap.get(`${key}.${r.column_name}`)?.[0];
8051
+ if (fk) {
8052
+ column.references = {
8053
+ table: fk.table,
8054
+ column: fk.column,
8055
+ onDelete: fk.onDelete,
8056
+ onUpdate: fk.onUpdate,
8057
+ name: fk.name
8058
+ };
8059
+ }
8060
+ table.columns.push(column);
7261
8061
  });
7262
8062
  indexRows.forEach((r) => {
7263
8063
  const key = `${r.table_schema}.${r.table_name}`;
@@ -7268,7 +8068,7 @@ var mssqlIntrospector = {
7268
8068
  name: r.index_name,
7269
8069
  columns: cols,
7270
8070
  unique: !!r.is_unique,
7271
- where: r.has_filter ? r.filter_definition : void 0
8071
+ where: r.has_filter ? r.filter_definition ?? void 0 : void 0
7272
8072
  };
7273
8073
  table.indexes = table.indexes || [];
7274
8074
  table.indexes.push(idx);
@@ -7304,51 +8104,6 @@ var introspectSchema = async (executor, dialect, options = {}) => {
7304
8104
  return handler.introspect(ctx, options);
7305
8105
  };
7306
8106
 
7307
- // src/core/functions/text.ts
7308
- var isColumnDef = (val) => !!val && typeof val === "object" && "type" in val && "name" in val;
7309
- var toOperand2 = (input) => {
7310
- if (isOperandNode(input)) return input;
7311
- if (isColumnDef(input)) return columnOperand(input);
7312
- return valueToOperand(input);
7313
- };
7314
- var fn = (key, args) => ({
7315
- type: "Function",
7316
- name: key,
7317
- fn: key,
7318
- args: args.map(toOperand2)
7319
- });
7320
- var lower = (value) => fn("LOWER", [value]);
7321
- var upper = (value) => fn("UPPER", [value]);
7322
- var ascii = (value) => fn("ASCII", [value]);
7323
- var char = (...codes) => {
7324
- if (codes.length === 0) throw new Error("char() expects at least 1 argument");
7325
- return fn("CHAR", codes);
7326
- };
7327
- var charLength = (value) => fn("CHAR_LENGTH", [value]);
7328
- var length = (value) => fn("LENGTH", [value]);
7329
- var trim = (value, chars) => chars === void 0 ? fn("TRIM", [value]) : fn("TRIM", [value, chars]);
7330
- var ltrim = (value) => fn("LTRIM", [value]);
7331
- var rtrim = (value) => fn("RTRIM", [value]);
7332
- var concat = (...args) => {
7333
- if (args.length < 2) throw new Error("concat() expects at least 2 arguments");
7334
- return fn("CONCAT", args);
7335
- };
7336
- var concatWs = (separator, ...args) => {
7337
- if (args.length < 1) throw new Error("concatWs() expects at least 2 arguments including the separator");
7338
- return fn("CONCAT_WS", [separator, ...args]);
7339
- };
7340
- var substr = (value, start, length2) => length2 === void 0 ? fn("SUBSTR", [value, start]) : fn("SUBSTR", [value, start, length2]);
7341
- var left = (value, len) => fn("LEFT", [value, len]);
7342
- var right = (value, len) => fn("RIGHT", [value, len]);
7343
- var position = (substring, value) => fn("POSITION", [substring, value]);
7344
- var instr = (value, substring) => fn("INSTR", [value, substring]);
7345
- var locate = (substring, value, start) => start === void 0 ? fn("LOCATE", [substring, value]) : fn("LOCATE", [substring, value, start]);
7346
- var replace = (value, search, replacement) => fn("REPLACE", [value, search, replacement]);
7347
- var repeat = (value, count2) => fn("REPEAT", [value, count2]);
7348
- var lpad = (value, len, pad) => fn("LPAD", [value, len, pad]);
7349
- var rpad = (value, len, pad) => fn("RPAD", [value, len, pad]);
7350
- var space = (count2) => fn("SPACE", [count2]);
7351
-
7352
8107
  // src/core/functions/numeric.ts
7353
8108
  var isColumnDef2 = (val) => !!val && typeof val === "object" && "type" in val && "name" in val;
7354
8109
  var toOperand3 = (input) => {
@@ -7356,42 +8111,42 @@ var toOperand3 = (input) => {
7356
8111
  if (isColumnDef2(input)) return columnOperand(input);
7357
8112
  return valueToOperand(input);
7358
8113
  };
7359
- var fn2 = (key, args) => ({
8114
+ var fn3 = (key, args) => ({
7360
8115
  type: "Function",
7361
8116
  name: key,
7362
8117
  fn: key,
7363
8118
  args: args.map(toOperand3)
7364
8119
  });
7365
- var abs = (value) => fn2("ABS", [value]);
7366
- var acos = (value) => fn2("ACOS", [value]);
7367
- var asin = (value) => fn2("ASIN", [value]);
7368
- var atan = (value) => fn2("ATAN", [value]);
7369
- var atan2 = (y, x) => fn2("ATAN2", [y, x]);
7370
- var ceil = (value) => fn2("CEIL", [value]);
7371
- var ceiling = (value) => fn2("CEILING", [value]);
7372
- var cos = (value) => fn2("COS", [value]);
7373
- var cot = (value) => fn2("COT", [value]);
7374
- var degrees = (value) => fn2("DEGREES", [value]);
7375
- var exp = (value) => fn2("EXP", [value]);
7376
- var floor = (value) => fn2("FLOOR", [value]);
7377
- var ln = (value) => fn2("LN", [value]);
7378
- var log = (value) => fn2("LOG", [value]);
7379
- var log10 = (value) => fn2("LOG10", [value]);
7380
- var logBase = (base, value) => fn2("LOG_BASE", [base, value]);
7381
- var mod = (x, y) => fn2("MOD", [x, y]);
7382
- var pi = () => fn2("PI", []);
7383
- var power = (x, y) => fn2("POWER", [x, y]);
7384
- var pow = (x, y) => fn2("POW", [x, y]);
7385
- var radians = (value) => fn2("RADIANS", [value]);
7386
- var random = () => fn2("RANDOM", []);
7387
- var rand = () => fn2("RAND", []);
7388
- var round = (value, decimals) => decimals === void 0 ? fn2("ROUND", [value]) : fn2("ROUND", [value, decimals]);
7389
- var sign = (value) => fn2("SIGN", [value]);
7390
- var sin = (value) => fn2("SIN", [value]);
7391
- var sqrt = (value) => fn2("SQRT", [value]);
7392
- var tan = (value) => fn2("TAN", [value]);
7393
- var trunc = (value, decimals) => decimals === void 0 ? fn2("TRUNC", [value]) : fn2("TRUNC", [value, decimals]);
7394
- var truncate = (value, decimals) => fn2("TRUNCATE", [value, decimals]);
8120
+ var abs = (value) => fn3("ABS", [value]);
8121
+ var acos = (value) => fn3("ACOS", [value]);
8122
+ var asin = (value) => fn3("ASIN", [value]);
8123
+ var atan = (value) => fn3("ATAN", [value]);
8124
+ var atan2 = (y, x) => fn3("ATAN2", [y, x]);
8125
+ var ceil = (value) => fn3("CEIL", [value]);
8126
+ var ceiling = (value) => fn3("CEILING", [value]);
8127
+ var cos = (value) => fn3("COS", [value]);
8128
+ var cot = (value) => fn3("COT", [value]);
8129
+ var degrees = (value) => fn3("DEGREES", [value]);
8130
+ var exp = (value) => fn3("EXP", [value]);
8131
+ var floor = (value) => fn3("FLOOR", [value]);
8132
+ var ln = (value) => fn3("LN", [value]);
8133
+ var log = (value) => fn3("LOG", [value]);
8134
+ var log10 = (value) => fn3("LOG10", [value]);
8135
+ var logBase = (base, value) => fn3("LOG_BASE", [base, value]);
8136
+ var mod = (x, y) => fn3("MOD", [x, y]);
8137
+ var pi = () => fn3("PI", []);
8138
+ var power = (x, y) => fn3("POWER", [x, y]);
8139
+ var pow = (x, y) => fn3("POW", [x, y]);
8140
+ var radians = (value) => fn3("RADIANS", [value]);
8141
+ var random = () => fn3("RANDOM", []);
8142
+ var rand = () => fn3("RAND", []);
8143
+ var round = (value, decimals) => decimals === void 0 ? fn3("ROUND", [value]) : fn3("ROUND", [value, decimals]);
8144
+ var sign = (value) => fn3("SIGN", [value]);
8145
+ var sin = (value) => fn3("SIN", [value]);
8146
+ var sqrt = (value) => fn3("SQRT", [value]);
8147
+ var tan = (value) => fn3("TAN", [value]);
8148
+ var trunc = (value, decimals) => decimals === void 0 ? fn3("TRUNC", [value]) : fn3("TRUNC", [value, decimals]);
8149
+ var truncate = (value, decimals) => fn3("TRUNCATE", [value, decimals]);
7395
8150
 
7396
8151
  // src/core/functions/datetime.ts
7397
8152
  var isColumnDef3 = (val) => !!val && typeof val === "object" && "type" in val && "name" in val;
@@ -7400,29 +8155,29 @@ var toOperand4 = (input) => {
7400
8155
  if (isColumnDef3(input)) return columnOperand(input);
7401
8156
  return valueToOperand(input);
7402
8157
  };
7403
- var fn3 = (key, args) => ({
8158
+ var fn4 = (key, args) => ({
7404
8159
  type: "Function",
7405
8160
  name: key,
7406
8161
  args: args.map(toOperand4)
7407
8162
  });
7408
- var now = () => fn3("NOW", []);
7409
- var currentDate = () => fn3("CURRENT_DATE", []);
7410
- var currentTime = () => fn3("CURRENT_TIME", []);
7411
- var utcNow = () => fn3("UTC_NOW", []);
7412
- var extract = (part, date) => fn3("EXTRACT", [part, date]);
7413
- var year = (date) => fn3("YEAR", [date]);
7414
- var month = (date) => fn3("MONTH", [date]);
7415
- var day = (date) => fn3("DAY", [date]);
7416
- var dateAdd = (date, interval, unit) => fn3("DATE_ADD", [date, interval, unit]);
7417
- var dateSub = (date, interval, unit) => fn3("DATE_SUB", [date, interval, unit]);
7418
- var dateDiff = (date1, date2) => fn3("DATE_DIFF", [date1, date2]);
7419
- var dateFormat = (date, format) => fn3("DATE_FORMAT", [date, format]);
7420
- var unixTimestamp = () => fn3("UNIX_TIMESTAMP", []);
7421
- var fromUnixTime = (timestamp) => fn3("FROM_UNIXTIME", [timestamp]);
7422
- var endOfMonth = (date) => fn3("END_OF_MONTH", [date]);
7423
- var dayOfWeek = (date) => fn3("DAY_OF_WEEK", [date]);
7424
- var weekOfYear = (date) => fn3("WEEK_OF_YEAR", [date]);
7425
- var dateTrunc = (part, date) => fn3("DATE_TRUNC", [part, date]);
8163
+ var now = () => fn4("NOW", []);
8164
+ var currentDate = () => fn4("CURRENT_DATE", []);
8165
+ var currentTime = () => fn4("CURRENT_TIME", []);
8166
+ var utcNow = () => fn4("UTC_NOW", []);
8167
+ var extract = (part, date) => fn4("EXTRACT", [part, date]);
8168
+ var year = (date) => fn4("YEAR", [date]);
8169
+ var month = (date) => fn4("MONTH", [date]);
8170
+ var day = (date) => fn4("DAY", [date]);
8171
+ var dateAdd = (date, interval, unit) => fn4("DATE_ADD", [date, interval, unit]);
8172
+ var dateSub = (date, interval, unit) => fn4("DATE_SUB", [date, interval, unit]);
8173
+ var dateDiff = (date1, date2) => fn4("DATE_DIFF", [date1, date2]);
8174
+ var dateFormat = (date, format) => fn4("DATE_FORMAT", [date, format]);
8175
+ var unixTimestamp = () => fn4("UNIX_TIMESTAMP", []);
8176
+ var fromUnixTime = (timestamp) => fn4("FROM_UNIXTIME", [timestamp]);
8177
+ var endOfMonth = (date) => fn4("END_OF_MONTH", [date]);
8178
+ var dayOfWeek = (date) => fn4("DAY_OF_WEEK", [date]);
8179
+ var weekOfYear = (date) => fn4("WEEK_OF_YEAR", [date]);
8180
+ var dateTrunc = (part, date) => fn4("DATE_TRUNC", [part, date]);
7426
8181
 
7427
8182
  // src/orm/als.ts
7428
8183
  var AsyncLocalStorage = class {
@@ -7657,6 +8412,7 @@ var TypeScriptGenerator = class {
7657
8412
  case "ScalarSubquery":
7658
8413
  case "CaseExpression":
7659
8414
  case "WindowFunction":
8415
+ case "Cast":
7660
8416
  return this.printOperand(term);
7661
8417
  default:
7662
8418
  return this.printExpression(term);
@@ -7716,6 +8472,9 @@ var TypeScriptGenerator = class {
7716
8472
  visitWindowFunction(node) {
7717
8473
  return this.printWindowFunctionOperand(node);
7718
8474
  }
8475
+ visitCast(node) {
8476
+ return this.printCastOperand(node);
8477
+ }
7719
8478
  visitAliasRef(node) {
7720
8479
  return `aliasRef('${node.name}')`;
7721
8480
  }
@@ -7727,12 +8486,12 @@ var TypeScriptGenerator = class {
7727
8486
  printBinaryExpression(binary) {
7728
8487
  const left2 = this.printOperand(binary.left);
7729
8488
  const right2 = this.printOperand(binary.right);
7730
- const fn4 = this.mapOp(binary.operator);
8489
+ const fn5 = this.mapOp(binary.operator);
7731
8490
  const args = [left2, right2];
7732
8491
  if (binary.escape) {
7733
8492
  args.push(this.printOperand(binary.escape));
7734
8493
  }
7735
- return `${fn4}(${args.join(", ")})`;
8494
+ return `${fn5}(${args.join(", ")})`;
7736
8495
  }
7737
8496
  /**
7738
8497
  * Prints a logical expression to TypeScript code
@@ -7761,13 +8520,13 @@ var TypeScriptGenerator = class {
7761
8520
  */
7762
8521
  printInExpression(inExpr) {
7763
8522
  const left2 = this.printOperand(inExpr.left);
7764
- const fn4 = this.mapOp(inExpr.operator);
8523
+ const fn5 = this.mapOp(inExpr.operator);
7765
8524
  if (Array.isArray(inExpr.right)) {
7766
8525
  const values = inExpr.right.map((v) => this.printOperand(v)).join(", ");
7767
- return `${fn4}(${left2}, [${values}])`;
8526
+ return `${fn5}(${left2}, [${values}])`;
7768
8527
  }
7769
8528
  const subquery = this.inlineChain(this.buildSelectLines(inExpr.right.query));
7770
- return `${fn4}(${left2}, (${subquery}))`;
8529
+ return `${fn5}(${left2}, (${subquery}))`;
7771
8530
  }
7772
8531
  /**
7773
8532
  * Prints a null expression to TypeScript code
@@ -7776,8 +8535,8 @@ var TypeScriptGenerator = class {
7776
8535
  */
7777
8536
  printNullExpression(nullExpr) {
7778
8537
  const left2 = this.printOperand(nullExpr.left);
7779
- const fn4 = this.mapOp(nullExpr.operator);
7780
- return `${fn4}(${left2})`;
8538
+ const fn5 = this.mapOp(nullExpr.operator);
8539
+ return `${fn5}(${left2})`;
7781
8540
  }
7782
8541
  /**
7783
8542
  * Prints a BETWEEN expression to TypeScript code
@@ -7821,9 +8580,9 @@ var TypeScriptGenerator = class {
7821
8580
  * @param fn - Function node
7822
8581
  * @returns TypeScript code representation
7823
8582
  */
7824
- printFunctionOperand(fn4) {
7825
- const args = fn4.args.map((a) => this.printOperand(a)).join(", ");
7826
- return `${fn4.name.toLowerCase()}(${args})`;
8583
+ printFunctionOperand(fn5) {
8584
+ const args = fn5.args.map((a) => this.printOperand(a)).join(", ");
8585
+ return `${fn5.name.toLowerCase()}(${args})`;
7827
8586
  }
7828
8587
  /**
7829
8588
  * Prints a JSON path operand to TypeScript code
@@ -7883,6 +8642,10 @@ var TypeScriptGenerator = class {
7883
8642
  result += ")";
7884
8643
  return result;
7885
8644
  }
8645
+ printCastOperand(node) {
8646
+ const typeLiteral = node.castType.replace(/'/g, "\\'");
8647
+ return `cast(${this.printOperand(node.expression)}, '${typeLiteral}')`;
8648
+ }
7886
8649
  /**
7887
8650
  * Converts method chain lines to inline format
7888
8651
  * @param lines - Method chain lines
@@ -9047,15 +9810,15 @@ var OrmSession = class {
9047
9810
  * @returns The result of the function
9048
9811
  * @throws If the transaction fails
9049
9812
  */
9050
- async transaction(fn4) {
9813
+ async transaction(fn5) {
9051
9814
  if (!this.executor.capabilities.transactions) {
9052
- const result = await fn4(this);
9815
+ const result = await fn5(this);
9053
9816
  await this.commit();
9054
9817
  return result;
9055
9818
  }
9056
9819
  await this.executor.beginTransaction();
9057
9820
  try {
9058
- const result = await fn4(this);
9821
+ const result = await fn5(this);
9059
9822
  await this.flushWithHooks();
9060
9823
  await this.executor.commitTransaction();
9061
9824
  await this.domainEvents.dispatch(this.unitOfWork.getTracked(), this);
@@ -9158,11 +9921,11 @@ var Orm = class {
9158
9921
  * @returns The result of the function
9159
9922
  * @throws If the transaction fails
9160
9923
  */
9161
- async transaction(fn4) {
9924
+ async transaction(fn5) {
9162
9925
  const executor = this.executorFactory.createTransactionalExecutor();
9163
9926
  const session = new OrmSession({ orm: this, executor });
9164
9927
  try {
9165
- return await session.transaction(() => fn4(session));
9928
+ return await session.transaction(() => fn5(session));
9166
9929
  } finally {
9167
9930
  await session.dispose();
9168
9931
  }
@@ -9248,13 +10011,14 @@ function Entity(options = {}) {
9248
10011
  return decoratorWithContext;
9249
10012
  }
9250
10013
 
9251
- // src/decorators/column.ts
10014
+ // src/decorators/column-decorator.ts
9252
10015
  var normalizeColumnInput = (input) => {
9253
10016
  const asOptions = input;
9254
10017
  const asDefinition = input;
9255
10018
  const column = {
9256
10019
  type: asOptions.type ?? asDefinition.type,
9257
10020
  args: asOptions.args ?? asDefinition.args,
10021
+ dialectTypes: asOptions.dialectTypes ?? asDefinition.dialectTypes,
9258
10022
  notNull: asOptions.notNull ?? asDefinition.notNull,
9259
10023
  primary: asOptions.primary ?? asDefinition.primary,
9260
10024
  tsType: asDefinition.tsType ?? asOptions.tsType,
@@ -9959,6 +10723,7 @@ function createPooledExecutorFactory(opts) {
9959
10723
  PostgresDialect,
9960
10724
  PrimaryKey,
9961
10725
  RelationKinds,
10726
+ STANDARD_COLUMN_TYPES,
9962
10727
  SelectQueryBuilder,
9963
10728
  SqlServerDialect,
9964
10729
  SqliteDialect,
@@ -9980,6 +10745,7 @@ function createPooledExecutorFactory(opts) {
9980
10745
  between,
9981
10746
  bootstrapEntities,
9982
10747
  caseWhen,
10748
+ cast,
9983
10749
  ceil,
9984
10750
  ceiling,
9985
10751
  char,
@@ -10047,6 +10813,7 @@ function createPooledExecutorFactory(opts) {
10047
10813
  instr,
10048
10814
  introspectSchema,
10049
10815
  isCaseExpressionNode,
10816
+ isCastExpressionNode,
10050
10817
  isExpressionSelectionNode,
10051
10818
  isFunctionNode,
10052
10819
  isNotNull,
@@ -10081,6 +10848,7 @@ function createPooledExecutorFactory(opts) {
10081
10848
  month,
10082
10849
  mul,
10083
10850
  neq,
10851
+ normalizeColumnType,
10084
10852
  notBetween,
10085
10853
  notExists,
10086
10854
  notInList,
@@ -10102,6 +10870,7 @@ function createPooledExecutorFactory(opts) {
10102
10870
  registerOperandDispatcher,
10103
10871
  registerSchemaIntrospector,
10104
10872
  renderColumnDefinition,
10873
+ renderTypeWithArgs,
10105
10874
  repeat,
10106
10875
  replace,
10107
10876
  right,