orchid-orm 1.6.39 → 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.mjs CHANGED
@@ -1,6 +1,7 @@
1
- import { columnTypes, getColumnTypes, addQueryOn, VirtualColumn, pushQueryValue, isQueryReturnsAll, getQueryAs, toSqlCacheKey, NotFoundError, relationQueryKey, Db, Adapter, anyShape, getClonedQueryData, columnsShapeToCode, primaryKeyToCode, indexToCode, constraintToCode, columnIndexesToCode, columnForeignKeysToCode, columnCheckToCode, identityToCode } from 'pqb';
1
+ import { columnTypes, getColumnTypes, addQueryOn, VirtualColumn, pushQueryValue, isQueryReturnsAll, getQueryAs, toSqlCacheKey, NotFoundError, relationQueryKey, Adapter, Db, anyShape, getClonedQueryData, columnsShapeToCode, primaryKeyToCode, indexToCode, constraintToCode, columnIndexesToCode, columnForeignKeysToCode, columnCheckToCode, identityToCode } from 'pqb';
2
2
  export { OrchidOrmError, OrchidOrmInternalError, columnTypes } from 'pqb';
3
3
  import { snakeCaseKey, toSnakeCase, emptyObject, pathToLog, toCamelCase, toPascalCase, singleQuote, codeToString, quoteObjectKey, addCode, columnDefaultArgumentToCode, deepCompare } from 'orchid-core';
4
+ import { AsyncLocalStorage } from 'node:async_hooks';
4
5
  import * as path from 'path';
5
6
  import path__default from 'path';
6
7
  import fs from 'fs/promises';
@@ -142,11 +143,11 @@ const makeBelongsToMethod = (relation, relationName, query) => {
142
143
  };
143
144
  };
144
145
  const nestedInsert$3 = ({ query, primaryKey }) => {
145
- return async (q, data) => {
146
+ return async (_, data) => {
146
147
  const connectOrCreate = data.filter(
147
148
  (item) => Boolean(item.connectOrCreate)
148
149
  );
149
- const t = query.transacting(q);
150
+ const t = query.clone();
150
151
  let connectOrCreated;
151
152
  if (connectOrCreate.length) {
152
153
  connectOrCreated = await Promise.all(
@@ -210,12 +211,12 @@ const nestedUpdate$3 = ({ query, primaryKey, foreignKey }) => {
210
211
  if (primaryKey in params.set) {
211
212
  update[foreignKey] = params.set[primaryKey];
212
213
  } else {
213
- update[foreignKey] = await query.transacting(q2)._findBy(params.set)._get(primaryKey);
214
+ update[foreignKey] = await query.findBy(params.set)._get(primaryKey);
214
215
  }
215
216
  } else if (params.create) {
216
- update[foreignKey] = await query.transacting(q2)._get(primaryKey)._create(params.create);
217
+ update[foreignKey] = await query.get(primaryKey)._create(params.create);
217
218
  } else if (params.delete) {
218
- const selectQuery = q2.transacting(q2);
219
+ const selectQuery = q2.clone();
219
220
  selectQuery.query.type = void 0;
220
221
  idForDelete = await selectQuery._getOptional(foreignKey);
221
222
  update[foreignKey] = null;
@@ -237,10 +238,10 @@ const nestedUpdate$3 = ({ query, primaryKey, foreignKey }) => {
237
238
  const data = await handleResult(q2, queryResult);
238
239
  const id = data[0][foreignKey];
239
240
  if (id !== null) {
240
- await query.transacting(q2)._findBy({ [primaryKey]: id })._update(upsert.update);
241
+ await query.findBy({ [primaryKey]: id })._update(upsert.update);
241
242
  } else {
242
243
  state.updateLaterPromises.push(
243
- query.transacting(q2)._select(primaryKey)._create(upsert.create).then((result) => {
244
+ query.select(primaryKey)._create(upsert.create).then((result) => {
244
245
  state.updateLater[foreignKey] = result[primaryKey];
245
246
  })
246
247
  );
@@ -248,12 +249,12 @@ const nestedUpdate$3 = ({ query, primaryKey, foreignKey }) => {
248
249
  return data;
249
250
  };
250
251
  } else if (params.delete || params.update) {
251
- q._afterQuery(async (q2, data) => {
252
+ q._afterQuery(async (_, data) => {
252
253
  const id = params.delete ? idForDelete : Array.isArray(data) ? data.length === 0 ? null : {
253
254
  in: data.map((item) => item[foreignKey]).filter((id2) => id2 !== null)
254
255
  } : data[foreignKey];
255
256
  if (id !== void 0 && id !== null) {
256
- const t = query.transacting(q2)._findBy({
257
+ const t = query.findBy({
257
258
  [primaryKey]: id
258
259
  });
259
260
  if (params.delete) {
@@ -445,11 +446,11 @@ const makeHasOneMethod = (table, relation, relationName, query) => {
445
446
  };
446
447
  };
447
448
  const nestedInsert$2 = ({ query, primaryKey, foreignKey }) => {
448
- return async (q, data) => {
449
+ return async (_, data) => {
449
450
  const connect = data.filter(
450
451
  (item) => Boolean(item[1].connect || item[1].connectOrCreate)
451
452
  );
452
- const t = query.transacting(q);
453
+ const t = query.clone();
453
454
  let connected;
454
455
  if (connect.length) {
455
456
  connected = await Promise.all(
@@ -485,7 +486,7 @@ const nestedUpdate$2 = ({ query, primaryKey, foreignKey }) => {
485
486
  const key = params.set ? "set" : params.create ? "create" : "upsert";
486
487
  throw new Error(`\`${key}\` option is not allowed in a batch update`);
487
488
  }
488
- const t = query.transacting(q);
489
+ const t = query.clone();
489
490
  const ids = data.map((item) => item[primaryKey]);
490
491
  const currentRelationsQuery = t.where({
491
492
  [foreignKey]: { in: ids }
@@ -654,11 +655,11 @@ const getWhereForNestedUpdate = (data, params, primaryKey, foreignKey) => {
654
655
  return where;
655
656
  };
656
657
  const nestedInsert$1 = ({ query, primaryKey, foreignKey }) => {
657
- return async (q, data) => {
658
+ return async (_, data) => {
658
659
  const connect = data.filter(
659
660
  (item) => Boolean(item[1].connect)
660
661
  );
661
- const t = query.transacting(q);
662
+ const t = query.clone();
662
663
  if (connect.length) {
663
664
  await Promise.all(
664
665
  connect.flatMap(
@@ -721,7 +722,7 @@ const nestedUpdate$1 = ({ query, primaryKey, foreignKey }) => {
721
722
  const key = params.set ? "set" : "create";
722
723
  throw new Error(`\`${key}\` option is not allowed in a batch update`);
723
724
  }
724
- const t = query.transacting(q);
725
+ const t = query.clone();
725
726
  if (params.create) {
726
727
  await t._count()._createMany(
727
728
  params.create.map((create) => __spreadProps$4(__spreadValues$6({}, create), {
@@ -871,6 +872,8 @@ const makeHasAndBelongsToManyMethod = (table, qb, relation, relationName, query)
871
872
  relationName,
872
873
  state
873
874
  ),
875
+ // joinQuery can be a property of RelationQuery and be used by whereExists and other stuff which needs it
876
+ // and the chained query itself may be a query around this joinQuery
874
877
  joinQuery(fromQuery, toQuery) {
875
878
  const join = toQuery.whereExists(
876
879
  subQuery,
@@ -893,10 +896,11 @@ const makeHasAndBelongsToManyMethod = (table, qb, relation, relationName, query)
893
896
  pushQueryValue(
894
897
  relationQuery,
895
898
  "afterCreate",
896
- async (q, result) => {
899
+ async (_, result) => {
897
900
  const fromQuery = ref.query.clone();
898
901
  fromQuery.query.select = [{ selectAs: { [fk]: pk } }];
899
- const createdCount = await subQuery.transacting(q).count()._createFrom(
902
+ const createdCount = await subQuery.count()._createFrom(
903
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
900
904
  fromQuery,
901
905
  {
902
906
  [afk]: result[apk]
@@ -913,8 +917,8 @@ const makeHasAndBelongsToManyMethod = (table, qb, relation, relationName, query)
913
917
  }
914
918
  };
915
919
  };
916
- const queryJoinTable = (state, q, data, conditions) => {
917
- const t = state.joinTableQuery.transacting(q);
920
+ const queryJoinTable = (state, data, conditions) => {
921
+ const t = state.joinTableQuery.clone();
918
922
  const where = {
919
923
  [state.foreignKey]: { in: data.map((item) => item[state.primaryKey]) }
920
924
  };
@@ -927,8 +931,10 @@ const queryJoinTable = (state, q, data, conditions) => {
927
931
  }
928
932
  return t._where(where);
929
933
  };
930
- const queryRelatedTable = (query, q, conditions) => {
931
- return query.transacting(q)._where(Array.isArray(conditions) ? { OR: conditions } : conditions);
934
+ const queryRelatedTable = (query, conditions) => {
935
+ return query.where(
936
+ Array.isArray(conditions) ? { OR: conditions } : conditions
937
+ );
932
938
  };
933
939
  const insertToJoinTable = (state, joinTableTransaction, data, ids) => {
934
940
  return joinTableTransaction._count()._createMany(
@@ -948,11 +954,11 @@ const nestedInsert = ({
948
954
  associationPrimaryKey,
949
955
  associationForeignKey
950
956
  }) => {
951
- return async (q, data) => {
957
+ return async (_, data) => {
952
958
  const connect = data.filter(
953
959
  (item) => Boolean(item[1].connect)
954
960
  );
955
- const t = relatedTableQuery.transacting(q);
961
+ const t = relatedTableQuery.clone();
956
962
  let connected;
957
963
  if (connect.length) {
958
964
  connected = await Promise.all(
@@ -1037,7 +1043,7 @@ const nestedInsert = ({
1037
1043
  connectI += len;
1038
1044
  }
1039
1045
  });
1040
- await joinTableQuery.transacting(q)._count()._createMany(
1046
+ await joinTableQuery.count()._createMany(
1041
1047
  allKeys.flatMap(([selfData, relationKeys]) => {
1042
1048
  const selfKey = selfData[primaryKey];
1043
1049
  return relationKeys.map((relationData) => ({
@@ -1049,10 +1055,10 @@ const nestedInsert = ({
1049
1055
  };
1050
1056
  };
1051
1057
  const nestedUpdate = (state) => {
1052
- return async (q, data, params) => {
1058
+ return async (_, data, params) => {
1053
1059
  if (params.create) {
1054
- const ids = await state.relatedTableQuery.transacting(q)._pluck(state.associationPrimaryKey)._createMany(params.create);
1055
- await state.joinTableQuery.transacting(q)._createMany(
1060
+ const ids = await state.relatedTableQuery.pluck(state.associationPrimaryKey)._createMany(params.create);
1061
+ await state.joinTableQuery.createMany(
1056
1062
  data.flatMap(
1057
1063
  (item) => ids.map((id) => ({
1058
1064
  [state.foreignKey]: item[state.primaryKey],
@@ -1062,38 +1068,40 @@ const nestedUpdate = (state) => {
1062
1068
  );
1063
1069
  }
1064
1070
  if (params.update) {
1065
- await state.relatedTableQuery.transacting(q)._whereExists(
1071
+ await state.relatedTableQuery.whereExists(
1066
1072
  state.joinTableQuery,
1067
- (q2) => q2._on(
1068
- state.associationForeignKeyFull,
1069
- state.associationPrimaryKeyFull
1070
- )._where({
1071
- IN: {
1072
- columns: [state.foreignKeyFull],
1073
- values: [data.map((item) => item[state.primaryKey])]
1074
- }
1075
- })
1073
+ (q) => (
1074
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1075
+ q._on(
1076
+ state.associationForeignKeyFull,
1077
+ state.associationPrimaryKeyFull
1078
+ )._where({
1079
+ IN: {
1080
+ columns: [state.foreignKeyFull],
1081
+ values: [data.map((item) => item[state.primaryKey])]
1082
+ }
1083
+ })
1084
+ )
1076
1085
  )._where(
1077
1086
  Array.isArray(params.update.where) ? { OR: params.update.where } : params.update.where
1078
1087
  )._update(params.update.data);
1079
1088
  }
1080
1089
  if (params.disconnect) {
1081
- await queryJoinTable(state, q, data, params.disconnect)._delete();
1090
+ await queryJoinTable(state, data, params.disconnect)._delete();
1082
1091
  }
1083
1092
  if (params.delete) {
1084
- const j = queryJoinTable(state, q, data, params.delete);
1093
+ const j = queryJoinTable(state, data, params.delete);
1085
1094
  const ids = await j._pluck(state.associationForeignKey)._delete();
1086
- await queryRelatedTable(state.relatedTableQuery, q, {
1095
+ await queryRelatedTable(state.relatedTableQuery, {
1087
1096
  [state.associationPrimaryKey]: { in: ids }
1088
1097
  })._delete();
1089
1098
  }
1090
1099
  if (params.set) {
1091
- const j = queryJoinTable(state, q, data);
1100
+ const j = queryJoinTable(state, data);
1092
1101
  await j._delete();
1093
1102
  delete j.query[toSqlCacheKey];
1094
1103
  const ids = await queryRelatedTable(
1095
1104
  state.relatedTableQuery,
1096
- q,
1097
1105
  params.set
1098
1106
  )._pluck(state.associationPrimaryKey);
1099
1107
  await insertToJoinTable(state, j, data, ids);
@@ -1268,25 +1276,11 @@ const makeRelationQuery = (table, definedAs, relationName, data) => {
1268
1276
  });
1269
1277
  };
1270
1278
 
1271
- function transaction(fn) {
1272
- if (fn.length === 0) {
1273
- throw new Error("Argument of $transaction callback should be used");
1274
- }
1275
- return this.$queryBuilder.transaction((q) => {
1276
- const orm = {};
1277
- for (const key in this) {
1278
- const value = this[key];
1279
- if (value instanceof Db) {
1280
- const table = value.transacting(q);
1281
- table.baseQuery = table;
1282
- table.db = orm;
1283
- orm[key] = table;
1284
- } else {
1285
- orm[key] = value;
1286
- }
1287
- }
1288
- return fn(orm);
1289
- });
1279
+ function transaction(fnOrOptions, fn) {
1280
+ return this.$queryBuilder.transaction(
1281
+ fnOrOptions,
1282
+ fn
1283
+ );
1290
1284
  }
1291
1285
 
1292
1286
  var __defProp$4 = Object.defineProperty;
@@ -1339,12 +1333,14 @@ const orchidORM = (_a, tables) => {
1339
1333
  autoPreparedStatements,
1340
1334
  noPrimaryKey
1341
1335
  };
1336
+ const transactionStorage = new AsyncLocalStorage();
1342
1337
  const qb = new Db(
1343
1338
  adapter,
1344
1339
  void 0,
1345
1340
  void 0,
1346
1341
  anyShape,
1347
1342
  columnTypes,
1343
+ transactionStorage,
1348
1344
  commonOptions
1349
1345
  );
1350
1346
  qb.queryBuilder = qb;
@@ -1369,10 +1365,12 @@ const orchidORM = (_a, tables) => {
1369
1365
  options2.noPrimaryKey = "ignore";
1370
1366
  const dbTable = new Db(
1371
1367
  adapter,
1368
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1372
1369
  qb,
1373
1370
  table.table,
1374
1371
  table.columns.shape,
1375
1372
  table.columnTypes,
1373
+ transactionStorage,
1376
1374
  options2
1377
1375
  );
1378
1376
  dbTable.definedAs = key;
@@ -2124,7 +2122,9 @@ const getColumnMethodArgs = (t, to, key, dataType) => {
2124
2122
  if (!value)
2125
2123
  return;
2126
2124
  if (key === "indexes") {
2127
- return columnIndexesToCode(value);
2125
+ return columnIndexesToCode(
2126
+ value
2127
+ );
2128
2128
  }
2129
2129
  if (key === "foreignKeys") {
2130
2130
  return columnForeignKeysToCode(value);