pqb 0.34.0 → 0.35.0

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.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { ExpressionTypeMethod, Expression, RawSQLBase, emptyObject, isTemplateLiteralArgs, ColumnTypeBase, setColumnData, pushColumnData, quoteObjectKey, toArray, singleQuote, addCode, singleQuoteArray, objectHasValues, columnDefaultArgumentToCode, columnErrorMessagesToCode, getValueKey, addValue, isExpression, joinTruthy, numberDataToCode, stringDataToCode, getDefaultLanguage, dateDataToCode, pushOrNewArrayToObject, returnArg as returnArg$1, noop, arrayDataToCode, emptyArray, callWithThis, applyTransforms, setParserToQuery, isRawSQL, pushOrNewArray, setDefaultNowFn, setDefaultLanguage, makeTimestampsHelpers, setCurrentColumnName, setAdapterConnectRetry, isObjectEmpty, ValExpression, applyMixins, toSnakeCase, snakeCaseKey } from 'orchid-core';
1
+ import { ExpressionTypeMethod, Expression, RawSQLBase, emptyObject, isTemplateLiteralArgs, ColumnTypeBase, setColumnData, pushColumnData, quoteObjectKey, toArray, singleQuote, addCode, singleQuoteArray, objectHasValues, columnDefaultArgumentToCode, columnErrorMessagesToCode, getValueKey, addValue, isExpression, joinTruthy, numberDataToCode, stringDataToCode, getDefaultLanguage, dateDataToCode, pushOrNewArrayToObject, returnArg as returnArg$1, noop, arrayDataToCode, emptyArray, applyTransforms, callWithThis, setParserToQuery, isRawSQL, pushOrNewArray, setDefaultNowFn, setDefaultLanguage, makeTimestampsHelpers, setCurrentColumnName, setAdapterConnectRetry, isObjectEmpty, ValExpression, applyMixins, toSnakeCase, snakeCaseKey } from 'orchid-core';
2
2
  import pg from 'pg';
3
3
  import { inspect } from 'node:util';
4
4
  import { AsyncLocalStorage } from 'node:async_hooks';
@@ -88,7 +88,7 @@ class DynamicRawSQL extends Expression {
88
88
  super();
89
89
  this.fn = fn;
90
90
  this.result = emptyObject;
91
- this.q = {};
91
+ this.q = { expr: this };
92
92
  }
93
93
  // Calls the given function to get SQL from it.
94
94
  makeSQL(ctx, quotedAs) {
@@ -117,21 +117,21 @@ const sqlFn = (...args) => {
117
117
  return (...args2) => new RawSQL(args2, arg);
118
118
  };
119
119
 
120
- var __defProp$h = Object.defineProperty;
120
+ var __defProp$i = Object.defineProperty;
121
121
  var __defProps$9 = Object.defineProperties;
122
122
  var __getOwnPropDescs$9 = Object.getOwnPropertyDescriptors;
123
- var __getOwnPropSymbols$i = Object.getOwnPropertySymbols;
124
- var __hasOwnProp$i = Object.prototype.hasOwnProperty;
125
- var __propIsEnum$i = Object.prototype.propertyIsEnumerable;
126
- var __defNormalProp$h = (obj, key, value) => key in obj ? __defProp$h(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
127
- var __spreadValues$h = (a, b) => {
123
+ var __getOwnPropSymbols$j = Object.getOwnPropertySymbols;
124
+ var __hasOwnProp$j = Object.prototype.hasOwnProperty;
125
+ var __propIsEnum$j = Object.prototype.propertyIsEnumerable;
126
+ var __defNormalProp$i = (obj, key, value) => key in obj ? __defProp$i(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
127
+ var __spreadValues$i = (a, b) => {
128
128
  for (var prop in b || (b = {}))
129
- if (__hasOwnProp$i.call(b, prop))
130
- __defNormalProp$h(a, prop, b[prop]);
131
- if (__getOwnPropSymbols$i)
132
- for (var prop of __getOwnPropSymbols$i(b)) {
133
- if (__propIsEnum$i.call(b, prop))
134
- __defNormalProp$h(a, prop, b[prop]);
129
+ if (__hasOwnProp$j.call(b, prop))
130
+ __defNormalProp$i(a, prop, b[prop]);
131
+ if (__getOwnPropSymbols$j)
132
+ for (var prop of __getOwnPropSymbols$j(b)) {
133
+ if (__propIsEnum$j.call(b, prop))
134
+ __defNormalProp$i(a, prop, b[prop]);
135
135
  }
136
136
  return a;
137
137
  };
@@ -334,13 +334,13 @@ class ColumnType extends ColumnTypeBase {
334
334
  */
335
335
  searchIndex(...args) {
336
336
  return pushColumnData(this, "indexes", {
337
- options: __spreadValues$h(__spreadValues$h({}, typeof args[0] === "string" ? args[1] : args[0]), this.dataType === "tsvector" ? { using: "GIN" } : { tsVector: true }),
337
+ options: __spreadValues$i(__spreadValues$i({}, typeof args[0] === "string" ? args[1] : args[0]), this.dataType === "tsvector" ? { using: "GIN" } : { tsVector: true }),
338
338
  name: typeof args[0] === "string" ? args[0] : void 0
339
339
  });
340
340
  }
341
341
  unique(...args) {
342
342
  return pushColumnData(this, "indexes", {
343
- options: __spreadProps$9(__spreadValues$h({}, typeof args[0] === "string" ? args[1] : args[0]), {
343
+ options: __spreadProps$9(__spreadValues$i({}, typeof args[0] === "string" ? args[1] : args[0]), {
344
344
  unique: true
345
345
  }),
346
346
  name: typeof args[0] === "string" ? args[0] : void 0
@@ -382,21 +382,21 @@ class ColumnType extends ColumnTypeBase {
382
382
  }
383
383
  }
384
384
 
385
- var __defProp$g = Object.defineProperty;
385
+ var __defProp$h = Object.defineProperty;
386
386
  var __defProps$8 = Object.defineProperties;
387
387
  var __getOwnPropDescs$8 = Object.getOwnPropertyDescriptors;
388
- var __getOwnPropSymbols$h = Object.getOwnPropertySymbols;
389
- var __hasOwnProp$h = Object.prototype.hasOwnProperty;
390
- var __propIsEnum$h = Object.prototype.propertyIsEnumerable;
391
- var __defNormalProp$g = (obj, key, value) => key in obj ? __defProp$g(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
392
- var __spreadValues$g = (a, b) => {
388
+ var __getOwnPropSymbols$i = Object.getOwnPropertySymbols;
389
+ var __hasOwnProp$i = Object.prototype.hasOwnProperty;
390
+ var __propIsEnum$i = Object.prototype.propertyIsEnumerable;
391
+ var __defNormalProp$h = (obj, key, value) => key in obj ? __defProp$h(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
392
+ var __spreadValues$h = (a, b) => {
393
393
  for (var prop in b || (b = {}))
394
- if (__hasOwnProp$h.call(b, prop))
395
- __defNormalProp$g(a, prop, b[prop]);
396
- if (__getOwnPropSymbols$h)
397
- for (var prop of __getOwnPropSymbols$h(b)) {
398
- if (__propIsEnum$h.call(b, prop))
399
- __defNormalProp$g(a, prop, b[prop]);
394
+ if (__hasOwnProp$i.call(b, prop))
395
+ __defNormalProp$h(a, prop, b[prop]);
396
+ if (__getOwnPropSymbols$i)
397
+ for (var prop of __getOwnPropSymbols$i(b)) {
398
+ if (__propIsEnum$i.call(b, prop))
399
+ __defNormalProp$h(a, prop, b[prop]);
400
400
  }
401
401
  return a;
402
402
  };
@@ -416,7 +416,7 @@ const simplifyColumnDefault = (value) => {
416
416
  const instantiateColumn = (typeFn, params) => {
417
417
  const column = typeFn();
418
418
  const { dateTimePrecision } = params;
419
- Object.assign(column.data, __spreadProps$8(__spreadValues$g({}, params), {
419
+ Object.assign(column.data, __spreadProps$8(__spreadValues$h({}, params), {
420
420
  dateTimePrecision: (
421
421
  // 0 is default for date, 6 is default for timestamp
422
422
  dateTimePrecision && dateTimePrecision !== 6 ? dateTimePrecision : void 0
@@ -840,21 +840,21 @@ const getSqlText = (sql) => {
840
840
  throw new Error(`Batch SQL is not supported in this query`);
841
841
  };
842
842
 
843
- var __defProp$f = Object.defineProperty;
843
+ var __defProp$g = Object.defineProperty;
844
844
  var __defProps$7 = Object.defineProperties;
845
845
  var __getOwnPropDescs$7 = Object.getOwnPropertyDescriptors;
846
- var __getOwnPropSymbols$g = Object.getOwnPropertySymbols;
847
- var __hasOwnProp$g = Object.prototype.hasOwnProperty;
848
- var __propIsEnum$g = Object.prototype.propertyIsEnumerable;
849
- var __defNormalProp$f = (obj, key, value) => key in obj ? __defProp$f(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
850
- var __spreadValues$f = (a, b) => {
846
+ var __getOwnPropSymbols$h = Object.getOwnPropertySymbols;
847
+ var __hasOwnProp$h = Object.prototype.hasOwnProperty;
848
+ var __propIsEnum$h = Object.prototype.propertyIsEnumerable;
849
+ var __defNormalProp$g = (obj, key, value) => key in obj ? __defProp$g(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
850
+ var __spreadValues$g = (a, b) => {
851
851
  for (var prop in b || (b = {}))
852
- if (__hasOwnProp$g.call(b, prop))
853
- __defNormalProp$f(a, prop, b[prop]);
854
- if (__getOwnPropSymbols$g)
855
- for (var prop of __getOwnPropSymbols$g(b)) {
856
- if (__propIsEnum$g.call(b, prop))
857
- __defNormalProp$f(a, prop, b[prop]);
852
+ if (__hasOwnProp$h.call(b, prop))
853
+ __defNormalProp$g(a, prop, b[prop]);
854
+ if (__getOwnPropSymbols$h)
855
+ for (var prop of __getOwnPropSymbols$h(b)) {
856
+ if (__propIsEnum$h.call(b, prop))
857
+ __defNormalProp$g(a, prop, b[prop]);
858
858
  }
859
859
  return a;
860
860
  };
@@ -931,7 +931,7 @@ const base = {
931
931
  (key, value, ctx, quotedAs) => `NOT ${key} IN ${quoteValue$1(value, ctx, quotedAs)}`
932
932
  )
933
933
  };
934
- const boolean = __spreadProps$7(__spreadValues$f({}, base), {
934
+ const boolean = __spreadProps$7(__spreadValues$g({}, base), {
935
935
  and: make(
936
936
  (key, value, ctx, quotedAs) => `${key} AND ${value.q.expr.toSQL(ctx, quotedAs)}`
937
937
  ),
@@ -939,7 +939,7 @@ const boolean = __spreadProps$7(__spreadValues$f({}, base), {
939
939
  (key, value, ctx, quotedAs) => `(${key}) OR (${value.q.expr.toSQL(ctx, quotedAs)})`
940
940
  )
941
941
  });
942
- const numeric = __spreadProps$7(__spreadValues$f({}, base), {
942
+ const numeric = __spreadProps$7(__spreadValues$g({}, base), {
943
943
  lt: make(
944
944
  (key, value, ctx, quotedAs) => `${key} < ${quoteValue$1(value, ctx, quotedAs)}`
945
945
  ),
@@ -960,7 +960,7 @@ const numeric = __spreadProps$7(__spreadValues$f({}, base), {
960
960
  )}`
961
961
  )
962
962
  });
963
- const text = __spreadProps$7(__spreadValues$f({}, base), {
963
+ const text = __spreadProps$7(__spreadValues$g({}, base), {
964
964
  contains: make(
965
965
  (key, value, ctx, quotedAs) => `${key} ILIKE '%' || ${quoteValue$1(value, ctx, quotedAs)} || '%'`
966
966
  ),
@@ -982,7 +982,7 @@ const text = __spreadProps$7(__spreadValues$f({}, base), {
982
982
  });
983
983
  const encodeJsonPath = (ctx, path) => addValue(ctx.values, `{${Array.isArray(path) ? path.join(", ") : path}}`);
984
984
  const jsonPathQueryOp = (key, [path, options], ctx) => `jsonb_path_query_first(${key}, ${addValue(ctx.values, path)}${(options == null ? void 0 : options.vars) ? `, ${addValue(ctx.values, JSON.stringify(options.vars))}${options.silent ? ", true" : ""}` : (options == null ? void 0 : options.silent) ? ", NULL, true" : ""})`;
985
- const json = __spreadProps$7(__spreadValues$f({}, base), {
985
+ const json = __spreadProps$7(__spreadValues$g({}, base), {
986
986
  jsonPathQueryFirst: Object.assign(
987
987
  function(path, options) {
988
988
  var _a, _b, _c, _d, _e;
@@ -1209,21 +1209,21 @@ class BigSerialColumn extends NumberAsStringBaseColumn {
1209
1209
  }
1210
1210
  }
1211
1211
 
1212
- var __defProp$e = Object.defineProperty;
1212
+ var __defProp$f = Object.defineProperty;
1213
1213
  var __defProps$6 = Object.defineProperties;
1214
1214
  var __getOwnPropDescs$6 = Object.getOwnPropertyDescriptors;
1215
- var __getOwnPropSymbols$f = Object.getOwnPropertySymbols;
1216
- var __hasOwnProp$f = Object.prototype.hasOwnProperty;
1217
- var __propIsEnum$f = Object.prototype.propertyIsEnumerable;
1218
- var __defNormalProp$e = (obj, key, value) => key in obj ? __defProp$e(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1219
- var __spreadValues$e = (a, b) => {
1215
+ var __getOwnPropSymbols$g = Object.getOwnPropertySymbols;
1216
+ var __hasOwnProp$g = Object.prototype.hasOwnProperty;
1217
+ var __propIsEnum$g = Object.prototype.propertyIsEnumerable;
1218
+ var __defNormalProp$f = (obj, key, value) => key in obj ? __defProp$f(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1219
+ var __spreadValues$f = (a, b) => {
1220
1220
  for (var prop in b || (b = {}))
1221
- if (__hasOwnProp$f.call(b, prop))
1222
- __defNormalProp$e(a, prop, b[prop]);
1223
- if (__getOwnPropSymbols$f)
1224
- for (var prop of __getOwnPropSymbols$f(b)) {
1225
- if (__propIsEnum$f.call(b, prop))
1226
- __defNormalProp$e(a, prop, b[prop]);
1221
+ if (__hasOwnProp$g.call(b, prop))
1222
+ __defNormalProp$f(a, prop, b[prop]);
1223
+ if (__getOwnPropSymbols$g)
1224
+ for (var prop of __getOwnPropSymbols$g(b)) {
1225
+ if (__propIsEnum$g.call(b, prop))
1226
+ __defNormalProp$f(a, prop, b[prop]);
1227
1227
  }
1228
1228
  return a;
1229
1229
  };
@@ -1275,7 +1275,7 @@ class StringColumn extends VarCharColumn {
1275
1275
  }
1276
1276
  }
1277
1277
  const textColumnToCode = (column, t, m) => {
1278
- const data = __spreadValues$e({}, column.data);
1278
+ const data = __spreadValues$f({}, column.data);
1279
1279
  let args = "";
1280
1280
  const hasMax = data.maxArg !== void 0 && data.max === data.maxArg;
1281
1281
  if (data.minArg !== void 0 && data.min === data.minArg || hasMax) {
@@ -1572,7 +1572,7 @@ class UUIDColumn extends ColumnType {
1572
1572
  `uuid()`,
1573
1573
  m,
1574
1574
  // don't output the default default
1575
- data.default instanceof RawSQLBase && data.default._sql === uuidDefaultSQL ? __spreadProps$6(__spreadValues$e({}, data), { default: void 0 }) : data
1575
+ data.default instanceof RawSQLBase && data.default._sql === uuidDefaultSQL ? __spreadProps$6(__spreadValues$f({}, data), { default: void 0 }) : data
1576
1576
  );
1577
1577
  }
1578
1578
  }
@@ -1868,31 +1868,41 @@ const columnWithDotToSql = (ctx, data, shape, column, index, quotedAs, select) =
1868
1868
  return `"${tableName}"."${key}"`;
1869
1869
  };
1870
1870
  const columnToSqlWithAs = (ctx, data, column, quotedAs, select) => {
1871
- var _a, _b, _c, _d;
1872
1871
  const index = column.indexOf(".");
1873
- if (index !== -1) {
1874
- const table = column.slice(0, index);
1875
- const key = column.slice(index + 1);
1876
- if (key === "*") {
1877
- if ((_a = data.joinedShapes) == null ? void 0 : _a[table]) {
1878
- return select ? `row_to_json("${table}".*) "${table}"` : `"${table}".r "${table}"`;
1879
- }
1880
- return column;
1872
+ return index !== -1 ? tableColumnToSqlWithAs(
1873
+ ctx,
1874
+ data,
1875
+ column,
1876
+ column.slice(0, index),
1877
+ column.slice(index + 1),
1878
+ quotedAs,
1879
+ select
1880
+ ) : ownColumnToSqlWithAs(ctx, data, column, quotedAs, select);
1881
+ };
1882
+ const tableColumnToSqlWithAs = (ctx, data, column, table, key, quotedAs, select) => {
1883
+ var _a, _b, _c;
1884
+ if (key === "*") {
1885
+ if ((_a = data.joinedShapes) == null ? void 0 : _a[table]) {
1886
+ return select ? `row_to_json("${table}".*) "${table}"` : `"${table}".r "${table}"`;
1881
1887
  }
1882
- const tableName = ((_b = data.joinOverrides) == null ? void 0 : _b[table]) || table;
1883
- const quoted = `"${table}"`;
1884
- const col2 = quoted === quotedAs ? data.shape[key] : (_c = data.joinedShapes) == null ? void 0 : _c[tableName][key];
1885
- if (col2) {
1886
- if (col2.data.name && col2.data.name !== key) {
1887
- return `"${tableName}"."${col2.data.name}" "${key}"`;
1888
- }
1889
- if (col2.data.computed) {
1890
- return `${col2.data.computed.toSQL(ctx, quoted)} "${key}"`;
1891
- }
1888
+ return column;
1889
+ }
1890
+ const tableName = ((_b = data.joinOverrides) == null ? void 0 : _b[table]) || table;
1891
+ const quoted = `"${table}"`;
1892
+ const col = quoted === quotedAs ? data.shape[key] : (_c = data.joinedShapes) == null ? void 0 : _c[tableName][key];
1893
+ if (col) {
1894
+ if (col.data.name && col.data.name !== key) {
1895
+ return `"${tableName}"."${col.data.name}" "${key}"`;
1896
+ }
1897
+ if (col.data.computed) {
1898
+ return `${col.data.computed.toSQL(ctx, quoted)} "${key}"`;
1892
1899
  }
1893
- return `"${tableName}"."${key}"`;
1894
1900
  }
1895
- if (!select && ((_d = data.joinedShapes) == null ? void 0 : _d[column])) {
1901
+ return `"${tableName}"."${key}"`;
1902
+ };
1903
+ const ownColumnToSqlWithAs = (ctx, data, column, quotedAs, select) => {
1904
+ var _a;
1905
+ if (!select && ((_a = data.joinedShapes) == null ? void 0 : _a[column])) {
1896
1906
  return select ? `row_to_json("${column}".*) "${column}"` : `"${column}".r "${column}"`;
1897
1907
  }
1898
1908
  const col = data.shape[column];
@@ -1906,11 +1916,6 @@ const columnToSqlWithAs = (ctx, data, column, quotedAs, select) => {
1906
1916
  }
1907
1917
  return `${quotedAs ? `${quotedAs}.` : ""}"${column}"`;
1908
1918
  };
1909
- const ownColumnToSql = (data, column, quotedAs) => {
1910
- var _a;
1911
- const name = (_a = data.shape[column]) == null ? void 0 : _a.data.name;
1912
- return `${quotedAs ? `${quotedAs}.` : ""}"${name || column}"${name && name !== column ? ` "${column}"` : ""}`;
1913
- };
1914
1919
  const rawOrColumnToSql = (ctx, data, expr, quotedAs, shape = data.shape, select) => {
1915
1920
  return typeof expr === "string" ? columnToSql(ctx, data, shape, expr, quotedAs, select) : expr.toSQL(ctx, quotedAs);
1916
1921
  };
@@ -2312,21 +2317,21 @@ const pushIn = (ctx, query, ands, quotedAs, arg) => {
2312
2317
  ands.push(`${multiple ? `(${columnsSql})` : columnsSql} IN ${value}`);
2313
2318
  };
2314
2319
 
2315
- var __defProp$d = Object.defineProperty;
2320
+ var __defProp$e = Object.defineProperty;
2316
2321
  var __defProps$5 = Object.defineProperties;
2317
2322
  var __getOwnPropDescs$5 = Object.getOwnPropertyDescriptors;
2318
- var __getOwnPropSymbols$e = Object.getOwnPropertySymbols;
2319
- var __hasOwnProp$e = Object.prototype.hasOwnProperty;
2320
- var __propIsEnum$e = Object.prototype.propertyIsEnumerable;
2321
- var __defNormalProp$d = (obj, key, value) => key in obj ? __defProp$d(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
2322
- var __spreadValues$d = (a, b) => {
2323
+ var __getOwnPropSymbols$f = Object.getOwnPropertySymbols;
2324
+ var __hasOwnProp$f = Object.prototype.hasOwnProperty;
2325
+ var __propIsEnum$f = Object.prototype.propertyIsEnumerable;
2326
+ var __defNormalProp$e = (obj, key, value) => key in obj ? __defProp$e(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
2327
+ var __spreadValues$e = (a, b) => {
2323
2328
  for (var prop in b || (b = {}))
2324
- if (__hasOwnProp$e.call(b, prop))
2325
- __defNormalProp$d(a, prop, b[prop]);
2326
- if (__getOwnPropSymbols$e)
2327
- for (var prop of __getOwnPropSymbols$e(b)) {
2328
- if (__propIsEnum$e.call(b, prop))
2329
- __defNormalProp$d(a, prop, b[prop]);
2329
+ if (__hasOwnProp$f.call(b, prop))
2330
+ __defNormalProp$e(a, prop, b[prop]);
2331
+ if (__getOwnPropSymbols$f)
2332
+ for (var prop of __getOwnPropSymbols$f(b)) {
2333
+ if (__propIsEnum$f.call(b, prop))
2334
+ __defNormalProp$e(a, prop, b[prop]);
2330
2335
  }
2331
2336
  return a;
2332
2337
  };
@@ -2392,8 +2397,8 @@ const processJoinItem = (ctx, table, query, args, quotedAs) => {
2392
2397
  const whereSql = whereToSql(
2393
2398
  ctx,
2394
2399
  q,
2395
- __spreadProps$5(__spreadValues$d({}, q.q), {
2396
- joinedShapes: __spreadProps$5(__spreadValues$d(__spreadValues$d({}, query.joinedShapes), q.q.joinedShapes), {
2400
+ __spreadProps$5(__spreadValues$e({}, q.q), {
2401
+ joinedShapes: __spreadProps$5(__spreadValues$e(__spreadValues$e({}, query.joinedShapes), q.q.joinedShapes), {
2397
2402
  [table.q.as || table.table]: table.q.shape
2398
2403
  })
2399
2404
  }),
@@ -2540,21 +2545,21 @@ const getIsJoinSubQuery = (query) => {
2540
2545
  return false;
2541
2546
  };
2542
2547
 
2543
- var __defProp$c = Object.defineProperty;
2548
+ var __defProp$d = Object.defineProperty;
2544
2549
  var __defProps$4 = Object.defineProperties;
2545
2550
  var __getOwnPropDescs$4 = Object.getOwnPropertyDescriptors;
2546
- var __getOwnPropSymbols$d = Object.getOwnPropertySymbols;
2547
- var __hasOwnProp$d = Object.prototype.hasOwnProperty;
2548
- var __propIsEnum$d = Object.prototype.propertyIsEnumerable;
2549
- var __defNormalProp$c = (obj, key, value) => key in obj ? __defProp$c(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
2550
- var __spreadValues$c = (a, b) => {
2551
+ var __getOwnPropSymbols$e = Object.getOwnPropertySymbols;
2552
+ var __hasOwnProp$e = Object.prototype.hasOwnProperty;
2553
+ var __propIsEnum$e = Object.prototype.propertyIsEnumerable;
2554
+ var __defNormalProp$d = (obj, key, value) => key in obj ? __defProp$d(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
2555
+ var __spreadValues$d = (a, b) => {
2551
2556
  for (var prop in b || (b = {}))
2552
- if (__hasOwnProp$d.call(b, prop))
2553
- __defNormalProp$c(a, prop, b[prop]);
2554
- if (__getOwnPropSymbols$d)
2555
- for (var prop of __getOwnPropSymbols$d(b)) {
2556
- if (__propIsEnum$d.call(b, prop))
2557
- __defNormalProp$c(a, prop, b[prop]);
2557
+ if (__hasOwnProp$e.call(b, prop))
2558
+ __defNormalProp$d(a, prop, b[prop]);
2559
+ if (__getOwnPropSymbols$e)
2560
+ for (var prop of __getOwnPropSymbols$e(b)) {
2561
+ if (__propIsEnum$e.call(b, prop))
2562
+ __defNormalProp$d(a, prop, b[prop]);
2558
2563
  }
2559
2564
  return a;
2560
2565
  };
@@ -2576,27 +2581,28 @@ const processJoinArgs = (joinTo, first, args, joinSubQuery) => {
2576
2581
  return { w: first, a: args };
2577
2582
  } else {
2578
2583
  const joinToQ = joinTo.q;
2579
- const shape = (_a = joinToQ.withShapes) == null ? void 0 : _a[first];
2580
- if (!shape) {
2581
- throw new Error("Cannot get shape of `with` statement");
2584
+ const w = (_a = joinToQ.withShapes) == null ? void 0 : _a[first];
2585
+ if (!w) {
2586
+ throw new Error("Cannot find a `with` statement");
2582
2587
  }
2583
2588
  const j = joinTo.queryBuilder.baseQuery.clone();
2584
2589
  j.table = first;
2585
2590
  j.q = {
2586
- shape,
2591
+ shape: w.shape,
2592
+ computeds: w.computeds,
2587
2593
  adapter: joinToQ.adapter,
2588
2594
  handleResult: joinToQ.handleResult,
2589
2595
  returnType: "all",
2590
2596
  logger: joinToQ.logger
2591
2597
  };
2592
2598
  j.baseQuery = j;
2593
- const joinedShapes = __spreadProps$4(__spreadValues$c({}, joinToQ.joinedShapes), {
2599
+ const joinedShapes = __spreadProps$4(__spreadValues$d({}, joinToQ.joinedShapes), {
2594
2600
  [joinToQ.as || joinTo.table]: joinTo.shape
2595
2601
  });
2596
2602
  const r = args[0](
2597
2603
  makeJoinQueryBuilder(
2598
2604
  j,
2599
- j.q.joinedShapes ? __spreadValues$c(__spreadValues$c({}, j.q.joinedShapes), joinedShapes) : joinedShapes,
2605
+ j.q.joinedShapes ? __spreadValues$d(__spreadValues$d({}, j.q.joinedShapes), joinedShapes) : joinedShapes,
2600
2606
  joinTo
2601
2607
  )
2602
2608
  );
@@ -2619,16 +2625,16 @@ const processJoinArgs = (joinTo, first, args, joinSubQuery) => {
2619
2625
  pushQueryArray(q, "or", query.or);
2620
2626
  }
2621
2627
  if (query.scopes) {
2622
- q.q.scopes = __spreadValues$c(__spreadValues$c({}, q.q.scopes), query.scopes);
2628
+ q.q.scopes = __spreadValues$d(__spreadValues$d({}, q.q.scopes), query.scopes);
2623
2629
  }
2624
2630
  }
2625
- const joinedShapes = __spreadProps$4(__spreadValues$c({}, joinTo.q.joinedShapes), {
2631
+ const joinedShapes = __spreadProps$4(__spreadValues$d({}, joinTo.q.joinedShapes), {
2626
2632
  [joinTo.q.as || joinTo.table]: joinTo.shape
2627
2633
  });
2628
2634
  const r = args0(
2629
2635
  makeJoinQueryBuilder(
2630
2636
  q,
2631
- q.q.joinedShapes ? __spreadValues$c(__spreadValues$c({}, q.q.joinedShapes), joinedShapes) : joinedShapes,
2637
+ q.q.joinedShapes ? __spreadValues$d(__spreadValues$d({}, q.q.joinedShapes), joinedShapes) : joinedShapes,
2632
2638
  joinTo
2633
2639
  )
2634
2640
  );
@@ -2676,30 +2682,32 @@ const _queryNone = (q) => {
2676
2682
  };
2677
2683
  const isQueryNone = (q) => q.then === noneMethods.then;
2678
2684
 
2679
- var __defProp$b = Object.defineProperty;
2685
+ var __defProp$c = Object.defineProperty;
2680
2686
  var __defProps$3 = Object.defineProperties;
2681
2687
  var __getOwnPropDescs$3 = Object.getOwnPropertyDescriptors;
2682
- var __getOwnPropSymbols$c = Object.getOwnPropertySymbols;
2683
- var __hasOwnProp$c = Object.prototype.hasOwnProperty;
2684
- var __propIsEnum$c = Object.prototype.propertyIsEnumerable;
2685
- var __defNormalProp$b = (obj, key, value) => key in obj ? __defProp$b(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
2686
- var __spreadValues$b = (a, b) => {
2688
+ var __getOwnPropSymbols$d = Object.getOwnPropertySymbols;
2689
+ var __hasOwnProp$d = Object.prototype.hasOwnProperty;
2690
+ var __propIsEnum$d = Object.prototype.propertyIsEnumerable;
2691
+ var __defNormalProp$c = (obj, key, value) => key in obj ? __defProp$c(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
2692
+ var __spreadValues$c = (a, b) => {
2687
2693
  for (var prop in b || (b = {}))
2688
- if (__hasOwnProp$c.call(b, prop))
2689
- __defNormalProp$b(a, prop, b[prop]);
2690
- if (__getOwnPropSymbols$c)
2691
- for (var prop of __getOwnPropSymbols$c(b)) {
2692
- if (__propIsEnum$c.call(b, prop))
2693
- __defNormalProp$b(a, prop, b[prop]);
2694
+ if (__hasOwnProp$d.call(b, prop))
2695
+ __defNormalProp$c(a, prop, b[prop]);
2696
+ if (__getOwnPropSymbols$d)
2697
+ for (var prop of __getOwnPropSymbols$d(b)) {
2698
+ if (__propIsEnum$d.call(b, prop))
2699
+ __defNormalProp$c(a, prop, b[prop]);
2694
2700
  }
2695
2701
  return a;
2696
2702
  };
2697
2703
  var __spreadProps$3 = (a, b) => __defProps$3(a, __getOwnPropDescs$3(b));
2698
2704
  const _join = (query, require2, type, first, args) => {
2699
- var _a, _b;
2705
+ var _a, _b, _c, _d;
2700
2706
  let joinKey;
2701
2707
  let shape;
2702
2708
  let parsers;
2709
+ let batchParsers;
2710
+ let computeds;
2703
2711
  let joinSubQuery = false;
2704
2712
  if (typeof first === "function") {
2705
2713
  first = first(query.relations);
@@ -2715,6 +2723,8 @@ const _join = (query, require2, type, first, args) => {
2715
2723
  if (joinKey) {
2716
2724
  shape = getShapeFromSelect(q, joinSubQuery);
2717
2725
  parsers = q.q.parsers;
2726
+ batchParsers = q.q.batchParsers;
2727
+ computeds = q.q.computeds;
2718
2728
  if (joinSubQuery) {
2719
2729
  first = q.clone();
2720
2730
  first.shape = shape;
@@ -2725,12 +2735,17 @@ const _join = (query, require2, type, first, args) => {
2725
2735
  const relation = query.relations[joinKey];
2726
2736
  if (relation) {
2727
2737
  shape = getShapeFromSelect(relation.relationConfig.query);
2728
- parsers = relation.relationConfig.query.q.parsers;
2738
+ const r = relation.relationConfig.query;
2739
+ parsers = r.q.parsers;
2740
+ batchParsers = r.q.batchParsers;
2741
+ computeds = r.q.computeds;
2729
2742
  } else {
2730
- shape = (_a = query.q.withShapes) == null ? void 0 : _a[joinKey];
2743
+ const w = (_a = query.q.withShapes) == null ? void 0 : _a[joinKey];
2744
+ shape = w == null ? void 0 : w.shape;
2745
+ computeds = w == null ? void 0 : w.computeds;
2731
2746
  if (shape) {
2732
2747
  if (!require2)
2733
- shape = __spreadValues$b({}, shape);
2748
+ shape = __spreadValues$c({}, shape);
2734
2749
  parsers = {};
2735
2750
  for (const key in shape) {
2736
2751
  const parser = shape[key].parseFn;
@@ -2741,20 +2756,6 @@ const _join = (query, require2, type, first, args) => {
2741
2756
  }
2742
2757
  }
2743
2758
  }
2744
- if (joinKey) {
2745
- setQueryObjectValue(
2746
- query,
2747
- "joinedShapes",
2748
- joinKey,
2749
- shape
2750
- );
2751
- setQueryObjectValue(
2752
- query,
2753
- "joinedParsers",
2754
- joinKey,
2755
- parsers
2756
- );
2757
- }
2758
2759
  const joinArgs = processJoinArgs(
2759
2760
  query,
2760
2761
  first,
@@ -2777,17 +2778,60 @@ const _join = (query, require2, type, first, args) => {
2777
2778
  joinKey,
2778
2779
  j.q.parsers
2779
2780
  );
2781
+ if (j.q.batchParsers) {
2782
+ ((_d = (_c = query.q).joinedBatchParsers) != null ? _d : _c.joinedBatchParsers = {})[joinKey] = j.q.batchParsers;
2783
+ }
2784
+ setQueryObjectValue(
2785
+ query,
2786
+ "joinedComputeds",
2787
+ joinKey,
2788
+ j.q.computeds
2789
+ );
2790
+ } else {
2791
+ addAllShapesAndParsers(
2792
+ query,
2793
+ joinKey,
2794
+ shape,
2795
+ parsers,
2796
+ batchParsers,
2797
+ computeds
2798
+ );
2780
2799
  }
2781
2800
  } else if (require2 && "r" in joinArgs && isQueryNone(joinArgs.r)) {
2782
2801
  return _queryNone(query);
2802
+ } else {
2803
+ addAllShapesAndParsers(
2804
+ query,
2805
+ joinKey,
2806
+ shape,
2807
+ parsers,
2808
+ batchParsers,
2809
+ computeds
2810
+ );
2783
2811
  }
2784
2812
  return pushQueryValue(query, "join", {
2785
2813
  type,
2786
2814
  args: joinArgs
2787
2815
  });
2788
2816
  };
2817
+ const addAllShapesAndParsers = (query, joinKey, shape, parsers, batchParsers, computeds) => {
2818
+ var _a, _b;
2819
+ if (!joinKey)
2820
+ return;
2821
+ setQueryObjectValue(query, "joinedShapes", joinKey, shape);
2822
+ setQueryObjectValue(query, "joinedParsers", joinKey, parsers);
2823
+ if (batchParsers) {
2824
+ ((_b = (_a = query.q).joinedBatchParsers) != null ? _b : _a.joinedBatchParsers = {})[joinKey] = batchParsers;
2825
+ }
2826
+ setQueryObjectValue(
2827
+ query,
2828
+ "joinedComputeds",
2829
+ joinKey,
2830
+ computeds
2831
+ );
2832
+ };
2789
2833
  const _joinLateral = (self, type, arg, cb, as) => {
2790
- var _a, _b, _c;
2834
+ var _a, _b, _c, _d, _e, _f, _g;
2791
2835
  const q = self;
2792
2836
  let relation;
2793
2837
  if (typeof arg === "string") {
@@ -2795,13 +2839,14 @@ const _joinLateral = (self, type, arg, cb, as) => {
2795
2839
  if (relation) {
2796
2840
  arg = relation.relationConfig.query.clone();
2797
2841
  } else {
2798
- const shape = (_a = q.q.withShapes) == null ? void 0 : _a[arg];
2799
- if (shape) {
2842
+ const w = (_a = q.q.withShapes) == null ? void 0 : _a[arg];
2843
+ if (w) {
2800
2844
  const t = Object.create(q.queryBuilder);
2801
2845
  t.table = arg;
2802
- t.shape = shape;
2803
- t.q = __spreadProps$3(__spreadValues$b({}, t.q), {
2804
- shape
2846
+ t.shape = w.shape;
2847
+ t.computeds = w.computeds;
2848
+ t.q = __spreadProps$3(__spreadValues$c({}, t.q), {
2849
+ shape: w.shape
2805
2850
  });
2806
2851
  t.baseQuery = t;
2807
2852
  arg = t;
@@ -2810,7 +2855,8 @@ const _joinLateral = (self, type, arg, cb, as) => {
2810
2855
  }
2811
2856
  const query = arg;
2812
2857
  query.q.joinTo = q;
2813
- ((_c = (_b = query.q).joinedShapes) != null ? _c : _b.joinedShapes = {})[getQueryAs(q)] = q.q.shape;
2858
+ const joinedAs = getQueryAs(q);
2859
+ ((_c = (_b = query.q).joinedShapes) != null ? _c : _b.joinedShapes = {})[joinedAs] = q.q.shape;
2814
2860
  let result = resolveSubQueryCallback(query, cb);
2815
2861
  if (relation) {
2816
2862
  result = relation.relationConfig.joinQuery(
@@ -2823,12 +2869,13 @@ const _joinLateral = (self, type, arg, cb, as) => {
2823
2869
  const shape = getShapeFromSelect(result, true);
2824
2870
  setQueryObjectValue(q, "joinedShapes", joinKey, shape);
2825
2871
  setQueryObjectValue(q, "joinedParsers", joinKey, result.q.parsers);
2872
+ if (result.q.batchParsers) {
2873
+ ((_e = (_d = q.q).joinedBatchParsers) != null ? _e : _d.joinedBatchParsers = {})[joinKey] = result.q.batchParsers;
2874
+ }
2826
2875
  }
2827
- return pushQueryValue(q, "join", [
2828
- type,
2829
- result,
2830
- as || getQueryAs(result)
2831
- ]);
2876
+ as || (as = getQueryAs(result));
2877
+ ((_g = (_f = q.q).joinedComputeds) != null ? _g : _f.joinedComputeds = {})[as] = result.q.computeds;
2878
+ return pushQueryValue(q, "join", [type, result, as]);
2832
2879
  };
2833
2880
 
2834
2881
  class EnumColumn extends ColumnType {
@@ -3119,7 +3166,201 @@ class Transaction {
3119
3166
  }
3120
3167
  }
3121
3168
 
3169
+ const applyBatchTransforms = (query, batches) => {
3170
+ if (query.transform) {
3171
+ for (const item of batches) {
3172
+ item.parent[item.key] = applyTransforms(
3173
+ query.returnType,
3174
+ query.transform,
3175
+ item.data
3176
+ );
3177
+ }
3178
+ }
3179
+ };
3180
+ const finalizeNestedHookSelect = (batches, returnType, tempColumns, renames, key) => {
3181
+ var _a;
3182
+ if (renames) {
3183
+ for (const { data } of batches) {
3184
+ for (const record of data) {
3185
+ if (record) {
3186
+ for (const a in renames) {
3187
+ record[a] = record[renames[a]];
3188
+ }
3189
+ }
3190
+ }
3191
+ }
3192
+ }
3193
+ if (tempColumns == null ? void 0 : tempColumns.size) {
3194
+ for (const { data } of batches) {
3195
+ for (const record of data) {
3196
+ if (record) {
3197
+ for (const key2 of tempColumns) {
3198
+ delete record[key2];
3199
+ }
3200
+ }
3201
+ }
3202
+ }
3203
+ }
3204
+ if (returnType === "one" || returnType === "oneOrThrow") {
3205
+ for (const batch of batches) {
3206
+ batch.data = batch.data[0];
3207
+ }
3208
+ } else if (returnType === "pluck") {
3209
+ for (const { data } of batches) {
3210
+ for (let i = 0; i < data.length; i++) {
3211
+ data[i] = data[i][key];
3212
+ }
3213
+ }
3214
+ } else if (returnType === "value" || returnType === "valueOrThrow") {
3215
+ for (const item of batches) {
3216
+ item.parent[item.key] = (_a = item.data[0]) == null ? void 0 : _a[key];
3217
+ }
3218
+ }
3219
+ };
3220
+
3221
+ class ComputedColumn {
3222
+ constructor(kind, deps, fn) {
3223
+ this.kind = kind;
3224
+ this.deps = deps;
3225
+ this.fn = fn;
3226
+ }
3227
+ }
3228
+ const computeAtRuntime = (deps, fn) => new ComputedColumn("one", deps, fn);
3229
+ const computeBatchAtRuntime = (deps, fn) => new ComputedColumn("many", deps, fn);
3230
+ const applyComputedColumns = (q, fn) => {
3231
+ var _a, _b;
3232
+ q.computeAtRuntime = computeAtRuntime;
3233
+ q.computeBatchAtRuntime = computeBatchAtRuntime;
3234
+ const computed = fn(q);
3235
+ for (const key in computed) {
3236
+ const item = computed[key];
3237
+ if (item instanceof ComputedColumn) {
3238
+ ((_b = (_a = q.q).computeds) != null ? _b : _a.computeds = {})[key] = item;
3239
+ } else {
3240
+ (q.shape[key] = item.result.value || UnknownColumn.instance).data.computed = item;
3241
+ }
3242
+ }
3243
+ q.computeAtRuntime = q.computeBatchAtRuntime = void 0;
3244
+ };
3245
+ const processComputedResult = (query, result) => {
3246
+ let promises;
3247
+ for (const key in query.selectedComputeds) {
3248
+ const computed = query.selectedComputeds[key];
3249
+ if (computed.kind === "one") {
3250
+ for (const record of result) {
3251
+ record[key] = computed.fn(record);
3252
+ }
3253
+ } else {
3254
+ const res = computed.fn(result);
3255
+ if (Array.isArray(res)) {
3256
+ saveBatchComputed(key, result, res);
3257
+ } else {
3258
+ (promises != null ? promises : promises = []).push(
3259
+ res.then(
3260
+ (res2) => saveBatchComputed(key, result, res2)
3261
+ )
3262
+ );
3263
+ }
3264
+ }
3265
+ }
3266
+ if (!promises)
3267
+ return;
3268
+ return Promise.all(promises);
3269
+ };
3270
+ const processComputedBatches = (query, batches, originalReturnType, returnType, tempColumns, renames, key) => {
3271
+ let promises;
3272
+ for (const key2 in query.selectedComputeds) {
3273
+ const computed = query.selectedComputeds[key2];
3274
+ if (computed.kind === "one") {
3275
+ for (const { data } of batches) {
3276
+ for (const record of data) {
3277
+ if (record) {
3278
+ record[key2] = computed.fn(record);
3279
+ }
3280
+ }
3281
+ }
3282
+ } else {
3283
+ for (const { data } of batches) {
3284
+ let present;
3285
+ let blanks;
3286
+ if (!returnType || returnType === "all") {
3287
+ present = data;
3288
+ } else {
3289
+ present = [];
3290
+ blanks = /* @__PURE__ */ new Set();
3291
+ for (let i = 0; i < data.length; i++) {
3292
+ if (data[i]) {
3293
+ present.push(data[i]);
3294
+ } else {
3295
+ blanks.add(i);
3296
+ }
3297
+ }
3298
+ }
3299
+ const res = computed.fn(present);
3300
+ if (Array.isArray(res)) {
3301
+ saveBatchComputed(key2, data, res, blanks);
3302
+ } else {
3303
+ (promises != null ? promises : promises = []).push(
3304
+ res.then(
3305
+ (res2) => saveBatchComputed(key2, data, res2, blanks)
3306
+ )
3307
+ );
3308
+ }
3309
+ }
3310
+ }
3311
+ }
3312
+ if (!promises)
3313
+ return;
3314
+ return Promise.all(promises).then(() => {
3315
+ finalizeNestedHookSelect(
3316
+ batches,
3317
+ originalReturnType,
3318
+ tempColumns,
3319
+ renames,
3320
+ key
3321
+ );
3322
+ applyBatchTransforms(query, batches);
3323
+ });
3324
+ };
3325
+ const saveBatchComputed = (key, result, res, blanks) => {
3326
+ const len = result.length;
3327
+ const actual = res.length + ((blanks == null ? void 0 : blanks.size) || 0);
3328
+ if (len !== actual) {
3329
+ throw new Error(
3330
+ `Incorrect length of batch computed result for column ${key}. Expected ${len}, received ${actual}.`
3331
+ );
3332
+ }
3333
+ if (blanks) {
3334
+ for (let i = 0, r = 0; i < len; i++) {
3335
+ if (!blanks.has(i)) {
3336
+ result[i][key] = res[r++];
3337
+ }
3338
+ }
3339
+ } else {
3340
+ for (let i = 0; i < len; i++) {
3341
+ result[i][key] = res[i];
3342
+ }
3343
+ }
3344
+ };
3345
+
3346
+ var __defProp$b = Object.defineProperty;
3347
+ var __getOwnPropSymbols$c = Object.getOwnPropertySymbols;
3348
+ var __hasOwnProp$c = Object.prototype.hasOwnProperty;
3349
+ var __propIsEnum$c = Object.prototype.propertyIsEnumerable;
3350
+ var __defNormalProp$b = (obj, key, value) => key in obj ? __defProp$b(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3351
+ var __spreadValues$b = (a, b) => {
3352
+ for (var prop in b || (b = {}))
3353
+ if (__hasOwnProp$c.call(b, prop))
3354
+ __defNormalProp$b(a, prop, b[prop]);
3355
+ if (__getOwnPropSymbols$c)
3356
+ for (var prop of __getOwnPropSymbols$c(b)) {
3357
+ if (__propIsEnum$c.call(b, prop))
3358
+ __defNormalProp$b(a, prop, b[prop]);
3359
+ }
3360
+ return a;
3361
+ };
3122
3362
  const queryMethodByReturnType = {
3363
+ undefined: "query",
3123
3364
  all: "query",
3124
3365
  rows: "arrays",
3125
3366
  pluck: "arrays",
@@ -3167,9 +3408,6 @@ Object.defineProperty(Then.prototype, "then", {
3167
3408
  });
3168
3409
  }
3169
3410
  });
3170
- const handleResult = (q, returnType, result, isSubQuery) => {
3171
- return parseResult(q, q.q.parsers, returnType, result, isSubQuery);
3172
- };
3173
3411
  function maybeWrappedThen(resolve, reject) {
3174
3412
  const { q } = this;
3175
3413
  let beforeHooks;
@@ -3227,7 +3465,7 @@ const callAfterHook = function(cb) {
3227
3465
  };
3228
3466
  const beginSql = { text: "BEGIN" };
3229
3467
  const then = async (q, adapter, trx, beforeHooks, afterHooks, afterCommitHooks, resolve, reject) => {
3230
- var _a;
3468
+ var _a, _b;
3231
3469
  const { q: query } = q;
3232
3470
  let sql;
3233
3471
  let logData;
@@ -3244,7 +3482,7 @@ const then = async (q, adapter, trx, beforeHooks, afterHooks, afterCommitHooks,
3244
3482
  sql = q.toSQL();
3245
3483
  const { hookSelect } = sql;
3246
3484
  const { returnType = "all" } = query;
3247
- const returns = hookSelect ? "all" : returnType;
3485
+ const tempReturnType = hookSelect || returnType === "rows" && q.q.batchParsers ? "all" : returnType;
3248
3486
  let result;
3249
3487
  let queryResult;
3250
3488
  if ("text" in sql) {
@@ -3254,7 +3492,7 @@ const then = async (q, adapter, trx, beforeHooks, afterHooks, afterCommitHooks,
3254
3492
  if (query.log) {
3255
3493
  logData = query.log.beforeQuery(sql);
3256
3494
  }
3257
- queryResult = await adapter[hookSelect ? "query" : queryMethodByReturnType[returnType]](sql);
3495
+ queryResult = await adapter[queryMethodByReturnType[tempReturnType]](sql);
3258
3496
  if (query.patchResult) {
3259
3497
  await query.patchResult(q, queryResult);
3260
3498
  }
@@ -3262,9 +3500,9 @@ const then = async (q, adapter, trx, beforeHooks, afterHooks, afterCommitHooks,
3262
3500
  query.log.afterQuery(sql, logData);
3263
3501
  sql = void 0;
3264
3502
  }
3265
- result = query.handleResult(q, returns, queryResult);
3503
+ result = query.handleResult(q, tempReturnType, queryResult);
3266
3504
  } else {
3267
- const queryMethod = hookSelect ? "query" : queryMethodByReturnType[returnType];
3505
+ const queryMethod = queryMethodByReturnType[tempReturnType];
3268
3506
  if (!trx) {
3269
3507
  if (query.log)
3270
3508
  logData = query.log.beforeQuery(beginSql);
@@ -3299,9 +3537,37 @@ const then = async (q, adapter, trx, beforeHooks, afterHooks, afterCommitHooks,
3299
3537
  if (query.patchResult) {
3300
3538
  await query.patchResult(q, queryResult);
3301
3539
  }
3302
- result = query.handleResult(q, returns, queryResult);
3540
+ result = query.handleResult(q, tempReturnType, queryResult);
3303
3541
  }
3304
- if (afterHooks || afterCommitHooks || query.after) {
3542
+ if (result && typeof result === "object" && typeof result.then === "function") {
3543
+ result = await result;
3544
+ }
3545
+ let tempColumns;
3546
+ let renames;
3547
+ if (hookSelect) {
3548
+ for (const column of hookSelect.keys()) {
3549
+ const as = hookSelect.get(column).as;
3550
+ if (as)
3551
+ (renames != null ? renames : renames = {})[column] = as;
3552
+ (_a = tempColumns != null ? tempColumns : tempColumns = /* @__PURE__ */ new Set()) == null ? void 0 : _a.add(as || column);
3553
+ }
3554
+ if (renames) {
3555
+ for (const record of result) {
3556
+ for (const a in renames) {
3557
+ const value = record[renames[a]];
3558
+ record[renames[a]] = record[a];
3559
+ record[a] = value;
3560
+ }
3561
+ }
3562
+ }
3563
+ if (query.selectedComputeds) {
3564
+ const promise = processComputedResult(query, result);
3565
+ if (promise)
3566
+ await promise;
3567
+ }
3568
+ }
3569
+ const hasAfterHook = afterHooks || afterCommitHooks || query.after;
3570
+ if (hasAfterHook) {
3305
3571
  if (queryResult.rowCount) {
3306
3572
  if (afterHooks || query.after) {
3307
3573
  const args = [result, q];
@@ -3313,7 +3579,7 @@ const then = async (q, adapter, trx, beforeHooks, afterHooks, afterCommitHooks,
3313
3579
  );
3314
3580
  }
3315
3581
  if (afterCommitHooks && trx) {
3316
- ((_a = trx.afterCommit) != null ? _a : trx.afterCommit = []).push(
3582
+ ((_b = trx.afterCommit) != null ? _b : trx.afterCommit = []).push(
3317
3583
  result,
3318
3584
  q,
3319
3585
  afterCommitHooks
@@ -3326,8 +3592,24 @@ const then = async (q, adapter, trx, beforeHooks, afterHooks, afterCommitHooks,
3326
3592
  const args = [result, q];
3327
3593
  await Promise.all(query.after.map(callAfterHook, args));
3328
3594
  }
3329
- if (hookSelect)
3330
- result = filterResult(q, returnType, queryResult, hookSelect, result);
3595
+ }
3596
+ if (hookSelect || tempReturnType !== returnType) {
3597
+ if (renames) {
3598
+ for (const record of result) {
3599
+ for (const a in renames) {
3600
+ record[a] = record[renames[a]];
3601
+ }
3602
+ }
3603
+ }
3604
+ result = filterResult(
3605
+ q,
3606
+ returnType,
3607
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
3608
+ queryResult,
3609
+ result,
3610
+ tempColumns,
3611
+ hasAfterHook
3612
+ );
3331
3613
  }
3332
3614
  if (query.transform) {
3333
3615
  result = applyTransforms(returnType, query.transform, result);
@@ -3373,57 +3655,91 @@ const assignError = (to, from) => {
3373
3655
  to.routine = from.routine;
3374
3656
  return to;
3375
3657
  };
3376
- const parseResult = (q, parsers, returnType = "all", result, isSubQuery) => {
3658
+ const handleResult = (q, returnType, result, isSubQuery) => {
3377
3659
  var _a, _b;
3660
+ const { parsers } = q.q;
3378
3661
  switch (returnType) {
3379
3662
  case "all": {
3380
3663
  if (q.q.throwOnNotFound && result.rows.length === 0)
3381
3664
  throw new NotFoundError(q);
3665
+ const promise = parseBatch(q, result);
3382
3666
  const { rows } = result;
3383
3667
  if (parsers) {
3384
3668
  for (const row of rows) {
3385
3669
  parseRecord(parsers, row);
3386
3670
  }
3387
3671
  }
3388
- return rows;
3672
+ return promise ? promise.then(() => rows) : rows;
3389
3673
  }
3390
3674
  case "one": {
3391
- const row = result.rows[0];
3392
- if (!row)
3675
+ const { rows } = result;
3676
+ if (!rows.length)
3393
3677
  return;
3394
- return parsers ? parseRecord(parsers, row) : row;
3678
+ const promise = parseBatch(q, result);
3679
+ if (parsers)
3680
+ parseRecord(parsers, rows[0]);
3681
+ return promise ? promise.then(() => rows[0]) : rows[0];
3395
3682
  }
3396
3683
  case "oneOrThrow": {
3397
- const row = result.rows[0];
3398
- if (!row)
3684
+ const { rows } = result;
3685
+ if (!rows.length)
3399
3686
  throw new NotFoundError(q);
3400
- return parsers ? parseRecord(parsers, row) : row;
3687
+ const promise = parseBatch(q, result);
3688
+ if (parsers)
3689
+ parseRecord(parsers, rows[0]);
3690
+ return promise ? promise.then(() => rows[0]) : rows[0];
3401
3691
  }
3402
3692
  case "rows": {
3403
- return parsers ? parseRows(
3404
- parsers,
3405
- result.fields,
3406
- result.rows
3407
- ) : result.rows;
3693
+ const { rows } = result;
3694
+ const promise = parseBatch(q, result);
3695
+ if (promise) {
3696
+ return promise.then(() => {
3697
+ if (parsers)
3698
+ parseRows(parsers, result.fields, rows);
3699
+ return rows;
3700
+ });
3701
+ } else if (parsers) {
3702
+ parseRows(parsers, result.fields, rows);
3703
+ }
3704
+ return rows;
3408
3705
  }
3409
3706
  case "pluck": {
3410
- const pluck = parsers == null ? void 0 : parsers.pluck;
3411
- if (pluck) {
3412
- return result.rows.map(isSubQuery ? pluck : (row) => pluck(row[0]));
3413
- } else if (isSubQuery) {
3414
- return result.rows;
3707
+ const { rows } = result;
3708
+ const promise = parseBatch(q, result);
3709
+ if (promise) {
3710
+ return promise.then(() => {
3711
+ parsePluck(parsers, isSubQuery, rows);
3712
+ return rows;
3713
+ });
3415
3714
  }
3416
- return result.rows.map((row) => row[0]);
3715
+ parsePluck(parsers, isSubQuery, rows);
3716
+ return rows;
3417
3717
  }
3418
3718
  case "value": {
3419
- const value = (_a = result.rows[0]) == null ? void 0 : _a[0];
3420
- return value !== void 0 ? parseValue(value, parsers) : q.q.notFoundDefault;
3719
+ const { rows } = result;
3720
+ const promise = parseBatch(q, result);
3721
+ if (promise) {
3722
+ return promise.then(() => {
3723
+ var _a2;
3724
+ return ((_a2 = rows[0]) == null ? void 0 : _a2[0]) !== void 0 ? parseValue(rows[0][0], parsers) : q.q.notFoundDefault;
3725
+ });
3726
+ }
3727
+ return ((_a = rows[0]) == null ? void 0 : _a[0]) !== void 0 ? parseValue(rows[0][0], parsers) : q.q.notFoundDefault;
3421
3728
  }
3422
3729
  case "valueOrThrow": {
3423
- const value = (_b = result.rows[0]) == null ? void 0 : _b[0];
3424
- if (value === void 0)
3730
+ const { rows } = result;
3731
+ const promise = parseBatch(q, result);
3732
+ if (promise) {
3733
+ return promise.then(() => {
3734
+ var _a2;
3735
+ if (((_a2 = rows[0]) == null ? void 0 : _a2[0]) === void 0)
3736
+ throw new NotFoundError(q);
3737
+ return parseValue(rows[0][0], parsers);
3738
+ });
3739
+ }
3740
+ if (((_b = rows[0]) == null ? void 0 : _b[0]) === void 0)
3425
3741
  throw new NotFoundError(q);
3426
- return parseValue(value, parsers);
3742
+ return parseValue(rows[0][0], parsers);
3427
3743
  }
3428
3744
  case "rowCount": {
3429
3745
  if (q.q.throwOnNotFound && result.rowCount === 0) {
@@ -3436,6 +3752,17 @@ const parseResult = (q, parsers, returnType = "all", result, isSubQuery) => {
3436
3752
  }
3437
3753
  }
3438
3754
  };
3755
+ const parseBatch = (q, queryResult) => {
3756
+ let promises;
3757
+ if (q.q.batchParsers) {
3758
+ for (const parser of q.q.batchParsers) {
3759
+ const res = parser.fn(parser.path, queryResult);
3760
+ if (res)
3761
+ (promises != null ? promises : promises = []).push(res);
3762
+ }
3763
+ }
3764
+ return promises && Promise.all(promises);
3765
+ };
3439
3766
  const parseRecord = (parsers, row) => {
3440
3767
  for (const key in parsers) {
3441
3768
  if (key in row) {
@@ -3453,38 +3780,43 @@ const parseRows = (parsers, fields, rows) => {
3453
3780
  }
3454
3781
  }
3455
3782
  }
3456
- return rows;
3783
+ };
3784
+ const parsePluck = (parsers, isSubQuery, rows) => {
3785
+ const pluck = parsers == null ? void 0 : parsers.pluck;
3786
+ if (pluck) {
3787
+ for (let i = 0; i < rows.length; i++) {
3788
+ rows[i] = pluck(isSubQuery ? rows[i] : rows[i][0]);
3789
+ }
3790
+ } else if (!isSubQuery) {
3791
+ for (let i = 0; i < rows.length; i++) {
3792
+ rows[i] = rows[i][0];
3793
+ }
3794
+ }
3457
3795
  };
3458
3796
  const parseValue = (value, parsers) => {
3459
3797
  const parser = parsers == null ? void 0 : parsers[getValueKey];
3460
3798
  return parser ? parser(value) : value;
3461
3799
  };
3462
- const filterResult = (q, returnType, queryResult, hookSelect, result) => {
3800
+ const filterResult = (q, returnType, queryResult, result, tempColumns, hasAfterHook) => {
3463
3801
  var _a;
3464
3802
  if (returnType === "all") {
3465
- const pick = getSelectPick(queryResult, hookSelect);
3466
- return result.map((full) => {
3467
- const filtered = {};
3468
- for (const key of pick) {
3469
- filtered[key] = full[key];
3470
- }
3471
- return filtered;
3472
- });
3803
+ return filterAllResult(result, tempColumns, hasAfterHook);
3473
3804
  }
3474
3805
  if (returnType === "oneOrThrow" || returnType === "one") {
3475
- const row = result[0];
3806
+ let row = result[0];
3476
3807
  if (!row) {
3477
3808
  if (returnType === "oneOrThrow")
3478
3809
  throw new NotFoundError(q);
3479
3810
  return void 0;
3811
+ } else if (!(tempColumns == null ? void 0 : tempColumns.size)) {
3812
+ return row;
3480
3813
  } else {
3481
- result = {};
3482
- for (const key in row) {
3483
- if (!hookSelect.includes(key)) {
3484
- result[key] = row[key];
3485
- }
3814
+ if (hasAfterHook)
3815
+ row = __spreadValues$b({}, row);
3816
+ for (const column of tempColumns) {
3817
+ delete row[column];
3486
3818
  }
3487
- return result;
3819
+ return row;
3488
3820
  }
3489
3821
  }
3490
3822
  if (returnType === "value") {
@@ -3504,20 +3836,30 @@ const filterResult = (q, returnType, queryResult, hookSelect, result) => {
3504
3836
  return result.map((row) => row[key]);
3505
3837
  }
3506
3838
  if (returnType === "rows") {
3507
- const pick = getSelectPick(queryResult, hookSelect);
3508
- return result.map(
3509
- (full) => pick.map((key) => full[key])
3510
- );
3839
+ result = filterAllResult(result, tempColumns, hasAfterHook);
3840
+ return result.map((record) => Object.values(record));
3511
3841
  }
3512
3842
  return;
3513
3843
  };
3514
- const getSelectPick = (queryResult, hookSelect) => {
3515
- const pick = [];
3516
- for (const field of queryResult.fields) {
3517
- if (!hookSelect.includes(field.name))
3518
- pick.push(field.name);
3844
+ const filterAllResult = (result, tempColumns, hasAfterHook) => {
3845
+ if (tempColumns == null ? void 0 : tempColumns.size) {
3846
+ if (hasAfterHook) {
3847
+ return result.map((data) => {
3848
+ const record = __spreadValues$b({}, data);
3849
+ for (const key of tempColumns) {
3850
+ delete record[key];
3851
+ }
3852
+ return record;
3853
+ });
3854
+ } else {
3855
+ for (const record of result) {
3856
+ for (const key of tempColumns) {
3857
+ delete record[key];
3858
+ }
3859
+ }
3860
+ }
3519
3861
  }
3520
- return pick;
3862
+ return result;
3521
3863
  };
3522
3864
 
3523
3865
  const addParserForRawExpression = (q, key, raw) => {
@@ -3525,58 +3867,220 @@ const addParserForRawExpression = (q, key, raw) => {
3525
3867
  if (type == null ? void 0 : type.parseFn)
3526
3868
  setParserToQuery(q.q, key, type.parseFn);
3527
3869
  };
3528
- const subQueryResult = {
3529
- // sub query can't return a rowCount, use -1 as for impossible case
3530
- rowCount: -1,
3531
- rows: emptyArray,
3532
- fields: emptyArray
3533
- };
3534
3870
  const addParsersForSelectJoined = (q, arg, as = arg) => {
3535
- var _a;
3871
+ var _a, _b, _c, _d;
3536
3872
  const parsers = (_a = q.q.joinedParsers) == null ? void 0 : _a[arg];
3537
3873
  if (parsers) {
3538
3874
  setParserToQuery(q.q, as, (row) => parseRecord(parsers, row));
3539
3875
  }
3876
+ const batchParsers = (_b = q.q.joinedBatchParsers) == null ? void 0 : _b[arg];
3877
+ if (batchParsers) {
3878
+ ((_d = (_c = q.q).batchParsers) != null ? _d : _c.batchParsers = []).push(
3879
+ ...batchParsers.map((x) => ({
3880
+ path: [as, ...x.path],
3881
+ fn: x.fn
3882
+ }))
3883
+ );
3884
+ }
3540
3885
  };
3541
3886
  const addParserForSelectItem = (q, as, key, arg) => {
3887
+ var _a, _b, _c, _d;
3542
3888
  if (typeof arg === "object" || typeof arg === "function") {
3543
3889
  if (isExpression(arg)) {
3544
3890
  addParserForRawExpression(q, key, arg);
3545
3891
  } else {
3546
3892
  const { q: query } = arg;
3547
- if (query.parsers || query.transform) {
3548
- setParserToQuery(q.q, key, (item) => {
3549
- const t = query.returnType || "all";
3550
- subQueryResult.rows = t === "value" || t === "valueOrThrow" ? [[item]] : t === "one" || t === "oneOrThrow" ? [item] : item;
3551
- const result = query.handleResult(arg, t, subQueryResult, true);
3552
- return query.transform ? applyTransforms(t, query.transform, result) : result;
3553
- });
3893
+ if (query.batchParsers) {
3894
+ const batchParsers = (_b = (_a = q.q).batchParsers) != null ? _b : _a.batchParsers = [];
3895
+ for (const bp of query.batchParsers) {
3896
+ batchParsers.push({ path: [key, ...bp.path], fn: bp.fn });
3897
+ }
3554
3898
  }
3555
- if (query.returnType === "valueOrThrow" || query.returnType === "oneOrThrow") {
3556
- pushQueryValue(
3557
- q,
3558
- "transform",
3559
- (data) => {
3560
- if (Array.isArray(data)) {
3561
- for (const item of data) {
3562
- if (item[key] === void 0) {
3563
- throw new NotFoundError(q);
3899
+ if (query.hookSelect || query.parsers || query.transform) {
3900
+ const batchParsers = (_d = (_c = q.q).batchParsers) != null ? _d : _c.batchParsers = [];
3901
+ batchParsers.push({
3902
+ path: [key],
3903
+ fn: (path, queryResult) => {
3904
+ var _a2, _b2, _c2;
3905
+ const { rows } = queryResult;
3906
+ const originalReturnType = query.returnType || "all";
3907
+ let returnType = originalReturnType;
3908
+ const { hookSelect } = query;
3909
+ const batches = [];
3910
+ let last = path.length;
3911
+ if (returnType === "value" || returnType === "valueOrThrow") {
3912
+ if (hookSelect) {
3913
+ batches.push = (item) => {
3914
+ if (!(key in item)) {
3915
+ returnType = returnType === "value" ? "one" : "oneOrThrow";
3916
+ }
3917
+ batches.push = Array.prototype.push;
3918
+ return batches.push(item);
3919
+ };
3920
+ } else {
3921
+ last--;
3922
+ }
3923
+ }
3924
+ collectNestedSelectBatches(batches, rows, path, last);
3925
+ switch (returnType) {
3926
+ case "all": {
3927
+ const { parsers } = query;
3928
+ if (parsers) {
3929
+ for (const { data } of batches) {
3930
+ for (const one of data) {
3931
+ parseRecord(parsers, one);
3932
+ }
3933
+ }
3564
3934
  }
3935
+ break;
3565
3936
  }
3566
- } else {
3567
- if (data[key] === void 0) {
3568
- throw new NotFoundError(q);
3937
+ case "one":
3938
+ case "oneOrThrow": {
3939
+ const { parsers } = query;
3940
+ if (parsers) {
3941
+ if (returnType === "one") {
3942
+ for (const { data } of batches) {
3943
+ if (data)
3944
+ parseRecord(parsers, data);
3945
+ }
3946
+ } else {
3947
+ for (const { data } of batches) {
3948
+ if (!data)
3949
+ throw new NotFoundError(arg);
3950
+ parseRecord(parsers, data);
3951
+ }
3952
+ }
3953
+ } else if (returnType !== "one") {
3954
+ for (const { data } of batches) {
3955
+ if (!data)
3956
+ throw new NotFoundError(arg);
3957
+ }
3958
+ }
3959
+ if (hookSelect) {
3960
+ for (const batch of batches) {
3961
+ batch.data = [batch.data];
3962
+ }
3963
+ }
3964
+ break;
3965
+ }
3966
+ case "pluck": {
3967
+ const parse = (_a2 = query.parsers) == null ? void 0 : _a2.pluck;
3968
+ if (parse) {
3969
+ for (const { data } of batches) {
3970
+ for (let i = 0; i < data.length; i++) {
3971
+ data[i] = parse(data[i]);
3972
+ }
3973
+ }
3974
+ }
3975
+ break;
3976
+ }
3977
+ case "value":
3978
+ case "valueOrThrow": {
3979
+ const parse = (_b2 = query.parsers) == null ? void 0 : _b2[getValueKey];
3980
+ if (parse) {
3981
+ if (returnType === "value") {
3982
+ for (const { data } of batches) {
3983
+ data[key] = data[key] === void 0 ? arg.q.notFoundDefault : parse(data[key]);
3984
+ }
3985
+ } else {
3986
+ for (const { data } of batches) {
3987
+ if (data[key] === void 0)
3988
+ throw new NotFoundError(arg);
3989
+ data[key] = parse(data[key]);
3990
+ }
3991
+ }
3992
+ } else if (returnType !== "value") {
3993
+ for (const { data } of batches) {
3994
+ if (data[key] === void 0)
3995
+ throw new NotFoundError(arg);
3996
+ }
3997
+ }
3998
+ if (hookSelect) {
3999
+ for (const batch of batches) {
4000
+ batch.data = [batch.data];
4001
+ }
4002
+ }
4003
+ break;
3569
4004
  }
3570
4005
  }
3571
- return data;
4006
+ if (hookSelect) {
4007
+ let tempColumns;
4008
+ let renames;
4009
+ for (const column of hookSelect.keys()) {
4010
+ const as2 = hookSelect.get(column).as;
4011
+ if (as2)
4012
+ (renames != null ? renames : renames = {})[column] = as2;
4013
+ (_c2 = tempColumns != null ? tempColumns : tempColumns = /* @__PURE__ */ new Set()) == null ? void 0 : _c2.add(as2 || column);
4014
+ }
4015
+ if (renames) {
4016
+ for (const { data } of batches) {
4017
+ for (const record of data) {
4018
+ if (record) {
4019
+ for (const a in renames) {
4020
+ const value = record[renames[a]];
4021
+ record[renames[a]] = record[a];
4022
+ record[a] = value;
4023
+ }
4024
+ }
4025
+ }
4026
+ }
4027
+ }
4028
+ if (query.selectedComputeds) {
4029
+ const maybePromise = processComputedBatches(
4030
+ query,
4031
+ batches,
4032
+ originalReturnType,
4033
+ returnType,
4034
+ tempColumns,
4035
+ renames,
4036
+ key
4037
+ );
4038
+ if (maybePromise)
4039
+ return maybePromise;
4040
+ }
4041
+ finalizeNestedHookSelect(
4042
+ batches,
4043
+ originalReturnType,
4044
+ tempColumns,
4045
+ renames,
4046
+ key
4047
+ );
4048
+ }
4049
+ applyBatchTransforms(query, batches);
4050
+ return;
3572
4051
  }
3573
- );
4052
+ });
3574
4053
  }
3575
4054
  }
3576
4055
  return arg;
3577
4056
  }
3578
4057
  return setParserForSelectedString(q, arg, as, key);
3579
4058
  };
4059
+ const collectNestedSelectBatches = (batches, rows, path, last) => {
4060
+ const stack = rows.map(
4061
+ (row) => ({
4062
+ data: row,
4063
+ i: 0
4064
+ })
4065
+ );
4066
+ while (stack.length > 0) {
4067
+ const item = stack.pop();
4068
+ const { i } = item;
4069
+ if (i === last) {
4070
+ batches.push(item);
4071
+ continue;
4072
+ }
4073
+ const { data } = item;
4074
+ const key = path[i];
4075
+ if (Array.isArray(data)) {
4076
+ for (let key2 = 0; key2 < data.length; key2++) {
4077
+ stack.push({ data: data[key2], parent: data, key: key2, i });
4078
+ }
4079
+ } else if (data && typeof data === "object") {
4080
+ stack.push({ data: data[key], parent: data, key, i: i + 1 });
4081
+ }
4082
+ }
4083
+ };
3580
4084
  const emptyArrSQL = new RawSQL("'[]'");
3581
4085
  const processSelectArg = (q, as, arg, columnAs) => {
3582
4086
  var _a, _b, _c, _d;
@@ -3590,7 +4094,7 @@ const processSelectArg = (q, as, arg, columnAs) => {
3590
4094
  value = resolveSubQueryCallback(q, value);
3591
4095
  if (isQueryNone(value)) {
3592
4096
  if (value.q.innerJoinLateral) {
3593
- return;
4097
+ return false;
3594
4098
  }
3595
4099
  } else if (!isExpression(value) && value.joinQuery) {
3596
4100
  value = value.joinQuery(value, q);
@@ -3600,17 +4104,23 @@ const processSelectArg = (q, as, arg, columnAs) => {
3600
4104
  query = value.json(false);
3601
4105
  value.q.coalesceValue = emptyArrSQL;
3602
4106
  } else if (returnType === "pluck") {
3603
- query = value.wrap(value.baseQuery.clone()).jsonAgg(value.q.select[0]);
4107
+ query = value.q.select ? value.wrap(value.baseQuery.clone()).jsonAgg(value.q.select[0]) : value.json(false);
3604
4108
  value.q.coalesceValue = emptyArrSQL;
3605
4109
  } else {
3606
- if ((returnType === "value" || returnType === "valueOrThrow") && value.q.select) {
3607
- if (typeof value.q.select[0] === "string") {
3608
- value.q.select[0] = {
3609
- selectAs: { r: value.q.select[0] }
3610
- };
4110
+ if (returnType === "value" || returnType === "valueOrThrow") {
4111
+ if (value.q.select) {
4112
+ if (typeof value.q.select[0] === "string") {
4113
+ value.q.select[0] = {
4114
+ selectAs: { r: value.q.select[0] }
4115
+ };
4116
+ }
4117
+ query = value;
4118
+ } else {
4119
+ query = value.json(false);
3611
4120
  }
4121
+ } else {
4122
+ query = value;
3612
4123
  }
3613
- query = value;
3614
4124
  }
3615
4125
  let asOverride = key;
3616
4126
  if ((_a = value.q.joinedShapes) == null ? void 0 : _a[key]) {
@@ -3644,7 +4154,7 @@ const processSelectArg = (q, as, arg, columnAs) => {
3644
4154
  return { selectAs };
3645
4155
  };
3646
4156
  const setParserForSelectedString = (q, arg, as, columnAs) => {
3647
- var _a, _b, _c, _d;
4157
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l;
3648
4158
  const index = arg.indexOf(".");
3649
4159
  if (index !== -1) {
3650
4160
  const table = arg.slice(0, index);
@@ -3652,26 +4162,59 @@ const setParserForSelectedString = (q, arg, as, columnAs) => {
3652
4162
  if (column === "*") {
3653
4163
  addParsersForSelectJoined(q, table, columnAs);
3654
4164
  return table === as ? column : arg;
3655
- } else {
3656
- if (table === as) {
4165
+ } else if (table === as) {
4166
+ if (columnAs) {
3657
4167
  const parser = (_a = q.q.parsers) == null ? void 0 : _a[column];
3658
4168
  if (parser)
3659
- setParserToQuery(q.q, columnAs || column, parser);
3660
- return column;
3661
- } else {
3662
- const parser = (_c = (_b = q.q.joinedParsers) == null ? void 0 : _b[table]) == null ? void 0 : _c[column];
3663
- if (parser)
3664
- setParserToQuery(q.q, columnAs || column, parser);
3665
- return arg;
4169
+ q.q.parsers[columnAs] = parser;
3666
4170
  }
4171
+ return handleComputed(q, q.q.computeds, column);
4172
+ } else {
4173
+ const parser = (_c = (_b = q.q.joinedParsers) == null ? void 0 : _b[table]) == null ? void 0 : _c[column];
4174
+ if (parser)
4175
+ setParserToQuery(q.q, columnAs || column, parser);
4176
+ const batchParsers = (_d = q.q.joinedBatchParsers) == null ? void 0 : _d[table];
4177
+ if (batchParsers) {
4178
+ for (const bp of batchParsers) {
4179
+ if (bp.path[0] === column) {
4180
+ ((_f = (_e = q.q).batchParsers) != null ? _f : _e.batchParsers = []).push(bp);
4181
+ }
4182
+ }
4183
+ }
4184
+ const computeds = (_g = q.q.joinedComputeds) == null ? void 0 : _g[table];
4185
+ if (computeds == null ? void 0 : computeds[column]) {
4186
+ const computed = computeds[column];
4187
+ const map = (_i = (_h = q.q).hookSelect) != null ? _i : _h.hookSelect = /* @__PURE__ */ new Map();
4188
+ for (const column2 of computed.deps) {
4189
+ map.set(column2, { select: `${table}.${column2}` });
4190
+ }
4191
+ ((_k = (_j = q.q).selectedComputeds) != null ? _k : _j.selectedComputeds = {})[column] = computed;
4192
+ return;
4193
+ }
4194
+ return arg;
3667
4195
  }
3668
4196
  } else {
3669
- const parser = (_d = q.q.parsers) == null ? void 0 : _d[arg];
3670
- if (parser)
3671
- setParserToQuery(q.q, columnAs || arg, parser);
3672
- return arg;
4197
+ if (columnAs) {
4198
+ const parser = (_l = q.q.parsers) == null ? void 0 : _l[arg];
4199
+ if (parser)
4200
+ q.q.parsers[columnAs] = parser;
4201
+ }
4202
+ return handleComputed(q, q.q.computeds, arg);
3673
4203
  }
3674
4204
  };
4205
+ const handleComputed = (q, computeds, column) => {
4206
+ var _a, _b, _c, _d;
4207
+ if (computeds == null ? void 0 : computeds[column]) {
4208
+ const computed = computeds[column];
4209
+ const map = (_b = (_a = q.q).hookSelect) != null ? _b : _a.hookSelect = /* @__PURE__ */ new Map();
4210
+ for (const column2 of computed.deps) {
4211
+ map.set(column2, { select: column2 });
4212
+ }
4213
+ ((_d = (_c = q.q).selectedComputeds) != null ? _d : _c.selectedComputeds = {})[column] = computed;
4214
+ return;
4215
+ }
4216
+ return column;
4217
+ };
3675
4218
  const getShapeFromSelect = (q, isSubQuery) => {
3676
4219
  const query = q.q;
3677
4220
  const { select, shape } = query;
@@ -3691,7 +4234,9 @@ const getShapeFromSelect = (q, isSubQuery) => {
3691
4234
  for (const item of select) {
3692
4235
  if (typeof item === "string") {
3693
4236
  addColumnToShapeFromSelect(q, item, shape, query, result, isSubQuery);
3694
- } else if ("selectAs" in item) {
4237
+ } else if (isExpression(item)) {
4238
+ result.value = item.result.value;
4239
+ } else if (item && "selectAs" in item) {
3695
4240
  for (const key in item.selectAs) {
3696
4241
  const it = item.selectAs[key];
3697
4242
  if (typeof it === "string") {
@@ -3706,7 +4251,7 @@ const getShapeFromSelect = (q, isSubQuery) => {
3706
4251
  );
3707
4252
  } else if (isExpression(it)) {
3708
4253
  result[key] = it.result.value;
3709
- } else {
4254
+ } else if (it) {
3710
4255
  const { returnType } = it.q;
3711
4256
  if (returnType === "value" || returnType === "valueOrThrow") {
3712
4257
  const type = it.q[getValueKey];
@@ -3717,8 +4262,6 @@ const getShapeFromSelect = (q, isSubQuery) => {
3717
4262
  }
3718
4263
  }
3719
4264
  }
3720
- } else if (isExpression(item)) {
3721
- result.value = item.result.value;
3722
4265
  }
3723
4266
  }
3724
4267
  }
@@ -3754,12 +4297,13 @@ function _querySelect(q, args) {
3754
4297
  return q;
3755
4298
  }
3756
4299
  const as = q.q.as || q.table;
3757
- const selectArgs = new Array(len);
3758
- for (let i = 0; i < len; i++) {
3759
- selectArgs[i] = processSelectArg(q, as, args[i]);
3760
- if (!selectArgs[i]) {
4300
+ const selectArgs = [];
4301
+ for (const arg of args) {
4302
+ const item = processSelectArg(q, as, arg);
4303
+ if (item)
4304
+ selectArgs.push(item);
4305
+ else if (item === false)
3761
4306
  return _queryNone(q);
3762
- }
3763
4307
  }
3764
4308
  return pushQueryArray(q, "select", selectArgs);
3765
4309
  }
@@ -3829,20 +4373,25 @@ const _get = (query, returnType, arg) => {
3829
4373
  }
3830
4374
  }
3831
4375
  q[getValueKey] = type;
3832
- setParserForSelectedString(
4376
+ const selected = setParserForSelectedString(
3833
4377
  query,
3834
4378
  arg,
3835
4379
  getQueryAs(query),
3836
4380
  getValueKey
3837
4381
  );
3838
- q.expr = new SelectItemExpression(query, arg, type);
4382
+ q.select = selected ? [
4383
+ q.expr = new SelectItemExpression(
4384
+ query,
4385
+ selected,
4386
+ type
4387
+ )
4388
+ ] : void 0;
3839
4389
  } else {
3840
4390
  type = arg.result.value;
3841
4391
  q[getValueKey] = type;
3842
4392
  addParserForRawExpression(query, getValueKey, arg);
3843
- q.expr = arg;
4393
+ q.select = [q.expr = arg];
3844
4394
  }
3845
- q.select = [q.expr];
3846
4395
  return setQueryOperators(
3847
4396
  query,
3848
4397
  (type == null ? void 0 : type.operators) || Operators.any
@@ -3878,23 +4427,27 @@ class AsMethods {
3878
4427
  }
3879
4428
 
3880
4429
  function queryFrom(self, arg) {
3881
- var _a, _b;
4430
+ var _a, _b, _c, _d;
3882
4431
  const data = self.q;
3883
4432
  if (typeof arg === "string") {
3884
4433
  data.as || (data.as = arg);
3885
- data.shape = (_a = data.withShapes) == null ? void 0 : _a[arg];
4434
+ const w = (_a = data.withShapes) == null ? void 0 : _a[arg];
4435
+ data.shape = (_b = w == null ? void 0 : w.shape) != null ? _b : emptyObject;
4436
+ data.computeds = w == null ? void 0 : w.computeds;
3886
4437
  } else if (isExpression(arg)) {
3887
4438
  data.as || (data.as = "t");
3888
4439
  } else if (Array.isArray(arg)) {
3889
4440
  const { shape } = data;
3890
- const parsers = (_b = data.parsers) != null ? _b : data.parsers = {};
4441
+ const parsers = (_c = data.parsers) != null ? _c : data.parsers = {};
4442
+ const computeds = (_d = data.computeds) != null ? _d : data.computeds = {};
3891
4443
  for (const item of arg) {
3892
4444
  if (typeof item === "string") {
3893
- const withShape = data.withShapes[item];
3894
- Object.assign(shape, withShape);
3895
- for (const key in withShape) {
3896
- if (withShape[key].parseFn) {
3897
- parsers[key] = withShape[key].parseFn;
4445
+ const w = data.withShapes[item];
4446
+ Object.assign(shape, w.shape);
4447
+ Object.assign(computeds, w.computeds);
4448
+ for (const key in w.shape) {
4449
+ if (w.shape[key].parseFn) {
4450
+ parsers[key] = w.shape[key].parseFn;
3898
4451
  }
3899
4452
  }
3900
4453
  } else if (!isExpression(item)) {
@@ -3907,6 +4460,7 @@ function queryFrom(self, arg) {
3907
4460
  data.as || (data.as = q.q.as || q.table || "t");
3908
4461
  data.shape = getShapeFromSelect(arg, true);
3909
4462
  data.parsers = q.q.parsers;
4463
+ data.batchParsers = q.q.batchParsers;
3910
4464
  }
3911
4465
  data.from = arg;
3912
4466
  return self;
@@ -4016,44 +4570,117 @@ function queryJson(self, coalesce) {
4016
4570
  const pushSelectSql = (ctx, table, query, quotedAs) => {
4017
4571
  ctx.sql.push(selectToSql(ctx, table, query, quotedAs));
4018
4572
  };
4019
- const selectToSql = (ctx, table, query, quotedAs) => {
4573
+ const selectToSql = (ctx, table, query, quotedAs, hookSelect = query.hookSelect) => {
4574
+ var _a, _b;
4575
+ let selected;
4576
+ const list = [];
4020
4577
  if (query.select) {
4021
- const list = [];
4022
4578
  for (const item of query.select) {
4023
4579
  if (typeof item === "string") {
4024
- list.push(selectedStringToSQL(ctx, table, query, quotedAs, item));
4025
- } else if ("selectAs" in item) {
4026
- const obj = item.selectAs;
4027
- for (const as in obj) {
4028
- const value = obj[as];
4029
- if (typeof value === "object" || typeof value === "function") {
4030
- if (isExpression(value)) {
4031
- list.push(`${value.toSQL(ctx, quotedAs)} "${as}"`);
4032
- } else {
4033
- pushSubQuerySql(ctx, value, as, list, quotedAs);
4580
+ let sql;
4581
+ if (item === "*") {
4582
+ if (hookSelect) {
4583
+ selected != null ? selected : selected = {};
4584
+ for (const key in table.internal.columnsKeysForSelectAll || query.shape) {
4585
+ selected[key] = quotedAs;
4034
4586
  }
4035
- } else {
4036
- list.push(
4037
- `${columnToSql(
4038
- ctx,
4039
- table.q,
4040
- table.q.shape,
4041
- value,
4042
- quotedAs,
4043
- true
4044
- )} "${as}"`
4587
+ }
4588
+ sql = selectAllSql(table, query, quotedAs);
4589
+ } else {
4590
+ const index = item.indexOf(".");
4591
+ if (index !== -1) {
4592
+ const tableName = item.slice(0, index);
4593
+ const key = item.slice(index + 1);
4594
+ if (hookSelect == null ? void 0 : hookSelect.get(key))
4595
+ (selected != null ? selected : selected = {})[key] = `"${tableName}"`;
4596
+ sql = tableColumnToSqlWithAs(
4597
+ ctx,
4598
+ table.q,
4599
+ item,
4600
+ tableName,
4601
+ key,
4602
+ quotedAs,
4603
+ true
4045
4604
  );
4605
+ } else {
4606
+ if (hookSelect == null ? void 0 : hookSelect.get(item))
4607
+ (selected != null ? selected : selected = {})[item] = quotedAs;
4608
+ sql = ownColumnToSqlWithAs(ctx, table.q, item, quotedAs, true);
4609
+ }
4610
+ }
4611
+ list.push(sql);
4612
+ } else if (item) {
4613
+ if ("selectAs" in item) {
4614
+ const obj = item.selectAs;
4615
+ for (const as in obj) {
4616
+ if (hookSelect)
4617
+ (selected != null ? selected : selected = {})[as] = true;
4618
+ const value = obj[as];
4619
+ if (typeof value === "object") {
4620
+ if (isExpression(value)) {
4621
+ list.push(`${value.toSQL(ctx, quotedAs)} "${as}"`);
4622
+ } else {
4623
+ pushSubQuerySql(ctx, value, as, list, quotedAs);
4624
+ }
4625
+ } else if (value) {
4626
+ list.push(
4627
+ `${columnToSql(
4628
+ ctx,
4629
+ table.q,
4630
+ table.q.shape,
4631
+ value,
4632
+ quotedAs,
4633
+ true
4634
+ )} "${as}"`
4635
+ );
4636
+ }
4046
4637
  }
4638
+ } else {
4639
+ list.push(selectedObjectToSQL(ctx, quotedAs, item));
4047
4640
  }
4641
+ }
4642
+ }
4643
+ }
4644
+ if (hookSelect) {
4645
+ for (const column of hookSelect.keys()) {
4646
+ const item = hookSelect.get(column);
4647
+ const { select } = item;
4648
+ let sql;
4649
+ let quotedTable;
4650
+ let columnName;
4651
+ let col;
4652
+ const index = select.indexOf(".");
4653
+ if (index !== -1) {
4654
+ const tableName = select.slice(0, index);
4655
+ quotedTable = `"${tableName}"`;
4656
+ columnName = select.slice(index + 1);
4657
+ col = (_b = (_a = table.q.joinedShapes) == null ? void 0 : _a[tableName]) == null ? void 0 : _b[columnName];
4658
+ sql = (col == null ? void 0 : col.data.computed) ? col.data.computed.toSQL(ctx, `"${tableName}"`) : `"${tableName}"."${(col == null ? void 0 : col.data.name) || columnName}"`;
4048
4659
  } else {
4049
- list.push(selectedObjectToSQL(ctx, quotedAs, item));
4660
+ quotedTable = quotedAs;
4661
+ columnName = select;
4662
+ col = query.shape[select];
4663
+ sql = simpleColumnToSQL(ctx, select, col, quotedAs);
4050
4664
  }
4665
+ if (selected == null ? void 0 : selected[columnName]) {
4666
+ if ((selected == null ? void 0 : selected[columnName]) === quotedTable) {
4667
+ hookSelect.delete(column);
4668
+ continue;
4669
+ }
4670
+ let i = 2;
4671
+ let name;
4672
+ while (selected[name = `${column}${i}`])
4673
+ i++;
4674
+ item.as = name;
4675
+ sql += ` "${name}"`;
4676
+ } else if (col == null ? void 0 : col.data.name) {
4677
+ sql += ` "${columnName}"`;
4678
+ }
4679
+ list.push(sql);
4051
4680
  }
4052
- return list.join(", ");
4053
4681
  }
4054
- return selectAllSql(table, query, quotedAs);
4682
+ return list.length ? list.join(", ") : selectAllSql(table, query, quotedAs);
4055
4683
  };
4056
- const selectedStringToSQL = (ctx, table, query, quotedAs, item) => item === "*" ? selectAllSql(table, query, quotedAs) : columnToSqlWithAs(ctx, table.q, item, quotedAs, true);
4057
4684
  function selectedObjectToSQL(ctx, quotedAs, item) {
4058
4685
  const sql = item.toSQL(ctx, quotedAs);
4059
4686
  return ctx.aliasValue ? `${sql} r` : sql;
@@ -4063,7 +4690,7 @@ const selectAllSql = (table, query, quotedAs) => {
4063
4690
  return ((_a = query.join) == null ? void 0 : _a.length) ? ((_b = table.internal.columnsForSelectAll) == null ? void 0 : _b.map((item) => `${quotedAs}.${item}`).join(", ")) || `${quotedAs}.*` : ((_c = table.internal.columnsForSelectAll) == null ? void 0 : _c.join(", ")) || "*";
4064
4691
  };
4065
4692
  const pushSubQuerySql = (ctx, query, as, list, quotedAs) => {
4066
- var _a;
4693
+ var _a, _b, _c;
4067
4694
  const { returnType = "all" } = query.q;
4068
4695
  if (isQueryNone(query)) {
4069
4696
  let sql;
@@ -4127,20 +4754,27 @@ const pushSubQuerySql = (ctx, query, as, list, quotedAs) => {
4127
4754
  case "pluck": {
4128
4755
  const { select } = query.q;
4129
4756
  const first = select == null ? void 0 : select[0];
4130
- if (!select || !first) {
4757
+ if (!first && ((_b = query.q.computeds) == null ? void 0 : _b[as])) {
4758
+ query = queryJson(query);
4759
+ } else if (!first) {
4131
4760
  throw new OrchidOrmInternalError(
4132
4761
  query,
4133
4762
  `Nothing was selected for pluck`
4134
4763
  );
4764
+ } else {
4765
+ const cloned = query.clone();
4766
+ cloned.q.select = [{ selectAs: { c: first } }];
4767
+ query = queryWrap(cloned, cloned.baseQuery.clone());
4768
+ _queryGetOptional(query, new RawSQL(`COALESCE(json_agg("c"), '[]')`));
4135
4769
  }
4136
- const cloned = query.clone();
4137
- cloned.q.select = [{ selectAs: { c: first } }];
4138
- query = queryWrap(cloned, cloned.baseQuery.clone());
4139
- _queryGetOptional(query, new RawSQL(`COALESCE(json_agg("c"), '[]')`));
4140
4770
  break;
4141
4771
  }
4142
4772
  case "value":
4143
4773
  case "valueOrThrow":
4774
+ if ((_c = query.q.computeds) == null ? void 0 : _c[as]) {
4775
+ query = queryJson(query);
4776
+ }
4777
+ break;
4144
4778
  case "rows":
4145
4779
  case "rowCount":
4146
4780
  case "void":
@@ -4642,42 +5276,22 @@ const encodeRow = (ctx, values, q, QueryClass, row, runtimeDefaults, quotedAs) =
4642
5276
  };
4643
5277
  const pushReturningSql = (ctx, q, data, quotedAs, hookSelect, keyword = "RETURNING") => {
4644
5278
  const { select } = data;
4645
- if (!(hookSelect == null ? void 0 : hookSelect.length) && !select)
4646
- return hookSelect;
4647
- let selected;
4648
- let hookFiltered;
4649
- if (select) {
4650
- selected = selectToSql(ctx, q, data, quotedAs);
5279
+ if (!(hookSelect == null ? void 0 : hookSelect.size) && !select)
5280
+ return hookSelect && /* @__PURE__ */ new Map();
5281
+ ctx.sql.push(keyword);
5282
+ if (q.q.hookSelect || hookSelect) {
5283
+ const tempSelect = new Map(q.q.hookSelect);
4651
5284
  if (hookSelect) {
4652
- if (select.includes("*")) {
4653
- hookFiltered = emptyArray;
4654
- } else {
4655
- hookFiltered = [];
4656
- for (const column of hookSelect) {
4657
- if (!hookFiltered.includes(column) && !(select == null ? void 0 : select.includes(column)) && !(select == null ? void 0 : select.includes(`${quotedAs}.${column}`))) {
4658
- hookFiltered.push(column);
4659
- }
4660
- }
5285
+ for (const column of hookSelect) {
5286
+ tempSelect.set(column, { select: column });
4661
5287
  }
4662
5288
  }
4663
- } else {
4664
- hookFiltered = [];
4665
- for (const column of hookSelect) {
4666
- if (!hookFiltered.includes(column))
4667
- hookFiltered.push(column);
4668
- }
5289
+ ctx.sql.push(selectToSql(ctx, q, data, quotedAs, tempSelect));
5290
+ return tempSelect;
5291
+ } else if (select) {
5292
+ ctx.sql.push(selectToSql(ctx, q, data, quotedAs));
4669
5293
  }
4670
- ctx.sql.push(keyword);
4671
- if (hookFiltered == null ? void 0 : hookFiltered.length) {
4672
- if (selected)
4673
- ctx.sql.push(`${selected},`);
4674
- ctx.sql.push(
4675
- hookFiltered.map((column) => ownColumnToSql(data, column, quotedAs)).join(", ")
4676
- );
4677
- } else {
4678
- ctx.sql.push(selected);
4679
- }
4680
- return hookFiltered;
5294
+ return;
4681
5295
  };
4682
5296
 
4683
5297
  const pushUpdateSql = (ctx, table, query, quotedAs) => {
@@ -5043,7 +5657,7 @@ const makeSQL = (table, options) => {
5043
5657
  if (query.for.mode)
5044
5658
  sql.push(query.for.mode);
5045
5659
  }
5046
- return { text: sql.join(" "), values };
5660
+ return { text: sql.join(" "), values, hookSelect: query.hookSelect };
5047
5661
  };
5048
5662
  function pushLimitSQL(sql, values, q) {
5049
5663
  if (!q.returnsOne) {
@@ -5076,6 +5690,8 @@ const cloneQuery = (q) => {
5076
5690
  q.with = q.with.slice(0);
5077
5691
  if (q.select)
5078
5692
  q.select = q.select.slice(0);
5693
+ if (q.hookSelect)
5694
+ q.hookSelect = new Map(q.hookSelect);
5079
5695
  if (q.and)
5080
5696
  q.and = q.and.slice(0);
5081
5697
  if (q.or)
@@ -5088,6 +5704,8 @@ const cloneQuery = (q) => {
5088
5704
  q.joinedShapes = __spreadValues$a({}, q.joinedShapes);
5089
5705
  if (q.scopes)
5090
5706
  q.scopes = __spreadValues$a({}, q.scopes);
5707
+ if (q.parsers)
5708
+ q.parsers = __spreadValues$a({}, q.parsers);
5091
5709
  if (q.updateData) {
5092
5710
  q.updateData = q.updateData.slice(
5093
5711
  0
@@ -5120,7 +5738,7 @@ const cloneQuery = (q) => {
5120
5738
  if (q.afterCreate) {
5121
5739
  q.afterCreate = q.afterCreate.slice(0);
5122
5740
  if (q.afterCreateSelect) {
5123
- q.afterCreateSelect = q.afterCreateSelect.slice(0);
5741
+ q.afterCreateSelect = new Set(q.afterCreateSelect);
5124
5742
  }
5125
5743
  }
5126
5744
  } else if (q.type === "update") {
@@ -5129,7 +5747,7 @@ const cloneQuery = (q) => {
5129
5747
  if (q.afterUpdate) {
5130
5748
  q.afterUpdate = q.afterUpdate.slice(0);
5131
5749
  if (q.afterUpdateSelect) {
5132
- q.afterUpdateSelect = q.afterUpdateSelect.slice(0);
5750
+ q.afterUpdateSelect = new Set(q.afterUpdateSelect);
5133
5751
  }
5134
5752
  }
5135
5753
  } else if (q.type === "delete") {
@@ -5138,7 +5756,7 @@ const cloneQuery = (q) => {
5138
5756
  if (q.afterDelete) {
5139
5757
  q.afterDelete = q.afterDelete.slice(0);
5140
5758
  if (q.afterDeleteSelect) {
5141
- q.afterDeleteSelect = q.afterDeleteSelect.slice(0);
5759
+ q.afterDeleteSelect = new Set(q.afterDeleteSelect);
5142
5760
  }
5143
5761
  }
5144
5762
  }
@@ -5163,8 +5781,6 @@ var __spreadValues$9 = (a, b) => {
5163
5781
  const getClonedQueryData = (query) => {
5164
5782
  const cloned = __spreadValues$9({}, query);
5165
5783
  delete cloned[toSQLCacheKey];
5166
- if (cloned.parsers)
5167
- cloned.parsers = __spreadValues$9({}, cloned.parsers);
5168
5784
  cloneQuery(cloned);
5169
5785
  return cloned;
5170
5786
  };
@@ -5369,12 +5985,14 @@ class VirtualColumn extends ColumnType {
5369
5985
  }
5370
5986
  }
5371
5987
 
5372
- class UnknownColumn extends VirtualColumn {
5988
+ const _UnknownColumn = class extends VirtualColumn {
5373
5989
  constructor(schema) {
5374
5990
  super(schema, schema.unknown());
5375
5991
  }
5376
- }
5377
- RawSQL.prototype.result = { value: new UnknownColumn(defaultSchemaConfig) };
5992
+ };
5993
+ let UnknownColumn = _UnknownColumn;
5994
+ UnknownColumn.instance = new _UnknownColumn(defaultSchemaConfig);
5995
+ RawSQL.prototype.result = { value: UnknownColumn.instance };
5378
5996
 
5379
5997
  const makeColumnsByType = (schema) => {
5380
5998
  const t = makeColumnTypes(schema);
@@ -6423,7 +7041,7 @@ const insert = (self, {
6423
7041
  q.values = values;
6424
7042
  if (!q.kind)
6425
7043
  q.kind = kind;
6426
- const { select, returnType = "all" } = q;
7044
+ const { select, returnType } = q;
6427
7045
  if (!select) {
6428
7046
  if (returnType !== "void")
6429
7047
  q.returnType = "rowCount";
@@ -6433,7 +7051,7 @@ const insert = (self, {
6433
7051
  } else if (returnType === "value" || returnType === "valueOrThrow") {
6434
7052
  q.returnType = "pluck";
6435
7053
  }
6436
- } else if (returnType === "all") {
7054
+ } else if (!returnType || returnType === "all") {
6437
7055
  q.returnType = "from" in values ? values.from.q.returnType : "one";
6438
7056
  } else if (returnType === "pluck") {
6439
7057
  q.returnType = "valueOrThrow";
@@ -6452,7 +7070,7 @@ const getFromSelectColumns = (from, obj, many) => {
6452
7070
  if (typeof item === "string") {
6453
7071
  const index = item.indexOf(".");
6454
7072
  queryColumns.push(index === -1 ? item : item.slice(index + 1));
6455
- } else if ("selectAs" in item) {
7073
+ } else if (item && "selectAs" in item) {
6456
7074
  queryColumns.push(...Object.keys(item.selectAs));
6457
7075
  }
6458
7076
  });
@@ -6496,12 +7114,7 @@ const _queryCreateMany = (q, data) => {
6496
7114
  };
6497
7115
  const _queryInsertMany = (q, data) => {
6498
7116
  const ctx = createCtx();
6499
- let result = insert(
6500
- q,
6501
- handleManyData(q, data, ctx),
6502
- "object",
6503
- true
6504
- );
7117
+ let result = insert(q, handleManyData(q, data, ctx), "object", true);
6505
7118
  if (!data.length)
6506
7119
  result = result.none();
6507
7120
  return result;
@@ -7314,11 +7927,15 @@ class Having {
7314
7927
  }
7315
7928
 
7316
7929
  const before = (q, key, cb) => pushQueryValue(q, `before${key}`, cb);
7317
- const after = (q, key, select, cb, commit) => pushQueryArray(
7318
- pushQueryValue(q, `after${key}${commit ? "Commit" : ""}`, cb),
7319
- `after${key}Select`,
7320
- select
7321
- );
7930
+ const after = (q, key, select, cb, commit) => {
7931
+ var _a, _b, _c;
7932
+ pushQueryValue(q, `after${key}${commit ? "Commit" : ""}`, cb);
7933
+ const set = (_c = (_a = q.q)[_b = `after${key}Select`]) != null ? _c : _a[_b] = /* @__PURE__ */ new Set();
7934
+ for (const column of select) {
7935
+ set.add(column);
7936
+ }
7937
+ return q;
7938
+ };
7322
7939
  const _queryHookBeforeQuery = (q, cb) => {
7323
7940
  return pushQueryValue(q, "before", cb);
7324
7941
  };
@@ -8379,7 +8996,9 @@ const mergableObjects = {
8379
8996
  parsers: true,
8380
8997
  defaults: true,
8381
8998
  joinedShapes: true,
8382
- joinedParsers: true
8999
+ joinedParsers: true,
9000
+ joinedBatchParsers: true,
9001
+ selectedComputeds: true
8383
9002
  };
8384
9003
  class MergeQueryMethods {
8385
9004
  merge(q) {
@@ -8404,6 +9023,8 @@ class MergeQueryMethods {
8404
9023
  b: a[key].b,
8405
9024
  u: [...a[key].u, ...value.u]
8406
9025
  } : value;
9026
+ } else if (value instanceof Set) {
9027
+ a[key] = a[key] ? /* @__PURE__ */ new Set([...a[key], ...value]) : value;
8407
9028
  } else {
8408
9029
  a[key] = value;
8409
9030
  }
@@ -8598,7 +9219,10 @@ class WithMethods {
8598
9219
  }
8599
9220
  pushQueryValue(q, "with", { n: name, o: options, q: query });
8600
9221
  const shape = getShapeFromSelect(query, true);
8601
- return setQueryObjectValue(q, "withShapes", name, shape);
9222
+ return setQueryObjectValue(q, "withShapes", name, {
9223
+ shape,
9224
+ computeds: query.q.computeds
9225
+ });
8602
9226
  }
8603
9227
  withRecursive(name, ...args) {
8604
9228
  var _a, _b, _c;
@@ -8607,10 +9231,9 @@ class WithMethods {
8607
9231
  const arg = q.queryBuilder.clone();
8608
9232
  arg.q.withShapes = q.q.withShapes;
8609
9233
  let query = typeof baseFn === "function" ? baseFn(arg) : baseFn;
8610
- const shape = ((_b = (_a = arg.q).withShapes) != null ? _b : _a.withShapes = {})[name] = getShapeFromSelect(
8611
- query,
8612
- true
8613
- );
9234
+ const shape = getShapeFromSelect(query, true);
9235
+ const withConfig = { shape, computeds: query.q.computeds };
9236
+ ((_b = (_a = arg.q).withShapes) != null ? _b : _a.withShapes = {})[name] = withConfig;
8614
9237
  const recursive = recursiveFn(arg);
8615
9238
  query = _queryUnion(query, [recursive], (_c = options.union) != null ? _c : "UNION ALL");
8616
9239
  options.recursive = true;
@@ -8620,7 +9243,7 @@ class WithMethods {
8620
9243
  });
8621
9244
  }
8622
9245
  pushQueryValue(q, "with", { n: name, o: options, q: query });
8623
- return setQueryObjectValue(q, "withShapes", name, shape);
9246
+ return setQueryObjectValue(q, "withShapes", name, withConfig);
8624
9247
  }
8625
9248
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
8626
9249
  withSql(name, ...args) {
@@ -8631,12 +9254,9 @@ class WithMethods {
8631
9254
  o: options,
8632
9255
  s: sql(q)
8633
9256
  });
8634
- return setQueryObjectValue(
8635
- q,
8636
- "withShapes",
8637
- name,
8638
- shape(this.columnTypes)
8639
- );
9257
+ return setQueryObjectValue(q, "withShapes", name, {
9258
+ shape: shape(this.columnTypes)
9259
+ });
8640
9260
  }
8641
9261
  }
8642
9262
 
@@ -10154,12 +10774,9 @@ function orCreate(q, data, updateData, mergeData) {
10154
10774
  if (mergeData)
10155
10775
  data = __spreadValues$1(__spreadValues$1({}, mergeData), data);
10156
10776
  const inner = q2.create(data);
10157
- const { handleResult: handleResult2 } = inner.q;
10158
10777
  inner.q.handleResult = (q3, t, r, s) => {
10159
- queryResult = r;
10160
- const res = handleResult2(q3, t, r, s);
10161
- result = res;
10162
- return res;
10778
+ result = handleResult(q3, t, r, s);
10779
+ return inner.q.hookSelect ? result.map((row) => __spreadValues$1({}, row)) : result;
10163
10780
  };
10164
10781
  await inner;
10165
10782
  created = true;
@@ -10807,8 +11424,13 @@ class QueryMethods {
10807
11424
  pluck(select) {
10808
11425
  const q = this.clone();
10809
11426
  q.q.returnType = "pluck";
10810
- q.q.select = [select];
10811
- addParserForSelectItem(q, q.q.as || q.table, "pluck", select);
11427
+ const selected = addParserForSelectItem(
11428
+ q,
11429
+ q.q.as || q.table,
11430
+ "pluck",
11431
+ select
11432
+ );
11433
+ q.q.select = selected ? [selected] : void 0;
10812
11434
  return q;
10813
11435
  }
10814
11436
  /**
@@ -11560,6 +12182,7 @@ class Db {
11560
12182
  tableData
11561
12183
  };
11562
12184
  this.baseQuery = this;
12185
+ this.relations = {};
11563
12186
  const logger = options.logger || console;
11564
12187
  const parsers = {};
11565
12188
  let hasParsers = false;
@@ -11610,6 +12233,7 @@ class Db {
11610
12233
  );
11611
12234
  }
11612
12235
  this.internal.columnsForSelectAll = list;
12236
+ this.internal.columnsKeysForSelectAll = __spreadValues({}, shape);
11613
12237
  }
11614
12238
  this.q = {
11615
12239
  adapter,
@@ -11648,6 +12272,8 @@ class Db {
11648
12272
  this.defaultSelectColumns = columns.filter(
11649
12273
  (column) => !shape[column].data.isHidden
11650
12274
  );
12275
+ if (options.computed)
12276
+ applyComputedColumns(this, options.computed);
11651
12277
  const defaultSelect = this.defaultSelectColumns.length === columns.length ? void 0 : this.defaultSelectColumns;
11652
12278
  this.toSQL = defaultSelect ? function(options2) {
11653
12279
  const q = this.clone();
@@ -11656,7 +12282,6 @@ class Db {
11656
12282
  }
11657
12283
  return toSQL.call(q, options2);
11658
12284
  } : toSQL;
11659
- this.relations = {};
11660
12285
  if (modifyQuery) {
11661
12286
  for (const cb of modifyQuery) {
11662
12287
  cb(this);
@@ -11954,16 +12579,6 @@ const testTransaction = {
11954
12579
  }
11955
12580
  };
11956
12581
 
11957
- function addComputedColumns(q, computed) {
11958
- const { shape } = q;
11959
- for (const key in computed) {
11960
- const expr = computed[key](q);
11961
- shape[key] = expr.result.value;
11962
- expr.result.value.data.computed = expr;
11963
- }
11964
- return q;
11965
- }
11966
-
11967
12582
  const rowToColumnInfo = (row) => {
11968
12583
  const typed = row;
11969
12584
  return {
@@ -12003,5 +12618,5 @@ function copyTableData(query, arg) {
12003
12618
  return q;
12004
12619
  }
12005
12620
 
12006
- export { Adapter, AggregateMethods, ArrayColumn, AsMethods, BigIntColumn, BigSerialColumn, BitColumn, BitVaryingColumn, BooleanColumn, BoxColumn, ByteaColumn, CidrColumn, CircleColumn, CitextColumn, Clear, ColumnRefExpression, ColumnType, Create, CustomTypeColumn, DateBaseColumn, DateColumn, DateTimeBaseClass, DateTimeTzBaseClass, Db, DecimalColumn, Delete, DomainColumn, DoublePrecisionColumn, DynamicRawSQL, EnumColumn, ExpressionMethods, FnExpression, For, FromMethods, Having, InetColumn, IntegerBaseColumn, IntegerColumn, IntervalColumn, JSONColumn, JSONTextColumn, Join, JsonMethods, LimitedTextBaseColumn, LineColumn, LsegColumn, MacAddr8Column, MacAddrColumn, MergeQueryMethods, MoneyColumn, MoreThanOneRowError, NotFoundError, NumberAsStringBaseColumn, NumberBaseColumn, OnConflictQueryBuilder, OnMethods, Operators, OrExpression, OrchidOrmError, OrchidOrmInternalError, PathColumn, PointColumn, PolygonColumn, QueryBase, QueryError, QueryGet, QueryHooks, QueryLog, QueryMethods, QueryUpsertOrCreate, RawSQL, RealColumn, RefExpression, SearchMethods, Select, SerialColumn, SmallIntColumn, SmallSerialColumn, SqlMethod, StringColumn, TextBaseColumn, TextColumn, Then, TimeColumn, TimestampColumn, TimestampTZColumn, Transaction, TransactionAdapter, TransformMethods, TsQueryColumn, TsVectorColumn, UUIDColumn, UnhandledTypeError, Union, UnknownColumn, Update, VarCharColumn, VirtualColumn, Where, WithMethods, XMLColumn, _initQueryBuilder, _queryAfterSaveCommit, _queryAll, _queryAs, _queryChangeCounter, _queryCreate, _queryCreateFrom, _queryCreateMany, _queryCreateManyFrom, _queryCreateManyRaw, _queryCreateRaw, _queryDefaults, _queryDelete, _queryExec, _queryFindBy, _queryFindByOptional, _queryGet, _queryGetOptional, _queryHookAfterCreate, _queryHookAfterCreateCommit, _queryHookAfterDelete, _queryHookAfterDeleteCommit, _queryHookAfterQuery, _queryHookAfterSave, _queryHookAfterUpdate, _queryHookAfterUpdateCommit, _queryHookBeforeCreate, _queryHookBeforeDelete, _queryHookBeforeQuery, _queryHookBeforeSave, _queryHookBeforeUpdate, _queryInsert, _queryInsertFrom, _queryInsertMany, _queryInsertManyFrom, _queryInsertManyRaw, _queryInsertRaw, _queryJoinOn, _queryJoinOnJsonPathEquals, _queryJoinOrOn, _queryOr, _queryOrNot, _queryRows, _querySelect, _queryTake, _queryTakeOptional, _queryUnion, _queryUpdate, _queryUpdateOrThrow, _queryUpdateRaw, _queryWhere, _queryWhereExists, _queryWhereIn, _queryWhereNot, _queryWhereNotSql, _queryWhereSql, addComputedColumns, addParserForRawExpression, addParserForSelectItem, addQueryOn, anyShape, checkIfASimpleQuery, cloneQuery, cloneQueryBaseUnscoped, columnCheckToCode, columnCode, columnForeignKeysToCode, columnIndexesToCode, columnsShapeToCode, commitSql$1 as commitSql, constraintInnerToCode, constraintToCode, copyTableData, countSelect, createDb, defaultSchemaConfig, extendQuery, foreignKeyArgumentToCode, getClonedQueryData, getColumnInfo, getColumnTypes, getPrimaryKeys, getQueryAs, getShapeFromSelect, getSqlText, handleResult, identityToCode, indexInnerToCode, indexToCode, instantiateColumn, isDefaultTimeStamp, isQueryReturnsAll, isSelectingCount, joinSubQuery, logColors, logParamToLogObject, makeColumnTypes, makeColumnsByType, makeFnExpression, makeRegexToFindInSql, makeSQL, parseRecord, parseResult, parseTableData, parseTableDataInput, primaryKeyInnerToCode, processSelectArg, pushLimitSQL, pushQueryArray, pushQueryOn, pushQueryOrOn, pushQueryValue, pushTableDataCode, queryFrom, queryFromSql, queryJson, queryMethodByReturnType, queryTypeWithLimitOne, queryWrap, quote, quoteString, raw, referencesArgsToCode, resolveSubQueryCallback, rollbackSql$1 as rollbackSql, saveSearchAlias, setParserForSelectedString, setQueryObjectValue, setQueryOperators, simplifyColumnDefault, sqlFn, sqlQueryArgsToExpression, tableDataMethods, templateLiteralToSQL, testTransaction, throwIfNoWhere, toSQL, toSQLCacheKey };
12621
+ export { Adapter, AggregateMethods, ArrayColumn, AsMethods, BigIntColumn, BigSerialColumn, BitColumn, BitVaryingColumn, BooleanColumn, BoxColumn, ByteaColumn, CidrColumn, CircleColumn, CitextColumn, Clear, ColumnRefExpression, ColumnType, ComputedColumn, Create, CustomTypeColumn, DateBaseColumn, DateColumn, DateTimeBaseClass, DateTimeTzBaseClass, Db, DecimalColumn, Delete, DomainColumn, DoublePrecisionColumn, DynamicRawSQL, EnumColumn, ExpressionMethods, FnExpression, For, FromMethods, Having, InetColumn, IntegerBaseColumn, IntegerColumn, IntervalColumn, JSONColumn, JSONTextColumn, Join, JsonMethods, LimitedTextBaseColumn, LineColumn, LsegColumn, MacAddr8Column, MacAddrColumn, MergeQueryMethods, MoneyColumn, MoreThanOneRowError, NotFoundError, NumberAsStringBaseColumn, NumberBaseColumn, OnConflictQueryBuilder, OnMethods, Operators, OrExpression, OrchidOrmError, OrchidOrmInternalError, PathColumn, PointColumn, PolygonColumn, QueryBase, QueryError, QueryGet, QueryHooks, QueryLog, QueryMethods, QueryUpsertOrCreate, RawSQL, RealColumn, RefExpression, SearchMethods, Select, SerialColumn, SmallIntColumn, SmallSerialColumn, SqlMethod, StringColumn, TextBaseColumn, TextColumn, Then, TimeColumn, TimestampColumn, TimestampTZColumn, Transaction, TransactionAdapter, TransformMethods, TsQueryColumn, TsVectorColumn, UUIDColumn, UnhandledTypeError, Union, UnknownColumn, Update, VarCharColumn, VirtualColumn, Where, WithMethods, XMLColumn, _initQueryBuilder, _queryAfterSaveCommit, _queryAll, _queryAs, _queryChangeCounter, _queryCreate, _queryCreateFrom, _queryCreateMany, _queryCreateManyFrom, _queryCreateManyRaw, _queryCreateRaw, _queryDefaults, _queryDelete, _queryExec, _queryFindBy, _queryFindByOptional, _queryGet, _queryGetOptional, _queryHookAfterCreate, _queryHookAfterCreateCommit, _queryHookAfterDelete, _queryHookAfterDeleteCommit, _queryHookAfterQuery, _queryHookAfterSave, _queryHookAfterUpdate, _queryHookAfterUpdateCommit, _queryHookBeforeCreate, _queryHookBeforeDelete, _queryHookBeforeQuery, _queryHookBeforeSave, _queryHookBeforeUpdate, _queryInsert, _queryInsertFrom, _queryInsertMany, _queryInsertManyFrom, _queryInsertManyRaw, _queryInsertRaw, _queryJoinOn, _queryJoinOnJsonPathEquals, _queryJoinOrOn, _queryOr, _queryOrNot, _queryRows, _querySelect, _queryTake, _queryTakeOptional, _queryUnion, _queryUpdate, _queryUpdateOrThrow, _queryUpdateRaw, _queryWhere, _queryWhereExists, _queryWhereIn, _queryWhereNot, _queryWhereNotSql, _queryWhereSql, addParserForRawExpression, addParserForSelectItem, addQueryOn, anyShape, applyComputedColumns, checkIfASimpleQuery, cloneQuery, cloneQueryBaseUnscoped, columnCheckToCode, columnCode, columnForeignKeysToCode, columnIndexesToCode, columnsShapeToCode, commitSql$1 as commitSql, constraintInnerToCode, constraintToCode, copyTableData, countSelect, createDb, defaultSchemaConfig, extendQuery, filterResult, foreignKeyArgumentToCode, getClonedQueryData, getColumnInfo, getColumnTypes, getPrimaryKeys, getQueryAs, getShapeFromSelect, getSqlText, handleResult, identityToCode, indexInnerToCode, indexToCode, instantiateColumn, isDefaultTimeStamp, isQueryReturnsAll, isSelectingCount, joinSubQuery, logColors, logParamToLogObject, makeColumnTypes, makeColumnsByType, makeFnExpression, makeRegexToFindInSql, makeSQL, parseRecord, parseTableData, parseTableDataInput, primaryKeyInnerToCode, processComputedBatches, processComputedResult, processSelectArg, pushLimitSQL, pushQueryArray, pushQueryOn, pushQueryOrOn, pushQueryValue, pushTableDataCode, queryFrom, queryFromSql, queryJson, queryMethodByReturnType, queryTypeWithLimitOne, queryWrap, quote, quoteString, raw, referencesArgsToCode, resolveSubQueryCallback, rollbackSql$1 as rollbackSql, saveSearchAlias, setParserForSelectedString, setQueryObjectValue, setQueryOperators, simplifyColumnDefault, sqlFn, sqlQueryArgsToExpression, tableDataMethods, templateLiteralToSQL, testTransaction, throwIfNoWhere, toSQL, toSQLCacheKey };
12007
12622
  //# sourceMappingURL=index.mjs.map