pqb 0.31.9 → 0.33.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.js CHANGED
@@ -881,6 +881,25 @@ const make = (_op) => {
881
881
  return setQueryOperators(this, boolean);
882
882
  },
883
883
  {
884
+ // function to turn the operator expression into SQL
885
+ _op
886
+ }
887
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
888
+ );
889
+ };
890
+ const makeVarArg = (_op) => {
891
+ return Object.assign(
892
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
893
+ function(...args) {
894
+ var _a, _b, _c;
895
+ ((_b = (_a = this.q).chain) != null ? _b : _a.chain = []).push(_op, args);
896
+ if ((_c = this.q.parsers) == null ? void 0 : _c[orchidCore.getValueKey]) {
897
+ this.q.parsers[orchidCore.getValueKey] = void 0;
898
+ }
899
+ return setQueryOperators(this, boolean);
900
+ },
901
+ {
902
+ // function to turn the operator expression into SQL
884
903
  _op
885
904
  }
886
905
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -963,15 +982,51 @@ const text = __spreadProps$7(__spreadValues$f({}, base), {
963
982
  (key, value, ctx, quotedAs) => `${key} LIKE '%' || ${quoteValue$1(value, ctx, quotedAs)}`
964
983
  )
965
984
  });
985
+ const encodeJsonPath = (ctx, path) => orchidCore.addValue(ctx.values, `{${Array.isArray(path) ? path.join(", ") : path}}`);
986
+ const jsonPathQueryOp = (key, [path, options], ctx) => `jsonb_path_query_first(${key}, ${orchidCore.addValue(ctx.values, path)}${(options == null ? void 0 : options.vars) ? `, ${orchidCore.addValue(ctx.values, JSON.stringify(options.vars))}${options.silent ? ", true" : ""}` : (options == null ? void 0 : options.silent) ? ", NULL, true" : ""})`;
966
987
  const json = __spreadProps$7(__spreadValues$f({}, base), {
967
- jsonPath: make(
968
- (key, [path, op, value], ctx, quotedAs) => `jsonb_path_query_first(${key}, '${path}') #>> '{}' ${op} ${value === null ? "null" : quoteValue$1(value, ctx, quotedAs, true)}`
988
+ jsonPathQueryFirst: Object.assign(
989
+ function(path, options) {
990
+ var _a, _b, _c, _d, _e;
991
+ ((_b = (_a = this.q).chain) != null ? _b : _a.chain = []).push(jsonPathQueryOp, [path, options]);
992
+ if ((_c = this.q.parsers) == null ? void 0 : _c[orchidCore.getValueKey]) {
993
+ this.q.parsers[orchidCore.getValueKey] = void 0;
994
+ }
995
+ if (options == null ? void 0 : options.type) {
996
+ const parse = options.type(this.columnTypes).parseFn;
997
+ if (parse)
998
+ ((_e = (_d = this.q).parsers) != null ? _e : _d.parsers = {})[orchidCore.getValueKey] = parse;
999
+ }
1000
+ return this;
1001
+ },
1002
+ { _op: jsonPathQueryOp }
969
1003
  ),
970
1004
  jsonSupersetOf: make(
971
1005
  (key, value, ctx, quotedAs) => `${key} @> ${quoteValue$1(value, ctx, quotedAs, true)}`
972
1006
  ),
973
1007
  jsonSubsetOf: make(
974
1008
  (key, value, ctx, quotedAs) => `${key} <@ ${quoteValue$1(value, ctx, quotedAs, true)}`
1009
+ ),
1010
+ jsonSet: makeVarArg(
1011
+ (key, [path, value], ctx) => `jsonb_set(${key}, ${encodeJsonPath(ctx, path)}, ${orchidCore.addValue(
1012
+ ctx.values,
1013
+ JSON.stringify(value)
1014
+ )})`
1015
+ ),
1016
+ jsonReplace: makeVarArg(
1017
+ (key, [path, value], ctx) => `jsonb_set(${key}, ${encodeJsonPath(ctx, path)}, ${orchidCore.addValue(
1018
+ ctx.values,
1019
+ JSON.stringify(value)
1020
+ )}, false)`
1021
+ ),
1022
+ jsonInsert: makeVarArg(
1023
+ (key, [path, value, options], ctx) => `jsonb_insert(${key}, ${encodeJsonPath(ctx, path)}, ${orchidCore.addValue(
1024
+ ctx.values,
1025
+ JSON.stringify(value)
1026
+ )}${(options == null ? void 0 : options.after) ? ", true" : ""})`
1027
+ ),
1028
+ jsonRemove: makeVarArg(
1029
+ (key, [path], ctx) => `(${key} #- ${encodeJsonPath(ctx, path)})`
975
1030
  )
976
1031
  });
977
1032
  const Operators = {
@@ -1740,7 +1795,8 @@ class BooleanColumn extends ColumnType {
1740
1795
  }
1741
1796
  }
1742
1797
 
1743
- const toCodeSkip = { encodeFn: JSON.stringify };
1798
+ const encodeFn = (x) => x === null ? x : JSON.stringify(x);
1799
+ const toCodeSkip = { encodeFn };
1744
1800
  class JSONColumn extends ColumnType {
1745
1801
  constructor() {
1746
1802
  super(...arguments);
@@ -1751,7 +1807,7 @@ class JSONColumn extends ColumnType {
1751
1807
  return columnCode(this, t, `json()`, m, this.data, toCodeSkip);
1752
1808
  }
1753
1809
  }
1754
- JSONColumn.prototype.encodeFn = JSON.stringify;
1810
+ JSONColumn.prototype.encodeFn = encodeFn;
1755
1811
  class JSONTextColumn extends ColumnType {
1756
1812
  constructor(schema) {
1757
1813
  super(schema, schema.stringSchema());
@@ -2076,9 +2132,13 @@ const processWhere = (ands, ctx, table, query, data, quotedAs) => {
2076
2132
  if ("prototype" in data || "baseQuery" in data) {
2077
2133
  const query2 = data;
2078
2134
  if (query2.q.expr) {
2079
- const q = joinSubQuery(table, query2);
2080
- q.q.select = [query2.q.expr];
2081
- ands.push(`(${getSqlText(makeSQL(q, ctx))})`);
2135
+ if (query2.q.subQuery === 1) {
2136
+ ands.push(selectToSql(ctx, table, query2.q, quotedAs));
2137
+ } else {
2138
+ const q = joinSubQuery(table, query2);
2139
+ q.q.select = [query2.q.expr];
2140
+ ands.push(`(${getSqlText(makeSQL(q, ctx))})`);
2141
+ }
2082
2142
  } else {
2083
2143
  pushWhereToSql(
2084
2144
  ands,
@@ -3609,7 +3669,7 @@ const processSelectArg = (q, as, arg, columnAs) => {
3609
3669
  (q2) => q2,
3610
3670
  key
3611
3671
  );
3612
- } else if (((_d = value.q) == null ? void 0 : _d.isSubQuery) && value.q.expr) {
3672
+ } else if (((_d = value.q) == null ? void 0 : _d.subQuery) && value.q.expr) {
3613
3673
  value = value.q.expr;
3614
3674
  }
3615
3675
  }
@@ -3784,7 +3844,7 @@ class SelectItemExpression extends orchidCore.Expression {
3784
3844
  // except that it will use non-aliasing `columnToSql` when `ctx.aliasValue` is true,
3785
3845
  // it is needed for relation sub-queries that returns a single column.
3786
3846
  makeSQL(ctx, quotedAs) {
3787
- 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);
3847
+ 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);
3788
3848
  }
3789
3849
  }
3790
3850
 
@@ -3992,50 +4052,6 @@ function queryJson(self, coalesce) {
3992
4052
  return q;
3993
4053
  }
3994
4054
 
3995
- const jsonColumnOrMethodToSql = (ctx, table, column, values, quotedAs) => {
3996
- return typeof column === "string" ? columnToSql(ctx, table.q, table.q.shape, column, quotedAs) : jsonToSql(ctx, table, column, values, quotedAs);
3997
- };
3998
- const jsonToSql = (ctx, table, item, values, quotedAs) => {
3999
- const json = item.__json;
4000
- if (json[0] === "pathQuery") {
4001
- const [, , , column, path, options] = json;
4002
- return `jsonb_path_query(${jsonColumnOrMethodToSql(
4003
- ctx,
4004
- table,
4005
- column,
4006
- values,
4007
- quotedAs
4008
- )}, ${orchidCore.addValue(values, path)}${(options == null ? void 0 : options.vars) ? `, ${orchidCore.addValue(values, options.vars)}` : ""}${(options == null ? void 0 : options.silent) ? ", true" : ""})`;
4009
- } else if (json[0] === "set") {
4010
- const [, , , column, path, value, options] = json;
4011
- return `jsonb_set(${jsonColumnOrMethodToSql(
4012
- ctx,
4013
- table,
4014
- column,
4015
- values,
4016
- quotedAs
4017
- )}, '{${path.join(", ")}}', ${orchidCore.addValue(values, JSON.stringify(value))}${(options == null ? void 0 : options.createIfMissing) ? ", true" : ""})`;
4018
- } else if (json[0] === "insert") {
4019
- const [, , , column, path, value, options] = json;
4020
- return `jsonb_insert(${jsonColumnOrMethodToSql(
4021
- ctx,
4022
- table,
4023
- column,
4024
- values,
4025
- quotedAs
4026
- )}, '{${path.join(", ")}}', ${orchidCore.addValue(values, JSON.stringify(value))}${(options == null ? void 0 : options.insertAfter) ? ", true" : ""})`;
4027
- } else if (json[0] === "remove") {
4028
- const [, , , column, path] = json;
4029
- return `${jsonColumnOrMethodToSql(
4030
- ctx,
4031
- table,
4032
- column,
4033
- values,
4034
- quotedAs
4035
- )} #- '{${path.join(", ")}}'`;
4036
- }
4037
- return "";
4038
- };
4039
4055
  const pushSelectSql = (ctx, table, query, quotedAs) => {
4040
4056
  ctx.sql.push(selectToSql(ctx, table, query, quotedAs));
4041
4057
  };
@@ -4069,7 +4085,7 @@ const selectToSql = (ctx, table, query, quotedAs) => {
4069
4085
  }
4070
4086
  }
4071
4087
  } else {
4072
- list.push(selectedObjectToSQL(ctx, table, quotedAs, item));
4088
+ list.push(selectedObjectToSQL(ctx, quotedAs, item));
4073
4089
  }
4074
4090
  }
4075
4091
  return list.join(", ");
@@ -4077,10 +4093,7 @@ const selectToSql = (ctx, table, query, quotedAs) => {
4077
4093
  return selectAllSql(table, query, quotedAs);
4078
4094
  };
4079
4095
  const selectedStringToSQL = (ctx, table, query, quotedAs, item) => item === "*" ? selectAllSql(table, query, quotedAs) : columnToSqlWithAs(ctx, table.q, item, quotedAs, true);
4080
- function selectedObjectToSQL(ctx, table, quotedAs, item) {
4081
- if ("__json" in item) {
4082
- return `${jsonToSql(ctx, table, item, ctx.values, quotedAs)} "${item.__json[1]}"`;
4083
- }
4096
+ function selectedObjectToSQL(ctx, quotedAs, item) {
4084
4097
  const sql = item.toSQL(ctx, quotedAs);
4085
4098
  return ctx.aliasValue ? `${sql} r` : sql;
4086
4099
  }
@@ -4770,11 +4783,12 @@ const processData = (ctx, table, set, data, quotedAs) => {
4770
4783
  };
4771
4784
  const processValue = (ctx, table, QueryClass, key, value, quotedAs) => {
4772
4785
  if (value && typeof value === "object") {
4773
- if (value.__json) {
4774
- return jsonToSql(ctx, table, value, ctx.values, quotedAs);
4775
- } else if (orchidCore.isExpression(value)) {
4786
+ if (orchidCore.isExpression(value)) {
4776
4787
  return value.toSQL(ctx, quotedAs);
4777
4788
  } else if (value instanceof QueryClass) {
4789
+ if (value.q.subQuery === 1) {
4790
+ return selectToSql(ctx, table, value.q, quotedAs);
4791
+ }
4778
4792
  return `(${getSqlText(
4779
4793
  joinSubQuery(table, value).toSQL(ctx)
4780
4794
  )})`;
@@ -5200,11 +5214,11 @@ const makeRegexToFindInSql = (value) => {
5200
5214
  return new RegExp(`${value}(?=(?:[^']*'[^']*')*[^']*$)`, "g");
5201
5215
  };
5202
5216
  const resolveSubQueryCallback = (q, cb) => {
5203
- const { isSubQuery, relChain } = q.q;
5204
- q.q.isSubQuery = true;
5217
+ const { subQuery, relChain } = q.q;
5218
+ q.q.subQuery = 1;
5205
5219
  q.q.relChain = void 0;
5206
5220
  const result = cb(q);
5207
- q.q.isSubQuery = isSubQuery;
5221
+ q.q.subQuery = subQuery;
5208
5222
  q.q.relChain = relChain;
5209
5223
  return result;
5210
5224
  };
@@ -6654,7 +6668,7 @@ class Create {
6654
6668
  * const createdCount = await db.table.insertMany([data, data, data]);
6655
6669
  * ```
6656
6670
  *
6657
- * Because of a limitation of Postgres protocol, queries having more than **65536** are going to fail in runtime.
6671
+ * Because of a limitation of Postgres protocol, queries having more than **65535** of values are going to fail in runtime.
6658
6672
  * To solve this seamlessly, OrchidORM will automatically batch such queries, and wrap them into a transaction, unless they are already in a transaction.
6659
6673
  *
6660
6674
  * ```ts
@@ -8276,183 +8290,6 @@ class OnMethods {
8276
8290
  }
8277
8291
  }
8278
8292
 
8279
- class JsonModifiers {
8280
- /**
8281
- * Return a JSON value/object/array where a given value is set at the given path.
8282
- * The path is an array of keys to access the value.
8283
- *
8284
- * Can be used in `update` callback.
8285
- *
8286
- * ```ts
8287
- * const result = await db.table.jsonSet('data', ['name'], 'new value').take();
8288
- *
8289
- * expect(result.data).toEqual({ name: 'new value' });
8290
- * ```
8291
- *
8292
- * Optionally takes parameters of type `{ as?: string, createIfMissing?: boolean }`
8293
- *
8294
- * ```ts
8295
- * await db.table.jsonSet('data', ['name'], 'new value', {
8296
- * as: 'alias', // select data as `alias`
8297
- * createIfMissing: true, // ignored if missing by default
8298
- * });
8299
- * ```
8300
- *
8301
- * @param column - name of JSON column, or a result of a nested json method
8302
- * @param path - path to value inside the json
8303
- * @param value - value to set into the json
8304
- * @param options - `as` to alias the json value when selecting, `createIfMissing: true` will create a new JSON property if it didn't exist before
8305
- */
8306
- jsonSet(column, path, value, options) {
8307
- var _a;
8308
- const q = this.clone();
8309
- const json = {
8310
- __json: [
8311
- "set",
8312
- (_a = options == null ? void 0 : options.as) != null ? _a : typeof column === "string" ? column : column.__json[1],
8313
- typeof column === "string" ? q.q.shape[column] : column.__json[2],
8314
- column,
8315
- path,
8316
- value,
8317
- options
8318
- ]
8319
- };
8320
- return Object.assign(pushQueryValue(q, "select", json), json);
8321
- }
8322
- /**
8323
- * 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.
8324
- *
8325
- * Can be used in `update` callback.
8326
- *
8327
- * ```ts
8328
- * // imagine user has data = { tags: ['two'] }
8329
- * const result = await db.table.jsonInsert('data', ['tags', 0], 'one').take();
8330
- *
8331
- * // 'one' is inserted to 0 position
8332
- * expect(result.data).toEqual({ tags: ['one', 'two'] });
8333
- * ```
8334
- *
8335
- * Optionally takes parameters of type `{ as?: string, insertAfter?: boolean }`
8336
- *
8337
- * ```ts
8338
- * // imagine user has data = { tags: ['one'] }
8339
- * const result = await db.table
8340
- * .jsonInsert('data', ['tags', 0], 'two', {
8341
- * as: 'alias', // select as an alias
8342
- * insertAfter: true, // insert after the specified position
8343
- * })
8344
- * .take();
8345
- *
8346
- * // 'one' is inserted to 0 position
8347
- * expect(result.alias).toEqual({ tags: ['one', 'two'] });
8348
- * ```
8349
- * @param column - name of JSON column, or a result of a nested json method
8350
- * @param path - path to the array inside the json, last path element is index to insert into
8351
- * @param value - value to insert into the json array
8352
- * @param options - `as` to alias the json value when selecting, `insertAfter: true` to insert after the specified position
8353
- */
8354
- jsonInsert(column, path, value, options) {
8355
- var _a;
8356
- const q = this.clone();
8357
- const json = {
8358
- __json: [
8359
- "insert",
8360
- (_a = options == null ? void 0 : options.as) != null ? _a : typeof column === "string" ? column : column.__json[1],
8361
- typeof column === "string" ? q.q.shape[column] : column.__json[2],
8362
- column,
8363
- path,
8364
- value,
8365
- options
8366
- ]
8367
- };
8368
- return Object.assign(pushQueryValue(q, "select", json), json);
8369
- }
8370
- /**
8371
- * Return a JSON value/object/array where a given value is removed at the given JSON path.
8372
- *
8373
- * Can be used in `update` callback.
8374
- *
8375
- * ```ts
8376
- * // imagine a user has data = { tags: ['one', 'two'] }
8377
- * const result = await db.table
8378
- * .jsonRemove(
8379
- * 'data',
8380
- * ['tags', 0],
8381
- * // optional parameters:
8382
- * {
8383
- * as: 'alias', // select as an alias
8384
- * },
8385
- * )
8386
- * .take();
8387
- *
8388
- * expect(result.alias).toEqual({ tags: ['two'] });
8389
- * ```
8390
- *
8391
- * @param column - name of JSON column, or a result of a nested json method
8392
- * @param path - path to the array inside the json, last path element is index to remove this element
8393
- * @param options - `as` to alias the json value when selecting
8394
- */
8395
- jsonRemove(column, path, options) {
8396
- var _a;
8397
- const q = this.clone();
8398
- const json = {
8399
- __json: [
8400
- "remove",
8401
- (_a = options == null ? void 0 : options.as) != null ? _a : typeof column === "string" ? column : column.__json[1],
8402
- typeof column === "string" ? q.q.shape[column] : column.__json[2],
8403
- column,
8404
- path
8405
- ]
8406
- };
8407
- return Object.assign(pushQueryValue(q, "select", json), json);
8408
- }
8409
- /**
8410
- * Selects a value from JSON data using a JSON path.
8411
- *
8412
- * ```ts
8413
- * import { columnTypes } from 'orchid-orm';
8414
- *
8415
- * db.table.jsonPathQuery(
8416
- * columnTypes.text(3, 100), // type of the value
8417
- * 'data', // name of the JSON column
8418
- * '$.name', // JSON path
8419
- * 'name', // select value as name
8420
- *
8421
- * // Optionally supports `vars` and `silent` options
8422
- * // check Postgres docs for jsonb_path_query for details
8423
- * {
8424
- * vars: 'vars',
8425
- * silent: true,
8426
- * },
8427
- * );
8428
- * ```
8429
- *
8430
- * Nested JSON operations can be used in place of JSON column name:
8431
- *
8432
- * ```ts
8433
- * db.table.jsonPathQuery(
8434
- * columnTypes.text(3, 100),
8435
- * // Available: .jsonSet, .jsonInsert, .jsonRemove
8436
- * db.table.jsonSet('data', ['key'], 'value'),
8437
- * '$.name',
8438
- * 'name',
8439
- * );
8440
- * ```
8441
- *
8442
- * @param type - provide a column type to have a correct result type
8443
- * @param column - name of JSON column, or a result of a nested json method
8444
- * @param path - special JSON path string to reference a JSON value
8445
- * @param as - optional alias for the selected value
8446
- * @param options - supports `vars` and `silent`, check Postgres docs of `json_path_query` for these
8447
- */
8448
- jsonPathQuery(type, column, path, as, options) {
8449
- const q = this.clone();
8450
- const json = {
8451
- __json: ["pathQuery", as, type, column, path, options]
8452
- };
8453
- return Object.assign(pushQueryValue(q, "select", json), json);
8454
- }
8455
- }
8456
8293
  class JsonMethods {
8457
8294
  /**
8458
8295
  * Wraps the query in a way to select a single JSON string.
@@ -8828,7 +8665,7 @@ const resolveCallbacksInArgs = (q, args) => {
8828
8665
  const qb = Object.create(q);
8829
8666
  qb.q = getClonedQueryData(q.q);
8830
8667
  qb.q.and = qb.q.or = qb.q.scopes = void 0;
8831
- qb.q.isSubQuery = true;
8668
+ qb.q.subQuery = 1;
8832
8669
  args[i] = resolveSubQueryCallback(qb, arg);
8833
8670
  }
8834
8671
  }
@@ -11541,7 +11378,6 @@ orchidCore.applyMixins(QueryMethods, [
11541
11378
  OnMethods,
11542
11379
  WithMethods,
11543
11380
  Union,
11544
- JsonModifiers,
11545
11381
  JsonMethods,
11546
11382
  Create,
11547
11383
  Update,
@@ -12180,7 +12016,6 @@ exports.JSONColumn = JSONColumn;
12180
12016
  exports.JSONTextColumn = JSONTextColumn;
12181
12017
  exports.Join = Join;
12182
12018
  exports.JsonMethods = JsonMethods;
12183
- exports.JsonModifiers = JsonModifiers;
12184
12019
  exports.LimitedTextBaseColumn = LimitedTextBaseColumn;
12185
12020
  exports.LineColumn = LineColumn;
12186
12021
  exports.LsegColumn = LsegColumn;