pqb 0.51.5 → 0.52.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
@@ -2862,14 +2862,25 @@ class AfterCommitError extends OrchidOrmError {
2862
2862
  this.hookResults = hookResults;
2863
2863
  }
2864
2864
  }
2865
- const _afterCommitError = (result, hookResults, catchAfterCommitError) => {
2866
- const err = new AfterCommitError(result, hookResults);
2867
- if (catchAfterCommitError) {
2868
- catchAfterCommitError(err);
2869
- } else {
2870
- throw err;
2865
+ const _runAfterCommitHooks = async (result, promises, getHookNames, catchAfterCommitErrors) => {
2866
+ const hookResults = await Promise.allSettled(promises);
2867
+ if (hookResults.some((result2) => result2.status === "rejected")) {
2868
+ const hookNames = getHookNames();
2869
+ for (const [i, r] of hookResults.entries()) {
2870
+ r.name = hookNames[i];
2871
+ }
2872
+ const err = new AfterCommitError(result, hookResults);
2873
+ if (!catchAfterCommitErrors) throw err;
2874
+ for (const fn of catchAfterCommitErrors) {
2875
+ try {
2876
+ fn(err);
2877
+ } catch {
2878
+ }
2879
+ }
2871
2880
  }
2872
2881
  };
2882
+ const isInUserTransaction = (trx) => !!(trx && // when inside test transactions, compare transaction counts to ensure there is a user transaction.
2883
+ (!trx.testTransactionCount || trx.transactionId >= trx.testTransactionCount));
2873
2884
  class Transaction {
2874
2885
  async transaction(cbOrOptions, cb) {
2875
2886
  let options;
@@ -2912,10 +2923,7 @@ class Transaction {
2912
2923
  throw err;
2913
2924
  });
2914
2925
  if (log) log.afterQuery(commitSql$1, logData);
2915
- await runAfterCommit(
2916
- trx.afterCommit,
2917
- result
2918
- );
2926
+ runAfterCommit(trx.afterCommit, result);
2919
2927
  return result;
2920
2928
  } else {
2921
2929
  try {
@@ -2940,7 +2948,7 @@ class Transaction {
2940
2948
  if (transactionId === trx.testTransactionCount) {
2941
2949
  const { afterCommit } = trx;
2942
2950
  trx.afterCommit = void 0;
2943
- await runAfterCommit(afterCommit, result);
2951
+ runAfterCommit(afterCommit, result);
2944
2952
  }
2945
2953
  return result;
2946
2954
  } finally {
@@ -2975,42 +2983,95 @@ class Transaction {
2975
2983
  }
2976
2984
  isInTransaction() {
2977
2985
  const trx = this.internal.transactionStorage.getStore();
2978
- return !!(trx && (!trx.testTransactionCount || trx.transactionId >= trx.testTransactionCount));
2986
+ return isInUserTransaction(trx);
2979
2987
  }
2980
- }
2981
- const runAfterCommit = async (afterCommit, result) => {
2982
- if (afterCommit) {
2983
- const promises = [];
2984
- let catchAfterCommitError;
2985
- for (let i = 0, len = afterCommit.length; i < len; i += 3) {
2986
- const result2 = afterCommit[i];
2987
- const q = afterCommit[i + 1];
2988
- if (q.q.catchAfterCommitError) {
2989
- catchAfterCommitError = q.q.catchAfterCommitError;
2990
- }
2991
- for (const fn of afterCommit[i + 2]) {
2992
- try {
2993
- promises.push(fn(result2, q));
2994
- } catch (err) {
2995
- promises.push(Promise.reject(err));
2988
+ /**
2989
+ * Schedules a hook to run after the outermost transaction commits:
2990
+ *
2991
+ * ```ts
2992
+ * await db.$transaction(async () => {
2993
+ * await db.table.create(data)
2994
+ * await db.table.where({ ...conditions }).update({ key: 'value' })
2995
+ *
2996
+ * db.$afterCommit(() => { // can be sync or async
2997
+ * console.log('after commit')
2998
+ * })
2999
+ * })
3000
+ * ```
3001
+ *
3002
+ * If used outside the transaction, the hook will be executed almost immediately, on the next microtask:
3003
+ *
3004
+ * ```ts
3005
+ * db.$afterCommit(async () => { // can be sync or async
3006
+ * console.log('after commit')
3007
+ * })
3008
+ * ```
3009
+ *
3010
+ * If the callback has no `try/catch` and throws an error,
3011
+ * this will cause `uncaughtException` if the callback is sync and `unhandledRejection` if it is async.
3012
+ */
3013
+ afterCommit(hook) {
3014
+ const trx = this.internal.transactionStorage.getStore();
3015
+ if (isInUserTransaction(trx)) {
3016
+ (trx.afterCommit ?? (trx.afterCommit = [])).push(hook);
3017
+ } else {
3018
+ queueMicrotask(hook);
3019
+ }
3020
+ }
3021
+ }
3022
+ const runAfterCommit = (afterCommit, result) => {
3023
+ queueMicrotask(async () => {
3024
+ if (afterCommit) {
3025
+ const promises = [];
3026
+ let catchAfterCommitErrors;
3027
+ for (let i = 0, len = afterCommit.length; i < len; ) {
3028
+ const first = afterCommit[i];
3029
+ if (typeof first === "function") {
3030
+ try {
3031
+ promises.push(first());
3032
+ } catch (err) {
3033
+ promises.push(Promise.reject(err));
3034
+ }
3035
+ i++;
3036
+ } else {
3037
+ const q = afterCommit[i + 1];
3038
+ if (q.q.catchAfterCommitErrors) {
3039
+ (catchAfterCommitErrors ?? (catchAfterCommitErrors = [])).push(...q.q.catchAfterCommitErrors);
3040
+ }
3041
+ for (const fn of afterCommit[i + 2]) {
3042
+ try {
3043
+ promises.push(fn(first, q));
3044
+ } catch (err) {
3045
+ promises.push(Promise.reject(err));
3046
+ }
3047
+ }
3048
+ i += 3;
2996
3049
  }
2997
3050
  }
2998
- }
2999
- const hookResults = await Promise.allSettled(promises);
3000
- if (hookResults.some((result2) => result2.status === "rejected")) {
3001
- const resultsWithNames = [];
3002
- let r = 0;
3003
- for (let i = 0, len = afterCommit.length; i < len; i += 3) {
3004
- for (const fn of afterCommit[i + 2]) {
3005
- resultsWithNames.push({
3006
- ...hookResults[r++],
3007
- name: fn.name
3008
- });
3051
+ const getHookNames = () => {
3052
+ const hookNames = [];
3053
+ for (let i = 0, len = afterCommit.length; i < len; ) {
3054
+ const first = afterCommit[i];
3055
+ if (typeof first === "function") {
3056
+ hookNames.push(first.name);
3057
+ i++;
3058
+ } else {
3059
+ for (const fn of afterCommit[i + 2]) {
3060
+ hookNames.push(fn.name);
3061
+ }
3062
+ i += 3;
3063
+ }
3009
3064
  }
3010
- }
3011
- _afterCommitError(result, resultsWithNames, catchAfterCommitError);
3065
+ return hookNames;
3066
+ };
3067
+ await _runAfterCommitHooks(
3068
+ result,
3069
+ promises,
3070
+ getHookNames,
3071
+ catchAfterCommitErrors
3072
+ );
3012
3073
  }
3013
- }
3074
+ });
3014
3075
  };
3015
3076
 
3016
3077
  const applyBatchTransforms = (q, batches) => {
@@ -3428,35 +3489,32 @@ const then = async (q, adapter, trx, beforeHooks, afterHooks, afterCommitHooks,
3428
3489
  );
3429
3490
  }
3430
3491
  if (afterCommitHooks) {
3431
- if (trx && // when inside test transactions, push to a transaction only unless it's the outer user transaction.
3432
- (!trx.testTransactionCount || trx.transactionId + 1 > trx.testTransactionCount)) {
3492
+ if (isInUserTransaction(trx)) {
3433
3493
  (trx.afterCommit ?? (trx.afterCommit = [])).push(
3434
3494
  result,
3435
3495
  q,
3436
3496
  afterCommitHooks
3437
3497
  );
3438
3498
  } else {
3439
- const promises = [];
3440
- for (const fn of afterCommitHooks) {
3441
- try {
3442
- promises.push(
3443
- fn(result, q)
3444
- );
3445
- } catch (err) {
3446
- promises.push(Promise.reject(err));
3499
+ const localResult = result;
3500
+ queueMicrotask(async () => {
3501
+ const promises = [];
3502
+ for (const fn of afterCommitHooks) {
3503
+ try {
3504
+ promises.push(
3505
+ fn(localResult, q)
3506
+ );
3507
+ } catch (err) {
3508
+ promises.push(Promise.reject(err));
3509
+ }
3447
3510
  }
3448
- }
3449
- const hookResults = await Promise.allSettled(promises);
3450
- if (hookResults.some((result2) => result2.status === "rejected")) {
3451
- _afterCommitError(
3452
- result,
3453
- hookResults.map((result2, i) => ({
3454
- ...result2,
3455
- name: afterCommitHooks[i].name
3456
- })),
3457
- q.q.catchAfterCommitError
3511
+ await _runAfterCommitHooks(
3512
+ localResult,
3513
+ promises,
3514
+ () => afterCommitHooks.map((h) => h.name),
3515
+ q.q.catchAfterCommitErrors
3458
3516
  );
3459
- }
3517
+ });
3460
3518
  }
3461
3519
  }
3462
3520
  } else if (query.after) {
@@ -9504,7 +9562,9 @@ class QueryHooks {
9504
9562
  * })
9505
9563
  * .catchAfterCommitError((err) => {
9506
9564
  * // err is instance of AfterCommitError (see below)
9507
- * });
9565
+ * })
9566
+ * // can be added multiple times, all catchers will be executed
9567
+ * .catchAfterCommitError((err) => {});
9508
9568
  *
9509
9569
  * // result is available even if an after commit hook has failed
9510
9570
  * result.id;
@@ -9512,7 +9572,7 @@ class QueryHooks {
9512
9572
  */
9513
9573
  catchAfterCommitError(fn) {
9514
9574
  const q = _clone(this);
9515
- q.q.catchAfterCommitError = fn;
9575
+ pushQueryValueImmutable(q, "catchAfterCommitErrors", fn);
9516
9576
  return q;
9517
9577
  }
9518
9578
  }
@@ -13191,5 +13251,5 @@ function copyTableData(query, arg) {
13191
13251
  return q;
13192
13252
  }
13193
13253
 
13194
- export { Adapter, AfterCommitError, AggregateMethods, ArrayColumn, AsMethods, BigIntColumn, BigSerialColumn, BitColumn, BitVaryingColumn, BooleanColumn, BoxColumn, ByteaColumn, CidrColumn, CircleColumn, CitextColumn, Clear, ColumnRefExpression, ColumnType, ComputedColumn, Create, CustomTypeColumn, DateBaseColumn, DateColumn, DateTimeBaseClass, DateTimeTzBaseClass, Db, DecimalColumn, Delete, DomainColumn, DoublePrecisionColumn, DynamicRawSQL, EnumColumn, ExpressionMethods, FnExpression, For, FromMethods, Having, InetColumn, IntegerBaseColumn, IntegerColumn, IntervalColumn, JSONColumn, JSONTextColumn, Join, JsonMethods, LimitedTextBaseColumn, LineColumn, LsegColumn, MacAddr8Column, MacAddrColumn, MergeQueryMethods, MoneyColumn, MoreThanOneRowError, NotFoundError, NumberAsStringBaseColumn, NumberBaseColumn, OnConflictQueryBuilder, OnMethods, Operators, OrExpression, OrchidOrmError, OrchidOrmInternalError, PathColumn, PointColumn, PolygonColumn, PostgisGeographyPointColumn, 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, _afterCommitError, _clone, _getSelectableColumn, _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, _queryResolveAlias, _queryRows, _querySelect, _queryTake, _queryTakeOptional, _queryUnion, _queryUpdate, _queryUpdateOrThrow, _queryUpdateRaw, _queryWhere, _queryWhereExists, _queryWhereIn, _queryWhereNot, _queryWhereNotOneOf, _queryWhereNotSql, _queryWhereOneOf, _queryWhereSql, addColumnParserToQuery, addParserForRawExpression, addParserForSelectItem, addQueryOn, anyShape, applyComputedColumns, assignDbDataToColumn, checkIfASimpleQuery, cloneQueryBaseUnscoped, columnCheckToCode, columnCode, columnExcludesToCode, columnForeignKeysToCode, columnIndexesToCode, columnsShapeToCode, commitSql$1 as commitSql, constraintInnerToCode, constraintToCode, copyTableData, countSelect, createDb, defaultSchemaConfig, escapeForLog, escapeForMigration, escapeString, excludeInnerToCode, excludeToCode, extendQuery, filterResult, foreignKeyArgumentToCode, getClonedQueryData, getColumnBaseType, getColumnInfo, getColumnTypes, getFullColumnTable, getPrimaryKeys, getQueryAs, getShapeFromSelect, getSqlText, handleResult, identityToCode, indexInnerToCode, indexToCode, isDefaultTimeStamp, isQueryReturnsAll, isSelectingCount, joinSubQuery, logParamToLogObject, makeColumnTypes, makeColumnsByType, makeFnExpression, makeRegexToFindInSql, parseRecord, parseTableData, parseTableDataInput, postgisTypmodToSql, primaryKeyInnerToCode, processComputedBatches, processComputedResult, processSelectArg, pushLimitSQL, pushQueryArrayImmutable, pushQueryOn, pushQueryOnForOuter, pushQueryOrOn, pushQueryValueImmutable, pushTableDataCode, queryFrom, queryFromSql, queryJson, queryMethodByReturnType, queryTypeWithLimitOne, queryWrap, raw, referencesArgsToCode, resolveSubQueryCallbackV2, rollbackSql$1 as rollbackSql, saveSearchAlias, setColumnDefaultParse, setColumnEncode, setColumnParse, setColumnParseNull, setParserForSelectedString, setQueryObjectValueImmutable, setQueryOperators, simplifyColumnDefault, sqlFn, sqlQueryArgsToExpression, tableDataMethods, templateLiteralToSQL, testTransaction, throwIfJoinLateral, throwIfNoWhere, toSQL };
13254
+ export { Adapter, AfterCommitError, AggregateMethods, ArrayColumn, AsMethods, BigIntColumn, BigSerialColumn, BitColumn, BitVaryingColumn, BooleanColumn, BoxColumn, ByteaColumn, CidrColumn, CircleColumn, CitextColumn, Clear, ColumnRefExpression, ColumnType, ComputedColumn, Create, CustomTypeColumn, DateBaseColumn, DateColumn, DateTimeBaseClass, DateTimeTzBaseClass, Db, DecimalColumn, Delete, DomainColumn, DoublePrecisionColumn, DynamicRawSQL, EnumColumn, ExpressionMethods, FnExpression, For, FromMethods, Having, InetColumn, IntegerBaseColumn, IntegerColumn, IntervalColumn, JSONColumn, JSONTextColumn, Join, JsonMethods, LimitedTextBaseColumn, LineColumn, LsegColumn, MacAddr8Column, MacAddrColumn, MergeQueryMethods, MoneyColumn, MoreThanOneRowError, NotFoundError, NumberAsStringBaseColumn, NumberBaseColumn, OnConflictQueryBuilder, OnMethods, Operators, OrExpression, OrchidOrmError, OrchidOrmInternalError, PathColumn, PointColumn, PolygonColumn, PostgisGeographyPointColumn, 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, _clone, _getSelectableColumn, _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, _queryResolveAlias, _queryRows, _querySelect, _queryTake, _queryTakeOptional, _queryUnion, _queryUpdate, _queryUpdateOrThrow, _queryUpdateRaw, _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$1 as commitSql, constraintInnerToCode, constraintToCode, copyTableData, countSelect, createDb, defaultSchemaConfig, escapeForLog, escapeForMigration, escapeString, excludeInnerToCode, excludeToCode, extendQuery, filterResult, foreignKeyArgumentToCode, getClonedQueryData, getColumnBaseType, getColumnInfo, getColumnTypes, getFullColumnTable, getPrimaryKeys, getQueryAs, getShapeFromSelect, getSqlText, handleResult, identityToCode, indexInnerToCode, indexToCode, isDefaultTimeStamp, isInUserTransaction, isQueryReturnsAll, isSelectingCount, joinSubQuery, logParamToLogObject, makeColumnTypes, makeColumnsByType, makeFnExpression, makeRegexToFindInSql, parseRecord, parseTableData, parseTableDataInput, postgisTypmodToSql, primaryKeyInnerToCode, processComputedBatches, processComputedResult, processSelectArg, pushLimitSQL, pushQueryArrayImmutable, pushQueryOn, pushQueryOnForOuter, pushQueryOrOn, pushQueryValueImmutable, pushTableDataCode, queryFrom, queryFromSql, queryJson, queryMethodByReturnType, queryTypeWithLimitOne, queryWrap, raw, referencesArgsToCode, resolveSubQueryCallbackV2, rollbackSql$1 as rollbackSql, saveSearchAlias, setColumnDefaultParse, setColumnEncode, setColumnParse, setColumnParseNull, setParserForSelectedString, setQueryObjectValueImmutable, setQueryOperators, simplifyColumnDefault, sqlFn, sqlQueryArgsToExpression, tableDataMethods, templateLiteralToSQL, testTransaction, throwIfJoinLateral, throwIfNoWhere, toSQL };
13195
13255
  //# sourceMappingURL=index.mjs.map