metal-orm 1.0.43 → 1.0.45

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 (85) hide show
  1. package/README.md +700 -557
  2. package/dist/index.cjs +896 -476
  3. package/dist/index.cjs.map +1 -1
  4. package/dist/index.d.cts +1146 -275
  5. package/dist/index.d.ts +1146 -275
  6. package/dist/index.js +896 -474
  7. package/dist/index.js.map +1 -1
  8. package/package.json +1 -1
  9. package/src/core/ast/adapters.ts +8 -2
  10. package/src/core/ast/builders.ts +105 -81
  11. package/src/core/ast/expression-builders.ts +430 -390
  12. package/src/core/ast/expression-visitor.ts +47 -8
  13. package/src/core/ast/helpers.ts +23 -0
  14. package/src/core/ast/join-node.ts +17 -1
  15. package/src/core/ddl/dialects/base-schema-dialect.ts +7 -1
  16. package/src/core/ddl/dialects/index.ts +1 -0
  17. package/src/core/ddl/dialects/mssql-schema-dialect.ts +1 -0
  18. package/src/core/ddl/dialects/mysql-schema-dialect.ts +1 -0
  19. package/src/core/ddl/dialects/postgres-schema-dialect.ts +1 -0
  20. package/src/core/ddl/dialects/sqlite-schema-dialect.ts +1 -0
  21. package/src/core/ddl/introspect/catalogs/index.ts +1 -0
  22. package/src/core/ddl/introspect/catalogs/postgres.ts +2 -0
  23. package/src/core/ddl/introspect/context.ts +6 -0
  24. package/src/core/ddl/introspect/functions/postgres.ts +13 -0
  25. package/src/core/ddl/introspect/mssql.ts +11 -0
  26. package/src/core/ddl/introspect/mysql.ts +2 -0
  27. package/src/core/ddl/introspect/postgres.ts +14 -0
  28. package/src/core/ddl/introspect/registry.ts +14 -0
  29. package/src/core/ddl/introspect/run-select.ts +13 -0
  30. package/src/core/ddl/introspect/sqlite.ts +22 -0
  31. package/src/core/ddl/introspect/utils.ts +18 -0
  32. package/src/core/ddl/naming-strategy.ts +6 -0
  33. package/src/core/ddl/schema-dialect.ts +19 -6
  34. package/src/core/ddl/schema-diff.ts +22 -0
  35. package/src/core/ddl/schema-generator.ts +22 -0
  36. package/src/core/ddl/schema-plan-executor.ts +6 -0
  37. package/src/core/ddl/schema-types.ts +6 -0
  38. package/src/core/dialect/abstract.ts +2 -2
  39. package/src/core/execution/pooling/pool.ts +12 -7
  40. package/src/core/functions/datetime.ts +57 -33
  41. package/src/core/functions/numeric.ts +95 -30
  42. package/src/core/functions/standard-strategy.ts +35 -0
  43. package/src/core/functions/text.ts +83 -22
  44. package/src/core/functions/types.ts +23 -8
  45. package/src/decorators/bootstrap.ts +16 -4
  46. package/src/decorators/column.ts +17 -0
  47. package/src/decorators/decorator-metadata.ts +27 -0
  48. package/src/decorators/entity.ts +8 -0
  49. package/src/decorators/index.ts +3 -0
  50. package/src/decorators/relations.ts +32 -0
  51. package/src/orm/als.ts +34 -9
  52. package/src/orm/entity-context.ts +54 -0
  53. package/src/orm/entity-metadata.ts +122 -9
  54. package/src/orm/execute.ts +15 -0
  55. package/src/orm/lazy-batch.ts +158 -98
  56. package/src/orm/relations/has-many.ts +44 -0
  57. package/src/orm/save-graph.ts +45 -0
  58. package/src/query/index.ts +74 -0
  59. package/src/query/target.ts +46 -0
  60. package/src/query-builder/delete-query-state.ts +30 -0
  61. package/src/query-builder/delete.ts +64 -19
  62. package/src/query-builder/hydration-manager.ts +46 -0
  63. package/src/query-builder/insert-query-state.ts +30 -0
  64. package/src/query-builder/insert.ts +46 -2
  65. package/src/query-builder/query-ast-service.ts +5 -0
  66. package/src/query-builder/query-resolution.ts +78 -0
  67. package/src/query-builder/raw-column-parser.ts +5 -0
  68. package/src/query-builder/relation-alias.ts +7 -0
  69. package/src/query-builder/relation-conditions.ts +61 -48
  70. package/src/query-builder/relation-service.ts +68 -63
  71. package/src/query-builder/relation-utils.ts +3 -0
  72. package/src/query-builder/select/cte-facet.ts +40 -0
  73. package/src/query-builder/select/from-facet.ts +80 -0
  74. package/src/query-builder/select/join-facet.ts +62 -0
  75. package/src/query-builder/select/predicate-facet.ts +103 -0
  76. package/src/query-builder/select/projection-facet.ts +69 -0
  77. package/src/query-builder/select/relation-facet.ts +81 -0
  78. package/src/query-builder/select/setop-facet.ts +36 -0
  79. package/src/query-builder/select-helpers.ts +13 -0
  80. package/src/query-builder/select-query-builder-deps.ts +19 -1
  81. package/src/query-builder/select-query-state.ts +2 -1
  82. package/src/query-builder/select.ts +795 -1163
  83. package/src/query-builder/update-query-state.ts +52 -0
  84. package/src/query-builder/update.ts +69 -19
  85. package/src/schema/table-guards.ts +31 -0
package/dist/index.cjs CHANGED
@@ -99,11 +99,9 @@ __export(index_exports, {
99
99
  cos: () => cos,
100
100
  cot: () => cot,
101
101
  count: () => count,
102
- createColumn: () => createColumn,
103
102
  createEntityFromRow: () => createEntityFromRow,
104
103
  createEntityProxy: () => createEntityProxy,
105
104
  createExecutorFromQueryRunner: () => createExecutorFromQueryRunner,
106
- createLiteral: () => createLiteral,
107
105
  createMssqlExecutor: () => createMssqlExecutor,
108
106
  createMysqlExecutor: () => createMysqlExecutor,
109
107
  createPooledExecutorFactory: () => createPooledExecutorFactory,
@@ -542,39 +540,48 @@ var isWindowFunctionNode = (node) => isOperandNode(node) && node.type === "Windo
542
540
  var isExpressionSelectionNode = (node) => isFunctionNode(node) || isCaseExpressionNode(node) || isWindowFunctionNode(node);
543
541
 
544
542
  // src/core/ast/expression-builders.ts
545
- var valueToOperand = (value) => {
546
- if (isOperandNode(value)) {
547
- return value;
548
- }
549
- return {
550
- type: "Literal",
551
- value
552
- };
553
- };
554
- var toNode = (col2) => {
555
- if (isOperandNode(col2)) return col2;
556
- const def = col2;
557
- return { type: "Column", table: def.table || "unknown", name: def.name };
558
- };
543
+ var isLiteralValue = (value) => value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean";
559
544
  var toLiteralNode = (value) => ({
560
545
  type: "Literal",
561
546
  value
562
547
  });
563
- var isLiteralValue = (value) => value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean";
564
- var isValueOperandInput = (value) => isOperandNode(value) || isLiteralValue(value);
565
- var toOperand = (val) => {
566
- if (isLiteralValue(val)) {
567
- return valueToOperand(val);
548
+ var columnRefToNode = (col2) => {
549
+ if (!col2.table) {
550
+ throw new Error(
551
+ `Column "${col2.name}" requires a table reference. Use columnOperand with a fully qualified ColumnRef or ColumnNode.`
552
+ );
568
553
  }
569
- return toNode(val);
554
+ return { type: "Column", table: col2.table, name: col2.name };
570
555
  };
556
+ var toOperandNode = (value) => {
557
+ if (isOperandNode(value)) {
558
+ return value;
559
+ }
560
+ if (isLiteralValue(value)) {
561
+ return toLiteralNode(value);
562
+ }
563
+ return columnRefToNode(value);
564
+ };
565
+ var valueToOperand = (value) => {
566
+ if (isOperandNode(value)) {
567
+ return value;
568
+ }
569
+ return toLiteralNode(value);
570
+ };
571
+ var toOperand = (val) => toOperandNode(val);
572
+ var isValueOperandInput = (value) => isOperandNode(value) || isLiteralValue(value);
571
573
  var hasQueryAst = (value) => typeof value.getAST === "function";
572
574
  var resolveSelectQueryNode = (query) => hasQueryAst(query) ? query.getAST() : query;
573
575
  var toScalarSubqueryNode = (query) => ({
574
576
  type: "ScalarSubquery",
575
577
  query: resolveSelectQueryNode(query)
576
578
  });
577
- var columnOperand = (col2) => toNode(col2);
579
+ var columnOperand = (col2) => {
580
+ if (isOperandNode(col2) && col2.type === "Column") {
581
+ return col2;
582
+ }
583
+ return columnRefToNode(col2);
584
+ };
578
585
  var outerRef = (col2) => ({
579
586
  ...columnOperand(col2),
580
587
  scope: "outer"
@@ -587,7 +594,7 @@ var correlateBy = (table, column) => outerRef({ name: column, table });
587
594
  var createBinaryExpression = (operator, left2, right2, escape) => {
588
595
  const node = {
589
596
  type: "BinaryExpression",
590
- left: toNode(left2),
597
+ left: toOperandNode(left2),
591
598
  operator,
592
599
  right: toOperand(right2)
593
600
  };
@@ -616,17 +623,17 @@ var or = (...operands) => ({
616
623
  });
617
624
  var isNull = (left2) => ({
618
625
  type: "NullExpression",
619
- left: toNode(left2),
626
+ left: toOperandNode(left2),
620
627
  operator: "IS NULL"
621
628
  });
622
629
  var isNotNull = (left2) => ({
623
630
  type: "NullExpression",
624
- left: toNode(left2),
631
+ left: toOperandNode(left2),
625
632
  operator: "IS NOT NULL"
626
633
  });
627
634
  var createInExpression = (operator, left2, right2) => ({
628
635
  type: "InExpression",
629
- left: toNode(left2),
636
+ left: toOperandNode(left2),
630
637
  operator,
631
638
  right: right2
632
639
  });
@@ -636,7 +643,7 @@ var inSubquery = (left2, subquery) => createInExpression("IN", left2, toScalarSu
636
643
  var notInSubquery = (left2, subquery) => createInExpression("NOT IN", left2, toScalarSubqueryNode(subquery));
637
644
  var createBetweenExpression = (operator, left2, lower2, upper2) => ({
638
645
  type: "BetweenExpression",
639
- left: toNode(left2),
646
+ left: toOperandNode(left2),
640
647
  operator,
641
648
  lower: toOperand(lower2),
642
649
  upper: toOperand(upper2)
@@ -818,16 +825,45 @@ var groupConcat = (col2, options) => ({
818
825
  });
819
826
 
820
827
  // src/core/ast/expression-visitor.ts
821
- var expressionDispatchers = /* @__PURE__ */ new Map();
822
- var operandDispatchers = /* @__PURE__ */ new Map();
828
+ var DispatcherRegistry = class _DispatcherRegistry {
829
+ constructor(dispatchers = /* @__PURE__ */ new Map()) {
830
+ this.dispatchers = dispatchers;
831
+ }
832
+ /**
833
+ * Registers a new dispatcher and returns a new registry instance
834
+ */
835
+ register(type, dispatcher) {
836
+ const newMap = new Map(this.dispatchers);
837
+ newMap.set(type, dispatcher);
838
+ return new _DispatcherRegistry(newMap);
839
+ }
840
+ /**
841
+ * Gets a dispatcher for the given type
842
+ */
843
+ get(type) {
844
+ return this.dispatchers.get(type);
845
+ }
846
+ /**
847
+ * Returns a new empty registry
848
+ */
849
+ clear() {
850
+ return new _DispatcherRegistry();
851
+ }
852
+ };
853
+ var expressionRegistry = new DispatcherRegistry();
854
+ var operandRegistry = new DispatcherRegistry();
823
855
  var registerExpressionDispatcher = (type, dispatcher) => {
824
- expressionDispatchers.set(type, dispatcher);
856
+ expressionRegistry = expressionRegistry.register(type, dispatcher);
825
857
  };
826
858
  var registerOperandDispatcher = (type, dispatcher) => {
827
- operandDispatchers.set(type, dispatcher);
859
+ operandRegistry = operandRegistry.register(type, dispatcher);
860
+ };
861
+ var clearExpressionDispatchers = () => {
862
+ expressionRegistry = expressionRegistry.clear();
863
+ };
864
+ var clearOperandDispatchers = () => {
865
+ operandRegistry = operandRegistry.clear();
828
866
  };
829
- var clearExpressionDispatchers = () => expressionDispatchers.clear();
830
- var clearOperandDispatchers = () => operandDispatchers.clear();
831
867
  var getNodeType = (node) => typeof node === "object" && node !== null && typeof node.type === "string" ? node.type : void 0;
832
868
  var unsupportedExpression = (node) => {
833
869
  throw new Error(`Unsupported expression type "${getNodeType(node) ?? "unknown"}"`);
@@ -836,7 +872,7 @@ var unsupportedOperand = (node) => {
836
872
  throw new Error(`Unsupported operand type "${getNodeType(node) ?? "unknown"}"`);
837
873
  };
838
874
  var visitExpression = (node, visitor) => {
839
- const dynamic = expressionDispatchers.get(node.type);
875
+ const dynamic = expressionRegistry.get(node.type);
840
876
  if (dynamic) return dynamic(node, visitor);
841
877
  switch (node.type) {
842
878
  case "BinaryExpression":
@@ -867,7 +903,7 @@ var visitExpression = (node, visitor) => {
867
903
  return unsupportedExpression(node);
868
904
  };
869
905
  var visitOperand = (node, visitor) => {
870
- const dynamic = operandDispatchers.get(node.type);
906
+ const dynamic = operandRegistry.get(node.type);
871
907
  if (dynamic) return dynamic(node, visitor);
872
908
  switch (node.type) {
873
909
  case "Column":
@@ -902,24 +938,35 @@ var visitOperand = (node, visitor) => {
902
938
  };
903
939
 
904
940
  // src/core/ast/adapters.ts
941
+ var hasAlias = (obj) => typeof obj === "object" && obj !== null && "alias" in obj;
905
942
  var toColumnRef = (col2) => ({
906
943
  name: col2.name,
907
944
  table: col2.table,
908
- alias: col2.alias
945
+ alias: hasAlias(col2) ? col2.alias : void 0
909
946
  });
910
947
  var toTableRef = (table) => ({
911
948
  name: table.name,
912
949
  schema: table.schema,
913
- alias: table.alias
950
+ alias: hasAlias(table) ? table.alias : void 0
914
951
  });
915
952
 
916
953
  // src/core/ast/builders.ts
954
+ var isColumnNode = (col2) => "type" in col2 && col2.type === "Column";
955
+ var resolveTableName = (def, table) => {
956
+ if (!def.table) {
957
+ return table.alias || table.name;
958
+ }
959
+ if (table.alias && def.table === table.name) {
960
+ return table.alias;
961
+ }
962
+ return def.table;
963
+ };
917
964
  var buildColumnNode = (table, column) => {
918
- if (column.type === "Column") {
965
+ if (isColumnNode(column)) {
919
966
  return column;
920
967
  }
921
968
  const def = column;
922
- const baseTable = def.table ? table.alias && def.table === table.name ? table.alias : def.table : table.alias || table.name;
969
+ const baseTable = resolveTableName(def, table);
923
970
  return {
924
971
  type: "Column",
925
972
  table: baseTable,
@@ -933,7 +980,8 @@ var buildColumnNodes = (table, names) => names.map((name) => ({
933
980
  }));
934
981
  var createTableNode = (table) => ({
935
982
  type: "Table",
936
- name: table.name
983
+ name: table.name,
984
+ schema: table.schema
937
985
  });
938
986
  var fnTable = (name, args = [], alias, opts) => ({
939
987
  type: "FunctionTable",
@@ -954,6 +1002,9 @@ var derivedTable = (query, alias, columnAliases) => ({
954
1002
 
955
1003
  // src/core/functions/standard-strategy.ts
956
1004
  var StandardFunctionStrategy = class _StandardFunctionStrategy {
1005
+ /**
1006
+ * Creates a new StandardFunctionStrategy and registers standard functions.
1007
+ */
957
1008
  constructor() {
958
1009
  this.renderers = /* @__PURE__ */ new Map();
959
1010
  this.registerStandard();
@@ -992,12 +1043,25 @@ var StandardFunctionStrategy = class _StandardFunctionStrategy {
992
1043
  this.add("DATE_TRUNC", ({ compiledArgs }) => `DATE_TRUNC(${compiledArgs[0]}, ${compiledArgs[1]})`);
993
1044
  this.add("GROUP_CONCAT", (ctx) => this.renderGroupConcat(ctx));
994
1045
  }
1046
+ /**
1047
+ * Registers a renderer for a function name.
1048
+ * @param name - The function name.
1049
+ * @param renderer - The renderer function.
1050
+ */
995
1051
  add(name, renderer) {
996
1052
  this.renderers.set(name, renderer);
997
1053
  }
1054
+ /**
1055
+ * @inheritDoc
1056
+ */
998
1057
  getRenderer(name) {
999
1058
  return this.renderers.get(name);
1000
1059
  }
1060
+ /**
1061
+ * Renders the GROUP_CONCAT function with optional ORDER BY and SEPARATOR.
1062
+ * @param ctx - The function render context.
1063
+ * @returns The rendered SQL string.
1064
+ */
1001
1065
  renderGroupConcat(ctx) {
1002
1066
  const arg = ctx.compiledArgs[0];
1003
1067
  const orderClause = this.buildOrderByExpression(ctx);
@@ -1005,6 +1069,11 @@ var StandardFunctionStrategy = class _StandardFunctionStrategy {
1005
1069
  const separatorClause = this.formatGroupConcatSeparator(ctx);
1006
1070
  return `GROUP_CONCAT(${arg}${orderSegment}${separatorClause})`;
1007
1071
  }
1072
+ /**
1073
+ * Builds the ORDER BY clause for functions like GROUP_CONCAT.
1074
+ * @param ctx - The function render context.
1075
+ * @returns The ORDER BY SQL clause or empty string.
1076
+ */
1008
1077
  buildOrderByExpression(ctx) {
1009
1078
  const orderBy = ctx.node.orderBy;
1010
1079
  if (!orderBy || orderBy.length === 0) {
@@ -1020,16 +1089,27 @@ var StandardFunctionStrategy = class _StandardFunctionStrategy {
1020
1089
  });
1021
1090
  return `ORDER BY ${parts.join(", ")}`;
1022
1091
  }
1092
+ /**
1093
+ * Formats the SEPARATOR clause for GROUP_CONCAT.
1094
+ * @param ctx - The function render context.
1095
+ * @returns The SEPARATOR SQL clause or empty string.
1096
+ */
1023
1097
  formatGroupConcatSeparator(ctx) {
1024
1098
  if (!ctx.node.separator) {
1025
1099
  return "";
1026
1100
  }
1027
1101
  return ` SEPARATOR ${ctx.compileOperand(ctx.node.separator)}`;
1028
1102
  }
1103
+ /**
1104
+ * Gets the separator operand for GROUP_CONCAT, defaulting to comma.
1105
+ * @param ctx - The function render context.
1106
+ * @returns The separator operand.
1107
+ */
1029
1108
  getGroupConcatSeparatorOperand(ctx) {
1030
1109
  return ctx.node.separator ?? _StandardFunctionStrategy.DEFAULT_GROUP_CONCAT_SEPARATOR;
1031
1110
  }
1032
1111
  static {
1112
+ /** Default separator for GROUP_CONCAT, a comma. */
1033
1113
  this.DEFAULT_GROUP_CONCAT_SEPARATOR = {
1034
1114
  type: "Literal",
1035
1115
  value: ","
@@ -2550,7 +2630,7 @@ var SelectQueryState = class _SelectQueryState {
2550
2630
  this.table = table;
2551
2631
  this.ast = ast ?? {
2552
2632
  type: "SelectQuery",
2553
- from: { type: "Table", name: table.name },
2633
+ from: createTableNode(table),
2554
2634
  columns: [],
2555
2635
  joins: []
2556
2636
  };
@@ -2701,10 +2781,18 @@ var SelectQueryState = class _SelectQueryState {
2701
2781
  var createJoinNode = (kind, tableName, condition, relationName) => ({
2702
2782
  type: "Join",
2703
2783
  kind,
2704
- table: typeof tableName === "string" ? { type: "Table", name: tableName } : tableName,
2784
+ table: typeof tableName === "string" ? parseQualifiedTableRef(tableName) : tableName,
2705
2785
  condition,
2706
2786
  meta: relationName ? { relationName } : void 0
2707
2787
  });
2788
+ var parseQualifiedTableRef = (ref) => {
2789
+ const parts = ref.split(".");
2790
+ if (parts.length === 2) {
2791
+ const [schema, name] = parts;
2792
+ return { type: "Table", schema, name };
2793
+ }
2794
+ return { type: "Table", name: ref };
2795
+ };
2708
2796
 
2709
2797
  // src/query-builder/hydration-manager.ts
2710
2798
  var HydrationManager = class _HydrationManager {
@@ -2791,6 +2879,11 @@ var HydrationManager = class _HydrationManager {
2791
2879
  const hasPagination = ast.limit !== void 0 || ast.offset !== void 0;
2792
2880
  return hasPagination && this.hasMultiplyingRelations(plan);
2793
2881
  }
2882
+ /**
2883
+ * Checks if the hydration plan contains relations that multiply rows
2884
+ * @param plan - Hydration plan to check
2885
+ * @returns True if plan has HasMany or BelongsToMany relations
2886
+ */
2794
2887
  hasMultiplyingRelations(plan) {
2795
2888
  return plan.relations.some(
2796
2889
  (rel) => rel.type === RelationKinds.HasMany || rel.type === RelationKinds.BelongsToMany
@@ -2868,6 +2961,12 @@ var HydrationManager = class _HydrationManager {
2868
2961
  ctes: [...ast.ctes ?? [], baseCte, pageCte]
2869
2962
  };
2870
2963
  }
2964
+ /**
2965
+ * Generates a unique CTE name by appending a suffix if needed
2966
+ * @param existing - Existing CTE nodes
2967
+ * @param baseName - Base name for the CTE
2968
+ * @returns Unique CTE name
2969
+ */
2871
2970
  nextCteName(existing, baseName) {
2872
2971
  const names = new Set((existing ?? []).map((cte) => cte.name));
2873
2972
  let candidate = baseName;
@@ -2878,6 +2977,11 @@ var HydrationManager = class _HydrationManager {
2878
2977
  }
2879
2978
  return candidate;
2880
2979
  }
2980
+ /**
2981
+ * Extracts projection names from column nodes
2982
+ * @param columns - Projection nodes
2983
+ * @returns Array of names or undefined if any column lacks name/alias
2984
+ */
2881
2985
  getProjectionNames(columns) {
2882
2986
  const names = [];
2883
2987
  for (const col2 of columns) {
@@ -2888,6 +2992,11 @@ var HydrationManager = class _HydrationManager {
2888
2992
  }
2889
2993
  return names;
2890
2994
  }
2995
+ /**
2996
+ * Builds a map of column keys to their aliases from projection nodes
2997
+ * @param columns - Projection nodes
2998
+ * @returns Map of 'table.name' to alias
2999
+ */
2891
3000
  buildProjectionAliasMap(columns) {
2892
3001
  const map = /* @__PURE__ */ new Map();
2893
3002
  for (const col2 of columns) {
@@ -2898,6 +3007,15 @@ var HydrationManager = class _HydrationManager {
2898
3007
  }
2899
3008
  return map;
2900
3009
  }
3010
+ /**
3011
+ * Maps order by nodes to use base CTE alias
3012
+ * @param orderBy - Original order by nodes
3013
+ * @param plan - Hydration plan
3014
+ * @param projectionAliases - Map of column aliases
3015
+ * @param baseAlias - Base CTE alias
3016
+ * @param availableColumns - Set of available column names
3017
+ * @returns Mapped order by nodes, null if cannot map
3018
+ */
2901
3019
  mapOrderBy(orderBy, plan, projectionAliases, baseAlias, availableColumns) {
2902
3020
  if (!orderBy || orderBy.length === 0) {
2903
3021
  return void 0;
@@ -2910,6 +3028,15 @@ var HydrationManager = class _HydrationManager {
2910
3028
  }
2911
3029
  return mapped;
2912
3030
  }
3031
+ /**
3032
+ * Maps a single ordering term to use base CTE alias
3033
+ * @param term - Ordering term to map
3034
+ * @param plan - Hydration plan
3035
+ * @param projectionAliases - Map of column aliases
3036
+ * @param baseAlias - Base CTE alias
3037
+ * @param availableColumns - Set of available column names
3038
+ * @returns Mapped term or null if cannot map
3039
+ */
2913
3040
  mapOrderingTerm(term, plan, projectionAliases, baseAlias, availableColumns) {
2914
3041
  if (term.type === "Column") {
2915
3042
  const col2 = term;
@@ -2925,6 +3052,13 @@ var HydrationManager = class _HydrationManager {
2925
3052
  }
2926
3053
  return null;
2927
3054
  }
3055
+ /**
3056
+ * Builds column nodes for paging CTE
3057
+ * @param primaryKey - Primary key name
3058
+ * @param orderBy - Order by nodes
3059
+ * @param tableAlias - Table alias for columns
3060
+ * @returns Array of column nodes for paging
3061
+ */
2928
3062
  buildPagingColumns(primaryKey, orderBy, tableAlias) {
2929
3063
  const columns = [{ type: "Column", table: tableAlias, name: primaryKey, alias: primaryKey }];
2930
3064
  if (!orderBy) return columns;
@@ -3297,6 +3431,11 @@ var QueryAstService = class {
3297
3431
  combineExpressions(existing, next) {
3298
3432
  return existing ? and(existing, next) : next;
3299
3433
  }
3434
+ /**
3435
+ * Normalizes an ordering term to a standard OrderingTerm
3436
+ * @param term - Column definition or ordering term to normalize
3437
+ * @returns Normalized ordering term
3438
+ */
3300
3439
  normalizeOrderingTerm(term) {
3301
3440
  const from = this.state.ast.from;
3302
3441
  const tableRef2 = from.type === "Table" && from.alias ? { ...this.table, alias: from.alias } : this.table;
@@ -3413,7 +3552,11 @@ var buildBelongsToManyJoins = (root, relationName, relation, joinKind, extra, ro
3413
3552
  { type: "Column", table: relation.pivotTable.name, name: relation.pivotForeignKeyToRoot },
3414
3553
  { type: "Column", table: rootTable, name: rootKey }
3415
3554
  );
3416
- const pivotJoin = createJoinNode(joinKind, relation.pivotTable.name, pivotCondition);
3555
+ const pivotJoin = createJoinNode(
3556
+ joinKind,
3557
+ { type: "Table", name: relation.pivotTable.name, schema: relation.pivotTable.schema },
3558
+ pivotCondition
3559
+ );
3417
3560
  let targetCondition = eq(
3418
3561
  { type: "Column", table: relation.target.name, name: targetKey },
3419
3562
  { type: "Column", table: relation.pivotTable.name, name: relation.pivotForeignKeyToTarget }
@@ -3423,7 +3566,7 @@ var buildBelongsToManyJoins = (root, relationName, relation, joinKind, extra, ro
3423
3566
  }
3424
3567
  const targetJoin = createJoinNode(
3425
3568
  joinKind,
3426
- relation.target.name,
3569
+ { type: "Table", name: relation.target.name, schema: relation.target.schema },
3427
3570
  targetCondition,
3428
3571
  relationName
3429
3572
  );
@@ -3601,7 +3744,12 @@ var RelationService = class {
3601
3744
  return joins.reduce((current, join) => this.astService(current).withJoin(join), state);
3602
3745
  }
3603
3746
  const condition = buildRelationJoinCondition(this.table, relation, extraCondition, rootAlias);
3604
- const joinNode = createJoinNode(joinKind, relation.target.name, condition, relationName);
3747
+ const joinNode = createJoinNode(
3748
+ joinKind,
3749
+ { type: "Table", name: relation.target.name, schema: relation.target.schema },
3750
+ condition,
3751
+ relationName
3752
+ );
3605
3753
  return this.astService(state).withJoin(joinNode);
3606
3754
  }
3607
3755
  /**
@@ -3646,25 +3794,6 @@ var RelationService = class {
3646
3794
  }
3647
3795
  };
3648
3796
 
3649
- // src/query-builder/select-query-builder-deps.ts
3650
- var defaultCreateQueryAstService = (table, state) => new QueryAstService(table, state);
3651
- var defaultCreateHydrationPlanner = (table) => new HydrationPlanner(table);
3652
- var defaultCreateHydration = (table, plannerFactory) => new HydrationManager(table, plannerFactory(table));
3653
- var resolveSelectQueryBuilderDependencies = (overrides = {}) => {
3654
- const createQueryAstService = overrides.createQueryAstService ?? defaultCreateQueryAstService;
3655
- const createHydrationPlanner = overrides.createHydrationPlanner ?? defaultCreateHydrationPlanner;
3656
- const createHydration = overrides.createHydration ?? ((table) => defaultCreateHydration(table, createHydrationPlanner));
3657
- const createRelationService = overrides.createRelationService ?? ((table, state, hydration) => new RelationService(table, state, hydration, createQueryAstService));
3658
- return {
3659
- createState: overrides.createState ?? ((table) => new SelectQueryState(table)),
3660
- createHydration,
3661
- createHydrationPlanner,
3662
- createQueryAstService,
3663
- createRelationService
3664
- };
3665
- };
3666
- var defaultSelectQueryBuilderDependencies = resolveSelectQueryBuilderDependencies();
3667
-
3668
3797
  // src/query-builder/column-selector.ts
3669
3798
  var ColumnSelector = class {
3670
3799
  /**
@@ -3790,6 +3919,29 @@ var RelationManager = class {
3790
3919
  }
3791
3920
  };
3792
3921
 
3922
+ // src/query-builder/select-query-builder-deps.ts
3923
+ var defaultCreateQueryAstService = (table, state) => new QueryAstService(table, state);
3924
+ var defaultCreateHydrationPlanner = (table) => new HydrationPlanner(table);
3925
+ var defaultCreateHydration = (table, plannerFactory) => new HydrationManager(table, plannerFactory(table));
3926
+ var resolveSelectQueryBuilderDependencies = (overrides = {}) => {
3927
+ const createQueryAstService = overrides.createQueryAstService ?? defaultCreateQueryAstService;
3928
+ const createHydrationPlanner = overrides.createHydrationPlanner ?? defaultCreateHydrationPlanner;
3929
+ const createHydration = overrides.createHydration ?? ((table) => defaultCreateHydration(table, createHydrationPlanner));
3930
+ const createRelationService = overrides.createRelationService ?? ((table, state, hydration) => new RelationService(table, state, hydration, createQueryAstService));
3931
+ const createColumnSelector = overrides.createColumnSelector ?? ((env) => new ColumnSelector(env));
3932
+ const createRelationManager = overrides.createRelationManager ?? ((env) => new RelationManager(env));
3933
+ return {
3934
+ createState: overrides.createState ?? ((table) => new SelectQueryState(table)),
3935
+ createHydration,
3936
+ createHydrationPlanner,
3937
+ createQueryAstService,
3938
+ createRelationService,
3939
+ createColumnSelector,
3940
+ createRelationManager
3941
+ };
3942
+ };
3943
+ var defaultSelectQueryBuilderDependencies = resolveSelectQueryBuilderDependencies();
3944
+
3793
3945
  // src/orm/hydration.ts
3794
3946
  var hydrateRows = (rows, plan) => {
3795
3947
  if (!plan || !rows.length) return rows;
@@ -3915,6 +4067,18 @@ var hideInternal = (obj, keys) => {
3915
4067
  }
3916
4068
  };
3917
4069
  var DefaultHasManyCollection = class {
4070
+ /**
4071
+ * Creates a new DefaultHasManyCollection instance.
4072
+ * @param ctx - The entity context
4073
+ * @param meta - The entity metadata
4074
+ * @param root - The root entity
4075
+ * @param relationName - The relation name
4076
+ * @param relation - The relation definition
4077
+ * @param rootTable - The root table definition
4078
+ * @param loader - The loader function for lazy loading
4079
+ * @param createEntity - Function to create entities from rows
4080
+ * @param localKey - The local key for the relation
4081
+ */
3918
4082
  constructor(ctx, meta, root, relationName, relation, rootTable, loader, createEntity, localKey) {
3919
4083
  this.ctx = ctx;
3920
4084
  this.meta = meta;
@@ -3932,6 +4096,10 @@ var DefaultHasManyCollection = class {
3932
4096
  hideInternal(this, ["ctx", "meta", "root", "relationName", "relation", "rootTable", "loader", "createEntity", "localKey"]);
3933
4097
  this.hydrateFromCache();
3934
4098
  }
4099
+ /**
4100
+ * Loads the related entities if not already loaded.
4101
+ * @returns Promise resolving to the array of child entities
4102
+ */
3935
4103
  async load() {
3936
4104
  if (this.loaded) return this.items;
3937
4105
  const map = await this.loader();
@@ -3941,9 +4109,18 @@ var DefaultHasManyCollection = class {
3941
4109
  this.loaded = true;
3942
4110
  return this.items;
3943
4111
  }
4112
+ /**
4113
+ * Gets the current items in the collection.
4114
+ * @returns Array of child entities
4115
+ */
3944
4116
  getItems() {
3945
4117
  return this.items;
3946
4118
  }
4119
+ /**
4120
+ * Adds a new child entity to the collection.
4121
+ * @param data - Partial data for the new entity
4122
+ * @returns The created entity
4123
+ */
3947
4124
  add(data) {
3948
4125
  const keyValue = this.root[this.localKey];
3949
4126
  const childRow = {
@@ -3963,6 +4140,10 @@ var DefaultHasManyCollection = class {
3963
4140
  );
3964
4141
  return entity;
3965
4142
  }
4143
+ /**
4144
+ * Attaches an existing entity to the collection.
4145
+ * @param entity - The entity to attach
4146
+ */
3966
4147
  attach(entity) {
3967
4148
  const keyValue = this.root[this.localKey];
3968
4149
  entity[this.relation.foreignKey] = keyValue;
@@ -3977,6 +4158,10 @@ var DefaultHasManyCollection = class {
3977
4158
  { kind: "attach", entity }
3978
4159
  );
3979
4160
  }
4161
+ /**
4162
+ * Removes an entity from the collection.
4163
+ * @param entity - The entity to remove
4164
+ */
3980
4165
  remove(entity) {
3981
4166
  this.items = this.items.filter((item) => item !== entity);
3982
4167
  this.removed.add(entity);
@@ -3989,6 +4174,9 @@ var DefaultHasManyCollection = class {
3989
4174
  { kind: "remove", entity }
3990
4175
  );
3991
4176
  }
4177
+ /**
4178
+ * Clears all entities from the collection.
4179
+ */
3992
4180
  clear() {
3993
4181
  for (const entity of [...this.items]) {
3994
4182
  this.remove(entity);
@@ -4005,6 +4193,10 @@ var DefaultHasManyCollection = class {
4005
4193
  this.items = rows.map((row) => this.createEntity(row));
4006
4194
  this.loaded = true;
4007
4195
  }
4196
+ /**
4197
+ * Returns the items for JSON serialization.
4198
+ * @returns Array of child entities
4199
+ */
4008
4200
  toJSON() {
4009
4201
  return this.items;
4010
4202
  }
@@ -4380,112 +4572,92 @@ var executeQuery = async (ctx, qb) => {
4380
4572
  return rowsFromResults(results);
4381
4573
  };
4382
4574
  var toKey6 = (value) => value === null || value === void 0 ? "" : String(value);
4383
- var loadHasManyRelation = async (ctx, rootTable, _relationName, relation) => {
4384
- const localKey = relation.localKey || findPrimaryKey(rootTable);
4385
- const roots = ctx.getEntitiesForTable(rootTable);
4386
- const keys = /* @__PURE__ */ new Set();
4575
+ var collectKeysFromRoots = (roots, key) => {
4576
+ const collected = /* @__PURE__ */ new Set();
4387
4577
  for (const tracked of roots) {
4388
- const value = tracked.entity[localKey];
4578
+ const value = tracked.entity[key];
4389
4579
  if (value !== null && value !== void 0) {
4390
- keys.add(value);
4580
+ collected.add(value);
4391
4581
  }
4392
4582
  }
4393
- if (!keys.size) {
4394
- return /* @__PURE__ */ new Map();
4395
- }
4396
- const selectMap = selectAllColumns(relation.target);
4397
- const fb = new SelectQueryBuilder(relation.target).select(selectMap);
4398
- const fkColumn = relation.target.columns[relation.foreignKey];
4399
- if (!fkColumn) return /* @__PURE__ */ new Map();
4400
- fb.where(inList(fkColumn, Array.from(keys)));
4401
- const rows = await executeQuery(ctx, fb);
4583
+ return collected;
4584
+ };
4585
+ var buildInListValues = (keys) => Array.from(keys);
4586
+ var fetchRowsForKeys = async (ctx, table, column, keys) => {
4587
+ const qb = new SelectQueryBuilder(table).select(selectAllColumns(table));
4588
+ qb.where(inList(column, buildInListValues(keys)));
4589
+ return executeQuery(ctx, qb);
4590
+ };
4591
+ var groupRowsByMany = (rows, keyColumn) => {
4402
4592
  const grouped = /* @__PURE__ */ new Map();
4403
4593
  for (const row of rows) {
4404
- const fkValue = row[relation.foreignKey];
4405
- if (fkValue === null || fkValue === void 0) continue;
4406
- const key = toKey6(fkValue);
4594
+ const value = row[keyColumn];
4595
+ if (value === null || value === void 0) continue;
4596
+ const key = toKey6(value);
4407
4597
  const bucket = grouped.get(key) ?? [];
4408
4598
  bucket.push(row);
4409
4599
  grouped.set(key, bucket);
4410
4600
  }
4411
4601
  return grouped;
4412
4602
  };
4413
- var loadHasOneRelation = async (ctx, rootTable, _relationName, relation) => {
4414
- const localKey = relation.localKey || findPrimaryKey(rootTable);
4415
- const roots = ctx.getEntitiesForTable(rootTable);
4416
- const keys = /* @__PURE__ */ new Set();
4417
- for (const tracked of roots) {
4418
- const value = tracked.entity[localKey];
4419
- if (value !== null && value !== void 0) {
4420
- keys.add(value);
4603
+ var groupRowsByUnique = (rows, keyColumn) => {
4604
+ const lookup = /* @__PURE__ */ new Map();
4605
+ for (const row of rows) {
4606
+ const value = row[keyColumn];
4607
+ if (value === null || value === void 0) continue;
4608
+ const key = toKey6(value);
4609
+ if (!lookup.has(key)) {
4610
+ lookup.set(key, row);
4421
4611
  }
4422
4612
  }
4613
+ return lookup;
4614
+ };
4615
+ var loadHasManyRelation = async (ctx, rootTable, _relationName, relation) => {
4616
+ const localKey = relation.localKey || findPrimaryKey(rootTable);
4617
+ const roots = ctx.getEntitiesForTable(rootTable);
4618
+ const keys = collectKeysFromRoots(roots, localKey);
4423
4619
  if (!keys.size) {
4424
4620
  return /* @__PURE__ */ new Map();
4425
4621
  }
4426
- const selectMap = selectAllColumns(relation.target);
4427
- const qb = new SelectQueryBuilder(relation.target).select(selectMap);
4428
4622
  const fkColumn = relation.target.columns[relation.foreignKey];
4429
4623
  if (!fkColumn) return /* @__PURE__ */ new Map();
4430
- qb.where(inList(fkColumn, Array.from(keys)));
4431
- const rows = await executeQuery(ctx, qb);
4432
- const lookup = /* @__PURE__ */ new Map();
4433
- for (const row of rows) {
4434
- const fkValue = row[relation.foreignKey];
4435
- if (fkValue === null || fkValue === void 0) continue;
4436
- const key = toKey6(fkValue);
4437
- if (!lookup.has(key)) {
4438
- lookup.set(key, row);
4439
- }
4624
+ const rows = await fetchRowsForKeys(ctx, relation.target, fkColumn, keys);
4625
+ return groupRowsByMany(rows, relation.foreignKey);
4626
+ };
4627
+ var loadHasOneRelation = async (ctx, rootTable, _relationName, relation) => {
4628
+ const localKey = relation.localKey || findPrimaryKey(rootTable);
4629
+ const roots = ctx.getEntitiesForTable(rootTable);
4630
+ const keys = collectKeysFromRoots(roots, localKey);
4631
+ if (!keys.size) {
4632
+ return /* @__PURE__ */ new Map();
4440
4633
  }
4441
- return lookup;
4634
+ const fkColumn = relation.target.columns[relation.foreignKey];
4635
+ if (!fkColumn) return /* @__PURE__ */ new Map();
4636
+ const rows = await fetchRowsForKeys(ctx, relation.target, fkColumn, keys);
4637
+ return groupRowsByUnique(rows, relation.foreignKey);
4442
4638
  };
4443
4639
  var loadBelongsToRelation = async (ctx, rootTable, _relationName, relation) => {
4444
4640
  const roots = ctx.getEntitiesForTable(rootTable);
4445
- const foreignKeys = /* @__PURE__ */ new Set();
4446
- for (const tracked of roots) {
4447
- const value = tracked.entity[relation.foreignKey];
4448
- if (value !== null && value !== void 0) {
4449
- foreignKeys.add(value);
4450
- }
4451
- }
4641
+ const foreignKeys = collectKeysFromRoots(roots, relation.foreignKey);
4452
4642
  if (!foreignKeys.size) {
4453
4643
  return /* @__PURE__ */ new Map();
4454
4644
  }
4455
- const selectMap = selectAllColumns(relation.target);
4456
- const qb = new SelectQueryBuilder(relation.target).select(selectMap);
4457
4645
  const targetKey = relation.localKey || findPrimaryKey(relation.target);
4458
4646
  const pkColumn = relation.target.columns[targetKey];
4459
4647
  if (!pkColumn) return /* @__PURE__ */ new Map();
4460
- qb.where(inList(pkColumn, Array.from(foreignKeys)));
4461
- const rows = await executeQuery(ctx, qb);
4462
- const map = /* @__PURE__ */ new Map();
4463
- for (const row of rows) {
4464
- const keyValue = row[targetKey];
4465
- if (keyValue === null || keyValue === void 0) continue;
4466
- map.set(toKey6(keyValue), row);
4467
- }
4468
- return map;
4648
+ const rows = await fetchRowsForKeys(ctx, relation.target, pkColumn, foreignKeys);
4649
+ return groupRowsByUnique(rows, targetKey);
4469
4650
  };
4470
4651
  var loadBelongsToManyRelation = async (ctx, rootTable, _relationName, relation) => {
4471
4652
  const rootKey = relation.localKey || findPrimaryKey(rootTable);
4472
4653
  const roots = ctx.getEntitiesForTable(rootTable);
4473
- const rootIds = /* @__PURE__ */ new Set();
4474
- for (const tracked of roots) {
4475
- const value = tracked.entity[rootKey];
4476
- if (value !== null && value !== void 0) {
4477
- rootIds.add(value);
4478
- }
4479
- }
4654
+ const rootIds = collectKeysFromRoots(roots, rootKey);
4480
4655
  if (!rootIds.size) {
4481
4656
  return /* @__PURE__ */ new Map();
4482
4657
  }
4483
- const pivotSelect = selectAllColumns(relation.pivotTable);
4484
- const pivotQb = new SelectQueryBuilder(relation.pivotTable).select(pivotSelect);
4485
- const pivotFkCol = relation.pivotTable.columns[relation.pivotForeignKeyToRoot];
4486
- if (!pivotFkCol) return /* @__PURE__ */ new Map();
4487
- pivotQb.where(inList(pivotFkCol, Array.from(rootIds)));
4488
- const pivotRows = await executeQuery(ctx, pivotQb);
4658
+ const pivotColumn = relation.pivotTable.columns[relation.pivotForeignKeyToRoot];
4659
+ if (!pivotColumn) return /* @__PURE__ */ new Map();
4660
+ const pivotRows = await fetchRowsForKeys(ctx, relation.pivotTable, pivotColumn, rootIds);
4489
4661
  const rootLookup = /* @__PURE__ */ new Map();
4490
4662
  const targetIds = /* @__PURE__ */ new Set();
4491
4663
  for (const pivot of pivotRows) {
@@ -4505,19 +4677,11 @@ var loadBelongsToManyRelation = async (ctx, rootTable, _relationName, relation)
4505
4677
  if (!targetIds.size) {
4506
4678
  return /* @__PURE__ */ new Map();
4507
4679
  }
4508
- const targetSelect = selectAllColumns(relation.target);
4509
4680
  const targetKey = relation.targetKey || findPrimaryKey(relation.target);
4510
4681
  const targetPkColumn = relation.target.columns[targetKey];
4511
4682
  if (!targetPkColumn) return /* @__PURE__ */ new Map();
4512
- const targetQb = new SelectQueryBuilder(relation.target).select(targetSelect);
4513
- targetQb.where(inList(targetPkColumn, Array.from(targetIds)));
4514
- const targetRows = await executeQuery(ctx, targetQb);
4515
- const targetMap = /* @__PURE__ */ new Map();
4516
- for (const row of targetRows) {
4517
- const pkValue = row[targetKey];
4518
- if (pkValue === null || pkValue === void 0) continue;
4519
- targetMap.set(toKey6(pkValue), row);
4520
- }
4683
+ const targetRows = await fetchRowsForKeys(ctx, relation.target, targetPkColumn, targetIds);
4684
+ const targetMap = groupRowsByUnique(targetRows, targetKey);
4521
4685
  const result = /* @__PURE__ */ new Map();
4522
4686
  for (const [rootId, entries] of rootLookup.entries()) {
4523
4687
  const bucket = [];
@@ -4794,21 +4958,21 @@ async function executeHydratedWithContexts(_execCtx, hydCtx, qb) {
4794
4958
  return executeWithEntityContext(entityCtx, qb);
4795
4959
  }
4796
4960
 
4961
+ // src/query-builder/query-resolution.ts
4962
+ function resolveSelectQuery(query) {
4963
+ const candidate = query;
4964
+ return typeof candidate.getAST === "function" && candidate.getAST ? candidate.getAST() : query;
4965
+ }
4966
+
4797
4967
  // src/query-builder/select.ts
4798
4968
  var SelectQueryBuilder = class _SelectQueryBuilder {
4799
4969
  /**
4800
-
4801
- * Creates a new SelectQueryBuilder instance
4802
-
4803
- * @param table - Table definition to query
4804
-
4805
- * @param state - Optional initial query state
4806
-
4807
- * @param hydration - Optional hydration manager
4808
-
4809
- * @param dependencies - Optional query builder dependencies
4810
-
4811
- */
4970
+ * Creates a new SelectQueryBuilder instance
4971
+ * @param table - Table definition to query
4972
+ * @param state - Optional initial query state
4973
+ * @param hydration - Optional hydration manager
4974
+ * @param dependencies - Optional query builder dependencies
4975
+ */
4812
4976
  constructor(table, state, hydration, dependencies, lazyRelations) {
4813
4977
  const deps = resolveSelectQueryBuilderDependencies(dependencies);
4814
4978
  this.env = { table, deps };
@@ -4819,9 +4983,15 @@ var SelectQueryBuilder = class _SelectQueryBuilder {
4819
4983
  hydration: initialHydration
4820
4984
  };
4821
4985
  this.lazyRelations = new Set(lazyRelations ?? []);
4822
- this.columnSelector = new ColumnSelector(this.env);
4823
- this.relationManager = new RelationManager(this.env);
4986
+ this.columnSelector = deps.createColumnSelector(this.env);
4987
+ this.relationManager = deps.createRelationManager(this.env);
4824
4988
  }
4989
+ /**
4990
+ * Creates a new SelectQueryBuilder instance with updated context and lazy relations
4991
+ * @param context - Updated query context
4992
+ * @param lazyRelations - Updated lazy relations set
4993
+ * @returns New SelectQueryBuilder instance
4994
+ */
4825
4995
  clone(context = this.context, lazyRelations = new Set(this.lazyRelations)) {
4826
4996
  return new _SelectQueryBuilder(this.env.table, context.state, context.hydration, this.env.deps, lazyRelations);
4827
4997
  }
@@ -4838,10 +5008,12 @@ var SelectQueryBuilder = class _SelectQueryBuilder {
4838
5008
  const nextContext = this.applyAst(this.context, (service) => service.withFrom(nextFrom));
4839
5009
  return this.clone(nextContext);
4840
5010
  }
4841
- resolveQueryNode(query) {
4842
- const candidate = query;
4843
- return typeof candidate.getAST === "function" && candidate.getAST ? candidate.getAST() : query;
4844
- }
5011
+ /**
5012
+ * Applies correlation expression to the query AST
5013
+ * @param ast - Query AST to modify
5014
+ * @param correlation - Correlation expression
5015
+ * @returns Modified AST with correlation applied
5016
+ */
4845
5017
  applyCorrelation(ast, correlation) {
4846
5018
  if (!correlation) return ast;
4847
5019
  const combinedWhere = ast.where ? and(correlation, ast.where) : correlation;
@@ -4850,39 +5022,53 @@ var SelectQueryBuilder = class _SelectQueryBuilder {
4850
5022
  where: combinedWhere
4851
5023
  };
4852
5024
  }
5025
+ /**
5026
+ * Creates a new child query builder for a related table
5027
+ * @param table - Table definition for the child builder
5028
+ * @returns New SelectQueryBuilder instance for the child table
5029
+ */
4853
5030
  createChildBuilder(table) {
4854
5031
  return new _SelectQueryBuilder(table, void 0, void 0, this.env.deps);
4855
5032
  }
5033
+ /**
5034
+ * Applies an AST mutation using the query AST service
5035
+ * @param context - Current query context
5036
+ * @param mutator - Function that mutates the AST
5037
+ * @returns Updated query context
5038
+ */
4856
5039
  applyAst(context, mutator) {
4857
5040
  const astService = this.env.deps.createQueryAstService(this.env.table, context.state);
4858
5041
  const nextState = mutator(astService);
4859
5042
  return { state: nextState, hydration: context.hydration };
4860
5043
  }
5044
+ /**
5045
+ * Applies a join to the query context
5046
+ * @param context - Current query context
5047
+ * @param table - Table to join
5048
+ * @param condition - Join condition
5049
+ * @param kind - Join kind
5050
+ * @returns Updated query context with join applied
5051
+ */
4861
5052
  applyJoin(context, table, condition, kind) {
4862
- const joinNode = createJoinNode(kind, table.name, condition);
5053
+ const joinNode = createJoinNode(kind, { type: "Table", name: table.name, schema: table.schema }, condition);
4863
5054
  return this.applyAst(context, (service) => service.withJoin(joinNode));
4864
5055
  }
5056
+ /**
5057
+ * Applies a set operation to the query
5058
+ * @param operator - Set operation kind
5059
+ * @param query - Query to combine with
5060
+ * @returns Updated query context with set operation
5061
+ */
4865
5062
  applySetOperation(operator, query) {
4866
- const subAst = this.resolveQueryNode(query);
5063
+ const subAst = resolveSelectQuery(query);
4867
5064
  return this.applyAst(this.context, (service) => service.withSetOperation(operator, subAst));
4868
5065
  }
4869
- /**
4870
-
4871
- * Selects specific columns for the query
4872
-
4873
- * @param columns - Record of column definitions, function nodes, case expressions, or window functions
4874
-
4875
- * @returns New query builder instance with selected columns
4876
-
4877
- */
4878
- select(columns) {
4879
- return this.clone(this.columnSelector.select(this.context, columns));
4880
- }
4881
- /**
4882
- * Selects columns from the root table by name (typed).
4883
- * @param cols - Column names on the root table
4884
- */
4885
- selectColumns(...cols) {
5066
+ select(...args) {
5067
+ if (args.length === 1 && typeof args[0] === "object" && args[0] !== null && typeof args[0] !== "string") {
5068
+ const columns = args[0];
5069
+ return this.clone(this.columnSelector.select(this.context, columns));
5070
+ }
5071
+ const cols = args;
4886
5072
  const selection = {};
4887
5073
  for (const key of cols) {
4888
5074
  const col2 = this.env.table.columns[key];
@@ -4891,53 +5077,37 @@ var SelectQueryBuilder = class _SelectQueryBuilder {
4891
5077
  }
4892
5078
  selection[key] = col2;
4893
5079
  }
4894
- return this.select(selection);
5080
+ return this.clone(this.columnSelector.select(this.context, selection));
4895
5081
  }
4896
5082
  /**
4897
-
4898
- * Selects raw column expressions
4899
-
4900
- * @param cols - Column expressions as strings
4901
-
4902
- * @returns New query builder instance with raw column selections
4903
-
4904
- */
5083
+ * Selects raw column expressions
5084
+ * @param cols - Column expressions as strings
5085
+ * @returns New query builder instance with raw column selections
5086
+ */
4905
5087
  selectRaw(...cols) {
4906
5088
  return this.clone(this.columnSelector.selectRaw(this.context, cols));
4907
5089
  }
4908
5090
  /**
4909
-
4910
- * Adds a Common Table Expression (CTE) to the query
4911
-
4912
- * @param name - Name of the CTE
4913
-
4914
- * @param query - Query builder or query node for the CTE
4915
-
4916
- * @param columns - Optional column names for the CTE
4917
-
4918
- * @returns New query builder instance with the CTE
4919
-
4920
- */
5091
+ * Adds a Common Table Expression (CTE) to the query
5092
+ * @param name - Name of the CTE
5093
+ * @param query - Query builder or query node for the CTE
5094
+ * @param columns - Optional column names for the CTE
5095
+ * @returns New query builder instance with the CTE
5096
+ */
4921
5097
  with(name, query, columns) {
4922
- const subAst = this.resolveQueryNode(query);
5098
+ const subAst = resolveSelectQuery(query);
4923
5099
  const nextContext = this.applyAst(this.context, (service) => service.withCte(name, subAst, columns, false));
4924
5100
  return this.clone(nextContext);
4925
5101
  }
4926
5102
  /**
4927
-
4928
- * Adds a recursive Common Table Expression (CTE) to the query
4929
-
4930
- * @param name - Name of the CTE
4931
-
4932
- * @param query - Query builder or query node for the CTE
4933
-
4934
- * @param columns - Optional column names for the CTE
4935
-
4936
- * @returns New query builder instance with the recursive CTE
4937
-
4938
- */
5103
+ * Adds a recursive Common Table Expression (CTE) to the query
5104
+ * @param name - Name of the CTE
5105
+ * @param query - Query builder or query node for the CTE
5106
+ * @param columns - Optional column names for the CTE
5107
+ * @returns New query builder instance with the recursive CTE
5108
+ */
4939
5109
  withRecursive(name, query, columns) {
4940
- const subAst = this.resolveQueryNode(query);
5110
+ const subAst = resolveSelectQuery(query);
4941
5111
  const nextContext = this.applyAst(this.context, (service) => service.withCte(name, subAst, columns, true));
4942
5112
  return this.clone(nextContext);
4943
5113
  }
@@ -4949,24 +5119,31 @@ var SelectQueryBuilder = class _SelectQueryBuilder {
4949
5119
  * @returns New query builder instance with updated FROM
4950
5120
  */
4951
5121
  fromSubquery(subquery, alias, columnAliases) {
4952
- const subAst = this.resolveQueryNode(subquery);
5122
+ const subAst = resolveSelectQuery(subquery);
4953
5123
  const fromNode = derivedTable(subAst, alias, columnAliases);
4954
5124
  const nextContext = this.applyAst(this.context, (service) => service.withFrom(fromNode));
4955
5125
  return this.clone(nextContext);
4956
5126
  }
4957
5127
  /**
4958
-
4959
- * Selects a subquery as a column
4960
-
4961
- * @param alias - Alias for the subquery column
4962
-
4963
- * @param sub - Query builder or query node for the subquery
4964
-
4965
- * @returns New query builder instance with the subquery selection
4966
-
4967
- */
5128
+ * Replaces the FROM clause with a function table expression.
5129
+ * @param name - Function name
5130
+ * @param args - Optional function arguments
5131
+ * @param alias - Optional alias for the function table
5132
+ * @param options - Optional function-table metadata (lateral, ordinality, column aliases, schema)
5133
+ */
5134
+ fromFunctionTable(name, args = [], alias, options) {
5135
+ const functionTable = fnTable(name, args, alias, options);
5136
+ const nextContext = this.applyAst(this.context, (service) => service.withFrom(functionTable));
5137
+ return this.clone(nextContext);
5138
+ }
5139
+ /**
5140
+ * Selects a subquery as a column
5141
+ * @param alias - Alias for the subquery column
5142
+ * @param sub - Query builder or query node for the subquery
5143
+ * @returns New query builder instance with the subquery selection
5144
+ */
4968
5145
  selectSubquery(alias, sub2) {
4969
- const query = this.resolveQueryNode(sub2);
5146
+ const query = resolveSelectQuery(sub2);
4970
5147
  return this.clone(this.columnSelector.selectSubquery(this.context, alias, query));
4971
5148
  }
4972
5149
  /**
@@ -4979,103 +5156,92 @@ var SelectQueryBuilder = class _SelectQueryBuilder {
4979
5156
  * @returns New query builder instance with the derived-table join
4980
5157
  */
4981
5158
  joinSubquery(subquery, alias, condition, joinKind = JOIN_KINDS.INNER, columnAliases) {
4982
- const subAst = this.resolveQueryNode(subquery);
5159
+ const subAst = resolveSelectQuery(subquery);
4983
5160
  const joinNode = createJoinNode(joinKind, derivedTable(subAst, alias, columnAliases), condition);
4984
5161
  const nextContext = this.applyAst(this.context, (service) => service.withJoin(joinNode));
4985
5162
  return this.clone(nextContext);
4986
5163
  }
4987
5164
  /**
4988
-
4989
- * Adds an INNER JOIN to the query
4990
-
4991
- * @param table - Table to join
4992
-
4993
- * @param condition - Join condition expression
4994
-
4995
- * @returns New query builder instance with the INNER JOIN
4996
-
4997
- */
5165
+ * Adds a join against a function table (e.g., `generate_series`) using `fnTable` internally.
5166
+ * @param name - Function name
5167
+ * @param args - Optional arguments passed to the function
5168
+ * @param alias - Alias for the function table so columns can be referenced
5169
+ * @param condition - Join condition expression
5170
+ * @param joinKind - Kind of join (defaults to INNER)
5171
+ * @param options - Optional metadata (lateral, ordinality, column aliases, schema)
5172
+ */
5173
+ joinFunctionTable(name, args = [], alias, condition, joinKind = JOIN_KINDS.INNER, options) {
5174
+ const functionTable = fnTable(name, args, alias, options);
5175
+ const joinNode = createJoinNode(joinKind, functionTable, condition);
5176
+ const nextContext = this.applyAst(this.context, (service) => service.withJoin(joinNode));
5177
+ return this.clone(nextContext);
5178
+ }
5179
+ /**
5180
+ * Adds an INNER JOIN to the query
5181
+ * @param table - Table to join
5182
+ * @param condition - Join condition expression
5183
+ * @returns New query builder instance with the INNER JOIN
5184
+ */
4998
5185
  innerJoin(table, condition) {
4999
5186
  const nextContext = this.applyJoin(this.context, table, condition, JOIN_KINDS.INNER);
5000
5187
  return this.clone(nextContext);
5001
5188
  }
5002
5189
  /**
5003
-
5004
- * Adds a LEFT JOIN to the query
5005
-
5006
- * @param table - Table to join
5007
-
5008
- * @param condition - Join condition expression
5009
-
5010
- * @returns New query builder instance with the LEFT JOIN
5011
-
5012
- */
5190
+ * Adds a LEFT JOIN to the query
5191
+ * @param table - Table to join
5192
+ * @param condition - Join condition expression
5193
+ * @returns New query builder instance with the LEFT JOIN
5194
+ */
5013
5195
  leftJoin(table, condition) {
5014
5196
  const nextContext = this.applyJoin(this.context, table, condition, JOIN_KINDS.LEFT);
5015
5197
  return this.clone(nextContext);
5016
5198
  }
5017
5199
  /**
5018
-
5019
- * Adds a RIGHT JOIN to the query
5020
-
5021
- * @param table - Table to join
5022
-
5023
- * @param condition - Join condition expression
5024
-
5025
- * @returns New query builder instance with the RIGHT JOIN
5026
-
5027
- */
5200
+ * Adds a RIGHT JOIN to the query
5201
+ * @param table - Table to join
5202
+ * @param condition - Join condition expression
5203
+ * @returns New query builder instance with the RIGHT JOIN
5204
+ */
5028
5205
  rightJoin(table, condition) {
5029
5206
  const nextContext = this.applyJoin(this.context, table, condition, JOIN_KINDS.RIGHT);
5030
5207
  return this.clone(nextContext);
5031
5208
  }
5032
5209
  /**
5033
-
5034
- * Matches records based on a relationship
5035
-
5036
- * @param relationName - Name of the relationship to match
5037
-
5038
- * @param predicate - Optional predicate expression
5039
-
5040
- * @returns New query builder instance with the relationship match
5041
-
5042
- */
5210
+ * Matches records based on a relationship
5211
+ * @param relationName - Name of the relationship to match
5212
+ * @param predicate - Optional predicate expression
5213
+ * @returns New query builder instance with the relationship match
5214
+ */
5043
5215
  match(relationName, predicate) {
5044
5216
  const nextContext = this.relationManager.match(this.context, relationName, predicate);
5045
5217
  return this.clone(nextContext);
5046
5218
  }
5047
5219
  /**
5048
-
5049
- * Joins a related table
5050
-
5051
- * @param relationName - Name of the relationship to join
5052
-
5053
- * @param joinKind - Type of join (defaults to INNER)
5054
-
5055
- * @param extraCondition - Optional additional join condition
5056
-
5057
- * @returns New query builder instance with the relationship join
5058
-
5059
- */
5220
+ * Joins a related table
5221
+ * @param relationName - Name of the relationship to join
5222
+ * @param joinKind - Type of join (defaults to INNER)
5223
+ * @param extraCondition - Optional additional join condition
5224
+ * @returns New query builder instance with the relationship join
5225
+ */
5060
5226
  joinRelation(relationName, joinKind = JOIN_KINDS.INNER, extraCondition) {
5061
5227
  const nextContext = this.relationManager.joinRelation(this.context, relationName, joinKind, extraCondition);
5062
5228
  return this.clone(nextContext);
5063
5229
  }
5064
5230
  /**
5065
-
5066
- * Includes related data in the query results
5067
-
5068
- * @param relationName - Name of the relationship to include
5069
-
5070
- * @param options - Optional include options
5071
-
5072
- * @returns New query builder instance with the relationship inclusion
5073
-
5074
- */
5231
+ * Includes related data in the query results
5232
+ * @param relationName - Name of the relationship to include
5233
+ * @param options - Optional include options
5234
+ * @returns New query builder instance with the relationship inclusion
5235
+ */
5075
5236
  include(relationName, options) {
5076
5237
  const nextContext = this.relationManager.include(this.context, relationName, options);
5077
5238
  return this.clone(nextContext);
5078
5239
  }
5240
+ /**
5241
+ * Includes a relation lazily in the query results
5242
+ * @param relationName - Name of the relation to include lazily
5243
+ * @returns New query builder instance with lazy relation inclusion
5244
+ */
5079
5245
  includeLazy(relationName) {
5080
5246
  const nextLazy = new Set(this.lazyRelations);
5081
5247
  nextLazy.add(relationName);
@@ -5106,43 +5272,57 @@ var SelectQueryBuilder = class _SelectQueryBuilder {
5106
5272
  return this.selectRelationColumns(relationName, ...cols);
5107
5273
  }
5108
5274
  /**
5109
- * Selects columns for the root table and relations from a single config object.
5275
+ * Selects columns for the root table and relations from an array of entries
5276
+ * @param config - Configuration array for deep column selection
5277
+ * @returns New query builder instance with deep column selections
5110
5278
  */
5111
5279
  selectColumnsDeep(config) {
5112
5280
  let currBuilder = this;
5113
- if (config.root?.length) {
5114
- currBuilder = currBuilder.selectColumns(...config.root);
5115
- }
5116
- for (const key of Object.keys(config)) {
5117
- if (key === "root") continue;
5118
- const relName = key;
5119
- const cols = config[relName];
5120
- if (!cols || !cols.length) continue;
5121
- currBuilder = currBuilder.selectRelationColumns(relName, ...cols);
5281
+ for (const entry of config) {
5282
+ if (entry.type === "root") {
5283
+ currBuilder = currBuilder.select(...entry.columns);
5284
+ } else {
5285
+ currBuilder = currBuilder.selectRelationColumns(entry.relationName, ...entry.columns);
5286
+ }
5122
5287
  }
5123
5288
  return currBuilder;
5124
5289
  }
5290
+ /**
5291
+ * Gets the list of lazy relations
5292
+ * @returns Array of lazy relation names
5293
+ */
5125
5294
  getLazyRelations() {
5126
5295
  return Array.from(this.lazyRelations);
5127
5296
  }
5297
+ /**
5298
+ * Gets the table definition for this query builder
5299
+ * @returns Table definition
5300
+ */
5128
5301
  getTable() {
5129
5302
  return this.env.table;
5130
5303
  }
5304
+ /**
5305
+ * Executes the query and returns hydrated results
5306
+ * @param ctx - ORM session context
5307
+ * @returns Promise of entity instances
5308
+ */
5131
5309
  async execute(ctx) {
5132
5310
  return executeHydrated(ctx, this);
5133
5311
  }
5312
+ /**
5313
+ * Executes the query with provided execution and hydration contexts
5314
+ * @param execCtx - Execution context
5315
+ * @param hydCtx - Hydration context
5316
+ * @returns Promise of entity instances
5317
+ */
5134
5318
  async executeWithContexts(execCtx, hydCtx) {
5135
5319
  return executeHydratedWithContexts(execCtx, hydCtx, this);
5136
5320
  }
5137
5321
  /**
5138
-
5139
- * Adds a WHERE condition to the query
5140
-
5141
- * @param expr - Expression for the WHERE clause
5142
-
5143
- * @returns New query builder instance with the WHERE condition
5144
-
5145
- */
5322
+ * Adds a WHERE condition to the query
5323
+ * @param expr - Expression for the WHERE clause
5324
+ * @returns New query builder instance with the WHERE condition
5325
+ */
5146
5326
  where(expr) {
5147
5327
  const nextContext = this.applyAst(this.context, (service) => service.withWhere(expr));
5148
5328
  return this.clone(nextContext);
@@ -5157,14 +5337,10 @@ var SelectQueryBuilder = class _SelectQueryBuilder {
5157
5337
  return this.clone(nextContext);
5158
5338
  }
5159
5339
  /**
5160
-
5161
- * Adds a HAVING condition to the query
5162
-
5163
- * @param expr - Expression for the HAVING clause
5164
-
5165
- * @returns New query builder instance with the HAVING condition
5166
-
5167
- */
5340
+ * Adds a HAVING condition to the query
5341
+ * @param expr - Expression for the HAVING clause
5342
+ * @returns New query builder instance with the HAVING condition
5343
+ */
5168
5344
  having(expr) {
5169
5345
  const nextContext = this.applyAst(this.context, (service) => service.withHaving(expr));
5170
5346
  return this.clone(nextContext);
@@ -5185,130 +5361,89 @@ var SelectQueryBuilder = class _SelectQueryBuilder {
5185
5361
  return this.clone(nextContext);
5186
5362
  }
5187
5363
  /**
5188
-
5189
- * Adds a DISTINCT clause to the query
5190
-
5191
- * @param cols - Columns to make distinct
5192
-
5193
- * @returns New query builder instance with the DISTINCT clause
5194
-
5195
- */
5364
+ * Adds a DISTINCT clause to the query
5365
+ * @param cols - Columns to make distinct
5366
+ * @returns New query builder instance with the DISTINCT clause
5367
+ */
5196
5368
  distinct(...cols) {
5197
5369
  return this.clone(this.columnSelector.distinct(this.context, cols));
5198
5370
  }
5199
5371
  /**
5200
-
5201
- * Adds a LIMIT clause to the query
5202
-
5203
- * @param n - Maximum number of rows to return
5204
-
5205
- * @returns New query builder instance with the LIMIT clause
5206
-
5207
- */
5372
+ * Adds a LIMIT clause to the query
5373
+ * @param n - Maximum number of rows to return
5374
+ * @returns New query builder instance with the LIMIT clause
5375
+ */
5208
5376
  limit(n) {
5209
5377
  const nextContext = this.applyAst(this.context, (service) => service.withLimit(n));
5210
5378
  return this.clone(nextContext);
5211
5379
  }
5212
5380
  /**
5213
-
5214
- * Adds an OFFSET clause to the query
5215
-
5216
- * @param n - Number of rows to skip
5217
-
5218
- * @returns New query builder instance with the OFFSET clause
5219
-
5220
- */
5381
+ * Adds an OFFSET clause to the query
5382
+ * @param n - Number of rows to skip
5383
+ * @returns New query builder instance with the OFFSET clause
5384
+ */
5221
5385
  offset(n) {
5222
5386
  const nextContext = this.applyAst(this.context, (service) => service.withOffset(n));
5223
5387
  return this.clone(nextContext);
5224
5388
  }
5225
5389
  /**
5226
-
5227
- * Combines this query with another using UNION
5228
-
5229
- * @param query - Query to union with
5230
-
5231
- * @returns New query builder instance with the set operation
5232
-
5233
- */
5390
+ * Combines this query with another using UNION
5391
+ * @param query - Query to union with
5392
+ * @returns New query builder instance with the set operation
5393
+ */
5234
5394
  union(query) {
5235
5395
  return this.clone(this.applySetOperation("UNION", query));
5236
5396
  }
5237
5397
  /**
5238
-
5239
- * Combines this query with another using UNION ALL
5240
-
5241
- * @param query - Query to union with
5242
-
5243
- * @returns New query builder instance with the set operation
5244
-
5245
- */
5398
+ * Combines this query with another using UNION ALL
5399
+ * @param query - Query to union with
5400
+ * @returns New query builder instance with the set operation
5401
+ */
5246
5402
  unionAll(query) {
5247
5403
  return this.clone(this.applySetOperation("UNION ALL", query));
5248
5404
  }
5249
5405
  /**
5250
-
5251
- * Combines this query with another using INTERSECT
5252
-
5253
- * @param query - Query to intersect with
5254
-
5255
- * @returns New query builder instance with the set operation
5256
-
5257
- */
5406
+ * Combines this query with another using INTERSECT
5407
+ * @param query - Query to intersect with
5408
+ * @returns New query builder instance with the set operation
5409
+ */
5258
5410
  intersect(query) {
5259
5411
  return this.clone(this.applySetOperation("INTERSECT", query));
5260
5412
  }
5261
5413
  /**
5262
-
5263
- * Combines this query with another using EXCEPT
5264
-
5265
- * @param query - Query to subtract
5266
-
5267
- * @returns New query builder instance with the set operation
5268
-
5269
- */
5414
+ * Combines this query with another using EXCEPT
5415
+ * @param query - Query to subtract
5416
+ * @returns New query builder instance with the set operation
5417
+ */
5270
5418
  except(query) {
5271
5419
  return this.clone(this.applySetOperation("EXCEPT", query));
5272
5420
  }
5273
5421
  /**
5274
-
5275
- * Adds a WHERE EXISTS condition to the query
5276
-
5277
- * @param subquery - Subquery to check for existence
5278
-
5279
- * @returns New query builder instance with the WHERE EXISTS condition
5280
-
5281
- */
5422
+ * Adds a WHERE EXISTS condition to the query
5423
+ * @param subquery - Subquery to check for existence
5424
+ * @returns New query builder instance with the WHERE EXISTS condition
5425
+ */
5282
5426
  whereExists(subquery, correlate) {
5283
- const subAst = this.resolveQueryNode(subquery);
5427
+ const subAst = resolveSelectQuery(subquery);
5284
5428
  const correlated = this.applyCorrelation(subAst, correlate);
5285
5429
  return this.where(exists(correlated));
5286
5430
  }
5287
5431
  /**
5288
-
5289
- * Adds a WHERE NOT EXISTS condition to the query
5290
-
5291
- * @param subquery - Subquery to check for non-existence
5292
-
5293
- * @returns New query builder instance with the WHERE NOT EXISTS condition
5294
-
5295
- */
5432
+ * Adds a WHERE NOT EXISTS condition to the query
5433
+ * @param subquery - Subquery to check for non-existence
5434
+ * @returns New query builder instance with the WHERE NOT EXISTS condition
5435
+ */
5296
5436
  whereNotExists(subquery, correlate) {
5297
- const subAst = this.resolveQueryNode(subquery);
5437
+ const subAst = resolveSelectQuery(subquery);
5298
5438
  const correlated = this.applyCorrelation(subAst, correlate);
5299
5439
  return this.where(notExists(correlated));
5300
5440
  }
5301
5441
  /**
5302
-
5303
- * Adds a WHERE EXISTS condition based on a relationship
5304
-
5305
- * @param relationName - Name of the relationship to check
5306
-
5307
- * @param callback - Optional callback to modify the relationship query
5308
-
5309
- * @returns New query builder instance with the relationship existence check
5310
-
5311
- */
5442
+ * Adds a WHERE EXISTS condition based on a relationship
5443
+ * @param relationName - Name of the relationship to check
5444
+ * @param callback - Optional callback to modify the relationship query
5445
+ * @returns New query builder instance with the relationship existence check
5446
+ */
5312
5447
  whereHas(relationName, callbackOrOptions, maybeOptions) {
5313
5448
  const relation = this.env.table.relations[relationName];
5314
5449
  if (!relation) {
@@ -5325,16 +5460,11 @@ var SelectQueryBuilder = class _SelectQueryBuilder {
5325
5460
  return this.where(exists(finalSubAst));
5326
5461
  }
5327
5462
  /**
5328
-
5329
- * Adds a WHERE NOT EXISTS condition based on a relationship
5330
-
5331
- * @param relationName - Name of the relationship to check
5332
-
5333
- * @param callback - Optional callback to modify the relationship query
5334
-
5335
- * @returns New query builder instance with the relationship non-existence check
5336
-
5337
- */
5463
+ * Adds a WHERE NOT EXISTS condition based on a relationship
5464
+ * @param relationName - Name of the relationship to check
5465
+ * @param callback - Optional callback to modify the relationship query
5466
+ * @returns New query builder instance with the relationship non-existence check
5467
+ */
5338
5468
  whereHasNot(relationName, callbackOrOptions, maybeOptions) {
5339
5469
  const relation = this.env.table.relations[relationName];
5340
5470
  if (!relation) {
@@ -5351,53 +5481,61 @@ var SelectQueryBuilder = class _SelectQueryBuilder {
5351
5481
  return this.where(notExists(finalSubAst));
5352
5482
  }
5353
5483
  /**
5354
-
5355
- * Compiles the query to SQL for a specific dialect
5356
-
5357
- * @param dialect - Database dialect to compile for
5358
-
5359
- * @returns Compiled query with SQL and parameters
5360
-
5361
- */
5484
+ * Compiles the query to SQL for a specific dialect
5485
+ * @param dialect - Database dialect to compile for
5486
+ * @returns Compiled query with SQL and parameters
5487
+ */
5362
5488
  compile(dialect) {
5363
5489
  const resolved = resolveDialectInput(dialect);
5364
- return resolved.compileSelect(this.context.state.ast);
5490
+ return resolved.compileSelect(this.getAST());
5365
5491
  }
5366
5492
  /**
5367
-
5368
- * Converts the query to SQL string for a specific dialect
5369
-
5370
- * @param dialect - Database dialect to generate SQL for
5371
-
5372
- * @returns SQL string representation of the query
5373
-
5374
- */
5493
+ * Converts the query to SQL string for a specific dialect
5494
+ * @param dialect - Database dialect to generate SQL for
5495
+ * @returns SQL string representation of the query
5496
+ */
5375
5497
  toSql(dialect) {
5376
5498
  return this.compile(dialect).sql;
5377
5499
  }
5378
5500
  /**
5379
-
5380
- * Gets the hydration plan for the query
5381
-
5382
- * @returns Hydration plan or undefined if none exists
5383
-
5384
- */
5501
+ * Gets the hydration plan for the query
5502
+ * @returns Hydration plan or undefined if none exists
5503
+ */
5385
5504
  getHydrationPlan() {
5386
5505
  return this.context.hydration.getPlan();
5387
5506
  }
5388
5507
  /**
5389
-
5390
- * Gets the Abstract Syntax Tree (AST) representation of the query
5391
-
5392
- * @returns Query AST with hydration applied
5393
-
5394
- */
5508
+ * Gets the Abstract Syntax Tree (AST) representation of the query
5509
+ * @returns Query AST with hydration applied
5510
+ */
5395
5511
  getAST() {
5396
5512
  return this.context.hydration.applyToAst(this.context.state.ast);
5397
5513
  }
5398
5514
  };
5399
- var createColumn = (table, name) => ({ type: "Column", table, name });
5400
- var createLiteral = (val) => ({ type: "Literal", value: val });
5515
+
5516
+ // src/schema/table-guards.ts
5517
+ var isColumnsRecord = (columns) => {
5518
+ return typeof columns === "object" && columns !== null;
5519
+ };
5520
+ var isRelationsRecord = (relations) => {
5521
+ return typeof relations === "object" && relations !== null;
5522
+ };
5523
+ var isTableDef = (value) => {
5524
+ if (typeof value !== "object" || value === null) {
5525
+ return false;
5526
+ }
5527
+ const candidate = value;
5528
+ if (typeof candidate.name !== "string") {
5529
+ return false;
5530
+ }
5531
+ if (!isColumnsRecord(candidate.columns)) {
5532
+ return false;
5533
+ }
5534
+ if (!isRelationsRecord(candidate.relations)) {
5535
+ return false;
5536
+ }
5537
+ return true;
5538
+ };
5401
5539
 
5402
5540
  // src/orm/entity-metadata.ts
5403
5541
  var metadataMap = /* @__PURE__ */ new Map();
@@ -5441,23 +5579,20 @@ var buildTableDef = (meta) => {
5441
5579
  if (meta.table) {
5442
5580
  return meta.table;
5443
5581
  }
5444
- const columns = Object.entries(meta.columns).reduce((acc, [key, def]) => {
5445
- acc[key] = {
5582
+ const columns = {};
5583
+ for (const [key, def] of Object.entries(meta.columns)) {
5584
+ columns[key] = {
5446
5585
  ...def,
5447
5586
  name: key,
5448
5587
  table: meta.tableName
5449
5588
  };
5450
- return acc;
5451
- }, {});
5589
+ }
5452
5590
  const table = defineTable(meta.tableName, columns, {}, meta.hooks);
5453
5591
  meta.table = table;
5454
5592
  return table;
5455
5593
  };
5456
5594
 
5457
5595
  // src/decorators/bootstrap.ts
5458
- var isTableDef = (value) => {
5459
- return typeof value === "object" && value !== null && "columns" in value;
5460
- };
5461
5596
  var unwrapTarget = (target) => {
5462
5597
  if (typeof target === "function" && target.prototype === void 0) {
5463
5598
  return target();
@@ -5593,6 +5728,11 @@ function esel(entity, ...props) {
5593
5728
 
5594
5729
  // src/query-builder/insert-query-state.ts
5595
5730
  var InsertQueryState = class _InsertQueryState {
5731
+ /**
5732
+ * Creates a new InsertQueryState instance
5733
+ * @param table - The table definition for the INSERT query
5734
+ * @param ast - Optional initial AST node, defaults to a basic INSERT query
5735
+ */
5596
5736
  constructor(table, ast) {
5597
5737
  this.table = table;
5598
5738
  this.ast = ast ?? {
@@ -5623,6 +5763,13 @@ var InsertQueryState = class _InsertQueryState {
5623
5763
  if (!names.length) return [];
5624
5764
  return buildColumnNodes(this.table, names);
5625
5765
  }
5766
+ /**
5767
+ * Adds VALUES clause to the INSERT query
5768
+ * @param rows - Array of row objects to insert
5769
+ * @returns A new InsertQueryState with the VALUES clause added
5770
+ * @throws Error if mixing VALUES with SELECT source
5771
+ * @throws Error if invalid values are provided
5772
+ */
5626
5773
  withValues(rows) {
5627
5774
  if (!rows.length) return this;
5628
5775
  if (this.ast.source.type === "InsertSelect") {
@@ -5649,6 +5796,11 @@ var InsertQueryState = class _InsertQueryState {
5649
5796
  }
5650
5797
  });
5651
5798
  }
5799
+ /**
5800
+ * Sets the columns for the INSERT query
5801
+ * @param columns - Column nodes to insert into
5802
+ * @returns A new InsertQueryState with the specified columns
5803
+ */
5652
5804
  withColumns(columns) {
5653
5805
  if (!columns.length) return this;
5654
5806
  return this.clone({
@@ -5656,6 +5808,14 @@ var InsertQueryState = class _InsertQueryState {
5656
5808
  columns: [...columns]
5657
5809
  });
5658
5810
  }
5811
+ /**
5812
+ * Adds SELECT source to the INSERT query
5813
+ * @param query - The SELECT query to use as source
5814
+ * @param columns - Target columns for the INSERT
5815
+ * @returns A new InsertQueryState with the SELECT source
5816
+ * @throws Error if mixing SELECT with VALUES source
5817
+ * @throws Error if no destination columns specified
5818
+ */
5659
5819
  withSelect(query, columns) {
5660
5820
  const targetColumns = columns.length ? columns : this.ast.columns.length ? this.ast.columns : this.getTableColumns();
5661
5821
  if (!targetColumns.length) {
@@ -5673,6 +5833,11 @@ var InsertQueryState = class _InsertQueryState {
5673
5833
  }
5674
5834
  });
5675
5835
  }
5836
+ /**
5837
+ * Adds a RETURNING clause to the INSERT query
5838
+ * @param columns - Columns to return after insertion
5839
+ * @returns A new InsertQueryState with the RETURNING clause added
5840
+ */
5676
5841
  withReturning(columns) {
5677
5842
  return this.clone({
5678
5843
  ...this.ast,
@@ -5683,6 +5848,11 @@ var InsertQueryState = class _InsertQueryState {
5683
5848
 
5684
5849
  // src/query-builder/insert.ts
5685
5850
  var InsertQueryBuilder = class _InsertQueryBuilder {
5851
+ /**
5852
+ * Creates a new InsertQueryBuilder instance
5853
+ * @param table - The table definition for the INSERT query
5854
+ * @param state - Optional initial query state, defaults to a new InsertQueryState
5855
+ */
5686
5856
  constructor(table, state) {
5687
5857
  this.table = table;
5688
5858
  this.state = state ?? new InsertQueryState(table);
@@ -5690,20 +5860,42 @@ var InsertQueryBuilder = class _InsertQueryBuilder {
5690
5860
  clone(state) {
5691
5861
  return new _InsertQueryBuilder(this.table, state);
5692
5862
  }
5863
+ /**
5864
+ * Adds VALUES to the INSERT query
5865
+ * @param rowOrRows - Single row object or array of row objects to insert
5866
+ * @returns A new InsertQueryBuilder with the VALUES clause added
5867
+ */
5693
5868
  values(rowOrRows) {
5694
5869
  const rows = Array.isArray(rowOrRows) ? rowOrRows : [rowOrRows];
5695
5870
  if (!rows.length) return this;
5696
5871
  return this.clone(this.state.withValues(rows));
5697
5872
  }
5873
+ /**
5874
+ * Specifies the columns for the INSERT query
5875
+ * @param columns - Column definitions or nodes to insert into
5876
+ * @returns A new InsertQueryBuilder with the specified columns
5877
+ */
5698
5878
  columns(...columns) {
5699
5879
  if (!columns.length) return this;
5700
5880
  return this.clone(this.state.withColumns(this.resolveColumnNodes(columns)));
5701
5881
  }
5882
+ /**
5883
+ * Sets the source of the INSERT query to a SELECT query
5884
+ * @template TSource - The source table type
5885
+ * @param query - The SELECT query or query builder to use as source
5886
+ * @param columns - Optional target columns for the INSERT
5887
+ * @returns A new InsertQueryBuilder with the SELECT source
5888
+ */
5702
5889
  fromSelect(query, columns = []) {
5703
5890
  const ast = this.resolveSelectQuery(query);
5704
5891
  const nodes = columns.length ? this.resolveColumnNodes(columns) : [];
5705
5892
  return this.clone(this.state.withSelect(ast, nodes));
5706
5893
  }
5894
+ /**
5895
+ * Adds a RETURNING clause to the INSERT query
5896
+ * @param columns - Columns to return after insertion
5897
+ * @returns A new InsertQueryBuilder with the RETURNING clause added
5898
+ */
5707
5899
  returning(...columns) {
5708
5900
  if (!columns.length) return this;
5709
5901
  const nodes = columns.map((column) => buildColumnNode(this.table, column));
@@ -5725,9 +5917,18 @@ var InsertQueryBuilder = class _InsertQueryBuilder {
5725
5917
  const dialect = resolveDialectInput(arg);
5726
5918
  return dialect.compileInsert(this.state.ast);
5727
5919
  }
5920
+ /**
5921
+ * Returns the SQL string for the INSERT query
5922
+ * @param arg - The compiler or dialect to generate SQL for
5923
+ * @returns The SQL string representation of the query
5924
+ */
5728
5925
  toSql(arg) {
5729
5926
  return this.compile(arg).sql;
5730
5927
  }
5928
+ /**
5929
+ * Returns the Abstract Syntax Tree (AST) representation of the query
5930
+ * @returns The AST node for the INSERT query
5931
+ */
5731
5932
  getAST() {
5732
5933
  return this.state.ast;
5733
5934
  }
@@ -5746,6 +5947,11 @@ var isUpdateValue = (value) => {
5746
5947
  }
5747
5948
  };
5748
5949
  var UpdateQueryState = class _UpdateQueryState {
5950
+ /**
5951
+ * Creates a new UpdateQueryState instance
5952
+ * @param table - Table definition for the update
5953
+ * @param ast - Optional existing AST
5954
+ */
5749
5955
  constructor(table, ast) {
5750
5956
  this.table = table;
5751
5957
  this.ast = ast ?? {
@@ -5755,9 +5961,19 @@ var UpdateQueryState = class _UpdateQueryState {
5755
5961
  joins: []
5756
5962
  };
5757
5963
  }
5964
+ /**
5965
+ * Creates a new UpdateQueryState with updated AST
5966
+ * @param nextAst - Updated AST
5967
+ * @returns New UpdateQueryState instance
5968
+ */
5758
5969
  clone(nextAst) {
5759
5970
  return new _UpdateQueryState(this.table, nextAst);
5760
5971
  }
5972
+ /**
5973
+ * Sets the columns to update with their new values
5974
+ * @param values - Record of column names to values
5975
+ * @returns New UpdateQueryState with SET clause
5976
+ */
5761
5977
  withSet(values) {
5762
5978
  const assignments = Object.entries(values).map(([column, rawValue]) => {
5763
5979
  if (!isUpdateValue(rawValue)) {
@@ -5779,30 +5995,55 @@ var UpdateQueryState = class _UpdateQueryState {
5779
5995
  set: assignments
5780
5996
  });
5781
5997
  }
5998
+ /**
5999
+ * Adds a WHERE condition to the update query
6000
+ * @param expr - WHERE expression
6001
+ * @returns New UpdateQueryState with WHERE clause
6002
+ */
5782
6003
  withWhere(expr) {
5783
6004
  return this.clone({
5784
6005
  ...this.ast,
5785
6006
  where: expr
5786
6007
  });
5787
6008
  }
6009
+ /**
6010
+ * Adds a RETURNING clause to the update query
6011
+ * @param columns - Columns to return
6012
+ * @returns New UpdateQueryState with RETURNING clause
6013
+ */
5788
6014
  withReturning(columns) {
5789
6015
  return this.clone({
5790
6016
  ...this.ast,
5791
6017
  returning: [...columns]
5792
6018
  });
5793
6019
  }
6020
+ /**
6021
+ * Sets the FROM clause for the update query
6022
+ * @param from - Table source for FROM
6023
+ * @returns New UpdateQueryState with FROM clause
6024
+ */
5794
6025
  withFrom(from) {
5795
6026
  return this.clone({
5796
6027
  ...this.ast,
5797
6028
  from
5798
6029
  });
5799
6030
  }
6031
+ /**
6032
+ * Adds a JOIN to the update query
6033
+ * @param join - Join node to add
6034
+ * @returns New UpdateQueryState with JOIN
6035
+ */
5800
6036
  withJoin(join) {
5801
6037
  return this.clone({
5802
6038
  ...this.ast,
5803
6039
  joins: [...this.ast.joins ?? [], join]
5804
6040
  });
5805
6041
  }
6042
+ /**
6043
+ * Applies an alias to the table being updated
6044
+ * @param alias - Alias for the table
6045
+ * @returns New UpdateQueryState with table alias
6046
+ */
5806
6047
  withTableAlias(alias) {
5807
6048
  return this.clone({
5808
6049
  ...this.ast,
@@ -5816,6 +6057,11 @@ var UpdateQueryState = class _UpdateQueryState {
5816
6057
 
5817
6058
  // src/query-builder/update.ts
5818
6059
  var UpdateQueryBuilder = class _UpdateQueryBuilder {
6060
+ /**
6061
+ * Creates a new UpdateQueryBuilder instance
6062
+ * @param table - The table definition for the UPDATE query
6063
+ * @param state - Optional initial query state, defaults to a new UpdateQueryState
6064
+ */
5819
6065
  constructor(table, state) {
5820
6066
  this.table = table;
5821
6067
  this.state = state ?? new UpdateQueryState(table);
@@ -5823,24 +6069,57 @@ var UpdateQueryBuilder = class _UpdateQueryBuilder {
5823
6069
  clone(state) {
5824
6070
  return new _UpdateQueryBuilder(this.table, state);
5825
6071
  }
6072
+ /**
6073
+ * Sets an alias for the table in the UPDATE query
6074
+ * @param alias - The alias to assign to the table
6075
+ * @returns A new UpdateQueryBuilder with the table alias set
6076
+ */
5826
6077
  as(alias) {
5827
6078
  return this.clone(this.state.withTableAlias(alias));
5828
6079
  }
6080
+ /**
6081
+ * Adds a FROM clause to the UPDATE query
6082
+ * @param source - The table source to use in the FROM clause
6083
+ * @returns A new UpdateQueryBuilder with the FROM clause added
6084
+ */
5829
6085
  from(source) {
5830
6086
  const tableSource = this.resolveTableSource(source);
5831
6087
  return this.clone(this.state.withFrom(tableSource));
5832
6088
  }
6089
+ /**
6090
+ * Adds a JOIN clause to the UPDATE query
6091
+ * @param table - The table to join with
6092
+ * @param condition - The join condition expression
6093
+ * @param kind - The type of join (defaults to INNER)
6094
+ * @param relationName - Optional name for the relation
6095
+ * @returns A new UpdateQueryBuilder with the JOIN clause added
6096
+ */
5833
6097
  join(table, condition, kind = JOIN_KINDS.INNER, relationName) {
5834
6098
  const joinTarget = this.resolveJoinTarget(table);
5835
6099
  const joinNode = createJoinNode(kind, joinTarget, condition, relationName);
5836
6100
  return this.clone(this.state.withJoin(joinNode));
5837
6101
  }
6102
+ /**
6103
+ * Adds a SET clause to the UPDATE query
6104
+ * @param values - The column-value pairs to update
6105
+ * @returns A new UpdateQueryBuilder with the SET clause added
6106
+ */
5838
6107
  set(values) {
5839
6108
  return this.clone(this.state.withSet(values));
5840
6109
  }
6110
+ /**
6111
+ * Adds a WHERE clause to the UPDATE query
6112
+ * @param expr - The expression to use as the WHERE condition
6113
+ * @returns A new UpdateQueryBuilder with the WHERE clause added
6114
+ */
5841
6115
  where(expr) {
5842
6116
  return this.clone(this.state.withWhere(expr));
5843
6117
  }
6118
+ /**
6119
+ * Adds a RETURNING clause to the UPDATE query
6120
+ * @param columns - Columns to return after update
6121
+ * @returns A new UpdateQueryBuilder with the RETURNING clause added
6122
+ */
5844
6123
  returning(...columns) {
5845
6124
  if (!columns.length) return this;
5846
6125
  const nodes = columns.map((column) => buildColumnNode(this.table, column));
@@ -5856,17 +6135,36 @@ var UpdateQueryBuilder = class _UpdateQueryBuilder {
5856
6135
  if (typeof table === "string") return table;
5857
6136
  return this.resolveTableSource(table);
5858
6137
  }
5859
- compile(arg) {
5860
- const candidate = arg;
5861
- if (typeof candidate.compileUpdate === "function") {
5862
- return candidate.compileUpdate(this.state.ast);
5863
- }
5864
- const dialect = resolveDialectInput(arg);
5865
- return dialect.compileUpdate(this.state.ast);
6138
+ /**
6139
+ * Compiles the UPDATE query for the specified dialect
6140
+ * @param dialect - The SQL dialect to compile for
6141
+ * @returns The compiled query with SQL and parameters
6142
+ */
6143
+ compile(dialect) {
6144
+ const resolved = resolveDialectInput(dialect);
6145
+ return resolved.compileUpdate(this.state.ast);
5866
6146
  }
5867
- toSql(arg) {
5868
- return this.compile(arg).sql;
6147
+ /**
6148
+ * Returns the SQL string for the UPDATE query
6149
+ * @param dialect - The SQL dialect to generate SQL for
6150
+ * @returns The SQL string representation of the query
6151
+ */
6152
+ toSql(dialect) {
6153
+ return this.compile(dialect).sql;
5869
6154
  }
6155
+ /**
6156
+ * Executes the UPDATE query using the provided session
6157
+ * @param session - The ORM session to execute the query with
6158
+ * @returns A promise that resolves to the query results
6159
+ */
6160
+ async execute(session) {
6161
+ const compiled = this.compile(session.dialect);
6162
+ return session.executor.executeSql(compiled.sql, compiled.params);
6163
+ }
6164
+ /**
6165
+ * Returns the Abstract Syntax Tree (AST) representation of the query
6166
+ * @returns The AST node for the UPDATE query
6167
+ */
5870
6168
  getAST() {
5871
6169
  return this.state.ast;
5872
6170
  }
@@ -5875,6 +6173,11 @@ var isTableSourceNode = (source) => typeof source.type === "string";
5875
6173
 
5876
6174
  // src/query-builder/delete-query-state.ts
5877
6175
  var DeleteQueryState = class _DeleteQueryState {
6176
+ /**
6177
+ * Creates a new DeleteQueryState instance
6178
+ * @param table - The table definition for the DELETE query
6179
+ * @param ast - Optional initial AST node, defaults to a basic DELETE query
6180
+ */
5878
6181
  constructor(table, ast) {
5879
6182
  this.table = table;
5880
6183
  this.ast = ast ?? {
@@ -5886,30 +6189,55 @@ var DeleteQueryState = class _DeleteQueryState {
5886
6189
  clone(nextAst) {
5887
6190
  return new _DeleteQueryState(this.table, nextAst);
5888
6191
  }
6192
+ /**
6193
+ * Adds a WHERE clause to the DELETE query
6194
+ * @param expr - The expression to use as the WHERE condition
6195
+ * @returns A new DeleteQueryState with the WHERE clause added
6196
+ */
5889
6197
  withWhere(expr) {
5890
6198
  return this.clone({
5891
6199
  ...this.ast,
5892
6200
  where: expr
5893
6201
  });
5894
6202
  }
6203
+ /**
6204
+ * Adds a RETURNING clause to the DELETE query
6205
+ * @param columns - The columns to return after deletion
6206
+ * @returns A new DeleteQueryState with the RETURNING clause added
6207
+ */
5895
6208
  withReturning(columns) {
5896
6209
  return this.clone({
5897
6210
  ...this.ast,
5898
6211
  returning: [...columns]
5899
6212
  });
5900
6213
  }
6214
+ /**
6215
+ * Adds a USING clause to the DELETE query
6216
+ * @param source - The table source to use in the USING clause
6217
+ * @returns A new DeleteQueryState with the USING clause added
6218
+ */
5901
6219
  withUsing(source) {
5902
6220
  return this.clone({
5903
6221
  ...this.ast,
5904
6222
  using: source
5905
6223
  });
5906
6224
  }
6225
+ /**
6226
+ * Adds a JOIN clause to the DELETE query
6227
+ * @param join - The join node to add
6228
+ * @returns A new DeleteQueryState with the JOIN clause added
6229
+ */
5907
6230
  withJoin(join) {
5908
6231
  return this.clone({
5909
6232
  ...this.ast,
5910
6233
  joins: [...this.ast.joins ?? [], join]
5911
6234
  });
5912
6235
  }
6236
+ /**
6237
+ * Sets an alias for the table in the DELETE query
6238
+ * @param alias - The alias to assign to the table
6239
+ * @returns A new DeleteQueryState with the table alias set
6240
+ */
5913
6241
  withTableAlias(alias) {
5914
6242
  return this.clone({
5915
6243
  ...this.ast,
@@ -5923,6 +6251,11 @@ var DeleteQueryState = class _DeleteQueryState {
5923
6251
 
5924
6252
  // src/query-builder/delete.ts
5925
6253
  var DeleteQueryBuilder = class _DeleteQueryBuilder {
6254
+ /**
6255
+ * Creates a new DeleteQueryBuilder instance
6256
+ * @param table - The table definition for the DELETE query
6257
+ * @param state - Optional initial query state, defaults to a new DeleteQueryState
6258
+ */
5926
6259
  constructor(table, state) {
5927
6260
  this.table = table;
5928
6261
  this.state = state ?? new DeleteQueryState(table);
@@ -5930,20 +6263,48 @@ var DeleteQueryBuilder = class _DeleteQueryBuilder {
5930
6263
  clone(state) {
5931
6264
  return new _DeleteQueryBuilder(this.table, state);
5932
6265
  }
6266
+ /**
6267
+ * Adds a WHERE clause to the DELETE query
6268
+ * @param expr - The expression to use as the WHERE condition
6269
+ * @returns A new DeleteQueryBuilder with the WHERE clause added
6270
+ */
5933
6271
  where(expr) {
5934
6272
  return this.clone(this.state.withWhere(expr));
5935
6273
  }
6274
+ /**
6275
+ * Sets an alias for the table in the DELETE query
6276
+ * @param alias - The alias to assign to the table
6277
+ * @returns A new DeleteQueryBuilder with the table alias set
6278
+ */
5936
6279
  as(alias) {
5937
6280
  return this.clone(this.state.withTableAlias(alias));
5938
6281
  }
6282
+ /**
6283
+ * Adds a USING clause to the DELETE query
6284
+ * @param source - The table source to use in the USING clause
6285
+ * @returns A new DeleteQueryBuilder with the USING clause added
6286
+ */
5939
6287
  using(source) {
5940
6288
  return this.clone(this.state.withUsing(this.resolveTableSource(source)));
5941
6289
  }
6290
+ /**
6291
+ * Adds a JOIN clause to the DELETE query
6292
+ * @param table - The table to join with
6293
+ * @param condition - The join condition expression
6294
+ * @param kind - The type of join (defaults to INNER)
6295
+ * @param relationName - Optional name for the relation
6296
+ * @returns A new DeleteQueryBuilder with the JOIN clause added
6297
+ */
5942
6298
  join(table, condition, kind = JOIN_KINDS.INNER, relationName) {
5943
6299
  const target = this.resolveJoinTarget(table);
5944
6300
  const joinNode = createJoinNode(kind, target, condition, relationName);
5945
6301
  return this.clone(this.state.withJoin(joinNode));
5946
6302
  }
6303
+ /**
6304
+ * Adds a RETURNING clause to the DELETE query
6305
+ * @param columns - The columns to return after deletion
6306
+ * @returns A new DeleteQueryBuilder with the RETURNING clause added
6307
+ */
5947
6308
  returning(...columns) {
5948
6309
  if (!columns.length) return this;
5949
6310
  const nodes = columns.map((column) => buildColumnNode(this.table, column));
@@ -5959,17 +6320,36 @@ var DeleteQueryBuilder = class _DeleteQueryBuilder {
5959
6320
  if (typeof table === "string") return table;
5960
6321
  return this.resolveTableSource(table);
5961
6322
  }
5962
- compile(arg) {
5963
- const candidate = arg;
5964
- if (typeof candidate.compileDelete === "function") {
5965
- return candidate.compileDelete(this.state.ast);
5966
- }
5967
- const dialect = resolveDialectInput(arg);
5968
- return dialect.compileDelete(this.state.ast);
6323
+ /**
6324
+ * Compiles the DELETE query for the specified dialect
6325
+ * @param dialect - The SQL dialect to compile for
6326
+ * @returns The compiled query with SQL and parameters
6327
+ */
6328
+ compile(dialect) {
6329
+ const resolved = resolveDialectInput(dialect);
6330
+ return resolved.compileDelete(this.state.ast);
5969
6331
  }
5970
- toSql(arg) {
5971
- return this.compile(arg).sql;
6332
+ /**
6333
+ * Returns the SQL string for the DELETE query
6334
+ * @param dialect - The SQL dialect to generate SQL for
6335
+ * @returns The SQL string representation of the query
6336
+ */
6337
+ toSql(dialect) {
6338
+ return this.compile(dialect).sql;
5972
6339
  }
6340
+ /**
6341
+ * Executes the DELETE query using the provided session
6342
+ * @param session - The ORM session to execute the query with
6343
+ * @returns A promise that resolves to the query results
6344
+ */
6345
+ async execute(session) {
6346
+ const compiled = this.compile(session.dialect);
6347
+ return session.executor.executeSql(compiled.sql, compiled.params);
6348
+ }
6349
+ /**
6350
+ * Returns the Abstract Syntax Tree (AST) representation of the query
6351
+ * @returns The AST node for the DELETE query
6352
+ */
5973
6353
  getAST() {
5974
6354
  return this.state.ast;
5975
6355
  }
@@ -6404,6 +6784,13 @@ async function runSelectNode(ast, ctx) {
6404
6784
 
6405
6785
  // src/core/ddl/introspect/postgres.ts
6406
6786
  var postgresIntrospector = {
6787
+ /**
6788
+ * Introspects the PostgreSQL database schema by querying information_schema and pg_catalog.
6789
+ * Builds tables with columns, primary keys, foreign keys, and indexes.
6790
+ * @param ctx - The introspection context with database executor.
6791
+ * @param options - Options for schema selection and table filtering.
6792
+ * @returns A promise resolving to the complete database schema.
6793
+ */
6407
6794
  async introspect(ctx, options) {
6408
6795
  const schema = options.schema || "public";
6409
6796
  const tables = [];
@@ -6691,6 +7078,12 @@ var toReferentialAction = (value) => {
6691
7078
  };
6692
7079
  var escapeSingleQuotes = (name) => name.replace(/'/g, "''");
6693
7080
  var sqliteIntrospector = {
7081
+ /**
7082
+ * Introspects the SQLite database schema by querying sqlite_master and various PRAGMAs.
7083
+ * @param ctx - The database execution context containing the DbExecutor.
7084
+ * @param options - Options controlling which tables and schemas to include.
7085
+ * @returns A promise that resolves to the introspected DatabaseSchema.
7086
+ */
6694
7087
  async introspect(ctx, options) {
6695
7088
  const tables = [];
6696
7089
  const tableRows = await queryRows(
@@ -6746,6 +7139,12 @@ var sqliteIntrospector = {
6746
7139
 
6747
7140
  // src/core/ddl/introspect/mssql.ts
6748
7141
  var mssqlIntrospector = {
7142
+ /**
7143
+ * Introspects the MSSQL database schema.
7144
+ * @param ctx - The introspection context containing the database executor.
7145
+ * @param options - Options for introspection, such as schema filter.
7146
+ * @returns A promise that resolves to the introspected database schema.
7147
+ */
6749
7148
  async introspect(ctx, options) {
6750
7149
  const schema = options.schema;
6751
7150
  const filterSchema = schema ? "sch.name = @p1" : "1=1";
@@ -7028,10 +7427,21 @@ var dateTrunc = (part, date) => fn3("DATE_TRUNC", [part, date]);
7028
7427
  // src/orm/als.ts
7029
7428
  var AsyncLocalStorage = class {
7030
7429
  /**
7031
- * Executes a callback with the specified store value
7032
- * @param store - Value to store during callback execution
7033
- * @param callback - Function to execute with the store value
7034
- * @returns Result of the callback function
7430
+ * Executes a callback function within a context containing the specified store value.
7431
+ * The store value is only available during the callback's execution and is automatically
7432
+ * cleared afterward.
7433
+ *
7434
+ * @param store - The context value to make available during callback execution
7435
+ * @param callback - Function to execute with the store value available
7436
+ * @returns Result of the callback function execution
7437
+ *
7438
+ * @example
7439
+ * ```
7440
+ * const als = new AsyncLocalStorage<number>();
7441
+ * als.run(42, () => {
7442
+ * console.log(als.getStore()); // Outputs: 42
7443
+ * });
7444
+ * ```
7035
7445
  */
7036
7446
  run(store, callback) {
7037
7447
  this.store = store;
@@ -7042,8 +7452,20 @@ var AsyncLocalStorage = class {
7042
7452
  }
7043
7453
  }
7044
7454
  /**
7045
- * Gets the currently stored value
7046
- * @returns Current store value or undefined if none exists
7455
+ * Retrieves the current store value from the async context.
7456
+ * Returns undefined if called outside of a `run()` callback execution.
7457
+ *
7458
+ * @returns Current store value or undefined if no context exists
7459
+ *
7460
+ * @example
7461
+ * ```
7462
+ * const als = new AsyncLocalStorage<string>();
7463
+ * console.log(als.getStore()); // Outputs: undefined
7464
+ *
7465
+ * als.run('hello', () => {
7466
+ * console.log(als.getStore()); // Outputs: 'hello'
7467
+ * });
7468
+ * ```
7047
7469
  */
7048
7470
  getStore() {
7049
7471
  return this.store;
@@ -9572,11 +9994,9 @@ function createPooledExecutorFactory(opts) {
9572
9994
  cos,
9573
9995
  cot,
9574
9996
  count,
9575
- createColumn,
9576
9997
  createEntityFromRow,
9577
9998
  createEntityProxy,
9578
9999
  createExecutorFromQueryRunner,
9579
- createLiteral,
9580
10000
  createMssqlExecutor,
9581
10001
  createMysqlExecutor,
9582
10002
  createPooledExecutorFactory,