orchid-orm 1.6.40 → 1.7.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.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import * as pqb from 'pqb';
2
- import { BelongsToRelation, HasManyRelation, HasOneRelation, Db, Adapter, FromArgs, Query, FromResult, AdapterOptions, QueryLogOptions, NoPrimaryKeyOption, HasAndBelongsToManyRelation, SetQueryTableAlias, defaultsKey, BaseRelation, RelationQuery, SetQueryReturnsOne, SetQueryReturnsOneOptional, SetQueryReturnsAll, DefaultColumnTypes, ColumnsShape, WhereResult, MergeQuery, SetQueryReturns, QueryReturnType } from 'pqb';
2
+ import { BelongsToRelation, HasManyRelation, HasOneRelation, Db, IsolationLevel, TransactionOptions, Adapter, FromArgs, Query, FromResult, AdapterOptions, QueryLogOptions, NoPrimaryKeyOption, HasAndBelongsToManyRelation, SetQueryTableAlias, defaultsKey, BaseRelation, RelationQuery, SetQueryReturnsOne, SetQueryReturnsOneOptional, SetQueryReturnsAll, DefaultColumnTypes, ColumnsShape, WhereResult, MergeQuery, SetQueryReturns, QueryReturnType } from 'pqb';
3
3
  export { OrchidOrmError, OrchidOrmInternalError, columnTypes } from 'pqb';
4
4
  import * as orchid_core from 'orchid-core';
5
5
  import { StringKey, EmptyObject, ColumnTypesBase, ColumnShapeOutput, SetOptional } from 'orchid-core';
@@ -59,7 +59,10 @@ type HasOneInfo<T extends Table, Relations extends RelationThunks, Relation exte
59
59
 
60
60
  declare function transaction<T extends {
61
61
  $queryBuilder: Db;
62
- }, Result>(this: T, fn: (db: T) => Promise<Result>): Promise<Result>;
62
+ }, Result>(this: T, fn: () => Promise<Result>): Promise<Result>;
63
+ declare function transaction<T extends {
64
+ $queryBuilder: Db;
65
+ }, Result>(this: T, options: IsolationLevel | TransactionOptions, fn: () => Promise<Result>): Promise<Result>;
63
66
 
64
67
  type OrchidORM<T extends TableClasses> = {
65
68
  [K in keyof T]: DbTable<T[K]>;
package/dist/index.js CHANGED
@@ -2,6 +2,7 @@
2
2
 
3
3
  var pqb = require('pqb');
4
4
  var orchidCore = require('orchid-core');
5
+ var node_async_hooks = require('node:async_hooks');
5
6
  var path = require('path');
6
7
  var fs = require('fs/promises');
7
8
  var typescript = require('typescript');
@@ -161,11 +162,11 @@ const makeBelongsToMethod = (relation, relationName, query) => {
161
162
  };
162
163
  };
163
164
  const nestedInsert$3 = ({ query, primaryKey }) => {
164
- return async (q, data) => {
165
+ return async (_, data) => {
165
166
  const connectOrCreate = data.filter(
166
167
  (item) => Boolean(item.connectOrCreate)
167
168
  );
168
- const t = query.transacting(q);
169
+ const t = query.clone();
169
170
  let connectOrCreated;
170
171
  if (connectOrCreate.length) {
171
172
  connectOrCreated = await Promise.all(
@@ -229,12 +230,12 @@ const nestedUpdate$3 = ({ query, primaryKey, foreignKey }) => {
229
230
  if (primaryKey in params.set) {
230
231
  update[foreignKey] = params.set[primaryKey];
231
232
  } else {
232
- update[foreignKey] = await query.transacting(q2)._findBy(params.set)._get(primaryKey);
233
+ update[foreignKey] = await query.findBy(params.set)._get(primaryKey);
233
234
  }
234
235
  } else if (params.create) {
235
- update[foreignKey] = await query.transacting(q2)._get(primaryKey)._create(params.create);
236
+ update[foreignKey] = await query.get(primaryKey)._create(params.create);
236
237
  } else if (params.delete) {
237
- const selectQuery = q2.transacting(q2);
238
+ const selectQuery = q2.clone();
238
239
  selectQuery.query.type = void 0;
239
240
  idForDelete = await selectQuery._getOptional(foreignKey);
240
241
  update[foreignKey] = null;
@@ -256,10 +257,10 @@ const nestedUpdate$3 = ({ query, primaryKey, foreignKey }) => {
256
257
  const data = await handleResult(q2, queryResult);
257
258
  const id = data[0][foreignKey];
258
259
  if (id !== null) {
259
- await query.transacting(q2)._findBy({ [primaryKey]: id })._update(upsert.update);
260
+ await query.findBy({ [primaryKey]: id })._update(upsert.update);
260
261
  } else {
261
262
  state.updateLaterPromises.push(
262
- query.transacting(q2)._select(primaryKey)._create(upsert.create).then((result) => {
263
+ query.select(primaryKey)._create(upsert.create).then((result) => {
263
264
  state.updateLater[foreignKey] = result[primaryKey];
264
265
  })
265
266
  );
@@ -267,12 +268,12 @@ const nestedUpdate$3 = ({ query, primaryKey, foreignKey }) => {
267
268
  return data;
268
269
  };
269
270
  } else if (params.delete || params.update) {
270
- q._afterQuery(async (q2, data) => {
271
+ q._afterQuery(async (_, data) => {
271
272
  const id = params.delete ? idForDelete : Array.isArray(data) ? data.length === 0 ? null : {
272
273
  in: data.map((item) => item[foreignKey]).filter((id2) => id2 !== null)
273
274
  } : data[foreignKey];
274
275
  if (id !== void 0 && id !== null) {
275
- const t = query.transacting(q2)._findBy({
276
+ const t = query.findBy({
276
277
  [primaryKey]: id
277
278
  });
278
279
  if (params.delete) {
@@ -464,11 +465,11 @@ const makeHasOneMethod = (table, relation, relationName, query) => {
464
465
  };
465
466
  };
466
467
  const nestedInsert$2 = ({ query, primaryKey, foreignKey }) => {
467
- return async (q, data) => {
468
+ return async (_, data) => {
468
469
  const connect = data.filter(
469
470
  (item) => Boolean(item[1].connect || item[1].connectOrCreate)
470
471
  );
471
- const t = query.transacting(q);
472
+ const t = query.clone();
472
473
  let connected;
473
474
  if (connect.length) {
474
475
  connected = await Promise.all(
@@ -504,7 +505,7 @@ const nestedUpdate$2 = ({ query, primaryKey, foreignKey }) => {
504
505
  const key = params.set ? "set" : params.create ? "create" : "upsert";
505
506
  throw new Error(`\`${key}\` option is not allowed in a batch update`);
506
507
  }
507
- const t = query.transacting(q);
508
+ const t = query.clone();
508
509
  const ids = data.map((item) => item[primaryKey]);
509
510
  const currentRelationsQuery = t.where({
510
511
  [foreignKey]: { in: ids }
@@ -673,11 +674,11 @@ const getWhereForNestedUpdate = (data, params, primaryKey, foreignKey) => {
673
674
  return where;
674
675
  };
675
676
  const nestedInsert$1 = ({ query, primaryKey, foreignKey }) => {
676
- return async (q, data) => {
677
+ return async (_, data) => {
677
678
  const connect = data.filter(
678
679
  (item) => Boolean(item[1].connect)
679
680
  );
680
- const t = query.transacting(q);
681
+ const t = query.clone();
681
682
  if (connect.length) {
682
683
  await Promise.all(
683
684
  connect.flatMap(
@@ -740,7 +741,7 @@ const nestedUpdate$1 = ({ query, primaryKey, foreignKey }) => {
740
741
  const key = params.set ? "set" : "create";
741
742
  throw new Error(`\`${key}\` option is not allowed in a batch update`);
742
743
  }
743
- const t = query.transacting(q);
744
+ const t = query.clone();
744
745
  if (params.create) {
745
746
  await t._count()._createMany(
746
747
  params.create.map((create) => __spreadProps$4(__spreadValues$6({}, create), {
@@ -914,10 +915,10 @@ const makeHasAndBelongsToManyMethod = (table, qb, relation, relationName, query)
914
915
  pqb.pushQueryValue(
915
916
  relationQuery,
916
917
  "afterCreate",
917
- async (q, result) => {
918
+ async (_, result) => {
918
919
  const fromQuery = ref.query.clone();
919
920
  fromQuery.query.select = [{ selectAs: { [fk]: pk } }];
920
- const createdCount = await subQuery.transacting(q).count()._createFrom(
921
+ const createdCount = await subQuery.count()._createFrom(
921
922
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
922
923
  fromQuery,
923
924
  {
@@ -935,8 +936,8 @@ const makeHasAndBelongsToManyMethod = (table, qb, relation, relationName, query)
935
936
  }
936
937
  };
937
938
  };
938
- const queryJoinTable = (state, q, data, conditions) => {
939
- const t = state.joinTableQuery.transacting(q);
939
+ const queryJoinTable = (state, data, conditions) => {
940
+ const t = state.joinTableQuery.clone();
940
941
  const where = {
941
942
  [state.foreignKey]: { in: data.map((item) => item[state.primaryKey]) }
942
943
  };
@@ -949,8 +950,10 @@ const queryJoinTable = (state, q, data, conditions) => {
949
950
  }
950
951
  return t._where(where);
951
952
  };
952
- const queryRelatedTable = (query, q, conditions) => {
953
- return query.transacting(q)._where(Array.isArray(conditions) ? { OR: conditions } : conditions);
953
+ const queryRelatedTable = (query, conditions) => {
954
+ return query.where(
955
+ Array.isArray(conditions) ? { OR: conditions } : conditions
956
+ );
954
957
  };
955
958
  const insertToJoinTable = (state, joinTableTransaction, data, ids) => {
956
959
  return joinTableTransaction._count()._createMany(
@@ -970,11 +973,11 @@ const nestedInsert = ({
970
973
  associationPrimaryKey,
971
974
  associationForeignKey
972
975
  }) => {
973
- return async (q, data) => {
976
+ return async (_, data) => {
974
977
  const connect = data.filter(
975
978
  (item) => Boolean(item[1].connect)
976
979
  );
977
- const t = relatedTableQuery.transacting(q);
980
+ const t = relatedTableQuery.clone();
978
981
  let connected;
979
982
  if (connect.length) {
980
983
  connected = await Promise.all(
@@ -1059,7 +1062,7 @@ const nestedInsert = ({
1059
1062
  connectI += len;
1060
1063
  }
1061
1064
  });
1062
- await joinTableQuery.transacting(q)._count()._createMany(
1065
+ await joinTableQuery.count()._createMany(
1063
1066
  allKeys.flatMap(([selfData, relationKeys]) => {
1064
1067
  const selfKey = selfData[primaryKey];
1065
1068
  return relationKeys.map((relationData) => ({
@@ -1071,10 +1074,10 @@ const nestedInsert = ({
1071
1074
  };
1072
1075
  };
1073
1076
  const nestedUpdate = (state) => {
1074
- return async (q, data, params) => {
1077
+ return async (_, data, params) => {
1075
1078
  if (params.create) {
1076
- const ids = await state.relatedTableQuery.transacting(q)._pluck(state.associationPrimaryKey)._createMany(params.create);
1077
- await state.joinTableQuery.transacting(q)._createMany(
1079
+ const ids = await state.relatedTableQuery.pluck(state.associationPrimaryKey)._createMany(params.create);
1080
+ await state.joinTableQuery.createMany(
1078
1081
  data.flatMap(
1079
1082
  (item) => ids.map((id) => ({
1080
1083
  [state.foreignKey]: item[state.primaryKey],
@@ -1084,11 +1087,11 @@ const nestedUpdate = (state) => {
1084
1087
  );
1085
1088
  }
1086
1089
  if (params.update) {
1087
- await state.relatedTableQuery.transacting(q)._whereExists(
1090
+ await state.relatedTableQuery.whereExists(
1088
1091
  state.joinTableQuery,
1089
- (q2) => (
1092
+ (q) => (
1090
1093
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
1091
- q2._on(
1094
+ q._on(
1092
1095
  state.associationForeignKeyFull,
1093
1096
  state.associationPrimaryKeyFull
1094
1097
  )._where({
@@ -1103,22 +1106,21 @@ const nestedUpdate = (state) => {
1103
1106
  )._update(params.update.data);
1104
1107
  }
1105
1108
  if (params.disconnect) {
1106
- await queryJoinTable(state, q, data, params.disconnect)._delete();
1109
+ await queryJoinTable(state, data, params.disconnect)._delete();
1107
1110
  }
1108
1111
  if (params.delete) {
1109
- const j = queryJoinTable(state, q, data, params.delete);
1112
+ const j = queryJoinTable(state, data, params.delete);
1110
1113
  const ids = await j._pluck(state.associationForeignKey)._delete();
1111
- await queryRelatedTable(state.relatedTableQuery, q, {
1114
+ await queryRelatedTable(state.relatedTableQuery, {
1112
1115
  [state.associationPrimaryKey]: { in: ids }
1113
1116
  })._delete();
1114
1117
  }
1115
1118
  if (params.set) {
1116
- const j = queryJoinTable(state, q, data);
1119
+ const j = queryJoinTable(state, data);
1117
1120
  await j._delete();
1118
1121
  delete j.query[pqb.toSqlCacheKey];
1119
1122
  const ids = await queryRelatedTable(
1120
1123
  state.relatedTableQuery,
1121
- q,
1122
1124
  params.set
1123
1125
  )._pluck(state.associationPrimaryKey);
1124
1126
  await insertToJoinTable(state, j, data, ids);
@@ -1293,25 +1295,11 @@ const makeRelationQuery = (table, definedAs, relationName, data) => {
1293
1295
  });
1294
1296
  };
1295
1297
 
1296
- function transaction(fn) {
1297
- if (fn.length === 0) {
1298
- throw new Error("Argument of $transaction callback should be used");
1299
- }
1300
- return this.$queryBuilder.transaction((q) => {
1301
- const orm = {};
1302
- for (const key in this) {
1303
- const value = this[key];
1304
- if (value instanceof pqb.Db) {
1305
- const table = value.transacting(q);
1306
- table.baseQuery = table;
1307
- table.db = orm;
1308
- orm[key] = table;
1309
- } else {
1310
- orm[key] = value;
1311
- }
1312
- }
1313
- return fn(orm);
1314
- });
1298
+ function transaction(fnOrOptions, fn) {
1299
+ return this.$queryBuilder.transaction(
1300
+ fnOrOptions,
1301
+ fn
1302
+ );
1315
1303
  }
1316
1304
 
1317
1305
  var __defProp$4 = Object.defineProperty;
@@ -1364,12 +1352,14 @@ const orchidORM = (_a, tables) => {
1364
1352
  autoPreparedStatements,
1365
1353
  noPrimaryKey
1366
1354
  };
1355
+ const transactionStorage = new node_async_hooks.AsyncLocalStorage();
1367
1356
  const qb = new pqb.Db(
1368
1357
  adapter,
1369
1358
  void 0,
1370
1359
  void 0,
1371
1360
  pqb.anyShape,
1372
1361
  pqb.columnTypes,
1362
+ transactionStorage,
1373
1363
  commonOptions
1374
1364
  );
1375
1365
  qb.queryBuilder = qb;
@@ -1399,6 +1389,7 @@ const orchidORM = (_a, tables) => {
1399
1389
  table.table,
1400
1390
  table.columns.shape,
1401
1391
  table.columnTypes,
1392
+ transactionStorage,
1402
1393
  options2
1403
1394
  );
1404
1395
  dbTable.definedAs = key;