metal-orm 1.0.46 → 1.0.48

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  var __defProp = Object.defineProperty;
2
2
  var __getOwnPropNames = Object.getOwnPropertyNames;
3
- var __esm = (fn4, res) => function __init() {
4
- return fn4 && (res = (0, fn4[__getOwnPropNames(fn4)[0]])(fn4 = 0)), res;
3
+ var __esm = (fn5, res) => function __init() {
4
+ return fn5 && (res = (0, fn5[__getOwnPropNames(fn5)[0]])(fn5 = 0)), res;
5
5
  };
6
6
  var __export = (target, all) => {
7
7
  for (var name in all)
@@ -357,7 +357,9 @@ var operandTypes = /* @__PURE__ */ new Set([
357
357
  "JsonPath",
358
358
  "ScalarSubquery",
359
359
  "CaseExpression",
360
- "WindowFunction"
360
+ "Cast",
361
+ "WindowFunction",
362
+ "ArithmeticExpression"
361
363
  ]);
362
364
  var hasTypeProperty = (value) => typeof value === "object" && value !== null && "type" in value;
363
365
  var isOperandNode = (node) => {
@@ -366,8 +368,9 @@ var isOperandNode = (node) => {
366
368
  };
367
369
  var isFunctionNode = (node) => isOperandNode(node) && node.type === "Function";
368
370
  var isCaseExpressionNode = (node) => isOperandNode(node) && node.type === "CaseExpression";
371
+ var isCastExpressionNode = (node) => isOperandNode(node) && node.type === "Cast";
369
372
  var isWindowFunctionNode = (node) => isOperandNode(node) && node.type === "WindowFunction";
370
- var isExpressionSelectionNode = (node) => isFunctionNode(node) || isCaseExpressionNode(node) || isWindowFunctionNode(node);
373
+ var isExpressionSelectionNode = (node) => isFunctionNode(node) || isCaseExpressionNode(node) || isCastExpressionNode(node) || isWindowFunctionNode(node);
371
374
 
372
375
  // src/core/ast/expression-builders.ts
373
376
  var isLiteralValue = (value) => value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean";
@@ -503,6 +506,11 @@ var caseWhen = (conditions, elseValue) => ({
503
506
  })),
504
507
  else: elseValue !== void 0 ? toOperand(elseValue) : void 0
505
508
  });
509
+ var cast = (expression, castType) => ({
510
+ type: "Cast",
511
+ expression: toOperand(expression),
512
+ castType
513
+ });
506
514
  var exists = (subquery) => ({
507
515
  type: "ExistsExpression",
508
516
  operator: "EXISTS",
@@ -760,6 +768,9 @@ var visitOperand = (node, visitor) => {
760
768
  case "AliasRef":
761
769
  if (visitor.visitAliasRef) return visitor.visitAliasRef(node);
762
770
  break;
771
+ case "Cast":
772
+ if (visitor.visitCast) return visitor.visitCast(node);
773
+ break;
763
774
  default:
764
775
  break;
765
776
  }
@@ -1286,6 +1297,10 @@ var Dialect = class _Dialect {
1286
1297
  parts.push("END");
1287
1298
  return parts.join(" ");
1288
1299
  });
1300
+ this.registerOperandCompiler("Cast", (node, ctx) => {
1301
+ const value = this.compileOperand(node.expression, ctx);
1302
+ return `CAST(${value} AS ${node.castType})`;
1303
+ });
1289
1304
  this.registerOperandCompiler("WindowFunction", (node, ctx) => {
1290
1305
  let result = `${node.name}(`;
1291
1306
  if (node.args.length > 0) {
@@ -1312,6 +1327,11 @@ var Dialect = class _Dialect {
1312
1327
  result += ")";
1313
1328
  return result;
1314
1329
  });
1330
+ this.registerOperandCompiler("ArithmeticExpression", (node, ctx) => {
1331
+ const left2 = this.compileOperand(node.left, ctx);
1332
+ const right2 = this.compileOperand(node.right, ctx);
1333
+ return `(${left2} ${node.operator} ${right2})`;
1334
+ });
1315
1335
  }
1316
1336
  // Default fallback, should be overridden by dialects if supported
1317
1337
  compileJsonPath(_node) {
@@ -1344,13 +1364,13 @@ var FunctionTableFormatter = class {
1344
1364
  * @param dialect - The dialect instance for compiling operands.
1345
1365
  * @returns SQL function table expression (e.g., "LATERAL schema.func(args) WITH ORDINALITY AS alias(col1, col2)").
1346
1366
  */
1347
- static format(fn4, ctx, dialect) {
1348
- const schemaPart = this.formatSchema(fn4, dialect);
1349
- const args = this.formatArgs(fn4, ctx, dialect);
1350
- const base = this.formatBase(fn4, schemaPart, args, dialect);
1351
- const lateral = this.formatLateral(fn4);
1352
- const alias = this.formatAlias(fn4, dialect);
1353
- const colAliases = this.formatColumnAliases(fn4, dialect);
1367
+ static format(fn5, ctx, dialect) {
1368
+ const schemaPart = this.formatSchema(fn5, dialect);
1369
+ const args = this.formatArgs(fn5, ctx, dialect);
1370
+ const base = this.formatBase(fn5, schemaPart, args, dialect);
1371
+ const lateral = this.formatLateral(fn5);
1372
+ const alias = this.formatAlias(fn5, dialect);
1373
+ const colAliases = this.formatColumnAliases(fn5, dialect);
1354
1374
  return `${lateral}${base}${alias}${colAliases}`;
1355
1375
  }
1356
1376
  /**
@@ -1360,9 +1380,9 @@ var FunctionTableFormatter = class {
1360
1380
  * @returns Schema prefix (e.g., "schema.") or empty string.
1361
1381
  * @internal
1362
1382
  */
1363
- static formatSchema(fn4, dialect) {
1364
- if (!fn4.schema) return "";
1365
- const quoted = dialect ? dialect.quoteIdentifier(fn4.schema) : fn4.schema;
1383
+ static formatSchema(fn5, dialect) {
1384
+ if (!fn5.schema) return "";
1385
+ const quoted = dialect ? dialect.quoteIdentifier(fn5.schema) : fn5.schema;
1366
1386
  return `${quoted}.`;
1367
1387
  }
1368
1388
  /**
@@ -1373,8 +1393,8 @@ var FunctionTableFormatter = class {
1373
1393
  * @returns Comma-separated function arguments.
1374
1394
  * @internal
1375
1395
  */
1376
- static formatArgs(fn4, ctx, dialect) {
1377
- return (fn4.args || []).map((a) => {
1396
+ static formatArgs(fn5, ctx, dialect) {
1397
+ return (fn5.args || []).map((a) => {
1378
1398
  if (ctx && dialect) {
1379
1399
  return dialect.compileOperand(a, ctx);
1380
1400
  }
@@ -1390,9 +1410,9 @@ var FunctionTableFormatter = class {
1390
1410
  * @returns Base function call expression (e.g., "schema.func(args) WITH ORDINALITY").
1391
1411
  * @internal
1392
1412
  */
1393
- static formatBase(fn4, schemaPart, args, dialect) {
1394
- const ordinality = fn4.withOrdinality ? " WITH ORDINALITY" : "";
1395
- const quoted = dialect ? dialect.quoteIdentifier(fn4.name) : fn4.name;
1413
+ static formatBase(fn5, schemaPart, args, dialect) {
1414
+ const ordinality = fn5.withOrdinality ? " WITH ORDINALITY" : "";
1415
+ const quoted = dialect ? dialect.quoteIdentifier(fn5.name) : fn5.name;
1396
1416
  return `${schemaPart}${quoted}(${args})${ordinality}`;
1397
1417
  }
1398
1418
  /**
@@ -1401,8 +1421,8 @@ var FunctionTableFormatter = class {
1401
1421
  * @returns "LATERAL " or empty string.
1402
1422
  * @internal
1403
1423
  */
1404
- static formatLateral(fn4) {
1405
- return fn4.lateral ? "LATERAL " : "";
1424
+ static formatLateral(fn5) {
1425
+ return fn5.lateral ? "LATERAL " : "";
1406
1426
  }
1407
1427
  /**
1408
1428
  * Formats the table alias for the function table.
@@ -1411,9 +1431,9 @@ var FunctionTableFormatter = class {
1411
1431
  * @returns " AS alias" or empty string.
1412
1432
  * @internal
1413
1433
  */
1414
- static formatAlias(fn4, dialect) {
1415
- if (!fn4.alias) return "";
1416
- const quoted = dialect ? dialect.quoteIdentifier(fn4.alias) : fn4.alias;
1434
+ static formatAlias(fn5, dialect) {
1435
+ if (!fn5.alias) return "";
1436
+ const quoted = dialect ? dialect.quoteIdentifier(fn5.alias) : fn5.alias;
1417
1437
  return ` AS ${quoted}`;
1418
1438
  }
1419
1439
  /**
@@ -1423,9 +1443,9 @@ var FunctionTableFormatter = class {
1423
1443
  * @returns "(col1, col2, ...)" or empty string.
1424
1444
  * @internal
1425
1445
  */
1426
- static formatColumnAliases(fn4, dialect) {
1427
- if (!fn4.columnAliases || !fn4.columnAliases.length) return "";
1428
- const aliases = fn4.columnAliases.map((col2) => dialect ? dialect.quoteIdentifier(col2) : col2).join(", ");
1446
+ static formatColumnAliases(fn5, dialect) {
1447
+ if (!fn5.columnAliases || !fn5.columnAliases.length) return "";
1448
+ const aliases = fn5.columnAliases.map((col2) => dialect ? dialect.quoteIdentifier(col2) : col2).join(", ");
1429
1449
  return `(${aliases})`;
1430
1450
  }
1431
1451
  };
@@ -1693,8 +1713,8 @@ var SqlDialectBase = class extends Dialect {
1693
1713
  }
1694
1714
  return this.compileTableSource(tableSource);
1695
1715
  }
1696
- compileFunctionTable(fn4, ctx) {
1697
- return FunctionTableFormatter.format(fn4, ctx, this);
1716
+ compileFunctionTable(fn5, ctx) {
1717
+ return FunctionTableFormatter.format(fn5, ctx, this);
1698
1718
  }
1699
1719
  compileDerivedTable(table, ctx) {
1700
1720
  if (!table.alias) {
@@ -2318,16 +2338,7 @@ var SqlServerDialect = class extends SqlDialectBase {
2318
2338
  }
2319
2339
  compileSelectCoreForMssql(ast, ctx) {
2320
2340
  const columns = ast.columns.map((c) => {
2321
- let expr = "";
2322
- if (c.type === "Function") {
2323
- expr = this.compileOperand(c, ctx);
2324
- } else if (c.type === "Column") {
2325
- expr = `${this.quoteIdentifier(c.table)}.${this.quoteIdentifier(c.name)}`;
2326
- } else if (c.type === "ScalarSubquery") {
2327
- expr = this.compileOperand(c, ctx);
2328
- } else if (c.type === "WindowFunction") {
2329
- expr = this.compileOperand(c, ctx);
2330
- }
2341
+ const expr = c.type === "Column" ? `${this.quoteIdentifier(c.table)}.${this.quoteIdentifier(c.name)}` : this.compileOperand(c, ctx);
2331
2342
  if (c.alias) {
2332
2343
  if (c.alias.includes("(")) return c.alias;
2333
2344
  return `${expr} AS ${this.quoteIdentifier(c.alias)}`;
@@ -6601,15 +6612,11 @@ var PgReferentialConstraints = defineTable(
6601
6612
  async function runSelect(qb, ctx) {
6602
6613
  const ast = qb.getAST();
6603
6614
  const compiled = ctx.dialect.compileSelect(ast);
6604
- const results = await ctx.executor.executeSql(compiled.sql, compiled.params);
6605
- const [first] = results;
6606
- return toRows(first);
6615
+ return await queryRows(ctx.executor, compiled.sql, compiled.params);
6607
6616
  }
6608
6617
  async function runSelectNode(ast, ctx) {
6609
6618
  const compiled = ctx.dialect.compileSelect(ast);
6610
- const results = await ctx.executor.executeSql(compiled.sql, compiled.params);
6611
- const [first] = results;
6612
- return toRows(first);
6619
+ return await queryRows(ctx.executor, compiled.sql, compiled.params);
6613
6620
  }
6614
6621
 
6615
6622
  // src/core/ddl/introspect/postgres.ts
@@ -6634,6 +6641,32 @@ var postgresIntrospector = {
6634
6641
  ordinal_position: PgInformationSchemaColumns.columns.ordinal_position
6635
6642
  }).where(eq(PgInformationSchemaColumns.columns.table_schema, schema)).orderBy(PgInformationSchemaColumns.columns.table_name).orderBy(PgInformationSchemaColumns.columns.ordinal_position);
6636
6643
  const columnRows = await runSelect(qbColumns, ctx);
6644
+ const columnCommentRows = await queryRows(
6645
+ ctx.executor,
6646
+ `
6647
+ SELECT
6648
+ ns.nspname AS table_schema,
6649
+ cls.relname AS table_name,
6650
+ att.attname AS column_name,
6651
+ pg_catalog.col_description(cls.oid, att.attnum) AS description
6652
+ FROM pg_catalog.pg_attribute att
6653
+ JOIN pg_catalog.pg_class cls ON cls.oid = att.attrelid
6654
+ JOIN pg_catalog.pg_namespace ns ON ns.oid = cls.relnamespace
6655
+ WHERE ns.nspname = $1
6656
+ AND att.attnum > 0
6657
+ AND NOT att.attisdropped
6658
+ `,
6659
+ [schema]
6660
+ );
6661
+ const columnComments = /* @__PURE__ */ new Map();
6662
+ columnCommentRows.forEach((r) => {
6663
+ if (!shouldIncludeTable(r.table_name, options)) return;
6664
+ if (!r.description) return;
6665
+ const key = `${r.table_schema}.${r.table_name}.${r.column_name}`;
6666
+ const trimmed = r.description.trim();
6667
+ if (!trimmed) return;
6668
+ columnComments.set(key, trimmed);
6669
+ });
6637
6670
  const qbPk = new SelectQueryBuilder(PgKeyColumnUsage).select({
6638
6671
  table_schema: PgKeyColumnUsage.columns.table_schema,
6639
6672
  table_name: PgKeyColumnUsage.columns.table_name,
@@ -6661,7 +6694,9 @@ var postgresIntrospector = {
6661
6694
  constraint_name: PgKeyColumnUsage.columns.constraint_name,
6662
6695
  foreign_table_schema: PgConstraintColumnUsage.columns.table_schema,
6663
6696
  foreign_table_name: PgConstraintColumnUsage.columns.table_name,
6664
- foreign_column_name: PgConstraintColumnUsage.columns.column_name
6697
+ foreign_column_name: PgConstraintColumnUsage.columns.column_name,
6698
+ delete_rule: PgReferentialConstraints.columns.delete_rule,
6699
+ update_rule: PgReferentialConstraints.columns.update_rule
6665
6700
  }).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));
6666
6701
  const fkRows = await runSelect(qbFk, ctx);
6667
6702
  const fkMap = /* @__PURE__ */ new Map();
@@ -6671,8 +6706,8 @@ var postgresIntrospector = {
6671
6706
  existing.push({
6672
6707
  table: `${r.foreign_table_schema}.${r.foreign_table_name}`,
6673
6708
  column: r.foreign_column_name,
6674
- onDelete: void 0,
6675
- onUpdate: void 0
6709
+ onDelete: r.delete_rule,
6710
+ onUpdate: r.update_rule
6676
6711
  });
6677
6712
  fkMap.set(key, existing);
6678
6713
  }
@@ -6776,12 +6811,15 @@ var postgresIntrospector = {
6776
6811
  });
6777
6812
  }
6778
6813
  const cols = tablesByKey.get(key);
6814
+ const commentKey = `${r.table_schema}.${r.table_name}.${r.column_name}`;
6815
+ const columnComment = columnComments.get(commentKey);
6779
6816
  const fk = fkMap.get(`${r.table_schema}.${r.table_name}.${r.column_name}`)?.[0];
6780
6817
  const column = {
6781
6818
  name: r.column_name,
6782
6819
  type: r.data_type,
6783
6820
  notNull: r.is_nullable === "NO",
6784
6821
  default: r.column_default ?? void 0,
6822
+ comment: columnComment ?? void 0,
6785
6823
  references: fk ? {
6786
6824
  table: fk.table,
6787
6825
  column: fk.column,
@@ -6809,32 +6847,252 @@ var postgresIntrospector = {
6809
6847
  }
6810
6848
  };
6811
6849
 
6850
+ // src/core/ddl/introspect/catalogs/mysql.ts
6851
+ var INFORMATION_SCHEMA = "information_schema";
6852
+ var InformationSchemaTables = defineTable(
6853
+ "tables",
6854
+ {
6855
+ table_schema: col.varchar(255),
6856
+ table_name: col.varchar(255),
6857
+ table_comment: col.varchar(1024)
6858
+ },
6859
+ {},
6860
+ void 0,
6861
+ { schema: INFORMATION_SCHEMA }
6862
+ );
6863
+ var InformationSchemaColumns = defineTable(
6864
+ "columns",
6865
+ {
6866
+ table_schema: col.varchar(255),
6867
+ table_name: col.varchar(255),
6868
+ column_name: col.varchar(255),
6869
+ column_type: col.varchar(255),
6870
+ data_type: col.varchar(255),
6871
+ is_nullable: col.varchar(3),
6872
+ column_default: col.varchar(1024),
6873
+ extra: col.varchar(255),
6874
+ column_comment: col.varchar(1024),
6875
+ ordinal_position: col.int()
6876
+ },
6877
+ {},
6878
+ void 0,
6879
+ { schema: INFORMATION_SCHEMA }
6880
+ );
6881
+ var InformationSchemaKeyColumnUsage = defineTable(
6882
+ "key_column_usage",
6883
+ {
6884
+ constraint_schema: col.varchar(255),
6885
+ constraint_name: col.varchar(255),
6886
+ table_schema: col.varchar(255),
6887
+ table_name: col.varchar(255),
6888
+ column_name: col.varchar(255),
6889
+ ordinal_position: col.int(),
6890
+ referenced_table_schema: col.varchar(255),
6891
+ referenced_table_name: col.varchar(255),
6892
+ referenced_column_name: col.varchar(255)
6893
+ },
6894
+ {},
6895
+ void 0,
6896
+ { schema: INFORMATION_SCHEMA }
6897
+ );
6898
+ var InformationSchemaReferentialConstraints = defineTable(
6899
+ "referential_constraints",
6900
+ {
6901
+ constraint_schema: col.varchar(255),
6902
+ constraint_name: col.varchar(255),
6903
+ delete_rule: col.varchar(255),
6904
+ update_rule: col.varchar(255)
6905
+ },
6906
+ {},
6907
+ void 0,
6908
+ { schema: INFORMATION_SCHEMA }
6909
+ );
6910
+ var InformationSchemaStatistics = defineTable(
6911
+ "statistics",
6912
+ {
6913
+ table_schema: col.varchar(255),
6914
+ table_name: col.varchar(255),
6915
+ index_name: col.varchar(255),
6916
+ non_unique: col.int(),
6917
+ column_name: col.varchar(255),
6918
+ seq_in_index: col.int()
6919
+ },
6920
+ {},
6921
+ void 0,
6922
+ { schema: INFORMATION_SCHEMA }
6923
+ );
6924
+
6812
6925
  // src/core/ddl/introspect/mysql.ts
6926
+ var tableNode = (table, alias) => ({
6927
+ type: "Table",
6928
+ name: table.name,
6929
+ schema: table.schema,
6930
+ alias
6931
+ });
6932
+ var columnNode = (table, name, alias) => ({
6933
+ type: "Column",
6934
+ table,
6935
+ name,
6936
+ alias
6937
+ });
6938
+ var combineConditions = (...expressions) => {
6939
+ const filtered = expressions.filter(Boolean);
6940
+ if (!filtered.length) return void 0;
6941
+ if (filtered.length === 1) return filtered[0];
6942
+ return and(...filtered);
6943
+ };
6944
+ var databaseFunction = {
6945
+ type: "Function",
6946
+ name: "DATABASE",
6947
+ fn: "DATABASE",
6948
+ args: []
6949
+ };
6813
6950
  var mysqlIntrospector = {
6814
6951
  async introspect(ctx, options) {
6815
6952
  const schema = options.schema;
6816
- const filterClause = schema ? "table_schema = ?" : "table_schema = database()";
6817
- const params = schema ? [schema] : [];
6818
- const columnRows = await queryRows(
6819
- ctx.executor,
6820
- `
6821
- SELECT table_schema, table_name, column_name, data_type, is_nullable, column_default, extra
6822
- FROM information_schema.columns
6823
- WHERE ${filterClause}
6824
- ORDER BY table_name, ordinal_position
6825
- `,
6826
- params
6827
- );
6828
- const pkRows = await queryRows(
6829
- ctx.executor,
6830
- `
6831
- SELECT table_schema, table_name, column_name
6832
- FROM information_schema.key_column_usage
6833
- WHERE constraint_name = 'PRIMARY' AND ${filterClause}
6834
- ORDER BY ordinal_position
6835
- `,
6836
- params
6837
- );
6953
+ const buildSchemaCondition = (alias) => schema ? eq(columnNode(alias, "table_schema"), schema) : eq(columnNode(alias, "table_schema"), databaseFunction);
6954
+ const tablesQuery = {
6955
+ type: "SelectQuery",
6956
+ from: tableNode(InformationSchemaTables, "t"),
6957
+ columns: [
6958
+ columnNode("t", "table_schema"),
6959
+ columnNode("t", "table_name"),
6960
+ columnNode("t", "table_comment")
6961
+ ],
6962
+ joins: [],
6963
+ where: buildSchemaCondition("t")
6964
+ };
6965
+ const columnsQuery = {
6966
+ type: "SelectQuery",
6967
+ from: tableNode(InformationSchemaColumns, "c"),
6968
+ columns: [
6969
+ columnNode("c", "table_schema"),
6970
+ columnNode("c", "table_name"),
6971
+ columnNode("c", "column_name"),
6972
+ columnNode("c", "column_type"),
6973
+ columnNode("c", "data_type"),
6974
+ columnNode("c", "is_nullable"),
6975
+ columnNode("c", "column_default"),
6976
+ columnNode("c", "extra"),
6977
+ columnNode("c", "column_comment")
6978
+ ],
6979
+ joins: [],
6980
+ where: buildSchemaCondition("c"),
6981
+ orderBy: [
6982
+ {
6983
+ type: "OrderBy",
6984
+ term: columnNode("c", "table_name"),
6985
+ direction: "ASC"
6986
+ },
6987
+ {
6988
+ type: "OrderBy",
6989
+ term: columnNode("c", "ordinal_position"),
6990
+ direction: "ASC"
6991
+ }
6992
+ ]
6993
+ };
6994
+ const pkQuery = {
6995
+ type: "SelectQuery",
6996
+ from: tableNode(InformationSchemaKeyColumnUsage, "kcu"),
6997
+ columns: [
6998
+ columnNode("kcu", "table_schema"),
6999
+ columnNode("kcu", "table_name"),
7000
+ columnNode("kcu", "column_name")
7001
+ ],
7002
+ joins: [],
7003
+ where: combineConditions(
7004
+ eq(columnNode("kcu", "constraint_name"), "PRIMARY"),
7005
+ buildSchemaCondition("kcu")
7006
+ ),
7007
+ orderBy: [
7008
+ {
7009
+ type: "OrderBy",
7010
+ term: columnNode("kcu", "ordinal_position"),
7011
+ direction: "ASC"
7012
+ }
7013
+ ]
7014
+ };
7015
+ const fkQuery = {
7016
+ type: "SelectQuery",
7017
+ from: tableNode(InformationSchemaKeyColumnUsage, "kcu"),
7018
+ columns: [
7019
+ columnNode("kcu", "table_schema"),
7020
+ columnNode("kcu", "table_name"),
7021
+ columnNode("kcu", "column_name"),
7022
+ columnNode("kcu", "constraint_name"),
7023
+ columnNode("kcu", "referenced_table_schema"),
7024
+ columnNode("kcu", "referenced_table_name"),
7025
+ columnNode("kcu", "referenced_column_name"),
7026
+ columnNode("rc", "delete_rule"),
7027
+ columnNode("rc", "update_rule")
7028
+ ],
7029
+ joins: [
7030
+ {
7031
+ type: "Join",
7032
+ kind: "INNER",
7033
+ table: tableNode(InformationSchemaReferentialConstraints, "rc"),
7034
+ condition: and(
7035
+ eq({ table: "rc", name: "constraint_schema" }, { table: "kcu", name: "constraint_schema" }),
7036
+ eq({ table: "rc", name: "constraint_name" }, { table: "kcu", name: "constraint_name" })
7037
+ )
7038
+ }
7039
+ ],
7040
+ where: combineConditions(
7041
+ isNotNull(columnNode("kcu", "referenced_table_name")),
7042
+ buildSchemaCondition("kcu")
7043
+ ),
7044
+ orderBy: [
7045
+ {
7046
+ type: "OrderBy",
7047
+ term: columnNode("kcu", "table_name"),
7048
+ direction: "ASC"
7049
+ },
7050
+ {
7051
+ type: "OrderBy",
7052
+ term: columnNode("kcu", "ordinal_position"),
7053
+ direction: "ASC"
7054
+ }
7055
+ ]
7056
+ };
7057
+ const indexQuery = {
7058
+ type: "SelectQuery",
7059
+ from: tableNode(InformationSchemaStatistics, "stats"),
7060
+ columns: [
7061
+ columnNode("stats", "table_schema"),
7062
+ columnNode("stats", "table_name"),
7063
+ columnNode("stats", "index_name"),
7064
+ columnNode("stats", "non_unique"),
7065
+ {
7066
+ ...groupConcat(columnNode("stats", "column_name"), {
7067
+ orderBy: [{ column: columnNode("stats", "seq_in_index") }]
7068
+ }),
7069
+ alias: "cols"
7070
+ }
7071
+ ],
7072
+ joins: [],
7073
+ where: combineConditions(
7074
+ neq(columnNode("stats", "index_name"), "PRIMARY"),
7075
+ buildSchemaCondition("stats")
7076
+ ),
7077
+ groupBy: [
7078
+ columnNode("stats", "table_schema"),
7079
+ columnNode("stats", "table_name"),
7080
+ columnNode("stats", "index_name"),
7081
+ columnNode("stats", "non_unique")
7082
+ ]
7083
+ };
7084
+ const tableRows = await runSelectNode(tablesQuery, ctx);
7085
+ const columnRows = await runSelectNode(columnsQuery, ctx);
7086
+ const pkRows = await runSelectNode(pkQuery, ctx);
7087
+ const fkRows = await runSelectNode(fkQuery, ctx);
7088
+ const indexRows = await runSelectNode(indexQuery, ctx);
7089
+ const tableComments = /* @__PURE__ */ new Map();
7090
+ tableRows.forEach((r) => {
7091
+ const key = `${r.table_schema}.${r.table_name}`;
7092
+ if (r.table_comment) {
7093
+ tableComments.set(key, r.table_comment);
7094
+ }
7095
+ });
6838
7096
  const pkMap = /* @__PURE__ */ new Map();
6839
7097
  pkRows.forEach((r) => {
6840
7098
  const key = `${r.table_schema}.${r.table_name}`;
@@ -6842,21 +7100,19 @@ var mysqlIntrospector = {
6842
7100
  list.push(r.column_name);
6843
7101
  pkMap.set(key, list);
6844
7102
  });
6845
- const indexRows = await queryRows(
6846
- ctx.executor,
6847
- `
6848
- SELECT
6849
- table_schema,
6850
- table_name,
6851
- index_name,
6852
- non_unique,
6853
- GROUP_CONCAT(column_name ORDER BY seq_in_index) AS cols
6854
- FROM information_schema.statistics
6855
- WHERE ${filterClause} AND index_name <> 'PRIMARY'
6856
- GROUP BY table_schema, table_name, index_name, non_unique
6857
- `,
6858
- params
6859
- );
7103
+ const fkMap = /* @__PURE__ */ new Map();
7104
+ fkRows.forEach((r) => {
7105
+ const key = `${r.table_schema}.${r.table_name}.${r.column_name}`;
7106
+ const list = fkMap.get(key) || [];
7107
+ list.push({
7108
+ table: `${r.referenced_table_schema}.${r.referenced_table_name}`,
7109
+ column: r.referenced_column_name,
7110
+ onDelete: r.delete_rule,
7111
+ onUpdate: r.update_rule,
7112
+ name: r.constraint_name
7113
+ });
7114
+ fkMap.set(key, list);
7115
+ });
6860
7116
  const tablesByKey = /* @__PURE__ */ new Map();
6861
7117
  columnRows.forEach((r) => {
6862
7118
  const key = `${r.table_schema}.${r.table_name}`;
@@ -6867,18 +7123,32 @@ var mysqlIntrospector = {
6867
7123
  schema: r.table_schema,
6868
7124
  columns: [],
6869
7125
  primaryKey: pkMap.get(key) || [],
6870
- indexes: []
7126
+ indexes: [],
7127
+ comment: tableComments.get(key) || void 0
6871
7128
  });
6872
7129
  }
6873
- const cols = tablesByKey.get(key);
7130
+ const table = tablesByKey.get(key);
7131
+ const columnType = r.column_type || r.data_type;
7132
+ const comment = r.column_comment?.trim() ? r.column_comment : void 0;
6874
7133
  const column = {
6875
7134
  name: r.column_name,
6876
- type: r.data_type,
7135
+ type: columnType,
6877
7136
  notNull: r.is_nullable === "NO",
6878
7137
  default: r.column_default ?? void 0,
6879
- autoIncrement: typeof r.extra === "string" && r.extra.includes("auto_increment")
7138
+ autoIncrement: typeof r.extra === "string" && r.extra.includes("auto_increment"),
7139
+ comment
6880
7140
  };
6881
- cols.columns.push(column);
7141
+ const fk = fkMap.get(`${key}.${r.column_name}`)?.[0];
7142
+ if (fk) {
7143
+ column.references = {
7144
+ table: fk.table,
7145
+ column: fk.column,
7146
+ onDelete: fk.onDelete,
7147
+ onUpdate: fk.onUpdate,
7148
+ name: fk.name
7149
+ };
7150
+ }
7151
+ table.columns.push(column);
6882
7152
  });
6883
7153
  indexRows.forEach((r) => {
6884
7154
  const key = `${r.table_schema}.${r.table_name}`;
@@ -6906,43 +7176,79 @@ var toReferentialAction = (value) => {
6906
7176
  }
6907
7177
  return void 0;
6908
7178
  };
6909
- var escapeSingleQuotes = (name) => name.replace(/'/g, "''");
7179
+ var columnNode2 = (table, name, alias) => ({
7180
+ type: "Column",
7181
+ table,
7182
+ name,
7183
+ alias
7184
+ });
7185
+ var buildPragmaQuery = (name, table, alias, columnAliases) => ({
7186
+ type: "SelectQuery",
7187
+ from: fnTable(name, [valueToOperand(table)], alias, { columnAliases }),
7188
+ columns: columnAliases.map((column) => columnNode2(alias, column)),
7189
+ joins: []
7190
+ });
7191
+ var runPragma = async (name, table, alias, columnAliases, ctx) => {
7192
+ const query = buildPragmaQuery(name, table, alias, columnAliases);
7193
+ return await runSelectNode(query, ctx);
7194
+ };
6910
7195
  var sqliteIntrospector = {
6911
- /**
6912
- * Introspects the SQLite database schema by querying sqlite_master and various PRAGMAs.
6913
- * @param ctx - The database execution context containing the DbExecutor.
6914
- * @param options - Options controlling which tables and schemas to include.
6915
- * @returns A promise that resolves to the introspected DatabaseSchema.
6916
- */
6917
7196
  async introspect(ctx, options) {
7197
+ const alias = "sqlite_master";
7198
+ const tablesQuery = {
7199
+ type: "SelectQuery",
7200
+ from: { type: "Table", name: "sqlite_master" },
7201
+ columns: [columnNode2(alias, "name")],
7202
+ joins: [],
7203
+ where: and(
7204
+ eq(columnNode2(alias, "type"), "table"),
7205
+ notLike(columnNode2(alias, "name"), "sqlite_%")
7206
+ )
7207
+ };
7208
+ const tableRows = await runSelectNode(tablesQuery, ctx);
6918
7209
  const tables = [];
6919
- const tableRows = await queryRows(
6920
- ctx.executor,
6921
- `SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%';`
6922
- );
6923
7210
  for (const row of tableRows) {
6924
- const name = row.name;
6925
- if (!shouldIncludeTable(name, options)) continue;
6926
- const table = { name, columns: [], primaryKey: [], indexes: [] };
6927
- const cols = await queryRows(ctx.executor, `PRAGMA table_info('${escapeSingleQuotes(name)}');`);
6928
- cols.forEach((c) => {
6929
- table.columns.push({
6930
- name: c.name,
6931
- type: c.type,
6932
- notNull: c.notnull === 1,
6933
- default: c.dflt_value ?? void 0,
7211
+ const tableName = row.name;
7212
+ if (!shouldIncludeTable(tableName, options)) continue;
7213
+ const tableInfo = await runPragma(
7214
+ "pragma_table_info",
7215
+ tableName,
7216
+ "ti",
7217
+ ["cid", "name", "type", "notnull", "dflt_value", "pk"],
7218
+ ctx
7219
+ );
7220
+ const foreignKeys = await runPragma(
7221
+ "pragma_foreign_key_list",
7222
+ tableName,
7223
+ "fk",
7224
+ ["id", "seq", "table", "from", "to", "on_update", "on_delete", "match"],
7225
+ ctx
7226
+ );
7227
+ const indexList = await runPragma(
7228
+ "pragma_index_list",
7229
+ tableName,
7230
+ "idx",
7231
+ ["seq", "name", "unique"],
7232
+ ctx
7233
+ );
7234
+ const tableEntry = { name: tableName, columns: [], primaryKey: [], indexes: [] };
7235
+ tableInfo.forEach((info) => {
7236
+ tableEntry.columns.push({
7237
+ name: info.name,
7238
+ type: info.type,
7239
+ notNull: info.notnull === 1,
7240
+ default: info.dflt_value ?? void 0,
6934
7241
  autoIncrement: false
6935
7242
  });
6936
- if (c.pk && c.pk > 0) {
6937
- table.primaryKey = table.primaryKey || [];
6938
- table.primaryKey.push(c.name);
7243
+ if (info.pk && info.pk > 0) {
7244
+ tableEntry.primaryKey = tableEntry.primaryKey || [];
7245
+ tableEntry.primaryKey.push(info.name);
6939
7246
  }
6940
7247
  });
6941
- const fkRows = await queryRows(ctx.executor, `PRAGMA foreign_key_list('${escapeSingleQuotes(name)}');`);
6942
- fkRows.forEach((fk) => {
6943
- const col2 = table.columns.find((c) => c.name === fk.from);
6944
- if (col2) {
6945
- col2.references = {
7248
+ foreignKeys.forEach((fk) => {
7249
+ const column = tableEntry.columns.find((col2) => col2.name === fk.from);
7250
+ if (column) {
7251
+ column.references = {
6946
7252
  table: fk.table,
6947
7253
  column: fk.to,
6948
7254
  onDelete: toReferentialAction(fk.on_delete),
@@ -6950,88 +7256,529 @@ var sqliteIntrospector = {
6950
7256
  };
6951
7257
  }
6952
7258
  });
6953
- const idxList = await queryRows(ctx.executor, `PRAGMA index_list('${escapeSingleQuotes(name)}');`);
6954
- for (const idx of idxList) {
6955
- const idxName = idx.name;
6956
- const columnsInfo = await queryRows(ctx.executor, `PRAGMA index_info('${escapeSingleQuotes(idxName)}');`);
7259
+ for (const idx of indexList) {
7260
+ if (!idx.name) continue;
7261
+ const indexColumns = await runPragma(
7262
+ "pragma_index_info",
7263
+ idx.name,
7264
+ "info",
7265
+ ["seqno", "cid", "name"],
7266
+ ctx
7267
+ );
6957
7268
  const idxEntry = {
6958
- name: idxName,
6959
- columns: columnsInfo.map((ci) => ({ column: ci.name })),
7269
+ name: idx.name,
7270
+ columns: indexColumns.map((col2) => ({ column: col2.name })),
6960
7271
  unique: idx.unique === 1
6961
7272
  };
6962
- table.indexes.push(idxEntry);
7273
+ tableEntry.indexes.push(idxEntry);
6963
7274
  }
6964
- tables.push(table);
7275
+ tables.push(tableEntry);
6965
7276
  }
6966
7277
  return { tables };
6967
7278
  }
6968
7279
  };
6969
7280
 
7281
+ // src/core/ddl/introspect/catalogs/mssql.ts
7282
+ var SysColumns = defineTable(
7283
+ "columns",
7284
+ {
7285
+ object_id: col.int(),
7286
+ name: col.varchar(255),
7287
+ column_id: col.int(),
7288
+ max_length: col.int(),
7289
+ precision: col.int(),
7290
+ scale: col.int(),
7291
+ is_nullable: col.boolean(),
7292
+ is_identity: col.boolean(),
7293
+ default_object_id: col.int(),
7294
+ user_type_id: col.int()
7295
+ },
7296
+ {},
7297
+ void 0,
7298
+ { schema: "sys" }
7299
+ );
7300
+ var SysTables = defineTable(
7301
+ "tables",
7302
+ {
7303
+ object_id: col.int(),
7304
+ name: col.varchar(255),
7305
+ schema_id: col.int(),
7306
+ is_ms_shipped: col.boolean()
7307
+ },
7308
+ {},
7309
+ void 0,
7310
+ { schema: "sys" }
7311
+ );
7312
+ var SysSchemas = defineTable(
7313
+ "schemas",
7314
+ {
7315
+ schema_id: col.int(),
7316
+ name: col.varchar(255)
7317
+ },
7318
+ {},
7319
+ void 0,
7320
+ { schema: "sys" }
7321
+ );
7322
+ var SysTypes = defineTable(
7323
+ "types",
7324
+ {
7325
+ user_type_id: col.int(),
7326
+ name: col.varchar(255)
7327
+ },
7328
+ {},
7329
+ void 0,
7330
+ { schema: "sys" }
7331
+ );
7332
+ var SysIndexes = defineTable(
7333
+ "indexes",
7334
+ {
7335
+ object_id: col.int(),
7336
+ index_id: col.int(),
7337
+ name: col.varchar(255),
7338
+ is_primary_key: col.boolean(),
7339
+ is_unique: col.boolean(),
7340
+ has_filter: col.boolean(),
7341
+ filter_definition: col.varchar(1024),
7342
+ is_hypothetical: col.boolean()
7343
+ },
7344
+ {},
7345
+ void 0,
7346
+ { schema: "sys" }
7347
+ );
7348
+ var SysIndexColumns = defineTable(
7349
+ "index_columns",
7350
+ {
7351
+ object_id: col.int(),
7352
+ index_id: col.int(),
7353
+ column_id: col.int(),
7354
+ key_ordinal: col.int()
7355
+ },
7356
+ {},
7357
+ void 0,
7358
+ { schema: "sys" }
7359
+ );
7360
+ var SysForeignKeys = defineTable(
7361
+ "foreign_keys",
7362
+ {
7363
+ object_id: col.int(),
7364
+ name: col.varchar(255),
7365
+ delete_referential_action_desc: col.varchar(64),
7366
+ update_referential_action_desc: col.varchar(64)
7367
+ },
7368
+ {},
7369
+ void 0,
7370
+ { schema: "sys" }
7371
+ );
7372
+ var SysForeignKeyColumns = defineTable(
7373
+ "foreign_key_columns",
7374
+ {
7375
+ constraint_object_id: col.int(),
7376
+ parent_object_id: col.int(),
7377
+ parent_column_id: col.int(),
7378
+ referenced_object_id: col.int(),
7379
+ referenced_column_id: col.int(),
7380
+ constraint_column_id: col.int()
7381
+ },
7382
+ {},
7383
+ void 0,
7384
+ { schema: "sys" }
7385
+ );
7386
+
7387
+ // src/core/functions/text.ts
7388
+ var isColumnDef = (val) => !!val && typeof val === "object" && "type" in val && "name" in val;
7389
+ var toOperand2 = (input) => {
7390
+ if (isOperandNode(input)) return input;
7391
+ if (isColumnDef(input)) return columnOperand(input);
7392
+ return valueToOperand(input);
7393
+ };
7394
+ var fn = (key, args) => ({
7395
+ type: "Function",
7396
+ name: key,
7397
+ fn: key,
7398
+ args: args.map(toOperand2)
7399
+ });
7400
+ var lower = (value) => fn("LOWER", [value]);
7401
+ var upper = (value) => fn("UPPER", [value]);
7402
+ var ascii = (value) => fn("ASCII", [value]);
7403
+ var char = (...codes) => {
7404
+ if (codes.length === 0) throw new Error("char() expects at least 1 argument");
7405
+ return fn("CHAR", codes);
7406
+ };
7407
+ var charLength = (value) => fn("CHAR_LENGTH", [value]);
7408
+ var length = (value) => fn("LENGTH", [value]);
7409
+ var trim = (value, chars) => chars === void 0 ? fn("TRIM", [value]) : fn("TRIM", [value, chars]);
7410
+ var ltrim = (value) => fn("LTRIM", [value]);
7411
+ var rtrim = (value) => fn("RTRIM", [value]);
7412
+ var concat = (...args) => {
7413
+ if (args.length < 2) throw new Error("concat() expects at least 2 arguments");
7414
+ return fn("CONCAT", args);
7415
+ };
7416
+ var concatWs = (separator, ...args) => {
7417
+ if (args.length < 1) throw new Error("concatWs() expects at least 2 arguments including the separator");
7418
+ return fn("CONCAT_WS", [separator, ...args]);
7419
+ };
7420
+ var substr = (value, start, length2) => length2 === void 0 ? fn("SUBSTR", [value, start]) : fn("SUBSTR", [value, start, length2]);
7421
+ var left = (value, len) => fn("LEFT", [value, len]);
7422
+ var right = (value, len) => fn("RIGHT", [value, len]);
7423
+ var position = (substring, value) => fn("POSITION", [substring, value]);
7424
+ var instr = (value, substring) => fn("INSTR", [value, substring]);
7425
+ var locate = (substring, value, start) => start === void 0 ? fn("LOCATE", [substring, value]) : fn("LOCATE", [substring, value, start]);
7426
+ var replace = (value, search, replacement) => fn("REPLACE", [value, search, replacement]);
7427
+ var repeat = (value, count2) => fn("REPEAT", [value, count2]);
7428
+ var lpad = (value, len, pad) => fn("LPAD", [value, len, pad]);
7429
+ var rpad = (value, len, pad) => fn("RPAD", [value, len, pad]);
7430
+ var space = (count2) => fn("SPACE", [count2]);
7431
+
7432
+ // src/core/ddl/introspect/functions/mssql.ts
7433
+ var isColumnReference = (value) => typeof value === "object" && value !== null && !("type" in value) && "name" in value && typeof value.name === "string";
7434
+ var toOperandNode2 = (value) => {
7435
+ if (isOperandNode(value)) return value;
7436
+ if (isColumnReference(value)) return columnOperand(value);
7437
+ return valueToOperand(value);
7438
+ };
7439
+ var fn2 = (name, args) => ({
7440
+ type: "Function",
7441
+ name,
7442
+ fn: name,
7443
+ args: args.map((arg) => toOperandNode2(arg))
7444
+ });
7445
+ var CHAR_TYPES = ["varchar", "char", "varbinary", "binary", "nvarchar", "nchar"];
7446
+ var DECIMAL_TYPES = ["decimal", "numeric"];
7447
+ var objectDefinition = (objectId) => fn2("OBJECT_DEFINITION", [objectId]);
7448
+ var buildMssqlDataType = (typeName, maxLength, precision, scale) => {
7449
+ const typeOperand = toOperandNode2(typeName);
7450
+ const maxLenOperand = toOperandNode2(maxLength);
7451
+ const precisionOperand = toOperandNode2(precision);
7452
+ const scaleOperand = toOperandNode2(scale);
7453
+ const typeLower = lower(typeOperand);
7454
+ const lengthCase = caseWhen(
7455
+ [
7456
+ {
7457
+ when: eq(maxLenOperand, -1),
7458
+ then: "max"
7459
+ },
7460
+ {
7461
+ when: inList(typeLower, ["nvarchar", "nchar"]),
7462
+ then: cast(div(maxLenOperand, 2), "varchar(10)")
7463
+ }
7464
+ ],
7465
+ cast(maxLenOperand, "varchar(10)")
7466
+ );
7467
+ const charSuffix = concat("(", lengthCase, ")");
7468
+ const decimalSuffix = concat(
7469
+ "(",
7470
+ cast(precisionOperand, "varchar(10)"),
7471
+ ",",
7472
+ cast(scaleOperand, "varchar(10)"),
7473
+ ")"
7474
+ );
7475
+ const suffix = caseWhen(
7476
+ [
7477
+ { when: inList(typeLower, CHAR_TYPES), then: charSuffix },
7478
+ { when: inList(typeLower, DECIMAL_TYPES), then: decimalSuffix }
7479
+ ],
7480
+ ""
7481
+ );
7482
+ return concat(typeLower, suffix);
7483
+ };
7484
+
6970
7485
  // src/core/ddl/introspect/mssql.ts
7486
+ var normalizeReferentialAction = (value) => {
7487
+ if (!value) return void 0;
7488
+ const normalized = value.replace(/_/g, " ").toUpperCase();
7489
+ const allowed = ["NO ACTION", "RESTRICT", "CASCADE", "SET NULL", "SET DEFAULT"];
7490
+ return allowed.includes(normalized) ? normalized : void 0;
7491
+ };
7492
+ var tableNode2 = (table, alias) => ({
7493
+ type: "Table",
7494
+ name: table.name,
7495
+ schema: table.schema,
7496
+ alias
7497
+ });
7498
+ var columnNode3 = (table, name, alias) => ({
7499
+ type: "Column",
7500
+ table,
7501
+ name,
7502
+ alias
7503
+ });
7504
+ var combineConditions2 = (...expressions) => {
7505
+ const filtered = expressions.filter(Boolean);
7506
+ if (!filtered.length) return void 0;
7507
+ if (filtered.length === 1) return filtered[0];
7508
+ return and(...filtered);
7509
+ };
6971
7510
  var mssqlIntrospector = {
6972
- /**
6973
- * Introspects the MSSQL database schema.
6974
- * @param ctx - The introspection context containing the database executor.
6975
- * @param options - Options for introspection, such as schema filter.
6976
- * @returns A promise that resolves to the introspected database schema.
6977
- */
6978
7511
  async introspect(ctx, options) {
6979
7512
  const schema = options.schema;
6980
- const filterSchema = schema ? "sch.name = @p1" : "1=1";
6981
- const params = schema ? [schema] : [];
6982
- const columnRows = await queryRows(
6983
- ctx.executor,
6984
- `
6985
- SELECT
6986
- sch.name AS table_schema,
6987
- t.name AS table_name,
6988
- c.name AS column_name,
6989
- LOWER(ty.name)
6990
- + CASE
6991
- WHEN LOWER(ty.name) IN ('varchar', 'char', 'varbinary', 'binary', 'nvarchar', 'nchar') THEN
6992
- '('
6993
- + (
6994
- CASE
6995
- WHEN c.max_length = -1 THEN 'max'
6996
- WHEN LOWER(ty.name) IN ('nvarchar', 'nchar') THEN CAST(c.max_length / 2 AS varchar(10))
6997
- ELSE CAST(c.max_length AS varchar(10))
6998
- END
6999
- )
7000
- + ')'
7001
- WHEN LOWER(ty.name) IN ('decimal', 'numeric') THEN
7002
- '(' + CAST(c.precision AS varchar(10)) + ',' + CAST(c.scale AS varchar(10)) + ')'
7003
- ELSE
7004
- ''
7005
- END AS data_type,
7006
- c.is_nullable,
7007
- c.is_identity,
7008
- object_definition(c.default_object_id) AS column_default
7009
- FROM sys.columns c
7010
- JOIN sys.tables t ON t.object_id = c.object_id
7011
- JOIN sys.schemas sch ON sch.schema_id = t.schema_id
7012
- JOIN sys.types ty ON ty.user_type_id = c.user_type_id
7013
- WHERE t.is_ms_shipped = 0 AND ${filterSchema}
7014
- `,
7015
- params
7016
- );
7017
- const pkRows = await queryRows(
7018
- ctx.executor,
7019
- `
7020
- SELECT
7021
- sch.name AS table_schema,
7022
- t.name AS table_name,
7023
- c.name AS column_name,
7024
- ic.key_ordinal
7025
- FROM sys.indexes i
7026
- JOIN sys.index_columns ic ON ic.object_id = i.object_id AND ic.index_id = i.index_id
7027
- JOIN sys.columns c ON c.object_id = ic.object_id AND c.column_id = ic.column_id
7028
- JOIN sys.tables t ON t.object_id = i.object_id
7029
- JOIN sys.schemas sch ON sch.schema_id = t.schema_id
7030
- WHERE i.is_primary_key = 1 AND ${filterSchema}
7031
- ORDER BY ic.key_ordinal
7032
- `,
7033
- params
7513
+ const schemaCondition = schema ? eq(columnNode3("sch", "name"), schema) : void 0;
7514
+ const dataTypeExpression = buildMssqlDataType(
7515
+ { table: "ty", name: "name" },
7516
+ { table: "c", name: "max_length" },
7517
+ { table: "c", name: "precision" },
7518
+ { table: "c", name: "scale" }
7034
7519
  );
7520
+ const defaultExpression = objectDefinition({ table: "c", name: "default_object_id" });
7521
+ const columnsQuery = {
7522
+ type: "SelectQuery",
7523
+ from: tableNode2(SysColumns, "c"),
7524
+ columns: [
7525
+ columnNode3("sch", "name", "table_schema"),
7526
+ columnNode3("t", "name", "table_name"),
7527
+ columnNode3("c", "name", "column_name"),
7528
+ { ...dataTypeExpression, alias: "data_type" },
7529
+ columnNode3("c", "is_nullable"),
7530
+ columnNode3("c", "is_identity"),
7531
+ { ...defaultExpression, alias: "column_default" }
7532
+ ],
7533
+ joins: [
7534
+ {
7535
+ type: "Join",
7536
+ kind: "INNER",
7537
+ table: tableNode2(SysTables, "t"),
7538
+ condition: eq({ table: "t", name: "object_id" }, { table: "c", name: "object_id" })
7539
+ },
7540
+ {
7541
+ type: "Join",
7542
+ kind: "INNER",
7543
+ table: tableNode2(SysSchemas, "sch"),
7544
+ condition: eq({ table: "sch", name: "schema_id" }, { table: "t", name: "schema_id" })
7545
+ },
7546
+ {
7547
+ type: "Join",
7548
+ kind: "INNER",
7549
+ table: tableNode2(SysTypes, "ty"),
7550
+ condition: eq({ table: "ty", name: "user_type_id" }, { table: "c", name: "user_type_id" })
7551
+ }
7552
+ ],
7553
+ where: combineConditions2(
7554
+ eq({ table: "t", name: "is_ms_shipped" }, 0),
7555
+ schemaCondition
7556
+ )
7557
+ };
7558
+ const pkQuery = {
7559
+ type: "SelectQuery",
7560
+ from: tableNode2(SysIndexes, "i"),
7561
+ columns: [
7562
+ columnNode3("sch", "name", "table_schema"),
7563
+ columnNode3("t", "name", "table_name"),
7564
+ columnNode3("c", "name", "column_name"),
7565
+ columnNode3("ic", "key_ordinal", "key_ordinal")
7566
+ ],
7567
+ joins: [
7568
+ {
7569
+ type: "Join",
7570
+ kind: "INNER",
7571
+ table: tableNode2(SysIndexColumns, "ic"),
7572
+ condition: and(
7573
+ eq({ table: "ic", name: "object_id" }, { table: "i", name: "object_id" }),
7574
+ eq({ table: "ic", name: "index_id" }, { table: "i", name: "index_id" })
7575
+ )
7576
+ },
7577
+ {
7578
+ type: "Join",
7579
+ kind: "INNER",
7580
+ table: tableNode2(SysColumns, "c"),
7581
+ condition: and(
7582
+ eq({ table: "c", name: "object_id" }, { table: "ic", name: "object_id" }),
7583
+ eq({ table: "c", name: "column_id" }, { table: "ic", name: "column_id" })
7584
+ )
7585
+ },
7586
+ {
7587
+ type: "Join",
7588
+ kind: "INNER",
7589
+ table: tableNode2(SysTables, "t"),
7590
+ condition: eq({ table: "t", name: "object_id" }, { table: "i", name: "object_id" })
7591
+ },
7592
+ {
7593
+ type: "Join",
7594
+ kind: "INNER",
7595
+ table: tableNode2(SysSchemas, "sch"),
7596
+ condition: eq({ table: "sch", name: "schema_id" }, { table: "t", name: "schema_id" })
7597
+ }
7598
+ ],
7599
+ where: combineConditions2(
7600
+ eq({ table: "i", name: "is_primary_key" }, 1),
7601
+ schemaCondition
7602
+ ),
7603
+ orderBy: [
7604
+ {
7605
+ type: "OrderBy",
7606
+ term: columnNode3("ic", "key_ordinal"),
7607
+ direction: "ASC"
7608
+ }
7609
+ ]
7610
+ };
7611
+ const fkQuery = {
7612
+ type: "SelectQuery",
7613
+ from: tableNode2(SysForeignKeyColumns, "fkc"),
7614
+ columns: [
7615
+ columnNode3("sch", "name", "table_schema"),
7616
+ columnNode3("t", "name", "table_name"),
7617
+ columnNode3("c", "name", "column_name"),
7618
+ columnNode3("fk", "name", "constraint_name"),
7619
+ columnNode3("rsch", "name", "referenced_schema"),
7620
+ columnNode3("rt", "name", "referenced_table"),
7621
+ columnNode3("rc", "name", "referenced_column"),
7622
+ columnNode3("fk", "delete_referential_action_desc", "delete_rule"),
7623
+ columnNode3("fk", "update_referential_action_desc", "update_rule")
7624
+ ],
7625
+ joins: [
7626
+ {
7627
+ type: "Join",
7628
+ kind: "INNER",
7629
+ table: tableNode2(SysForeignKeys, "fk"),
7630
+ condition: eq({ table: "fk", name: "object_id" }, { table: "fkc", name: "constraint_object_id" })
7631
+ },
7632
+ {
7633
+ type: "Join",
7634
+ kind: "INNER",
7635
+ table: tableNode2(SysTables, "t"),
7636
+ condition: eq({ table: "t", name: "object_id" }, { table: "fkc", name: "parent_object_id" })
7637
+ },
7638
+ {
7639
+ type: "Join",
7640
+ kind: "INNER",
7641
+ table: tableNode2(SysSchemas, "sch"),
7642
+ condition: eq({ table: "sch", name: "schema_id" }, { table: "t", name: "schema_id" })
7643
+ },
7644
+ {
7645
+ type: "Join",
7646
+ kind: "INNER",
7647
+ table: tableNode2(SysColumns, "c"),
7648
+ condition: and(
7649
+ eq({ table: "c", name: "object_id" }, { table: "fkc", name: "parent_object_id" }),
7650
+ eq({ table: "c", name: "column_id" }, { table: "fkc", name: "parent_column_id" })
7651
+ )
7652
+ },
7653
+ {
7654
+ type: "Join",
7655
+ kind: "INNER",
7656
+ table: tableNode2(SysTables, "rt"),
7657
+ condition: eq({ table: "rt", name: "object_id" }, { table: "fkc", name: "referenced_object_id" })
7658
+ },
7659
+ {
7660
+ type: "Join",
7661
+ kind: "INNER",
7662
+ table: tableNode2(SysSchemas, "rsch"),
7663
+ condition: eq({ table: "rsch", name: "schema_id" }, { table: "rt", name: "schema_id" })
7664
+ },
7665
+ {
7666
+ type: "Join",
7667
+ kind: "INNER",
7668
+ table: tableNode2(SysColumns, "rc"),
7669
+ condition: and(
7670
+ eq({ table: "rc", name: "object_id" }, { table: "fkc", name: "referenced_object_id" }),
7671
+ eq({ table: "rc", name: "column_id" }, { table: "fkc", name: "referenced_column_id" })
7672
+ )
7673
+ }
7674
+ ],
7675
+ where: combineConditions2(
7676
+ eq({ table: "t", name: "is_ms_shipped" }, 0),
7677
+ schemaCondition
7678
+ ),
7679
+ orderBy: [
7680
+ {
7681
+ type: "OrderBy",
7682
+ term: columnNode3("fk", "name"),
7683
+ direction: "ASC"
7684
+ },
7685
+ {
7686
+ type: "OrderBy",
7687
+ term: columnNode3("fkc", "constraint_column_id"),
7688
+ direction: "ASC"
7689
+ }
7690
+ ]
7691
+ };
7692
+ const indexQuery = {
7693
+ type: "SelectQuery",
7694
+ from: tableNode2(SysIndexes, "i"),
7695
+ columns: [
7696
+ columnNode3("sch", "name", "table_schema"),
7697
+ columnNode3("t", "name", "table_name"),
7698
+ columnNode3("i", "name", "index_name"),
7699
+ columnNode3("i", "is_unique"),
7700
+ columnNode3("i", "has_filter"),
7701
+ columnNode3("i", "filter_definition")
7702
+ ],
7703
+ joins: [
7704
+ {
7705
+ type: "Join",
7706
+ kind: "INNER",
7707
+ table: tableNode2(SysTables, "t"),
7708
+ condition: eq({ table: "t", name: "object_id" }, { table: "i", name: "object_id" })
7709
+ },
7710
+ {
7711
+ type: "Join",
7712
+ kind: "INNER",
7713
+ table: tableNode2(SysSchemas, "sch"),
7714
+ condition: eq({ table: "sch", name: "schema_id" }, { table: "t", name: "schema_id" })
7715
+ }
7716
+ ],
7717
+ where: combineConditions2(
7718
+ eq({ table: "i", name: "is_primary_key" }, 0),
7719
+ eq({ table: "i", name: "is_hypothetical" }, 0),
7720
+ schemaCondition
7721
+ )
7722
+ };
7723
+ const indexColumnsQuery = {
7724
+ type: "SelectQuery",
7725
+ from: tableNode2(SysIndexColumns, "ic"),
7726
+ columns: [
7727
+ columnNode3("sch", "name", "table_schema"),
7728
+ columnNode3("t", "name", "table_name"),
7729
+ columnNode3("i", "name", "index_name"),
7730
+ columnNode3("c", "name", "column_name"),
7731
+ columnNode3("ic", "key_ordinal", "key_ordinal")
7732
+ ],
7733
+ joins: [
7734
+ {
7735
+ type: "Join",
7736
+ kind: "INNER",
7737
+ table: tableNode2(SysIndexes, "i"),
7738
+ condition: and(
7739
+ eq({ table: "ic", name: "object_id" }, { table: "i", name: "object_id" }),
7740
+ eq({ table: "ic", name: "index_id" }, { table: "i", name: "index_id" })
7741
+ )
7742
+ },
7743
+ {
7744
+ type: "Join",
7745
+ kind: "INNER",
7746
+ table: tableNode2(SysColumns, "c"),
7747
+ condition: and(
7748
+ eq({ table: "c", name: "object_id" }, { table: "ic", name: "object_id" }),
7749
+ eq({ table: "c", name: "column_id" }, { table: "ic", name: "column_id" })
7750
+ )
7751
+ },
7752
+ {
7753
+ type: "Join",
7754
+ kind: "INNER",
7755
+ table: tableNode2(SysTables, "t"),
7756
+ condition: eq({ table: "t", name: "object_id" }, { table: "i", name: "object_id" })
7757
+ },
7758
+ {
7759
+ type: "Join",
7760
+ kind: "INNER",
7761
+ table: tableNode2(SysSchemas, "sch"),
7762
+ condition: eq({ table: "sch", name: "schema_id" }, { table: "t", name: "schema_id" })
7763
+ }
7764
+ ],
7765
+ where: combineConditions2(
7766
+ eq({ table: "i", name: "is_primary_key" }, 0),
7767
+ schemaCondition
7768
+ ),
7769
+ orderBy: [
7770
+ {
7771
+ type: "OrderBy",
7772
+ term: columnNode3("ic", "key_ordinal"),
7773
+ direction: "ASC"
7774
+ }
7775
+ ]
7776
+ };
7777
+ const columnRows = await runSelectNode(columnsQuery, ctx);
7778
+ const pkRows = await runSelectNode(pkQuery, ctx);
7779
+ const fkRows = await runSelectNode(fkQuery, ctx);
7780
+ const indexRows = await runSelectNode(indexQuery, ctx);
7781
+ const indexColsRows = await runSelectNode(indexColumnsQuery, ctx);
7035
7782
  const pkMap = /* @__PURE__ */ new Map();
7036
7783
  pkRows.forEach((r) => {
7037
7784
  const key = `${r.table_schema}.${r.table_name}`;
@@ -7039,42 +7786,19 @@ var mssqlIntrospector = {
7039
7786
  list.push(r.column_name);
7040
7787
  pkMap.set(key, list);
7041
7788
  });
7042
- const indexRows = await queryRows(
7043
- ctx.executor,
7044
- `
7045
- SELECT
7046
- sch.name AS table_schema,
7047
- t.name AS table_name,
7048
- i.name AS index_name,
7049
- i.is_unique,
7050
- i.has_filter,
7051
- i.filter_definition
7052
- FROM sys.indexes i
7053
- JOIN sys.tables t ON t.object_id = i.object_id
7054
- JOIN sys.schemas sch ON sch.schema_id = t.schema_id
7055
- WHERE i.is_primary_key = 0 AND i.is_hypothetical = 0 AND ${filterSchema}
7056
- `,
7057
- params
7058
- );
7059
- const indexColsRows = await queryRows(
7060
- ctx.executor,
7061
- `
7062
- SELECT
7063
- sch.name AS table_schema,
7064
- t.name AS table_name,
7065
- i.name AS index_name,
7066
- c.name AS column_name,
7067
- ic.key_ordinal
7068
- FROM sys.index_columns ic
7069
- JOIN sys.indexes i ON i.object_id = ic.object_id AND i.index_id = ic.index_id
7070
- JOIN sys.columns c ON c.object_id = ic.object_id AND c.column_id = ic.column_id
7071
- JOIN sys.tables t ON t.object_id = i.object_id
7072
- JOIN sys.schemas sch ON sch.schema_id = t.schema_id
7073
- WHERE i.is_primary_key = 0 AND ${filterSchema}
7074
- ORDER BY ic.key_ordinal
7075
- `,
7076
- params
7077
- );
7789
+ const fkMap = /* @__PURE__ */ new Map();
7790
+ fkRows.forEach((r) => {
7791
+ const key = `${r.table_schema}.${r.table_name}.${r.column_name}`;
7792
+ const list = fkMap.get(key) || [];
7793
+ list.push({
7794
+ table: `${r.referenced_schema}.${r.referenced_table}`,
7795
+ column: r.referenced_column,
7796
+ onDelete: normalizeReferentialAction(r.delete_rule),
7797
+ onUpdate: normalizeReferentialAction(r.update_rule),
7798
+ name: r.constraint_name
7799
+ });
7800
+ fkMap.set(key, list);
7801
+ });
7078
7802
  const indexColumnsMap = /* @__PURE__ */ new Map();
7079
7803
  indexColsRows.forEach((r) => {
7080
7804
  const key = `${r.table_schema}.${r.table_name}.${r.index_name}`;
@@ -7095,7 +7819,7 @@ var mssqlIntrospector = {
7095
7819
  indexes: []
7096
7820
  });
7097
7821
  }
7098
- const t = tablesByKey.get(key);
7822
+ const table = tablesByKey.get(key);
7099
7823
  const column = {
7100
7824
  name: r.column_name,
7101
7825
  type: r.data_type,
@@ -7103,7 +7827,17 @@ var mssqlIntrospector = {
7103
7827
  default: r.column_default ?? void 0,
7104
7828
  autoIncrement: !!r.is_identity
7105
7829
  };
7106
- t.columns.push(column);
7830
+ const fk = fkMap.get(`${key}.${r.column_name}`)?.[0];
7831
+ if (fk) {
7832
+ column.references = {
7833
+ table: fk.table,
7834
+ column: fk.column,
7835
+ onDelete: fk.onDelete,
7836
+ onUpdate: fk.onUpdate,
7837
+ name: fk.name
7838
+ };
7839
+ }
7840
+ table.columns.push(column);
7107
7841
  });
7108
7842
  indexRows.forEach((r) => {
7109
7843
  const key = `${r.table_schema}.${r.table_name}`;
@@ -7114,7 +7848,7 @@ var mssqlIntrospector = {
7114
7848
  name: r.index_name,
7115
7849
  columns: cols,
7116
7850
  unique: !!r.is_unique,
7117
- where: r.has_filter ? r.filter_definition : void 0
7851
+ where: r.has_filter ? r.filter_definition ?? void 0 : void 0
7118
7852
  };
7119
7853
  table.indexes = table.indexes || [];
7120
7854
  table.indexes.push(idx);
@@ -7150,51 +7884,6 @@ var introspectSchema = async (executor, dialect, options = {}) => {
7150
7884
  return handler.introspect(ctx, options);
7151
7885
  };
7152
7886
 
7153
- // src/core/functions/text.ts
7154
- var isColumnDef = (val) => !!val && typeof val === "object" && "type" in val && "name" in val;
7155
- var toOperand2 = (input) => {
7156
- if (isOperandNode(input)) return input;
7157
- if (isColumnDef(input)) return columnOperand(input);
7158
- return valueToOperand(input);
7159
- };
7160
- var fn = (key, args) => ({
7161
- type: "Function",
7162
- name: key,
7163
- fn: key,
7164
- args: args.map(toOperand2)
7165
- });
7166
- var lower = (value) => fn("LOWER", [value]);
7167
- var upper = (value) => fn("UPPER", [value]);
7168
- var ascii = (value) => fn("ASCII", [value]);
7169
- var char = (...codes) => {
7170
- if (codes.length === 0) throw new Error("char() expects at least 1 argument");
7171
- return fn("CHAR", codes);
7172
- };
7173
- var charLength = (value) => fn("CHAR_LENGTH", [value]);
7174
- var length = (value) => fn("LENGTH", [value]);
7175
- var trim = (value, chars) => chars === void 0 ? fn("TRIM", [value]) : fn("TRIM", [value, chars]);
7176
- var ltrim = (value) => fn("LTRIM", [value]);
7177
- var rtrim = (value) => fn("RTRIM", [value]);
7178
- var concat = (...args) => {
7179
- if (args.length < 2) throw new Error("concat() expects at least 2 arguments");
7180
- return fn("CONCAT", args);
7181
- };
7182
- var concatWs = (separator, ...args) => {
7183
- if (args.length < 1) throw new Error("concatWs() expects at least 2 arguments including the separator");
7184
- return fn("CONCAT_WS", [separator, ...args]);
7185
- };
7186
- var substr = (value, start, length2) => length2 === void 0 ? fn("SUBSTR", [value, start]) : fn("SUBSTR", [value, start, length2]);
7187
- var left = (value, len) => fn("LEFT", [value, len]);
7188
- var right = (value, len) => fn("RIGHT", [value, len]);
7189
- var position = (substring, value) => fn("POSITION", [substring, value]);
7190
- var instr = (value, substring) => fn("INSTR", [value, substring]);
7191
- var locate = (substring, value, start) => start === void 0 ? fn("LOCATE", [substring, value]) : fn("LOCATE", [substring, value, start]);
7192
- var replace = (value, search, replacement) => fn("REPLACE", [value, search, replacement]);
7193
- var repeat = (value, count2) => fn("REPEAT", [value, count2]);
7194
- var lpad = (value, len, pad) => fn("LPAD", [value, len, pad]);
7195
- var rpad = (value, len, pad) => fn("RPAD", [value, len, pad]);
7196
- var space = (count2) => fn("SPACE", [count2]);
7197
-
7198
7887
  // src/core/functions/numeric.ts
7199
7888
  var isColumnDef2 = (val) => !!val && typeof val === "object" && "type" in val && "name" in val;
7200
7889
  var toOperand3 = (input) => {
@@ -7202,42 +7891,42 @@ var toOperand3 = (input) => {
7202
7891
  if (isColumnDef2(input)) return columnOperand(input);
7203
7892
  return valueToOperand(input);
7204
7893
  };
7205
- var fn2 = (key, args) => ({
7894
+ var fn3 = (key, args) => ({
7206
7895
  type: "Function",
7207
7896
  name: key,
7208
7897
  fn: key,
7209
7898
  args: args.map(toOperand3)
7210
7899
  });
7211
- var abs = (value) => fn2("ABS", [value]);
7212
- var acos = (value) => fn2("ACOS", [value]);
7213
- var asin = (value) => fn2("ASIN", [value]);
7214
- var atan = (value) => fn2("ATAN", [value]);
7215
- var atan2 = (y, x) => fn2("ATAN2", [y, x]);
7216
- var ceil = (value) => fn2("CEIL", [value]);
7217
- var ceiling = (value) => fn2("CEILING", [value]);
7218
- var cos = (value) => fn2("COS", [value]);
7219
- var cot = (value) => fn2("COT", [value]);
7220
- var degrees = (value) => fn2("DEGREES", [value]);
7221
- var exp = (value) => fn2("EXP", [value]);
7222
- var floor = (value) => fn2("FLOOR", [value]);
7223
- var ln = (value) => fn2("LN", [value]);
7224
- var log = (value) => fn2("LOG", [value]);
7225
- var log10 = (value) => fn2("LOG10", [value]);
7226
- var logBase = (base, value) => fn2("LOG_BASE", [base, value]);
7227
- var mod = (x, y) => fn2("MOD", [x, y]);
7228
- var pi = () => fn2("PI", []);
7229
- var power = (x, y) => fn2("POWER", [x, y]);
7230
- var pow = (x, y) => fn2("POW", [x, y]);
7231
- var radians = (value) => fn2("RADIANS", [value]);
7232
- var random = () => fn2("RANDOM", []);
7233
- var rand = () => fn2("RAND", []);
7234
- var round = (value, decimals) => decimals === void 0 ? fn2("ROUND", [value]) : fn2("ROUND", [value, decimals]);
7235
- var sign = (value) => fn2("SIGN", [value]);
7236
- var sin = (value) => fn2("SIN", [value]);
7237
- var sqrt = (value) => fn2("SQRT", [value]);
7238
- var tan = (value) => fn2("TAN", [value]);
7239
- var trunc = (value, decimals) => decimals === void 0 ? fn2("TRUNC", [value]) : fn2("TRUNC", [value, decimals]);
7240
- var truncate = (value, decimals) => fn2("TRUNCATE", [value, decimals]);
7900
+ var abs = (value) => fn3("ABS", [value]);
7901
+ var acos = (value) => fn3("ACOS", [value]);
7902
+ var asin = (value) => fn3("ASIN", [value]);
7903
+ var atan = (value) => fn3("ATAN", [value]);
7904
+ var atan2 = (y, x) => fn3("ATAN2", [y, x]);
7905
+ var ceil = (value) => fn3("CEIL", [value]);
7906
+ var ceiling = (value) => fn3("CEILING", [value]);
7907
+ var cos = (value) => fn3("COS", [value]);
7908
+ var cot = (value) => fn3("COT", [value]);
7909
+ var degrees = (value) => fn3("DEGREES", [value]);
7910
+ var exp = (value) => fn3("EXP", [value]);
7911
+ var floor = (value) => fn3("FLOOR", [value]);
7912
+ var ln = (value) => fn3("LN", [value]);
7913
+ var log = (value) => fn3("LOG", [value]);
7914
+ var log10 = (value) => fn3("LOG10", [value]);
7915
+ var logBase = (base, value) => fn3("LOG_BASE", [base, value]);
7916
+ var mod = (x, y) => fn3("MOD", [x, y]);
7917
+ var pi = () => fn3("PI", []);
7918
+ var power = (x, y) => fn3("POWER", [x, y]);
7919
+ var pow = (x, y) => fn3("POW", [x, y]);
7920
+ var radians = (value) => fn3("RADIANS", [value]);
7921
+ var random = () => fn3("RANDOM", []);
7922
+ var rand = () => fn3("RAND", []);
7923
+ var round = (value, decimals) => decimals === void 0 ? fn3("ROUND", [value]) : fn3("ROUND", [value, decimals]);
7924
+ var sign = (value) => fn3("SIGN", [value]);
7925
+ var sin = (value) => fn3("SIN", [value]);
7926
+ var sqrt = (value) => fn3("SQRT", [value]);
7927
+ var tan = (value) => fn3("TAN", [value]);
7928
+ var trunc = (value, decimals) => decimals === void 0 ? fn3("TRUNC", [value]) : fn3("TRUNC", [value, decimals]);
7929
+ var truncate = (value, decimals) => fn3("TRUNCATE", [value, decimals]);
7241
7930
 
7242
7931
  // src/core/functions/datetime.ts
7243
7932
  var isColumnDef3 = (val) => !!val && typeof val === "object" && "type" in val && "name" in val;
@@ -7246,29 +7935,29 @@ var toOperand4 = (input) => {
7246
7935
  if (isColumnDef3(input)) return columnOperand(input);
7247
7936
  return valueToOperand(input);
7248
7937
  };
7249
- var fn3 = (key, args) => ({
7938
+ var fn4 = (key, args) => ({
7250
7939
  type: "Function",
7251
7940
  name: key,
7252
7941
  args: args.map(toOperand4)
7253
7942
  });
7254
- var now = () => fn3("NOW", []);
7255
- var currentDate = () => fn3("CURRENT_DATE", []);
7256
- var currentTime = () => fn3("CURRENT_TIME", []);
7257
- var utcNow = () => fn3("UTC_NOW", []);
7258
- var extract = (part, date) => fn3("EXTRACT", [part, date]);
7259
- var year = (date) => fn3("YEAR", [date]);
7260
- var month = (date) => fn3("MONTH", [date]);
7261
- var day = (date) => fn3("DAY", [date]);
7262
- var dateAdd = (date, interval, unit) => fn3("DATE_ADD", [date, interval, unit]);
7263
- var dateSub = (date, interval, unit) => fn3("DATE_SUB", [date, interval, unit]);
7264
- var dateDiff = (date1, date2) => fn3("DATE_DIFF", [date1, date2]);
7265
- var dateFormat = (date, format) => fn3("DATE_FORMAT", [date, format]);
7266
- var unixTimestamp = () => fn3("UNIX_TIMESTAMP", []);
7267
- var fromUnixTime = (timestamp) => fn3("FROM_UNIXTIME", [timestamp]);
7268
- var endOfMonth = (date) => fn3("END_OF_MONTH", [date]);
7269
- var dayOfWeek = (date) => fn3("DAY_OF_WEEK", [date]);
7270
- var weekOfYear = (date) => fn3("WEEK_OF_YEAR", [date]);
7271
- var dateTrunc = (part, date) => fn3("DATE_TRUNC", [part, date]);
7943
+ var now = () => fn4("NOW", []);
7944
+ var currentDate = () => fn4("CURRENT_DATE", []);
7945
+ var currentTime = () => fn4("CURRENT_TIME", []);
7946
+ var utcNow = () => fn4("UTC_NOW", []);
7947
+ var extract = (part, date) => fn4("EXTRACT", [part, date]);
7948
+ var year = (date) => fn4("YEAR", [date]);
7949
+ var month = (date) => fn4("MONTH", [date]);
7950
+ var day = (date) => fn4("DAY", [date]);
7951
+ var dateAdd = (date, interval, unit) => fn4("DATE_ADD", [date, interval, unit]);
7952
+ var dateSub = (date, interval, unit) => fn4("DATE_SUB", [date, interval, unit]);
7953
+ var dateDiff = (date1, date2) => fn4("DATE_DIFF", [date1, date2]);
7954
+ var dateFormat = (date, format) => fn4("DATE_FORMAT", [date, format]);
7955
+ var unixTimestamp = () => fn4("UNIX_TIMESTAMP", []);
7956
+ var fromUnixTime = (timestamp) => fn4("FROM_UNIXTIME", [timestamp]);
7957
+ var endOfMonth = (date) => fn4("END_OF_MONTH", [date]);
7958
+ var dayOfWeek = (date) => fn4("DAY_OF_WEEK", [date]);
7959
+ var weekOfYear = (date) => fn4("WEEK_OF_YEAR", [date]);
7960
+ var dateTrunc = (part, date) => fn4("DATE_TRUNC", [part, date]);
7272
7961
 
7273
7962
  // src/orm/als.ts
7274
7963
  var AsyncLocalStorage = class {
@@ -7503,6 +8192,7 @@ var TypeScriptGenerator = class {
7503
8192
  case "ScalarSubquery":
7504
8193
  case "CaseExpression":
7505
8194
  case "WindowFunction":
8195
+ case "Cast":
7506
8196
  return this.printOperand(term);
7507
8197
  default:
7508
8198
  return this.printExpression(term);
@@ -7562,6 +8252,9 @@ var TypeScriptGenerator = class {
7562
8252
  visitWindowFunction(node) {
7563
8253
  return this.printWindowFunctionOperand(node);
7564
8254
  }
8255
+ visitCast(node) {
8256
+ return this.printCastOperand(node);
8257
+ }
7565
8258
  visitAliasRef(node) {
7566
8259
  return `aliasRef('${node.name}')`;
7567
8260
  }
@@ -7573,12 +8266,12 @@ var TypeScriptGenerator = class {
7573
8266
  printBinaryExpression(binary) {
7574
8267
  const left2 = this.printOperand(binary.left);
7575
8268
  const right2 = this.printOperand(binary.right);
7576
- const fn4 = this.mapOp(binary.operator);
8269
+ const fn5 = this.mapOp(binary.operator);
7577
8270
  const args = [left2, right2];
7578
8271
  if (binary.escape) {
7579
8272
  args.push(this.printOperand(binary.escape));
7580
8273
  }
7581
- return `${fn4}(${args.join(", ")})`;
8274
+ return `${fn5}(${args.join(", ")})`;
7582
8275
  }
7583
8276
  /**
7584
8277
  * Prints a logical expression to TypeScript code
@@ -7607,13 +8300,13 @@ var TypeScriptGenerator = class {
7607
8300
  */
7608
8301
  printInExpression(inExpr) {
7609
8302
  const left2 = this.printOperand(inExpr.left);
7610
- const fn4 = this.mapOp(inExpr.operator);
8303
+ const fn5 = this.mapOp(inExpr.operator);
7611
8304
  if (Array.isArray(inExpr.right)) {
7612
8305
  const values = inExpr.right.map((v) => this.printOperand(v)).join(", ");
7613
- return `${fn4}(${left2}, [${values}])`;
8306
+ return `${fn5}(${left2}, [${values}])`;
7614
8307
  }
7615
8308
  const subquery = this.inlineChain(this.buildSelectLines(inExpr.right.query));
7616
- return `${fn4}(${left2}, (${subquery}))`;
8309
+ return `${fn5}(${left2}, (${subquery}))`;
7617
8310
  }
7618
8311
  /**
7619
8312
  * Prints a null expression to TypeScript code
@@ -7622,8 +8315,8 @@ var TypeScriptGenerator = class {
7622
8315
  */
7623
8316
  printNullExpression(nullExpr) {
7624
8317
  const left2 = this.printOperand(nullExpr.left);
7625
- const fn4 = this.mapOp(nullExpr.operator);
7626
- return `${fn4}(${left2})`;
8318
+ const fn5 = this.mapOp(nullExpr.operator);
8319
+ return `${fn5}(${left2})`;
7627
8320
  }
7628
8321
  /**
7629
8322
  * Prints a BETWEEN expression to TypeScript code
@@ -7667,9 +8360,9 @@ var TypeScriptGenerator = class {
7667
8360
  * @param fn - Function node
7668
8361
  * @returns TypeScript code representation
7669
8362
  */
7670
- printFunctionOperand(fn4) {
7671
- const args = fn4.args.map((a) => this.printOperand(a)).join(", ");
7672
- return `${fn4.name.toLowerCase()}(${args})`;
8363
+ printFunctionOperand(fn5) {
8364
+ const args = fn5.args.map((a) => this.printOperand(a)).join(", ");
8365
+ return `${fn5.name.toLowerCase()}(${args})`;
7673
8366
  }
7674
8367
  /**
7675
8368
  * Prints a JSON path operand to TypeScript code
@@ -7729,6 +8422,10 @@ var TypeScriptGenerator = class {
7729
8422
  result += ")";
7730
8423
  return result;
7731
8424
  }
8425
+ printCastOperand(node) {
8426
+ const typeLiteral = node.castType.replace(/'/g, "\\'");
8427
+ return `cast(${this.printOperand(node.expression)}, '${typeLiteral}')`;
8428
+ }
7732
8429
  /**
7733
8430
  * Converts method chain lines to inline format
7734
8431
  * @param lines - Method chain lines
@@ -8893,15 +9590,15 @@ var OrmSession = class {
8893
9590
  * @returns The result of the function
8894
9591
  * @throws If the transaction fails
8895
9592
  */
8896
- async transaction(fn4) {
9593
+ async transaction(fn5) {
8897
9594
  if (!this.executor.capabilities.transactions) {
8898
- const result = await fn4(this);
9595
+ const result = await fn5(this);
8899
9596
  await this.commit();
8900
9597
  return result;
8901
9598
  }
8902
9599
  await this.executor.beginTransaction();
8903
9600
  try {
8904
- const result = await fn4(this);
9601
+ const result = await fn5(this);
8905
9602
  await this.flushWithHooks();
8906
9603
  await this.executor.commitTransaction();
8907
9604
  await this.domainEvents.dispatch(this.unitOfWork.getTracked(), this);
@@ -9004,11 +9701,11 @@ var Orm = class {
9004
9701
  * @returns The result of the function
9005
9702
  * @throws If the transaction fails
9006
9703
  */
9007
- async transaction(fn4) {
9704
+ async transaction(fn5) {
9008
9705
  const executor = this.executorFactory.createTransactionalExecutor();
9009
9706
  const session = new OrmSession({ orm: this, executor });
9010
9707
  try {
9011
- return await session.transaction(() => fn4(session));
9708
+ return await session.transaction(() => fn5(session));
9012
9709
  } finally {
9013
9710
  await session.dispose();
9014
9711
  }
@@ -9827,6 +10524,7 @@ export {
9827
10524
  between,
9828
10525
  bootstrapEntities,
9829
10526
  caseWhen,
10527
+ cast,
9830
10528
  ceil,
9831
10529
  ceiling,
9832
10530
  char,
@@ -9894,6 +10592,7 @@ export {
9894
10592
  instr,
9895
10593
  introspectSchema,
9896
10594
  isCaseExpressionNode,
10595
+ isCastExpressionNode,
9897
10596
  isExpressionSelectionNode,
9898
10597
  isFunctionNode,
9899
10598
  isNotNull,