pqb 0.30.6 → 0.31.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, 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, setParserToQuery, applyTransforms, 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';
@@ -2377,25 +2377,14 @@ const subJoinToSql = (ctx, jq, innerAs, outerAs, cloned) => {
2377
2377
  }).text}) ${outerAs || innerAs}`;
2378
2378
  };
2379
2379
  const processArgs = (args, ctx, query, joinAs, joinShape, quotedAs) => {
2380
- if (args.length === 1) {
2381
- return getObjectOrRawConditions(
2382
- ctx,
2383
- query,
2384
- args[0],
2385
- quotedAs,
2386
- joinAs,
2387
- joinShape
2388
- );
2389
- } else {
2390
- return getConditionsFor3Or4LengthItem(
2391
- ctx,
2392
- query,
2393
- joinAs,
2394
- quotedAs,
2395
- args,
2396
- joinShape
2397
- );
2398
- }
2380
+ return args.length === 1 ? getObjectOrRawConditions(ctx, query, args[0], quotedAs, joinAs, joinShape) : getConditionsFor3Or4LengthItem(
2381
+ ctx,
2382
+ query,
2383
+ joinAs,
2384
+ quotedAs,
2385
+ args,
2386
+ joinShape
2387
+ );
2399
2388
  };
2400
2389
  const getConditionsFor3Or4LengthItem = (ctx, query, target, quotedAs, args, joinShape) => {
2401
2390
  const [leftColumn, opOrRightColumn, maybeRightColumn] = args;
@@ -2548,7 +2537,9 @@ const processJoinArgs = (joinTo, first, args, joinSubQuery) => {
2548
2537
  );
2549
2538
  return { w: first, r, s: joinSubQuery || getIsJoinSubQuery(r) };
2550
2539
  }
2551
- } else if (typeof args[0] === "function") {
2540
+ }
2541
+ const args0 = args.length ? args[0] : returnArg$1;
2542
+ if (typeof args0 === "function") {
2552
2543
  const q = first;
2553
2544
  if (q.joinQueryAfterCallback) {
2554
2545
  let base = q.baseQuery;
@@ -2566,7 +2557,7 @@ const processJoinArgs = (joinTo, first, args, joinSubQuery) => {
2566
2557
  const joinedShapes = __spreadProps$4(__spreadValues$c({}, joinTo.q.joinedShapes), {
2567
2558
  [joinTo.q.as || joinTo.table]: joinTo.shape
2568
2559
  });
2569
- const r = args[0](
2560
+ const r = args0(
2570
2561
  makeJoinQueryBuilder(
2571
2562
  q,
2572
2563
  q.q.joinedShapes ? __spreadValues$c(__spreadValues$c({}, q.q.joinedShapes), joinedShapes) : joinedShapes,
@@ -3683,15 +3674,16 @@ class AsMethods {
3683
3674
  }
3684
3675
 
3685
3676
  function queryFrom(self, arg) {
3686
- var _a;
3677
+ var _a, _b;
3687
3678
  const data = self.q;
3688
3679
  if (typeof arg === "string") {
3689
3680
  data.as || (data.as = arg);
3681
+ data.shape = (_a = data.withShapes) == null ? void 0 : _a[arg];
3690
3682
  } else if (isExpression(arg)) {
3691
3683
  data.as || (data.as = "t");
3692
3684
  } else if (Array.isArray(arg)) {
3693
3685
  const { shape } = data;
3694
- const parsers = (_a = data.parsers) != null ? _a : data.parsers = {};
3686
+ const parsers = (_b = data.parsers) != null ? _b : data.parsers = {};
3695
3687
  for (const item of arg) {
3696
3688
  if (typeof item === "string") {
3697
3689
  const withShape = data.withShapes[item];
@@ -3721,7 +3713,7 @@ function queryFromSql(self, args) {
3721
3713
  data.from = sqlQueryArgsToExpression(args);
3722
3714
  return self;
3723
3715
  }
3724
- class From {
3716
+ class FromMethods {
3725
3717
  /**
3726
3718
  * Set the `FROM` value, by default the table name is used.
3727
3719
  *
@@ -4078,20 +4070,21 @@ const havingToSql = (ctx, query, quotedAs) => {
4078
4070
  ).join(" AND ");
4079
4071
  };
4080
4072
 
4081
- const pushWithSql = (ctx, withData) => {
4082
- if (!withData.length)
4073
+ const pushWithSql = (ctx, items) => {
4074
+ if (!items.length)
4083
4075
  return;
4084
4076
  ctx.sql.push(
4085
4077
  "WITH",
4086
- withData.map((withItem) => {
4087
- const [name, options, query] = withItem;
4078
+ items.map((item) => {
4079
+ var _a;
4088
4080
  let inner;
4089
- if (isExpression(query)) {
4090
- inner = query.toSQL(ctx, `"${name}"`);
4081
+ if (item.q) {
4082
+ inner = makeSQL(item.q, ctx).text;
4091
4083
  } else {
4092
- inner = makeSQL(query, ctx).text;
4084
+ inner = item.s.toSQL(ctx, `"${item.n}"`);
4093
4085
  }
4094
- 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})`;
4095
4088
  }).join(", ")
4096
4089
  );
4097
4090
  };
@@ -4773,54 +4766,50 @@ const makeSQL = (table, options) => {
4773
4766
  }
4774
4767
  }
4775
4768
  const quotedAs = (query.as || table.table) && `"${query.as || table.table}"`;
4776
- sql.push("SELECT");
4777
- if (query.distinct) {
4778
- pushDistinctSql(ctx, table, query.distinct, quotedAs);
4779
- }
4780
- pushSelectSql(ctx, table, query, quotedAs);
4781
- if (table.table || query.from) {
4782
- pushFromAndAs(ctx, table, query, quotedAs);
4783
- }
4784
- if (query.join) {
4785
- pushJoinSql(
4786
- ctx,
4787
- table,
4788
- query,
4789
- quotedAs
4790
- );
4791
- }
4792
- if (query.and || query.or) {
4793
- pushWhereStatementSql(ctx, table, query, quotedAs);
4794
- }
4795
- if (query.group) {
4796
- const group = query.group.map(
4797
- (item) => isExpression(item) ? item.toSQL(ctx, quotedAs) : columnToSql(ctx, table.q, table.q.shape, item, quotedAs)
4798
- );
4799
- sql.push(`GROUP BY ${group.join(", ")}`);
4800
- }
4801
- if (query.having)
4802
- pushHavingSql(ctx, query, quotedAs);
4803
- if (query.window) {
4804
- const window = [];
4805
- query.window.forEach((item) => {
4806
- for (const key in item) {
4807
- window.push(
4808
- `"${key}" AS ${windowToSql(ctx, query, item[key], quotedAs)}`
4809
- );
4810
- }
4811
- });
4812
- sql.push(`WINDOW ${window.join(", ")}`);
4813
- }
4814
4769
  if (query.union) {
4815
- for (const item of query.union) {
4816
- let itemSql;
4817
- if (isExpression(item.arg)) {
4818
- itemSql = item.arg.toSQL(ctx, quotedAs);
4819
- } else {
4820
- const argSql = makeSQL(item.arg, { values });
4821
- itemSql = argSql.text;
4822
- }
4823
- sql.push(`${item.kind} ${item.wrap ? `(${itemSql})` : itemSql}`);
4770
+ sql.push(`(${makeSQL(query.union.b, { values }).text})`);
4771
+ for (const u of query.union.u) {
4772
+ const itemSql = isExpression(u.a) ? u.a.toSQL(ctx, quotedAs) : makeSQL(u.a, { values }).text;
4773
+ sql.push(`${u.k} (${itemSql})`);
4774
+ }
4775
+ } else {
4776
+ sql.push("SELECT");
4777
+ if (query.distinct) {
4778
+ pushDistinctSql(ctx, table, query.distinct, quotedAs);
4779
+ }
4780
+ pushSelectSql(ctx, table, query, quotedAs);
4781
+ if (table.table || query.from) {
4782
+ pushFromAndAs(ctx, table, query, quotedAs);
4783
+ }
4784
+ if (query.join) {
4785
+ pushJoinSql(
4786
+ ctx,
4787
+ table,
4788
+ query,
4789
+ quotedAs
4790
+ );
4791
+ }
4792
+ if (query.and || query.or) {
4793
+ pushWhereStatementSql(ctx, table, query, quotedAs);
4794
+ }
4795
+ if (query.group) {
4796
+ const group = query.group.map(
4797
+ (item) => isExpression(item) ? item.toSQL(ctx, quotedAs) : columnToSql(ctx, table.q, table.q.shape, item, quotedAs)
4798
+ );
4799
+ sql.push(`GROUP BY ${group.join(", ")}`);
4800
+ }
4801
+ if (query.having)
4802
+ pushHavingSql(ctx, query, quotedAs);
4803
+ if (query.window) {
4804
+ const window = [];
4805
+ query.window.forEach((item) => {
4806
+ for (const key in item) {
4807
+ window.push(
4808
+ `"${key}" AS ${windowToSql(ctx, query, item[key], quotedAs)}`
4809
+ );
4810
+ }
4811
+ });
4812
+ sql.push(`WINDOW ${window.join(", ")}`);
4824
4813
  }
4825
4814
  }
4826
4815
  if (query.order) {
@@ -4904,7 +4893,7 @@ const cloneQuery = (q) => {
4904
4893
  if (q.window)
4905
4894
  q.window = q.window.slice(0);
4906
4895
  if (q.union)
4907
- q.union = q.union.slice(0);
4896
+ q.union = { b: q.union.b, u: q.union.u.slice(0) };
4908
4897
  if (q.order)
4909
4898
  q.order = q.order.slice(0);
4910
4899
  } else if (q.type === "insert") {
@@ -6364,7 +6353,7 @@ class Create {
6364
6353
  *
6365
6354
  * await db.table.create({
6366
6355
  * // raw SQL
6367
- * column1: sql`'John' || ' ' || 'Doe'`,
6356
+ * column1: (q) => q.sql`'John' || ' ' || 'Doe'`,
6368
6357
  *
6369
6358
  * // query that returns a single value
6370
6359
  * // returning multiple values will result in Postgres error
@@ -8302,6 +8291,11 @@ class MergeQueryMethods {
8302
8291
  a[key] = a[key] ? [...a[key], ...value] : value;
8303
8292
  } else if (mergableObjects[key]) {
8304
8293
  a[key] = a[key] ? __spreadValues$5(__spreadValues$5({}, a[key]), value) : value;
8294
+ } else if (key === "union") {
8295
+ a[key] = a[key] ? {
8296
+ b: a[key].b,
8297
+ u: [...a[key].u, ...value.u]
8298
+ } : value;
8305
8299
  } else {
8306
8300
  a[key] = value;
8307
8301
  }
@@ -8315,196 +8309,225 @@ class MergeQueryMethods {
8315
8309
  }
8316
8310
  }
8317
8311
 
8318
- var __defProp$4 = Object.defineProperty;
8319
- var __defProps$1 = Object.defineProperties;
8320
- var __getOwnPropDescs$1 = Object.getOwnPropertyDescriptors;
8321
- var __getOwnPropSymbols$4 = Object.getOwnPropertySymbols;
8322
- var __hasOwnProp$4 = Object.prototype.hasOwnProperty;
8323
- var __propIsEnum$4 = Object.prototype.propertyIsEnumerable;
8324
- var __defNormalProp$4 = (obj, key, value) => key in obj ? __defProp$4(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
8325
- var __spreadValues$4 = (a, b) => {
8326
- for (var prop in b || (b = {}))
8327
- if (__hasOwnProp$4.call(b, prop))
8328
- __defNormalProp$4(a, prop, b[prop]);
8329
- if (__getOwnPropSymbols$4)
8330
- for (var prop of __getOwnPropSymbols$4(b)) {
8331
- if (__propIsEnum$4.call(b, prop))
8332
- __defNormalProp$4(a, prop, b[prop]);
8333
- }
8334
- return a;
8312
+ const _queryUnion = (base, args, k) => {
8313
+ const q = base.baseQuery.clone();
8314
+ const u = args.map(
8315
+ (a) => ({
8316
+ a: typeof a === "function" ? a(q) : a,
8317
+ k
8318
+ })
8319
+ );
8320
+ const union = q.q.union = base.q.union;
8321
+ if (union) {
8322
+ union.u.push(...u);
8323
+ } else {
8324
+ q.q.union = {
8325
+ b: base,
8326
+ u
8327
+ };
8328
+ }
8329
+ return q;
8335
8330
  };
8336
- var __spreadProps$1 = (a, b) => __defProps$1(a, __getOwnPropDescs$1(b));
8337
- class With {
8331
+ class Union {
8338
8332
  /**
8339
- * Add Common Table Expression (CTE) to the query.
8333
+ * Creates a union query, takes one or more queries or SQL expressions.
8340
8334
  *
8341
8335
  * ```ts
8342
- * import { columnTypes } from 'orchid-orm';
8343
- * import { NumberColumn } from './number';
8344
- *
8345
- * // .with optionally accepts such options:
8346
- * type WithOptions = {
8347
- * // list of columns returned by this WITH statement
8348
- * // by default all columns from provided column shape will be included
8349
- * // true is for default behavior
8350
- * columns?: string[] | boolean;
8351
- *
8352
- * // Adds RECURSIVE keyword:
8353
- * recursive?: true;
8354
- *
8355
- * // Adds MATERIALIZED keyword:
8356
- * materialized?: true;
8357
- *
8358
- * // Adds NOT MATERIALIZED keyword:
8359
- * notMaterialized?: true;
8360
- * };
8361
- *
8362
- * // accepts columns shape and a raw expression:
8363
- * db.table.with(
8364
- * 'alias',
8365
- * {
8366
- * id: columnTypes.integer(),
8367
- * name: columnTypes.text(3, 100),
8368
- * },
8369
- * sql`SELECT id, name FROM "someTable"`,
8370
- * );
8371
- *
8372
- * // accepts query:
8373
- * db.table.with('alias', db.table.all());
8374
- *
8375
- * // accepts a callback for a query builder:
8376
- * db.table.with('alias', (qb) =>
8377
- * qb.select({ one: sql`1`.type((t) => t.integer()) }),
8378
- * );
8379
- *
8380
- * // All mentioned forms can accept options as a second argument:
8381
- * db.table.with(
8382
- * 'alias',
8383
- * {
8384
- * recursive: true,
8385
- * materialized: true,
8386
- * },
8387
- * rawOrQueryOrCallback,
8388
- * );
8336
+ * // The first query of the union
8337
+ * db.one
8338
+ * .select('id', 'name')
8339
+ * // add two more queries to the union
8340
+ * .union(
8341
+ * db.two.select('id', 'name'),
8342
+ * (q = q.sql`SELECT id, name FROM "thirdTable"`),
8343
+ * )
8344
+ * // sub-sequent `union` is equivalent to passing multiple queries into a single `union`
8345
+ * .union(db.three.select('id', 'name'));
8389
8346
  * ```
8390
8347
  *
8391
- * Defined `WITH` table can be used in `.from` or `.join` with all the type safeness:
8348
+ * `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.
8392
8349
  *
8393
8350
  * ```ts
8394
- * db.table.with('alias', db.table.all()).from('alias').select('alias.id');
8395
- *
8396
- * db.table
8397
- * .with('alias', db.table.all())
8398
- * .join('alias', 'alias.id', 'user.id')
8399
- * .select('alias.id');
8351
+ * // order, limit, offset are applied ONLY to 'one'
8352
+ * db.one
8353
+ * .order('x')
8354
+ * .limit(1)
8355
+ * .offset(1)
8356
+ * // 'two' also has order, limit, and offset
8357
+ * .unionAll(db.two.order('y').limit(2).offset(2))
8358
+ * // sets order, limit, offset for all records
8359
+ * .order('z')
8360
+ * .limit(3)
8361
+ * .offset(3);
8400
8362
  * ```
8401
8363
  *
8402
- * @param args - first argument is an alias for this CTE, other arguments can be column shape, query object, or raw SQL.
8403
- */
8404
- with(...args) {
8405
- const q = this.clone();
8406
- let options = args.length === 3 && !isExpression(args[2]) || args.length === 4 ? args[1] : void 0;
8407
- const last = args[args.length - 1];
8408
- const query = typeof last === "function" ? last(q.queryBuilder) : last;
8409
- const shape = args.length === 4 ? args[2] : isExpression(query) ? args[1] : query.q.shape;
8410
- if ((options == null ? void 0 : options.columns) === true) {
8411
- options = __spreadProps$1(__spreadValues$4({}, options), {
8412
- columns: Object.keys(shape)
8413
- });
8414
- }
8415
- pushQueryValue(q, "with", [args[0], options || emptyObject, query]);
8416
- return setQueryObjectValue(q, "withShapes", args[0], shape);
8417
- }
8418
- }
8419
-
8420
- class Union {
8421
- /**
8422
- * 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`.
8423
- * If the `wrap` parameter is true, the queries will be individually wrapped in parentheses.
8364
+ * Equivalent SQL:
8424
8365
  *
8425
- * ```ts
8426
- * SomeTable.select('id', 'name').union(
8427
- * [
8428
- * OtherTable.select('id', 'name'),
8429
- * sql`SELECT id, name FROM "thirdTable"`,
8430
- * ],
8431
- * true, // optional wrap parameter
8432
- * );
8366
+ * ```sql
8367
+ * -- both union parts have their own order, limit, offset
8368
+ * ( SELECT * FROM one ORDER x ASC LIMIT 1 OFFSET 1 )
8369
+ * UNION ALL
8370
+ * ( SELECT * FROM two ORDER y ASC LIMIT 2 OFFSET 2 )
8371
+ * -- order, limit, offset of the whole query
8372
+ * ORDER BY z ASC LIMIT 3 OFFSET 3
8433
8373
  * ```
8434
8374
  *
8435
- * @param args - array of queries or raw SQLs
8436
- * @param wrap - provide `true` if you want the queries to be wrapped into parentheses
8375
+ * All the listed methods have the same signature, they are only different by SQL keyword:
8376
+ *
8377
+ * - `union` - union of all queries, performs deduplication
8378
+ * - `unionAll` - `union` that allows duplicated rows
8379
+ * - `intersect` - get only rows that are present in all queries
8380
+ * - `intersectAll` - `intersect` that allows duplicated rows
8381
+ * - `except` - get only rows that are in the first query but not in the second
8382
+ * - `exceptAll` - `except` that allows duplicated rows
8383
+ *
8384
+ * @param args - array of queries or SQL expressions
8437
8385
  */
8438
- union(args, wrap) {
8439
- return pushQueryArray(
8386
+ union(...args) {
8387
+ return _queryUnion(
8440
8388
  this.clone(),
8441
- "union",
8442
- args.map((arg) => ({ arg, kind: "UNION", wrap }))
8389
+ args,
8390
+ "UNION"
8443
8391
  );
8444
8392
  }
8445
8393
  /**
8446
- * Same as `union`, but allows duplicated rows.
8394
+ * Same as {@link union}, but allows duplicated rows.
8447
8395
  *
8448
- * @param args - array of queries or raw SQLs
8449
- * @param wrap - provide `true` if you want the queries to be wrapped into parentheses
8396
+ * @param args - array of queries or SQL expressions
8450
8397
  */
8451
- unionAll(args, wrap) {
8452
- return pushQueryArray(
8398
+ unionAll(...args) {
8399
+ return _queryUnion(
8453
8400
  this.clone(),
8454
- "union",
8455
- args.map((arg) => ({ arg, kind: "UNION ALL", wrap }))
8401
+ args,
8402
+ "UNION ALL"
8456
8403
  );
8457
8404
  }
8458
8405
  /**
8459
- * Same as `union`, but uses a `INTERSECT` SQL keyword instead
8406
+ * Same as {@link union}, but uses a `INTERSECT` SQL keyword instead
8460
8407
  *
8461
- * @param args - array of queries or raw SQLs
8462
- * @param wrap - provide `true` if you want the queries to be wrapped into parentheses
8408
+ * @param args - array of queries or SQL expressions
8463
8409
  */
8464
- intersect(args, wrap) {
8465
- return pushQueryArray(
8410
+ intersect(...args) {
8411
+ return _queryUnion(
8466
8412
  this.clone(),
8467
- "union",
8468
- args.map((arg) => ({ arg, kind: "INTERSECT", wrap }))
8413
+ args,
8414
+ "INTERSECT"
8469
8415
  );
8470
8416
  }
8471
8417
  /**
8472
- * Same as `intersect`, but allows duplicated rows.
8418
+ * Same as {@link intersect}, but allows duplicated rows.
8473
8419
  *
8474
- * @param args - array of queries or raw SQLs
8475
- * @param wrap - provide `true` if you want the queries to be wrapped into parentheses
8420
+ * @param args - array of queries or SQL expressions
8476
8421
  */
8477
- intersectAll(args, wrap) {
8478
- return pushQueryArray(
8422
+ intersectAll(...args) {
8423
+ return _queryUnion(
8479
8424
  this.clone(),
8480
- "union",
8481
- args.map((arg) => ({ arg, kind: "INTERSECT ALL", wrap }))
8425
+ args,
8426
+ "INTERSECT ALL"
8482
8427
  );
8483
8428
  }
8484
8429
  /**
8485
- * Same as `union`, but uses an `EXCEPT` SQL keyword instead
8430
+ * Same as {@link union}, but uses an `EXCEPT` SQL keyword instead
8486
8431
  *
8487
- * @param args - array of queries or raw SQLs
8488
- * @param wrap - provide `true` if you want the queries to be wrapped into parentheses
8432
+ * @param args - array of queries or SQL expressions
8489
8433
  */
8490
- except(args, wrap) {
8491
- return pushQueryArray(
8434
+ except(...args) {
8435
+ return _queryUnion(
8492
8436
  this.clone(),
8493
- "union",
8494
- args.map((arg) => ({ arg, kind: "EXCEPT", wrap }))
8437
+ args,
8438
+ "EXCEPT"
8495
8439
  );
8496
8440
  }
8497
8441
  /**
8498
- * Same as `except`, but allows duplicated rows.
8442
+ * Same as {@link except}, but allows duplicated rows.
8499
8443
  *
8500
- * @param args - array of queries or raw SQLs
8501
- * @param wrap - provide `true` if you want the queries to be wrapped into parentheses
8444
+ * @param args - array of queries or SQL expressions
8502
8445
  */
8503
- exceptAll(args, wrap) {
8504
- return pushQueryArray(
8446
+ exceptAll(...args) {
8447
+ return _queryUnion(
8505
8448
  this.clone(),
8506
- "union",
8507
- args.map((arg) => ({ arg, kind: "EXCEPT ALL", wrap }))
8449
+ args,
8450
+ "EXCEPT ALL"
8451
+ );
8452
+ }
8453
+ }
8454
+
8455
+ var __defProp$4 = Object.defineProperty;
8456
+ var __defProps$1 = Object.defineProperties;
8457
+ var __getOwnPropDescs$1 = Object.getOwnPropertyDescriptors;
8458
+ var __getOwnPropSymbols$4 = Object.getOwnPropertySymbols;
8459
+ var __hasOwnProp$4 = Object.prototype.hasOwnProperty;
8460
+ var __propIsEnum$4 = Object.prototype.propertyIsEnumerable;
8461
+ var __defNormalProp$4 = (obj, key, value) => key in obj ? __defProp$4(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
8462
+ var __spreadValues$4 = (a, b) => {
8463
+ for (var prop in b || (b = {}))
8464
+ if (__hasOwnProp$4.call(b, prop))
8465
+ __defNormalProp$4(a, prop, b[prop]);
8466
+ if (__getOwnPropSymbols$4)
8467
+ for (var prop of __getOwnPropSymbols$4(b)) {
8468
+ if (__propIsEnum$4.call(b, prop))
8469
+ __defNormalProp$4(a, prop, b[prop]);
8470
+ }
8471
+ return a;
8472
+ };
8473
+ var __spreadProps$1 = (a, b) => __defProps$1(a, __getOwnPropDescs$1(b));
8474
+ class WithMethods {
8475
+ with(name, second, third) {
8476
+ const q = this.clone();
8477
+ let [options, queryArg] = third ? [second, third] : [void 0, second];
8478
+ let query;
8479
+ if (typeof queryArg === "function") {
8480
+ const arg = q.queryBuilder.clone();
8481
+ arg.q.withShapes = q.q.withShapes;
8482
+ query = queryArg(arg);
8483
+ } else {
8484
+ query = queryArg;
8485
+ }
8486
+ if ((options == null ? void 0 : options.columns) === true) {
8487
+ options = __spreadProps$1(__spreadValues$4({}, options), {
8488
+ columns: Object.keys(query.shape)
8489
+ });
8490
+ }
8491
+ pushQueryValue(q, "with", { n: name, o: options, q: query });
8492
+ const shape = getShapeFromSelect(query, true);
8493
+ return setQueryObjectValue(q, "withShapes", name, shape);
8494
+ }
8495
+ withRecursive(name, ...args) {
8496
+ var _a, _b, _c;
8497
+ const q = this.clone();
8498
+ let [options, baseFn, recursiveFn] = args.length === 2 ? [{}, args[0], args[1]] : args;
8499
+ const arg = q.queryBuilder.clone();
8500
+ arg.q.withShapes = q.q.withShapes;
8501
+ let query = typeof baseFn === "function" ? baseFn(arg) : baseFn;
8502
+ const shape = ((_b = (_a = arg.q).withShapes) != null ? _b : _a.withShapes = {})[name] = getShapeFromSelect(
8503
+ query,
8504
+ true
8505
+ );
8506
+ const recursive = recursiveFn(arg);
8507
+ query = _queryUnion(query, [recursive], (_c = options.union) != null ? _c : "UNION ALL");
8508
+ options.recursive = true;
8509
+ if (options.columns === true) {
8510
+ options = __spreadProps$1(__spreadValues$4({}, options), {
8511
+ columns: Object.keys(shape)
8512
+ });
8513
+ }
8514
+ pushQueryValue(q, "with", { n: name, o: options, q: query });
8515
+ return setQueryObjectValue(q, "withShapes", name, shape);
8516
+ }
8517
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
8518
+ withSql(name, ...args) {
8519
+ const q = this.clone();
8520
+ const [options, shape, sql] = args.length === 2 ? [void 0, args[0], args[1]] : args;
8521
+ pushQueryValue(q, "with", {
8522
+ n: name,
8523
+ o: options,
8524
+ s: sql(q)
8525
+ });
8526
+ return setQueryObjectValue(
8527
+ q,
8528
+ "withShapes",
8529
+ name,
8530
+ shape(this.columnTypes)
8508
8531
  );
8509
8532
  }
8510
8533
  }
@@ -9338,11 +9361,10 @@ const _queryUpdate = (query, arg) => {
9338
9361
  "q",
9339
9362
  "withShapes"
9340
9363
  );
9341
- pushQueryValue(query, "with", [
9342
- as,
9343
- emptyObject,
9344
- value
9345
- ]);
9364
+ pushQueryValue(query, "with", {
9365
+ n: as,
9366
+ q: value
9367
+ });
9346
9368
  set[key] = new RawSQL(`(SELECT * FROM "${as}")`);
9347
9369
  }
9348
9370
  } else {
@@ -9440,7 +9462,7 @@ class Update {
9440
9462
  * column1: 123,
9441
9463
  *
9442
9464
  * // use raw SQL to update the column
9443
- * column2: sql`2 + 2`,
9465
+ * column2: (q) => q.sql`2 + 2`,
9444
9466
  *
9445
9467
  * // use query that returns a single value
9446
9468
  * // returning multiple values will result in Postgres error
@@ -9554,7 +9576,7 @@ class Update {
9554
9576
  );
9555
9577
  }
9556
9578
  /**
9557
- * `updateRaw` is for updating records with raw expression.
9579
+ * `updateSql` is for updating records with raw expression.
9558
9580
  *
9559
9581
  * The behavior is the same as a regular `update` method has:
9560
9582
  * `find` or `where` must precede calling this method,
@@ -9565,14 +9587,14 @@ class Update {
9565
9587
  * const value = 'new name';
9566
9588
  *
9567
9589
  * // update with SQL template string
9568
- * const updatedCount = await db.table.find(1).updateRaw`name = ${value}`;
9590
+ * const updatedCount = await db.table.find(1).updateSql`name = ${value}`;
9569
9591
  *
9570
9592
  * // or update with `sql` function:
9571
- * await db.table.find(1).updateRaw(sql`name = ${value}`);
9593
+ * await db.table.find(1).updateSql(sql`name = ${value}`);
9572
9594
  * ```
9573
9595
  * @param args - raw SQL via a template string or by using a `sql` method
9574
9596
  */
9575
- updateRaw(...args) {
9597
+ updateSql(...args) {
9576
9598
  return _queryUpdateRaw(
9577
9599
  this.clone(),
9578
9600
  sqlQueryArgsToExpression(args)
@@ -11147,10 +11169,7 @@ class QueryMethods {
11147
11169
  * pets: (q) => q.pets.join().none(),
11148
11170
  * });
11149
11171
  *
11150
- * await db.user.join(
11151
- * (q) => q.pets.none(),
11152
- * (q) => q,
11153
- * );
11172
+ * await db.user.join((q) => q.pets.none());
11154
11173
  *
11155
11174
  * await db.user.join('pets', (q) => q.none());
11156
11175
  * ```
@@ -11306,10 +11325,10 @@ applyMixins(QueryMethods, [
11306
11325
  AsMethods,
11307
11326
  AggregateMethods,
11308
11327
  Select,
11309
- From,
11328
+ FromMethods,
11310
11329
  Join,
11311
11330
  OnMethods,
11312
- With,
11331
+ WithMethods,
11313
11332
  Union,
11314
11333
  JsonModifiers,
11315
11334
  JsonMethods,
@@ -11909,5 +11928,5 @@ function copyTableData(query, arg) {
11909
11928
  return q;
11910
11929
  }
11911
11930
 
11912
- 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 };
11931
+ 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 };
11913
11932
  //# sourceMappingURL=index.mjs.map