pqb 0.56.9 → 0.56.11

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, templateLiteralSQLToCode, quoteObjectKey, toArray, emptyArray, singleQuote, addCode, singleQuoteArray, objectHasValues, toSnakeCase, columnDefaultArgumentToCode, columnErrorMessagesToCode, setObjectValueImmutable, getValueKey, addValue, isIterable, isExpression, dateDataToCode, joinTruthy, arrayDataToCode, numberDataToCode, noop, stringDataToCode, getDefaultLanguage, setDefaultNowFn, setDefaultLanguage, setCurrentColumnName, timestampHelpers, _getQueryAliasOrName, _getQueryOuterAliases, returnArg, pushQueryValueImmutable, NotFoundError, OrchidOrmInternalError, _setSubQueryAliases, _applyRelationAliases, isRelationQuery, getFreeAlias, _checkIfAliased, logColors, OrchidOrmError, applyTransforms, callWithThis, requirePrimaryKeys, pick, _setQueryAs, _copyQueryAliasToQuery, setParserToQuery, newDelayedRelationSelect, pushOrNewArray, getPrimaryKeys, setDelayedRelation, UnhandledTypeError, isRawSQL, pushOrNewArrayToObjectImmutable, _getQueryFreeAlias, _setQueryAlias, QueryHookUtils, MoreThanOneRowError, isObjectEmpty, ValExpression, applyMixins, _getQueryAs, QueryError, snakeCaseKey } from 'orchid-core';
1
+ import { ExpressionTypeMethod, Expression, RawSQLBase, emptyObject, isTemplateLiteralArgs, ColumnTypeBase, setColumnData, pushColumnData, templateLiteralSQLToCode, quoteObjectKey, toArray, emptyArray, singleQuote, addCode, singleQuoteArray, objectHasValues, toSnakeCase, columnDefaultArgumentToCode, columnErrorMessagesToCode, setObjectValueImmutable, getValueKey, addValue, isIterable, isExpression, dateDataToCode, joinTruthy, arrayDataToCode, numberDataToCode, noop, stringDataToCode, getDefaultLanguage, setDefaultNowFn, setDefaultLanguage, setCurrentColumnName, timestampHelpers, _getQueryAliasOrName, _getQueryOuterAliases, returnArg, pushQueryValueImmutable, NotFoundError, applyTransforms, OrchidOrmInternalError, _setSubQueryAliases, _applyRelationAliases, isRelationQuery, getFreeAlias, _checkIfAliased, getQueryParsers, logColors, OrchidOrmError, callWithThis, requirePrimaryKeys, _setQueryAs, _copyQueryAliasToQuery, setParserToQuery, _addToHookSelectWithTable, spreadObjectValues, _addToHookSelect, newDelayedRelationSelect, pushOrNewArray, getPrimaryKeys, setDelayedRelation, UnhandledTypeError, isRawSQL, pushOrNewArrayToObjectImmutable, _getQueryFreeAlias, _setQueryAlias, QueryHookUtils, MoreThanOneRowError, isObjectEmpty, ValExpression, applyMixins, _getQueryAs, QueryError, snakeCaseKey } from 'orchid-core';
2
2
  import { inspect } from 'node:util';
3
3
  import { AsyncLocalStorage } from 'node:async_hooks';
4
4
  import { templateLiteralToSQL as templateLiteralToSQL$1 } from 'pqb';
@@ -1764,6 +1764,9 @@ const defaultSchemaConfig = {
1764
1764
  narrowType() {
1765
1765
  return this;
1766
1766
  },
1767
+ narrowAllTypes() {
1768
+ return this;
1769
+ },
1767
1770
  dateAsNumber() {
1768
1771
  return this.parse(Date.parse);
1769
1772
  },
@@ -2969,6 +2972,7 @@ const pushIn = (ctx, query, ands, quotedAs, arg) => {
2969
2972
  const processJoinItem = (ctx, table, query, args, quotedAs) => {
2970
2973
  let target;
2971
2974
  let on;
2975
+ const forbidLateral = "u" in args;
2972
2976
  if ("l" in args) {
2973
2977
  const { aliasValue } = ctx;
2974
2978
  ctx.aliasValue = true;
@@ -2989,7 +2993,7 @@ const processJoinItem = (ctx, table, query, args, quotedAs) => {
2989
2993
  target += ` ${joinAs}`;
2990
2994
  }
2991
2995
  if (r && s) {
2992
- target = `LATERAL ${subJoinToSql(ctx, j, quotedTable, joinAs, true)}`;
2996
+ target = subJoinToSql(ctx, j, quotedTable, !forbidLateral, joinAs, true);
2993
2997
  } else {
2994
2998
  on = whereToSql(ctx, j, j.q, joinAs);
2995
2999
  }
@@ -2999,7 +3003,7 @@ const processJoinItem = (ctx, table, query, args, quotedAs) => {
2999
3003
  if ("r" in args) {
3000
3004
  const { s, r } = args;
3001
3005
  if (s) {
3002
- target = `LATERAL ${subJoinToSql(ctx, r, target, target)}`;
3006
+ target = subJoinToSql(ctx, r, target, !forbidLateral, target);
3003
3007
  } else {
3004
3008
  on = whereToSql(ctx, r, r.q, target);
3005
3009
  }
@@ -3030,14 +3034,14 @@ const processJoinItem = (ctx, table, query, args, quotedAs) => {
3030
3034
  let joinAs;
3031
3035
  if ("r" in args) {
3032
3036
  const { r } = args;
3033
- const res = getArgQueryTarget(ctx, q, s, s);
3034
- target = s ? `LATERAL ${res.target}` : res.target;
3037
+ const res = getArgQueryTarget(ctx, q, s && !forbidLateral, s, s);
3038
+ target = res.target;
3035
3039
  joinAs = res.joinAs;
3036
- if (!s) {
3040
+ if (!s || forbidLateral) {
3037
3041
  on = whereToSql(ctx, r, r.q, `"${getQueryAs(r)}"`);
3038
3042
  }
3039
3043
  } else {
3040
- const res = getArgQueryTarget(ctx, q, s);
3044
+ const res = getArgQueryTarget(ctx, q, false, s);
3041
3045
  target = res.target;
3042
3046
  joinAs = res.joinAs;
3043
3047
  if ("a" in args) {
@@ -3066,7 +3070,7 @@ const processJoinItem = (ctx, table, query, args, quotedAs) => {
3066
3070
  }
3067
3071
  return { target, on };
3068
3072
  };
3069
- const getArgQueryTarget = (ctx, first, joinSubQuery, cloned) => {
3073
+ const getArgQueryTarget = (ctx, first, lateral, joinSubQuery, cloned) => {
3070
3074
  const joinQuery = first.q;
3071
3075
  const quotedFrom = typeof joinQuery.from === "string" ? `"${joinQuery.from}"` : void 0;
3072
3076
  let joinAs = quotedFrom || `"${first.table}"`;
@@ -3074,7 +3078,7 @@ const getArgQueryTarget = (ctx, first, joinSubQuery, cloned) => {
3074
3078
  const addAs = qAs && qAs !== joinAs;
3075
3079
  if (joinSubQuery) {
3076
3080
  return {
3077
- target: subJoinToSql(ctx, first, joinAs, qAs, cloned),
3081
+ target: subJoinToSql(ctx, first, joinAs, lateral, qAs, cloned),
3078
3082
  joinAs: addAs ? qAs : joinAs
3079
3083
  };
3080
3084
  } else {
@@ -3086,12 +3090,13 @@ const getArgQueryTarget = (ctx, first, joinSubQuery, cloned) => {
3086
3090
  return { target, joinAs };
3087
3091
  }
3088
3092
  };
3089
- const subJoinToSql = (ctx, jq, innerAs, outerAs, cloned) => {
3093
+ const subJoinToSql = (ctx, jq, innerAs, lateral, outerAs, cloned) => {
3090
3094
  if (!jq.q.select && jq.q.selectAllColumns) {
3091
3095
  if (!cloned) jq = jq.clone();
3092
3096
  jq.q.select = [new RawSQL(`${innerAs}.*`)];
3093
3097
  }
3094
- return `(${getSqlText(jq.toSQL(ctx))}) ${outerAs || innerAs}`;
3098
+ const sql = `(${getSqlText(jq.toSQL(ctx))}) ${outerAs || innerAs}`;
3099
+ return lateral ? `LATERAL ${sql}` : sql;
3095
3100
  };
3096
3101
  const processArgs = (args, ctx, query, joinAs, joinShape, quotedAs) => {
3097
3102
  return args.length ? args.length === 1 ? getObjectOrRawConditions(
@@ -3175,7 +3180,26 @@ const skipQueryKeysForSubQuery = {
3175
3180
  returnsOne: true,
3176
3181
  aliases: true,
3177
3182
  defaults: true,
3178
- transform: true
3183
+ transform: true,
3184
+ throwOnNotFound: true,
3185
+ before: true,
3186
+ after: true,
3187
+ beforeCreate: true,
3188
+ afterCreate: true,
3189
+ afterCreateCommit: true,
3190
+ afterCreateSelect: true,
3191
+ beforeUpdate: true,
3192
+ afterUpdate: true,
3193
+ afterUpdateCommit: true,
3194
+ afterUpdateSelect: true,
3195
+ beforeDelete: true,
3196
+ afterDelete: true,
3197
+ afterDeleteCommit: true,
3198
+ afterDeleteSelect: true,
3199
+ catchAfterCommitErrors: true,
3200
+ log: true,
3201
+ logger: true,
3202
+ autoPreparedStatements: true
3179
3203
  };
3180
3204
  const getIsJoinSubQuery = (query) => {
3181
3205
  const {
@@ -3190,14 +3214,14 @@ const getIsJoinSubQuery = (query) => {
3190
3214
  return false;
3191
3215
  };
3192
3216
 
3193
- const processJoinArgs = (joinTo, first, args, joinSubQuery, whereExists) => {
3217
+ const processJoinArgs = (joinTo, first, args, joinSubQuery, shape, whereExists, forbidLateral) => {
3194
3218
  if (typeof first === "string") {
3195
3219
  if (first in joinTo.relations) {
3196
3220
  const { query: toQuery, joinQuery } = joinTo.relations[first];
3197
3221
  const j = joinQuery(toQuery, joinTo);
3198
3222
  if (typeof args[0] === "function") {
3199
3223
  const r = args[0](
3200
- makeJoinQueryBuilder(j, j.q.joinedShapes, joinTo)
3224
+ makeJoinQueryBuilder(j, j.q.joinedShapes, joinTo, shape)
3201
3225
  );
3202
3226
  return {
3203
3227
  j: j.merge(r),
@@ -3218,7 +3242,7 @@ const processJoinArgs = (joinTo, first, args, joinSubQuery, whereExists) => {
3218
3242
  j.table = first;
3219
3243
  j.q = {
3220
3244
  shape: w.shape,
3221
- computeds: w.computeds,
3245
+ runtimeComputeds: w.computeds,
3222
3246
  adapter: joinToQ.adapter,
3223
3247
  handleResult: joinToQ.handleResult,
3224
3248
  returnType: "all",
@@ -3236,7 +3260,8 @@ const processJoinArgs = (joinTo, first, args, joinSubQuery, whereExists) => {
3236
3260
  ...j.q.joinedShapes,
3237
3261
  ...joinedShapes
3238
3262
  } : joinedShapes,
3239
- joinTo
3263
+ joinTo,
3264
+ shape
3240
3265
  )
3241
3266
  );
3242
3267
  return {
@@ -3248,7 +3273,7 @@ const processJoinArgs = (joinTo, first, args, joinSubQuery, whereExists) => {
3248
3273
  }
3249
3274
  const args0 = args.length ? args[0] : returnArg;
3250
3275
  if (typeof args0 === "function") {
3251
- const q = first;
3276
+ let q = first;
3252
3277
  if (q.joinQueryAfterCallback) {
3253
3278
  let base = q.baseQuery;
3254
3279
  if (q.q.as) {
@@ -3258,14 +3283,17 @@ const processJoinArgs = (joinTo, first, args, joinSubQuery, whereExists) => {
3258
3283
  base,
3259
3284
  joinTo
3260
3285
  );
3261
- if (query.and) {
3262
- pushQueryArrayImmutable(q, "and", query.and);
3263
- }
3264
- if (query.or) {
3265
- pushQueryArrayImmutable(q, "or", query.or);
3266
- }
3267
- if (query.scopes) {
3268
- q.q.scopes = { ...q.q.scopes, ...query.scopes };
3286
+ if (query.and || query.or || query.scopes) {
3287
+ q = _clone(q);
3288
+ if (query.and) {
3289
+ pushQueryArrayImmutable(q, "and", query.and);
3290
+ }
3291
+ if (query.or) {
3292
+ pushQueryArrayImmutable(q, "or", query.or);
3293
+ }
3294
+ if (query.scopes) {
3295
+ q.q.scopes = { ...q.q.scopes, ...query.scopes };
3296
+ }
3269
3297
  }
3270
3298
  }
3271
3299
  const joinedShapes = {
@@ -3279,11 +3307,16 @@ const processJoinArgs = (joinTo, first, args, joinSubQuery, whereExists) => {
3279
3307
  ...q.q.joinedShapes,
3280
3308
  ...joinedShapes
3281
3309
  } : joinedShapes,
3282
- joinTo
3310
+ joinTo,
3311
+ shape
3283
3312
  )
3284
3313
  );
3285
3314
  joinSubQuery || (joinSubQuery = getIsJoinSubQuery(r));
3286
- return { q: joinSubQuery ? q.merge(r) : q, r, s: joinSubQuery };
3315
+ return {
3316
+ q: joinSubQuery && !forbidLateral ? q.merge(r) : q,
3317
+ r,
3318
+ s: joinSubQuery
3319
+ };
3287
3320
  }
3288
3321
  return {
3289
3322
  q: first,
@@ -3299,12 +3332,15 @@ const preprocessJoinArg = (q, arg) => {
3299
3332
  arg.joinQueryAfterCallback = arg.joinQuery;
3300
3333
  return arg;
3301
3334
  };
3302
- const makeJoinQueryBuilder = (joinedQuery, joinedShapes, joinTo) => {
3335
+ const makeJoinQueryBuilder = (joinedQuery, joinedShapes, joinTo, shape) => {
3303
3336
  const q = joinedQuery.baseQuery.clone();
3304
3337
  q.baseQuery = q;
3305
3338
  q.q.as = joinedQuery.q.as;
3306
3339
  q.q.joinedShapes = joinedShapes;
3307
3340
  q.q.joinTo = joinTo;
3341
+ if (shape) {
3342
+ q.q.shape = shape;
3343
+ }
3308
3344
  return q;
3309
3345
  };
3310
3346
 
@@ -3324,14 +3360,23 @@ const noneMethods = {
3324
3360
  // It is `async` so it returns a chainable Promise.
3325
3361
  async then(resolve, reject) {
3326
3362
  try {
3327
- const result = noneResult(this, this.q, this.q.returnType);
3328
- resolve?.(result);
3363
+ let result = noneResult(this, this.q, this.q.returnType);
3364
+ if (this.q.transform) {
3365
+ result = applyTransforms(
3366
+ this.q,
3367
+ this.q.returnType,
3368
+ this.q.transform,
3369
+ result
3370
+ );
3371
+ }
3372
+ return resolve?.(result);
3329
3373
  } catch (err) {
3330
- reject?.(err);
3374
+ return reject?.(err);
3331
3375
  }
3332
3376
  },
3333
- // `catch` returns a Promise, so it is chainable with then/catch.
3334
- catch: () => new Promise(noop)
3377
+ catch(reject) {
3378
+ return this.then(void 0, reject);
3379
+ }
3335
3380
  };
3336
3381
  const _queryNone = (q) => {
3337
3382
  if (isQueryNone(q)) return q;
@@ -3478,6 +3523,7 @@ const existsArgs = (self, q, args) => {
3478
3523
  preprocessJoinArg(self, q),
3479
3524
  args,
3480
3525
  false,
3526
+ void 0,
3481
3527
  true
3482
3528
  );
3483
3529
  return [
@@ -4318,7 +4364,7 @@ const getFullColumnTable = (q, column, index, as) => {
4318
4364
  return as && table !== as && _checkIfAliased(q, table, as) ? as : table;
4319
4365
  };
4320
4366
 
4321
- const _join = (query, require, type, first, args) => {
4367
+ const _joinReturningArgs = (query, require, first, args, forbidLateral) => {
4322
4368
  let joinKey;
4323
4369
  let shape;
4324
4370
  let parsers;
@@ -4333,7 +4379,7 @@ const _join = (query, require, type, first, args) => {
4333
4379
  first = first._internalJoin;
4334
4380
  }
4335
4381
  if (require && isQueryNone(first)) {
4336
- return _queryNone(query);
4382
+ return;
4337
4383
  }
4338
4384
  const q = first;
4339
4385
  if (!isInternalJoin) {
@@ -4342,9 +4388,9 @@ const _join = (query, require, type, first, args) => {
4342
4388
  joinKey = q.q.as || q.table;
4343
4389
  if (joinKey) {
4344
4390
  shape = getShapeFromSelect(q, joinSubQuery && !!q.q.select);
4345
- parsers = q.q.parsers;
4391
+ parsers = getQueryParsers(q);
4346
4392
  batchParsers = q.q.batchParsers;
4347
- computeds = q.q.computeds;
4393
+ computeds = q.q.runtimeComputeds;
4348
4394
  if (joinSubQuery) {
4349
4395
  first = q.clone();
4350
4396
  first.shape = shape;
@@ -4356,9 +4402,9 @@ const _join = (query, require, type, first, args) => {
4356
4402
  if (relation) {
4357
4403
  shape = getShapeFromSelect(relation.query);
4358
4404
  const r = relation.query;
4359
- parsers = r.q.parsers;
4405
+ parsers = getQueryParsers(r);
4360
4406
  batchParsers = r.q.batchParsers;
4361
- computeds = r.q.computeds;
4407
+ computeds = r.q.runtimeComputeds;
4362
4408
  } else {
4363
4409
  const w = query.q.withShapes?.[joinKey];
4364
4410
  shape = w?.shape;
@@ -4376,18 +4422,23 @@ const _join = (query, require, type, first, args) => {
4376
4422
  query,
4377
4423
  first,
4378
4424
  args,
4379
- joinSubQuery
4425
+ joinSubQuery,
4426
+ shape,
4427
+ false,
4428
+ forbidLateral
4380
4429
  );
4381
4430
  if (require && "r" in joinArgs && isQueryNone(joinArgs.r)) {
4382
- return _queryNone(query);
4431
+ return;
4383
4432
  } else if (joinKey && "s" in joinArgs && joinArgs.s) {
4384
4433
  const j = "j" in joinArgs ? joinArgs.r ?? joinArgs.j : "r" in joinArgs ? joinArgs.r : joinArgs.q;
4385
4434
  const jq = j.q;
4386
4435
  if (jq.select || !jq.selectAllColumns) {
4387
4436
  const { q } = query;
4388
- const shape2 = getShapeFromSelect(j, true);
4389
- setObjectValueImmutable(q, "joinedShapes", joinKey, shape2);
4390
- setObjectValueImmutable(q, "joinedParsers", joinKey, jq.parsers);
4437
+ if ("r" in joinArgs && joinArgs.r) {
4438
+ joinArgs.c = shape = getShapeFromSelect(j, true);
4439
+ }
4440
+ setObjectValueImmutable(q, "joinedShapes", joinKey, shape);
4441
+ setObjectValueImmutable(q, "joinedParsers", joinKey, getQueryParsers(j));
4391
4442
  if (jq.batchParsers) {
4392
4443
  setObjectValueImmutable(
4393
4444
  jq,
@@ -4396,7 +4447,12 @@ const _join = (query, require, type, first, args) => {
4396
4447
  jq.batchParsers
4397
4448
  );
4398
4449
  }
4399
- setObjectValueImmutable(q, "joinedComputeds", joinKey, jq.computeds);
4450
+ setObjectValueImmutable(
4451
+ q,
4452
+ "joinedComputeds",
4453
+ joinKey,
4454
+ jq.runtimeComputeds
4455
+ );
4400
4456
  } else {
4401
4457
  addAllShapesAndParsers(
4402
4458
  query,
@@ -4417,6 +4473,13 @@ const _join = (query, require, type, first, args) => {
4417
4473
  computeds
4418
4474
  );
4419
4475
  }
4476
+ return joinArgs;
4477
+ };
4478
+ const _join = (query, require, type, first, args) => {
4479
+ const joinArgs = _joinReturningArgs(query, require, first, args);
4480
+ if (!joinArgs) {
4481
+ return _queryNone(query);
4482
+ }
4420
4483
  pushQueryValueImmutable(query, "join", {
4421
4484
  type,
4422
4485
  args: joinArgs
@@ -4482,7 +4545,12 @@ const _joinLateral = (self, type, arg, as, innerJoinLateral) => {
4482
4545
  if (joinKey) {
4483
4546
  const shape = getShapeFromSelect(arg, true);
4484
4547
  setObjectValueImmutable(q.q, "joinedShapes", joinKey, shape);
4485
- setObjectValueImmutable(q.q, "joinedParsers", joinKey, arg.q.parsers);
4548
+ setObjectValueImmutable(
4549
+ q.q,
4550
+ "joinedParsers",
4551
+ joinKey,
4552
+ getQueryParsers(arg)
4553
+ );
4486
4554
  if (arg.q.batchParsers) {
4487
4555
  setObjectValueImmutable(
4488
4556
  q.q,
@@ -4493,7 +4561,7 @@ const _joinLateral = (self, type, arg, as, innerJoinLateral) => {
4493
4561
  }
4494
4562
  }
4495
4563
  as || (as = getQueryAs(arg));
4496
- setObjectValueImmutable(q.q, "joinedComputeds", as, arg.q.computeds);
4564
+ setObjectValueImmutable(q.q, "joinedComputeds", as, arg.q.runtimeComputeds);
4497
4565
  pushQueryValueImmutable(q, "join", {
4498
4566
  type: `${type} LATERAL`,
4499
4567
  args: { l: arg, a: as, i: innerJoinLateral }
@@ -4878,6 +4946,7 @@ class ComputedColumn {
4878
4946
  const computeAtRuntime = (deps, fn) => new ComputedColumn("one", deps, fn);
4879
4947
  const computeBatchAtRuntime = (deps, fn) => new ComputedColumn("many", deps, fn);
4880
4948
  const applyComputedColumns = (q, fn) => {
4949
+ var _a;
4881
4950
  q.computeAtRuntime = computeAtRuntime;
4882
4951
  q.computeBatchAtRuntime = computeBatchAtRuntime;
4883
4952
  const computed = fn(q);
@@ -4885,8 +4954,8 @@ const applyComputedColumns = (q, fn) => {
4885
4954
  let item = computed[key];
4886
4955
  if (typeof item === "function") item = item.call(computed);
4887
4956
  if (item instanceof ComputedColumn) {
4888
- q.q.computeds = {
4889
- ...q.q.computeds,
4957
+ q.q.runtimeComputeds = {
4958
+ ...q.q.runtimeComputeds,
4890
4959
  [key]: item
4891
4960
  };
4892
4961
  } else {
@@ -4902,11 +4971,10 @@ const applyComputedColumns = (q, fn) => {
4902
4971
  data.computed = item;
4903
4972
  data.explicitSelect = true;
4904
4973
  data.readOnly = true;
4905
- addColumnParserToQuery(
4906
- q.q,
4907
- key,
4908
- item.result.value
4909
- );
4974
+ const parse = item.result.value._parse;
4975
+ if (parse) {
4976
+ ((_a = q.q).defaultParsers ?? (_a.defaultParsers = {}))[key] = parse;
4977
+ }
4910
4978
  }
4911
4979
  }
4912
4980
  q.computeAtRuntime = q.computeBatchAtRuntime = void 0;
@@ -5115,7 +5183,7 @@ const then = async (q, adapter, trx, beforeHooks, afterHooks, afterCommitHooks,
5115
5183
  )
5116
5184
  );
5117
5185
  }
5118
- sql = q.toSQL();
5186
+ const localSql = sql = q.toSQL();
5119
5187
  const { hookSelect, delayedRelationSelect } = sql;
5120
5188
  const { returnType = "all" } = query;
5121
5189
  const tempReturnType = hookSelect || returnType === "rows" && q.q.batchParsers || delayedRelationSelect?.value ? "all" : returnType;
@@ -5140,7 +5208,7 @@ const then = async (q, adapter, trx, beforeHooks, afterHooks, afterCommitHooks,
5140
5208
  if (query.patchResult) {
5141
5209
  await query.patchResult(q, hookSelect, queryResult);
5142
5210
  }
5143
- result = query.handleResult(q, tempReturnType, queryResult);
5211
+ result = query.handleResult(q, tempReturnType, queryResult, localSql);
5144
5212
  } else {
5145
5213
  const queryMethod = queryMethodByReturnType[tempReturnType];
5146
5214
  const queryBatch = async (batch) => {
@@ -5178,10 +5246,7 @@ const then = async (q, adapter, trx, beforeHooks, afterHooks, afterCommitHooks,
5178
5246
  if (query.patchResult) {
5179
5247
  await query.patchResult(q, hookSelect, queryResult);
5180
5248
  }
5181
- result = query.handleResult(q, tempReturnType, queryResult);
5182
- }
5183
- if (result && typeof result === "object" && typeof result.then === "function") {
5184
- result = await result;
5249
+ result = query.handleResult(q, tempReturnType, queryResult, localSql);
5185
5250
  }
5186
5251
  let tempColumns;
5187
5252
  let renames;
@@ -5205,8 +5270,8 @@ const then = async (q, adapter, trx, beforeHooks, afterHooks, afterCommitHooks,
5205
5270
  }
5206
5271
  }
5207
5272
  if (query.selectedComputeds) {
5208
- const promise = processComputedResult(query, result);
5209
- if (promise) await promise;
5273
+ const promise2 = processComputedResult(query, result);
5274
+ if (promise2) await promise2;
5210
5275
  }
5211
5276
  }
5212
5277
  const hasAfterHook = afterHooks || afterCommitHooks || query.after;
@@ -5263,19 +5328,15 @@ const then = async (q, adapter, trx, beforeHooks, afterHooks, afterCommitHooks,
5263
5328
  );
5264
5329
  const selectQuery = q2.clone();
5265
5330
  selectQuery.q.type = selectQuery.q.returnType = void 0;
5266
- ((_a = selectQuery.q).and ?? (_a.and = [])).push(pick(result, primaryKeys));
5267
- const relationsSelect = delayedRelationSelect.value;
5268
- let selectAs;
5269
- if (renames) {
5270
- selectAs = {};
5271
- for (const key in renames) {
5272
- if (key in relationsSelect) {
5273
- selectAs[renames[key]] = relationsSelect[key];
5274
- }
5275
- }
5276
- } else {
5277
- selectAs = { ...relationsSelect };
5331
+ const matchSourceTableIds = {};
5332
+ for (const pkey of primaryKeys) {
5333
+ matchSourceTableIds[pkey] = {
5334
+ in: result.map((row) => row[pkey])
5335
+ };
5278
5336
  }
5337
+ ((_a = selectQuery.q).and ?? (_a.and = [])).push(matchSourceTableIds);
5338
+ const relationsSelect = delayedRelationSelect.value;
5339
+ const selectAs = { ...relationsSelect };
5279
5340
  const select = [{ selectAs }];
5280
5341
  const relationKeyAliases = primaryKeys.map((key) => {
5281
5342
  if (key in selectAs) {
@@ -5299,16 +5360,30 @@ const then = async (q, adapter, trx, beforeHooks, afterHooks, afterCommitHooks,
5299
5360
  Object.assign(row, relationRow);
5300
5361
  }
5301
5362
  }
5363
+ if (renames) {
5364
+ for (const key in relationsSelect) {
5365
+ if (key in renames) {
5366
+ delete renames[key];
5367
+ }
5368
+ }
5369
+ }
5302
5370
  }
5371
+ const promise = parseBatch(q, queryResult, delayedRelationSelect);
5372
+ if (promise) await promise;
5303
5373
  if (hookSelect || tempReturnType !== returnType) {
5304
5374
  if (renames) {
5305
- for (const a in renames) {
5306
- for (const record of result) {
5307
- const value = record[a];
5308
- record[a] = record[renames[a]];
5309
- record[renames[a]] = value;
5375
+ const renamedResult = Array.from({
5376
+ length: result.length
5377
+ });
5378
+ for (let i = 0, len = result.length; i < len; ++i) {
5379
+ const record = result[i];
5380
+ const renamedRecord = renamedResult[i] = { ...record };
5381
+ for (const a in renames) {
5382
+ renamedRecord[a] = record[renames[a]];
5383
+ renamedRecord[renames[a]] = record[a];
5310
5384
  }
5311
5385
  }
5386
+ result = renamedResult;
5312
5387
  }
5313
5388
  result = filterResult(
5314
5389
  q,
@@ -5362,68 +5437,46 @@ const execQuery = (adapter, method, sql) => {
5362
5437
  return result;
5363
5438
  });
5364
5439
  };
5365
- const handleResult = (q, returnType, result, isSubQuery) => {
5366
- const { parsers } = q.q;
5440
+ const handleResult = (q, returnType, result, sql, isSubQuery) => {
5441
+ const parsers = getQueryParsers(q, sql.hookSelect);
5367
5442
  switch (returnType) {
5368
5443
  case "all": {
5369
5444
  if (q.q.throwOnNotFound && result.rows.length === 0)
5370
5445
  throw new NotFoundError(q);
5371
- const promise = parseBatch(q, result);
5372
5446
  const { rows } = result;
5373
5447
  if (parsers) {
5374
5448
  for (const row of rows) {
5375
5449
  parseRecord(parsers, row);
5376
5450
  }
5377
5451
  }
5378
- return promise ? promise.then(() => rows) : rows;
5452
+ return rows;
5379
5453
  }
5380
5454
  case "one": {
5381
5455
  const { rows } = result;
5382
5456
  if (!rows.length) return;
5383
- const promise = parseBatch(q, result);
5384
5457
  if (parsers) parseRecord(parsers, rows[0]);
5385
- return promise ? promise.then(() => rows[0]) : rows[0];
5458
+ return rows[0];
5386
5459
  }
5387
5460
  case "oneOrThrow": {
5388
5461
  const { rows } = result;
5389
5462
  if (!rows.length) throw new NotFoundError(q);
5390
- const promise = parseBatch(q, result);
5391
5463
  if (parsers) parseRecord(parsers, rows[0]);
5392
- return promise ? promise.then(() => rows[0]) : rows[0];
5464
+ return rows[0];
5393
5465
  }
5394
5466
  case "rows": {
5395
5467
  const { rows } = result;
5396
- const promise = parseBatch(q, result);
5397
- if (promise) {
5398
- return promise.then(() => {
5399
- if (parsers) parseRows(parsers, result.fields, rows);
5400
- return rows;
5401
- });
5402
- } else if (parsers) {
5468
+ if (parsers) {
5403
5469
  parseRows(parsers, result.fields, rows);
5404
5470
  }
5405
5471
  return rows;
5406
5472
  }
5407
5473
  case "pluck": {
5408
5474
  const { rows } = result;
5409
- const promise = parseBatch(q, result);
5410
- if (promise) {
5411
- return promise.then(() => {
5412
- parsePluck(parsers, isSubQuery, rows);
5413
- return rows;
5414
- });
5415
- }
5416
5475
  parsePluck(parsers, isSubQuery, rows);
5417
5476
  return rows;
5418
5477
  }
5419
5478
  case "value": {
5420
5479
  const { rows } = result;
5421
- const promise = parseBatch(q, result);
5422
- if (promise) {
5423
- return promise.then(() => {
5424
- return rows[0]?.[0] !== void 0 ? parseValue(rows[0][0], parsers) : q.q.notFoundDefault;
5425
- });
5426
- }
5427
5480
  return rows[0]?.[0] !== void 0 ? parseValue(rows[0][0], parsers) : q.q.notFoundDefault;
5428
5481
  }
5429
5482
  case "valueOrThrow": {
@@ -5434,13 +5487,6 @@ const handleResult = (q, returnType, result, isSubQuery) => {
5434
5487
  return result.rowCount;
5435
5488
  }
5436
5489
  const { rows } = result;
5437
- const promise = parseBatch(q, result);
5438
- if (promise) {
5439
- return promise.then(() => {
5440
- if (rows[0]?.[0] === void 0) throw new NotFoundError(q);
5441
- return parseValue(rows[0][0], parsers);
5442
- });
5443
- }
5444
5490
  if (rows[0]?.[0] === void 0) throw new NotFoundError(q);
5445
5491
  return parseValue(rows[0][0], parsers);
5446
5492
  }
@@ -5449,9 +5495,9 @@ const handleResult = (q, returnType, result, isSubQuery) => {
5449
5495
  }
5450
5496
  }
5451
5497
  };
5452
- const parseBatch = (q, queryResult) => {
5498
+ const parseBatch = (q, queryResult, delayedRelationSelect) => {
5453
5499
  let promises;
5454
- if (q.q.batchParsers) {
5500
+ if (q.q.batchParsers && !delayedRelationSelect?.value) {
5455
5501
  for (const parser of q.q.batchParsers) {
5456
5502
  const res = parser.fn(parser.path, queryResult);
5457
5503
  if (res) (promises ?? (promises = [])).push(res);
@@ -5564,44 +5610,46 @@ const filterAllResult = (result, tempColumns, hasAfterHook) => {
5564
5610
  return result;
5565
5611
  };
5566
5612
 
5613
+ const addWithParsers = (w, parsers) => {
5614
+ for (const key in w.shape) {
5615
+ const { _parse } = w.shape[key];
5616
+ if (_parse) parsers[key] = _parse;
5617
+ }
5618
+ };
5567
5619
  function queryFrom(self, arg) {
5568
5620
  const data = self.q;
5569
5621
  if (typeof arg === "string") {
5570
5622
  data.as || (data.as = arg);
5571
5623
  const w = data.withShapes?.[arg];
5572
5624
  data.shape = w?.shape ?? anyShape;
5573
- data.computeds = w?.computeds;
5574
- } else if (isExpression(arg)) {
5575
- data.as || (data.as = "t");
5625
+ data.runtimeComputeds = w?.computeds;
5626
+ const parsers = {};
5627
+ data.defaultParsers = parsers;
5628
+ if (w) addWithParsers(w, parsers);
5576
5629
  } else if (Array.isArray(arg)) {
5577
5630
  const { shape } = data;
5578
- let clonedParsers = false;
5631
+ const joinedParsers = {};
5579
5632
  for (const item of arg) {
5580
5633
  if (typeof item === "string") {
5581
5634
  const w = data.withShapes[item];
5582
5635
  Object.assign(shape, w.shape);
5583
- if (w.computeds) data.computeds = { ...data.computeds, ...w.computeds };
5584
- for (const key in w.shape) {
5585
- addColumnParserToQuery(
5586
- self,
5587
- key,
5588
- w.shape[key]
5589
- );
5590
- }
5636
+ if (w.computeds)
5637
+ data.runtimeComputeds = { ...data.runtimeComputeds, ...w.computeds };
5638
+ const parsers = {};
5639
+ joinedParsers[item] = parsers;
5640
+ addWithParsers(w, parsers);
5591
5641
  } else if (!isExpression(item)) {
5592
5642
  Object.assign(shape, getShapeFromSelect(item, true));
5593
- if (!clonedParsers) {
5594
- data.parsers = { ...data.parsers };
5595
- clonedParsers = true;
5596
- }
5597
- Object.assign(data.parsers, item.q.parsers);
5643
+ const key = getQueryAs(item);
5644
+ joinedParsers[key] = getQueryParsers(item);
5598
5645
  }
5599
5646
  }
5647
+ data.joinedParsers = joinedParsers;
5600
5648
  } else {
5601
5649
  const q = arg;
5602
5650
  data.as || (data.as = q.q.as || q.table || "t");
5603
5651
  data.shape = getShapeFromSelect(q, true);
5604
- data.parsers = q.q.parsers;
5652
+ data.defaultParsers = getQueryParsers(q);
5605
5653
  data.batchParsers = q.q.batchParsers;
5606
5654
  }
5607
5655
  data.from = arg;
@@ -5714,7 +5762,7 @@ const addParsersForSelectJoined = (q, arg, as = arg) => {
5714
5762
  }
5715
5763
  };
5716
5764
  const addParserForSelectItem = (q, as, key, arg, columnAlias, joinQuery) => {
5717
- if (typeof arg === "object" || typeof arg === "function") {
5765
+ if (typeof arg === "object") {
5718
5766
  const { q: query } = arg;
5719
5767
  if (query.batchParsers) {
5720
5768
  pushQueryArrayImmutable(
@@ -5726,7 +5774,8 @@ const addParserForSelectItem = (q, as, key, arg, columnAlias, joinQuery) => {
5726
5774
  }))
5727
5775
  );
5728
5776
  }
5729
- if (query.hookSelect || query.parsers || query.transform || query.returnType === "oneOrThrow" || query.returnType === "valueOrThrow" || query.returnType === "one" || query.returnType === "value") {
5777
+ const parsers = isExpression(arg) ? void 0 : getQueryParsers(arg);
5778
+ if (parsers || query.hookSelect || query.transform || query.returnType === "oneOrThrow" || query.returnType === "valueOrThrow" || query.returnType === "one" || query.returnType === "value") {
5730
5779
  pushQueryValueImmutable(q, "batchParsers", {
5731
5780
  path: [key],
5732
5781
  fn: (path, queryResult) => {
@@ -5750,7 +5799,6 @@ const addParserForSelectItem = (q, as, key, arg, columnAlias, joinQuery) => {
5750
5799
  collectNestedSelectBatches(batches, rows, path, last);
5751
5800
  switch (returnType) {
5752
5801
  case "all": {
5753
- const { parsers } = query;
5754
5802
  if (parsers) {
5755
5803
  for (const { data } of batches) {
5756
5804
  for (const one of data) {
@@ -5762,7 +5810,6 @@ const addParserForSelectItem = (q, as, key, arg, columnAlias, joinQuery) => {
5762
5810
  }
5763
5811
  case "one":
5764
5812
  case "oneOrThrow": {
5765
- const { parsers } = query;
5766
5813
  if (parsers) {
5767
5814
  if (returnType === "one") {
5768
5815
  for (const batch of batches) {
@@ -5793,7 +5840,7 @@ const addParserForSelectItem = (q, as, key, arg, columnAlias, joinQuery) => {
5793
5840
  break;
5794
5841
  }
5795
5842
  case "pluck": {
5796
- const parse = query.parsers?.pluck;
5843
+ const parse = parsers?.pluck;
5797
5844
  if (parse) {
5798
5845
  for (const { data } of batches) {
5799
5846
  for (let i = 0; i < data.length; i++) {
@@ -5806,7 +5853,7 @@ const addParserForSelectItem = (q, as, key, arg, columnAlias, joinQuery) => {
5806
5853
  case "value":
5807
5854
  case "valueOrThrow": {
5808
5855
  const notNullable = !query.getColumn?.data.isNullable;
5809
- const parse = query.parsers?.[getValueKey];
5856
+ const parse = parsers?.[getValueKey];
5810
5857
  if (parse) {
5811
5858
  if (returnType === "value") {
5812
5859
  for (const item of batches) {
@@ -6037,31 +6084,30 @@ const setParserForSelectedString = (query, arg, as, columnAs, columnAlias) => {
6037
6084
  const computeds = q.joinedComputeds?.[table];
6038
6085
  if (computeds?.[column]) {
6039
6086
  const computed = computeds[column];
6040
- const map = q.hookSelect = new Map(q.hookSelect);
6041
- for (const column2 of computed.deps) {
6042
- map.set(column2, { select: `${table}.${column2}` });
6043
- }
6087
+ _addToHookSelectWithTable(query, computed.deps, table);
6044
6088
  setObjectValueImmutable(q, "selectedComputeds", column, computed);
6045
6089
  return;
6046
6090
  }
6047
6091
  return arg;
6048
6092
  };
6049
6093
  const selectColumn = (query, q, key, columnAs, columnAlias) => {
6050
- if (columnAs && q.parsers) {
6051
- const parser = q.parsers[key];
6052
- if (parser) setObjectValueImmutable(q, "parsers", columnAs, parser);
6053
- }
6054
- if (q.computeds?.[key]) {
6055
- const computed = q.computeds[key];
6056
- const map = query.q.hookSelect = new Map(query.q.hookSelect);
6057
- for (const key2 of computed.deps) {
6058
- map.set(key2, { select: key2 });
6059
- }
6060
- query.q.selectedComputeds = {
6061
- ...query.q.selectedComputeds,
6062
- [columnAlias || key]: computed
6063
- };
6064
- return;
6094
+ if (key === "*") {
6095
+ const { defaultParsers } = query.q;
6096
+ if (defaultParsers) {
6097
+ spreadObjectValues(query.q, "parsers", defaultParsers);
6098
+ }
6099
+ } else {
6100
+ const parser = query.q.defaultParsers?.[key];
6101
+ if (parser) setObjectValueImmutable(q, "parsers", columnAs || key, parser);
6102
+ if (q.runtimeComputeds?.[key]) {
6103
+ const computed = q.runtimeComputeds[key];
6104
+ _addToHookSelect(query, computed.deps);
6105
+ query.q.selectedComputeds = {
6106
+ ...query.q.selectedComputeds,
6107
+ [columnAlias || key]: computed
6108
+ };
6109
+ return;
6110
+ }
6065
6111
  }
6066
6112
  return key;
6067
6113
  };
@@ -6194,6 +6240,11 @@ function _querySelect(q, args) {
6194
6240
  }
6195
6241
  return pushQueryArrayImmutable(q, "select", selectArgs);
6196
6242
  }
6243
+ const _querySelectAll = (query) => {
6244
+ const q = query;
6245
+ q.q.select = ["*"];
6246
+ q.q.parsers = q.q.defaultParsers;
6247
+ };
6197
6248
  class Select {
6198
6249
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
6199
6250
  select(...args) {
@@ -6217,7 +6268,7 @@ class Select {
6217
6268
  */
6218
6269
  selectAll() {
6219
6270
  const q = _clone(this);
6220
- q.q.select = ["*"];
6271
+ _querySelectAll(q);
6221
6272
  if (q.q.returning) {
6222
6273
  q.q.returnType = q.q.returningMany ? "all" : "oneOrThrow";
6223
6274
  q.q.returning = void 0;
@@ -7074,7 +7125,7 @@ const selectAllSql = (query, quotedAs, jsonList) => {
7074
7125
  if (jsonList) {
7075
7126
  Object.assign(jsonList, query.selectAllShape);
7076
7127
  }
7077
- return query.join?.length ? query.selectAllColumns?.map((item) => `${quotedAs}.${item}`).join(", ") || `${quotedAs}.*` : query.selectAllColumns?.join(", ") || "*";
7128
+ return query.join?.length || query.updateFrom ? query.selectAllColumns?.map((item) => `${quotedAs}.${item}`).join(", ") || `${quotedAs}.*` : query.selectAllColumns?.join(", ") || "*";
7078
7129
  };
7079
7130
  const pushSubQuerySql = (ctx, mainQuery, query, as, list, quotedAs, aliases) => {
7080
7131
  const { returnType = "all" } = query.q;
@@ -7145,7 +7196,7 @@ const pushSubQuerySql = (ctx, mainQuery, query, as, list, quotedAs, aliases) =>
7145
7196
  case "pluck": {
7146
7197
  const { select } = query.q;
7147
7198
  const first = select?.[0];
7148
- if (!first && query.q.computeds?.[as]) {
7199
+ if (!first && query.q.runtimeComputeds?.[as]) {
7149
7200
  query = queryJson(query);
7150
7201
  } else if (!first) {
7151
7202
  throw new OrchidOrmInternalError(
@@ -7162,7 +7213,7 @@ const pushSubQuerySql = (ctx, mainQuery, query, as, list, quotedAs, aliases) =>
7162
7213
  }
7163
7214
  case "value":
7164
7215
  case "valueOrThrow":
7165
- if (!query.q.returning && query.q.computeds?.[as]) {
7216
+ if (!query.q.returning && query.q.runtimeComputeds?.[as]) {
7166
7217
  query = queryJson(query);
7167
7218
  }
7168
7219
  break;
@@ -7274,9 +7325,6 @@ const pushFromAndAs = (ctx, table, data, quotedAs) => {
7274
7325
  let sql = "FROM ";
7275
7326
  const from = getFrom(ctx, table, data, quotedAs);
7276
7327
  sql += from;
7277
- if (data.as && quotedAs && quotedAs !== from) {
7278
- sql += ` ${quotedAs}`;
7279
- }
7280
7328
  for (const as in data.sources) {
7281
7329
  const source = data.sources[as];
7282
7330
  const lang = getSearchLang(ctx, data, source, quotedAs);
@@ -7323,6 +7371,9 @@ const getFrom = (ctx, table, data, quotedAs) => {
7323
7371
  return fromToSql(ctx, data, from, quotedAs);
7324
7372
  }
7325
7373
  let sql = quoteSchemaAndTable(data.schema, table.table);
7374
+ if (data.as && quotedAs && quotedAs !== sql) {
7375
+ sql += ` ${quotedAs}`;
7376
+ }
7326
7377
  if (data.only) sql = `ONLY ${sql}`;
7327
7378
  return sql;
7328
7379
  };
@@ -7331,13 +7382,13 @@ const fromToSql = (ctx, data, from, quotedAs) => {
7331
7382
  let sql;
7332
7383
  if (typeof from === "object") {
7333
7384
  if (isExpression(from)) {
7334
- sql = from.toSQL(ctx, quotedAs);
7385
+ sql = from.toSQL(ctx, quotedAs) + " " + quotedAs;
7335
7386
  } else {
7336
7387
  only = from.q.only;
7337
7388
  if (!from.table) {
7338
7389
  sql = `(${getSqlText(toSQL(from, ctx))})`;
7339
7390
  } else if (!checkIfASimpleQuery(from)) {
7340
- sql = `(${getSqlText(toSQL(from, ctx))})`;
7391
+ sql = `(${getSqlText(toSQL(from, ctx))}) ${quotedAs || `"${getQueryAs(from)}"`}`;
7341
7392
  } else {
7342
7393
  sql = quoteSchemaAndTable(from.q.schema, from.table);
7343
7394
  }
@@ -7455,7 +7506,45 @@ const pushUpdateSql = (ctx, table, query, quotedAs) => {
7455
7506
  }
7456
7507
  ctx.sql.push("SET");
7457
7508
  ctx.sql.push(set.join(", "));
7458
- pushWhereStatementSql(ctx, table, query, quotedAs);
7509
+ const { updateFrom } = query;
7510
+ let fromWhereSql;
7511
+ if (updateFrom) {
7512
+ const { target, on } = processJoinItem(
7513
+ ctx,
7514
+ table,
7515
+ query,
7516
+ updateFrom,
7517
+ quotedAs
7518
+ );
7519
+ ctx.sql.push(`FROM ${target}`);
7520
+ fromWhereSql = on;
7521
+ if (query.join) {
7522
+ const joinSet = query.join.length > 1 ? /* @__PURE__ */ new Set() : null;
7523
+ for (const item of query.join) {
7524
+ const { target: target2, on: on2 } = processJoinItem(
7525
+ ctx,
7526
+ table,
7527
+ query,
7528
+ item.args,
7529
+ quotedAs
7530
+ );
7531
+ if (joinSet) {
7532
+ const key = `${item.type}${target2}${on2}`;
7533
+ if (joinSet.has(key)) continue;
7534
+ joinSet.add(key);
7535
+ }
7536
+ ctx.sql.push(`${item.type} ${target2} ON true`);
7537
+ if (on2) {
7538
+ fromWhereSql = fromWhereSql ? fromWhereSql + " AND " + on2 : on2;
7539
+ }
7540
+ }
7541
+ }
7542
+ }
7543
+ const mainWhereSql = whereToSql(ctx, table, query, quotedAs);
7544
+ const whereSql = mainWhereSql ? fromWhereSql ? mainWhereSql + " AND " + fromWhereSql : mainWhereSql : fromWhereSql;
7545
+ if (whereSql) {
7546
+ ctx.sql.push("WHERE", whereSql);
7547
+ }
7459
7548
  hookSelect = pushUpdateReturning(
7460
7549
  ctx,
7461
7550
  table,
@@ -8747,7 +8836,7 @@ class WithMethods {
8747
8836
  const shape = getShapeFromSelect(query, true);
8748
8837
  return setQueryObjectValueImmutable(q, "withShapes", name, {
8749
8838
  shape,
8750
- computeds: query.q.computeds
8839
+ computeds: query.q.runtimeComputeds
8751
8840
  });
8752
8841
  }
8753
8842
  withRecursive(name, ...args) {
@@ -8758,7 +8847,7 @@ class WithMethods {
8758
8847
  arg.q.withShapes = q.q.withShapes;
8759
8848
  let query = typeof baseFn === "function" ? baseFn(arg) : baseFn;
8760
8849
  const shape = getShapeFromSelect(query, true);
8761
- const withConfig = { shape, computeds: query.q.computeds };
8850
+ const withConfig = { shape, computeds: query.q.runtimeComputeds };
8762
8851
  ((_a = arg.q).withShapes ?? (_a.withShapes = {}))[name] = withConfig;
8763
8852
  const recursive = recursiveFn(arg);
8764
8853
  query = _queryUnion(query, [recursive], options.union ?? "UNION ALL");
@@ -8775,14 +8864,15 @@ class WithMethods {
8775
8864
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
8776
8865
  withSql(name, ...args) {
8777
8866
  const q = _clone(this);
8778
- const [options, shape, sql] = args.length === 2 ? [void 0, args[0], args[1]] : args;
8867
+ const [options, shapeFn, sql] = args.length === 2 ? [void 0, args[0], args[1]] : args;
8868
+ const shape = shapeFn(this.columnTypes);
8779
8869
  pushQueryValueImmutable(q, "with", {
8780
8870
  n: name,
8781
- o: options,
8871
+ o: { ...options, columns: Object.keys(shape) },
8782
8872
  s: sql(q)
8783
8873
  });
8784
8874
  return setQueryObjectValueImmutable(q, "withShapes", name, {
8785
- shape: shape(this.columnTypes)
8875
+ shape
8786
8876
  });
8787
8877
  }
8788
8878
  }
@@ -9033,7 +9123,7 @@ const createSelect = (q) => {
9033
9123
  if (q.q.returnType === "void" || isSelectingCount(q)) {
9034
9124
  q.q.select = void 0;
9035
9125
  } else if (!q.q.select) {
9036
- q.q.select = ["*"];
9126
+ _querySelectAll(q);
9037
9127
  q.q.returning = true;
9038
9128
  }
9039
9129
  };
@@ -10879,6 +10969,7 @@ class JsonMethods {
10879
10969
  const mergableObjects = /* @__PURE__ */ new Set([
10880
10970
  "shape",
10881
10971
  "withShapes",
10972
+ "defaultParsers",
10882
10973
  "parsers",
10883
10974
  "defaults",
10884
10975
  "joinedShapes",
@@ -10965,7 +11056,8 @@ const _queryChangeCounter = (self, op, data) => {
10965
11056
  pushQueryValueImmutable(self, "updateData", map);
10966
11057
  return self;
10967
11058
  };
10968
- const _queryUpdate = (query, arg) => {
11059
+ const _queryUpdate = (updateSelf, arg) => {
11060
+ const query = updateSelf;
10969
11061
  const { q } = query;
10970
11062
  q.type = "update";
10971
11063
  const returnCount = !q.select;
@@ -10973,6 +11065,7 @@ const _queryUpdate = (query, arg) => {
10973
11065
  pushQueryValueImmutable(query, "updateData", set);
10974
11066
  const { shape } = q;
10975
11067
  const ctx = {};
11068
+ let selectQuery;
10976
11069
  for (const key in arg) {
10977
11070
  const item = shape[key];
10978
11071
  if (!item && shape !== anyShape) {
@@ -10984,8 +11077,12 @@ const _queryUpdate = (query, arg) => {
10984
11077
  if (item) throwOnReadOnly(query, item, key);
10985
11078
  let value = set[key];
10986
11079
  if (typeof value === "function") {
11080
+ if (!selectQuery) {
11081
+ selectQuery = query.clone();
11082
+ selectQuery.q.type = void 0;
11083
+ }
10987
11084
  value = resolveSubQueryCallbackV2(
10988
- query.baseQuery,
11085
+ selectQuery,
10989
11086
  value
10990
11087
  );
10991
11088
  if (value instanceof Db && value.q.type && value.q.subQuery) {
@@ -10998,14 +11095,7 @@ const _queryUpdate = (query, arg) => {
10998
11095
  }
10999
11096
  if (value !== null && value !== void 0 && !isExpression(value)) {
11000
11097
  if (value instanceof Db) {
11001
- moveQueryValueToWith(
11002
- query,
11003
- q,
11004
- value,
11005
- "with",
11006
- set,
11007
- key
11008
- );
11098
+ moveQueryValueToWith(query, q, value, "with", set, key);
11009
11099
  } else {
11010
11100
  const encode = item?.data.encode;
11011
11101
  if (encode) set[key] = encode(value);
@@ -11033,10 +11123,7 @@ const _queryUpdate = (query, arg) => {
11033
11123
  primaryKeys,
11034
11124
  queryResult.rows.map((item) => primaryKeys.map((key) => item[key]))
11035
11125
  );
11036
- await _queryUpdate(
11037
- t,
11038
- ctx.collect.data
11039
- );
11126
+ await _queryUpdate(t, ctx.collect.data);
11040
11127
  for (const row of queryResult.rows) {
11041
11128
  Object.assign(row, ctx.collect.data);
11042
11129
  }
@@ -11048,7 +11135,9 @@ const _queryUpdate = (query, arg) => {
11048
11135
  q.returnType = "valueOrThrow";
11049
11136
  q.returning = true;
11050
11137
  }
11051
- throwIfNoWhere(query, "update");
11138
+ if (!q.updateFrom) {
11139
+ throwIfNoWhere(query, "update");
11140
+ }
11052
11141
  return query;
11053
11142
  };
11054
11143
  const _queryUpdateOrThrow = (q, arg) => {
@@ -11286,6 +11375,77 @@ class Update {
11286
11375
  updateOrThrow(arg) {
11287
11376
  return _queryUpdateOrThrow(_clone(this), arg);
11288
11377
  }
11378
+ /**
11379
+ * Use `updateFrom` to update records in one table based on a query result from another table or CTE.
11380
+ *
11381
+ * `updateFrom` accepts the same arguments as {@link Query.join}.
11382
+ *
11383
+ * ```ts
11384
+ * // save all author names to their books by using a relation name:
11385
+ * db.books.updateFrom('author').set({ authorName: (q) => q.ref('author.name') });
11386
+ *
11387
+ * // update from authors that match the condition:
11388
+ * db.books
11389
+ * .updateFrom((q) => q.author.where({ writingSkills: 'good' }))
11390
+ * .set({ authorName: (q) => q.ref('author.name') });
11391
+ *
11392
+ * // update from any table using custom `on` conditions:
11393
+ * db.books
11394
+ * .updateFrom(
11395
+ * () => db.authors,
11396
+ * (q) => q.on('authors.id', 'books.authorId'),
11397
+ * )
11398
+ * .set({ authorName: (q) => q.ref('author.name') });
11399
+ *
11400
+ * // conditions after `updateFrom` can reference both tables:
11401
+ * db.books
11402
+ * .updateFrom(() => db.authors)
11403
+ * .where({
11404
+ * 'authors.id': (q) => q.ref('books.authorId'),
11405
+ * })
11406
+ * .set({ authorName: (q) => q.ref('author.name') });
11407
+ *
11408
+ * // can join and use another table in between `updateFrom` and `set`:
11409
+ * db.books
11410
+ * .updateFrom('author')
11411
+ * .join('publisher')
11412
+ * .set({
11413
+ * authorName: (q) => q.ref('author.name'),
11414
+ * publisherName: (q) => q.ref('publisher.name'),
11415
+ * });
11416
+ *
11417
+ * // updating from a CTE
11418
+ * db.books
11419
+ * .with('a', () =>
11420
+ * db.authors.where({ writingSkills: 'good' }).select('id', 'name').limit(10),
11421
+ * )
11422
+ * .updateFrom('a', (q) => q.on('a.id', 'books.authorId'))
11423
+ * .set({ authorName: (q) => q.ref('author.name') });
11424
+ * ```
11425
+ */
11426
+ updateFrom(arg, ...args) {
11427
+ const q = _clone(this);
11428
+ const joinArgs = _joinReturningArgs(
11429
+ q,
11430
+ true,
11431
+ arg,
11432
+ args,
11433
+ // eslint-disable-line @typescript-eslint/no-explicit-any
11434
+ true
11435
+ );
11436
+ if (!joinArgs) {
11437
+ return _queryNone(q);
11438
+ }
11439
+ joinArgs.u = true;
11440
+ q.q.updateFrom = joinArgs;
11441
+ return q;
11442
+ }
11443
+ /**
11444
+ * Use after {@link updateFrom}
11445
+ */
11446
+ set(arg) {
11447
+ return _queryUpdate(_clone(this), arg);
11448
+ }
11289
11449
  /**
11290
11450
  * Increments a column by `1`, returns a count of updated records by default.
11291
11451
  *
@@ -11614,8 +11774,8 @@ function orCreate(query, data, updateData, mergeData) {
11614
11774
  const { handleResult } = q;
11615
11775
  let result;
11616
11776
  let created = false;
11617
- q.handleResult = (q2, t, r, s) => {
11618
- return created ? result : handleResult(q2, t, r, s);
11777
+ q.handleResult = (q2, t, r, s, i) => {
11778
+ return created ? result : handleResult(q2, t, r, s, i);
11619
11779
  };
11620
11780
  q.hookSelect = new Map(q.hookSelect);
11621
11781
  q.patchResult = async (q2, hookSelect, queryResult) => {
@@ -11654,7 +11814,7 @@ function orCreate(query, data, updateData, mergeData) {
11654
11814
  );
11655
11815
  let afterHooks;
11656
11816
  let afterCommitHooks;
11657
- q22.q.handleResult = (a, t, r, s) => {
11817
+ q22.q.handleResult = (a, t, r, s, i) => {
11658
11818
  if (hasAfterCallback || hasAfterCommitCallback) {
11659
11819
  const fieldName = r.fields[0].name;
11660
11820
  if (r.rows[0][fieldName]) {
@@ -11666,7 +11826,7 @@ function orCreate(query, data, updateData, mergeData) {
11666
11826
  }
11667
11827
  delete r.rows[0][fieldName];
11668
11828
  }
11669
- result = handleResult(a, t, r, s);
11829
+ result = handleResult(a, t, r, s, i);
11670
11830
  return a.q.hookSelect ? result.map((row) => ({ ...row })) : result;
11671
11831
  };
11672
11832
  q22.q.log = q2.q.log;
@@ -12990,15 +13150,6 @@ class Db extends QueryMethods {
12990
13150
  const self = this;
12991
13151
  const { softDelete } = options;
12992
13152
  const scopes = options.scopes || softDelete ? {} : emptyObject;
12993
- this.internal = {
12994
- transactionStorage,
12995
- scopes,
12996
- snakeCase: options.snakeCase,
12997
- noPrimaryKey: options.noPrimaryKey === "ignore",
12998
- comment: options.comment,
12999
- nowSQL: options.nowSQL,
13000
- tableData
13001
- };
13002
13153
  this.baseQuery = this;
13003
13154
  this.relations = {};
13004
13155
  this.relationQueries = {};
@@ -13008,6 +13159,7 @@ class Db extends QueryMethods {
13008
13159
  let modifyQuery = void 0;
13009
13160
  let prepareSelectAll = false;
13010
13161
  let hasHookSetters;
13162
+ let runtimeDefaultColumns;
13011
13163
  const { snakeCase } = options;
13012
13164
  for (const key in shape) {
13013
13165
  const column = shape[key];
@@ -13033,9 +13185,8 @@ class Db extends QueryMethods {
13033
13185
  modifyQuery = pushOrNewArray(modifyQuery, (q) => mq(q, column));
13034
13186
  }
13035
13187
  if (typeof column.data.default === "function") {
13036
- const arr = this.internal.runtimeDefaultColumns;
13037
- if (!arr) this.internal.runtimeDefaultColumns = [key];
13038
- else arr.push(key);
13188
+ if (!runtimeDefaultColumns) runtimeDefaultColumns = [key];
13189
+ else runtimeDefaultColumns.push(key);
13039
13190
  if (!column.data.runtimeDefault) {
13040
13191
  const {
13041
13192
  data: { default: def, encode }
@@ -13047,6 +13198,16 @@ class Db extends QueryMethods {
13047
13198
  hasHookSetters = true;
13048
13199
  }
13049
13200
  }
13201
+ this.internal = {
13202
+ runtimeDefaultColumns,
13203
+ transactionStorage,
13204
+ scopes,
13205
+ snakeCase: options.snakeCase,
13206
+ noPrimaryKey: options.noPrimaryKey === "ignore",
13207
+ comment: options.comment,
13208
+ nowSQL: options.nowSQL,
13209
+ tableData
13210
+ };
13050
13211
  this.q = {
13051
13212
  adapter,
13052
13213
  shape,
@@ -13054,7 +13215,7 @@ class Db extends QueryMethods {
13054
13215
  logger,
13055
13216
  log: logParamToLogObject(logger, options.log),
13056
13217
  autoPreparedStatements: options.autoPreparedStatements ?? false,
13057
- parsers: hasParsers ? parsers : void 0,
13218
+ defaultParsers: hasParsers ? parsers : void 0,
13058
13219
  language: options.language,
13059
13220
  schema: options?.schema
13060
13221
  };
@@ -13458,5 +13619,5 @@ function copyTableData(query, arg) {
13458
13619
  return q;
13459
13620
  }
13460
13621
 
13461
- export { AfterCommitError, AggregateMethods, ArrayColumn, BigIntColumn, BigSerialColumn, BitColumn, BitVaryingColumn, BooleanColumn, BoxColumn, ByteaColumn, CidrColumn, CircleColumn, CitextColumn, Clear, ColumnRefExpression, ColumnType, ComputedColumn, 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, NumberAsStringBaseColumn, NumberBaseColumn, OnMethods, Operators, OrExpression, PathColumn, PointColumn, PolygonColumn, PostgisGeographyPointColumn, QueryAsMethods, QueryGet, QueryHooks, QueryLog, QueryMethods, QueryUpsert, RawSQL, RealColumn, RefExpression, SearchMethods, Select, SerialColumn, SmallIntColumn, SmallSerialColumn, SqlMethod, StringColumn, TextBaseColumn, TextColumn, Then, TimeColumn, TimestampColumn, TimestampTZColumn, Transaction, TransformMethods, TsQueryColumn, TsVectorColumn, UUIDColumn, Union, UnknownColumn, Update, VarCharColumn, VirtualColumn, Where, WithMethods, XMLColumn, _addWith, _clone, _getSelectableColumn, _initQueryBuilder, _queryAfterSaveCommit, _queryAll, _queryChangeCounter, _queryCreate, _queryCreateForEachFrom, _queryCreateMany, _queryCreateManyFrom, _queryCreateOneFrom, _queryDefaults, _queryDelete, _queryExec, _queryFindBy, _queryFindByOptional, _queryGet, _queryGetOptional, _queryHookAfterCreate, _queryHookAfterCreateCommit, _queryHookAfterDelete, _queryHookAfterDeleteCommit, _queryHookAfterQuery, _queryHookAfterSave, _queryHookAfterUpdate, _queryHookAfterUpdateCommit, _queryHookBeforeCreate, _queryHookBeforeDelete, _queryHookBeforeQuery, _queryHookBeforeSave, _queryHookBeforeUpdate, _queryInsert, _queryInsertForEachFrom, _queryInsertMany, _queryInsertManyFrom, _queryInsertOneFrom, _queryJoinOn, _queryJoinOnJsonPathEquals, _queryJoinOrOn, _queryOr, _queryOrNot, _queryRows, _querySelect, _queryTake, _queryTakeOptional, _queryUnion, _queryUpdate, _queryUpdateOrThrow, _queryWhere, _queryWhereExists, _queryWhereIn, _queryWhereNot, _queryWhereNotOneOf, _queryWhereNotSql, _queryWhereOneOf, _queryWhereSql, _runAfterCommitHooks, addColumnParserToQuery, addParserForRawExpression, addParserForSelectItem, addQueryOn, anyShape, applyComputedColumns, assignDbDataToColumn, checkIfASimpleQuery, cloneQueryBaseUnscoped, columnCheckToCode, columnCode, columnExcludesToCode, columnForeignKeysToCode, columnIndexesToCode, columnsShapeToCode, commitSql, constraintInnerToCode, constraintToCode, copyTableData, countSelect, createDbWithAdapter, defaultSchemaConfig, escapeForLog, escapeForMigration, escapeString, excludeInnerToCode, excludeToCode, extendQuery, filterResult, foreignKeyArgumentToCode, getClonedQueryData, getColumnBaseType, getColumnInfo, getColumnTypes, getFullColumnTable, getQueryAs, getShapeFromSelect, getSqlText, handleResult, identityToCode, indexInnerToCode, indexToCode, isDefaultTimeStamp, isInUserTransaction, isQueryReturnsAll, isSelectingCount, joinSubQuery, logParamToLogObject, makeColumnTypes, makeColumnsByType, makeFnExpression, moveQueryValueToWith, parseRecord, parseTableData, parseTableDataInput, postgisTypmodToSql, primaryKeyInnerToCode, processComputedBatches, processComputedResult, processSelectArg, pushLimitSQL, pushQueryArrayImmutable, pushQueryOn, pushQueryOnForOuter, pushQueryOrOn, pushTableDataCode, queryFrom, queryFromSql, queryJson, queryMethodByReturnType, queryTypeWithLimitOne, queryWrap, raw, referencesArgsToCode, resolveSubQueryCallbackV2, rollbackSql, saveAliasedShape, setColumnDefaultParse, setColumnEncode, setColumnParse, setColumnParseNull, setParserForSelectedString, setQueryObjectValueImmutable, setQueryOperators, simplifyColumnDefault, sqlFn, sqlQueryArgsToExpression, tableDataMethods, templateLiteralToSQL, testTransaction, throwIfJoinLateral, throwIfNoWhere, toSQL };
13622
+ export { AfterCommitError, AggregateMethods, ArrayColumn, BigIntColumn, BigSerialColumn, BitColumn, BitVaryingColumn, BooleanColumn, BoxColumn, ByteaColumn, CidrColumn, CircleColumn, CitextColumn, Clear, ColumnRefExpression, ColumnType, ComputedColumn, 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, NumberAsStringBaseColumn, NumberBaseColumn, OnMethods, Operators, OrExpression, PathColumn, PointColumn, PolygonColumn, PostgisGeographyPointColumn, QueryAsMethods, QueryGet, QueryHooks, QueryLog, QueryMethods, QueryUpsert, RawSQL, RealColumn, RefExpression, SearchMethods, Select, SerialColumn, SmallIntColumn, SmallSerialColumn, SqlMethod, StringColumn, TextBaseColumn, TextColumn, Then, TimeColumn, TimestampColumn, TimestampTZColumn, Transaction, TransformMethods, TsQueryColumn, TsVectorColumn, UUIDColumn, Union, UnknownColumn, Update, VarCharColumn, VirtualColumn, Where, WithMethods, XMLColumn, _addWith, _clone, _getSelectableColumn, _initQueryBuilder, _queryAfterSaveCommit, _queryAll, _queryChangeCounter, _queryCreate, _queryCreateForEachFrom, _queryCreateMany, _queryCreateManyFrom, _queryCreateOneFrom, _queryDefaults, _queryDelete, _queryExec, _queryFindBy, _queryFindByOptional, _queryGet, _queryGetOptional, _queryHookAfterCreate, _queryHookAfterCreateCommit, _queryHookAfterDelete, _queryHookAfterDeleteCommit, _queryHookAfterQuery, _queryHookAfterSave, _queryHookAfterUpdate, _queryHookAfterUpdateCommit, _queryHookBeforeCreate, _queryHookBeforeDelete, _queryHookBeforeQuery, _queryHookBeforeSave, _queryHookBeforeUpdate, _queryInsert, _queryInsertForEachFrom, _queryInsertMany, _queryInsertManyFrom, _queryInsertOneFrom, _queryJoinOn, _queryJoinOnJsonPathEquals, _queryJoinOrOn, _queryOr, _queryOrNot, _queryRows, _querySelect, _querySelectAll, _queryTake, _queryTakeOptional, _queryUnion, _queryUpdate, _queryUpdateOrThrow, _queryWhere, _queryWhereExists, _queryWhereIn, _queryWhereNot, _queryWhereNotOneOf, _queryWhereNotSql, _queryWhereOneOf, _queryWhereSql, _runAfterCommitHooks, addColumnParserToQuery, addParserForRawExpression, addParserForSelectItem, addQueryOn, anyShape, applyComputedColumns, assignDbDataToColumn, checkIfASimpleQuery, cloneQueryBaseUnscoped, columnCheckToCode, columnCode, columnExcludesToCode, columnForeignKeysToCode, columnIndexesToCode, columnsShapeToCode, commitSql, constraintInnerToCode, constraintToCode, copyTableData, countSelect, createDbWithAdapter, defaultSchemaConfig, escapeForLog, escapeForMigration, escapeString, excludeInnerToCode, excludeToCode, extendQuery, filterResult, foreignKeyArgumentToCode, getClonedQueryData, getColumnBaseType, getColumnInfo, getColumnTypes, getFullColumnTable, getQueryAs, getShapeFromSelect, getSqlText, handleResult, identityToCode, indexInnerToCode, indexToCode, isDefaultTimeStamp, isInUserTransaction, isQueryReturnsAll, isSelectingCount, joinSubQuery, logParamToLogObject, makeColumnTypes, makeColumnsByType, makeFnExpression, moveQueryValueToWith, parseRecord, parseTableData, parseTableDataInput, postgisTypmodToSql, primaryKeyInnerToCode, processComputedBatches, processComputedResult, processSelectArg, pushLimitSQL, pushQueryArrayImmutable, pushQueryOn, pushQueryOnForOuter, pushQueryOrOn, pushTableDataCode, queryFrom, queryFromSql, queryJson, queryMethodByReturnType, queryTypeWithLimitOne, queryWrap, raw, referencesArgsToCode, resolveSubQueryCallbackV2, rollbackSql, saveAliasedShape, setColumnDefaultParse, setColumnEncode, setColumnParse, setColumnParseNull, setParserForSelectedString, setQueryObjectValueImmutable, setQueryOperators, simplifyColumnDefault, sqlFn, sqlQueryArgsToExpression, tableDataMethods, templateLiteralToSQL, testTransaction, throwIfJoinLateral, throwIfNoWhere, toSQL };
13462
13623
  //# sourceMappingURL=index.mjs.map