metal-orm 1.1.19 → 1.1.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -6,8 +6,8 @@ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require
6
6
  if (typeof require !== "undefined") return require.apply(this, arguments);
7
7
  throw Error('Dynamic require of "' + x + '" is not supported');
8
8
  });
9
- var __esm = (fn8, res) => function __init() {
10
- return fn8 && (res = (0, fn8[__getOwnPropNames(fn8)[0]])(fn8 = 0)), res;
9
+ var __esm = (fn9, res) => function __init() {
10
+ return fn9 && (res = (0, fn9[__getOwnPropNames(fn9)[0]])(fn9 = 0)), res;
11
11
  };
12
12
  var __export = (target, all) => {
13
13
  for (var name in all)
@@ -143,7 +143,9 @@ var STANDARD_COLUMN_TYPES = [
143
143
  "DATETIME",
144
144
  "TIMESTAMP",
145
145
  "TIMESTAMPTZ",
146
- "BOOLEAN"
146
+ "BOOLEAN",
147
+ "VECTOR",
148
+ "HALFVEC"
147
149
  ];
148
150
  var STANDARD_TYPE_SET = new Set(STANDARD_COLUMN_TYPES.map((t) => t.toLowerCase()));
149
151
  var normalizeColumnType = (type) => {
@@ -253,6 +255,27 @@ var col = {
253
255
  * @param values - Enum values
254
256
  */
255
257
  enum: (values) => ({ name: "", type: "ENUM", args: values }),
258
+ /**
259
+ * Creates a vector column definition
260
+ * @param dimensions - Vector dimensions
261
+ * @param options - Vector options (e.g. elementType: 'float16' | 'float32')
262
+ */
263
+ vector: (dimensions, options) => ({
264
+ name: "",
265
+ type: "VECTOR",
266
+ args: [dimensions],
267
+ vectorOptions: { dimensions, ...options }
268
+ }),
269
+ /**
270
+ * Creates a half-precision (float16) vector column definition (pgvector halfvec / SQL Server float16 vector / sqlite-vec float16)
271
+ * @param dimensions - Vector dimensions
272
+ */
273
+ halfvec: (dimensions) => ({
274
+ name: "",
275
+ type: "HALFVEC",
276
+ args: [dimensions],
277
+ vectorOptions: { dimensions, elementType: "float16" }
278
+ }),
256
279
  /**
257
280
  * Creates a column definition with a custom SQL type.
258
281
  * Useful for dialect-specific types without polluting the standard set.
@@ -1726,13 +1749,13 @@ var FunctionTableFormatter = class {
1726
1749
  * @param dialect - The dialect instance for compiling operands.
1727
1750
  * @returns SQL function table expression (e.g., "LATERAL schema.func(args) WITH ORDINALITY AS alias(col1, col2)").
1728
1751
  */
1729
- static format(fn8, ctx, dialect) {
1730
- const schemaPart = this.formatSchema(fn8, dialect);
1731
- const args = this.formatArgs(fn8, ctx, dialect);
1732
- const base = this.formatBase(fn8, schemaPart, args);
1733
- const lateral = this.formatLateral(fn8);
1734
- const alias = this.formatAlias(fn8, dialect);
1735
- const colAliases = this.formatColumnAliases(fn8, dialect);
1752
+ static format(fn9, ctx, dialect) {
1753
+ const schemaPart = this.formatSchema(fn9, dialect);
1754
+ const args = this.formatArgs(fn9, ctx, dialect);
1755
+ const base = this.formatBase(fn9, schemaPart, args);
1756
+ const lateral = this.formatLateral(fn9);
1757
+ const alias = this.formatAlias(fn9, dialect);
1758
+ const colAliases = this.formatColumnAliases(fn9, dialect);
1736
1759
  return `${lateral}${base}${alias}${colAliases}`;
1737
1760
  }
1738
1761
  /**
@@ -1742,9 +1765,9 @@ var FunctionTableFormatter = class {
1742
1765
  * @returns Schema prefix (e.g., "schema.") or empty string.
1743
1766
  * @internal
1744
1767
  */
1745
- static formatSchema(fn8, dialect) {
1746
- if (!fn8.schema) return "";
1747
- const quoted = dialect ? dialect.quoteIdentifier(fn8.schema) : fn8.schema;
1768
+ static formatSchema(fn9, dialect) {
1769
+ if (!fn9.schema) return "";
1770
+ const quoted = dialect ? dialect.quoteIdentifier(fn9.schema) : fn9.schema;
1748
1771
  return `${quoted}.`;
1749
1772
  }
1750
1773
  /**
@@ -1755,8 +1778,8 @@ var FunctionTableFormatter = class {
1755
1778
  * @returns Comma-separated function arguments.
1756
1779
  * @internal
1757
1780
  */
1758
- static formatArgs(fn8, ctx, dialect) {
1759
- return (fn8.args || []).map((a) => {
1781
+ static formatArgs(fn9, ctx, dialect) {
1782
+ return (fn9.args || []).map((a) => {
1760
1783
  if (ctx && dialect) {
1761
1784
  return dialect.compileOperand(a, ctx);
1762
1785
  }
@@ -1772,9 +1795,9 @@ var FunctionTableFormatter = class {
1772
1795
  * @returns Base function call expression (e.g., "schema.func(args) WITH ORDINALITY").
1773
1796
  * @internal
1774
1797
  */
1775
- static formatBase(fn8, schemaPart, args) {
1776
- const ordinality = fn8.withOrdinality ? " WITH ORDINALITY" : "";
1777
- return `${schemaPart}${fn8.name}(${args})${ordinality}`;
1798
+ static formatBase(fn9, schemaPart, args) {
1799
+ const ordinality = fn9.withOrdinality ? " WITH ORDINALITY" : "";
1800
+ return `${schemaPart}${fn9.name}(${args})${ordinality}`;
1778
1801
  }
1779
1802
  /**
1780
1803
  * Formats the LATERAL keyword if present.
@@ -1782,8 +1805,8 @@ var FunctionTableFormatter = class {
1782
1805
  * @returns "LATERAL " or empty string.
1783
1806
  * @internal
1784
1807
  */
1785
- static formatLateral(fn8) {
1786
- return fn8.lateral ? "LATERAL " : "";
1808
+ static formatLateral(fn9) {
1809
+ return fn9.lateral ? "LATERAL " : "";
1787
1810
  }
1788
1811
  /**
1789
1812
  * Formats the table alias for the function table.
@@ -1792,9 +1815,9 @@ var FunctionTableFormatter = class {
1792
1815
  * @returns " AS alias" or empty string.
1793
1816
  * @internal
1794
1817
  */
1795
- static formatAlias(fn8, dialect) {
1796
- if (!fn8.alias) return "";
1797
- const quoted = dialect ? dialect.quoteIdentifier(fn8.alias) : fn8.alias;
1818
+ static formatAlias(fn9, dialect) {
1819
+ if (!fn9.alias) return "";
1820
+ const quoted = dialect ? dialect.quoteIdentifier(fn9.alias) : fn9.alias;
1798
1821
  return ` AS ${quoted}`;
1799
1822
  }
1800
1823
  /**
@@ -1804,9 +1827,9 @@ var FunctionTableFormatter = class {
1804
1827
  * @returns "(col1, col2, ...)" or empty string.
1805
1828
  * @internal
1806
1829
  */
1807
- static formatColumnAliases(fn8, dialect) {
1808
- if (!fn8.columnAliases || !fn8.columnAliases.length) return "";
1809
- const aliases = fn8.columnAliases.map((col2) => dialect ? dialect.quoteIdentifier(col2) : col2).join(", ");
1830
+ static formatColumnAliases(fn9, dialect) {
1831
+ if (!fn9.columnAliases || !fn9.columnAliases.length) return "";
1832
+ const aliases = fn9.columnAliases.map((col2) => dialect ? dialect.quoteIdentifier(col2) : col2).join(", ");
1810
1833
  return `(${aliases})`;
1811
1834
  }
1812
1835
  };
@@ -2088,24 +2111,24 @@ var SqlDialectBase = class extends Dialect {
2088
2111
  }
2089
2112
  return this.compileTableSource(tableSource);
2090
2113
  }
2091
- compileFunctionTable(fn8, ctx) {
2092
- const key = fn8.key ?? fn8.name;
2114
+ compileFunctionTable(fn9, ctx) {
2115
+ const key = fn9.key ?? fn9.name;
2093
2116
  if (ctx) {
2094
2117
  const renderer = this.tableFunctionStrategy.getRenderer(key);
2095
2118
  if (renderer) {
2096
- const compiledArgs = (fn8.args ?? []).map((arg) => this.compileOperand(arg, ctx));
2119
+ const compiledArgs = (fn9.args ?? []).map((arg) => this.compileOperand(arg, ctx));
2097
2120
  return renderer({
2098
- node: fn8,
2121
+ node: fn9,
2099
2122
  compiledArgs,
2100
2123
  compileOperand: (operand) => this.compileOperand(operand, ctx),
2101
2124
  quoteIdentifier: this.quoteIdentifier.bind(this)
2102
2125
  });
2103
2126
  }
2104
- if (fn8.key) {
2127
+ if (fn9.key) {
2105
2128
  throw new Error(`Table function "${key}" is not supported by dialect "${this.dialect}".`);
2106
2129
  }
2107
2130
  }
2108
- return FunctionTableFormatter.format(fn8, ctx, this);
2131
+ return FunctionTableFormatter.format(fn9, ctx, this);
2109
2132
  }
2110
2133
  compileDerivedTable(table, ctx) {
2111
2134
  if (!table.alias) {
@@ -2294,6 +2317,26 @@ var PostgresFunctionStrategy = class extends StandardFunctionStrategy {
2294
2317
  const pathArray = this.formatJsonbPathArray(pathNode);
2295
2318
  return `jsonb_set(${compiledArgs[0]}, ${pathArray}, ${compiledArgs[2]}::jsonb, true)`;
2296
2319
  });
2320
+ this.add("VECTOR_DISTANCE", ({ node, compiledArgs }) => {
2321
+ if (compiledArgs.length !== 3) throw new Error("VECTOR_DISTANCE expects 3 arguments (metric, v1, v2)");
2322
+ const metric = node.args[0]?.type === "Literal" ? String(node.args[0].value).toLowerCase() : compiledArgs[0].replace(/['"]/g, "").toLowerCase();
2323
+ const [, v1, v2] = compiledArgs;
2324
+ switch (metric) {
2325
+ case "cosine":
2326
+ return `(${v1} <=> ${v2})`;
2327
+ case "euclidean":
2328
+ case "l2":
2329
+ return `(${v1} <-> ${v2})`;
2330
+ case "dot":
2331
+ case "inner_product":
2332
+ return `(${v1} <#> ${v2})`;
2333
+ case "manhattan":
2334
+ case "l1":
2335
+ return `(${v1} <~> ${v2})`;
2336
+ default:
2337
+ return `(${v1} <=> ${v2})`;
2338
+ }
2339
+ });
2297
2340
  }
2298
2341
  formatJsonbPathArray(pathNode) {
2299
2342
  const rawPath = String(pathNode.value ?? "");
@@ -2525,6 +2568,14 @@ var MysqlFunctionStrategy = class extends StandardFunctionStrategy {
2525
2568
  if (compiledArgs.length !== 2) throw new Error("ARRAY_APPEND expects 2 arguments (array, value)");
2526
2569
  return `JSON_ARRAY_APPEND(${compiledArgs[0]}, '$', ${compiledArgs[1]})`;
2527
2570
  });
2571
+ this.add("VECTOR_DISTANCE", ({ node, compiledArgs }) => {
2572
+ if (compiledArgs.length !== 3) throw new Error("VECTOR_DISTANCE expects 3 arguments (metric, v1, v2)");
2573
+ let metric = node.args[0]?.type === "Literal" ? String(node.args[0].value).toUpperCase() : compiledArgs[0].replace(/['"]/g, "").toUpperCase();
2574
+ if (metric === "L2") metric = "EUCLIDEAN";
2575
+ if (metric === "INNER_PRODUCT") metric = "DOT";
2576
+ const [, v1, v2] = compiledArgs;
2577
+ return `DISTANCE(${v1}, ${v2}, '${metric}')`;
2578
+ });
2528
2579
  }
2529
2580
  };
2530
2581
 
@@ -2761,6 +2812,15 @@ var SqliteFunctionStrategy = class extends StandardFunctionStrategy {
2761
2812
  return `json_array_append(${compiledArgs[0]}, '$', ${compiledArgs[1]})`;
2762
2813
  });
2763
2814
  this.add("CHR", ({ compiledArgs }) => `CHAR(${compiledArgs[0]})`);
2815
+ this.add("VECTOR_DISTANCE", ({ node, compiledArgs }) => {
2816
+ if (compiledArgs.length !== 3) throw new Error("VECTOR_DISTANCE expects 3 arguments (metric, v1, v2)");
2817
+ const metric = node.args[0]?.type === "Literal" ? String(node.args[0].value).toLowerCase() : compiledArgs[0].replace(/['"]/g, "").toLowerCase();
2818
+ const [, v1, v2] = compiledArgs;
2819
+ if (metric === "euclidean" || metric === "l2") {
2820
+ return `vec_distance_L2(${v1}, ${v2})`;
2821
+ }
2822
+ return `vec_distance_cosine(${v1}, ${v2})`;
2823
+ });
2764
2824
  }
2765
2825
  };
2766
2826
 
@@ -2962,6 +3022,15 @@ var MssqlFunctionStrategy = class extends StandardFunctionStrategy {
2962
3022
  this.add("ARRAY_APPEND", () => {
2963
3023
  throw new Error("ARRAY_APPEND is not supported on SQL Server");
2964
3024
  });
3025
+ this.add("VECTOR_DISTANCE", ({ node, compiledArgs }) => {
3026
+ if (compiledArgs.length !== 3) throw new Error("VECTOR_DISTANCE expects 3 arguments (metric, v1, v2)");
3027
+ let metric = node.args[0]?.type === "Literal" ? String(node.args[0].value).toLowerCase() : compiledArgs[0].replace(/['"]/g, "").toLowerCase();
3028
+ if (metric === "l2") metric = "euclidean";
3029
+ if (metric === "l1") metric = "manhattan";
3030
+ if (metric === "inner_product") metric = "dot";
3031
+ const [, v1, v2] = compiledArgs;
3032
+ return `VECTOR_DISTANCE('${metric}', ${v1}, ${v2})`;
3033
+ });
2965
3034
  }
2966
3035
  };
2967
3036
 
@@ -13411,6 +13480,50 @@ var fn7 = (key, args) => ({
13411
13480
  var afn3 = (key, args) => asType(fn7(key, args));
13412
13481
  var arrayAppend = (array, value) => afn3("ARRAY_APPEND", [array, value]);
13413
13482
 
13483
+ // src/core/functions/vector.ts
13484
+ var isColumnDef7 = (val) => !!val && typeof val === "object" && "type" in val && "name" in val;
13485
+ var toOperand8 = (input) => {
13486
+ if (isOperandNode(input)) return input;
13487
+ if (isColumnDef7(input)) return columnOperand(input);
13488
+ if (Array.isArray(input) || input instanceof Float32Array) {
13489
+ const formatted = `[${Array.from(input).join(", ")}]`;
13490
+ return valueToOperand(formatted);
13491
+ }
13492
+ return valueToOperand(input);
13493
+ };
13494
+ var fn8 = (key, args) => ({
13495
+ type: "Function",
13496
+ name: key,
13497
+ fn: key,
13498
+ args
13499
+ });
13500
+ var vectorDistance = (metric, v1, v2) => {
13501
+ const metricOp = valueToOperand(metric.toLowerCase());
13502
+ return asType(fn8("VECTOR_DISTANCE", [metricOp, toOperand8(v1), toOperand8(v2)]));
13503
+ };
13504
+ var cosineDistance = (v1, v2) => vectorDistance("cosine", v1, v2);
13505
+ var l2Distance = (v1, v2) => vectorDistance("euclidean", v1, v2);
13506
+ var euclideanDistance = (v1, v2) => vectorDistance("euclidean", v1, v2);
13507
+ var innerProduct = (v1, v2) => vectorDistance("dot", v1, v2);
13508
+ var dotProduct = (v1, v2) => vectorDistance("dot", v1, v2);
13509
+ var l1Distance = (v1, v2) => vectorDistance("manhattan", v1, v2);
13510
+ var manhattanDistance = (v1, v2) => vectorDistance("manhattan", v1, v2);
13511
+ var vectorMatch = (column, vector, k) => {
13512
+ const match = {
13513
+ type: "BinaryExpression",
13514
+ left: toOperand8(column),
13515
+ operator: "MATCH",
13516
+ right: toOperand8(vector)
13517
+ };
13518
+ const kNode = {
13519
+ type: "BinaryExpression",
13520
+ left: valueToOperand("k"),
13521
+ operator: "=",
13522
+ right: valueToOperand(k)
13523
+ };
13524
+ return { type: "LogicalExpression", operator: "AND", operands: [match, kNode] };
13525
+ };
13526
+
13414
13527
  // src/orm/als.ts
13415
13528
  var AsyncLocalStorage = class {
13416
13529
  store;
@@ -13726,12 +13839,12 @@ var TypeScriptGenerator = class {
13726
13839
  printBinaryExpression(binary) {
13727
13840
  const left2 = this.printOperand(binary.left);
13728
13841
  const right2 = this.printOperand(binary.right);
13729
- const fn8 = this.mapOp(binary.operator);
13842
+ const fn9 = this.mapOp(binary.operator);
13730
13843
  const args = [left2, right2];
13731
13844
  if (binary.escape) {
13732
13845
  args.push(this.printOperand(binary.escape));
13733
13846
  }
13734
- return `${fn8}(${args.join(", ")})`;
13847
+ return `${fn9}(${args.join(", ")})`;
13735
13848
  }
13736
13849
  /**
13737
13850
  * Prints a logical expression to TypeScript code
@@ -13763,13 +13876,13 @@ var TypeScriptGenerator = class {
13763
13876
  */
13764
13877
  printInExpression(inExpr) {
13765
13878
  const left2 = this.printOperand(inExpr.left);
13766
- const fn8 = this.mapOp(inExpr.operator);
13879
+ const fn9 = this.mapOp(inExpr.operator);
13767
13880
  if (Array.isArray(inExpr.right)) {
13768
13881
  const values = inExpr.right.map((v) => this.printOperand(v)).join(", ");
13769
- return `${fn8}(${left2}, [${values}])`;
13882
+ return `${fn9}(${left2}, [${values}])`;
13770
13883
  }
13771
13884
  const subquery = this.inlineChain(this.buildSelectLines(inExpr.right.query));
13772
- return `${fn8}(${left2}, (${subquery}))`;
13885
+ return `${fn9}(${left2}, (${subquery}))`;
13773
13886
  }
13774
13887
  /**
13775
13888
  * Prints a null expression to TypeScript code
@@ -13778,8 +13891,8 @@ var TypeScriptGenerator = class {
13778
13891
  */
13779
13892
  printNullExpression(nullExpr) {
13780
13893
  const left2 = this.printOperand(nullExpr.left);
13781
- const fn8 = this.mapOp(nullExpr.operator);
13782
- return `${fn8}(${left2})`;
13894
+ const fn9 = this.mapOp(nullExpr.operator);
13895
+ return `${fn9}(${left2})`;
13783
13896
  }
13784
13897
  /**
13785
13898
  * Prints a BETWEEN expression to TypeScript code
@@ -13823,9 +13936,9 @@ var TypeScriptGenerator = class {
13823
13936
  * @param fn - Function node
13824
13937
  * @returns TypeScript code representation
13825
13938
  */
13826
- printFunctionOperand(fn8) {
13827
- const args = fn8.args.map((a) => this.printOperand(a)).join(", ");
13828
- return `${fn8.name.toLowerCase()}(${args})`;
13939
+ printFunctionOperand(fn9) {
13940
+ const args = fn9.args.map((a) => this.printOperand(a)).join(", ");
13941
+ return `${fn9.name.toLowerCase()}(${args})`;
13829
13942
  }
13830
13943
  /**
13831
13944
  * Prints a JSON path operand to TypeScript code
@@ -15440,9 +15553,9 @@ var OrmSession = class {
15440
15553
  * @returns The result of the function
15441
15554
  * @throws If the transaction fails
15442
15555
  */
15443
- async transaction(fn8) {
15556
+ async transaction(fn9) {
15444
15557
  if (!this.executor.capabilities.transactions) {
15445
- const result = await fn8(this);
15558
+ const result = await fn9(this);
15446
15559
  await this.commit();
15447
15560
  return result;
15448
15561
  }
@@ -15458,7 +15571,7 @@ var OrmSession = class {
15458
15571
  }
15459
15572
  this.transactionDepth += 1;
15460
15573
  try {
15461
- const result = await fn8(this);
15574
+ const result = await fn9(this);
15462
15575
  this.throwIfRollbackOnly();
15463
15576
  await this.flushWithHooks();
15464
15577
  this.throwIfRollbackOnly();
@@ -15972,7 +16085,7 @@ var Orm = class {
15972
16085
  * @returns The result of the function
15973
16086
  * @throws If the transaction fails
15974
16087
  */
15975
- async transaction(fn8) {
16088
+ async transaction(fn9) {
15976
16089
  const executor = this.executorFactory.createTransactionalExecutor();
15977
16090
  const session = new OrmSession({
15978
16091
  orm: this,
@@ -15980,7 +16093,7 @@ var Orm = class {
15980
16093
  cacheManager: this.cacheManager
15981
16094
  });
15982
16095
  try {
15983
- return await session.transaction(() => fn8(session));
16096
+ return await session.transaction(() => fn9(session));
15984
16097
  } finally {
15985
16098
  await session.dispose();
15986
16099
  }
@@ -21269,10 +21382,10 @@ async function runChunk(task, chunkIndex, totalChunks, rowsInChunk, timing, onCh
21269
21382
  }
21270
21383
  return result;
21271
21384
  }
21272
- async function maybeTransaction(session, transactional, fn8) {
21273
- if (!transactional) return fn8();
21385
+ async function maybeTransaction(session, transactional, fn9) {
21386
+ if (!transactional) return fn9();
21274
21387
  const ormSession = session;
21275
- return ormSession.transaction(fn8);
21388
+ return ormSession.transaction(fn9);
21276
21389
  }
21277
21390
  function aggregateOutcomes(outcomes) {
21278
21391
  const result = {
@@ -21738,6 +21851,7 @@ export {
21738
21851
  concatWs,
21739
21852
  correlateBy,
21740
21853
  cos,
21854
+ cosineDistance,
21741
21855
  cot,
21742
21856
  count,
21743
21857
  countAll,
@@ -21774,12 +21888,14 @@ export {
21774
21888
  denseRank,
21775
21889
  diffSchema,
21776
21890
  div,
21891
+ dotProduct,
21777
21892
  dtoToOpenApiSchema,
21778
21893
  endOfMonth,
21779
21894
  entityRef,
21780
21895
  entityRefs,
21781
21896
  eq,
21782
21897
  esel,
21898
+ euclideanDistance,
21783
21899
  exclude,
21784
21900
  executeFilteredPaged,
21785
21901
  executeHydrated,
@@ -21837,6 +21953,7 @@ export {
21837
21953
  inList,
21838
21954
  inSubquery,
21839
21955
  initcap,
21956
+ innerProduct,
21840
21957
  insertInto,
21841
21958
  instr,
21842
21959
  introspectSchema,
@@ -21865,6 +21982,8 @@ export {
21865
21982
  jsonPath,
21866
21983
  jsonSet,
21867
21984
  jsonify,
21985
+ l1Distance,
21986
+ l2Distance,
21868
21987
  lag,
21869
21988
  lastValue,
21870
21989
  lead,
@@ -21892,6 +22011,7 @@ export {
21892
22011
  lt,
21893
22012
  lte,
21894
22013
  ltrim,
22014
+ manhattanDistance,
21895
22015
  mapFields,
21896
22016
  materializeAs,
21897
22017
  max,
@@ -22011,6 +22131,8 @@ export {
22011
22131
  validateTreeTable,
22012
22132
  valueToOperand,
22013
22133
  variance,
22134
+ vectorDistance,
22135
+ vectorMatch,
22014
22136
  visitExpression,
22015
22137
  visitOperand,
22016
22138
  weekOfYear,