pqb 0.32.0 → 0.33.1

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, setParserToQuery, applyTransforms, 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, callWithThis, applyTransforms, 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';
@@ -879,6 +879,25 @@ const make = (_op) => {
879
879
  return setQueryOperators(this, boolean);
880
880
  },
881
881
  {
882
+ // function to turn the operator expression into SQL
883
+ _op
884
+ }
885
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
886
+ );
887
+ };
888
+ const makeVarArg = (_op) => {
889
+ return Object.assign(
890
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
891
+ function(...args) {
892
+ var _a, _b, _c;
893
+ ((_b = (_a = this.q).chain) != null ? _b : _a.chain = []).push(_op, args);
894
+ if ((_c = this.q.parsers) == null ? void 0 : _c[getValueKey]) {
895
+ this.q.parsers[getValueKey] = void 0;
896
+ }
897
+ return setQueryOperators(this, boolean);
898
+ },
899
+ {
900
+ // function to turn the operator expression into SQL
882
901
  _op
883
902
  }
884
903
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -961,15 +980,51 @@ const text = __spreadProps$7(__spreadValues$f({}, base), {
961
980
  (key, value, ctx, quotedAs) => `${key} LIKE '%' || ${quoteValue$1(value, ctx, quotedAs)}`
962
981
  )
963
982
  });
983
+ const encodeJsonPath = (ctx, path) => addValue(ctx.values, `{${Array.isArray(path) ? path.join(", ") : path}}`);
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" : ""})`;
964
985
  const json = __spreadProps$7(__spreadValues$f({}, base), {
965
- jsonPath: make(
966
- (key, [path, op, value], ctx, quotedAs) => `jsonb_path_query_first(${key}, '${path}') #>> '{}' ${op} ${value === null ? "null" : quoteValue$1(value, ctx, quotedAs, true)}`
986
+ jsonPathQueryFirst: Object.assign(
987
+ function(path, options) {
988
+ var _a, _b, _c, _d, _e;
989
+ ((_b = (_a = this.q).chain) != null ? _b : _a.chain = []).push(jsonPathQueryOp, [path, options]);
990
+ if ((_c = this.q.parsers) == null ? void 0 : _c[getValueKey]) {
991
+ this.q.parsers[getValueKey] = void 0;
992
+ }
993
+ if (options == null ? void 0 : options.type) {
994
+ const parse = options.type(this.columnTypes).parseFn;
995
+ if (parse)
996
+ ((_e = (_d = this.q).parsers) != null ? _e : _d.parsers = {})[getValueKey] = parse;
997
+ }
998
+ return this;
999
+ },
1000
+ { _op: jsonPathQueryOp }
967
1001
  ),
968
1002
  jsonSupersetOf: make(
969
1003
  (key, value, ctx, quotedAs) => `${key} @> ${quoteValue$1(value, ctx, quotedAs, true)}`
970
1004
  ),
971
1005
  jsonSubsetOf: make(
972
1006
  (key, value, ctx, quotedAs) => `${key} <@ ${quoteValue$1(value, ctx, quotedAs, true)}`
1007
+ ),
1008
+ jsonSet: makeVarArg(
1009
+ (key, [path, value], ctx) => `jsonb_set(${key}, ${encodeJsonPath(ctx, path)}, ${addValue(
1010
+ ctx.values,
1011
+ JSON.stringify(value)
1012
+ )})`
1013
+ ),
1014
+ jsonReplace: makeVarArg(
1015
+ (key, [path, value], ctx) => `jsonb_set(${key}, ${encodeJsonPath(ctx, path)}, ${addValue(
1016
+ ctx.values,
1017
+ JSON.stringify(value)
1018
+ )}, false)`
1019
+ ),
1020
+ jsonInsert: makeVarArg(
1021
+ (key, [path, value, options], ctx) => `jsonb_insert(${key}, ${encodeJsonPath(ctx, path)}, ${addValue(
1022
+ ctx.values,
1023
+ JSON.stringify(value)
1024
+ )}${(options == null ? void 0 : options.after) ? ", true" : ""})`
1025
+ ),
1026
+ jsonRemove: makeVarArg(
1027
+ (key, [path], ctx) => `(${key} #- ${encodeJsonPath(ctx, path)})`
973
1028
  )
974
1029
  });
975
1030
  const Operators = {
@@ -2075,9 +2130,13 @@ const processWhere = (ands, ctx, table, query, data, quotedAs) => {
2075
2130
  if ("prototype" in data || "baseQuery" in data) {
2076
2131
  const query2 = data;
2077
2132
  if (query2.q.expr) {
2078
- const q = joinSubQuery(table, query2);
2079
- q.q.select = [query2.q.expr];
2080
- ands.push(`(${getSqlText(makeSQL(q, ctx))})`);
2133
+ if (query2.q.subQuery === 1) {
2134
+ ands.push(selectToSql(ctx, table, query2.q, quotedAs));
2135
+ } else {
2136
+ const q = joinSubQuery(table, query2);
2137
+ q.q.select = [query2.q.expr];
2138
+ ands.push(`(${getSqlText(makeSQL(q, ctx))})`);
2139
+ }
2081
2140
  } else {
2082
2141
  pushWhereToSql(
2083
2142
  ands,
@@ -3304,9 +3363,7 @@ const then = async (q, adapter, trx, beforeHooks, afterHooks, afterCommitHooks,
3304
3363
  result = filterResult(q, returnType, queryResult, hookSelect, result);
3305
3364
  }
3306
3365
  if (query.transform) {
3307
- for (const fn of query.transform) {
3308
- result = fn(result);
3309
- }
3366
+ result = applyTransforms(returnType, query.transform, result);
3310
3367
  }
3311
3368
  return resolve == null ? void 0 : resolve(result);
3312
3369
  } catch (err) {
@@ -3524,10 +3581,8 @@ const addParserForSelectItem = (q, as, key, arg) => {
3524
3581
  setParserToQuery(q.q, key, (item) => {
3525
3582
  const t = query.returnType || "all";
3526
3583
  subQueryResult.rows = t === "value" || t === "valueOrThrow" ? [[item]] : t === "one" || t === "oneOrThrow" ? [item] : item;
3527
- return applyTransforms(
3528
- query.transform,
3529
- query.handleResult(arg, t, subQueryResult, true)
3530
- );
3584
+ const result = query.handleResult(arg, t, subQueryResult, true);
3585
+ return query.transform ? applyTransforms(t, query.transform, result) : result;
3531
3586
  });
3532
3587
  }
3533
3588
  if (query.returnType === "valueOrThrow" || query.returnType === "oneOrThrow") {
@@ -3608,7 +3663,7 @@ const processSelectArg = (q, as, arg, columnAs) => {
3608
3663
  (q2) => q2,
3609
3664
  key
3610
3665
  );
3611
- } else if (((_d = value.q) == null ? void 0 : _d.isSubQuery) && value.q.expr) {
3666
+ } else if (((_d = value.q) == null ? void 0 : _d.subQuery) && value.q.expr) {
3612
3667
  value = value.q.expr;
3613
3668
  }
3614
3669
  }
@@ -3783,7 +3838,7 @@ class SelectItemExpression extends Expression {
3783
3838
  // except that it will use non-aliasing `columnToSql` when `ctx.aliasValue` is true,
3784
3839
  // it is needed for relation sub-queries that returns a single column.
3785
3840
  makeSQL(ctx, quotedAs) {
3786
- return typeof this.item === "string" ? this.item === "*" ? selectAllSql(this.query, this.q, quotedAs) : ctx.aliasValue ? columnToSql(ctx, this.q, this.q.shape, this.item, quotedAs, true) : columnToSqlWithAs(ctx, this.q, this.item, quotedAs, true) : selectedObjectToSQL(ctx, this.query, quotedAs, this.item);
3841
+ return typeof this.item === "string" ? this.item === "*" ? selectAllSql(this.query, this.q, quotedAs) : ctx.aliasValue ? columnToSql(ctx, this.q, this.q.shape, this.item, quotedAs, true) : columnToSqlWithAs(ctx, this.q, this.item, quotedAs, true) : selectedObjectToSQL(ctx, quotedAs, this.item);
3787
3842
  }
3788
3843
  }
3789
3844
 
@@ -3991,50 +4046,6 @@ function queryJson(self, coalesce) {
3991
4046
  return q;
3992
4047
  }
3993
4048
 
3994
- const jsonColumnOrMethodToSql = (ctx, table, column, values, quotedAs) => {
3995
- return typeof column === "string" ? columnToSql(ctx, table.q, table.q.shape, column, quotedAs) : jsonToSql(ctx, table, column, values, quotedAs);
3996
- };
3997
- const jsonToSql = (ctx, table, item, values, quotedAs) => {
3998
- const json = item.__json;
3999
- if (json[0] === "pathQuery") {
4000
- const [, , , column, path, options] = json;
4001
- return `jsonb_path_query(${jsonColumnOrMethodToSql(
4002
- ctx,
4003
- table,
4004
- column,
4005
- values,
4006
- quotedAs
4007
- )}, ${addValue(values, path)}${(options == null ? void 0 : options.vars) ? `, ${addValue(values, options.vars)}` : ""}${(options == null ? void 0 : options.silent) ? ", true" : ""})`;
4008
- } else if (json[0] === "set") {
4009
- const [, , , column, path, value, options] = json;
4010
- return `jsonb_set(${jsonColumnOrMethodToSql(
4011
- ctx,
4012
- table,
4013
- column,
4014
- values,
4015
- quotedAs
4016
- )}, '{${path.join(", ")}}', ${addValue(values, JSON.stringify(value))}${(options == null ? void 0 : options.createIfMissing) ? ", true" : ""})`;
4017
- } else if (json[0] === "insert") {
4018
- const [, , , column, path, value, options] = json;
4019
- return `jsonb_insert(${jsonColumnOrMethodToSql(
4020
- ctx,
4021
- table,
4022
- column,
4023
- values,
4024
- quotedAs
4025
- )}, '{${path.join(", ")}}', ${addValue(values, JSON.stringify(value))}${(options == null ? void 0 : options.insertAfter) ? ", true" : ""})`;
4026
- } else if (json[0] === "remove") {
4027
- const [, , , column, path] = json;
4028
- return `${jsonColumnOrMethodToSql(
4029
- ctx,
4030
- table,
4031
- column,
4032
- values,
4033
- quotedAs
4034
- )} #- '{${path.join(", ")}}'`;
4035
- }
4036
- return "";
4037
- };
4038
4049
  const pushSelectSql = (ctx, table, query, quotedAs) => {
4039
4050
  ctx.sql.push(selectToSql(ctx, table, query, quotedAs));
4040
4051
  };
@@ -4068,7 +4079,7 @@ const selectToSql = (ctx, table, query, quotedAs) => {
4068
4079
  }
4069
4080
  }
4070
4081
  } else {
4071
- list.push(selectedObjectToSQL(ctx, table, quotedAs, item));
4082
+ list.push(selectedObjectToSQL(ctx, quotedAs, item));
4072
4083
  }
4073
4084
  }
4074
4085
  return list.join(", ");
@@ -4076,10 +4087,7 @@ const selectToSql = (ctx, table, query, quotedAs) => {
4076
4087
  return selectAllSql(table, query, quotedAs);
4077
4088
  };
4078
4089
  const selectedStringToSQL = (ctx, table, query, quotedAs, item) => item === "*" ? selectAllSql(table, query, quotedAs) : columnToSqlWithAs(ctx, table.q, item, quotedAs, true);
4079
- function selectedObjectToSQL(ctx, table, quotedAs, item) {
4080
- if ("__json" in item) {
4081
- return `${jsonToSql(ctx, table, item, ctx.values, quotedAs)} "${item.__json[1]}"`;
4082
- }
4090
+ function selectedObjectToSQL(ctx, quotedAs, item) {
4083
4091
  const sql = item.toSQL(ctx, quotedAs);
4084
4092
  return ctx.aliasValue ? `${sql} r` : sql;
4085
4093
  }
@@ -4769,11 +4777,12 @@ const processData = (ctx, table, set, data, quotedAs) => {
4769
4777
  };
4770
4778
  const processValue = (ctx, table, QueryClass, key, value, quotedAs) => {
4771
4779
  if (value && typeof value === "object") {
4772
- if (value.__json) {
4773
- return jsonToSql(ctx, table, value, ctx.values, quotedAs);
4774
- } else if (isExpression(value)) {
4780
+ if (isExpression(value)) {
4775
4781
  return value.toSQL(ctx, quotedAs);
4776
4782
  } else if (value instanceof QueryClass) {
4783
+ if (value.q.subQuery === 1) {
4784
+ return selectToSql(ctx, table, value.q, quotedAs);
4785
+ }
4777
4786
  return `(${getSqlText(
4778
4787
  joinSubQuery(table, value).toSQL(ctx)
4779
4788
  )})`;
@@ -5199,11 +5208,11 @@ const makeRegexToFindInSql = (value) => {
5199
5208
  return new RegExp(`${value}(?=(?:[^']*'[^']*')*[^']*$)`, "g");
5200
5209
  };
5201
5210
  const resolveSubQueryCallback = (q, cb) => {
5202
- const { isSubQuery, relChain } = q.q;
5203
- q.q.isSubQuery = true;
5211
+ const { subQuery, relChain } = q.q;
5212
+ q.q.subQuery = 1;
5204
5213
  q.q.relChain = void 0;
5205
5214
  const result = cb(q);
5206
- q.q.isSubQuery = isSubQuery;
5215
+ q.q.subQuery = subQuery;
5207
5216
  q.q.relChain = relChain;
5208
5217
  return result;
5209
5218
  };
@@ -6653,7 +6662,7 @@ class Create {
6653
6662
  * const createdCount = await db.table.insertMany([data, data, data]);
6654
6663
  * ```
6655
6664
  *
6656
- * Because of a limitation of Postgres protocol, queries having more than **65536** are going to fail in runtime.
6665
+ * Because of a limitation of Postgres protocol, queries having more than **65535** of values are going to fail in runtime.
6657
6666
  * To solve this seamlessly, OrchidORM will automatically batch such queries, and wrap them into a transaction, unless they are already in a transaction.
6658
6667
  *
6659
6668
  * ```ts
@@ -6698,7 +6707,10 @@ class Create {
6698
6707
  * @param args - object with columns list and raw SQL for values
6699
6708
  */
6700
6709
  createRaw(...args) {
6701
- return _queryCreateRaw(this.clone(), args);
6710
+ return _queryCreateRaw(
6711
+ this.clone(),
6712
+ args
6713
+ );
6702
6714
  }
6703
6715
  /**
6704
6716
  * Works exactly as {@link createRaw}, except that it returns inserted row count by default.
@@ -6706,7 +6718,10 @@ class Create {
6706
6718
  * @param args - object with columns list and raw SQL for values
6707
6719
  */
6708
6720
  insertRaw(...args) {
6709
- return _queryInsertRaw(this.clone(), args);
6721
+ return _queryInsertRaw(
6722
+ this.clone(),
6723
+ args
6724
+ );
6710
6725
  }
6711
6726
  /**
6712
6727
  * `createManyRaw` and `insertManyRaw` are for creating many record with raw SQL expressions.
@@ -6727,7 +6742,10 @@ class Create {
6727
6742
  * @param args - object with columns list and array of raw SQL for values
6728
6743
  */
6729
6744
  createManyRaw(...args) {
6730
- return _queryCreateManyRaw(this.clone(), args);
6745
+ return _queryCreateManyRaw(
6746
+ this.clone(),
6747
+ args
6748
+ );
6731
6749
  }
6732
6750
  /**
6733
6751
  * Works exactly as {@link createManyRaw}, except that it returns inserted row count by default.
@@ -6735,7 +6753,10 @@ class Create {
6735
6753
  * @param args - object with columns list and array of raw SQL for values
6736
6754
  */
6737
6755
  insertManyRaw(...args) {
6738
- return _queryInsertManyRaw(this.clone(), args);
6756
+ return _queryInsertManyRaw(
6757
+ this.clone(),
6758
+ args
6759
+ );
6739
6760
  }
6740
6761
  /**
6741
6762
  * These methods are for creating a single record, for batch creating see {@link createManyFrom}.
@@ -6777,7 +6798,11 @@ class Create {
6777
6798
  * @param data - additionally you can set some columns
6778
6799
  */
6779
6800
  createFrom(query, data) {
6780
- return _queryCreateFrom(this.clone(), query, data);
6801
+ return _queryCreateFrom(
6802
+ this.clone(),
6803
+ query,
6804
+ data
6805
+ );
6781
6806
  }
6782
6807
  /**
6783
6808
  * Works exactly as {@link createFrom}, except that it returns inserted row count by default.
@@ -6786,7 +6811,11 @@ class Create {
6786
6811
  * @param data - additionally you can set some columns
6787
6812
  */
6788
6813
  insertFrom(query, data) {
6789
- return _queryInsertFrom(this.clone(), query, data);
6814
+ return _queryInsertFrom(
6815
+ this.clone(),
6816
+ query,
6817
+ data
6818
+ );
6790
6819
  }
6791
6820
  /**
6792
6821
  * Similar to `createFrom`, but intended to create many records.
@@ -6802,7 +6831,10 @@ class Create {
6802
6831
  * @param query - query to create new records from
6803
6832
  */
6804
6833
  createManyFrom(query) {
6805
- return _queryCreateManyFrom(this.clone(), query);
6834
+ return _queryCreateManyFrom(
6835
+ this.clone(),
6836
+ query
6837
+ );
6806
6838
  }
6807
6839
  /**
6808
6840
  * Works exactly as {@link createManyFrom}, except that it returns inserted row count by default.
@@ -6810,7 +6842,10 @@ class Create {
6810
6842
  * @param query - query to create new records from
6811
6843
  */
6812
6844
  insertManyFrom(query) {
6813
- return _queryInsertManyFrom(this.clone(), query);
6845
+ return _queryInsertManyFrom(
6846
+ this.clone(),
6847
+ query
6848
+ );
6814
6849
  }
6815
6850
  /**
6816
6851
  * `defaults` allows setting values that will be used later in `create`.
@@ -6835,7 +6870,10 @@ class Create {
6835
6870
  * @param data - default values for `create` and `createMany` which will follow `defaults`
6836
6871
  */
6837
6872
  defaults(data) {
6838
- return _queryDefaults(this.clone(), data);
6873
+ return _queryDefaults(
6874
+ this.clone(),
6875
+ data
6876
+ );
6839
6877
  }
6840
6878
  /**
6841
6879
  * By default, violating unique constraint will cause the creative query to throw,
@@ -7297,9 +7335,7 @@ class Having {
7297
7335
  return pushQueryValue(
7298
7336
  q,
7299
7337
  "having",
7300
- args.map(
7301
- (arg) => arg(q).q.expr
7302
- )
7338
+ args.map((arg) => arg(q).q.expr)
7303
7339
  );
7304
7340
  }
7305
7341
  /**
@@ -8275,183 +8311,6 @@ class OnMethods {
8275
8311
  }
8276
8312
  }
8277
8313
 
8278
- class JsonModifiers {
8279
- /**
8280
- * Return a JSON value/object/array where a given value is set at the given path.
8281
- * The path is an array of keys to access the value.
8282
- *
8283
- * Can be used in `update` callback.
8284
- *
8285
- * ```ts
8286
- * const result = await db.table.jsonSet('data', ['name'], 'new value').take();
8287
- *
8288
- * expect(result.data).toEqual({ name: 'new value' });
8289
- * ```
8290
- *
8291
- * Optionally takes parameters of type `{ as?: string, createIfMissing?: boolean }`
8292
- *
8293
- * ```ts
8294
- * await db.table.jsonSet('data', ['name'], 'new value', {
8295
- * as: 'alias', // select data as `alias`
8296
- * createIfMissing: true, // ignored if missing by default
8297
- * });
8298
- * ```
8299
- *
8300
- * @param column - name of JSON column, or a result of a nested json method
8301
- * @param path - path to value inside the json
8302
- * @param value - value to set into the json
8303
- * @param options - `as` to alias the json value when selecting, `createIfMissing: true` will create a new JSON property if it didn't exist before
8304
- */
8305
- jsonSet(column, path, value, options) {
8306
- var _a;
8307
- const q = this.clone();
8308
- const json = {
8309
- __json: [
8310
- "set",
8311
- (_a = options == null ? void 0 : options.as) != null ? _a : typeof column === "string" ? column : column.__json[1],
8312
- typeof column === "string" ? q.q.shape[column] : column.__json[2],
8313
- column,
8314
- path,
8315
- value,
8316
- options
8317
- ]
8318
- };
8319
- return Object.assign(pushQueryValue(q, "select", json), json);
8320
- }
8321
- /**
8322
- * Return a JSON value/object/array where a given value is inserted at the given JSON path. Value can be a single value or JSON object. If a value exists at the given path, the value is not replaced.
8323
- *
8324
- * Can be used in `update` callback.
8325
- *
8326
- * ```ts
8327
- * // imagine user has data = { tags: ['two'] }
8328
- * const result = await db.table.jsonInsert('data', ['tags', 0], 'one').take();
8329
- *
8330
- * // 'one' is inserted to 0 position
8331
- * expect(result.data).toEqual({ tags: ['one', 'two'] });
8332
- * ```
8333
- *
8334
- * Optionally takes parameters of type `{ as?: string, insertAfter?: boolean }`
8335
- *
8336
- * ```ts
8337
- * // imagine user has data = { tags: ['one'] }
8338
- * const result = await db.table
8339
- * .jsonInsert('data', ['tags', 0], 'two', {
8340
- * as: 'alias', // select as an alias
8341
- * insertAfter: true, // insert after the specified position
8342
- * })
8343
- * .take();
8344
- *
8345
- * // 'one' is inserted to 0 position
8346
- * expect(result.alias).toEqual({ tags: ['one', 'two'] });
8347
- * ```
8348
- * @param column - name of JSON column, or a result of a nested json method
8349
- * @param path - path to the array inside the json, last path element is index to insert into
8350
- * @param value - value to insert into the json array
8351
- * @param options - `as` to alias the json value when selecting, `insertAfter: true` to insert after the specified position
8352
- */
8353
- jsonInsert(column, path, value, options) {
8354
- var _a;
8355
- const q = this.clone();
8356
- const json = {
8357
- __json: [
8358
- "insert",
8359
- (_a = options == null ? void 0 : options.as) != null ? _a : typeof column === "string" ? column : column.__json[1],
8360
- typeof column === "string" ? q.q.shape[column] : column.__json[2],
8361
- column,
8362
- path,
8363
- value,
8364
- options
8365
- ]
8366
- };
8367
- return Object.assign(pushQueryValue(q, "select", json), json);
8368
- }
8369
- /**
8370
- * Return a JSON value/object/array where a given value is removed at the given JSON path.
8371
- *
8372
- * Can be used in `update` callback.
8373
- *
8374
- * ```ts
8375
- * // imagine a user has data = { tags: ['one', 'two'] }
8376
- * const result = await db.table
8377
- * .jsonRemove(
8378
- * 'data',
8379
- * ['tags', 0],
8380
- * // optional parameters:
8381
- * {
8382
- * as: 'alias', // select as an alias
8383
- * },
8384
- * )
8385
- * .take();
8386
- *
8387
- * expect(result.alias).toEqual({ tags: ['two'] });
8388
- * ```
8389
- *
8390
- * @param column - name of JSON column, or a result of a nested json method
8391
- * @param path - path to the array inside the json, last path element is index to remove this element
8392
- * @param options - `as` to alias the json value when selecting
8393
- */
8394
- jsonRemove(column, path, options) {
8395
- var _a;
8396
- const q = this.clone();
8397
- const json = {
8398
- __json: [
8399
- "remove",
8400
- (_a = options == null ? void 0 : options.as) != null ? _a : typeof column === "string" ? column : column.__json[1],
8401
- typeof column === "string" ? q.q.shape[column] : column.__json[2],
8402
- column,
8403
- path
8404
- ]
8405
- };
8406
- return Object.assign(pushQueryValue(q, "select", json), json);
8407
- }
8408
- /**
8409
- * Selects a value from JSON data using a JSON path.
8410
- *
8411
- * ```ts
8412
- * import { columnTypes } from 'orchid-orm';
8413
- *
8414
- * db.table.jsonPathQuery(
8415
- * columnTypes.text(3, 100), // type of the value
8416
- * 'data', // name of the JSON column
8417
- * '$.name', // JSON path
8418
- * 'name', // select value as name
8419
- *
8420
- * // Optionally supports `vars` and `silent` options
8421
- * // check Postgres docs for jsonb_path_query for details
8422
- * {
8423
- * vars: 'vars',
8424
- * silent: true,
8425
- * },
8426
- * );
8427
- * ```
8428
- *
8429
- * Nested JSON operations can be used in place of JSON column name:
8430
- *
8431
- * ```ts
8432
- * db.table.jsonPathQuery(
8433
- * columnTypes.text(3, 100),
8434
- * // Available: .jsonSet, .jsonInsert, .jsonRemove
8435
- * db.table.jsonSet('data', ['key'], 'value'),
8436
- * '$.name',
8437
- * 'name',
8438
- * );
8439
- * ```
8440
- *
8441
- * @param type - provide a column type to have a correct result type
8442
- * @param column - name of JSON column, or a result of a nested json method
8443
- * @param path - special JSON path string to reference a JSON value
8444
- * @param as - optional alias for the selected value
8445
- * @param options - supports `vars` and `silent`, check Postgres docs of `json_path_query` for these
8446
- */
8447
- jsonPathQuery(type, column, path, as, options) {
8448
- const q = this.clone();
8449
- const json = {
8450
- __json: ["pathQuery", as, type, column, path, options]
8451
- };
8452
- return Object.assign(pushQueryValue(q, "select", json), json);
8453
- }
8454
- }
8455
8314
  class JsonMethods {
8456
8315
  /**
8457
8316
  * Wraps the query in a way to select a single JSON string.
@@ -8827,7 +8686,7 @@ const resolveCallbacksInArgs = (q, args) => {
8827
8686
  const qb = Object.create(q);
8828
8687
  qb.q = getClonedQueryData(q.q);
8829
8688
  qb.q.and = qb.q.or = qb.q.scopes = void 0;
8830
- qb.q.isSubQuery = true;
8689
+ qb.q.subQuery = 1;
8831
8690
  args[i] = resolveSubQueryCallback(qb, arg);
8832
8691
  }
8833
8692
  }
@@ -10526,6 +10385,8 @@ class TransformMethods {
10526
10385
  *
10527
10386
  * `transform` method should be called in the last order, other methods can't be chained after calling it.
10528
10387
  *
10388
+ * It is meant to transform the whole result of a query, for transforming individual records consider using {@link QueryMap.map}.
10389
+ *
10529
10390
  * The [hooks](/guide/hooks.html) that are going to run after the query will receive the query result **before** transferring.
10530
10391
  *
10531
10392
  * Consider the following example of a cursor-based pagination by `id`:
@@ -10577,6 +10438,52 @@ class TransformMethods {
10577
10438
  }
10578
10439
  }
10579
10440
 
10441
+ class QueryMap {
10442
+ /**
10443
+ * Use `map` to transform individual records of a query result.
10444
+ *
10445
+ * It accepts a single record and should return a single transformed record.
10446
+ *
10447
+ * For transforming the whole result of a query, consider using [transform](#transform) instead.
10448
+ *
10449
+ * The [hooks](/guide/hooks) that are going to run after the query will receive the query result **before** transformation.
10450
+ *
10451
+ * ```ts
10452
+ * // add a `titleLength` to every post
10453
+ * const posts = await db.post.limit(10).map((post) => ({
10454
+ * ...post,
10455
+ * titleLength: post.title.length,
10456
+ * }));
10457
+ *
10458
+ * posts[0].titleLength; // number
10459
+ *
10460
+ * // using the exact same `map` function to transform a single post
10461
+ * const singlePost = await db.post.find(id).map((post) => ({
10462
+ * ...post,
10463
+ * titleLength: post.title.length,
10464
+ * }));
10465
+ *
10466
+ * singlePost.titleLength; // number
10467
+ *
10468
+ * // can be used in sub-queries
10469
+ * const postsWithComments = await db.post.select('title', {
10470
+ * comments: (q) =>
10471
+ * q.comments.map((comment) => ({
10472
+ * ...comment,
10473
+ * truncatedContent: comment.content.slice(0, 100),
10474
+ * })),
10475
+ * });
10476
+ *
10477
+ * postsWithComments[0].comments[0].truncatedContent; // string
10478
+ * ```
10479
+ *
10480
+ * @param fn - function to transform an individual record
10481
+ */
10482
+ map(fn) {
10483
+ return pushQueryValue(this.clone(), "transform", { map: fn });
10484
+ }
10485
+ }
10486
+
10580
10487
  class ScopeMethods {
10581
10488
  /**
10582
10489
  * See {@link ScopeMethods}
@@ -11540,7 +11447,6 @@ applyMixins(QueryMethods, [
11540
11447
  OnMethods,
11541
11448
  WithMethods,
11542
11449
  Union,
11543
- JsonModifiers,
11544
11450
  JsonMethods,
11545
11451
  Create,
11546
11452
  Update,
@@ -11559,6 +11465,7 @@ applyMixins(QueryMethods, [
11559
11465
  MergeQueryMethods,
11560
11466
  SqlMethod,
11561
11467
  TransformMethods,
11468
+ QueryMap,
11562
11469
  ScopeMethods,
11563
11470
  SoftDeleteMethods,
11564
11471
  ExpressionMethods
@@ -12135,5 +12042,5 @@ function copyTableData(query, arg) {
12135
12042
  return q;
12136
12043
  }
12137
12044
 
12138
- export { Adapter, AggregateMethods, ArrayColumn, AsMethods, BigIntColumn, BigSerialColumn, BitColumn, BitVaryingColumn, BooleanColumn, BoxColumn, ByteaColumn, CharColumn, 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, JsonModifiers, 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 };
12045
+ export { Adapter, AggregateMethods, ArrayColumn, AsMethods, BigIntColumn, BigSerialColumn, BitColumn, BitVaryingColumn, BooleanColumn, BoxColumn, ByteaColumn, CharColumn, 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 };
12139
12046
  //# sourceMappingURL=index.mjs.map