metal-orm 1.0.42 → 1.0.43

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 (86) hide show
  1. package/README.md +22 -7
  2. package/dist/index.cjs +130 -74
  3. package/dist/index.cjs.map +1 -1
  4. package/dist/index.d.cts +121 -96
  5. package/dist/index.d.ts +121 -96
  6. package/dist/index.js +128 -74
  7. package/dist/index.js.map +1 -1
  8. package/package.json +8 -2
  9. package/scripts/run-eslint.mjs +34 -0
  10. package/src/codegen/typescript.ts +32 -15
  11. package/src/core/ast/builders.ts +7 -2
  12. package/src/core/ast/expression-builders.ts +0 -2
  13. package/src/core/ast/expression-nodes.ts +14 -5
  14. package/src/core/ast/expression-visitor.ts +11 -8
  15. package/src/core/ast/join-node.ts +1 -1
  16. package/src/core/ast/query.ts +6 -6
  17. package/src/core/ast/window-functions.ts +10 -2
  18. package/src/core/ddl/dialects/base-schema-dialect.ts +30 -3
  19. package/src/core/ddl/dialects/mssql-schema-dialect.ts +4 -0
  20. package/src/core/ddl/dialects/mysql-schema-dialect.ts +2 -0
  21. package/src/core/ddl/dialects/postgres-schema-dialect.ts +13 -1
  22. package/src/core/ddl/dialects/render-reference.test.ts +69 -0
  23. package/src/core/ddl/dialects/sqlite-schema-dialect.ts +9 -0
  24. package/src/core/ddl/introspect/mssql.ts +42 -8
  25. package/src/core/ddl/introspect/mysql.ts +30 -6
  26. package/src/core/ddl/introspect/postgres.ts +88 -34
  27. package/src/core/ddl/introspect/run-select.ts +6 -4
  28. package/src/core/ddl/introspect/sqlite.ts +56 -11
  29. package/src/core/ddl/introspect/types.ts +0 -1
  30. package/src/core/ddl/introspect/utils.ts +3 -3
  31. package/src/core/ddl/schema-dialect.ts +1 -0
  32. package/src/core/ddl/schema-generator.ts +4 -12
  33. package/src/core/ddl/sql-writing.ts +4 -4
  34. package/src/core/dialect/abstract.ts +18 -6
  35. package/src/core/dialect/base/function-table-formatter.ts +3 -2
  36. package/src/core/dialect/base/join-compiler.ts +5 -3
  37. package/src/core/dialect/base/returning-strategy.ts +1 -0
  38. package/src/core/dialect/base/sql-dialect.ts +3 -3
  39. package/src/core/dialect/mssql/functions.ts +24 -25
  40. package/src/core/dialect/mssql/index.ts +1 -4
  41. package/src/core/dialect/mysql/functions.ts +0 -1
  42. package/src/core/dialect/postgres/functions.ts +33 -34
  43. package/src/core/dialect/postgres/index.ts +1 -0
  44. package/src/core/dialect/sqlite/functions.ts +18 -19
  45. package/src/core/dialect/sqlite/index.ts +2 -0
  46. package/src/core/execution/db-executor.ts +1 -1
  47. package/src/core/execution/executors/mysql-executor.ts +2 -2
  48. package/src/core/execution/executors/postgres-executor.ts +1 -1
  49. package/src/core/execution/pooling/pool.ts +2 -0
  50. package/src/core/functions/datetime.ts +1 -1
  51. package/src/core/functions/numeric.ts +1 -1
  52. package/src/core/functions/text.ts +1 -1
  53. package/src/decorators/bootstrap.ts +27 -8
  54. package/src/decorators/column.ts +3 -11
  55. package/src/decorators/decorator-metadata.ts +3 -9
  56. package/src/decorators/entity.ts +21 -5
  57. package/src/decorators/relations.ts +2 -11
  58. package/src/orm/entity-context.ts +8 -8
  59. package/src/orm/entity-meta.ts +8 -8
  60. package/src/orm/entity-metadata.ts +11 -9
  61. package/src/orm/entity.ts +28 -29
  62. package/src/orm/execute.ts +4 -4
  63. package/src/orm/hydration.ts +42 -39
  64. package/src/orm/identity-map.ts +1 -1
  65. package/src/orm/lazy-batch.ts +9 -9
  66. package/src/orm/orm-session.ts +24 -23
  67. package/src/orm/orm.ts +2 -5
  68. package/src/orm/relation-change-processor.ts +12 -11
  69. package/src/orm/relations/belongs-to.ts +11 -11
  70. package/src/orm/relations/has-many.ts +10 -10
  71. package/src/orm/relations/has-one.ts +8 -7
  72. package/src/orm/relations/many-to-many.ts +13 -13
  73. package/src/orm/runtime-types.ts +4 -4
  74. package/src/orm/save-graph.ts +31 -25
  75. package/src/orm/unit-of-work.ts +17 -17
  76. package/src/query-builder/delete.ts +4 -3
  77. package/src/query-builder/hydration-manager.ts +6 -5
  78. package/src/query-builder/insert.ts +12 -8
  79. package/src/query-builder/query-ast-service.ts +2 -2
  80. package/src/query-builder/raw-column-parser.ts +2 -1
  81. package/src/query-builder/select-helpers.ts +2 -2
  82. package/src/query-builder/select.ts +31 -31
  83. package/src/query-builder/update.ts +4 -3
  84. package/src/schema/column.ts +26 -26
  85. package/src/schema/table.ts +47 -18
  86. package/src/schema/types.ts +22 -22
package/dist/index.js CHANGED
@@ -32,7 +32,8 @@ var init_schema_plan_executor = __esm({
32
32
  // src/schema/table.ts
33
33
  var defineTable = (name, columns, relations = {}, hooks, options = {}) => {
34
34
  const colsWithNames = Object.entries(columns).reduce((acc, [key, def]) => {
35
- acc[key] = { ...def, name: key, table: name };
35
+ const colDef = { ...def, name: key, table: name };
36
+ acc[key] = colDef;
36
37
  return acc;
37
38
  }, {});
38
39
  return {
@@ -56,17 +57,20 @@ var withColumnProps = (table) => {
56
57
  if (cached) return cached;
57
58
  const proxy = new Proxy(table, {
58
59
  get(target, prop, receiver) {
59
- if (prop === "$") return target.columns;
60
+ const t = target;
61
+ if (prop === "$") return t.columns;
60
62
  if (Reflect.has(target, prop)) return Reflect.get(target, prop, receiver);
61
- if (typeof prop === "string" && prop in target.columns) return target.columns[prop];
63
+ if (typeof prop === "string" && prop in t.columns) return t.columns[prop];
62
64
  return void 0;
63
65
  },
64
66
  has(target, prop) {
65
- return prop === "$" || Reflect.has(target, prop) || typeof prop === "string" && prop in target.columns;
67
+ const t = target;
68
+ return prop === "$" || Reflect.has(target, prop) || typeof prop === "string" && prop in t.columns;
66
69
  },
67
70
  ownKeys(target) {
71
+ const t = target;
68
72
  const base = Reflect.ownKeys(target);
69
- const cols = Object.keys(target.columns);
73
+ const cols = Object.keys(t.columns);
70
74
  for (const k of cols) {
71
75
  if (!base.includes(k)) base.push(k);
72
76
  }
@@ -98,6 +102,14 @@ var withColumnProps = (table) => {
98
102
  return proxy;
99
103
  };
100
104
  var tableRef = (table) => withColumnProps(table);
105
+ function getColumn(table, key) {
106
+ const col2 = table.columns[key];
107
+ if (!col2) {
108
+ const tableName = table.name || "<unknown>";
109
+ throw new Error(`Column '${key}' does not exist on table '${tableName}'`);
110
+ }
111
+ return col2;
112
+ }
101
113
 
102
114
  // src/schema/column.ts
103
115
  var col = {
@@ -302,10 +314,14 @@ var operandTypes = /* @__PURE__ */ new Set([
302
314
  "CaseExpression",
303
315
  "WindowFunction"
304
316
  ]);
305
- var isOperandNode = (node) => node && operandTypes.has(node.type);
306
- var isFunctionNode = (node) => node?.type === "Function";
307
- var isCaseExpressionNode = (node) => node?.type === "CaseExpression";
308
- var isWindowFunctionNode = (node) => node?.type === "WindowFunction";
317
+ var hasTypeProperty = (value) => typeof value === "object" && value !== null && "type" in value;
318
+ var isOperandNode = (node) => {
319
+ if (!hasTypeProperty(node)) return false;
320
+ return operandTypes.has(node.type);
321
+ };
322
+ var isFunctionNode = (node) => isOperandNode(node) && node.type === "Function";
323
+ var isCaseExpressionNode = (node) => isOperandNode(node) && node.type === "CaseExpression";
324
+ var isWindowFunctionNode = (node) => isOperandNode(node) && node.type === "WindowFunction";
309
325
  var isExpressionSelectionNode = (node) => isFunctionNode(node) || isCaseExpressionNode(node) || isWindowFunctionNode(node);
310
326
 
311
327
  // src/core/ast/expression-builders.ts
@@ -595,14 +611,15 @@ var registerOperandDispatcher = (type, dispatcher) => {
595
611
  };
596
612
  var clearExpressionDispatchers = () => expressionDispatchers.clear();
597
613
  var clearOperandDispatchers = () => operandDispatchers.clear();
614
+ var getNodeType = (node) => typeof node === "object" && node !== null && typeof node.type === "string" ? node.type : void 0;
598
615
  var unsupportedExpression = (node) => {
599
- throw new Error(`Unsupported expression type "${node?.type ?? "unknown"}"`);
616
+ throw new Error(`Unsupported expression type "${getNodeType(node) ?? "unknown"}"`);
600
617
  };
601
618
  var unsupportedOperand = (node) => {
602
- throw new Error(`Unsupported operand type "${node?.type ?? "unknown"}"`);
619
+ throw new Error(`Unsupported operand type "${getNodeType(node) ?? "unknown"}"`);
603
620
  };
604
621
  var visitExpression = (node, visitor) => {
605
- const dynamic = expressionDispatchers.get(node?.type);
622
+ const dynamic = expressionDispatchers.get(node.type);
606
623
  if (dynamic) return dynamic(node, visitor);
607
624
  switch (node.type) {
608
625
  case "BinaryExpression":
@@ -633,7 +650,7 @@ var visitExpression = (node, visitor) => {
633
650
  return unsupportedExpression(node);
634
651
  };
635
652
  var visitOperand = (node, visitor) => {
636
- const dynamic = operandDispatchers.get(node?.type);
653
+ const dynamic = operandDispatchers.get(node.type);
637
654
  if (dynamic) return dynamic(node, visitor);
638
655
  switch (node.type) {
639
656
  case "Column":
@@ -860,7 +877,8 @@ var Dialect = class _Dialect {
860
877
  if (!where) return "";
861
878
  return ` WHERE ${this.compileExpression(where, ctx)}`;
862
879
  }
863
- compileReturning(returning, ctx) {
880
+ compileReturning(returning, _ctx) {
881
+ void _ctx;
864
882
  if (!returning || returning.length === 0) return "";
865
883
  throw new Error("RETURNING is not supported by this dialect.");
866
884
  }
@@ -908,14 +926,16 @@ var Dialect = class _Dialect {
908
926
  * @param index - Parameter index
909
927
  * @returns Formatted placeholder string
910
928
  */
911
- formatPlaceholder(index) {
929
+ formatPlaceholder(_index) {
930
+ void _index;
912
931
  return "?";
913
932
  }
914
933
  /**
915
934
  * Whether the current dialect supports a given set operation.
916
935
  * Override in concrete dialects to restrict support.
917
936
  */
918
- supportsSetOperation(kind) {
937
+ supportsSetOperation(_kind) {
938
+ void _kind;
919
939
  return true;
920
940
  }
921
941
  /**
@@ -1108,15 +1128,22 @@ var Dialect = class _Dialect {
1108
1128
  }
1109
1129
  registerDefaultOperandCompilers() {
1110
1130
  this.registerOperandCompiler("Literal", (literal, ctx) => ctx.addParameter(literal.value));
1111
- this.registerOperandCompiler("AliasRef", (alias, _ctx) => this.quoteIdentifier(alias.name));
1131
+ this.registerOperandCompiler("AliasRef", (alias, _ctx) => {
1132
+ void _ctx;
1133
+ return this.quoteIdentifier(alias.name);
1134
+ });
1112
1135
  this.registerOperandCompiler("Column", (column, _ctx) => {
1136
+ void _ctx;
1113
1137
  return `${this.quoteIdentifier(column.table)}.${this.quoteIdentifier(column.name)}`;
1114
1138
  });
1115
1139
  this.registerOperandCompiler(
1116
1140
  "Function",
1117
1141
  (fnNode, ctx) => this.compileFunctionOperand(fnNode, ctx)
1118
1142
  );
1119
- this.registerOperandCompiler("JsonPath", (path, _ctx) => this.compileJsonPath(path));
1143
+ this.registerOperandCompiler("JsonPath", (path, _ctx) => {
1144
+ void _ctx;
1145
+ return this.compileJsonPath(path);
1146
+ });
1120
1147
  this.registerOperandCompiler("ScalarSubquery", (node, ctx) => {
1121
1148
  const sql = this.compileSelectAst(node.query, ctx).trim().replace(/;$/, "");
1122
1149
  return `(${sql})`;
@@ -1160,7 +1187,8 @@ var Dialect = class _Dialect {
1160
1187
  });
1161
1188
  }
1162
1189
  // Default fallback, should be overridden by dialects if supported
1163
- compileJsonPath(node) {
1190
+ compileJsonPath(_node) {
1191
+ void _node;
1164
1192
  throw new Error("JSON Path not supported by this dialect");
1165
1193
  }
1166
1194
  /**
@@ -1326,6 +1354,7 @@ var NoReturningStrategy = class {
1326
1354
  * @throws Error indicating RETURNING is not supported.
1327
1355
  */
1328
1356
  compileReturning(returning, _ctx) {
1357
+ void _ctx;
1329
1358
  if (!returning || returning.length === 0) return "";
1330
1359
  throw new Error("RETURNING is not supported by this dialect.");
1331
1360
  }
@@ -1727,6 +1756,7 @@ var PostgresDialect = class extends SqlDialectBase {
1727
1756
  return `${col2}->>'${node.path}'`;
1728
1757
  }
1729
1758
  compileReturning(returning, ctx) {
1759
+ void ctx;
1730
1760
  if (!returning || returning.length === 0) return "";
1731
1761
  const columns = this.formatReturningColumns(returning);
1732
1762
  return ` RETURNING ${columns}`;
@@ -1977,9 +2007,11 @@ var SqliteDialect = class extends SqlDialectBase {
1977
2007
  return `json_extract(${col2}, '${node.path}')`;
1978
2008
  }
1979
2009
  compileQualifiedColumn(column, _table) {
2010
+ void _table;
1980
2011
  return this.quoteIdentifier(column.name);
1981
2012
  }
1982
2013
  compileReturning(returning, ctx) {
2014
+ void ctx;
1983
2015
  if (!returning || returning.length === 0) return "";
1984
2016
  const columns = this.formatReturningColumns(returning);
1985
2017
  return ` RETURNING ${columns}`;
@@ -2632,7 +2664,8 @@ var HydrationManager = class _HydrationManager {
2632
2664
  getProjectionNames(columns) {
2633
2665
  const names = [];
2634
2666
  for (const col2 of columns) {
2635
- const alias = col2.alias ?? col2.name;
2667
+ const node = col2;
2668
+ const alias = node.alias ?? node.name;
2636
2669
  if (!alias) return void 0;
2637
2670
  names.push(alias);
2638
2671
  }
@@ -2849,7 +2882,8 @@ var buildDefaultHydrationPlan = (table) => ({
2849
2882
  // src/query-builder/raw-column-parser.ts
2850
2883
  var parseRawColumn = (col2, tableName, ctes) => {
2851
2884
  if (col2.includes("(")) {
2852
- const [fn4, rest] = col2.split("(");
2885
+ const [_fn, rest] = col2.split("(");
2886
+ void _fn;
2853
2887
  const colName = rest.replace(")", "");
2854
2888
  const [table, name] = colName.includes(".") ? colName.split(".") : [tableName, colName];
2855
2889
  return { type: "Column", table, name, alias: col2 };
@@ -3049,7 +3083,7 @@ var QueryAstService = class {
3049
3083
  normalizeOrderingTerm(term) {
3050
3084
  const from = this.state.ast.from;
3051
3085
  const tableRef2 = from.type === "Table" && from.alias ? { ...this.table, alias: from.alias } : this.table;
3052
- const termType = term?.type;
3086
+ const termType = term.type;
3053
3087
  if (termType === "Column") {
3054
3088
  return term;
3055
3089
  }
@@ -4049,7 +4083,6 @@ var DefaultManyToManyCollection = class {
4049
4083
  }
4050
4084
  async syncByIds(ids) {
4051
4085
  await this.load();
4052
- const targetKey = this.relation.targetKey || findPrimaryKey(this.relation.target);
4053
4086
  const normalized = new Set(ids.map((id) => toKey5(id)));
4054
4087
  const currentIds = new Set(this.items.map((item) => toKey5(this.extractId(item))));
4055
4088
  for (const id of normalized) {
@@ -4320,7 +4353,6 @@ var createEntityProxy = (ctx, table, row, lazyRelations = []) => {
4320
4353
  enumerable: false,
4321
4354
  writable: false
4322
4355
  });
4323
- let proxy;
4324
4356
  const handler = {
4325
4357
  get(targetObj, prop, receiver) {
4326
4358
  if (prop === ENTITY_META) {
@@ -4328,7 +4360,7 @@ var createEntityProxy = (ctx, table, row, lazyRelations = []) => {
4328
4360
  }
4329
4361
  if (prop === "$load") {
4330
4362
  return async (relationName) => {
4331
- const wrapper = getRelationWrapper(meta, relationName, proxy);
4363
+ const wrapper = getRelationWrapper(meta, relationName, receiver);
4332
4364
  if (wrapper && typeof wrapper.load === "function") {
4333
4365
  return wrapper.load();
4334
4366
  }
@@ -4336,19 +4368,19 @@ var createEntityProxy = (ctx, table, row, lazyRelations = []) => {
4336
4368
  };
4337
4369
  }
4338
4370
  if (typeof prop === "string" && table.relations[prop]) {
4339
- return getRelationWrapper(meta, prop, proxy);
4371
+ return getRelationWrapper(meta, prop, receiver);
4340
4372
  }
4341
4373
  return Reflect.get(targetObj, prop, receiver);
4342
4374
  },
4343
4375
  set(targetObj, prop, value, receiver) {
4344
4376
  const result = Reflect.set(targetObj, prop, value, receiver);
4345
4377
  if (typeof prop === "string" && table.columns[prop]) {
4346
- ctx.markDirty(proxy);
4378
+ ctx.markDirty(receiver);
4347
4379
  }
4348
4380
  return result;
4349
4381
  }
4350
4382
  };
4351
- proxy = new Proxy(target, handler);
4383
+ const proxy = new Proxy(target, handler);
4352
4384
  populateHydrationCache(proxy, row, meta);
4353
4385
  return proxy;
4354
4386
  };
@@ -4590,7 +4622,8 @@ var SelectQueryBuilder = class _SelectQueryBuilder {
4590
4622
  return this.clone(nextContext);
4591
4623
  }
4592
4624
  resolveQueryNode(query) {
4593
- return typeof query.getAST === "function" ? query.getAST() : query;
4625
+ const candidate = query;
4626
+ return typeof candidate.getAST === "function" && candidate.getAST ? candidate.getAST() : query;
4594
4627
  }
4595
4628
  applyCorrelation(ast, correlation) {
4596
4629
  if (!correlation) return ast;
@@ -4859,18 +4892,18 @@ var SelectQueryBuilder = class _SelectQueryBuilder {
4859
4892
  * Selects columns for the root table and relations from a single config object.
4860
4893
  */
4861
4894
  selectColumnsDeep(config) {
4862
- let qb = this;
4895
+ let currBuilder = this;
4863
4896
  if (config.root?.length) {
4864
- qb = qb.selectColumns(...config.root);
4897
+ currBuilder = currBuilder.selectColumns(...config.root);
4865
4898
  }
4866
4899
  for (const key of Object.keys(config)) {
4867
4900
  if (key === "root") continue;
4868
4901
  const relName = key;
4869
4902
  const cols = config[relName];
4870
4903
  if (!cols || !cols.length) continue;
4871
- qb = qb.selectRelationColumns(relName, ...cols);
4904
+ currBuilder = currBuilder.selectRelationColumns(relName, ...cols);
4872
4905
  }
4873
- return qb;
4906
+ return currBuilder;
4874
4907
  }
4875
4908
  getLazyRelations() {
4876
4909
  return Array.from(this.lazyRelations);
@@ -5305,6 +5338,13 @@ var selectFromEntity = (ctor) => {
5305
5338
  }
5306
5339
  return new SelectQueryBuilder(table);
5307
5340
  };
5341
+ var entityRef = (ctor) => {
5342
+ const table = getTableDefFromEntity(ctor);
5343
+ if (!table) {
5344
+ throw new Error(`Entity '${ctor.name}' is not registered with decorators or has not been bootstrapped`);
5345
+ }
5346
+ return tableRef(table);
5347
+ };
5308
5348
 
5309
5349
  // src/query-builder/select-helpers.ts
5310
5350
  function sel(table, ...cols) {
@@ -5457,11 +5497,13 @@ var InsertQueryBuilder = class _InsertQueryBuilder {
5457
5497
  return columns.map((column) => buildColumnNode(this.table, column));
5458
5498
  }
5459
5499
  resolveSelectQuery(query) {
5460
- return typeof query.getAST === "function" ? query.getAST() : query;
5500
+ const candidate = query;
5501
+ return typeof candidate.getAST === "function" && candidate.getAST ? candidate.getAST() : query;
5461
5502
  }
5462
5503
  compile(arg) {
5463
- if (typeof arg.compileInsert === "function") {
5464
- return arg.compileInsert(this.state.ast);
5504
+ const candidate = arg;
5505
+ if (typeof candidate.compileInsert === "function") {
5506
+ return candidate.compileInsert(this.state.ast);
5465
5507
  }
5466
5508
  const dialect = resolveDialectInput(arg);
5467
5509
  return dialect.compileInsert(this.state.ast);
@@ -5598,8 +5640,9 @@ var UpdateQueryBuilder = class _UpdateQueryBuilder {
5598
5640
  return this.resolveTableSource(table);
5599
5641
  }
5600
5642
  compile(arg) {
5601
- if (typeof arg.compileUpdate === "function") {
5602
- return arg.compileUpdate(this.state.ast);
5643
+ const candidate = arg;
5644
+ if (typeof candidate.compileUpdate === "function") {
5645
+ return candidate.compileUpdate(this.state.ast);
5603
5646
  }
5604
5647
  const dialect = resolveDialectInput(arg);
5605
5648
  return dialect.compileUpdate(this.state.ast);
@@ -5700,8 +5743,9 @@ var DeleteQueryBuilder = class _DeleteQueryBuilder {
5700
5743
  return this.resolveTableSource(table);
5701
5744
  }
5702
5745
  compile(arg) {
5703
- if (typeof arg.compileDelete === "function") {
5704
- return arg.compileDelete(this.state.ast);
5746
+ const candidate = arg;
5747
+ if (typeof candidate.compileDelete === "function") {
5748
+ return candidate.compileDelete(this.state.ast);
5705
5749
  }
5706
5750
  const dialect = resolveDialectInput(arg);
5707
5751
  return dialect.compileDelete(this.state.ast);
@@ -5751,7 +5795,7 @@ var generateCreateTableSql = (table, dialect) => {
5751
5795
  const pk = resolvePrimaryKey(table);
5752
5796
  const inlinePkColumns = /* @__PURE__ */ new Set();
5753
5797
  const columnLines = Object.values(table.columns).map((col2) => {
5754
- const includePk = dialect.preferInlinePkAutoincrement?.(col2, table, pk) && pk.includes(col2.name);
5798
+ const includePk = dialect.preferInlinePkAutoincrement(col2, table, pk) && pk.includes(col2.name);
5755
5799
  if (includePk) {
5756
5800
  inlinePkColumns.add(col2.name);
5757
5801
  }
@@ -6256,7 +6300,7 @@ var postgresIntrospector = {
6256
6300
  ],
6257
6301
  where: and(
6258
6302
  eq({ table: "ns", name: "nspname" }, schema),
6259
- eq({ table: "i", name: "indisprimary" }, { type: "Literal", value: false })
6303
+ eq({ table: "i", name: "indisprimary" }, false)
6260
6304
  )
6261
6305
  };
6262
6306
  const indexQueryRows = await runSelectNode(indexQuery, ctx);
@@ -6420,6 +6464,14 @@ var mysqlIntrospector = {
6420
6464
  };
6421
6465
 
6422
6466
  // src/core/ddl/introspect/sqlite.ts
6467
+ var toReferentialAction = (value) => {
6468
+ if (!value) return void 0;
6469
+ const normalized = value.toUpperCase();
6470
+ if (normalized === "NO ACTION" || normalized === "RESTRICT" || normalized === "CASCADE" || normalized === "SET NULL" || normalized === "SET DEFAULT") {
6471
+ return normalized;
6472
+ }
6473
+ return void 0;
6474
+ };
6423
6475
  var escapeSingleQuotes = (name) => name.replace(/'/g, "''");
6424
6476
  var sqliteIntrospector = {
6425
6477
  async introspect(ctx, options) {
@@ -6453,8 +6505,8 @@ var sqliteIntrospector = {
6453
6505
  col2.references = {
6454
6506
  table: fk.table,
6455
6507
  column: fk.to,
6456
- onDelete: fk.on_delete?.toUpperCase(),
6457
- onUpdate: fk.on_update?.toUpperCase()
6508
+ onDelete: toReferentialAction(fk.on_delete),
6509
+ onUpdate: toReferentialAction(fk.on_update)
6458
6510
  };
6459
6511
  }
6460
6512
  });
@@ -6864,11 +6916,7 @@ var TypeScriptGenerator = class {
6864
6916
  const lines = [];
6865
6917
  const hydration = ast.meta?.hydration;
6866
6918
  const hydratedRelations = new Set(hydration?.relations?.map((r) => r.name) ?? []);
6867
- const selections = ast.columns.filter((col2) => !(hydration && isRelationAlias(col2.alias))).map((col2) => {
6868
- const key = col2.alias || col2.name;
6869
- const operand = col2;
6870
- return `${key}: ${this.printOperand(operand)}`;
6871
- });
6919
+ const selections = ast.columns.filter((col2) => !(hydration && isRelationAlias(col2.alias))).map((col2, index) => `${this.getSelectionKey(col2, index)}: ${this.printOperand(col2)}`);
6872
6920
  lines.push(`db.select({`);
6873
6921
  selections.forEach((sel2, index) => {
6874
6922
  lines.push(` ${sel2}${index < selections.length - 1 ? "," : ""}`);
@@ -6956,7 +7004,7 @@ var TypeScriptGenerator = class {
6956
7004
  * Prints an ordering term (operand/expression/alias) to TypeScript code.
6957
7005
  */
6958
7006
  printOrderingTerm(term) {
6959
- if (!term || !term.type) {
7007
+ if (!term || !("type" in term)) {
6960
7008
  throw new Error("Unsupported ordering term");
6961
7009
  }
6962
7010
  switch (term.type) {
@@ -6975,6 +7023,18 @@ var TypeScriptGenerator = class {
6975
7023
  return this.printExpression(term);
6976
7024
  }
6977
7025
  }
7026
+ getSelectionKey(selection, index) {
7027
+ if (selection.alias) {
7028
+ return selection.alias;
7029
+ }
7030
+ if (this.isNamedSelection(selection)) {
7031
+ return selection.name;
7032
+ }
7033
+ return `selection${index + 1}`;
7034
+ }
7035
+ isNamedSelection(selection) {
7036
+ return "name" in selection;
7037
+ }
6978
7038
  visitBinaryExpression(binary) {
6979
7039
  return this.printBinaryExpression(binary);
6980
7040
  }
@@ -7758,6 +7818,7 @@ var RelationChangeProcessor = class {
7758
7818
  * @param _entry - The relation change entry (reserved for future use)
7759
7819
  */
7760
7820
  async handleBelongsToChange(_entry) {
7821
+ void _entry;
7761
7822
  }
7762
7823
  /**
7763
7824
  * Handles changes for belongs-to-many relations.
@@ -7871,7 +7932,7 @@ var RelationChangeProcessor = class {
7871
7932
  const key = findPrimaryKey(table);
7872
7933
  const value = entity[key];
7873
7934
  if (value === void 0 || value === null) return null;
7874
- return value;
7935
+ return value ?? null;
7875
7936
  }
7876
7937
  };
7877
7938
 
@@ -8463,8 +8524,6 @@ var Orm = class {
8463
8524
  const session = new OrmSession({ orm: this, executor });
8464
8525
  try {
8465
8526
  return await session.transaction(() => fn4(session));
8466
- } catch (err) {
8467
- throw err;
8468
8527
  } finally {
8469
8528
  await session.dispose();
8470
8529
  }
@@ -8495,9 +8554,6 @@ var getOrCreateMetadataBag = (context) => {
8495
8554
  var readMetadataBag = (context) => {
8496
8555
  return context.metadata?.[METADATA_KEY];
8497
8556
  };
8498
- var registerInitializer = (context, initializer) => {
8499
- context.addInitializer?.(initializer);
8500
- };
8501
8557
 
8502
8558
  // src/decorators/entity.ts
8503
8559
  var toSnakeCase = (value) => {
@@ -8527,14 +8583,24 @@ function Entity(options = {}) {
8527
8583
  if (bag) {
8528
8584
  const meta = ensureEntityMetadata(ctor);
8529
8585
  for (const entry of bag.columns) {
8530
- if (!meta.columns[entry.propertyName]) {
8531
- addColumnMetadata(ctor, entry.propertyName, { ...entry.column });
8586
+ if (meta.columns[entry.propertyName]) {
8587
+ throw new Error(
8588
+ `Column '${entry.propertyName}' is already defined on entity '${ctor.name}'.`
8589
+ );
8532
8590
  }
8591
+ addColumnMetadata(ctor, entry.propertyName, { ...entry.column });
8533
8592
  }
8534
8593
  for (const entry of bag.relations) {
8535
- if (!meta.relations[entry.propertyName]) {
8536
- addRelationMetadata(ctor, entry.propertyName, entry.relation);
8594
+ if (meta.relations[entry.propertyName]) {
8595
+ throw new Error(
8596
+ `Relation '${entry.propertyName}' is already defined on entity '${ctor.name}'.`
8597
+ );
8537
8598
  }
8599
+ const relationCopy = entry.relation.kind === RelationKinds.BelongsToMany ? {
8600
+ ...entry.relation,
8601
+ defaultPivotColumns: entry.relation.defaultPivotColumns ? [...entry.relation.defaultPivotColumns] : void 0
8602
+ } : { ...entry.relation };
8603
+ addRelationMetadata(ctor, entry.propertyName, relationCopy);
8538
8604
  }
8539
8605
  }
8540
8606
  }
@@ -8597,13 +8663,6 @@ var registerColumnFromContext = (context, column) => {
8597
8663
  if (!bag.columns.some((entry) => entry.propertyName === propertyName)) {
8598
8664
  bag.columns.push({ propertyName, column: { ...column } });
8599
8665
  }
8600
- registerInitializer(context, function() {
8601
- const ctor = resolveConstructor(this);
8602
- if (!ctor) {
8603
- return;
8604
- }
8605
- registerColumn(ctor, propertyName, column);
8606
- });
8607
8666
  };
8608
8667
  function Column(definition) {
8609
8668
  const normalized = normalizeColumnInput(definition);
@@ -8659,13 +8718,6 @@ var createFieldDecorator = (metadataFactory) => {
8659
8718
  if (!bag.relations.some((entry) => entry.propertyName === propertyName2)) {
8660
8719
  bag.relations.push({ propertyName: propertyName2, relation: relationMetadata });
8661
8720
  }
8662
- registerInitializer(ctx, function() {
8663
- const ctor2 = resolveConstructor2(this);
8664
- if (!ctor2) {
8665
- return;
8666
- }
8667
- registerRelation(ctor2, propertyName2, relationMetadata);
8668
- });
8669
8721
  return;
8670
8722
  }
8671
8723
  const propertyName = normalizePropertyName2(propertyKeyOrContext);
@@ -9330,6 +9382,7 @@ export {
9330
9382
  diffSchema,
9331
9383
  div,
9332
9384
  endOfMonth,
9385
+ entityRef,
9333
9386
  eq,
9334
9387
  esel,
9335
9388
  executeHydrated,
@@ -9342,6 +9395,7 @@ export {
9342
9395
  fromUnixTime,
9343
9396
  generateCreateTableSql,
9344
9397
  generateSchemaSql,
9398
+ getColumn,
9345
9399
  getSchemaIntrospector,
9346
9400
  getTableDefFromEntity,
9347
9401
  groupConcat,