metal-orm 1.0.45 → 1.0.47

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/dist/index.cjs +1092 -323
  2. package/dist/index.cjs.map +1 -1
  3. package/dist/index.d.cts +99 -9
  4. package/dist/index.d.ts +99 -9
  5. package/dist/index.js +1087 -323
  6. package/dist/index.js.map +1 -1
  7. package/package.json +1 -1
  8. package/scripts/generate-entities.mjs +36 -9
  9. package/src/codegen/typescript.ts +22 -10
  10. package/src/core/ast/adapters.ts +2 -1
  11. package/src/core/ast/expression-builders.ts +13 -0
  12. package/src/core/ast/expression-nodes.ts +25 -5
  13. package/src/core/ast/expression-visitor.ts +5 -0
  14. package/src/core/ast/query.ts +9 -1
  15. package/src/core/ddl/dialects/base-schema-dialect.ts +2 -1
  16. package/src/core/ddl/dialects/mssql-schema-dialect.ts +10 -23
  17. package/src/core/ddl/dialects/mysql-schema-dialect.ts +10 -24
  18. package/src/core/ddl/dialects/postgres-schema-dialect.ts +10 -23
  19. package/src/core/ddl/dialects/render-reference.test.ts +2 -1
  20. package/src/core/ddl/dialects/sqlite-schema-dialect.ts +9 -23
  21. package/src/core/ddl/introspect/catalogs/index.ts +4 -1
  22. package/src/core/ddl/introspect/catalogs/mssql.ts +126 -0
  23. package/src/core/ddl/introspect/catalogs/mysql.ts +89 -0
  24. package/src/core/ddl/introspect/catalogs/postgres.ts +2 -1
  25. package/src/core/ddl/introspect/catalogs/sqlite.ts +47 -0
  26. package/src/core/ddl/introspect/functions/mssql.ts +84 -0
  27. package/src/core/ddl/introspect/mssql.ts +471 -194
  28. package/src/core/ddl/introspect/mysql.ts +336 -125
  29. package/src/core/ddl/introspect/postgres.ts +45 -5
  30. package/src/core/ddl/introspect/run-select.ts +3 -8
  31. package/src/core/ddl/introspect/sqlite.ts +113 -59
  32. package/src/core/ddl/schema-dialect.ts +2 -1
  33. package/src/core/ddl/schema-diff.ts +2 -1
  34. package/src/core/ddl/schema-generator.ts +2 -1
  35. package/src/core/ddl/schema-types.ts +3 -1
  36. package/src/core/ddl/sql-writing.ts +2 -1
  37. package/src/core/dialect/abstract.ts +12 -1
  38. package/src/core/dialect/mssql/index.ts +4 -10
  39. package/src/core/functions/datetime.ts +2 -1
  40. package/src/core/functions/numeric.ts +2 -1
  41. package/src/core/functions/text.ts +2 -1
  42. package/src/decorators/{column.ts → column-decorator.ts} +4 -1
  43. package/src/decorators/index.ts +1 -1
  44. package/src/index.ts +2 -1
  45. package/src/orm/entity-metadata.ts +2 -1
  46. package/src/orm/lazy-batch.ts +2 -1
  47. package/src/orm/orm-session.ts +2 -1
  48. package/src/query-builder/column-selector.ts +2 -1
  49. package/src/query-builder/delete.ts +2 -1
  50. package/src/query-builder/insert.ts +2 -1
  51. package/src/query-builder/query-ast-service.ts +4 -3
  52. package/src/query-builder/relation-projection-helper.ts +2 -1
  53. package/src/query-builder/relation-service.ts +2 -1
  54. package/src/query-builder/select/predicate-facet.ts +2 -1
  55. package/src/query-builder/select/projection-facet.ts +2 -1
  56. package/src/query-builder/select-helpers.ts +2 -1
  57. package/src/query-builder/select-query-state.ts +2 -0
  58. package/src/query-builder/select.ts +2 -1
  59. package/src/query-builder/update.ts +2 -1
  60. package/src/schema/{column.ts → column-types.ts} +317 -290
  61. package/src/schema/table-guards.ts +1 -1
  62. package/src/schema/table.ts +1 -1
  63. package/src/schema/types.ts +10 -8
package/dist/index.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)
@@ -111,7 +111,38 @@ function getColumn(table, key) {
111
111
  return col2;
112
112
  }
113
113
 
114
- // src/schema/column.ts
114
+ // src/schema/column-types.ts
115
+ var STANDARD_COLUMN_TYPES = [
116
+ "INT",
117
+ "INTEGER",
118
+ "BIGINT",
119
+ "VARCHAR",
120
+ "TEXT",
121
+ "JSON",
122
+ "ENUM",
123
+ "DECIMAL",
124
+ "FLOAT",
125
+ "DOUBLE",
126
+ "UUID",
127
+ "BINARY",
128
+ "VARBINARY",
129
+ "BLOB",
130
+ "DATE",
131
+ "DATETIME",
132
+ "TIMESTAMP",
133
+ "TIMESTAMPTZ",
134
+ "BOOLEAN"
135
+ ];
136
+ var STANDARD_TYPE_SET = new Set(STANDARD_COLUMN_TYPES.map((t) => t.toLowerCase()));
137
+ var normalizeColumnType = (type) => {
138
+ if (typeof type !== "string") return type;
139
+ const lower2 = type.toLowerCase();
140
+ return STANDARD_TYPE_SET.has(lower2) ? lower2 : type;
141
+ };
142
+ var renderTypeWithArgs = (sqlType, args) => {
143
+ if (!args || args.length === 0) return sqlType;
144
+ return `${sqlType}(${args.join(", ")})`;
145
+ };
115
146
  var col = {
116
147
  /**
117
148
  * Creates an integer column definition
@@ -171,7 +202,10 @@ var col = {
171
202
  /**
172
203
  * Creates a Postgres bytea column definition
173
204
  */
174
- bytea: () => ({ name: "", type: "BYTEA" }),
205
+ bytea: () => ({
206
+ name: "",
207
+ type: "BYTEA"
208
+ }),
175
209
  /**
176
210
  * Creates a timestamp column definition
177
211
  */
@@ -203,6 +237,17 @@ var col = {
203
237
  * @param values - Enum values
204
238
  */
205
239
  enum: (values) => ({ name: "", type: "ENUM", args: values }),
240
+ /**
241
+ * Creates a column definition with a custom SQL type.
242
+ * Useful for dialect-specific types without polluting the standard set.
243
+ */
244
+ custom: (type, opts = {}) => ({
245
+ name: "",
246
+ type,
247
+ args: opts.args,
248
+ tsType: opts.tsType,
249
+ dialectTypes: opts.dialect ? { [opts.dialect]: type } : void 0
250
+ }),
206
251
  /**
207
252
  * Marks a column definition as a primary key
208
253
  * @param def - Column definition to modify
@@ -312,7 +357,9 @@ var operandTypes = /* @__PURE__ */ new Set([
312
357
  "JsonPath",
313
358
  "ScalarSubquery",
314
359
  "CaseExpression",
315
- "WindowFunction"
360
+ "Cast",
361
+ "WindowFunction",
362
+ "ArithmeticExpression"
316
363
  ]);
317
364
  var hasTypeProperty = (value) => typeof value === "object" && value !== null && "type" in value;
318
365
  var isOperandNode = (node) => {
@@ -321,8 +368,9 @@ var isOperandNode = (node) => {
321
368
  };
322
369
  var isFunctionNode = (node) => isOperandNode(node) && node.type === "Function";
323
370
  var isCaseExpressionNode = (node) => isOperandNode(node) && node.type === "CaseExpression";
371
+ var isCastExpressionNode = (node) => isOperandNode(node) && node.type === "Cast";
324
372
  var isWindowFunctionNode = (node) => isOperandNode(node) && node.type === "WindowFunction";
325
- var isExpressionSelectionNode = (node) => isFunctionNode(node) || isCaseExpressionNode(node) || isWindowFunctionNode(node);
373
+ var isExpressionSelectionNode = (node) => isFunctionNode(node) || isCaseExpressionNode(node) || isCastExpressionNode(node) || isWindowFunctionNode(node);
326
374
 
327
375
  // src/core/ast/expression-builders.ts
328
376
  var isLiteralValue = (value) => value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean";
@@ -458,6 +506,11 @@ var caseWhen = (conditions, elseValue) => ({
458
506
  })),
459
507
  else: elseValue !== void 0 ? toOperand(elseValue) : void 0
460
508
  });
509
+ var cast = (expression, castType) => ({
510
+ type: "Cast",
511
+ expression: toOperand(expression),
512
+ castType
513
+ });
461
514
  var exists = (subquery) => ({
462
515
  type: "ExistsExpression",
463
516
  operator: "EXISTS",
@@ -715,6 +768,9 @@ var visitOperand = (node, visitor) => {
715
768
  case "AliasRef":
716
769
  if (visitor.visitAliasRef) return visitor.visitAliasRef(node);
717
770
  break;
771
+ case "Cast":
772
+ if (visitor.visitCast) return visitor.visitCast(node);
773
+ break;
718
774
  default:
719
775
  break;
720
776
  }
@@ -1241,6 +1297,10 @@ var Dialect = class _Dialect {
1241
1297
  parts.push("END");
1242
1298
  return parts.join(" ");
1243
1299
  });
1300
+ this.registerOperandCompiler("Cast", (node, ctx) => {
1301
+ const value = this.compileOperand(node.expression, ctx);
1302
+ return `CAST(${value} AS ${node.castType})`;
1303
+ });
1244
1304
  this.registerOperandCompiler("WindowFunction", (node, ctx) => {
1245
1305
  let result = `${node.name}(`;
1246
1306
  if (node.args.length > 0) {
@@ -1267,6 +1327,11 @@ var Dialect = class _Dialect {
1267
1327
  result += ")";
1268
1328
  return result;
1269
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
+ });
1270
1335
  }
1271
1336
  // Default fallback, should be overridden by dialects if supported
1272
1337
  compileJsonPath(_node) {
@@ -1299,13 +1364,13 @@ var FunctionTableFormatter = class {
1299
1364
  * @param dialect - The dialect instance for compiling operands.
1300
1365
  * @returns SQL function table expression (e.g., "LATERAL schema.func(args) WITH ORDINALITY AS alias(col1, col2)").
1301
1366
  */
1302
- static format(fn4, ctx, dialect) {
1303
- const schemaPart = this.formatSchema(fn4, dialect);
1304
- const args = this.formatArgs(fn4, ctx, dialect);
1305
- const base = this.formatBase(fn4, schemaPart, args, dialect);
1306
- const lateral = this.formatLateral(fn4);
1307
- const alias = this.formatAlias(fn4, dialect);
1308
- 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);
1309
1374
  return `${lateral}${base}${alias}${colAliases}`;
1310
1375
  }
1311
1376
  /**
@@ -1315,9 +1380,9 @@ var FunctionTableFormatter = class {
1315
1380
  * @returns Schema prefix (e.g., "schema.") or empty string.
1316
1381
  * @internal
1317
1382
  */
1318
- static formatSchema(fn4, dialect) {
1319
- if (!fn4.schema) return "";
1320
- 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;
1321
1386
  return `${quoted}.`;
1322
1387
  }
1323
1388
  /**
@@ -1328,8 +1393,8 @@ var FunctionTableFormatter = class {
1328
1393
  * @returns Comma-separated function arguments.
1329
1394
  * @internal
1330
1395
  */
1331
- static formatArgs(fn4, ctx, dialect) {
1332
- return (fn4.args || []).map((a) => {
1396
+ static formatArgs(fn5, ctx, dialect) {
1397
+ return (fn5.args || []).map((a) => {
1333
1398
  if (ctx && dialect) {
1334
1399
  return dialect.compileOperand(a, ctx);
1335
1400
  }
@@ -1345,9 +1410,9 @@ var FunctionTableFormatter = class {
1345
1410
  * @returns Base function call expression (e.g., "schema.func(args) WITH ORDINALITY").
1346
1411
  * @internal
1347
1412
  */
1348
- static formatBase(fn4, schemaPart, args, dialect) {
1349
- const ordinality = fn4.withOrdinality ? " WITH ORDINALITY" : "";
1350
- 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;
1351
1416
  return `${schemaPart}${quoted}(${args})${ordinality}`;
1352
1417
  }
1353
1418
  /**
@@ -1356,8 +1421,8 @@ var FunctionTableFormatter = class {
1356
1421
  * @returns "LATERAL " or empty string.
1357
1422
  * @internal
1358
1423
  */
1359
- static formatLateral(fn4) {
1360
- return fn4.lateral ? "LATERAL " : "";
1424
+ static formatLateral(fn5) {
1425
+ return fn5.lateral ? "LATERAL " : "";
1361
1426
  }
1362
1427
  /**
1363
1428
  * Formats the table alias for the function table.
@@ -1366,9 +1431,9 @@ var FunctionTableFormatter = class {
1366
1431
  * @returns " AS alias" or empty string.
1367
1432
  * @internal
1368
1433
  */
1369
- static formatAlias(fn4, dialect) {
1370
- if (!fn4.alias) return "";
1371
- 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;
1372
1437
  return ` AS ${quoted}`;
1373
1438
  }
1374
1439
  /**
@@ -1378,9 +1443,9 @@ var FunctionTableFormatter = class {
1378
1443
  * @returns "(col1, col2, ...)" or empty string.
1379
1444
  * @internal
1380
1445
  */
1381
- static formatColumnAliases(fn4, dialect) {
1382
- if (!fn4.columnAliases || !fn4.columnAliases.length) return "";
1383
- 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(", ");
1384
1449
  return `(${aliases})`;
1385
1450
  }
1386
1451
  };
@@ -1648,8 +1713,8 @@ var SqlDialectBase = class extends Dialect {
1648
1713
  }
1649
1714
  return this.compileTableSource(tableSource);
1650
1715
  }
1651
- compileFunctionTable(fn4, ctx) {
1652
- return FunctionTableFormatter.format(fn4, ctx, this);
1716
+ compileFunctionTable(fn5, ctx) {
1717
+ return FunctionTableFormatter.format(fn5, ctx, this);
1653
1718
  }
1654
1719
  compileDerivedTable(table, ctx) {
1655
1720
  if (!table.alias) {
@@ -2273,16 +2338,7 @@ var SqlServerDialect = class extends SqlDialectBase {
2273
2338
  }
2274
2339
  compileSelectCoreForMssql(ast, ctx) {
2275
2340
  const columns = ast.columns.map((c) => {
2276
- let expr = "";
2277
- if (c.type === "Function") {
2278
- expr = this.compileOperand(c, ctx);
2279
- } else if (c.type === "Column") {
2280
- expr = `${this.quoteIdentifier(c.table)}.${this.quoteIdentifier(c.name)}`;
2281
- } else if (c.type === "ScalarSubquery") {
2282
- expr = this.compileOperand(c, ctx);
2283
- } else if (c.type === "WindowFunction") {
2284
- expr = this.compileOperand(c, ctx);
2285
- }
2341
+ const expr = c.type === "Column" ? `${this.quoteIdentifier(c.table)}.${this.quoteIdentifier(c.name)}` : this.compileOperand(c, ctx);
2286
2342
  if (c.alias) {
2287
2343
  if (c.alias.includes("(")) return c.alias;
2288
2344
  return `${expr} AS ${this.quoteIdentifier(c.alias)}`;
@@ -6556,15 +6612,11 @@ var PgReferentialConstraints = defineTable(
6556
6612
  async function runSelect(qb, ctx) {
6557
6613
  const ast = qb.getAST();
6558
6614
  const compiled = ctx.dialect.compileSelect(ast);
6559
- const results = await ctx.executor.executeSql(compiled.sql, compiled.params);
6560
- const [first] = results;
6561
- return toRows(first);
6615
+ return await queryRows(ctx.executor, compiled.sql, compiled.params);
6562
6616
  }
6563
6617
  async function runSelectNode(ast, ctx) {
6564
6618
  const compiled = ctx.dialect.compileSelect(ast);
6565
- const results = await ctx.executor.executeSql(compiled.sql, compiled.params);
6566
- const [first] = results;
6567
- return toRows(first);
6619
+ return await queryRows(ctx.executor, compiled.sql, compiled.params);
6568
6620
  }
6569
6621
 
6570
6622
  // src/core/ddl/introspect/postgres.ts
@@ -6589,6 +6641,32 @@ var postgresIntrospector = {
6589
6641
  ordinal_position: PgInformationSchemaColumns.columns.ordinal_position
6590
6642
  }).where(eq(PgInformationSchemaColumns.columns.table_schema, schema)).orderBy(PgInformationSchemaColumns.columns.table_name).orderBy(PgInformationSchemaColumns.columns.ordinal_position);
6591
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
+ });
6592
6670
  const qbPk = new SelectQueryBuilder(PgKeyColumnUsage).select({
6593
6671
  table_schema: PgKeyColumnUsage.columns.table_schema,
6594
6672
  table_name: PgKeyColumnUsage.columns.table_name,
@@ -6616,7 +6694,9 @@ var postgresIntrospector = {
6616
6694
  constraint_name: PgKeyColumnUsage.columns.constraint_name,
6617
6695
  foreign_table_schema: PgConstraintColumnUsage.columns.table_schema,
6618
6696
  foreign_table_name: PgConstraintColumnUsage.columns.table_name,
6619
- 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
6620
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));
6621
6701
  const fkRows = await runSelect(qbFk, ctx);
6622
6702
  const fkMap = /* @__PURE__ */ new Map();
@@ -6626,8 +6706,8 @@ var postgresIntrospector = {
6626
6706
  existing.push({
6627
6707
  table: `${r.foreign_table_schema}.${r.foreign_table_name}`,
6628
6708
  column: r.foreign_column_name,
6629
- onDelete: void 0,
6630
- onUpdate: void 0
6709
+ onDelete: r.delete_rule,
6710
+ onUpdate: r.update_rule
6631
6711
  });
6632
6712
  fkMap.set(key, existing);
6633
6713
  }
@@ -6731,12 +6811,15 @@ var postgresIntrospector = {
6731
6811
  });
6732
6812
  }
6733
6813
  const cols = tablesByKey.get(key);
6814
+ const commentKey = `${r.table_schema}.${r.table_name}.${r.column_name}`;
6815
+ const columnComment = columnComments.get(commentKey);
6734
6816
  const fk = fkMap.get(`${r.table_schema}.${r.table_name}.${r.column_name}`)?.[0];
6735
6817
  const column = {
6736
6818
  name: r.column_name,
6737
6819
  type: r.data_type,
6738
6820
  notNull: r.is_nullable === "NO",
6739
6821
  default: r.column_default ?? void 0,
6822
+ comment: columnComment ?? void 0,
6740
6823
  references: fk ? {
6741
6824
  table: fk.table,
6742
6825
  column: fk.column,
@@ -6764,32 +6847,252 @@ var postgresIntrospector = {
6764
6847
  }
6765
6848
  };
6766
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
+
6767
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
+ };
6768
6950
  var mysqlIntrospector = {
6769
6951
  async introspect(ctx, options) {
6770
6952
  const schema = options.schema;
6771
- const filterClause = schema ? "table_schema = ?" : "table_schema = database()";
6772
- const params = schema ? [schema] : [];
6773
- const columnRows = await queryRows(
6774
- ctx.executor,
6775
- `
6776
- SELECT table_schema, table_name, column_name, data_type, is_nullable, column_default, extra
6777
- FROM information_schema.columns
6778
- WHERE ${filterClause}
6779
- ORDER BY table_name, ordinal_position
6780
- `,
6781
- params
6782
- );
6783
- const pkRows = await queryRows(
6784
- ctx.executor,
6785
- `
6786
- SELECT table_schema, table_name, column_name
6787
- FROM information_schema.key_column_usage
6788
- WHERE constraint_name = 'PRIMARY' AND ${filterClause}
6789
- ORDER BY ordinal_position
6790
- `,
6791
- params
6792
- );
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
+ });
6793
7096
  const pkMap = /* @__PURE__ */ new Map();
6794
7097
  pkRows.forEach((r) => {
6795
7098
  const key = `${r.table_schema}.${r.table_name}`;
@@ -6797,21 +7100,19 @@ var mysqlIntrospector = {
6797
7100
  list.push(r.column_name);
6798
7101
  pkMap.set(key, list);
6799
7102
  });
6800
- const indexRows = await queryRows(
6801
- ctx.executor,
6802
- `
6803
- SELECT
6804
- table_schema,
6805
- table_name,
6806
- index_name,
6807
- non_unique,
6808
- GROUP_CONCAT(column_name ORDER BY seq_in_index) AS cols
6809
- FROM information_schema.statistics
6810
- WHERE ${filterClause} AND index_name <> 'PRIMARY'
6811
- GROUP BY table_schema, table_name, index_name, non_unique
6812
- `,
6813
- params
6814
- );
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
+ });
6815
7116
  const tablesByKey = /* @__PURE__ */ new Map();
6816
7117
  columnRows.forEach((r) => {
6817
7118
  const key = `${r.table_schema}.${r.table_name}`;
@@ -6822,18 +7123,32 @@ var mysqlIntrospector = {
6822
7123
  schema: r.table_schema,
6823
7124
  columns: [],
6824
7125
  primaryKey: pkMap.get(key) || [],
6825
- indexes: []
7126
+ indexes: [],
7127
+ comment: tableComments.get(key) || void 0
6826
7128
  });
6827
7129
  }
6828
- 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;
6829
7133
  const column = {
6830
7134
  name: r.column_name,
6831
- type: r.data_type,
7135
+ type: columnType,
6832
7136
  notNull: r.is_nullable === "NO",
6833
7137
  default: r.column_default ?? void 0,
6834
- autoIncrement: typeof r.extra === "string" && r.extra.includes("auto_increment")
7138
+ autoIncrement: typeof r.extra === "string" && r.extra.includes("auto_increment"),
7139
+ comment
6835
7140
  };
6836
- 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);
6837
7152
  });
6838
7153
  indexRows.forEach((r) => {
6839
7154
  const key = `${r.table_schema}.${r.table_name}`;
@@ -6861,43 +7176,79 @@ var toReferentialAction = (value) => {
6861
7176
  }
6862
7177
  return void 0;
6863
7178
  };
6864
- 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
+ };
6865
7195
  var sqliteIntrospector = {
6866
- /**
6867
- * Introspects the SQLite database schema by querying sqlite_master and various PRAGMAs.
6868
- * @param ctx - The database execution context containing the DbExecutor.
6869
- * @param options - Options controlling which tables and schemas to include.
6870
- * @returns A promise that resolves to the introspected DatabaseSchema.
6871
- */
6872
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);
6873
7209
  const tables = [];
6874
- const tableRows = await queryRows(
6875
- ctx.executor,
6876
- `SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%';`
6877
- );
6878
7210
  for (const row of tableRows) {
6879
- const name = row.name;
6880
- if (!shouldIncludeTable(name, options)) continue;
6881
- const table = { name, columns: [], primaryKey: [], indexes: [] };
6882
- const cols = await queryRows(ctx.executor, `PRAGMA table_info('${escapeSingleQuotes(name)}');`);
6883
- cols.forEach((c) => {
6884
- table.columns.push({
6885
- name: c.name,
6886
- type: c.type,
6887
- notNull: c.notnull === 1,
6888
- 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,
6889
7241
  autoIncrement: false
6890
7242
  });
6891
- if (c.pk && c.pk > 0) {
6892
- table.primaryKey = table.primaryKey || [];
6893
- table.primaryKey.push(c.name);
7243
+ if (info.pk && info.pk > 0) {
7244
+ tableEntry.primaryKey = tableEntry.primaryKey || [];
7245
+ tableEntry.primaryKey.push(info.name);
6894
7246
  }
6895
7247
  });
6896
- const fkRows = await queryRows(ctx.executor, `PRAGMA foreign_key_list('${escapeSingleQuotes(name)}');`);
6897
- fkRows.forEach((fk) => {
6898
- const col2 = table.columns.find((c) => c.name === fk.from);
6899
- if (col2) {
6900
- col2.references = {
7248
+ foreignKeys.forEach((fk) => {
7249
+ const column = tableEntry.columns.find((col2) => col2.name === fk.from);
7250
+ if (column) {
7251
+ column.references = {
6901
7252
  table: fk.table,
6902
7253
  column: fk.to,
6903
7254
  onDelete: toReferentialAction(fk.on_delete),
@@ -6905,72 +7256,529 @@ var sqliteIntrospector = {
6905
7256
  };
6906
7257
  }
6907
7258
  });
6908
- const idxList = await queryRows(ctx.executor, `PRAGMA index_list('${escapeSingleQuotes(name)}');`);
6909
- for (const idx of idxList) {
6910
- const idxName = idx.name;
6911
- 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
+ );
6912
7268
  const idxEntry = {
6913
- name: idxName,
6914
- columns: columnsInfo.map((ci) => ({ column: ci.name })),
7269
+ name: idx.name,
7270
+ columns: indexColumns.map((col2) => ({ column: col2.name })),
6915
7271
  unique: idx.unique === 1
6916
7272
  };
6917
- table.indexes.push(idxEntry);
7273
+ tableEntry.indexes.push(idxEntry);
6918
7274
  }
6919
- tables.push(table);
7275
+ tables.push(tableEntry);
6920
7276
  }
6921
7277
  return { tables };
6922
7278
  }
6923
7279
  };
6924
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
+
6925
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
+ };
6926
7510
  var mssqlIntrospector = {
6927
- /**
6928
- * Introspects the MSSQL database schema.
6929
- * @param ctx - The introspection context containing the database executor.
6930
- * @param options - Options for introspection, such as schema filter.
6931
- * @returns A promise that resolves to the introspected database schema.
6932
- */
6933
7511
  async introspect(ctx, options) {
6934
7512
  const schema = options.schema;
6935
- const filterSchema = schema ? "sch.name = @p1" : "1=1";
6936
- const params = schema ? [schema] : [];
6937
- const columnRows = await queryRows(
6938
- ctx.executor,
6939
- `
6940
- SELECT
6941
- sch.name AS table_schema,
6942
- t.name AS table_name,
6943
- c.name AS column_name,
6944
- ty.name AS data_type,
6945
- c.is_nullable,
6946
- c.is_identity,
6947
- object_definition(c.default_object_id) AS column_default
6948
- FROM sys.columns c
6949
- JOIN sys.tables t ON t.object_id = c.object_id
6950
- JOIN sys.schemas sch ON sch.schema_id = t.schema_id
6951
- JOIN sys.types ty ON ty.user_type_id = c.user_type_id
6952
- WHERE t.is_ms_shipped = 0 AND ${filterSchema}
6953
- `,
6954
- params
6955
- );
6956
- const pkRows = await queryRows(
6957
- ctx.executor,
6958
- `
6959
- SELECT
6960
- sch.name AS table_schema,
6961
- t.name AS table_name,
6962
- c.name AS column_name,
6963
- ic.key_ordinal
6964
- FROM sys.indexes i
6965
- JOIN sys.index_columns ic ON ic.object_id = i.object_id AND ic.index_id = i.index_id
6966
- JOIN sys.columns c ON c.object_id = ic.object_id AND c.column_id = ic.column_id
6967
- JOIN sys.tables t ON t.object_id = i.object_id
6968
- JOIN sys.schemas sch ON sch.schema_id = t.schema_id
6969
- WHERE i.is_primary_key = 1 AND ${filterSchema}
6970
- ORDER BY ic.key_ordinal
6971
- `,
6972
- 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" }
6973
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);
6974
7782
  const pkMap = /* @__PURE__ */ new Map();
6975
7783
  pkRows.forEach((r) => {
6976
7784
  const key = `${r.table_schema}.${r.table_name}`;
@@ -6978,42 +7786,19 @@ var mssqlIntrospector = {
6978
7786
  list.push(r.column_name);
6979
7787
  pkMap.set(key, list);
6980
7788
  });
6981
- const indexRows = await queryRows(
6982
- ctx.executor,
6983
- `
6984
- SELECT
6985
- sch.name AS table_schema,
6986
- t.name AS table_name,
6987
- i.name AS index_name,
6988
- i.is_unique,
6989
- i.has_filter,
6990
- i.filter_definition
6991
- FROM sys.indexes i
6992
- JOIN sys.tables t ON t.object_id = i.object_id
6993
- JOIN sys.schemas sch ON sch.schema_id = t.schema_id
6994
- WHERE i.is_primary_key = 0 AND i.is_hypothetical = 0 AND ${filterSchema}
6995
- `,
6996
- params
6997
- );
6998
- const indexColsRows = await queryRows(
6999
- ctx.executor,
7000
- `
7001
- SELECT
7002
- sch.name AS table_schema,
7003
- t.name AS table_name,
7004
- i.name AS index_name,
7005
- c.name AS column_name,
7006
- ic.key_ordinal
7007
- FROM sys.index_columns ic
7008
- JOIN sys.indexes i ON i.object_id = ic.object_id AND i.index_id = ic.index_id
7009
- JOIN sys.columns c ON c.object_id = ic.object_id AND c.column_id = ic.column_id
7010
- JOIN sys.tables t ON t.object_id = i.object_id
7011
- JOIN sys.schemas sch ON sch.schema_id = t.schema_id
7012
- WHERE i.is_primary_key = 0 AND ${filterSchema}
7013
- ORDER BY ic.key_ordinal
7014
- `,
7015
- params
7016
- );
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
+ });
7017
7802
  const indexColumnsMap = /* @__PURE__ */ new Map();
7018
7803
  indexColsRows.forEach((r) => {
7019
7804
  const key = `${r.table_schema}.${r.table_name}.${r.index_name}`;
@@ -7034,7 +7819,7 @@ var mssqlIntrospector = {
7034
7819
  indexes: []
7035
7820
  });
7036
7821
  }
7037
- const t = tablesByKey.get(key);
7822
+ const table = tablesByKey.get(key);
7038
7823
  const column = {
7039
7824
  name: r.column_name,
7040
7825
  type: r.data_type,
@@ -7042,7 +7827,17 @@ var mssqlIntrospector = {
7042
7827
  default: r.column_default ?? void 0,
7043
7828
  autoIncrement: !!r.is_identity
7044
7829
  };
7045
- 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);
7046
7841
  });
7047
7842
  indexRows.forEach((r) => {
7048
7843
  const key = `${r.table_schema}.${r.table_name}`;
@@ -7053,7 +7848,7 @@ var mssqlIntrospector = {
7053
7848
  name: r.index_name,
7054
7849
  columns: cols,
7055
7850
  unique: !!r.is_unique,
7056
- where: r.has_filter ? r.filter_definition : void 0
7851
+ where: r.has_filter ? r.filter_definition ?? void 0 : void 0
7057
7852
  };
7058
7853
  table.indexes = table.indexes || [];
7059
7854
  table.indexes.push(idx);
@@ -7089,51 +7884,6 @@ var introspectSchema = async (executor, dialect, options = {}) => {
7089
7884
  return handler.introspect(ctx, options);
7090
7885
  };
7091
7886
 
7092
- // src/core/functions/text.ts
7093
- var isColumnDef = (val) => !!val && typeof val === "object" && "type" in val && "name" in val;
7094
- var toOperand2 = (input) => {
7095
- if (isOperandNode(input)) return input;
7096
- if (isColumnDef(input)) return columnOperand(input);
7097
- return valueToOperand(input);
7098
- };
7099
- var fn = (key, args) => ({
7100
- type: "Function",
7101
- name: key,
7102
- fn: key,
7103
- args: args.map(toOperand2)
7104
- });
7105
- var lower = (value) => fn("LOWER", [value]);
7106
- var upper = (value) => fn("UPPER", [value]);
7107
- var ascii = (value) => fn("ASCII", [value]);
7108
- var char = (...codes) => {
7109
- if (codes.length === 0) throw new Error("char() expects at least 1 argument");
7110
- return fn("CHAR", codes);
7111
- };
7112
- var charLength = (value) => fn("CHAR_LENGTH", [value]);
7113
- var length = (value) => fn("LENGTH", [value]);
7114
- var trim = (value, chars) => chars === void 0 ? fn("TRIM", [value]) : fn("TRIM", [value, chars]);
7115
- var ltrim = (value) => fn("LTRIM", [value]);
7116
- var rtrim = (value) => fn("RTRIM", [value]);
7117
- var concat = (...args) => {
7118
- if (args.length < 2) throw new Error("concat() expects at least 2 arguments");
7119
- return fn("CONCAT", args);
7120
- };
7121
- var concatWs = (separator, ...args) => {
7122
- if (args.length < 1) throw new Error("concatWs() expects at least 2 arguments including the separator");
7123
- return fn("CONCAT_WS", [separator, ...args]);
7124
- };
7125
- var substr = (value, start, length2) => length2 === void 0 ? fn("SUBSTR", [value, start]) : fn("SUBSTR", [value, start, length2]);
7126
- var left = (value, len) => fn("LEFT", [value, len]);
7127
- var right = (value, len) => fn("RIGHT", [value, len]);
7128
- var position = (substring, value) => fn("POSITION", [substring, value]);
7129
- var instr = (value, substring) => fn("INSTR", [value, substring]);
7130
- var locate = (substring, value, start) => start === void 0 ? fn("LOCATE", [substring, value]) : fn("LOCATE", [substring, value, start]);
7131
- var replace = (value, search, replacement) => fn("REPLACE", [value, search, replacement]);
7132
- var repeat = (value, count2) => fn("REPEAT", [value, count2]);
7133
- var lpad = (value, len, pad) => fn("LPAD", [value, len, pad]);
7134
- var rpad = (value, len, pad) => fn("RPAD", [value, len, pad]);
7135
- var space = (count2) => fn("SPACE", [count2]);
7136
-
7137
7887
  // src/core/functions/numeric.ts
7138
7888
  var isColumnDef2 = (val) => !!val && typeof val === "object" && "type" in val && "name" in val;
7139
7889
  var toOperand3 = (input) => {
@@ -7141,42 +7891,42 @@ var toOperand3 = (input) => {
7141
7891
  if (isColumnDef2(input)) return columnOperand(input);
7142
7892
  return valueToOperand(input);
7143
7893
  };
7144
- var fn2 = (key, args) => ({
7894
+ var fn3 = (key, args) => ({
7145
7895
  type: "Function",
7146
7896
  name: key,
7147
7897
  fn: key,
7148
7898
  args: args.map(toOperand3)
7149
7899
  });
7150
- var abs = (value) => fn2("ABS", [value]);
7151
- var acos = (value) => fn2("ACOS", [value]);
7152
- var asin = (value) => fn2("ASIN", [value]);
7153
- var atan = (value) => fn2("ATAN", [value]);
7154
- var atan2 = (y, x) => fn2("ATAN2", [y, x]);
7155
- var ceil = (value) => fn2("CEIL", [value]);
7156
- var ceiling = (value) => fn2("CEILING", [value]);
7157
- var cos = (value) => fn2("COS", [value]);
7158
- var cot = (value) => fn2("COT", [value]);
7159
- var degrees = (value) => fn2("DEGREES", [value]);
7160
- var exp = (value) => fn2("EXP", [value]);
7161
- var floor = (value) => fn2("FLOOR", [value]);
7162
- var ln = (value) => fn2("LN", [value]);
7163
- var log = (value) => fn2("LOG", [value]);
7164
- var log10 = (value) => fn2("LOG10", [value]);
7165
- var logBase = (base, value) => fn2("LOG_BASE", [base, value]);
7166
- var mod = (x, y) => fn2("MOD", [x, y]);
7167
- var pi = () => fn2("PI", []);
7168
- var power = (x, y) => fn2("POWER", [x, y]);
7169
- var pow = (x, y) => fn2("POW", [x, y]);
7170
- var radians = (value) => fn2("RADIANS", [value]);
7171
- var random = () => fn2("RANDOM", []);
7172
- var rand = () => fn2("RAND", []);
7173
- var round = (value, decimals) => decimals === void 0 ? fn2("ROUND", [value]) : fn2("ROUND", [value, decimals]);
7174
- var sign = (value) => fn2("SIGN", [value]);
7175
- var sin = (value) => fn2("SIN", [value]);
7176
- var sqrt = (value) => fn2("SQRT", [value]);
7177
- var tan = (value) => fn2("TAN", [value]);
7178
- var trunc = (value, decimals) => decimals === void 0 ? fn2("TRUNC", [value]) : fn2("TRUNC", [value, decimals]);
7179
- 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]);
7180
7930
 
7181
7931
  // src/core/functions/datetime.ts
7182
7932
  var isColumnDef3 = (val) => !!val && typeof val === "object" && "type" in val && "name" in val;
@@ -7185,29 +7935,29 @@ var toOperand4 = (input) => {
7185
7935
  if (isColumnDef3(input)) return columnOperand(input);
7186
7936
  return valueToOperand(input);
7187
7937
  };
7188
- var fn3 = (key, args) => ({
7938
+ var fn4 = (key, args) => ({
7189
7939
  type: "Function",
7190
7940
  name: key,
7191
7941
  args: args.map(toOperand4)
7192
7942
  });
7193
- var now = () => fn3("NOW", []);
7194
- var currentDate = () => fn3("CURRENT_DATE", []);
7195
- var currentTime = () => fn3("CURRENT_TIME", []);
7196
- var utcNow = () => fn3("UTC_NOW", []);
7197
- var extract = (part, date) => fn3("EXTRACT", [part, date]);
7198
- var year = (date) => fn3("YEAR", [date]);
7199
- var month = (date) => fn3("MONTH", [date]);
7200
- var day = (date) => fn3("DAY", [date]);
7201
- var dateAdd = (date, interval, unit) => fn3("DATE_ADD", [date, interval, unit]);
7202
- var dateSub = (date, interval, unit) => fn3("DATE_SUB", [date, interval, unit]);
7203
- var dateDiff = (date1, date2) => fn3("DATE_DIFF", [date1, date2]);
7204
- var dateFormat = (date, format) => fn3("DATE_FORMAT", [date, format]);
7205
- var unixTimestamp = () => fn3("UNIX_TIMESTAMP", []);
7206
- var fromUnixTime = (timestamp) => fn3("FROM_UNIXTIME", [timestamp]);
7207
- var endOfMonth = (date) => fn3("END_OF_MONTH", [date]);
7208
- var dayOfWeek = (date) => fn3("DAY_OF_WEEK", [date]);
7209
- var weekOfYear = (date) => fn3("WEEK_OF_YEAR", [date]);
7210
- 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]);
7211
7961
 
7212
7962
  // src/orm/als.ts
7213
7963
  var AsyncLocalStorage = class {
@@ -7442,6 +8192,7 @@ var TypeScriptGenerator = class {
7442
8192
  case "ScalarSubquery":
7443
8193
  case "CaseExpression":
7444
8194
  case "WindowFunction":
8195
+ case "Cast":
7445
8196
  return this.printOperand(term);
7446
8197
  default:
7447
8198
  return this.printExpression(term);
@@ -7501,6 +8252,9 @@ var TypeScriptGenerator = class {
7501
8252
  visitWindowFunction(node) {
7502
8253
  return this.printWindowFunctionOperand(node);
7503
8254
  }
8255
+ visitCast(node) {
8256
+ return this.printCastOperand(node);
8257
+ }
7504
8258
  visitAliasRef(node) {
7505
8259
  return `aliasRef('${node.name}')`;
7506
8260
  }
@@ -7512,12 +8266,12 @@ var TypeScriptGenerator = class {
7512
8266
  printBinaryExpression(binary) {
7513
8267
  const left2 = this.printOperand(binary.left);
7514
8268
  const right2 = this.printOperand(binary.right);
7515
- const fn4 = this.mapOp(binary.operator);
8269
+ const fn5 = this.mapOp(binary.operator);
7516
8270
  const args = [left2, right2];
7517
8271
  if (binary.escape) {
7518
8272
  args.push(this.printOperand(binary.escape));
7519
8273
  }
7520
- return `${fn4}(${args.join(", ")})`;
8274
+ return `${fn5}(${args.join(", ")})`;
7521
8275
  }
7522
8276
  /**
7523
8277
  * Prints a logical expression to TypeScript code
@@ -7546,13 +8300,13 @@ var TypeScriptGenerator = class {
7546
8300
  */
7547
8301
  printInExpression(inExpr) {
7548
8302
  const left2 = this.printOperand(inExpr.left);
7549
- const fn4 = this.mapOp(inExpr.operator);
8303
+ const fn5 = this.mapOp(inExpr.operator);
7550
8304
  if (Array.isArray(inExpr.right)) {
7551
8305
  const values = inExpr.right.map((v) => this.printOperand(v)).join(", ");
7552
- return `${fn4}(${left2}, [${values}])`;
8306
+ return `${fn5}(${left2}, [${values}])`;
7553
8307
  }
7554
8308
  const subquery = this.inlineChain(this.buildSelectLines(inExpr.right.query));
7555
- return `${fn4}(${left2}, (${subquery}))`;
8309
+ return `${fn5}(${left2}, (${subquery}))`;
7556
8310
  }
7557
8311
  /**
7558
8312
  * Prints a null expression to TypeScript code
@@ -7561,8 +8315,8 @@ var TypeScriptGenerator = class {
7561
8315
  */
7562
8316
  printNullExpression(nullExpr) {
7563
8317
  const left2 = this.printOperand(nullExpr.left);
7564
- const fn4 = this.mapOp(nullExpr.operator);
7565
- return `${fn4}(${left2})`;
8318
+ const fn5 = this.mapOp(nullExpr.operator);
8319
+ return `${fn5}(${left2})`;
7566
8320
  }
7567
8321
  /**
7568
8322
  * Prints a BETWEEN expression to TypeScript code
@@ -7606,9 +8360,9 @@ var TypeScriptGenerator = class {
7606
8360
  * @param fn - Function node
7607
8361
  * @returns TypeScript code representation
7608
8362
  */
7609
- printFunctionOperand(fn4) {
7610
- const args = fn4.args.map((a) => this.printOperand(a)).join(", ");
7611
- 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})`;
7612
8366
  }
7613
8367
  /**
7614
8368
  * Prints a JSON path operand to TypeScript code
@@ -7668,6 +8422,10 @@ var TypeScriptGenerator = class {
7668
8422
  result += ")";
7669
8423
  return result;
7670
8424
  }
8425
+ printCastOperand(node) {
8426
+ const typeLiteral = node.castType.replace(/'/g, "\\'");
8427
+ return `cast(${this.printOperand(node.expression)}, '${typeLiteral}')`;
8428
+ }
7671
8429
  /**
7672
8430
  * Converts method chain lines to inline format
7673
8431
  * @param lines - Method chain lines
@@ -8832,15 +9590,15 @@ var OrmSession = class {
8832
9590
  * @returns The result of the function
8833
9591
  * @throws If the transaction fails
8834
9592
  */
8835
- async transaction(fn4) {
9593
+ async transaction(fn5) {
8836
9594
  if (!this.executor.capabilities.transactions) {
8837
- const result = await fn4(this);
9595
+ const result = await fn5(this);
8838
9596
  await this.commit();
8839
9597
  return result;
8840
9598
  }
8841
9599
  await this.executor.beginTransaction();
8842
9600
  try {
8843
- const result = await fn4(this);
9601
+ const result = await fn5(this);
8844
9602
  await this.flushWithHooks();
8845
9603
  await this.executor.commitTransaction();
8846
9604
  await this.domainEvents.dispatch(this.unitOfWork.getTracked(), this);
@@ -8943,11 +9701,11 @@ var Orm = class {
8943
9701
  * @returns The result of the function
8944
9702
  * @throws If the transaction fails
8945
9703
  */
8946
- async transaction(fn4) {
9704
+ async transaction(fn5) {
8947
9705
  const executor = this.executorFactory.createTransactionalExecutor();
8948
9706
  const session = new OrmSession({ orm: this, executor });
8949
9707
  try {
8950
- return await session.transaction(() => fn4(session));
9708
+ return await session.transaction(() => fn5(session));
8951
9709
  } finally {
8952
9710
  await session.dispose();
8953
9711
  }
@@ -9033,13 +9791,14 @@ function Entity(options = {}) {
9033
9791
  return decoratorWithContext;
9034
9792
  }
9035
9793
 
9036
- // src/decorators/column.ts
9794
+ // src/decorators/column-decorator.ts
9037
9795
  var normalizeColumnInput = (input) => {
9038
9796
  const asOptions = input;
9039
9797
  const asDefinition = input;
9040
9798
  const column = {
9041
9799
  type: asOptions.type ?? asDefinition.type,
9042
9800
  args: asOptions.args ?? asDefinition.args,
9801
+ dialectTypes: asOptions.dialectTypes ?? asDefinition.dialectTypes,
9043
9802
  notNull: asOptions.notNull ?? asDefinition.notNull,
9044
9803
  primary: asOptions.primary ?? asDefinition.primary,
9045
9804
  tsType: asDefinition.tsType ?? asOptions.tsType,
@@ -9743,6 +10502,7 @@ export {
9743
10502
  PostgresDialect,
9744
10503
  PrimaryKey,
9745
10504
  RelationKinds,
10505
+ STANDARD_COLUMN_TYPES,
9746
10506
  SelectQueryBuilder,
9747
10507
  SqlServerDialect,
9748
10508
  SqliteDialect,
@@ -9764,6 +10524,7 @@ export {
9764
10524
  between,
9765
10525
  bootstrapEntities,
9766
10526
  caseWhen,
10527
+ cast,
9767
10528
  ceil,
9768
10529
  ceiling,
9769
10530
  char,
@@ -9831,6 +10592,7 @@ export {
9831
10592
  instr,
9832
10593
  introspectSchema,
9833
10594
  isCaseExpressionNode,
10595
+ isCastExpressionNode,
9834
10596
  isExpressionSelectionNode,
9835
10597
  isFunctionNode,
9836
10598
  isNotNull,
@@ -9865,6 +10627,7 @@ export {
9865
10627
  month,
9866
10628
  mul,
9867
10629
  neq,
10630
+ normalizeColumnType,
9868
10631
  notBetween,
9869
10632
  notExists,
9870
10633
  notInList,
@@ -9886,6 +10649,7 @@ export {
9886
10649
  registerOperandDispatcher,
9887
10650
  registerSchemaIntrospector,
9888
10651
  renderColumnDefinition,
10652
+ renderTypeWithArgs,
9889
10653
  repeat,
9890
10654
  replace,
9891
10655
  right,