pqb 0.30.7 → 0.31.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
@@ -3674,15 +3674,16 @@ class AsMethods {
3674
3674
  }
3675
3675
 
3676
3676
  function queryFrom(self, arg) {
3677
- var _a;
3677
+ var _a, _b;
3678
3678
  const data = self.q;
3679
3679
  if (typeof arg === "string") {
3680
3680
  data.as || (data.as = arg);
3681
+ data.shape = (_a = data.withShapes) == null ? void 0 : _a[arg];
3681
3682
  } else if (isExpression(arg)) {
3682
3683
  data.as || (data.as = "t");
3683
3684
  } else if (Array.isArray(arg)) {
3684
3685
  const { shape } = data;
3685
- const parsers = (_a = data.parsers) != null ? _a : data.parsers = {};
3686
+ const parsers = (_b = data.parsers) != null ? _b : data.parsers = {};
3686
3687
  for (const item of arg) {
3687
3688
  if (typeof item === "string") {
3688
3689
  const withShape = data.withShapes[item];
@@ -3712,7 +3713,7 @@ function queryFromSql(self, args) {
3712
3713
  data.from = sqlQueryArgsToExpression(args);
3713
3714
  return self;
3714
3715
  }
3715
- class From {
3716
+ class FromMethods {
3716
3717
  /**
3717
3718
  * Set the `FROM` value, by default the table name is used.
3718
3719
  *
@@ -4069,20 +4070,21 @@ const havingToSql = (ctx, query, quotedAs) => {
4069
4070
  ).join(" AND ");
4070
4071
  };
4071
4072
 
4072
- const pushWithSql = (ctx, withData) => {
4073
- if (!withData.length)
4073
+ const pushWithSql = (ctx, items) => {
4074
+ if (!items.length)
4074
4075
  return;
4075
4076
  ctx.sql.push(
4076
4077
  "WITH",
4077
- withData.map((withItem) => {
4078
- const [name, options, query] = withItem;
4078
+ items.map((item) => {
4079
+ var _a;
4079
4080
  let inner;
4080
- if (isExpression(query)) {
4081
- inner = query.toSQL(ctx, `"${name}"`);
4081
+ if (item.q) {
4082
+ inner = makeSQL(item.q, ctx).text;
4082
4083
  } else {
4083
- inner = makeSQL(query, ctx).text;
4084
+ inner = item.s.toSQL(ctx, `"${item.n}"`);
4084
4085
  }
4085
- return `${options.recursive ? "RECURSIVE " : ""}"${name}"${options.columns ? `(${options.columns.map((x) => `"${x}"`).join(", ")})` : ""} AS ${options.materialized ? "MATERIALIZED " : options.notMaterialized ? "NOT MATERIALIZED " : ""}(${inner})`;
4086
+ const o = (_a = item.o) != null ? _a : emptyObject;
4087
+ return `${o.recursive ? "RECURSIVE " : ""}"${item.n}"${o.columns ? `(${o.columns.map((x) => `"${x}"`).join(", ")})` : ""} AS ${o.materialized ? "MATERIALIZED " : o.notMaterialized ? "NOT MATERIALIZED " : ""}(${inner})`;
4086
4088
  }).join(", ")
4087
4089
  );
4088
4090
  };
@@ -4401,12 +4403,6 @@ const mergeColumnsSql = (quotedColumns2) => {
4401
4403
  };
4402
4404
  const encodeRow = (ctx, q, QueryClass, row, runtimeDefaults, quotedAs) => {
4403
4405
  const arr = row.map((value) => {
4404
- if (typeof value === "function") {
4405
- value = resolveSubQueryCallback(
4406
- q,
4407
- value
4408
- );
4409
- }
4410
4406
  if (value && typeof value === "object") {
4411
4407
  if (value instanceof Expression) {
4412
4408
  return value.toSQL(ctx, quotedAs);
@@ -4709,6 +4705,7 @@ const toSQL = (table, options) => {
4709
4705
  return !(options == null ? void 0 : options.clearCache) && table.q[toSQLCacheKey] || (table.q[toSQLCacheKey] = makeSQL(table, options));
4710
4706
  };
4711
4707
  const makeSQL = (table, options) => {
4708
+ var _a;
4712
4709
  const query = table.q;
4713
4710
  const sql = [];
4714
4711
  const values = (options == null ? void 0 : options.values) || [];
@@ -4722,24 +4719,21 @@ const makeSQL = (table, options) => {
4722
4719
  pushWithSql(ctx, query.with);
4723
4720
  }
4724
4721
  if (query.type) {
4722
+ const tableName = (_a = table.table) != null ? _a : query.as;
4723
+ if (!tableName)
4724
+ throw new Error(`Table is missing for ${query.type}`);
4725
4725
  if (query.type === "truncate") {
4726
- if (!table.table)
4727
- throw new Error("Table is missing for truncate");
4728
- pushTruncateSql(ctx, table.table, query);
4726
+ pushTruncateSql(ctx, tableName, query);
4729
4727
  return { text: sql.join(" "), values };
4730
4728
  }
4731
4729
  if (query.type === "columnInfo") {
4732
- if (!table.table)
4733
- throw new Error("Table is missing for truncate");
4734
4730
  pushColumnInfoSql(ctx, table, query);
4735
4731
  return { text: sql.join(" "), values };
4736
4732
  }
4737
- if (!table.table)
4738
- throw new Error(`Table is missing for ${query.type}`);
4739
- const quotedAs2 = `"${query.as || table.table}"`;
4733
+ const quotedAs2 = `"${query.as || tableName}"`;
4740
4734
  if (query.type === "insert") {
4741
4735
  return {
4742
- hookSelect: pushInsertSql(ctx, table, query, `"${table.table}"`),
4736
+ hookSelect: pushInsertSql(ctx, table, query, `"${tableName}"`),
4743
4737
  text: sql.join(" "),
4744
4738
  values
4745
4739
  };
@@ -4764,54 +4758,50 @@ const makeSQL = (table, options) => {
4764
4758
  }
4765
4759
  }
4766
4760
  const quotedAs = (query.as || table.table) && `"${query.as || table.table}"`;
4767
- sql.push("SELECT");
4768
- if (query.distinct) {
4769
- pushDistinctSql(ctx, table, query.distinct, quotedAs);
4770
- }
4771
- pushSelectSql(ctx, table, query, quotedAs);
4772
- if (table.table || query.from) {
4773
- pushFromAndAs(ctx, table, query, quotedAs);
4774
- }
4775
- if (query.join) {
4776
- pushJoinSql(
4777
- ctx,
4778
- table,
4779
- query,
4780
- quotedAs
4781
- );
4782
- }
4783
- if (query.and || query.or) {
4784
- pushWhereStatementSql(ctx, table, query, quotedAs);
4785
- }
4786
- if (query.group) {
4787
- const group = query.group.map(
4788
- (item) => isExpression(item) ? item.toSQL(ctx, quotedAs) : columnToSql(ctx, table.q, table.q.shape, item, quotedAs)
4789
- );
4790
- sql.push(`GROUP BY ${group.join(", ")}`);
4791
- }
4792
- if (query.having)
4793
- pushHavingSql(ctx, query, quotedAs);
4794
- if (query.window) {
4795
- const window = [];
4796
- query.window.forEach((item) => {
4797
- for (const key in item) {
4798
- window.push(
4799
- `"${key}" AS ${windowToSql(ctx, query, item[key], quotedAs)}`
4800
- );
4801
- }
4802
- });
4803
- sql.push(`WINDOW ${window.join(", ")}`);
4804
- }
4805
4761
  if (query.union) {
4806
- for (const item of query.union) {
4807
- let itemSql;
4808
- if (isExpression(item.arg)) {
4809
- itemSql = item.arg.toSQL(ctx, quotedAs);
4810
- } else {
4811
- const argSql = makeSQL(item.arg, { values });
4812
- itemSql = argSql.text;
4813
- }
4814
- sql.push(`${item.kind} ${item.wrap ? `(${itemSql})` : itemSql}`);
4762
+ sql.push(`(${makeSQL(query.union.b, { values }).text})`);
4763
+ for (const u of query.union.u) {
4764
+ const itemSql = isExpression(u.a) ? u.a.toSQL(ctx, quotedAs) : makeSQL(u.a, { values }).text;
4765
+ sql.push(`${u.k} (${itemSql})`);
4766
+ }
4767
+ } else {
4768
+ sql.push("SELECT");
4769
+ if (query.distinct) {
4770
+ pushDistinctSql(ctx, table, query.distinct, quotedAs);
4771
+ }
4772
+ pushSelectSql(ctx, table, query, quotedAs);
4773
+ if (table.table || query.from) {
4774
+ pushFromAndAs(ctx, table, query, quotedAs);
4775
+ }
4776
+ if (query.join) {
4777
+ pushJoinSql(
4778
+ ctx,
4779
+ table,
4780
+ query,
4781
+ quotedAs
4782
+ );
4783
+ }
4784
+ if (query.and || query.or) {
4785
+ pushWhereStatementSql(ctx, table, query, quotedAs);
4786
+ }
4787
+ if (query.group) {
4788
+ const group = query.group.map(
4789
+ (item) => isExpression(item) ? item.toSQL(ctx, quotedAs) : columnToSql(ctx, table.q, table.q.shape, item, quotedAs)
4790
+ );
4791
+ sql.push(`GROUP BY ${group.join(", ")}`);
4792
+ }
4793
+ if (query.having)
4794
+ pushHavingSql(ctx, query, quotedAs);
4795
+ if (query.window) {
4796
+ const window = [];
4797
+ query.window.forEach((item) => {
4798
+ for (const key in item) {
4799
+ window.push(
4800
+ `"${key}" AS ${windowToSql(ctx, query, item[key], quotedAs)}`
4801
+ );
4802
+ }
4803
+ });
4804
+ sql.push(`WINDOW ${window.join(", ")}`);
4815
4805
  }
4816
4806
  }
4817
4807
  if (query.order) {
@@ -4895,7 +4885,7 @@ const cloneQuery = (q) => {
4895
4885
  if (q.window)
4896
4886
  q.window = q.window.slice(0);
4897
4887
  if (q.union)
4898
- q.union = q.union.slice(0);
4888
+ q.union = { b: q.union.b, u: q.union.u.slice(0) };
4899
4889
  if (q.order)
4900
4890
  q.order = q.order.slice(0);
4901
4891
  } else if (q.type === "insert") {
@@ -6155,9 +6145,17 @@ const processCreateItem = (q, item, rowIndex, ctx, encoders) => {
6155
6145
  item,
6156
6146
  rowIndex
6157
6147
  );
6158
- } else if (!ctx.columns.has(key) && (shape[key] && !shape[key].data.computed || shape === anyShape)) {
6159
- ctx.columns.set(key, ctx.columns.size);
6160
- encoders[key] = (_c = shape[key]) == null ? void 0 : _c.encodeFn;
6148
+ } else {
6149
+ if (typeof item[key] === "function") {
6150
+ item[key] = resolveSubQueryCallback(
6151
+ q,
6152
+ item[key]
6153
+ );
6154
+ }
6155
+ if (!ctx.columns.has(key) && (shape[key] && !shape[key].data.computed || shape === anyShape)) {
6156
+ ctx.columns.set(key, ctx.columns.size);
6157
+ encoders[key] = (_c = shape[key]) == null ? void 0 : _c.encodeFn;
6158
+ }
6161
6159
  }
6162
6160
  }
6163
6161
  };
@@ -6363,6 +6361,22 @@ class Create {
6363
6361
  * });
6364
6362
  * ```
6365
6363
  *
6364
+ * `create` and `insert` can be used in {@link WithMethods.with} expressions:
6365
+ *
6366
+ * ```ts
6367
+ * db.$queryBuilder
6368
+ * // create a record in one table
6369
+ * .with('a', db.table.select('id').create(data))
6370
+ * // create a record in other table using the first table record id
6371
+ * .with('b', (q) =>
6372
+ * db.otherTable.select('id').create({
6373
+ * ...otherData,
6374
+ * aId: () => q.from('a').get('id'),
6375
+ * }),
6376
+ * )
6377
+ * .from('b');
6378
+ * ```
6379
+ *
6366
6380
  * @param data - data for the record, may have values, raw SQL, queries, relation operations.
6367
6381
  */
6368
6382
  create(data) {
@@ -6871,6 +6885,19 @@ class Delete {
6871
6885
  * // delete all users who have corresponding profile records:
6872
6886
  * db.table.join(Profile, 'profile.userId', 'user.id').all().delete();
6873
6887
  * ```
6888
+ *
6889
+ * `delete` can be used in {@link WithMethods.with} expressions:
6890
+ *
6891
+ * ```ts
6892
+ * db.$queryBuilder
6893
+ * // delete a record in one table
6894
+ * .with('a', db.table.find(1).select('id').delete())
6895
+ * // delete a record in other table using the first table record id
6896
+ * .with('b', (q) =>
6897
+ * db.otherTable.select('id').whereIn('aId', q.from('a').pluck('id')).delete(),
6898
+ * )
6899
+ * .from('b');
6900
+ * ```
6874
6901
  */
6875
6902
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
6876
6903
  delete(..._args) {
@@ -8293,6 +8320,11 @@ class MergeQueryMethods {
8293
8320
  a[key] = a[key] ? [...a[key], ...value] : value;
8294
8321
  } else if (mergableObjects[key]) {
8295
8322
  a[key] = a[key] ? __spreadValues$5(__spreadValues$5({}, a[key]), value) : value;
8323
+ } else if (key === "union") {
8324
+ a[key] = a[key] ? {
8325
+ b: a[key].b,
8326
+ u: [...a[key].u, ...value.u]
8327
+ } : value;
8296
8328
  } else {
8297
8329
  a[key] = value;
8298
8330
  }
@@ -8306,196 +8338,225 @@ class MergeQueryMethods {
8306
8338
  }
8307
8339
  }
8308
8340
 
8309
- var __defProp$4 = Object.defineProperty;
8310
- var __defProps$1 = Object.defineProperties;
8311
- var __getOwnPropDescs$1 = Object.getOwnPropertyDescriptors;
8312
- var __getOwnPropSymbols$4 = Object.getOwnPropertySymbols;
8313
- var __hasOwnProp$4 = Object.prototype.hasOwnProperty;
8314
- var __propIsEnum$4 = Object.prototype.propertyIsEnumerable;
8315
- var __defNormalProp$4 = (obj, key, value) => key in obj ? __defProp$4(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
8316
- var __spreadValues$4 = (a, b) => {
8317
- for (var prop in b || (b = {}))
8318
- if (__hasOwnProp$4.call(b, prop))
8319
- __defNormalProp$4(a, prop, b[prop]);
8320
- if (__getOwnPropSymbols$4)
8321
- for (var prop of __getOwnPropSymbols$4(b)) {
8322
- if (__propIsEnum$4.call(b, prop))
8323
- __defNormalProp$4(a, prop, b[prop]);
8324
- }
8325
- return a;
8341
+ const _queryUnion = (base, args, k) => {
8342
+ const q = base.baseQuery.clone();
8343
+ const u = args.map(
8344
+ (a) => ({
8345
+ a: typeof a === "function" ? a(q) : a,
8346
+ k
8347
+ })
8348
+ );
8349
+ const union = q.q.union = base.q.union;
8350
+ if (union) {
8351
+ union.u.push(...u);
8352
+ } else {
8353
+ q.q.union = {
8354
+ b: base,
8355
+ u
8356
+ };
8357
+ }
8358
+ return q;
8326
8359
  };
8327
- var __spreadProps$1 = (a, b) => __defProps$1(a, __getOwnPropDescs$1(b));
8328
- class With {
8360
+ class Union {
8329
8361
  /**
8330
- * Add Common Table Expression (CTE) to the query.
8362
+ * Creates a union query, takes one or more queries or SQL expressions.
8331
8363
  *
8332
8364
  * ```ts
8333
- * import { columnTypes } from 'orchid-orm';
8334
- * import { NumberColumn } from './number';
8335
- *
8336
- * // .with optionally accepts such options:
8337
- * type WithOptions = {
8338
- * // list of columns returned by this WITH statement
8339
- * // by default all columns from provided column shape will be included
8340
- * // true is for default behavior
8341
- * columns?: string[] | boolean;
8342
- *
8343
- * // Adds RECURSIVE keyword:
8344
- * recursive?: true;
8345
- *
8346
- * // Adds MATERIALIZED keyword:
8347
- * materialized?: true;
8348
- *
8349
- * // Adds NOT MATERIALIZED keyword:
8350
- * notMaterialized?: true;
8351
- * };
8352
- *
8353
- * // accepts columns shape and a raw expression:
8354
- * db.table.with(
8355
- * 'alias',
8356
- * {
8357
- * id: columnTypes.integer(),
8358
- * name: columnTypes.text(3, 100),
8359
- * },
8360
- * sql`SELECT id, name FROM "someTable"`,
8361
- * );
8362
- *
8363
- * // accepts query:
8364
- * db.table.with('alias', db.table.all());
8365
- *
8366
- * // accepts a callback for a query builder:
8367
- * db.table.with('alias', (qb) =>
8368
- * qb.select({ one: sql`1`.type((t) => t.integer()) }),
8369
- * );
8370
- *
8371
- * // All mentioned forms can accept options as a second argument:
8372
- * db.table.with(
8373
- * 'alias',
8374
- * {
8375
- * recursive: true,
8376
- * materialized: true,
8377
- * },
8378
- * rawOrQueryOrCallback,
8379
- * );
8365
+ * // The first query of the union
8366
+ * db.one
8367
+ * .select('id', 'name')
8368
+ * // add two more queries to the union
8369
+ * .union(
8370
+ * db.two.select('id', 'name'),
8371
+ * (q = q.sql`SELECT id, name FROM "thirdTable"`),
8372
+ * )
8373
+ * // sub-sequent `union` is equivalent to passing multiple queries into a single `union`
8374
+ * .union(db.three.select('id', 'name'));
8380
8375
  * ```
8381
8376
  *
8382
- * Defined `WITH` table can be used in `.from` or `.join` with all the type safeness:
8377
+ * `order`, `limit`, `offset` are special, it matters if you place them **before** or **after** the `union`, it also have a meaning to place them before and after.
8383
8378
  *
8384
8379
  * ```ts
8385
- * db.table.with('alias', db.table.all()).from('alias').select('alias.id');
8386
- *
8387
- * db.table
8388
- * .with('alias', db.table.all())
8389
- * .join('alias', 'alias.id', 'user.id')
8390
- * .select('alias.id');
8380
+ * // order, limit, offset are applied ONLY to 'one'
8381
+ * db.one
8382
+ * .order('x')
8383
+ * .limit(1)
8384
+ * .offset(1)
8385
+ * // 'two' also has order, limit, and offset
8386
+ * .unionAll(db.two.order('y').limit(2).offset(2))
8387
+ * // sets order, limit, offset for all records
8388
+ * .order('z')
8389
+ * .limit(3)
8390
+ * .offset(3);
8391
8391
  * ```
8392
8392
  *
8393
- * @param args - first argument is an alias for this CTE, other arguments can be column shape, query object, or raw SQL.
8394
- */
8395
- with(...args) {
8396
- const q = this.clone();
8397
- let options = args.length === 3 && !isExpression(args[2]) || args.length === 4 ? args[1] : void 0;
8398
- const last = args[args.length - 1];
8399
- const query = typeof last === "function" ? last(q.queryBuilder) : last;
8400
- const shape = args.length === 4 ? args[2] : isExpression(query) ? args[1] : query.q.shape;
8401
- if ((options == null ? void 0 : options.columns) === true) {
8402
- options = __spreadProps$1(__spreadValues$4({}, options), {
8403
- columns: Object.keys(shape)
8404
- });
8405
- }
8406
- pushQueryValue(q, "with", [args[0], options || emptyObject, query]);
8407
- return setQueryObjectValue(q, "withShapes", args[0], shape);
8408
- }
8409
- }
8410
-
8411
- class Union {
8412
- /**
8413
- * Creates a union query, taking an array or a list of callbacks, builders, or raw statements to build the union statement, with optional boolean `wrap`.
8414
- * If the `wrap` parameter is true, the queries will be individually wrapped in parentheses.
8393
+ * Equivalent SQL:
8415
8394
  *
8416
- * ```ts
8417
- * SomeTable.select('id', 'name').union(
8418
- * [
8419
- * OtherTable.select('id', 'name'),
8420
- * sql`SELECT id, name FROM "thirdTable"`,
8421
- * ],
8422
- * true, // optional wrap parameter
8423
- * );
8395
+ * ```sql
8396
+ * -- both union parts have their own order, limit, offset
8397
+ * ( SELECT * FROM one ORDER x ASC LIMIT 1 OFFSET 1 )
8398
+ * UNION ALL
8399
+ * ( SELECT * FROM two ORDER y ASC LIMIT 2 OFFSET 2 )
8400
+ * -- order, limit, offset of the whole query
8401
+ * ORDER BY z ASC LIMIT 3 OFFSET 3
8424
8402
  * ```
8425
8403
  *
8426
- * @param args - array of queries or raw SQLs
8427
- * @param wrap - provide `true` if you want the queries to be wrapped into parentheses
8404
+ * All the listed methods have the same signature, they are only different by SQL keyword:
8405
+ *
8406
+ * - `union` - union of all queries, performs deduplication
8407
+ * - `unionAll` - `union` that allows duplicated rows
8408
+ * - `intersect` - get only rows that are present in all queries
8409
+ * - `intersectAll` - `intersect` that allows duplicated rows
8410
+ * - `except` - get only rows that are in the first query but not in the second
8411
+ * - `exceptAll` - `except` that allows duplicated rows
8412
+ *
8413
+ * @param args - array of queries or SQL expressions
8428
8414
  */
8429
- union(args, wrap) {
8430
- return pushQueryArray(
8415
+ union(...args) {
8416
+ return _queryUnion(
8431
8417
  this.clone(),
8432
- "union",
8433
- args.map((arg) => ({ arg, kind: "UNION", wrap }))
8418
+ args,
8419
+ "UNION"
8434
8420
  );
8435
8421
  }
8436
8422
  /**
8437
- * Same as `union`, but allows duplicated rows.
8423
+ * Same as {@link union}, but allows duplicated rows.
8438
8424
  *
8439
- * @param args - array of queries or raw SQLs
8440
- * @param wrap - provide `true` if you want the queries to be wrapped into parentheses
8425
+ * @param args - array of queries or SQL expressions
8441
8426
  */
8442
- unionAll(args, wrap) {
8443
- return pushQueryArray(
8427
+ unionAll(...args) {
8428
+ return _queryUnion(
8444
8429
  this.clone(),
8445
- "union",
8446
- args.map((arg) => ({ arg, kind: "UNION ALL", wrap }))
8430
+ args,
8431
+ "UNION ALL"
8447
8432
  );
8448
8433
  }
8449
8434
  /**
8450
- * Same as `union`, but uses a `INTERSECT` SQL keyword instead
8435
+ * Same as {@link union}, but uses a `INTERSECT` SQL keyword instead
8451
8436
  *
8452
- * @param args - array of queries or raw SQLs
8453
- * @param wrap - provide `true` if you want the queries to be wrapped into parentheses
8437
+ * @param args - array of queries or SQL expressions
8454
8438
  */
8455
- intersect(args, wrap) {
8456
- return pushQueryArray(
8439
+ intersect(...args) {
8440
+ return _queryUnion(
8457
8441
  this.clone(),
8458
- "union",
8459
- args.map((arg) => ({ arg, kind: "INTERSECT", wrap }))
8442
+ args,
8443
+ "INTERSECT"
8460
8444
  );
8461
8445
  }
8462
8446
  /**
8463
- * Same as `intersect`, but allows duplicated rows.
8447
+ * Same as {@link intersect}, but allows duplicated rows.
8464
8448
  *
8465
- * @param args - array of queries or raw SQLs
8466
- * @param wrap - provide `true` if you want the queries to be wrapped into parentheses
8449
+ * @param args - array of queries or SQL expressions
8467
8450
  */
8468
- intersectAll(args, wrap) {
8469
- return pushQueryArray(
8451
+ intersectAll(...args) {
8452
+ return _queryUnion(
8470
8453
  this.clone(),
8471
- "union",
8472
- args.map((arg) => ({ arg, kind: "INTERSECT ALL", wrap }))
8454
+ args,
8455
+ "INTERSECT ALL"
8473
8456
  );
8474
8457
  }
8475
8458
  /**
8476
- * Same as `union`, but uses an `EXCEPT` SQL keyword instead
8459
+ * Same as {@link union}, but uses an `EXCEPT` SQL keyword instead
8477
8460
  *
8478
- * @param args - array of queries or raw SQLs
8479
- * @param wrap - provide `true` if you want the queries to be wrapped into parentheses
8461
+ * @param args - array of queries or SQL expressions
8480
8462
  */
8481
- except(args, wrap) {
8482
- return pushQueryArray(
8463
+ except(...args) {
8464
+ return _queryUnion(
8483
8465
  this.clone(),
8484
- "union",
8485
- args.map((arg) => ({ arg, kind: "EXCEPT", wrap }))
8466
+ args,
8467
+ "EXCEPT"
8486
8468
  );
8487
8469
  }
8488
8470
  /**
8489
- * Same as `except`, but allows duplicated rows.
8471
+ * Same as {@link except}, but allows duplicated rows.
8490
8472
  *
8491
- * @param args - array of queries or raw SQLs
8492
- * @param wrap - provide `true` if you want the queries to be wrapped into parentheses
8473
+ * @param args - array of queries or SQL expressions
8493
8474
  */
8494
- exceptAll(args, wrap) {
8495
- return pushQueryArray(
8475
+ exceptAll(...args) {
8476
+ return _queryUnion(
8496
8477
  this.clone(),
8497
- "union",
8498
- args.map((arg) => ({ arg, kind: "EXCEPT ALL", wrap }))
8478
+ args,
8479
+ "EXCEPT ALL"
8480
+ );
8481
+ }
8482
+ }
8483
+
8484
+ var __defProp$4 = Object.defineProperty;
8485
+ var __defProps$1 = Object.defineProperties;
8486
+ var __getOwnPropDescs$1 = Object.getOwnPropertyDescriptors;
8487
+ var __getOwnPropSymbols$4 = Object.getOwnPropertySymbols;
8488
+ var __hasOwnProp$4 = Object.prototype.hasOwnProperty;
8489
+ var __propIsEnum$4 = Object.prototype.propertyIsEnumerable;
8490
+ var __defNormalProp$4 = (obj, key, value) => key in obj ? __defProp$4(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
8491
+ var __spreadValues$4 = (a, b) => {
8492
+ for (var prop in b || (b = {}))
8493
+ if (__hasOwnProp$4.call(b, prop))
8494
+ __defNormalProp$4(a, prop, b[prop]);
8495
+ if (__getOwnPropSymbols$4)
8496
+ for (var prop of __getOwnPropSymbols$4(b)) {
8497
+ if (__propIsEnum$4.call(b, prop))
8498
+ __defNormalProp$4(a, prop, b[prop]);
8499
+ }
8500
+ return a;
8501
+ };
8502
+ var __spreadProps$1 = (a, b) => __defProps$1(a, __getOwnPropDescs$1(b));
8503
+ class WithMethods {
8504
+ with(name, second, third) {
8505
+ const q = this.clone();
8506
+ let [options, queryArg] = third ? [second, third] : [void 0, second];
8507
+ let query;
8508
+ if (typeof queryArg === "function") {
8509
+ const arg = q.queryBuilder.clone();
8510
+ arg.q.withShapes = q.q.withShapes;
8511
+ query = queryArg(arg);
8512
+ } else {
8513
+ query = queryArg;
8514
+ }
8515
+ if ((options == null ? void 0 : options.columns) === true) {
8516
+ options = __spreadProps$1(__spreadValues$4({}, options), {
8517
+ columns: Object.keys(query.shape)
8518
+ });
8519
+ }
8520
+ pushQueryValue(q, "with", { n: name, o: options, q: query });
8521
+ const shape = getShapeFromSelect(query, true);
8522
+ return setQueryObjectValue(q, "withShapes", name, shape);
8523
+ }
8524
+ withRecursive(name, ...args) {
8525
+ var _a, _b, _c;
8526
+ const q = this.clone();
8527
+ let [options, baseFn, recursiveFn] = args.length === 2 ? [{}, args[0], args[1]] : args;
8528
+ const arg = q.queryBuilder.clone();
8529
+ arg.q.withShapes = q.q.withShapes;
8530
+ let query = typeof baseFn === "function" ? baseFn(arg) : baseFn;
8531
+ const shape = ((_b = (_a = arg.q).withShapes) != null ? _b : _a.withShapes = {})[name] = getShapeFromSelect(
8532
+ query,
8533
+ true
8534
+ );
8535
+ const recursive = recursiveFn(arg);
8536
+ query = _queryUnion(query, [recursive], (_c = options.union) != null ? _c : "UNION ALL");
8537
+ options.recursive = true;
8538
+ if (options.columns === true) {
8539
+ options = __spreadProps$1(__spreadValues$4({}, options), {
8540
+ columns: Object.keys(shape)
8541
+ });
8542
+ }
8543
+ pushQueryValue(q, "with", { n: name, o: options, q: query });
8544
+ return setQueryObjectValue(q, "withShapes", name, shape);
8545
+ }
8546
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
8547
+ withSql(name, ...args) {
8548
+ const q = this.clone();
8549
+ const [options, shape, sql] = args.length === 2 ? [void 0, args[0], args[1]] : args;
8550
+ pushQueryValue(q, "with", {
8551
+ n: name,
8552
+ o: options,
8553
+ s: sql(q)
8554
+ });
8555
+ return setQueryObjectValue(
8556
+ q,
8557
+ "withShapes",
8558
+ name,
8559
+ shape(this.columnTypes)
8499
8560
  );
8500
8561
  }
8501
8562
  }
@@ -9329,11 +9390,10 @@ const _queryUpdate = (query, arg) => {
9329
9390
  "q",
9330
9391
  "withShapes"
9331
9392
  );
9332
- pushQueryValue(query, "with", [
9333
- as,
9334
- emptyObject,
9335
- value
9336
- ]);
9393
+ pushQueryValue(query, "with", {
9394
+ n: as,
9395
+ q: value
9396
+ });
9337
9397
  set[key] = new RawSQL(`(SELECT * FROM "${as}")`);
9338
9398
  }
9339
9399
  } else {
@@ -9500,7 +9560,24 @@ class Update {
9500
9560
  * })
9501
9561
  * ```
9502
9562
  *
9503
- * It is not supported because query inside `WITH` cannot reference the table in `UPDATE`.
9563
+ * `update` can be used in {@link WithMethods.with} expressions:
9564
+ *
9565
+ * ```ts
9566
+ * db.$queryBuilder
9567
+ * // update record in one table
9568
+ * .with('a', db.table.find(1).select('id').update(data))
9569
+ * // update record in other table using the first table record id
9570
+ * .with('b', (q) =>
9571
+ * db.otherTable
9572
+ * .find(1)
9573
+ * .select('id')
9574
+ * .update({
9575
+ * ...otherData,
9576
+ * aId: () => q.from('a').get('id'),
9577
+ * }),
9578
+ * )
9579
+ * .from('b');
9580
+ * ```
9504
9581
  *
9505
9582
  * ### null, undefined, unknown columns
9506
9583
  *
@@ -11294,10 +11371,10 @@ applyMixins(QueryMethods, [
11294
11371
  AsMethods,
11295
11372
  AggregateMethods,
11296
11373
  Select,
11297
- From,
11374
+ FromMethods,
11298
11375
  Join,
11299
11376
  OnMethods,
11300
- With,
11377
+ WithMethods,
11301
11378
  Union,
11302
11379
  JsonModifiers,
11303
11380
  JsonMethods,
@@ -11897,5 +11974,5 @@ function copyTableData(query, arg) {
11897
11974
  return q;
11898
11975
  }
11899
11976
 
11900
- 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, From, 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, With, 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, _queryUpdate, _queryUpdateOrThrow, _queryUpdateRaw, _queryWhere, _queryWhereExists, _queryWhereIn, _queryWhereNot, _queryWhereNotSql, _queryWhereSql, addComputedColumns, addParserForRawExpression, addParserForSelectItem, addQueryOn, anyShape, checkIfASimpleQuery, cloneQuery, cloneQueryBaseUnscoped, columnCheckToCode, columnCode, columnForeignKeysToCode, columnIndexesToCode, columnsShapeToCode, constraintInnerToCode, constraintToCode, copyTableData, countSelect, createDb, defaultSchemaConfig, extendQuery, foreignKeyArgumentToCode, getClonedQueryData, getColumnInfo, getColumnTypes, getPrimaryKeys, getQueryAs, getShapeFromSelect, 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, saveSearchAlias, setParserForSelectedString, setQueryObjectValue, setQueryOperators, simplifyColumnDefault, sqlFn, sqlQueryArgsToExpression, tableDataMethods, templateLiteralToSQL, testTransaction, throwIfNoWhere, toSQL, toSQLCacheKey };
11977
+ 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, constraintInnerToCode, constraintToCode, copyTableData, countSelect, createDb, defaultSchemaConfig, extendQuery, foreignKeyArgumentToCode, getClonedQueryData, getColumnInfo, getColumnTypes, getPrimaryKeys, getQueryAs, getShapeFromSelect, 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, saveSearchAlias, setParserForSelectedString, setQueryObjectValue, setQueryOperators, simplifyColumnDefault, sqlFn, sqlQueryArgsToExpression, tableDataMethods, templateLiteralToSQL, testTransaction, throwIfNoWhere, toSQL, toSQLCacheKey };
11901
11978
  //# sourceMappingURL=index.mjs.map