metal-orm 1.0.46 → 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.
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)
@@ -86,6 +86,7 @@ __export(index_exports, {
86
86
  between: () => between,
87
87
  bootstrapEntities: () => bootstrapEntities,
88
88
  caseWhen: () => caseWhen,
89
+ cast: () => cast,
89
90
  ceil: () => ceil,
90
91
  ceiling: () => ceiling,
91
92
  char: () => char,
@@ -153,6 +154,7 @@ __export(index_exports, {
153
154
  instr: () => instr,
154
155
  introspectSchema: () => introspectSchema,
155
156
  isCaseExpressionNode: () => isCaseExpressionNode,
157
+ isCastExpressionNode: () => isCastExpressionNode,
156
158
  isExpressionSelectionNode: () => isExpressionSelectionNode,
157
159
  isFunctionNode: () => isFunctionNode,
158
160
  isNotNull: () => isNotNull,
@@ -575,7 +577,9 @@ var operandTypes = /* @__PURE__ */ new Set([
575
577
  "JsonPath",
576
578
  "ScalarSubquery",
577
579
  "CaseExpression",
578
- "WindowFunction"
580
+ "Cast",
581
+ "WindowFunction",
582
+ "ArithmeticExpression"
579
583
  ]);
580
584
  var hasTypeProperty = (value) => typeof value === "object" && value !== null && "type" in value;
581
585
  var isOperandNode = (node) => {
@@ -584,8 +588,9 @@ var isOperandNode = (node) => {
584
588
  };
585
589
  var isFunctionNode = (node) => isOperandNode(node) && node.type === "Function";
586
590
  var isCaseExpressionNode = (node) => isOperandNode(node) && node.type === "CaseExpression";
591
+ var isCastExpressionNode = (node) => isOperandNode(node) && node.type === "Cast";
587
592
  var isWindowFunctionNode = (node) => isOperandNode(node) && node.type === "WindowFunction";
588
- var isExpressionSelectionNode = (node) => isFunctionNode(node) || isCaseExpressionNode(node) || isWindowFunctionNode(node);
593
+ var isExpressionSelectionNode = (node) => isFunctionNode(node) || isCaseExpressionNode(node) || isCastExpressionNode(node) || isWindowFunctionNode(node);
589
594
 
590
595
  // src/core/ast/expression-builders.ts
591
596
  var isLiteralValue = (value) => value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean";
@@ -721,6 +726,11 @@ var caseWhen = (conditions, elseValue) => ({
721
726
  })),
722
727
  else: elseValue !== void 0 ? toOperand(elseValue) : void 0
723
728
  });
729
+ var cast = (expression, castType) => ({
730
+ type: "Cast",
731
+ expression: toOperand(expression),
732
+ castType
733
+ });
724
734
  var exists = (subquery) => ({
725
735
  type: "ExistsExpression",
726
736
  operator: "EXISTS",
@@ -978,6 +988,9 @@ var visitOperand = (node, visitor) => {
978
988
  case "AliasRef":
979
989
  if (visitor.visitAliasRef) return visitor.visitAliasRef(node);
980
990
  break;
991
+ case "Cast":
992
+ if (visitor.visitCast) return visitor.visitCast(node);
993
+ break;
981
994
  default:
982
995
  break;
983
996
  }
@@ -1504,6 +1517,10 @@ var Dialect = class _Dialect {
1504
1517
  parts.push("END");
1505
1518
  return parts.join(" ");
1506
1519
  });
1520
+ this.registerOperandCompiler("Cast", (node, ctx) => {
1521
+ const value = this.compileOperand(node.expression, ctx);
1522
+ return `CAST(${value} AS ${node.castType})`;
1523
+ });
1507
1524
  this.registerOperandCompiler("WindowFunction", (node, ctx) => {
1508
1525
  let result = `${node.name}(`;
1509
1526
  if (node.args.length > 0) {
@@ -1530,6 +1547,11 @@ var Dialect = class _Dialect {
1530
1547
  result += ")";
1531
1548
  return result;
1532
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
+ });
1533
1555
  }
1534
1556
  // Default fallback, should be overridden by dialects if supported
1535
1557
  compileJsonPath(_node) {
@@ -1562,13 +1584,13 @@ var FunctionTableFormatter = class {
1562
1584
  * @param dialect - The dialect instance for compiling operands.
1563
1585
  * @returns SQL function table expression (e.g., "LATERAL schema.func(args) WITH ORDINALITY AS alias(col1, col2)").
1564
1586
  */
1565
- static format(fn4, ctx, dialect) {
1566
- const schemaPart = this.formatSchema(fn4, dialect);
1567
- const args = this.formatArgs(fn4, ctx, dialect);
1568
- const base = this.formatBase(fn4, schemaPart, args, dialect);
1569
- const lateral = this.formatLateral(fn4);
1570
- const alias = this.formatAlias(fn4, dialect);
1571
- 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);
1572
1594
  return `${lateral}${base}${alias}${colAliases}`;
1573
1595
  }
1574
1596
  /**
@@ -1578,9 +1600,9 @@ var FunctionTableFormatter = class {
1578
1600
  * @returns Schema prefix (e.g., "schema.") or empty string.
1579
1601
  * @internal
1580
1602
  */
1581
- static formatSchema(fn4, dialect) {
1582
- if (!fn4.schema) return "";
1583
- 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;
1584
1606
  return `${quoted}.`;
1585
1607
  }
1586
1608
  /**
@@ -1591,8 +1613,8 @@ var FunctionTableFormatter = class {
1591
1613
  * @returns Comma-separated function arguments.
1592
1614
  * @internal
1593
1615
  */
1594
- static formatArgs(fn4, ctx, dialect) {
1595
- return (fn4.args || []).map((a) => {
1616
+ static formatArgs(fn5, ctx, dialect) {
1617
+ return (fn5.args || []).map((a) => {
1596
1618
  if (ctx && dialect) {
1597
1619
  return dialect.compileOperand(a, ctx);
1598
1620
  }
@@ -1608,9 +1630,9 @@ var FunctionTableFormatter = class {
1608
1630
  * @returns Base function call expression (e.g., "schema.func(args) WITH ORDINALITY").
1609
1631
  * @internal
1610
1632
  */
1611
- static formatBase(fn4, schemaPart, args, dialect) {
1612
- const ordinality = fn4.withOrdinality ? " WITH ORDINALITY" : "";
1613
- 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;
1614
1636
  return `${schemaPart}${quoted}(${args})${ordinality}`;
1615
1637
  }
1616
1638
  /**
@@ -1619,8 +1641,8 @@ var FunctionTableFormatter = class {
1619
1641
  * @returns "LATERAL " or empty string.
1620
1642
  * @internal
1621
1643
  */
1622
- static formatLateral(fn4) {
1623
- return fn4.lateral ? "LATERAL " : "";
1644
+ static formatLateral(fn5) {
1645
+ return fn5.lateral ? "LATERAL " : "";
1624
1646
  }
1625
1647
  /**
1626
1648
  * Formats the table alias for the function table.
@@ -1629,9 +1651,9 @@ var FunctionTableFormatter = class {
1629
1651
  * @returns " AS alias" or empty string.
1630
1652
  * @internal
1631
1653
  */
1632
- static formatAlias(fn4, dialect) {
1633
- if (!fn4.alias) return "";
1634
- 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;
1635
1657
  return ` AS ${quoted}`;
1636
1658
  }
1637
1659
  /**
@@ -1641,9 +1663,9 @@ var FunctionTableFormatter = class {
1641
1663
  * @returns "(col1, col2, ...)" or empty string.
1642
1664
  * @internal
1643
1665
  */
1644
- static formatColumnAliases(fn4, dialect) {
1645
- if (!fn4.columnAliases || !fn4.columnAliases.length) return "";
1646
- 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(", ");
1647
1669
  return `(${aliases})`;
1648
1670
  }
1649
1671
  };
@@ -1911,8 +1933,8 @@ var SqlDialectBase = class extends Dialect {
1911
1933
  }
1912
1934
  return this.compileTableSource(tableSource);
1913
1935
  }
1914
- compileFunctionTable(fn4, ctx) {
1915
- return FunctionTableFormatter.format(fn4, ctx, this);
1936
+ compileFunctionTable(fn5, ctx) {
1937
+ return FunctionTableFormatter.format(fn5, ctx, this);
1916
1938
  }
1917
1939
  compileDerivedTable(table, ctx) {
1918
1940
  if (!table.alias) {
@@ -2536,16 +2558,7 @@ var SqlServerDialect = class extends SqlDialectBase {
2536
2558
  }
2537
2559
  compileSelectCoreForMssql(ast, ctx) {
2538
2560
  const columns = ast.columns.map((c) => {
2539
- let expr = "";
2540
- if (c.type === "Function") {
2541
- expr = this.compileOperand(c, ctx);
2542
- } else if (c.type === "Column") {
2543
- expr = `${this.quoteIdentifier(c.table)}.${this.quoteIdentifier(c.name)}`;
2544
- } else if (c.type === "ScalarSubquery") {
2545
- expr = this.compileOperand(c, ctx);
2546
- } else if (c.type === "WindowFunction") {
2547
- expr = this.compileOperand(c, ctx);
2548
- }
2561
+ const expr = c.type === "Column" ? `${this.quoteIdentifier(c.table)}.${this.quoteIdentifier(c.name)}` : this.compileOperand(c, ctx);
2549
2562
  if (c.alias) {
2550
2563
  if (c.alias.includes("(")) return c.alias;
2551
2564
  return `${expr} AS ${this.quoteIdentifier(c.alias)}`;
@@ -6819,15 +6832,11 @@ var PgReferentialConstraints = defineTable(
6819
6832
  async function runSelect(qb, ctx) {
6820
6833
  const ast = qb.getAST();
6821
6834
  const compiled = ctx.dialect.compileSelect(ast);
6822
- const results = await ctx.executor.executeSql(compiled.sql, compiled.params);
6823
- const [first] = results;
6824
- return toRows(first);
6835
+ return await queryRows(ctx.executor, compiled.sql, compiled.params);
6825
6836
  }
6826
6837
  async function runSelectNode(ast, ctx) {
6827
6838
  const compiled = ctx.dialect.compileSelect(ast);
6828
- const results = await ctx.executor.executeSql(compiled.sql, compiled.params);
6829
- const [first] = results;
6830
- return toRows(first);
6839
+ return await queryRows(ctx.executor, compiled.sql, compiled.params);
6831
6840
  }
6832
6841
 
6833
6842
  // src/core/ddl/introspect/postgres.ts
@@ -6852,6 +6861,32 @@ var postgresIntrospector = {
6852
6861
  ordinal_position: PgInformationSchemaColumns.columns.ordinal_position
6853
6862
  }).where(eq(PgInformationSchemaColumns.columns.table_schema, schema)).orderBy(PgInformationSchemaColumns.columns.table_name).orderBy(PgInformationSchemaColumns.columns.ordinal_position);
6854
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
+ });
6855
6890
  const qbPk = new SelectQueryBuilder(PgKeyColumnUsage).select({
6856
6891
  table_schema: PgKeyColumnUsage.columns.table_schema,
6857
6892
  table_name: PgKeyColumnUsage.columns.table_name,
@@ -6879,7 +6914,9 @@ var postgresIntrospector = {
6879
6914
  constraint_name: PgKeyColumnUsage.columns.constraint_name,
6880
6915
  foreign_table_schema: PgConstraintColumnUsage.columns.table_schema,
6881
6916
  foreign_table_name: PgConstraintColumnUsage.columns.table_name,
6882
- 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
6883
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));
6884
6921
  const fkRows = await runSelect(qbFk, ctx);
6885
6922
  const fkMap = /* @__PURE__ */ new Map();
@@ -6889,8 +6926,8 @@ var postgresIntrospector = {
6889
6926
  existing.push({
6890
6927
  table: `${r.foreign_table_schema}.${r.foreign_table_name}`,
6891
6928
  column: r.foreign_column_name,
6892
- onDelete: void 0,
6893
- onUpdate: void 0
6929
+ onDelete: r.delete_rule,
6930
+ onUpdate: r.update_rule
6894
6931
  });
6895
6932
  fkMap.set(key, existing);
6896
6933
  }
@@ -6994,12 +7031,15 @@ var postgresIntrospector = {
6994
7031
  });
6995
7032
  }
6996
7033
  const cols = tablesByKey.get(key);
7034
+ const commentKey = `${r.table_schema}.${r.table_name}.${r.column_name}`;
7035
+ const columnComment = columnComments.get(commentKey);
6997
7036
  const fk = fkMap.get(`${r.table_schema}.${r.table_name}.${r.column_name}`)?.[0];
6998
7037
  const column = {
6999
7038
  name: r.column_name,
7000
7039
  type: r.data_type,
7001
7040
  notNull: r.is_nullable === "NO",
7002
7041
  default: r.column_default ?? void 0,
7042
+ comment: columnComment ?? void 0,
7003
7043
  references: fk ? {
7004
7044
  table: fk.table,
7005
7045
  column: fk.column,
@@ -7027,32 +7067,252 @@ var postgresIntrospector = {
7027
7067
  }
7028
7068
  };
7029
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
+
7030
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
+ };
7031
7170
  var mysqlIntrospector = {
7032
7171
  async introspect(ctx, options) {
7033
7172
  const schema = options.schema;
7034
- const filterClause = schema ? "table_schema = ?" : "table_schema = database()";
7035
- const params = schema ? [schema] : [];
7036
- const columnRows = await queryRows(
7037
- ctx.executor,
7038
- `
7039
- SELECT table_schema, table_name, column_name, data_type, is_nullable, column_default, extra
7040
- FROM information_schema.columns
7041
- WHERE ${filterClause}
7042
- ORDER BY table_name, ordinal_position
7043
- `,
7044
- params
7045
- );
7046
- const pkRows = await queryRows(
7047
- ctx.executor,
7048
- `
7049
- SELECT table_schema, table_name, column_name
7050
- FROM information_schema.key_column_usage
7051
- WHERE constraint_name = 'PRIMARY' AND ${filterClause}
7052
- ORDER BY ordinal_position
7053
- `,
7054
- params
7055
- );
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
+ });
7056
7316
  const pkMap = /* @__PURE__ */ new Map();
7057
7317
  pkRows.forEach((r) => {
7058
7318
  const key = `${r.table_schema}.${r.table_name}`;
@@ -7060,21 +7320,19 @@ var mysqlIntrospector = {
7060
7320
  list.push(r.column_name);
7061
7321
  pkMap.set(key, list);
7062
7322
  });
7063
- const indexRows = await queryRows(
7064
- ctx.executor,
7065
- `
7066
- SELECT
7067
- table_schema,
7068
- table_name,
7069
- index_name,
7070
- non_unique,
7071
- GROUP_CONCAT(column_name ORDER BY seq_in_index) AS cols
7072
- FROM information_schema.statistics
7073
- WHERE ${filterClause} AND index_name <> 'PRIMARY'
7074
- GROUP BY table_schema, table_name, index_name, non_unique
7075
- `,
7076
- params
7077
- );
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
+ });
7078
7336
  const tablesByKey = /* @__PURE__ */ new Map();
7079
7337
  columnRows.forEach((r) => {
7080
7338
  const key = `${r.table_schema}.${r.table_name}`;
@@ -7085,18 +7343,32 @@ var mysqlIntrospector = {
7085
7343
  schema: r.table_schema,
7086
7344
  columns: [],
7087
7345
  primaryKey: pkMap.get(key) || [],
7088
- indexes: []
7346
+ indexes: [],
7347
+ comment: tableComments.get(key) || void 0
7089
7348
  });
7090
7349
  }
7091
- 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;
7092
7353
  const column = {
7093
7354
  name: r.column_name,
7094
- type: r.data_type,
7355
+ type: columnType,
7095
7356
  notNull: r.is_nullable === "NO",
7096
7357
  default: r.column_default ?? void 0,
7097
- autoIncrement: typeof r.extra === "string" && r.extra.includes("auto_increment")
7358
+ autoIncrement: typeof r.extra === "string" && r.extra.includes("auto_increment"),
7359
+ comment
7098
7360
  };
7099
- 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);
7100
7372
  });
7101
7373
  indexRows.forEach((r) => {
7102
7374
  const key = `${r.table_schema}.${r.table_name}`;
@@ -7124,43 +7396,79 @@ var toReferentialAction = (value) => {
7124
7396
  }
7125
7397
  return void 0;
7126
7398
  };
7127
- 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
+ };
7128
7415
  var sqliteIntrospector = {
7129
- /**
7130
- * Introspects the SQLite database schema by querying sqlite_master and various PRAGMAs.
7131
- * @param ctx - The database execution context containing the DbExecutor.
7132
- * @param options - Options controlling which tables and schemas to include.
7133
- * @returns A promise that resolves to the introspected DatabaseSchema.
7134
- */
7135
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);
7136
7429
  const tables = [];
7137
- const tableRows = await queryRows(
7138
- ctx.executor,
7139
- `SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%';`
7140
- );
7141
7430
  for (const row of tableRows) {
7142
- const name = row.name;
7143
- if (!shouldIncludeTable(name, options)) continue;
7144
- const table = { name, columns: [], primaryKey: [], indexes: [] };
7145
- const cols = await queryRows(ctx.executor, `PRAGMA table_info('${escapeSingleQuotes(name)}');`);
7146
- cols.forEach((c) => {
7147
- table.columns.push({
7148
- name: c.name,
7149
- type: c.type,
7150
- notNull: c.notnull === 1,
7151
- 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,
7152
7461
  autoIncrement: false
7153
7462
  });
7154
- if (c.pk && c.pk > 0) {
7155
- table.primaryKey = table.primaryKey || [];
7156
- table.primaryKey.push(c.name);
7463
+ if (info.pk && info.pk > 0) {
7464
+ tableEntry.primaryKey = tableEntry.primaryKey || [];
7465
+ tableEntry.primaryKey.push(info.name);
7157
7466
  }
7158
7467
  });
7159
- const fkRows = await queryRows(ctx.executor, `PRAGMA foreign_key_list('${escapeSingleQuotes(name)}');`);
7160
- fkRows.forEach((fk) => {
7161
- const col2 = table.columns.find((c) => c.name === fk.from);
7162
- if (col2) {
7163
- col2.references = {
7468
+ foreignKeys.forEach((fk) => {
7469
+ const column = tableEntry.columns.find((col2) => col2.name === fk.from);
7470
+ if (column) {
7471
+ column.references = {
7164
7472
  table: fk.table,
7165
7473
  column: fk.to,
7166
7474
  onDelete: toReferentialAction(fk.on_delete),
@@ -7168,88 +7476,529 @@ var sqliteIntrospector = {
7168
7476
  };
7169
7477
  }
7170
7478
  });
7171
- const idxList = await queryRows(ctx.executor, `PRAGMA index_list('${escapeSingleQuotes(name)}');`);
7172
- for (const idx of idxList) {
7173
- const idxName = idx.name;
7174
- 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
+ );
7175
7488
  const idxEntry = {
7176
- name: idxName,
7177
- columns: columnsInfo.map((ci) => ({ column: ci.name })),
7489
+ name: idx.name,
7490
+ columns: indexColumns.map((col2) => ({ column: col2.name })),
7178
7491
  unique: idx.unique === 1
7179
7492
  };
7180
- table.indexes.push(idxEntry);
7493
+ tableEntry.indexes.push(idxEntry);
7181
7494
  }
7182
- tables.push(table);
7495
+ tables.push(tableEntry);
7183
7496
  }
7184
7497
  return { tables };
7185
7498
  }
7186
7499
  };
7187
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
+
7188
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
+ };
7189
7730
  var mssqlIntrospector = {
7190
- /**
7191
- * Introspects the MSSQL database schema.
7192
- * @param ctx - The introspection context containing the database executor.
7193
- * @param options - Options for introspection, such as schema filter.
7194
- * @returns A promise that resolves to the introspected database schema.
7195
- */
7196
7731
  async introspect(ctx, options) {
7197
7732
  const schema = options.schema;
7198
- const filterSchema = schema ? "sch.name = @p1" : "1=1";
7199
- const params = schema ? [schema] : [];
7200
- const columnRows = await queryRows(
7201
- ctx.executor,
7202
- `
7203
- SELECT
7204
- sch.name AS table_schema,
7205
- t.name AS table_name,
7206
- c.name AS column_name,
7207
- LOWER(ty.name)
7208
- + CASE
7209
- WHEN LOWER(ty.name) IN ('varchar', 'char', 'varbinary', 'binary', 'nvarchar', 'nchar') THEN
7210
- '('
7211
- + (
7212
- CASE
7213
- WHEN c.max_length = -1 THEN 'max'
7214
- WHEN LOWER(ty.name) IN ('nvarchar', 'nchar') THEN CAST(c.max_length / 2 AS varchar(10))
7215
- ELSE CAST(c.max_length AS varchar(10))
7216
- END
7217
- )
7218
- + ')'
7219
- WHEN LOWER(ty.name) IN ('decimal', 'numeric') THEN
7220
- '(' + CAST(c.precision AS varchar(10)) + ',' + CAST(c.scale AS varchar(10)) + ')'
7221
- ELSE
7222
- ''
7223
- END AS data_type,
7224
- c.is_nullable,
7225
- c.is_identity,
7226
- object_definition(c.default_object_id) AS column_default
7227
- FROM sys.columns c
7228
- JOIN sys.tables t ON t.object_id = c.object_id
7229
- JOIN sys.schemas sch ON sch.schema_id = t.schema_id
7230
- JOIN sys.types ty ON ty.user_type_id = c.user_type_id
7231
- WHERE t.is_ms_shipped = 0 AND ${filterSchema}
7232
- `,
7233
- params
7234
- );
7235
- const pkRows = await queryRows(
7236
- ctx.executor,
7237
- `
7238
- SELECT
7239
- sch.name AS table_schema,
7240
- t.name AS table_name,
7241
- c.name AS column_name,
7242
- ic.key_ordinal
7243
- FROM sys.indexes i
7244
- JOIN sys.index_columns ic ON ic.object_id = i.object_id AND ic.index_id = i.index_id
7245
- JOIN sys.columns c ON c.object_id = ic.object_id AND c.column_id = ic.column_id
7246
- JOIN sys.tables t ON t.object_id = i.object_id
7247
- JOIN sys.schemas sch ON sch.schema_id = t.schema_id
7248
- WHERE i.is_primary_key = 1 AND ${filterSchema}
7249
- ORDER BY ic.key_ordinal
7250
- `,
7251
- 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" }
7252
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);
7253
8002
  const pkMap = /* @__PURE__ */ new Map();
7254
8003
  pkRows.forEach((r) => {
7255
8004
  const key = `${r.table_schema}.${r.table_name}`;
@@ -7257,42 +8006,19 @@ var mssqlIntrospector = {
7257
8006
  list.push(r.column_name);
7258
8007
  pkMap.set(key, list);
7259
8008
  });
7260
- const indexRows = await queryRows(
7261
- ctx.executor,
7262
- `
7263
- SELECT
7264
- sch.name AS table_schema,
7265
- t.name AS table_name,
7266
- i.name AS index_name,
7267
- i.is_unique,
7268
- i.has_filter,
7269
- i.filter_definition
7270
- FROM sys.indexes i
7271
- JOIN sys.tables t ON t.object_id = i.object_id
7272
- JOIN sys.schemas sch ON sch.schema_id = t.schema_id
7273
- WHERE i.is_primary_key = 0 AND i.is_hypothetical = 0 AND ${filterSchema}
7274
- `,
7275
- params
7276
- );
7277
- const indexColsRows = await queryRows(
7278
- ctx.executor,
7279
- `
7280
- SELECT
7281
- sch.name AS table_schema,
7282
- t.name AS table_name,
7283
- i.name AS index_name,
7284
- c.name AS column_name,
7285
- ic.key_ordinal
7286
- FROM sys.index_columns ic
7287
- JOIN sys.indexes i ON i.object_id = ic.object_id AND i.index_id = ic.index_id
7288
- JOIN sys.columns c ON c.object_id = ic.object_id AND c.column_id = ic.column_id
7289
- JOIN sys.tables t ON t.object_id = i.object_id
7290
- JOIN sys.schemas sch ON sch.schema_id = t.schema_id
7291
- WHERE i.is_primary_key = 0 AND ${filterSchema}
7292
- ORDER BY ic.key_ordinal
7293
- `,
7294
- params
7295
- );
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
+ });
7296
8022
  const indexColumnsMap = /* @__PURE__ */ new Map();
7297
8023
  indexColsRows.forEach((r) => {
7298
8024
  const key = `${r.table_schema}.${r.table_name}.${r.index_name}`;
@@ -7313,7 +8039,7 @@ var mssqlIntrospector = {
7313
8039
  indexes: []
7314
8040
  });
7315
8041
  }
7316
- const t = tablesByKey.get(key);
8042
+ const table = tablesByKey.get(key);
7317
8043
  const column = {
7318
8044
  name: r.column_name,
7319
8045
  type: r.data_type,
@@ -7321,7 +8047,17 @@ var mssqlIntrospector = {
7321
8047
  default: r.column_default ?? void 0,
7322
8048
  autoIncrement: !!r.is_identity
7323
8049
  };
7324
- 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);
7325
8061
  });
7326
8062
  indexRows.forEach((r) => {
7327
8063
  const key = `${r.table_schema}.${r.table_name}`;
@@ -7332,7 +8068,7 @@ var mssqlIntrospector = {
7332
8068
  name: r.index_name,
7333
8069
  columns: cols,
7334
8070
  unique: !!r.is_unique,
7335
- where: r.has_filter ? r.filter_definition : void 0
8071
+ where: r.has_filter ? r.filter_definition ?? void 0 : void 0
7336
8072
  };
7337
8073
  table.indexes = table.indexes || [];
7338
8074
  table.indexes.push(idx);
@@ -7368,51 +8104,6 @@ var introspectSchema = async (executor, dialect, options = {}) => {
7368
8104
  return handler.introspect(ctx, options);
7369
8105
  };
7370
8106
 
7371
- // src/core/functions/text.ts
7372
- var isColumnDef = (val) => !!val && typeof val === "object" && "type" in val && "name" in val;
7373
- var toOperand2 = (input) => {
7374
- if (isOperandNode(input)) return input;
7375
- if (isColumnDef(input)) return columnOperand(input);
7376
- return valueToOperand(input);
7377
- };
7378
- var fn = (key, args) => ({
7379
- type: "Function",
7380
- name: key,
7381
- fn: key,
7382
- args: args.map(toOperand2)
7383
- });
7384
- var lower = (value) => fn("LOWER", [value]);
7385
- var upper = (value) => fn("UPPER", [value]);
7386
- var ascii = (value) => fn("ASCII", [value]);
7387
- var char = (...codes) => {
7388
- if (codes.length === 0) throw new Error("char() expects at least 1 argument");
7389
- return fn("CHAR", codes);
7390
- };
7391
- var charLength = (value) => fn("CHAR_LENGTH", [value]);
7392
- var length = (value) => fn("LENGTH", [value]);
7393
- var trim = (value, chars) => chars === void 0 ? fn("TRIM", [value]) : fn("TRIM", [value, chars]);
7394
- var ltrim = (value) => fn("LTRIM", [value]);
7395
- var rtrim = (value) => fn("RTRIM", [value]);
7396
- var concat = (...args) => {
7397
- if (args.length < 2) throw new Error("concat() expects at least 2 arguments");
7398
- return fn("CONCAT", args);
7399
- };
7400
- var concatWs = (separator, ...args) => {
7401
- if (args.length < 1) throw new Error("concatWs() expects at least 2 arguments including the separator");
7402
- return fn("CONCAT_WS", [separator, ...args]);
7403
- };
7404
- var substr = (value, start, length2) => length2 === void 0 ? fn("SUBSTR", [value, start]) : fn("SUBSTR", [value, start, length2]);
7405
- var left = (value, len) => fn("LEFT", [value, len]);
7406
- var right = (value, len) => fn("RIGHT", [value, len]);
7407
- var position = (substring, value) => fn("POSITION", [substring, value]);
7408
- var instr = (value, substring) => fn("INSTR", [value, substring]);
7409
- var locate = (substring, value, start) => start === void 0 ? fn("LOCATE", [substring, value]) : fn("LOCATE", [substring, value, start]);
7410
- var replace = (value, search, replacement) => fn("REPLACE", [value, search, replacement]);
7411
- var repeat = (value, count2) => fn("REPEAT", [value, count2]);
7412
- var lpad = (value, len, pad) => fn("LPAD", [value, len, pad]);
7413
- var rpad = (value, len, pad) => fn("RPAD", [value, len, pad]);
7414
- var space = (count2) => fn("SPACE", [count2]);
7415
-
7416
8107
  // src/core/functions/numeric.ts
7417
8108
  var isColumnDef2 = (val) => !!val && typeof val === "object" && "type" in val && "name" in val;
7418
8109
  var toOperand3 = (input) => {
@@ -7420,42 +8111,42 @@ var toOperand3 = (input) => {
7420
8111
  if (isColumnDef2(input)) return columnOperand(input);
7421
8112
  return valueToOperand(input);
7422
8113
  };
7423
- var fn2 = (key, args) => ({
8114
+ var fn3 = (key, args) => ({
7424
8115
  type: "Function",
7425
8116
  name: key,
7426
8117
  fn: key,
7427
8118
  args: args.map(toOperand3)
7428
8119
  });
7429
- var abs = (value) => fn2("ABS", [value]);
7430
- var acos = (value) => fn2("ACOS", [value]);
7431
- var asin = (value) => fn2("ASIN", [value]);
7432
- var atan = (value) => fn2("ATAN", [value]);
7433
- var atan2 = (y, x) => fn2("ATAN2", [y, x]);
7434
- var ceil = (value) => fn2("CEIL", [value]);
7435
- var ceiling = (value) => fn2("CEILING", [value]);
7436
- var cos = (value) => fn2("COS", [value]);
7437
- var cot = (value) => fn2("COT", [value]);
7438
- var degrees = (value) => fn2("DEGREES", [value]);
7439
- var exp = (value) => fn2("EXP", [value]);
7440
- var floor = (value) => fn2("FLOOR", [value]);
7441
- var ln = (value) => fn2("LN", [value]);
7442
- var log = (value) => fn2("LOG", [value]);
7443
- var log10 = (value) => fn2("LOG10", [value]);
7444
- var logBase = (base, value) => fn2("LOG_BASE", [base, value]);
7445
- var mod = (x, y) => fn2("MOD", [x, y]);
7446
- var pi = () => fn2("PI", []);
7447
- var power = (x, y) => fn2("POWER", [x, y]);
7448
- var pow = (x, y) => fn2("POW", [x, y]);
7449
- var radians = (value) => fn2("RADIANS", [value]);
7450
- var random = () => fn2("RANDOM", []);
7451
- var rand = () => fn2("RAND", []);
7452
- var round = (value, decimals) => decimals === void 0 ? fn2("ROUND", [value]) : fn2("ROUND", [value, decimals]);
7453
- var sign = (value) => fn2("SIGN", [value]);
7454
- var sin = (value) => fn2("SIN", [value]);
7455
- var sqrt = (value) => fn2("SQRT", [value]);
7456
- var tan = (value) => fn2("TAN", [value]);
7457
- var trunc = (value, decimals) => decimals === void 0 ? fn2("TRUNC", [value]) : fn2("TRUNC", [value, decimals]);
7458
- 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]);
7459
8150
 
7460
8151
  // src/core/functions/datetime.ts
7461
8152
  var isColumnDef3 = (val) => !!val && typeof val === "object" && "type" in val && "name" in val;
@@ -7464,29 +8155,29 @@ var toOperand4 = (input) => {
7464
8155
  if (isColumnDef3(input)) return columnOperand(input);
7465
8156
  return valueToOperand(input);
7466
8157
  };
7467
- var fn3 = (key, args) => ({
8158
+ var fn4 = (key, args) => ({
7468
8159
  type: "Function",
7469
8160
  name: key,
7470
8161
  args: args.map(toOperand4)
7471
8162
  });
7472
- var now = () => fn3("NOW", []);
7473
- var currentDate = () => fn3("CURRENT_DATE", []);
7474
- var currentTime = () => fn3("CURRENT_TIME", []);
7475
- var utcNow = () => fn3("UTC_NOW", []);
7476
- var extract = (part, date) => fn3("EXTRACT", [part, date]);
7477
- var year = (date) => fn3("YEAR", [date]);
7478
- var month = (date) => fn3("MONTH", [date]);
7479
- var day = (date) => fn3("DAY", [date]);
7480
- var dateAdd = (date, interval, unit) => fn3("DATE_ADD", [date, interval, unit]);
7481
- var dateSub = (date, interval, unit) => fn3("DATE_SUB", [date, interval, unit]);
7482
- var dateDiff = (date1, date2) => fn3("DATE_DIFF", [date1, date2]);
7483
- var dateFormat = (date, format) => fn3("DATE_FORMAT", [date, format]);
7484
- var unixTimestamp = () => fn3("UNIX_TIMESTAMP", []);
7485
- var fromUnixTime = (timestamp) => fn3("FROM_UNIXTIME", [timestamp]);
7486
- var endOfMonth = (date) => fn3("END_OF_MONTH", [date]);
7487
- var dayOfWeek = (date) => fn3("DAY_OF_WEEK", [date]);
7488
- var weekOfYear = (date) => fn3("WEEK_OF_YEAR", [date]);
7489
- 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]);
7490
8181
 
7491
8182
  // src/orm/als.ts
7492
8183
  var AsyncLocalStorage = class {
@@ -7721,6 +8412,7 @@ var TypeScriptGenerator = class {
7721
8412
  case "ScalarSubquery":
7722
8413
  case "CaseExpression":
7723
8414
  case "WindowFunction":
8415
+ case "Cast":
7724
8416
  return this.printOperand(term);
7725
8417
  default:
7726
8418
  return this.printExpression(term);
@@ -7780,6 +8472,9 @@ var TypeScriptGenerator = class {
7780
8472
  visitWindowFunction(node) {
7781
8473
  return this.printWindowFunctionOperand(node);
7782
8474
  }
8475
+ visitCast(node) {
8476
+ return this.printCastOperand(node);
8477
+ }
7783
8478
  visitAliasRef(node) {
7784
8479
  return `aliasRef('${node.name}')`;
7785
8480
  }
@@ -7791,12 +8486,12 @@ var TypeScriptGenerator = class {
7791
8486
  printBinaryExpression(binary) {
7792
8487
  const left2 = this.printOperand(binary.left);
7793
8488
  const right2 = this.printOperand(binary.right);
7794
- const fn4 = this.mapOp(binary.operator);
8489
+ const fn5 = this.mapOp(binary.operator);
7795
8490
  const args = [left2, right2];
7796
8491
  if (binary.escape) {
7797
8492
  args.push(this.printOperand(binary.escape));
7798
8493
  }
7799
- return `${fn4}(${args.join(", ")})`;
8494
+ return `${fn5}(${args.join(", ")})`;
7800
8495
  }
7801
8496
  /**
7802
8497
  * Prints a logical expression to TypeScript code
@@ -7825,13 +8520,13 @@ var TypeScriptGenerator = class {
7825
8520
  */
7826
8521
  printInExpression(inExpr) {
7827
8522
  const left2 = this.printOperand(inExpr.left);
7828
- const fn4 = this.mapOp(inExpr.operator);
8523
+ const fn5 = this.mapOp(inExpr.operator);
7829
8524
  if (Array.isArray(inExpr.right)) {
7830
8525
  const values = inExpr.right.map((v) => this.printOperand(v)).join(", ");
7831
- return `${fn4}(${left2}, [${values}])`;
8526
+ return `${fn5}(${left2}, [${values}])`;
7832
8527
  }
7833
8528
  const subquery = this.inlineChain(this.buildSelectLines(inExpr.right.query));
7834
- return `${fn4}(${left2}, (${subquery}))`;
8529
+ return `${fn5}(${left2}, (${subquery}))`;
7835
8530
  }
7836
8531
  /**
7837
8532
  * Prints a null expression to TypeScript code
@@ -7840,8 +8535,8 @@ var TypeScriptGenerator = class {
7840
8535
  */
7841
8536
  printNullExpression(nullExpr) {
7842
8537
  const left2 = this.printOperand(nullExpr.left);
7843
- const fn4 = this.mapOp(nullExpr.operator);
7844
- return `${fn4}(${left2})`;
8538
+ const fn5 = this.mapOp(nullExpr.operator);
8539
+ return `${fn5}(${left2})`;
7845
8540
  }
7846
8541
  /**
7847
8542
  * Prints a BETWEEN expression to TypeScript code
@@ -7885,9 +8580,9 @@ var TypeScriptGenerator = class {
7885
8580
  * @param fn - Function node
7886
8581
  * @returns TypeScript code representation
7887
8582
  */
7888
- printFunctionOperand(fn4) {
7889
- const args = fn4.args.map((a) => this.printOperand(a)).join(", ");
7890
- 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})`;
7891
8586
  }
7892
8587
  /**
7893
8588
  * Prints a JSON path operand to TypeScript code
@@ -7947,6 +8642,10 @@ var TypeScriptGenerator = class {
7947
8642
  result += ")";
7948
8643
  return result;
7949
8644
  }
8645
+ printCastOperand(node) {
8646
+ const typeLiteral = node.castType.replace(/'/g, "\\'");
8647
+ return `cast(${this.printOperand(node.expression)}, '${typeLiteral}')`;
8648
+ }
7950
8649
  /**
7951
8650
  * Converts method chain lines to inline format
7952
8651
  * @param lines - Method chain lines
@@ -9111,15 +9810,15 @@ var OrmSession = class {
9111
9810
  * @returns The result of the function
9112
9811
  * @throws If the transaction fails
9113
9812
  */
9114
- async transaction(fn4) {
9813
+ async transaction(fn5) {
9115
9814
  if (!this.executor.capabilities.transactions) {
9116
- const result = await fn4(this);
9815
+ const result = await fn5(this);
9117
9816
  await this.commit();
9118
9817
  return result;
9119
9818
  }
9120
9819
  await this.executor.beginTransaction();
9121
9820
  try {
9122
- const result = await fn4(this);
9821
+ const result = await fn5(this);
9123
9822
  await this.flushWithHooks();
9124
9823
  await this.executor.commitTransaction();
9125
9824
  await this.domainEvents.dispatch(this.unitOfWork.getTracked(), this);
@@ -9222,11 +9921,11 @@ var Orm = class {
9222
9921
  * @returns The result of the function
9223
9922
  * @throws If the transaction fails
9224
9923
  */
9225
- async transaction(fn4) {
9924
+ async transaction(fn5) {
9226
9925
  const executor = this.executorFactory.createTransactionalExecutor();
9227
9926
  const session = new OrmSession({ orm: this, executor });
9228
9927
  try {
9229
- return await session.transaction(() => fn4(session));
9928
+ return await session.transaction(() => fn5(session));
9230
9929
  } finally {
9231
9930
  await session.dispose();
9232
9931
  }
@@ -10046,6 +10745,7 @@ function createPooledExecutorFactory(opts) {
10046
10745
  between,
10047
10746
  bootstrapEntities,
10048
10747
  caseWhen,
10748
+ cast,
10049
10749
  ceil,
10050
10750
  ceiling,
10051
10751
  char,
@@ -10113,6 +10813,7 @@ function createPooledExecutorFactory(opts) {
10113
10813
  instr,
10114
10814
  introspectSchema,
10115
10815
  isCaseExpressionNode,
10816
+ isCastExpressionNode,
10116
10817
  isExpressionSelectionNode,
10117
10818
  isFunctionNode,
10118
10819
  isNotNull,