orchid-orm 1.6.40 → 1.8.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]>;
@@ -152,6 +155,8 @@ declare const createBaseTable: <CT extends ColumnTypesBase>({ columnTypes, snake
152
155
  table: string;
153
156
  columns: TableConfig;
154
157
  schema?: string | undefined;
158
+ noPrimaryKey?: boolean | undefined;
159
+ snakeCase: boolean | undefined;
155
160
  columnTypes: ColumnTypesBase extends CT ? {
156
161
  timestamps: <T extends orchid_core.ColumnTypeBase<unknown, orchid_core.BaseOperators, unknown, orchid_core.ColumnDataBase>>(this: {
157
162
  name(name: string): {
@@ -269,8 +274,6 @@ declare const createBaseTable: <CT extends ColumnTypesBase>({ columnTypes, snake
269
274
  }) | undefined): {};
270
275
  check(check: orchid_core.RawExpression): {};
271
276
  } : CT;
272
- noPrimaryKey?: boolean | undefined;
273
- snakeCase: boolean | undefined;
274
277
  setColumns: <T_18 extends ColumnsShape>(fn: (t: ColumnTypesBase extends CT ? {
275
278
  timestamps: <T extends orchid_core.ColumnTypeBase<unknown, orchid_core.BaseOperators, unknown, orchid_core.ColumnDataBase>>(this: {
276
279
  name(name: string): {
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');
@@ -36,7 +37,7 @@ const createBaseTable = ({
36
37
  );
37
38
  };
38
39
  const create = (columnTypes, snakeCase) => {
39
- return class BaseTable {
40
+ const base = class BaseTable {
40
41
  constructor() {
41
42
  this.snakeCase = snakeCase;
42
43
  this.setColumns = (fn) => {
@@ -93,6 +94,8 @@ const create = (columnTypes, snakeCase) => {
93
94
  };
94
95
  }
95
96
  };
97
+ base.prototype.columnTypes = columnTypes;
98
+ return base;
96
99
  };
97
100
 
98
101
  class BelongsToVirtualColumn extends pqb.VirtualColumn {
@@ -161,11 +164,11 @@ const makeBelongsToMethod = (relation, relationName, query) => {
161
164
  };
162
165
  };
163
166
  const nestedInsert$3 = ({ query, primaryKey }) => {
164
- return async (q, data) => {
167
+ return async (_, data) => {
165
168
  const connectOrCreate = data.filter(
166
169
  (item) => Boolean(item.connectOrCreate)
167
170
  );
168
- const t = query.transacting(q);
171
+ const t = query.clone();
169
172
  let connectOrCreated;
170
173
  if (connectOrCreate.length) {
171
174
  connectOrCreated = await Promise.all(
@@ -229,12 +232,12 @@ const nestedUpdate$3 = ({ query, primaryKey, foreignKey }) => {
229
232
  if (primaryKey in params.set) {
230
233
  update[foreignKey] = params.set[primaryKey];
231
234
  } else {
232
- update[foreignKey] = await query.transacting(q2)._findBy(params.set)._get(primaryKey);
235
+ update[foreignKey] = await query.findBy(params.set)._get(primaryKey);
233
236
  }
234
237
  } else if (params.create) {
235
- update[foreignKey] = await query.transacting(q2)._get(primaryKey)._create(params.create);
238
+ update[foreignKey] = await query.get(primaryKey)._create(params.create);
236
239
  } else if (params.delete) {
237
- const selectQuery = q2.transacting(q2);
240
+ const selectQuery = q2.clone();
238
241
  selectQuery.query.type = void 0;
239
242
  idForDelete = await selectQuery._getOptional(foreignKey);
240
243
  update[foreignKey] = null;
@@ -256,10 +259,10 @@ const nestedUpdate$3 = ({ query, primaryKey, foreignKey }) => {
256
259
  const data = await handleResult(q2, queryResult);
257
260
  const id = data[0][foreignKey];
258
261
  if (id !== null) {
259
- await query.transacting(q2)._findBy({ [primaryKey]: id })._update(upsert.update);
262
+ await query.findBy({ [primaryKey]: id })._update(upsert.update);
260
263
  } else {
261
264
  state.updateLaterPromises.push(
262
- query.transacting(q2)._select(primaryKey)._create(upsert.create).then((result) => {
265
+ query.select(primaryKey)._create(upsert.create).then((result) => {
263
266
  state.updateLater[foreignKey] = result[primaryKey];
264
267
  })
265
268
  );
@@ -267,12 +270,12 @@ const nestedUpdate$3 = ({ query, primaryKey, foreignKey }) => {
267
270
  return data;
268
271
  };
269
272
  } else if (params.delete || params.update) {
270
- q._afterQuery(async (q2, data) => {
273
+ q._afterQuery(async (_, data) => {
271
274
  const id = params.delete ? idForDelete : Array.isArray(data) ? data.length === 0 ? null : {
272
275
  in: data.map((item) => item[foreignKey]).filter((id2) => id2 !== null)
273
276
  } : data[foreignKey];
274
277
  if (id !== void 0 && id !== null) {
275
- const t = query.transacting(q2)._findBy({
278
+ const t = query.findBy({
276
279
  [primaryKey]: id
277
280
  });
278
281
  if (params.delete) {
@@ -464,11 +467,11 @@ const makeHasOneMethod = (table, relation, relationName, query) => {
464
467
  };
465
468
  };
466
469
  const nestedInsert$2 = ({ query, primaryKey, foreignKey }) => {
467
- return async (q, data) => {
470
+ return async (_, data) => {
468
471
  const connect = data.filter(
469
472
  (item) => Boolean(item[1].connect || item[1].connectOrCreate)
470
473
  );
471
- const t = query.transacting(q);
474
+ const t = query.clone();
472
475
  let connected;
473
476
  if (connect.length) {
474
477
  connected = await Promise.all(
@@ -504,7 +507,7 @@ const nestedUpdate$2 = ({ query, primaryKey, foreignKey }) => {
504
507
  const key = params.set ? "set" : params.create ? "create" : "upsert";
505
508
  throw new Error(`\`${key}\` option is not allowed in a batch update`);
506
509
  }
507
- const t = query.transacting(q);
510
+ const t = query.clone();
508
511
  const ids = data.map((item) => item[primaryKey]);
509
512
  const currentRelationsQuery = t.where({
510
513
  [foreignKey]: { in: ids }
@@ -673,11 +676,11 @@ const getWhereForNestedUpdate = (data, params, primaryKey, foreignKey) => {
673
676
  return where;
674
677
  };
675
678
  const nestedInsert$1 = ({ query, primaryKey, foreignKey }) => {
676
- return async (q, data) => {
679
+ return async (_, data) => {
677
680
  const connect = data.filter(
678
681
  (item) => Boolean(item[1].connect)
679
682
  );
680
- const t = query.transacting(q);
683
+ const t = query.clone();
681
684
  if (connect.length) {
682
685
  await Promise.all(
683
686
  connect.flatMap(
@@ -740,7 +743,7 @@ const nestedUpdate$1 = ({ query, primaryKey, foreignKey }) => {
740
743
  const key = params.set ? "set" : "create";
741
744
  throw new Error(`\`${key}\` option is not allowed in a batch update`);
742
745
  }
743
- const t = query.transacting(q);
746
+ const t = query.clone();
744
747
  if (params.create) {
745
748
  await t._count()._createMany(
746
749
  params.create.map((create) => __spreadProps$4(__spreadValues$6({}, create), {
@@ -914,10 +917,10 @@ const makeHasAndBelongsToManyMethod = (table, qb, relation, relationName, query)
914
917
  pqb.pushQueryValue(
915
918
  relationQuery,
916
919
  "afterCreate",
917
- async (q, result) => {
920
+ async (_, result) => {
918
921
  const fromQuery = ref.query.clone();
919
922
  fromQuery.query.select = [{ selectAs: { [fk]: pk } }];
920
- const createdCount = await subQuery.transacting(q).count()._createFrom(
923
+ const createdCount = await subQuery.count()._createFrom(
921
924
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
922
925
  fromQuery,
923
926
  {
@@ -935,8 +938,8 @@ const makeHasAndBelongsToManyMethod = (table, qb, relation, relationName, query)
935
938
  }
936
939
  };
937
940
  };
938
- const queryJoinTable = (state, q, data, conditions) => {
939
- const t = state.joinTableQuery.transacting(q);
941
+ const queryJoinTable = (state, data, conditions) => {
942
+ const t = state.joinTableQuery.clone();
940
943
  const where = {
941
944
  [state.foreignKey]: { in: data.map((item) => item[state.primaryKey]) }
942
945
  };
@@ -949,8 +952,10 @@ const queryJoinTable = (state, q, data, conditions) => {
949
952
  }
950
953
  return t._where(where);
951
954
  };
952
- const queryRelatedTable = (query, q, conditions) => {
953
- return query.transacting(q)._where(Array.isArray(conditions) ? { OR: conditions } : conditions);
955
+ const queryRelatedTable = (query, conditions) => {
956
+ return query.where(
957
+ Array.isArray(conditions) ? { OR: conditions } : conditions
958
+ );
954
959
  };
955
960
  const insertToJoinTable = (state, joinTableTransaction, data, ids) => {
956
961
  return joinTableTransaction._count()._createMany(
@@ -970,11 +975,11 @@ const nestedInsert = ({
970
975
  associationPrimaryKey,
971
976
  associationForeignKey
972
977
  }) => {
973
- return async (q, data) => {
978
+ return async (_, data) => {
974
979
  const connect = data.filter(
975
980
  (item) => Boolean(item[1].connect)
976
981
  );
977
- const t = relatedTableQuery.transacting(q);
982
+ const t = relatedTableQuery.clone();
978
983
  let connected;
979
984
  if (connect.length) {
980
985
  connected = await Promise.all(
@@ -1059,7 +1064,7 @@ const nestedInsert = ({
1059
1064
  connectI += len;
1060
1065
  }
1061
1066
  });
1062
- await joinTableQuery.transacting(q)._count()._createMany(
1067
+ await joinTableQuery.count()._createMany(
1063
1068
  allKeys.flatMap(([selfData, relationKeys]) => {
1064
1069
  const selfKey = selfData[primaryKey];
1065
1070
  return relationKeys.map((relationData) => ({
@@ -1071,10 +1076,10 @@ const nestedInsert = ({
1071
1076
  };
1072
1077
  };
1073
1078
  const nestedUpdate = (state) => {
1074
- return async (q, data, params) => {
1079
+ return async (_, data, params) => {
1075
1080
  if (params.create) {
1076
- const ids = await state.relatedTableQuery.transacting(q)._pluck(state.associationPrimaryKey)._createMany(params.create);
1077
- await state.joinTableQuery.transacting(q)._createMany(
1081
+ const ids = await state.relatedTableQuery.pluck(state.associationPrimaryKey)._createMany(params.create);
1082
+ await state.joinTableQuery.createMany(
1078
1083
  data.flatMap(
1079
1084
  (item) => ids.map((id) => ({
1080
1085
  [state.foreignKey]: item[state.primaryKey],
@@ -1084,11 +1089,11 @@ const nestedUpdate = (state) => {
1084
1089
  );
1085
1090
  }
1086
1091
  if (params.update) {
1087
- await state.relatedTableQuery.transacting(q)._whereExists(
1092
+ await state.relatedTableQuery.whereExists(
1088
1093
  state.joinTableQuery,
1089
- (q2) => (
1094
+ (q) => (
1090
1095
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
1091
- q2._on(
1096
+ q._on(
1092
1097
  state.associationForeignKeyFull,
1093
1098
  state.associationPrimaryKeyFull
1094
1099
  )._where({
@@ -1103,22 +1108,21 @@ const nestedUpdate = (state) => {
1103
1108
  )._update(params.update.data);
1104
1109
  }
1105
1110
  if (params.disconnect) {
1106
- await queryJoinTable(state, q, data, params.disconnect)._delete();
1111
+ await queryJoinTable(state, data, params.disconnect)._delete();
1107
1112
  }
1108
1113
  if (params.delete) {
1109
- const j = queryJoinTable(state, q, data, params.delete);
1114
+ const j = queryJoinTable(state, data, params.delete);
1110
1115
  const ids = await j._pluck(state.associationForeignKey)._delete();
1111
- await queryRelatedTable(state.relatedTableQuery, q, {
1116
+ await queryRelatedTable(state.relatedTableQuery, {
1112
1117
  [state.associationPrimaryKey]: { in: ids }
1113
1118
  })._delete();
1114
1119
  }
1115
1120
  if (params.set) {
1116
- const j = queryJoinTable(state, q, data);
1121
+ const j = queryJoinTable(state, data);
1117
1122
  await j._delete();
1118
1123
  delete j.query[pqb.toSqlCacheKey];
1119
1124
  const ids = await queryRelatedTable(
1120
1125
  state.relatedTableQuery,
1121
- q,
1122
1126
  params.set
1123
1127
  )._pluck(state.associationPrimaryKey);
1124
1128
  await insertToJoinTable(state, j, data, ids);
@@ -1293,25 +1297,11 @@ const makeRelationQuery = (table, definedAs, relationName, data) => {
1293
1297
  });
1294
1298
  };
1295
1299
 
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
- });
1300
+ function transaction(fnOrOptions, fn) {
1301
+ return this.$queryBuilder.transaction(
1302
+ fnOrOptions,
1303
+ fn
1304
+ );
1315
1305
  }
1316
1306
 
1317
1307
  var __defProp$4 = Object.defineProperty;
@@ -1364,12 +1354,14 @@ const orchidORM = (_a, tables) => {
1364
1354
  autoPreparedStatements,
1365
1355
  noPrimaryKey
1366
1356
  };
1357
+ const transactionStorage = new node_async_hooks.AsyncLocalStorage();
1367
1358
  const qb = new pqb.Db(
1368
1359
  adapter,
1369
1360
  void 0,
1370
1361
  void 0,
1371
1362
  pqb.anyShape,
1372
1363
  pqb.columnTypes,
1364
+ transactionStorage,
1373
1365
  commonOptions
1374
1366
  );
1375
1367
  qb.queryBuilder = qb;
@@ -1399,6 +1391,7 @@ const orchidORM = (_a, tables) => {
1399
1391
  table.table,
1400
1392
  table.columns.shape,
1401
1393
  table.columnTypes,
1394
+ transactionStorage,
1402
1395
  options2
1403
1396
  );
1404
1397
  dbTable.definedAs = key;
@@ -1624,12 +1617,6 @@ const ts = {
1624
1617
  }
1625
1618
  };
1626
1619
 
1627
- const getImportPath = (from, to) => {
1628
- const rel = path.relative(path.dirname(from), to).split(path.sep).join(path.posix.sep);
1629
- const importPath = rel.startsWith("./") || rel.startsWith("../") ? rel : `./${rel}`;
1630
- return importPath.replace(/\.[tj]s$/, "");
1631
- };
1632
-
1633
1620
  const libraryName = "orchid-orm";
1634
1621
  const importKey = "orchidORM";
1635
1622
  const newFile = (options) => `import { orchidORM } from 'orchid-orm';
@@ -1710,7 +1697,7 @@ const createTable$1 = ({ filePath, tablePath, statements, object, content, space
1710
1697
  const key = orchidCore.toCamelCase(ast.name);
1711
1698
  const value = `${orchidCore.toPascalCase(ast.name)}Table`;
1712
1699
  const changes = new FileChanges(content);
1713
- const importPath = getImportPath(filePath, tablePath(orchidCore.toCamelCase(ast.name)));
1700
+ const importPath = orchidCore.getImportPath(filePath, tablePath(orchidCore.toCamelCase(ast.name)));
1714
1701
  const existing = Array.from(
1715
1702
  ts.import.iterateWithSource(statements, importPath)
1716
1703
  );
@@ -1740,7 +1727,7 @@ ${spaces}`;
1740
1727
  };
1741
1728
  const dropTable = ({ filePath, tablePath, statements, object, content }, ast) => {
1742
1729
  const changes = new FileChanges(content);
1743
- const importPath = getImportPath(filePath, tablePath(orchidCore.toCamelCase(ast.name)));
1730
+ const importPath = orchidCore.getImportPath(filePath, tablePath(orchidCore.toCamelCase(ast.name)));
1744
1731
  const tableClassName = `${orchidCore.toPascalCase(ast.name)}Table`;
1745
1732
  const importNames = [];
1746
1733
  for (const node of ts.import.iterateWithSource(statements, importPath)) {
@@ -1806,7 +1793,7 @@ const createTable = async (_a) => {
1806
1793
  "logger"
1807
1794
  ]);
1808
1795
  const tablePath = params.tablePath(orchidCore.toCamelCase(ast.name));
1809
- const baseTablePath = getImportPath(tablePath, params.baseTablePath);
1796
+ const baseTablePath = orchidCore.getImportPath(tablePath, params.baseTablePath);
1810
1797
  const props = [];
1811
1798
  if (ast.schema) {
1812
1799
  props.push(`schema = ${orchidCore.singleQuote(ast.schema)};`);