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.js CHANGED
@@ -1,17 +1,13 @@
1
1
  'use strict';
2
2
 
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
3
  var pqb = require('pqb');
6
4
  var orchidCore = require('orchid-core');
5
+ var node_async_hooks = require('node:async_hooks');
7
6
  var path = require('path');
8
7
  var fs = require('fs/promises');
9
8
  var typescript = require('typescript');
10
9
 
11
- function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
12
-
13
- function _interopNamespace(e) {
14
- if (e && e.__esModule) return e;
10
+ function _interopNamespaceDefault(e) {
15
11
  var n = Object.create(null);
16
12
  if (e) {
17
13
  Object.keys(e).forEach(function (k) {
@@ -24,14 +20,11 @@ function _interopNamespace(e) {
24
20
  }
25
21
  });
26
22
  }
27
- n["default"] = e;
23
+ n.default = e;
28
24
  return Object.freeze(n);
29
25
  }
30
26
 
31
- var path__default = /*#__PURE__*/_interopDefaultLegacy(path);
32
- var path__namespace = /*#__PURE__*/_interopNamespace(path);
33
- var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);
34
- var typescript__default = /*#__PURE__*/_interopDefaultLegacy(typescript);
27
+ var path__namespace = /*#__PURE__*/_interopNamespaceDefault(path);
35
28
 
36
29
  const createBaseTable = ({
37
30
  columnTypes,
@@ -169,11 +162,11 @@ const makeBelongsToMethod = (relation, relationName, query) => {
169
162
  };
170
163
  };
171
164
  const nestedInsert$3 = ({ query, primaryKey }) => {
172
- return async (q, data) => {
165
+ return async (_, data) => {
173
166
  const connectOrCreate = data.filter(
174
167
  (item) => Boolean(item.connectOrCreate)
175
168
  );
176
- const t = query.transacting(q);
169
+ const t = query.clone();
177
170
  let connectOrCreated;
178
171
  if (connectOrCreate.length) {
179
172
  connectOrCreated = await Promise.all(
@@ -237,12 +230,12 @@ const nestedUpdate$3 = ({ query, primaryKey, foreignKey }) => {
237
230
  if (primaryKey in params.set) {
238
231
  update[foreignKey] = params.set[primaryKey];
239
232
  } else {
240
- update[foreignKey] = await query.transacting(q2)._findBy(params.set)._get(primaryKey);
233
+ update[foreignKey] = await query.findBy(params.set)._get(primaryKey);
241
234
  }
242
235
  } else if (params.create) {
243
- update[foreignKey] = await query.transacting(q2)._get(primaryKey)._create(params.create);
236
+ update[foreignKey] = await query.get(primaryKey)._create(params.create);
244
237
  } else if (params.delete) {
245
- const selectQuery = q2.transacting(q2);
238
+ const selectQuery = q2.clone();
246
239
  selectQuery.query.type = void 0;
247
240
  idForDelete = await selectQuery._getOptional(foreignKey);
248
241
  update[foreignKey] = null;
@@ -264,10 +257,10 @@ const nestedUpdate$3 = ({ query, primaryKey, foreignKey }) => {
264
257
  const data = await handleResult(q2, queryResult);
265
258
  const id = data[0][foreignKey];
266
259
  if (id !== null) {
267
- await query.transacting(q2)._findBy({ [primaryKey]: id })._update(upsert.update);
260
+ await query.findBy({ [primaryKey]: id })._update(upsert.update);
268
261
  } else {
269
262
  state.updateLaterPromises.push(
270
- query.transacting(q2)._select(primaryKey)._create(upsert.create).then((result) => {
263
+ query.select(primaryKey)._create(upsert.create).then((result) => {
271
264
  state.updateLater[foreignKey] = result[primaryKey];
272
265
  })
273
266
  );
@@ -275,12 +268,12 @@ const nestedUpdate$3 = ({ query, primaryKey, foreignKey }) => {
275
268
  return data;
276
269
  };
277
270
  } else if (params.delete || params.update) {
278
- q._afterQuery(async (q2, data) => {
271
+ q._afterQuery(async (_, data) => {
279
272
  const id = params.delete ? idForDelete : Array.isArray(data) ? data.length === 0 ? null : {
280
273
  in: data.map((item) => item[foreignKey]).filter((id2) => id2 !== null)
281
274
  } : data[foreignKey];
282
275
  if (id !== void 0 && id !== null) {
283
- const t = query.transacting(q2)._findBy({
276
+ const t = query.findBy({
284
277
  [primaryKey]: id
285
278
  });
286
279
  if (params.delete) {
@@ -472,11 +465,11 @@ const makeHasOneMethod = (table, relation, relationName, query) => {
472
465
  };
473
466
  };
474
467
  const nestedInsert$2 = ({ query, primaryKey, foreignKey }) => {
475
- return async (q, data) => {
468
+ return async (_, data) => {
476
469
  const connect = data.filter(
477
470
  (item) => Boolean(item[1].connect || item[1].connectOrCreate)
478
471
  );
479
- const t = query.transacting(q);
472
+ const t = query.clone();
480
473
  let connected;
481
474
  if (connect.length) {
482
475
  connected = await Promise.all(
@@ -512,7 +505,7 @@ const nestedUpdate$2 = ({ query, primaryKey, foreignKey }) => {
512
505
  const key = params.set ? "set" : params.create ? "create" : "upsert";
513
506
  throw new Error(`\`${key}\` option is not allowed in a batch update`);
514
507
  }
515
- const t = query.transacting(q);
508
+ const t = query.clone();
516
509
  const ids = data.map((item) => item[primaryKey]);
517
510
  const currentRelationsQuery = t.where({
518
511
  [foreignKey]: { in: ids }
@@ -681,11 +674,11 @@ const getWhereForNestedUpdate = (data, params, primaryKey, foreignKey) => {
681
674
  return where;
682
675
  };
683
676
  const nestedInsert$1 = ({ query, primaryKey, foreignKey }) => {
684
- return async (q, data) => {
677
+ return async (_, data) => {
685
678
  const connect = data.filter(
686
679
  (item) => Boolean(item[1].connect)
687
680
  );
688
- const t = query.transacting(q);
681
+ const t = query.clone();
689
682
  if (connect.length) {
690
683
  await Promise.all(
691
684
  connect.flatMap(
@@ -748,7 +741,7 @@ const nestedUpdate$1 = ({ query, primaryKey, foreignKey }) => {
748
741
  const key = params.set ? "set" : "create";
749
742
  throw new Error(`\`${key}\` option is not allowed in a batch update`);
750
743
  }
751
- const t = query.transacting(q);
744
+ const t = query.clone();
752
745
  if (params.create) {
753
746
  await t._count()._createMany(
754
747
  params.create.map((create) => __spreadProps$4(__spreadValues$6({}, create), {
@@ -898,6 +891,8 @@ const makeHasAndBelongsToManyMethod = (table, qb, relation, relationName, query)
898
891
  relationName,
899
892
  state
900
893
  ),
894
+ // joinQuery can be a property of RelationQuery and be used by whereExists and other stuff which needs it
895
+ // and the chained query itself may be a query around this joinQuery
901
896
  joinQuery(fromQuery, toQuery) {
902
897
  const join = toQuery.whereExists(
903
898
  subQuery,
@@ -920,10 +915,11 @@ const makeHasAndBelongsToManyMethod = (table, qb, relation, relationName, query)
920
915
  pqb.pushQueryValue(
921
916
  relationQuery,
922
917
  "afterCreate",
923
- async (q, result) => {
918
+ async (_, result) => {
924
919
  const fromQuery = ref.query.clone();
925
920
  fromQuery.query.select = [{ selectAs: { [fk]: pk } }];
926
- const createdCount = await subQuery.transacting(q).count()._createFrom(
921
+ const createdCount = await subQuery.count()._createFrom(
922
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
927
923
  fromQuery,
928
924
  {
929
925
  [afk]: result[apk]
@@ -940,8 +936,8 @@ const makeHasAndBelongsToManyMethod = (table, qb, relation, relationName, query)
940
936
  }
941
937
  };
942
938
  };
943
- const queryJoinTable = (state, q, data, conditions) => {
944
- const t = state.joinTableQuery.transacting(q);
939
+ const queryJoinTable = (state, data, conditions) => {
940
+ const t = state.joinTableQuery.clone();
945
941
  const where = {
946
942
  [state.foreignKey]: { in: data.map((item) => item[state.primaryKey]) }
947
943
  };
@@ -954,8 +950,10 @@ const queryJoinTable = (state, q, data, conditions) => {
954
950
  }
955
951
  return t._where(where);
956
952
  };
957
- const queryRelatedTable = (query, q, conditions) => {
958
- 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
+ );
959
957
  };
960
958
  const insertToJoinTable = (state, joinTableTransaction, data, ids) => {
961
959
  return joinTableTransaction._count()._createMany(
@@ -975,11 +973,11 @@ const nestedInsert = ({
975
973
  associationPrimaryKey,
976
974
  associationForeignKey
977
975
  }) => {
978
- return async (q, data) => {
976
+ return async (_, data) => {
979
977
  const connect = data.filter(
980
978
  (item) => Boolean(item[1].connect)
981
979
  );
982
- const t = relatedTableQuery.transacting(q);
980
+ const t = relatedTableQuery.clone();
983
981
  let connected;
984
982
  if (connect.length) {
985
983
  connected = await Promise.all(
@@ -1064,7 +1062,7 @@ const nestedInsert = ({
1064
1062
  connectI += len;
1065
1063
  }
1066
1064
  });
1067
- await joinTableQuery.transacting(q)._count()._createMany(
1065
+ await joinTableQuery.count()._createMany(
1068
1066
  allKeys.flatMap(([selfData, relationKeys]) => {
1069
1067
  const selfKey = selfData[primaryKey];
1070
1068
  return relationKeys.map((relationData) => ({
@@ -1076,10 +1074,10 @@ const nestedInsert = ({
1076
1074
  };
1077
1075
  };
1078
1076
  const nestedUpdate = (state) => {
1079
- return async (q, data, params) => {
1077
+ return async (_, data, params) => {
1080
1078
  if (params.create) {
1081
- const ids = await state.relatedTableQuery.transacting(q)._pluck(state.associationPrimaryKey)._createMany(params.create);
1082
- await state.joinTableQuery.transacting(q)._createMany(
1079
+ const ids = await state.relatedTableQuery.pluck(state.associationPrimaryKey)._createMany(params.create);
1080
+ await state.joinTableQuery.createMany(
1083
1081
  data.flatMap(
1084
1082
  (item) => ids.map((id) => ({
1085
1083
  [state.foreignKey]: item[state.primaryKey],
@@ -1089,38 +1087,40 @@ const nestedUpdate = (state) => {
1089
1087
  );
1090
1088
  }
1091
1089
  if (params.update) {
1092
- await state.relatedTableQuery.transacting(q)._whereExists(
1090
+ await state.relatedTableQuery.whereExists(
1093
1091
  state.joinTableQuery,
1094
- (q2) => q2._on(
1095
- state.associationForeignKeyFull,
1096
- state.associationPrimaryKeyFull
1097
- )._where({
1098
- IN: {
1099
- columns: [state.foreignKeyFull],
1100
- values: [data.map((item) => item[state.primaryKey])]
1101
- }
1102
- })
1092
+ (q) => (
1093
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1094
+ q._on(
1095
+ state.associationForeignKeyFull,
1096
+ state.associationPrimaryKeyFull
1097
+ )._where({
1098
+ IN: {
1099
+ columns: [state.foreignKeyFull],
1100
+ values: [data.map((item) => item[state.primaryKey])]
1101
+ }
1102
+ })
1103
+ )
1103
1104
  )._where(
1104
1105
  Array.isArray(params.update.where) ? { OR: params.update.where } : params.update.where
1105
1106
  )._update(params.update.data);
1106
1107
  }
1107
1108
  if (params.disconnect) {
1108
- await queryJoinTable(state, q, data, params.disconnect)._delete();
1109
+ await queryJoinTable(state, data, params.disconnect)._delete();
1109
1110
  }
1110
1111
  if (params.delete) {
1111
- const j = queryJoinTable(state, q, data, params.delete);
1112
+ const j = queryJoinTable(state, data, params.delete);
1112
1113
  const ids = await j._pluck(state.associationForeignKey)._delete();
1113
- await queryRelatedTable(state.relatedTableQuery, q, {
1114
+ await queryRelatedTable(state.relatedTableQuery, {
1114
1115
  [state.associationPrimaryKey]: { in: ids }
1115
1116
  })._delete();
1116
1117
  }
1117
1118
  if (params.set) {
1118
- const j = queryJoinTable(state, q, data);
1119
+ const j = queryJoinTable(state, data);
1119
1120
  await j._delete();
1120
1121
  delete j.query[pqb.toSqlCacheKey];
1121
1122
  const ids = await queryRelatedTable(
1122
1123
  state.relatedTableQuery,
1123
- q,
1124
1124
  params.set
1125
1125
  )._pluck(state.associationPrimaryKey);
1126
1126
  await insertToJoinTable(state, j, data, ids);
@@ -1295,25 +1295,11 @@ const makeRelationQuery = (table, definedAs, relationName, data) => {
1295
1295
  });
1296
1296
  };
1297
1297
 
1298
- function transaction(fn) {
1299
- if (fn.length === 0) {
1300
- throw new Error("Argument of $transaction callback should be used");
1301
- }
1302
- return this.$queryBuilder.transaction((q) => {
1303
- const orm = {};
1304
- for (const key in this) {
1305
- const value = this[key];
1306
- if (value instanceof pqb.Db) {
1307
- const table = value.transacting(q);
1308
- table.baseQuery = table;
1309
- table.db = orm;
1310
- orm[key] = table;
1311
- } else {
1312
- orm[key] = value;
1313
- }
1314
- }
1315
- return fn(orm);
1316
- });
1298
+ function transaction(fnOrOptions, fn) {
1299
+ return this.$queryBuilder.transaction(
1300
+ fnOrOptions,
1301
+ fn
1302
+ );
1317
1303
  }
1318
1304
 
1319
1305
  var __defProp$4 = Object.defineProperty;
@@ -1366,12 +1352,14 @@ const orchidORM = (_a, tables) => {
1366
1352
  autoPreparedStatements,
1367
1353
  noPrimaryKey
1368
1354
  };
1355
+ const transactionStorage = new node_async_hooks.AsyncLocalStorage();
1369
1356
  const qb = new pqb.Db(
1370
1357
  adapter,
1371
1358
  void 0,
1372
1359
  void 0,
1373
1360
  pqb.anyShape,
1374
1361
  pqb.columnTypes,
1362
+ transactionStorage,
1375
1363
  commonOptions
1376
1364
  );
1377
1365
  qb.queryBuilder = qb;
@@ -1396,10 +1384,12 @@ const orchidORM = (_a, tables) => {
1396
1384
  options2.noPrimaryKey = "ignore";
1397
1385
  const dbTable = new pqb.Db(
1398
1386
  adapter,
1387
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1399
1388
  qb,
1400
1389
  table.table,
1401
1390
  table.columns.shape,
1402
1391
  table.columnTypes,
1392
+ transactionStorage,
1403
1393
  options2
1404
1394
  );
1405
1395
  dbTable.definedAs = key;
@@ -1486,7 +1476,7 @@ class FileChanges {
1486
1476
  }
1487
1477
  }
1488
1478
 
1489
- const { createSourceFile, ScriptTarget, SyntaxKind } = typescript__default["default"];
1479
+ const { createSourceFile, ScriptTarget, SyntaxKind } = typescript;
1490
1480
  const iterate = (kind) => {
1491
1481
  return function* (statements) {
1492
1482
  for (const node of statements) {
@@ -1626,7 +1616,7 @@ const ts = {
1626
1616
  };
1627
1617
 
1628
1618
  const getImportPath = (from, to) => {
1629
- const rel = path__default["default"].relative(path__default["default"].dirname(from), to).split(path__default["default"].sep).join(path__default["default"].posix.sep);
1619
+ const rel = path.relative(path.dirname(from), to).split(path.sep).join(path.posix.sep);
1630
1620
  const importPath = rel.startsWith("./") || rel.startsWith("../") ? rel : `./${rel}`;
1631
1621
  return importPath.replace(/\.[tj]s$/, "");
1632
1622
  };
@@ -1656,7 +1646,7 @@ const optionsToString = (options) => {
1656
1646
  return lines.join("\n ");
1657
1647
  };
1658
1648
  const updateMainFile = async (filePath, tablePath, ast, options, logger) => {
1659
- const result = await fs__default["default"].readFile(filePath, "utf-8").then(
1649
+ const result = await fs.readFile(filePath, "utf-8").then(
1660
1650
  (content2) => ({ error: void 0, content: content2 }),
1661
1651
  (error) => {
1662
1652
  return { error, content: void 0 };
@@ -1699,9 +1689,9 @@ const updateMainFile = async (filePath, tablePath, ast, options, logger) => {
1699
1689
  }
1700
1690
  if (write) {
1701
1691
  if (result.error) {
1702
- await fs__default["default"].mkdir(path__default["default"].dirname(filePath), { recursive: true });
1692
+ await fs.mkdir(path.dirname(filePath), { recursive: true });
1703
1693
  }
1704
- await fs__default["default"].writeFile(filePath, write);
1694
+ await fs.writeFile(filePath, write);
1705
1695
  logger == null ? void 0 : logger.log(
1706
1696
  `${result.content ? "Updated" : "Created"} ${orchidCore.pathToLog(filePath)}`
1707
1697
  );
@@ -1828,9 +1818,9 @@ const createTable = async (_a) => {
1828
1818
  props,
1829
1819
  "}\n"
1830
1820
  ];
1831
- await fs__default["default"].mkdir(path__default["default"].dirname(tablePath), { recursive: true });
1821
+ await fs.mkdir(path.dirname(tablePath), { recursive: true });
1832
1822
  try {
1833
- await fs__default["default"].writeFile(tablePath, orchidCore.codeToString(code, "", " "), { flag: "wx" });
1823
+ await fs.writeFile(tablePath, orchidCore.codeToString(code, "", " "), { flag: "wx" });
1834
1824
  logger == null ? void 0 : logger.log(`Created ${orchidCore.pathToLog(tablePath)}`);
1835
1825
  } catch (err) {
1836
1826
  if (err.code !== "EEXIST") {
@@ -1876,7 +1866,7 @@ const changeTable = async (_a) => {
1876
1866
  "logger"
1877
1867
  ]);
1878
1868
  const tablePath = params.tablePath(orchidCore.toCamelCase(ast.name));
1879
- const content = await fs__default["default"].readFile(tablePath, "utf-8").catch(() => void 0);
1869
+ const content = await fs.readFile(tablePath, "utf-8").catch(() => void 0);
1880
1870
  if (!content)
1881
1871
  return;
1882
1872
  const changes = new FileChanges(content);
@@ -1890,7 +1880,7 @@ const changeTable = async (_a) => {
1890
1880
  addColumns(context);
1891
1881
  addTableData(context);
1892
1882
  }
1893
- await fs__default["default"].writeFile(tablePath, changes.apply());
1883
+ await fs.writeFile(tablePath, changes.apply());
1894
1884
  logger == null ? void 0 : logger.log(`Updated ${orchidCore.pathToLog(tablePath)}`);
1895
1885
  };
1896
1886
  function* iterateColumnsShapes(statements, className) {
@@ -2151,7 +2141,9 @@ const getColumnMethodArgs = (t, to, key, dataType) => {
2151
2141
  if (!value)
2152
2142
  return;
2153
2143
  if (key === "indexes") {
2154
- return pqb.columnIndexesToCode(value);
2144
+ return pqb.columnIndexesToCode(
2145
+ value
2146
+ );
2155
2147
  }
2156
2148
  if (key === "foreignKeys") {
2157
2149
  return pqb.columnForeignKeysToCode(value);
@@ -2359,7 +2351,7 @@ const renameTable = async (_a) => {
2359
2351
  ]);
2360
2352
  var _a2;
2361
2353
  const tablePath = params.tablePath(orchidCore.toCamelCase(ast.from));
2362
- const content = await fs__default["default"].readFile(tablePath, "utf-8").catch(() => void 0);
2354
+ const content = await fs.readFile(tablePath, "utf-8").catch(() => void 0);
2363
2355
  if (!content)
2364
2356
  return;
2365
2357
  const changes = new FileChanges(content);
@@ -2399,7 +2391,7 @@ const renameTable = async (_a) => {
2399
2391
  }
2400
2392
  }
2401
2393
  }
2402
- await fs__default["default"].writeFile(tablePath, changes.apply());
2394
+ await fs.writeFile(tablePath, changes.apply());
2403
2395
  logger == null ? void 0 : logger.log(`Updated ${orchidCore.pathToLog(tablePath)}`);
2404
2396
  };
2405
2397
 
@@ -2438,8 +2430,8 @@ const createBaseTableFile = async ({
2438
2430
  baseTablePath,
2439
2431
  logger
2440
2432
  }) => {
2441
- await fs__default["default"].mkdir(path__default["default"].dirname(baseTablePath), { recursive: true });
2442
- await fs__default["default"].writeFile(
2433
+ await fs.mkdir(path.dirname(baseTablePath), { recursive: true });
2434
+ await fs.writeFile(
2443
2435
  baseTablePath,
2444
2436
  `import { createBaseTable } from 'orchid-orm';
2445
2437