orchid-orm 1.10.6 → 1.11.1

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,17 +1,8 @@
1
- import { addQueryHook, columnTypes, getColumnTypes, addQueryOn, VirtualColumn, pushQueryValue, isQueryReturnsAll, getQueryAs, toSqlCacheKey, NotFoundError, relationQueryKey, Adapter, Db, anyShape, getClonedQueryData } from 'pqb';
1
+ import { columnTypes, QueryHooks, getColumnTypes, addQueryOn, VirtualColumn, pushQueryValue, isQueryReturnsAll, getQueryAs, toSqlCacheKey, OrchidOrmInternalError, NotFoundError, relationQueryKey, Adapter, Db, anyShape, getClonedQueryData } from 'pqb';
2
2
  export { OrchidOrmError, OrchidOrmInternalError, columnTypes, testTransaction } from 'pqb';
3
- import { getCallerFilePath, snakeCaseKey, toSnakeCase } from 'orchid-core';
3
+ import { getStackTrace, applyMixins, getCallerFilePath, snakeCaseKey, toSnakeCase } from 'orchid-core';
4
4
  import { AsyncLocalStorage } from 'node:async_hooks';
5
5
 
6
- const addTableHooks = (table, hooks) => {
7
- for (const key in hooks) {
8
- addQueryHook(
9
- table.baseQuery,
10
- key,
11
- hooks[key]
12
- );
13
- }
14
- };
15
6
  const createBaseTable = ({
16
7
  columnTypes: columnTypes$1,
17
8
  snakeCase,
@@ -20,40 +11,52 @@ const createBaseTable = ({
20
11
  exportAs
21
12
  } = { columnTypes: columnTypes }) => {
22
13
  const ct = typeof columnTypes$1 === "function" ? columnTypes$1(columnTypes) : columnTypes$1 || columnTypes;
23
- filePath != null ? filePath : filePath = getCallerFilePath();
24
- if (!filePath) {
25
- throw new Error(
26
- `Failed to determine file path of a base table. Please set the \`filePath\` option of \`createBaseTable\` manually.`
27
- );
28
- }
29
14
  return create(
30
15
  ct,
31
- filePath,
16
+ // stack is needed only if filePath wasn't given
17
+ filePath || getStackTrace(),
32
18
  snakeCase,
33
19
  nowSQL,
34
20
  exportAs
35
21
  );
36
22
  };
37
- const create = (columnTypes, filePath, snakeCase, nowSQL, exportAs = "BaseTable") => {
23
+ const create = (columnTypes, filePathOrStack, snakeCase, nowSQL, exportAs = "BaseTable") => {
38
24
  var _a;
25
+ let filePath;
39
26
  const base = (_a = class {
40
27
  constructor() {
41
28
  this.snakeCase = snakeCase;
42
29
  this.columnTypes = columnTypes;
30
+ this.query = {};
43
31
  }
44
- setHooks(callbacks) {
45
- return callbacks;
32
+ static getFilePath() {
33
+ if (filePath)
34
+ return filePath;
35
+ if (typeof filePathOrStack === "string")
36
+ return filePath = filePathOrStack;
37
+ filePath = getCallerFilePath(filePathOrStack);
38
+ if (filePath)
39
+ return filePath;
40
+ throw new Error(
41
+ `Failed to determine file path of a base table. Please set the \`filePath\` option of \`createBaseTable\` manually.`
42
+ );
43
+ }
44
+ clone() {
45
+ return this;
46
+ }
47
+ getFilePath() {
48
+ if (this.filePath)
49
+ return this.filePath;
50
+ if (typeof filePathOrStack === "string")
51
+ return this.filePath = filePathOrStack;
52
+ const filePath2 = getCallerFilePath(filePathOrStack);
53
+ if (filePath2)
54
+ return this.filePath = filePath2;
55
+ throw new Error(
56
+ `Failed to determine file path for table ${this.constructor.name}. Please set \`filePath\` property manually`
57
+ );
46
58
  }
47
59
  setColumns(fn) {
48
- if (!this.filePath) {
49
- const filePath2 = getCallerFilePath();
50
- if (!filePath2) {
51
- throw new Error(
52
- `Failed to determine file path for table ${this.constructor.name}. Please set \`filePath\` property manually`
53
- );
54
- }
55
- this.filePath = filePath2;
56
- }
57
60
  columnTypes[snakeCaseKey] = this.snakeCase;
58
61
  const shape = getColumnTypes(columnTypes, fn, nowSQL);
59
62
  if (this.snakeCase) {
@@ -104,7 +107,8 @@ const create = (columnTypes, filePath, snakeCase, nowSQL, exportAs = "BaseTable"
104
107
  options
105
108
  };
106
109
  }
107
- }, _a.filePath = filePath, _a.nowSQL = nowSQL, _a.exportAs = exportAs, _a);
110
+ }, _a.nowSQL = nowSQL, _a.exportAs = exportAs, _a);
111
+ applyMixins(base, [QueryHooks]);
108
112
  base.prototype.columnTypes = columnTypes;
109
113
  return base;
110
114
  };
@@ -224,9 +228,9 @@ const nestedInsert$3 = ({ query, primaryKey }) => {
224
228
  let createdI = 0;
225
229
  let connectedI = 0;
226
230
  connectOrCreatedI = 0;
227
- return data.map(
228
- (item) => item.connectOrCreate ? connectOrCreated[connectOrCreatedI++] || created[createdI++] : item.connect ? connected[connectedI++] : created[createdI++]
229
- );
231
+ return data.map((item) => {
232
+ return item.connectOrCreate ? connectOrCreated[connectOrCreatedI++] || created[createdI++] : item.connect ? connected[connectedI++] : created[createdI++];
233
+ });
230
234
  };
231
235
  };
232
236
  const nestedUpdate$3 = ({ query, primaryKey, foreignKey }) => {
@@ -235,7 +239,7 @@ const nestedUpdate$3 = ({ query, primaryKey, foreignKey }) => {
235
239
  if (params.upsert && isQueryReturnsAll(q)) {
236
240
  throw new Error("`upsert` option is not allowed in a batch update");
237
241
  }
238
- let idForDelete;
242
+ let idsForDelete;
239
243
  q._beforeUpdate(async (q2) => {
240
244
  if (params.disconnect) {
241
245
  update[foreignKey] = null;
@@ -250,7 +254,7 @@ const nestedUpdate$3 = ({ query, primaryKey, foreignKey }) => {
250
254
  } else if (params.delete) {
251
255
  const selectQuery = q2.clone();
252
256
  selectQuery.query.type = void 0;
253
- idForDelete = await selectQuery._getOptional(foreignKey);
257
+ idsForDelete = await selectQuery._pluck(foreignKey);
254
258
  update[foreignKey] = null;
255
259
  }
256
260
  });
@@ -273,12 +277,12 @@ const nestedUpdate$3 = ({ query, primaryKey, foreignKey }) => {
273
277
  }
274
278
  });
275
279
  } else if (params.delete || params.update) {
276
- q._afterQuery(async (_, data) => {
277
- const id = params.delete ? idForDelete : Array.isArray(data) ? data.length === 0 ? null : {
280
+ q._afterUpdate([], async (data) => {
281
+ const id = params.delete ? { in: idsForDelete } : Array.isArray(data) ? data.length === 0 ? null : {
278
282
  in: data.map((item) => item[foreignKey]).filter((id2) => id2 !== null)
279
283
  } : data[foreignKey];
280
284
  if (id !== void 0 && id !== null) {
281
- const t = query.findBy({
285
+ const t = query.where({
282
286
  [primaryKey]: id
283
287
  });
284
288
  if (params.delete) {
@@ -312,22 +316,20 @@ const hasRelationHandleCreate = (q, ctx, item, rowIndex, key, primaryKey, nested
312
316
  return;
313
317
  }
314
318
  q.query.wrapInTransaction = true;
315
- ctx.returnTypeAll = true;
316
- ctx.requiredReturning[primaryKey] = true;
317
319
  const relationData = [values];
318
320
  store.hasRelation[key] = relationData;
319
- pushQueryValue(q, "afterCreate", async (q2) => {
320
- const { resultAll } = ctx;
321
- return nestedInsert(
321
+ q._afterCreate(
322
+ [primaryKey],
323
+ (rows, q2) => nestedInsert(
322
324
  q2,
323
325
  relationData.map(([rowIndex2, data]) => [
324
- resultAll[rowIndex2],
326
+ rows[rowIndex2],
325
327
  data
326
328
  ])
327
- );
328
- });
329
+ )
330
+ );
329
331
  };
330
- const hasRelationHandleUpdate = (q, ctx, set, key, primaryKey, nestedUpdate) => {
332
+ const hasRelationHandleUpdate = (q, set, key, primaryKey, nestedUpdate) => {
331
333
  var _a, _b;
332
334
  const value = set[key];
333
335
  if (!value.set && !("upsert" in value) && (!value.disconnect || Array.isArray(value.disconnect) && value.disconnect.length === 0) && (!value.delete || Array.isArray(value.delete) && value.delete.length === 0) && (!value.update || Array.isArray(value.update.where) && value.update.where.length === 0) && (!value.create || Array.isArray(value.create) && value.create.length === 0))
@@ -336,11 +338,10 @@ const hasRelationHandleUpdate = (q, ctx, set, key, primaryKey, nestedUpdate) =>
336
338
  q._select(primaryKey);
337
339
  }
338
340
  q.query.wrapInTransaction = true;
339
- ctx.returnTypeAll = true;
340
- pushQueryValue(q, "afterUpdate", (q2) => {
341
+ q._afterUpdate(q.primaryKeys, (rows, q2) => {
341
342
  return nestedUpdate(
342
343
  q2,
343
- ctx.resultAll,
344
+ rows,
344
345
  value
345
346
  );
346
347
  });
@@ -384,10 +385,14 @@ class HasOneVirtualColumn extends VirtualColumn {
384
385
  this.nestedInsert
385
386
  );
386
387
  }
387
- update(q, ctx, set) {
388
+ update(q, _, set) {
389
+ const params = set[this.key];
390
+ if ((params.set || params.create || params.upsert) && isQueryReturnsAll(q)) {
391
+ const key = params.set ? "set" : params.create ? "create" : "upsert";
392
+ throw new Error(`\`${key}\` option is not allowed in a batch update`);
393
+ }
388
394
  hasRelationHandleUpdate(
389
395
  q,
390
- ctx,
391
396
  set,
392
397
  this.key,
393
398
  this.state.primaryKey,
@@ -500,11 +505,7 @@ const nestedInsert$2 = ({ query, primaryKey, foreignKey }) => {
500
505
  };
501
506
  };
502
507
  const nestedUpdate$2 = ({ query, primaryKey, foreignKey }) => {
503
- return async (q, data, params) => {
504
- if ((params.set || params.create || params.upsert) && isQueryReturnsAll(q)) {
505
- const key = params.set ? "set" : params.create ? "create" : "upsert";
506
- throw new Error(`\`${key}\` option is not allowed in a batch update`);
507
- }
508
+ return async (_, data, params) => {
508
509
  const t = query.clone();
509
510
  const ids = data.map((item) => item[primaryKey]);
510
511
  const currentRelationsQuery = t.where({
@@ -577,10 +578,14 @@ class HasManyVirtualColumn extends VirtualColumn {
577
578
  this.nestedInsert
578
579
  );
579
580
  }
580
- update(q, ctx, set) {
581
+ update(q, _, set) {
582
+ const params = set[this.key];
583
+ if ((params.set || params.create) && isQueryReturnsAll(q)) {
584
+ const key = params.set ? "set" : "create";
585
+ throw new Error(`\`${key}\` option is not allowed in a batch update`);
586
+ }
581
587
  hasRelationHandleUpdate(
582
588
  q,
583
- ctx,
584
589
  set,
585
590
  this.key,
586
591
  this.state.primaryKey,
@@ -736,12 +741,8 @@ const nestedInsert$1 = ({ query, primaryKey, foreignKey }) => {
736
741
  };
737
742
  };
738
743
  const nestedUpdate$1 = ({ query, primaryKey, foreignKey }) => {
739
- return async (q, data, params) => {
744
+ return async (_, data, params) => {
740
745
  var _a;
741
- if ((params.set || params.create) && isQueryReturnsAll(q)) {
742
- const key = params.set ? "set" : "create";
743
- throw new Error(`\`${key}\` option is not allowed in a batch update`);
744
- }
745
746
  const t = query.clone();
746
747
  if (params.create) {
747
748
  await t._count()._createMany(
@@ -771,7 +772,7 @@ const nestedUpdate$1 = ({ query, primaryKey, foreignKey }) => {
771
772
  }
772
773
  if (params.delete || params.update) {
773
774
  delete t.query[toSqlCacheKey];
774
- const q2 = t._where(
775
+ const q = t._where(
775
776
  getWhereForNestedUpdate(
776
777
  data,
777
778
  params.delete || ((_a = params.update) == null ? void 0 : _a.where),
@@ -780,9 +781,9 @@ const nestedUpdate$1 = ({ query, primaryKey, foreignKey }) => {
780
781
  )
781
782
  );
782
783
  if (params.delete) {
783
- await q2._delete();
784
+ await q._delete();
784
785
  } else if (params.update) {
785
- await q2._update(params.update.data);
786
+ await q._update(params.update.data);
786
787
  }
787
788
  }
788
789
  };
@@ -826,10 +827,9 @@ class HasAndBelongsToManyVirtualColumn extends VirtualColumn {
826
827
  this.nestedInsert
827
828
  );
828
829
  }
829
- update(q, ctx, set) {
830
+ update(q, _, set) {
830
831
  hasRelationHandleUpdate(
831
832
  q,
832
- ctx,
833
833
  set,
834
834
  this.key,
835
835
  this.state.primaryKey,
@@ -909,24 +909,26 @@ const makeHasAndBelongsToManyMethod = (table, qb, relation, relationName, query)
909
909
  primaryKey: pk,
910
910
  modifyRelatedQuery(relationQuery) {
911
911
  const ref = {};
912
- pushQueryValue(
913
- relationQuery,
914
- "afterCreate",
915
- async (_, result) => {
916
- const fromQuery = ref.query.clone();
917
- fromQuery.query.select = [{ selectAs: { [fk]: pk } }];
918
- const createdCount = await subQuery.count()._createFrom(
919
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
920
- fromQuery,
921
- {
922
- [afk]: result[apk]
923
- }
912
+ relationQuery._afterCreate([], async (result) => {
913
+ if (result.length > 1) {
914
+ throw new OrchidOrmInternalError(
915
+ relationQuery,
916
+ "Creating multiple `hasAndBelongsToMany` records is not yet supported"
924
917
  );
925
- if (createdCount === 0) {
926
- throw new NotFoundError(fromQuery);
918
+ }
919
+ const fromQuery = ref.query.clone();
920
+ fromQuery.query.select = [{ selectAs: { [fk]: pk } }];
921
+ const createdCount = await subQuery.count()._createFrom(
922
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
923
+ fromQuery,
924
+ {
925
+ [afk]: result[0][apk]
927
926
  }
927
+ );
928
+ if (createdCount === 0) {
929
+ throw new NotFoundError(fromQuery);
928
930
  }
929
- );
931
+ });
930
932
  return (q) => {
931
933
  ref.query = q;
932
934
  };
@@ -1437,11 +1439,16 @@ const orchidORM = (_a, tables) => {
1437
1439
  dbTable.db = result;
1438
1440
  dbTable.filePath = table.filePath;
1439
1441
  dbTable.name = table.constructor.name;
1440
- if (table.hooks)
1441
- addTableHooks(dbTable, table.hooks);
1442
1442
  result[key] = dbTable;
1443
1443
  }
1444
1444
  applyRelations(qb, tableInstances, result);
1445
+ for (const key in tables) {
1446
+ const table = tableInstances[key];
1447
+ if (table.init) {
1448
+ table.init(result);
1449
+ Object.assign(result[key].baseQuery.query, table.query);
1450
+ }
1451
+ }
1445
1452
  return result;
1446
1453
  };
1447
1454
 
@@ -1488,5 +1495,5 @@ const createRepo = (table, methods) => {
1488
1495
  });
1489
1496
  };
1490
1497
 
1491
- export { addTableHooks, createBaseTable, createRepo, orchidORM };
1498
+ export { createBaseTable, createRepo, orchidORM };
1492
1499
  //# sourceMappingURL=index.mjs.map