orchid-orm 1.9.21 → 1.9.23

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
@@ -3,29 +3,6 @@
3
3
  var pqb = require('pqb');
4
4
  var orchidCore = require('orchid-core');
5
5
  var node_async_hooks = require('node:async_hooks');
6
- var path = require('path');
7
- var fs = require('fs/promises');
8
- var typescript = require('typescript');
9
- var inflection = require('inflection');
10
-
11
- function _interopNamespaceDefault(e) {
12
- var n = Object.create(null);
13
- if (e) {
14
- Object.keys(e).forEach(function (k) {
15
- if (k !== 'default') {
16
- var d = Object.getOwnPropertyDescriptor(e, k);
17
- Object.defineProperty(n, k, d.get ? d : {
18
- enumerable: true,
19
- get: function () { return e[k]; }
20
- });
21
- }
22
- });
23
- }
24
- n.default = e;
25
- return Object.freeze(n);
26
- }
27
-
28
- var path__namespace = /*#__PURE__*/_interopNamespaceDefault(path);
29
6
 
30
7
  const createBaseTable = ({
31
8
  columnTypes,
@@ -277,7 +254,8 @@ const nestedUpdate$3 = ({ query, primaryKey, foreignKey }) => {
277
254
  if (id !== null) {
278
255
  await query.findBy({ [primaryKey]: id })._update(upsert.update);
279
256
  } else {
280
- const result = await query.select(primaryKey)._create(upsert.create);
257
+ const data = typeof upsert.create === "function" ? upsert.create() : upsert.create;
258
+ const result = await query.select(primaryKey)._create(data);
281
259
  ((_a2 = state.updateData) != null ? _a2 : state.updateData = {})[foreignKey] = result[primaryKey];
282
260
  }
283
261
  });
@@ -355,25 +333,25 @@ const hasRelationHandleUpdate = (q, ctx, set, key, primaryKey, nestedUpdate) =>
355
333
  });
356
334
  };
357
335
 
358
- var __defProp$7 = Object.defineProperty;
359
- var __defProps$5 = Object.defineProperties;
360
- var __getOwnPropDescs$5 = Object.getOwnPropertyDescriptors;
361
- var __getOwnPropSymbols$9 = Object.getOwnPropertySymbols;
362
- var __hasOwnProp$9 = Object.prototype.hasOwnProperty;
363
- var __propIsEnum$9 = Object.prototype.propertyIsEnumerable;
364
- var __defNormalProp$7 = (obj, key, value) => key in obj ? __defProp$7(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
365
- var __spreadValues$7 = (a, b) => {
336
+ var __defProp$4 = Object.defineProperty;
337
+ var __defProps$3 = Object.defineProperties;
338
+ var __getOwnPropDescs$3 = Object.getOwnPropertyDescriptors;
339
+ var __getOwnPropSymbols$4 = Object.getOwnPropertySymbols;
340
+ var __hasOwnProp$4 = Object.prototype.hasOwnProperty;
341
+ var __propIsEnum$4 = Object.prototype.propertyIsEnumerable;
342
+ var __defNormalProp$4 = (obj, key, value) => key in obj ? __defProp$4(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
343
+ var __spreadValues$4 = (a, b) => {
366
344
  for (var prop in b || (b = {}))
367
- if (__hasOwnProp$9.call(b, prop))
368
- __defNormalProp$7(a, prop, b[prop]);
369
- if (__getOwnPropSymbols$9)
370
- for (var prop of __getOwnPropSymbols$9(b)) {
371
- if (__propIsEnum$9.call(b, prop))
372
- __defNormalProp$7(a, prop, b[prop]);
345
+ if (__hasOwnProp$4.call(b, prop))
346
+ __defNormalProp$4(a, prop, b[prop]);
347
+ if (__getOwnPropSymbols$4)
348
+ for (var prop of __getOwnPropSymbols$4(b)) {
349
+ if (__propIsEnum$4.call(b, prop))
350
+ __defNormalProp$4(a, prop, b[prop]);
373
351
  }
374
352
  return a;
375
353
  };
376
- var __spreadProps$5 = (a, b) => __defProps$5(a, __getOwnPropDescs$5(b));
354
+ var __spreadProps$3 = (a, b) => __defProps$3(a, __getOwnPropDescs$3(b));
377
355
  class HasOneVirtualColumn extends pqb.VirtualColumn {
378
356
  constructor(key, state) {
379
357
  super();
@@ -506,7 +484,7 @@ const nestedInsert$2 = ({ query, primaryKey, foreignKey }) => {
506
484
  );
507
485
  if (create.length) {
508
486
  await t._count()._createMany(
509
- create.map(([selfData, item]) => __spreadValues$7({
487
+ create.map(([selfData, item]) => __spreadValues$4({
510
488
  [foreignKey]: selfData[primaryKey]
511
489
  }, "create" in item ? item.create : item.connectOrCreate.create))
512
490
  );
@@ -527,7 +505,7 @@ const nestedUpdate$2 = ({ query, primaryKey, foreignKey }) => {
527
505
  if (params.create || params.disconnect || params.set) {
528
506
  await currentRelationsQuery._update({ [foreignKey]: null });
529
507
  if (params.create) {
530
- await t._count()._create(__spreadProps$5(__spreadValues$7({}, params.create), {
508
+ await t._count()._create(__spreadProps$3(__spreadValues$4({}, params.create), {
531
509
  [foreignKey]: data[0][primaryKey]
532
510
  }));
533
511
  }
@@ -542,8 +520,9 @@ const nestedUpdate$2 = ({ query, primaryKey, foreignKey }) => {
542
520
  const { update, create } = params.upsert;
543
521
  const updatedIds = await currentRelationsQuery._pluck(foreignKey)._update(update);
544
522
  if (updatedIds.length < ids.length) {
523
+ const data2 = typeof create === "function" ? create() : create;
545
524
  await t.createMany(
546
- ids.filter((id) => !updatedIds.includes(id)).map((id) => __spreadProps$5(__spreadValues$7({}, create), {
525
+ ids.filter((id) => !updatedIds.includes(id)).map((id) => __spreadProps$3(__spreadValues$4({}, data2), {
547
526
  [foreignKey]: id
548
527
  }))
549
528
  );
@@ -552,25 +531,25 @@ const nestedUpdate$2 = ({ query, primaryKey, foreignKey }) => {
552
531
  };
553
532
  };
554
533
 
555
- var __defProp$6 = Object.defineProperty;
556
- var __defProps$4 = Object.defineProperties;
557
- var __getOwnPropDescs$4 = Object.getOwnPropertyDescriptors;
558
- var __getOwnPropSymbols$8 = Object.getOwnPropertySymbols;
559
- var __hasOwnProp$8 = Object.prototype.hasOwnProperty;
560
- var __propIsEnum$8 = Object.prototype.propertyIsEnumerable;
561
- var __defNormalProp$6 = (obj, key, value) => key in obj ? __defProp$6(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
562
- var __spreadValues$6 = (a, b) => {
534
+ var __defProp$3 = Object.defineProperty;
535
+ var __defProps$2 = Object.defineProperties;
536
+ var __getOwnPropDescs$2 = Object.getOwnPropertyDescriptors;
537
+ var __getOwnPropSymbols$3 = Object.getOwnPropertySymbols;
538
+ var __hasOwnProp$3 = Object.prototype.hasOwnProperty;
539
+ var __propIsEnum$3 = Object.prototype.propertyIsEnumerable;
540
+ var __defNormalProp$3 = (obj, key, value) => key in obj ? __defProp$3(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
541
+ var __spreadValues$3 = (a, b) => {
563
542
  for (var prop in b || (b = {}))
564
- if (__hasOwnProp$8.call(b, prop))
565
- __defNormalProp$6(a, prop, b[prop]);
566
- if (__getOwnPropSymbols$8)
567
- for (var prop of __getOwnPropSymbols$8(b)) {
568
- if (__propIsEnum$8.call(b, prop))
569
- __defNormalProp$6(a, prop, b[prop]);
543
+ if (__hasOwnProp$3.call(b, prop))
544
+ __defNormalProp$3(a, prop, b[prop]);
545
+ if (__getOwnPropSymbols$3)
546
+ for (var prop of __getOwnPropSymbols$3(b)) {
547
+ if (__propIsEnum$3.call(b, prop))
548
+ __defNormalProp$3(a, prop, b[prop]);
570
549
  }
571
550
  return a;
572
551
  };
573
- var __spreadProps$4 = (a, b) => __defProps$4(a, __getOwnPropDescs$4(b));
552
+ var __spreadProps$2 = (a, b) => __defProps$2(a, __getOwnPropDescs$2(b));
574
553
  class HasManyVirtualColumn extends pqb.VirtualColumn {
575
554
  constructor(key, state) {
576
555
  super();
@@ -736,10 +715,10 @@ const nestedInsert$1 = ({ query, primaryKey, foreignKey }) => {
736
715
  await t._createMany(
737
716
  create.flatMap(([selfData, { create: create2 = [], connectOrCreate: connectOrCreate2 = [] }]) => {
738
717
  return [
739
- ...create2.map((item) => __spreadValues$6({
718
+ ...create2.map((item) => __spreadValues$3({
740
719
  [foreignKey]: selfData[primaryKey]
741
720
  }, item)),
742
- ...connectOrCreate2.filter(() => connected[connectedI++] === 0).map((item) => __spreadValues$6({
721
+ ...connectOrCreate2.filter(() => connected[connectedI++] === 0).map((item) => __spreadValues$3({
743
722
  [foreignKey]: selfData[primaryKey]
744
723
  }, item.create))
745
724
  ];
@@ -758,7 +737,7 @@ const nestedUpdate$1 = ({ query, primaryKey, foreignKey }) => {
758
737
  const t = query.clone();
759
738
  if (params.create) {
760
739
  await t._count()._createMany(
761
- params.create.map((create) => __spreadProps$4(__spreadValues$6({}, create), {
740
+ params.create.map((create) => __spreadProps$2(__spreadValues$3({}, create), {
762
741
  [foreignKey]: data[0][primaryKey]
763
742
  }))
764
743
  );
@@ -801,25 +780,25 @@ const nestedUpdate$1 = ({ query, primaryKey, foreignKey }) => {
801
780
  };
802
781
  };
803
782
 
804
- var __defProp$5 = Object.defineProperty;
805
- var __defProps$3 = Object.defineProperties;
806
- var __getOwnPropDescs$3 = Object.getOwnPropertyDescriptors;
807
- var __getOwnPropSymbols$7 = Object.getOwnPropertySymbols;
808
- var __hasOwnProp$7 = Object.prototype.hasOwnProperty;
809
- var __propIsEnum$7 = Object.prototype.propertyIsEnumerable;
810
- var __defNormalProp$5 = (obj, key, value) => key in obj ? __defProp$5(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
811
- var __spreadValues$5 = (a, b) => {
783
+ var __defProp$2 = Object.defineProperty;
784
+ var __defProps$1 = Object.defineProperties;
785
+ var __getOwnPropDescs$1 = Object.getOwnPropertyDescriptors;
786
+ var __getOwnPropSymbols$2 = Object.getOwnPropertySymbols;
787
+ var __hasOwnProp$2 = Object.prototype.hasOwnProperty;
788
+ var __propIsEnum$2 = Object.prototype.propertyIsEnumerable;
789
+ var __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
790
+ var __spreadValues$2 = (a, b) => {
812
791
  for (var prop in b || (b = {}))
813
- if (__hasOwnProp$7.call(b, prop))
814
- __defNormalProp$5(a, prop, b[prop]);
815
- if (__getOwnPropSymbols$7)
816
- for (var prop of __getOwnPropSymbols$7(b)) {
817
- if (__propIsEnum$7.call(b, prop))
818
- __defNormalProp$5(a, prop, b[prop]);
792
+ if (__hasOwnProp$2.call(b, prop))
793
+ __defNormalProp$2(a, prop, b[prop]);
794
+ if (__getOwnPropSymbols$2)
795
+ for (var prop of __getOwnPropSymbols$2(b)) {
796
+ if (__propIsEnum$2.call(b, prop))
797
+ __defNormalProp$2(a, prop, b[prop]);
819
798
  }
820
799
  return a;
821
800
  };
822
- var __spreadProps$3 = (a, b) => __defProps$3(a, __getOwnPropDescs$3(b));
801
+ var __spreadProps$1 = (a, b) => __defProps$1(a, __getOwnPropDescs$1(b));
823
802
  class HasAndBelongsToManyVirtualColumn extends pqb.VirtualColumn {
824
803
  constructor(key, state) {
825
804
  super();
@@ -854,7 +833,7 @@ const removeColumnName = (column) => {
854
833
  if (!column.data.name)
855
834
  return column;
856
835
  const cloned = Object.create(column);
857
- cloned.data = __spreadProps$3(__spreadValues$5({}, column.data), { name: void 0 });
836
+ cloned.data = __spreadProps$1(__spreadValues$2({}, column.data), { name: void 0 });
858
837
  return cloned;
859
838
  };
860
839
  const makeHasAndBelongsToManyMethod = (table, qb, relation, relationName, query) => {
@@ -875,7 +854,7 @@ const makeHasAndBelongsToManyMethod = (table, qb, relation, relationName, query)
875
854
  [fk]: removeColumnName(table.shape[pk]),
876
855
  [afk]: removeColumnName(query.shape[apk])
877
856
  };
878
- baseQuery.query = __spreadProps$3(__spreadValues$5({}, baseQuery.query), {
857
+ baseQuery.query = __spreadProps$1(__spreadValues$2({}, baseQuery.query), {
879
858
  shape: baseQuery.shape
880
859
  });
881
860
  const subQuery = Object.create(baseQuery);
@@ -908,7 +887,7 @@ const makeHasAndBelongsToManyMethod = (table, qb, relation, relationName, query)
908
887
  subQuery,
909
888
  (q) => q._on(associationForeignKeyFull, `${pqb.getQueryAs(toQuery)}.${apk}`)._on(foreignKeyFull, `${pqb.getQueryAs(fromQuery)}.${pk}`)
910
889
  );
911
- join.query.joinedShapes = __spreadProps$3(__spreadValues$5({}, join.query.joinedShapes), {
890
+ join.query.joinedShapes = __spreadProps$1(__spreadValues$2({}, join.query.joinedShapes), {
912
891
  [fromQuery.query.as || fromQuery.table]: fromQuery.query.shape
913
892
  });
914
893
  return join;
@@ -1264,6 +1243,16 @@ const applyRelation = (qb, { relationName, relation, dbTable, otherDbTable }, de
1264
1243
  }
1265
1244
  makeRelationQuery(dbTable, relationName, data, query);
1266
1245
  baseQuery.joinQuery = data.joinQuery;
1246
+ const { join: originalJoin } = baseQuery;
1247
+ baseQuery.join = function(...args) {
1248
+ if (args.length) {
1249
+ return originalJoin.apply(this, args);
1250
+ } else {
1251
+ const q = this.clone();
1252
+ q.query.innerJoinLateral = true;
1253
+ return q;
1254
+ }
1255
+ };
1267
1256
  dbTable.relations[relationName] = {
1268
1257
  type,
1269
1258
  key: relationName,
@@ -1314,33 +1303,33 @@ function transaction(fnOrOptions, fn) {
1314
1303
  );
1315
1304
  }
1316
1305
 
1317
- var __defProp$4 = Object.defineProperty;
1318
- var __defProps$2 = Object.defineProperties;
1319
- var __getOwnPropDescs$2 = Object.getOwnPropertyDescriptors;
1320
- var __getOwnPropSymbols$6 = Object.getOwnPropertySymbols;
1321
- var __hasOwnProp$6 = Object.prototype.hasOwnProperty;
1322
- var __propIsEnum$6 = Object.prototype.propertyIsEnumerable;
1323
- var __defNormalProp$4 = (obj, key, value) => key in obj ? __defProp$4(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1324
- var __spreadValues$4 = (a, b) => {
1306
+ var __defProp$1 = Object.defineProperty;
1307
+ var __defProps = Object.defineProperties;
1308
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
1309
+ var __getOwnPropSymbols$1 = Object.getOwnPropertySymbols;
1310
+ var __hasOwnProp$1 = Object.prototype.hasOwnProperty;
1311
+ var __propIsEnum$1 = Object.prototype.propertyIsEnumerable;
1312
+ var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1313
+ var __spreadValues$1 = (a, b) => {
1325
1314
  for (var prop in b || (b = {}))
1326
- if (__hasOwnProp$6.call(b, prop))
1327
- __defNormalProp$4(a, prop, b[prop]);
1328
- if (__getOwnPropSymbols$6)
1329
- for (var prop of __getOwnPropSymbols$6(b)) {
1330
- if (__propIsEnum$6.call(b, prop))
1331
- __defNormalProp$4(a, prop, b[prop]);
1315
+ if (__hasOwnProp$1.call(b, prop))
1316
+ __defNormalProp$1(a, prop, b[prop]);
1317
+ if (__getOwnPropSymbols$1)
1318
+ for (var prop of __getOwnPropSymbols$1(b)) {
1319
+ if (__propIsEnum$1.call(b, prop))
1320
+ __defNormalProp$1(a, prop, b[prop]);
1332
1321
  }
1333
1322
  return a;
1334
1323
  };
1335
- var __spreadProps$2 = (a, b) => __defProps$2(a, __getOwnPropDescs$2(b));
1336
- var __objRest$3 = (source, exclude) => {
1324
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
1325
+ var __objRest = (source, exclude) => {
1337
1326
  var target = {};
1338
1327
  for (var prop in source)
1339
- if (__hasOwnProp$6.call(source, prop) && exclude.indexOf(prop) < 0)
1328
+ if (__hasOwnProp$1.call(source, prop) && exclude.indexOf(prop) < 0)
1340
1329
  target[prop] = source[prop];
1341
- if (source != null && __getOwnPropSymbols$6)
1342
- for (var prop of __getOwnPropSymbols$6(source)) {
1343
- if (exclude.indexOf(prop) < 0 && __propIsEnum$6.call(source, prop))
1330
+ if (source != null && __getOwnPropSymbols$1)
1331
+ for (var prop of __getOwnPropSymbols$1(source)) {
1332
+ if (exclude.indexOf(prop) < 0 && __propIsEnum$1.call(source, prop))
1344
1333
  target[prop] = source[prop];
1345
1334
  }
1346
1335
  return target;
@@ -1351,7 +1340,7 @@ const orchidORM = (_a, tables) => {
1351
1340
  logger,
1352
1341
  autoPreparedStatements,
1353
1342
  noPrimaryKey = "error"
1354
- } = _b, options = __objRest$3(_b, [
1343
+ } = _b, options = __objRest(_b, [
1355
1344
  "log",
1356
1345
  "logger",
1357
1346
  "autoPreparedStatements",
@@ -1398,7 +1387,7 @@ const orchidORM = (_a, tables) => {
1398
1387
  }
1399
1388
  const table = new tables[key]();
1400
1389
  tableInstances[key] = table;
1401
- const options2 = __spreadProps$2(__spreadValues$4({}, commonOptions), {
1390
+ const options2 = __spreadProps(__spreadValues$1({}, commonOptions), {
1402
1391
  schema: table.schema
1403
1392
  });
1404
1393
  if (table.noPrimaryKey)
@@ -1423,24 +1412,24 @@ const orchidORM = (_a, tables) => {
1423
1412
  return result;
1424
1413
  };
1425
1414
 
1426
- var __defProp$3 = Object.defineProperty;
1427
- var __getOwnPropSymbols$5 = Object.getOwnPropertySymbols;
1428
- var __hasOwnProp$5 = Object.prototype.hasOwnProperty;
1429
- var __propIsEnum$5 = Object.prototype.propertyIsEnumerable;
1430
- var __defNormalProp$3 = (obj, key, value) => key in obj ? __defProp$3(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1431
- var __spreadValues$3 = (a, b) => {
1415
+ var __defProp = Object.defineProperty;
1416
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
1417
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
1418
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
1419
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1420
+ var __spreadValues = (a, b) => {
1432
1421
  for (var prop in b || (b = {}))
1433
- if (__hasOwnProp$5.call(b, prop))
1434
- __defNormalProp$3(a, prop, b[prop]);
1435
- if (__getOwnPropSymbols$5)
1436
- for (var prop of __getOwnPropSymbols$5(b)) {
1437
- if (__propIsEnum$5.call(b, prop))
1438
- __defNormalProp$3(a, prop, b[prop]);
1422
+ if (__hasOwnProp.call(b, prop))
1423
+ __defNormalProp(a, prop, b[prop]);
1424
+ if (__getOwnPropSymbols)
1425
+ for (var prop of __getOwnPropSymbols(b)) {
1426
+ if (__propIsEnum.call(b, prop))
1427
+ __defNormalProp(a, prop, b[prop]);
1439
1428
  }
1440
1429
  return a;
1441
1430
  };
1442
1431
  const createRepo = (table, methods) => {
1443
- const queryMethods = __spreadValues$3(__spreadValues$3(__spreadValues$3(__spreadValues$3({}, methods.queryMethods), methods.queryOneMethods), methods.queryWithWhereMethods), methods.queryOneWithWhereMethods);
1432
+ const queryMethods = __spreadValues(__spreadValues(__spreadValues(__spreadValues({}, methods.queryMethods), methods.queryOneMethods), methods.queryWithWhereMethods), methods.queryOneWithWhereMethods);
1444
1433
  const plainMethods = methods.methods;
1445
1434
  const repo = (q2) => {
1446
1435
  const proto = Object.create(q2.baseQuery);
@@ -1466,1373 +1455,6 @@ const createRepo = (table, methods) => {
1466
1455
  });
1467
1456
  };
1468
1457
 
1469
- class FileChanges {
1470
- constructor(content) {
1471
- this.content = content;
1472
- this.ranges = [];
1473
- }
1474
- add(at, text, end = at) {
1475
- if (this.ranges.length === 0) {
1476
- this.ranges.push([0, at], text, [end, this.content.length]);
1477
- } else {
1478
- const last = this.ranges[this.ranges.length - 1];
1479
- last[1] = at;
1480
- this.ranges.push(text, [end, this.content.length]);
1481
- }
1482
- }
1483
- replace(from, to, text) {
1484
- this.add(from, text, to);
1485
- }
1486
- remove(from, to) {
1487
- if (this.ranges.length === 0) {
1488
- this.ranges.push([0, from], [to, this.content.length]);
1489
- } else {
1490
- const last = this.ranges[this.ranges.length - 1];
1491
- last[1] = from;
1492
- this.ranges.push([to, this.content.length]);
1493
- }
1494
- }
1495
- apply() {
1496
- return this.ranges.length ? this.ranges.map(
1497
- (item) => typeof item === "string" ? item : this.content.slice(item[0], item[1])
1498
- ).join("") : this.content;
1499
- }
1500
- }
1501
-
1502
- const { createSourceFile, ScriptTarget, SyntaxKind } = typescript;
1503
- const iterate = (kind) => {
1504
- return function* (statements) {
1505
- for (const node of statements) {
1506
- if (node.kind === kind) {
1507
- yield node;
1508
- }
1509
- }
1510
- };
1511
- };
1512
- const isNode = (kind) => {
1513
- return (node) => {
1514
- return (node == null ? void 0 : node.kind) === kind;
1515
- };
1516
- };
1517
- const ts = {
1518
- getStatements(content) {
1519
- const { statements } = createSourceFile(
1520
- "file.ts",
1521
- content,
1522
- ScriptTarget.Latest,
1523
- true
1524
- );
1525
- return statements;
1526
- },
1527
- is: {
1528
- call: isNode(SyntaxKind.CallExpression),
1529
- objectLiteral: isNode(
1530
- SyntaxKind.ObjectLiteralExpression
1531
- ),
1532
- propertyAssignment: isNode(
1533
- SyntaxKind.PropertyAssignment
1534
- ),
1535
- shorthandPropertyAssignment: isNode(
1536
- SyntaxKind.ShorthandPropertyAssignment
1537
- ),
1538
- identifier: isNode(SyntaxKind.Identifier),
1539
- stringLiteral: isNode(SyntaxKind.StringLiteral),
1540
- arrayLiteral: isNode(
1541
- SyntaxKind.ArrayLiteralExpression
1542
- ),
1543
- numericLiteral: isNode(SyntaxKind.NumericLiteral),
1544
- computedPropertyName: isNode(
1545
- SyntaxKind.ComputedPropertyName
1546
- ),
1547
- privateIdentifier: isNode(SyntaxKind.PrivateIdentifier),
1548
- this: isNode(SyntaxKind.ThisKeyword),
1549
- propertyAccess: isNode(
1550
- SyntaxKind.PropertyAccessExpression
1551
- ),
1552
- arrowFunction: isNode(SyntaxKind.ArrowFunction),
1553
- parenthesizedExpression: isNode(
1554
- SyntaxKind.ParenthesizedExpression
1555
- ),
1556
- spreadAssignment: isNode(SyntaxKind.SpreadAssignment)
1557
- },
1558
- import: {
1559
- iterate: iterate(SyntaxKind.ImportDeclaration),
1560
- *iterateWithSource(statements, path) {
1561
- for (const node of ts.import.iterate(statements)) {
1562
- if (ts.import.getSource(node) !== path)
1563
- continue;
1564
- yield node;
1565
- }
1566
- },
1567
- getSource(node) {
1568
- return node.moduleSpecifier.getText().slice(1, -1);
1569
- },
1570
- getEndPos(statements) {
1571
- let end = 0;
1572
- for (const node of ts.import.iterate(statements)) {
1573
- end = node.end;
1574
- }
1575
- return end;
1576
- },
1577
- getStatementsImportedName(statements, path, key) {
1578
- for (const node of ts.import.iterateWithSource(statements, path)) {
1579
- const name = ts.import.getImportName(node, key);
1580
- if (name)
1581
- return name;
1582
- }
1583
- return;
1584
- },
1585
- getImportName(node, key) {
1586
- var _a, _b;
1587
- if (!node.importClause)
1588
- return;
1589
- const elements = (_a = node.importClause.namedBindings) == null ? void 0 : _a.elements;
1590
- if (!elements)
1591
- return;
1592
- for (const element of elements) {
1593
- if (((_b = element.propertyName) == null ? void 0 : _b.escapedText) === key || element.name.escapedText === key) {
1594
- return element.name.escapedText.toString();
1595
- }
1596
- }
1597
- return;
1598
- }
1599
- },
1600
- variable: {
1601
- iterate: iterate(SyntaxKind.VariableStatement),
1602
- *iterateDeclarations(statements) {
1603
- for (const node of ts.variable.iterate(statements)) {
1604
- for (const dec of node.declarationList.declarations) {
1605
- yield dec;
1606
- }
1607
- }
1608
- }
1609
- },
1610
- class: {
1611
- iterate: iterate(SyntaxKind.ClassDeclaration)
1612
- },
1613
- prop: {
1614
- getName({ name }) {
1615
- if (ts.is.identifier(name)) {
1616
- return name.escapedText;
1617
- } else {
1618
- return name == null ? void 0 : name.getText();
1619
- }
1620
- },
1621
- getValue(prop) {
1622
- if (ts.is.propertyAssignment(prop)) {
1623
- return prop.initializer.getText();
1624
- } else if (ts.is.shorthandPropertyAssignment(prop)) {
1625
- return prop.name.escapedText.toString();
1626
- } else {
1627
- return;
1628
- }
1629
- }
1630
- },
1631
- spaces: {
1632
- getAtLine(content, pos) {
1633
- var _a;
1634
- const lines = content.slice(0, pos).split("\n");
1635
- const last = lines[lines.length - 1];
1636
- return ((_a = last.match(/^\s+/)) == null ? void 0 : _a[0]) || "";
1637
- }
1638
- }
1639
- };
1640
-
1641
- const libraryName = "orchid-orm";
1642
- const importKey = "orchidORM";
1643
- const newFile = (options) => `import { orchidORM } from 'orchid-orm';
1644
-
1645
- export const db = orchidORM(
1646
- {
1647
- ${optionsToString(options)}
1648
- },
1649
- {
1650
- }
1651
- );
1652
- `;
1653
- const optionsToString = (options) => {
1654
- const lines = [];
1655
- for (const key in options) {
1656
- const value = options[key];
1657
- if (typeof value !== "object" && typeof value !== "function") {
1658
- lines.push(
1659
- `${key}: ${typeof value === "string" ? orchidCore.singleQuote(value) : value},`
1660
- );
1661
- }
1662
- }
1663
- return lines.join("\n ");
1664
- };
1665
- const updateMainFile = async (filePath, tablePath, ast, options, logger) => {
1666
- const result = await fs.readFile(filePath, "utf-8").then(
1667
- (content2) => ({ error: void 0, content: content2 }),
1668
- (error) => {
1669
- return { error, content: void 0 };
1670
- }
1671
- );
1672
- if (result.error && result.error.code !== "ENOENT")
1673
- throw result.error;
1674
- const content = result.content || newFile(options);
1675
- const statements = ts.getStatements(content);
1676
- const importName = ts.import.getStatementsImportedName(
1677
- statements,
1678
- libraryName,
1679
- importKey
1680
- );
1681
- if (!importName) {
1682
- throw new AppCodeUpdaterError(
1683
- `Main file does not contain import of orchid-orm`
1684
- );
1685
- }
1686
- const object = getTablesListObject(importName, statements);
1687
- if (!object) {
1688
- throw new Error("List of tables is not found in main file");
1689
- }
1690
- const spaces = ts.spaces.getAtLine(content, object.end);
1691
- const context = {
1692
- filePath,
1693
- tablePath,
1694
- statements,
1695
- object,
1696
- content,
1697
- spaces
1698
- };
1699
- let write;
1700
- if (ast.type === "table") {
1701
- if (ast.action === "create") {
1702
- write = createTable$1(context, ast);
1703
- } else {
1704
- write = dropTable(context, ast);
1705
- }
1706
- }
1707
- if (write) {
1708
- if (result.error) {
1709
- await fs.mkdir(path.dirname(filePath), { recursive: true });
1710
- }
1711
- await fs.writeFile(filePath, write);
1712
- logger == null ? void 0 : logger.log(
1713
- `${result.content ? "Updated" : "Created"} ${orchidCore.pathToLog(filePath)}`
1714
- );
1715
- }
1716
- };
1717
- const createTable$1 = ({ filePath, tablePath, statements, object, content, spaces }, ast) => {
1718
- const key = orchidCore.toCamelCase(ast.name);
1719
- const value = `${orchidCore.toPascalCase(ast.name)}Table`;
1720
- const changes = new FileChanges(content);
1721
- const importPath = orchidCore.getImportPath(filePath, tablePath(orchidCore.toCamelCase(ast.name)));
1722
- const existing = Array.from(
1723
- ts.import.iterateWithSource(statements, importPath)
1724
- );
1725
- if (existing.length)
1726
- return;
1727
- for (const prop of object.properties) {
1728
- if (key === ts.prop.getName(prop)) {
1729
- return;
1730
- }
1731
- }
1732
- const importPos = ts.import.getEndPos(statements);
1733
- changes.add(
1734
- importPos,
1735
- `${importPos === 0 ? "" : "\n"}import { ${value} } from '${importPath}';`
1736
- );
1737
- let insert = `
1738
- ${spaces} ${key}: ${value},`;
1739
- if (object.properties.length && !object.properties.hasTrailingComma) {
1740
- insert = `,${insert}`;
1741
- }
1742
- if (!content.slice(object.properties.end, object.end).includes("\n")) {
1743
- insert += `
1744
- ${spaces}`;
1745
- }
1746
- changes.add(object.properties.end, insert);
1747
- return changes.apply();
1748
- };
1749
- const dropTable = ({ filePath, tablePath, statements, object, content }, ast) => {
1750
- const changes = new FileChanges(content);
1751
- const importPath = orchidCore.getImportPath(filePath, tablePath(orchidCore.toCamelCase(ast.name)));
1752
- const tableClassName = `${orchidCore.toPascalCase(ast.name)}Table`;
1753
- const importNames = [];
1754
- for (const node of ts.import.iterateWithSource(statements, importPath)) {
1755
- changes.remove(node.pos, node.end);
1756
- const name = ts.import.getImportName(node, tableClassName);
1757
- if (name && !importNames.includes(name)) {
1758
- importNames.push(name);
1759
- }
1760
- }
1761
- for (const prop of object.properties) {
1762
- const name = ts.prop.getValue(prop);
1763
- if (!name || !importNames.includes(name))
1764
- continue;
1765
- let { end } = prop;
1766
- if (content[end] === ",")
1767
- end++;
1768
- changes.remove(prop.pos, end);
1769
- }
1770
- return changes.apply();
1771
- };
1772
- const getTablesListObject = (importName, statements) => {
1773
- for (const node of ts.variable.iterateDeclarations(statements)) {
1774
- const call = node.initializer;
1775
- if (!ts.is.call(call))
1776
- continue;
1777
- if (call.expression.getText() !== importName)
1778
- continue;
1779
- if (call.arguments.length !== 2) {
1780
- throw new Error(
1781
- "Invalid number of arguments when initializing orchid orm"
1782
- );
1783
- }
1784
- const object = call.arguments[1];
1785
- if (!ts.is.objectLiteral(object)) {
1786
- throw new Error("Second argument of orchidORM must be an object literal");
1787
- }
1788
- return object;
1789
- }
1790
- return;
1791
- };
1792
-
1793
- const handleForeignKey = async ({
1794
- getTable,
1795
- relations,
1796
- tableName,
1797
- columns,
1798
- foreignTableName,
1799
- foreignColumns,
1800
- skipBelongsTo
1801
- }) => {
1802
- var _a, _b;
1803
- const table = await getTable(tableName);
1804
- if (!table)
1805
- return;
1806
- const foreignTable = await getTable(foreignTableName);
1807
- if (!foreignTable)
1808
- return;
1809
- if (!skipBelongsTo) {
1810
- (_a = relations[tableName]) != null ? _a : relations[tableName] = {
1811
- path: table.path,
1812
- relations: []
1813
- };
1814
- relations[tableName].relations.push({
1815
- kind: "belongsTo",
1816
- columns,
1817
- className: foreignTable.name,
1818
- path: foreignTable.path,
1819
- foreignColumns
1820
- });
1821
- }
1822
- (_b = relations[foreignTableName]) != null ? _b : relations[foreignTableName] = {
1823
- path: foreignTable.path,
1824
- relations: []
1825
- };
1826
- relations[foreignTableName].relations.push({
1827
- kind: "hasMany",
1828
- columns: foreignColumns,
1829
- className: table.name,
1830
- path: table.path,
1831
- foreignColumns: columns
1832
- });
1833
- };
1834
-
1835
- var __getOwnPropSymbols$4 = Object.getOwnPropertySymbols;
1836
- var __hasOwnProp$4 = Object.prototype.hasOwnProperty;
1837
- var __propIsEnum$4 = Object.prototype.propertyIsEnumerable;
1838
- var __objRest$2 = (source, exclude) => {
1839
- var target = {};
1840
- for (var prop in source)
1841
- if (__hasOwnProp$4.call(source, prop) && exclude.indexOf(prop) < 0)
1842
- target[prop] = source[prop];
1843
- if (source != null && __getOwnPropSymbols$4)
1844
- for (var prop of __getOwnPropSymbols$4(source)) {
1845
- if (exclude.indexOf(prop) < 0 && __propIsEnum$4.call(source, prop))
1846
- target[prop] = source[prop];
1847
- }
1848
- return target;
1849
- };
1850
- const createTable = async (_a) => {
1851
- var _b = _a, {
1852
- ast,
1853
- logger,
1854
- getTable,
1855
- relations,
1856
- tables
1857
- } = _b, params = __objRest$2(_b, [
1858
- "ast",
1859
- "logger",
1860
- "getTable",
1861
- "relations",
1862
- "tables"
1863
- ]);
1864
- const key = orchidCore.toCamelCase(ast.name);
1865
- const tablePath = params.tablePath(key);
1866
- const baseTablePath = orchidCore.getImportPath(tablePath, params.baseTable.filePath);
1867
- const className = `${orchidCore.toPascalCase(ast.name)}Table`;
1868
- tables[ast.name] = {
1869
- key,
1870
- name: className,
1871
- path: tablePath
1872
- };
1873
- const imports = {
1874
- [baseTablePath]: params.baseTable.name
1875
- };
1876
- const props = [];
1877
- if (ast.schema) {
1878
- props.push(`schema = ${orchidCore.singleQuote(ast.schema)};`);
1879
- }
1880
- props.push(`readonly table = ${orchidCore.singleQuote(ast.name)};`);
1881
- if (ast.noPrimaryKey === "ignore") {
1882
- props.push("noPrimaryKey = true;");
1883
- }
1884
- props.push(
1885
- "columns = this.setColumns((t) => ({",
1886
- pqb.columnsShapeToCode(ast.shape, ast, "t"),
1887
- "}));"
1888
- );
1889
- const relCode = await getRelations(
1890
- ast,
1891
- getTable,
1892
- tablePath,
1893
- imports,
1894
- relations,
1895
- ast.name
1896
- );
1897
- if (relCode) {
1898
- props.push("", ...relCode);
1899
- }
1900
- const code = [
1901
- ...Object.entries(imports).map(
1902
- ([from, name]) => `import { ${name} } from '${from}';`
1903
- ),
1904
- "",
1905
- `export class ${className} extends ${params.baseTable.name} {`,
1906
- props,
1907
- "}\n"
1908
- ];
1909
- await fs.mkdir(path.dirname(tablePath), { recursive: true });
1910
- try {
1911
- await fs.writeFile(tablePath, orchidCore.codeToString(code, "", " "), { flag: "wx" });
1912
- logger == null ? void 0 : logger.log(`Created ${orchidCore.pathToLog(tablePath)}`);
1913
- } catch (err) {
1914
- if (err.code !== "EEXIST") {
1915
- throw err;
1916
- }
1917
- }
1918
- };
1919
- const getRelations = async (ast, getTable, tablePath, imports, relations, tableName) => {
1920
- const refs = [];
1921
- for (const key in ast.shape) {
1922
- const item = ast.shape[key];
1923
- if (!(item instanceof pqb.ColumnType) || !item.data.foreignKeys)
1924
- continue;
1925
- for (const fkey of item.data.foreignKeys) {
1926
- if ("table" in fkey) {
1927
- refs.push({
1928
- table: fkey.table,
1929
- columns: [key],
1930
- foreignColumns: fkey.columns
1931
- });
1932
- }
1933
- }
1934
- }
1935
- if (ast.constraints) {
1936
- for (const { references: ref } of ast.constraints) {
1937
- if (ref && typeof ref.fnOrTable === "string") {
1938
- refs.push({
1939
- table: ref.fnOrTable,
1940
- columns: ref.columns,
1941
- foreignColumns: ref.foreignColumns
1942
- });
1943
- }
1944
- }
1945
- }
1946
- if (!refs.length)
1947
- return;
1948
- const code = [];
1949
- for (const ref of refs) {
1950
- const { columns, foreignColumns } = ref;
1951
- if (columns.length > 1 || foreignColumns.length > 1)
1952
- continue;
1953
- const info = await getTable(ref.table);
1954
- if (!info)
1955
- continue;
1956
- const path2 = orchidCore.getImportPath(tablePath, info.path);
1957
- imports[path2] = info.name;
1958
- code.push(
1959
- `${info.key}: this.belongsTo(() => ${info.name}, {`,
1960
- [`primaryKey: '${foreignColumns[0]}',`, `foreignKey: '${columns[0]}',`],
1961
- "}),"
1962
- );
1963
- await handleForeignKey({
1964
- getTable,
1965
- relations,
1966
- tableName,
1967
- columns: ref.columns,
1968
- foreignTableName: ref.table,
1969
- foreignColumns: ref.foreignColumns,
1970
- skipBelongsTo: true
1971
- });
1972
- }
1973
- return code.length ? ["relations = {", code, "};"] : void 0;
1974
- };
1975
-
1976
- var __defProp$2 = Object.defineProperty;
1977
- var __getOwnPropSymbols$3 = Object.getOwnPropertySymbols;
1978
- var __hasOwnProp$3 = Object.prototype.hasOwnProperty;
1979
- var __propIsEnum$3 = Object.prototype.propertyIsEnumerable;
1980
- var __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1981
- var __spreadValues$2 = (a, b) => {
1982
- for (var prop in b || (b = {}))
1983
- if (__hasOwnProp$3.call(b, prop))
1984
- __defNormalProp$2(a, prop, b[prop]);
1985
- if (__getOwnPropSymbols$3)
1986
- for (var prop of __getOwnPropSymbols$3(b)) {
1987
- if (__propIsEnum$3.call(b, prop))
1988
- __defNormalProp$2(a, prop, b[prop]);
1989
- }
1990
- return a;
1991
- };
1992
- var __objRest$1 = (source, exclude) => {
1993
- var target = {};
1994
- for (var prop in source)
1995
- if (__hasOwnProp$3.call(source, prop) && exclude.indexOf(prop) < 0)
1996
- target[prop] = source[prop];
1997
- if (source != null && __getOwnPropSymbols$3)
1998
- for (var prop of __getOwnPropSymbols$3(source)) {
1999
- if (exclude.indexOf(prop) < 0 && __propIsEnum$3.call(source, prop))
2000
- target[prop] = source[prop];
2001
- }
2002
- return target;
2003
- };
2004
- const changeTable = async (_a) => {
2005
- var _b = _a, {
2006
- ast,
2007
- logger
2008
- } = _b, params = __objRest$1(_b, [
2009
- "ast",
2010
- "logger"
2011
- ]);
2012
- const tablePath = params.tablePath(orchidCore.toCamelCase(ast.name));
2013
- const content = await fs.readFile(tablePath, "utf-8").catch(() => void 0);
2014
- if (!content)
2015
- return;
2016
- const changes = new FileChanges(content);
2017
- const statements = ts.getStatements(content);
2018
- const className = orchidCore.toPascalCase(ast.name) + "Table";
2019
- for (const { t, object } of iterateColumnsShapes(statements, className)) {
2020
- const context = makeChangeContext(changes, ast, content, object, t);
2021
- prependSpaces(context);
2022
- applySchemaChanges(context);
2023
- appendTrailingComma(context);
2024
- addColumns(context);
2025
- addTableData(context);
2026
- }
2027
- await fs.writeFile(tablePath, changes.apply());
2028
- logger == null ? void 0 : logger.log(`Updated ${orchidCore.pathToLog(tablePath)}`);
2029
- };
2030
- function* iterateColumnsShapes(statements, className) {
2031
- var _a, _b;
2032
- for (const node of ts.class.iterate(statements)) {
2033
- if (((_a = node.name) == null ? void 0 : _a.escapedText) !== className)
2034
- continue;
2035
- for (const member of node.members) {
2036
- const name = ts.prop.getName(member);
2037
- const { initializer: call } = member;
2038
- if (name !== "columns" || !call || !ts.is.call(call))
2039
- continue;
2040
- const { expression } = call;
2041
- if (!ts.is.propertyAccess(expression) || !ts.is.this(expression.expression) || expression.name.escapedText !== "setColumns")
2042
- continue;
2043
- const [arg] = call.arguments;
2044
- if (!ts.is.arrowFunction(arg))
2045
- continue;
2046
- const { parameters, body } = arg;
2047
- const param = (_b = parameters[0]) == null ? void 0 : _b.name;
2048
- if (!ts.is.identifier(param) || !ts.is.parenthesizedExpression(body))
2049
- continue;
2050
- const { expression: object } = body;
2051
- if (!ts.is.objectLiteral(object))
2052
- continue;
2053
- yield { t: param.escapedText.toString(), object };
2054
- }
2055
- }
2056
- }
2057
- const makeChangeContext = (changes, ast, content, object, t) => {
2058
- const add = {};
2059
- const drop = {};
2060
- const change = {};
2061
- const { properties: props } = object;
2062
- const existingColumns = getExistingColumns(props);
2063
- for (const key in ast.shape) {
2064
- const item = ast.shape[key];
2065
- if (item.type === "add" && !existingColumns[key]) {
2066
- add[key] = item.item;
2067
- }
2068
- if (!existingColumns[key])
2069
- continue;
2070
- if (item.type === "drop" && existingColumns[key]) {
2071
- drop[key] = true;
2072
- } else if (item.type === "change" && existingColumns[key]) {
2073
- change[key] = item;
2074
- }
2075
- }
2076
- const spaces = ts.spaces.getAtLine(content, object.end);
2077
- const shape = { add, drop, change };
2078
- return {
2079
- changes,
2080
- props,
2081
- shape,
2082
- spaces,
2083
- t,
2084
- object,
2085
- add: ast.add,
2086
- drop: ast.drop
2087
- };
2088
- };
2089
- const getExistingColumns = (props) => {
2090
- const existingColumns = {};
2091
- props.map((prop) => ts.is.propertyAssignment(prop) && ts.prop.getName(prop)).filter((name) => !!name).forEach((name) => existingColumns[name] = true);
2092
- for (const prop of props) {
2093
- if (!ts.is.propertyAssignment(prop))
2094
- continue;
2095
- const name = ts.prop.getName(prop);
2096
- if (name)
2097
- existingColumns[name] = true;
2098
- }
2099
- return existingColumns;
2100
- };
2101
- const prependSpaces = ({
2102
- props,
2103
- shape: { add },
2104
- changes,
2105
- spaces
2106
- }) => {
2107
- if (Object.keys(add).length && props.pos === props.end) {
2108
- changes.add(props.pos, `
2109
- ${spaces}`);
2110
- }
2111
- };
2112
- const applySchemaChanges = (context) => {
2113
- const {
2114
- props,
2115
- shape: { drop: dropColumns, change: changeColumns },
2116
- add,
2117
- drop
2118
- } = context;
2119
- props.forEach((prop, i) => {
2120
- if (ts.is.spreadAssignment(prop)) {
2121
- const call = prop.expression;
2122
- if (!ts.is.call(call))
2123
- return;
2124
- const access = call.expression;
2125
- if (!ts.is.propertyAccess(access))
2126
- return;
2127
- const name = access.name.escapedText.toString();
2128
- if (name === "primaryKey") {
2129
- if (drop.primaryKey || add.primaryKey) {
2130
- removeProp(context, prop, i);
2131
- }
2132
- } else if (name === "index") {
2133
- dropMatchingIndexes(context, prop, i, call, drop.indexes);
2134
- } else if (name === "foreignKey") {
2135
- dropMatchingForeignKey(context, prop, i, call, drop.constraints);
2136
- } else if (name === "check") {
2137
- dropMatchingCheck(context, prop, i, call, drop.constraints);
2138
- } else if (name === "constraint") {
2139
- dropMatchingConstraint(context, prop, i, call, drop.constraints);
2140
- }
2141
- } else if (ts.is.propertyAssignment(prop)) {
2142
- const name = ts.prop.getName(prop);
2143
- if (!name)
2144
- return;
2145
- if (dropColumns[name]) {
2146
- removeProp(context, prop, i);
2147
- } else {
2148
- const changeItem = changeColumns[name];
2149
- if (changeItem) {
2150
- changeColumn(context, changeItem, prop);
2151
- }
2152
- }
2153
- }
2154
- });
2155
- };
2156
- const removeProp = ({ props, changes }, prop, i) => {
2157
- var _a;
2158
- const end = ((_a = props[i + 1]) == null ? void 0 : _a.pos) || props.end;
2159
- changes.remove(prop.pos, end);
2160
- };
2161
- const changeColumn = ({ changes, t, spaces }, changeItem, prop) => {
2162
- const { from, to } = changeItem;
2163
- if ((from.type !== to.type || !!from.identity !== !!to.identity) && to.column) {
2164
- changes.replace(
2165
- prop.initializer.pos,
2166
- prop.end,
2167
- ` ${orchidCore.codeToString(to.column.toCode(t), spaces + " ", " ").trim()}`
2168
- );
2169
- return;
2170
- }
2171
- const items = [];
2172
- let chain = prop.initializer;
2173
- while (ts.is.call(chain) && ts.is.propertyAccess(chain.expression)) {
2174
- items.push(chain);
2175
- chain = chain.expression.expression;
2176
- }
2177
- const propsToChange = {};
2178
- for (const key in from) {
2179
- if (to[key] !== from[key]) {
2180
- propsToChange[key] = true;
2181
- }
2182
- }
2183
- for (const key in to) {
2184
- if (to[key] !== from[key]) {
2185
- propsToChange[key] = true;
2186
- }
2187
- }
2188
- const changedProps = {};
2189
- const replaced = {};
2190
- for (const item of items.reverse()) {
2191
- if (!ts.is.propertyAccess(item.expression))
2192
- continue;
2193
- const { name } = item.expression;
2194
- let key = name.escapedText.toString();
2195
- if (key === "index")
2196
- key = "indexes";
2197
- else if (key === "foreignKey")
2198
- key = "foreignKeys";
2199
- if (!propsToChange[key])
2200
- continue;
2201
- let remove = true;
2202
- if (!replaced[key]) {
2203
- let code = getColumnMethodArgs(t, to, key, to.type);
2204
- if (!code && key === "identity" && to.type) {
2205
- code = [`.${to.type}()`];
2206
- }
2207
- if (code) {
2208
- changes.replace(
2209
- item.expression.expression.end,
2210
- item.end,
2211
- orchidCore.codeToString(code, spaces + " ", " ").trim()
2212
- );
2213
- replaced[key] = true;
2214
- remove = false;
2215
- }
2216
- }
2217
- if (remove) {
2218
- changes.remove(item.expression.expression.end, item.end);
2219
- }
2220
- changedProps[key] = true;
2221
- }
2222
- let append = "";
2223
- for (const key in propsToChange) {
2224
- if (changedProps[key])
2225
- continue;
2226
- const code = getColumnMethodArgs(t, to, key);
2227
- if (code) {
2228
- append += orchidCore.codeToString(code, spaces + " ", " ").trim();
2229
- }
2230
- }
2231
- if (append) {
2232
- changes.add(prop.end, append);
2233
- }
2234
- };
2235
- const appendTrailingComma = ({ props, changes }) => {
2236
- if (!props.hasTrailingComma) {
2237
- const last = props[props.length - 1];
2238
- if (last) {
2239
- changes.add(last.end, ",");
2240
- }
2241
- }
2242
- };
2243
- const addColumns = ({
2244
- shape: { add },
2245
- changes,
2246
- object,
2247
- t,
2248
- spaces
2249
- }) => {
2250
- const end = object.end - 1;
2251
- for (const key in add) {
2252
- const code = orchidCore.codeToString(add[key].toCode(t), spaces + " ", " ");
2253
- changes.add(end, ` ${orchidCore.quoteObjectKey(key)}: ${code.trim()},
2254
- ${spaces}`);
2255
- }
2256
- };
2257
- const addTableData = ({ add, changes, object, t, spaces }) => {
2258
- const end = object.end - 1;
2259
- if (add.primaryKey) {
2260
- const code = orchidCore.codeToString(
2261
- pqb.primaryKeyToCode(add.primaryKey, t),
2262
- spaces,
2263
- " "
2264
- );
2265
- changes.add(end, ` ${code.trim()}
2266
- ${spaces}`);
2267
- }
2268
- if (add.indexes) {
2269
- for (const item of add.indexes) {
2270
- const code = orchidCore.codeToString(pqb.indexToCode(item, t), spaces + " ", " ");
2271
- changes.add(end, ` ${code.trim()}
2272
- ${spaces}`);
2273
- }
2274
- }
2275
- if (add.constraints) {
2276
- for (const item of add.constraints) {
2277
- const code = orchidCore.codeToString(pqb.constraintToCode(item, t), spaces + " ", " ");
2278
- changes.add(end, ` ${code.trim()}
2279
- ${spaces}`);
2280
- }
2281
- }
2282
- };
2283
- const getColumnMethodArgs = (t, to, key, dataType) => {
2284
- const value = to[key];
2285
- if (!value)
2286
- return;
2287
- if (key === "indexes") {
2288
- return pqb.columnIndexesToCode(
2289
- value
2290
- );
2291
- }
2292
- if (key === "foreignKeys") {
2293
- return pqb.columnForeignKeysToCode(value);
2294
- }
2295
- if (key === "check") {
2296
- return [pqb.columnCheckToCode(t, value)];
2297
- }
2298
- if (key === "identity") {
2299
- const code2 = pqb.identityToCode(value, dataType);
2300
- code2[0] = `.${code2[0]}`;
2301
- return code2;
2302
- }
2303
- const code = [`.${key}(`];
2304
- if (key === "collate" || key === "compression") {
2305
- orchidCore.addCode(code, orchidCore.singleQuote(value));
2306
- } else if (key === "default") {
2307
- orchidCore.addCode(code, orchidCore.columnDefaultArgumentToCode(t, value));
2308
- } else if (key !== "nullable" && key !== "primaryKey") {
2309
- return;
2310
- }
2311
- orchidCore.addCode(code, ")");
2312
- return code;
2313
- };
2314
- const dropMatchingIndexes = (context, prop, i, call, items) => {
2315
- if (!(items == null ? void 0 : items.length))
2316
- return;
2317
- const [columnsNode, optionsNode] = call.arguments;
2318
- const columns = [];
2319
- if (ts.is.stringLiteral(columnsNode)) {
2320
- columns.push({ column: columnsNode.text });
2321
- } else if (ts.is.arrayLiteral(columnsNode)) {
2322
- for (const node of columnsNode.elements) {
2323
- if (ts.is.stringLiteral(node)) {
2324
- columns.push({ column: node.text });
2325
- } else if (ts.is.objectLiteral(node)) {
2326
- const object = collectObjectFromCode(node);
2327
- if (!object)
2328
- return;
2329
- columns.push(object);
2330
- }
2331
- }
2332
- } else {
2333
- return;
2334
- }
2335
- const options = ts.is.objectLiteral(optionsNode) && collectObjectFromCode(optionsNode) || {};
2336
- for (const item of items) {
2337
- if (orchidCore.deepCompare(columns, item.columns) && orchidCore.deepCompare(options, item.options)) {
2338
- removeProp(context, prop, i);
2339
- }
2340
- }
2341
- };
2342
- const dropMatchingForeignKey = (context, prop, i, call, items) => {
2343
- if (!(items == null ? void 0 : items.length))
2344
- return;
2345
- const existing = parseReferencesArgs(context, call.arguments);
2346
- if (!existing)
2347
- return;
2348
- for (const item of items) {
2349
- if (compareReferences(existing, item.references))
2350
- removeProp(context, prop, i);
2351
- }
2352
- };
2353
- const parseReferencesArgs = (context, args) => {
2354
- const columns = collectStringArrayFromCode(args[0]);
2355
- if (!columns)
2356
- return;
2357
- const fnOrTableNode = args[1];
2358
- let fnOrTable;
2359
- if (ts.is.stringLiteral(fnOrTableNode)) {
2360
- fnOrTable = fnOrTableNode.text;
2361
- } else if (ts.is.arrowFunction(fnOrTableNode)) {
2362
- fnOrTable = context.changes.content.slice(fnOrTableNode.pos, fnOrTableNode.end).replaceAll(/\s/g, "");
2363
- } else {
2364
- return;
2365
- }
2366
- const foreignColumns = collectStringArrayFromCode(args[2]);
2367
- if (!foreignColumns)
2368
- return;
2369
- const options = ts.is.objectLiteral(args[3]) && collectObjectFromCode(args[3]) || {};
2370
- return { columns, fnOrTable, foreignColumns, options };
2371
- };
2372
- const compareReferences = (existing, item) => {
2373
- if (!item)
2374
- return;
2375
- const itemOptions = item.options ? __spreadValues$2({}, item.options) : void 0;
2376
- if (itemOptions) {
2377
- delete itemOptions.dropMode;
2378
- }
2379
- return orchidCore.deepCompare(existing == null ? void 0 : existing.columns, item == null ? void 0 : item.columns) && orchidCore.deepCompare(existing == null ? void 0 : existing.fnOrTable, item == null ? void 0 : item.fnOrTable.toString()) && orchidCore.deepCompare(existing == null ? void 0 : existing.foreignColumns, item == null ? void 0 : item.foreignColumns) && orchidCore.deepCompare(existing == null ? void 0 : existing.options, itemOptions);
2380
- };
2381
- const dropMatchingCheck = (context, prop, i, call, items) => {
2382
- if (!(items == null ? void 0 : items.length))
2383
- return;
2384
- const sql = parseCheckArg(context, call.arguments[0]);
2385
- for (const item of items) {
2386
- const { check } = item;
2387
- if (!check)
2388
- continue;
2389
- if (check.__raw === sql) {
2390
- removeProp(context, prop, i);
2391
- }
2392
- }
2393
- };
2394
- const parseCheckArg = (context, arg) => {
2395
- if (!arg || !ts.is.call(arg))
2396
- return;
2397
- const { expression } = arg;
2398
- if (!ts.is.propertyAccess(expression) || !ts.is.identifier(expression.expression) || expression.expression.escapedText !== context.t || expression.name.escapedText !== "raw")
2399
- return;
2400
- const [sqlArg] = arg.arguments;
2401
- if (!sqlArg || !ts.is.stringLiteral(sqlArg))
2402
- return;
2403
- return sqlArg.text;
2404
- };
2405
- const dropMatchingConstraint = (context, prop, i, call, items) => {
2406
- var _a;
2407
- if (!(items == null ? void 0 : items.length))
2408
- return;
2409
- const {
2410
- arguments: [arg]
2411
- } = call;
2412
- if (!arg || !ts.is.objectLiteral(arg))
2413
- return;
2414
- const existing = {};
2415
- for (const prop2 of arg.properties) {
2416
- if (!ts.is.propertyAssignment(prop2))
2417
- return;
2418
- const name = ts.prop.getName(prop2);
2419
- if (!name)
2420
- return;
2421
- const init = prop2.initializer;
2422
- if (name === "name") {
2423
- if (!ts.is.stringLiteral(init))
2424
- return;
2425
- existing.name = init.text;
2426
- } else if (name === "references") {
2427
- if (!ts.is.arrayLiteral(init))
2428
- return;
2429
- const refs = parseReferencesArgs(context, init.elements);
2430
- if (!refs)
2431
- return;
2432
- existing.references = refs;
2433
- } else if (name === "check") {
2434
- existing.check = parseCheckArg(context, init);
2435
- }
2436
- }
2437
- for (const item of items) {
2438
- if (existing.name !== item.name)
2439
- continue;
2440
- if (existing.check !== ((_a = item.check) == null ? void 0 : _a.__raw))
2441
- continue;
2442
- if ((existing.references || item.references) && !compareReferences(existing.references, item.references))
2443
- continue;
2444
- removeProp(context, prop, i);
2445
- }
2446
- };
2447
- const collectStringArrayFromCode = (node) => {
2448
- if (!ts.is.arrayLiteral(node))
2449
- return;
2450
- const result = node.elements.filter(ts.is.stringLiteral).map((item) => item.text);
2451
- return result.length === node.elements.length ? result : void 0;
2452
- };
2453
- const collectObjectFromCode = (node) => {
2454
- const object = {};
2455
- for (const prop of node.properties) {
2456
- if (!ts.is.propertyAssignment(prop))
2457
- return;
2458
- const name = ts.prop.getName(prop);
2459
- if (!name)
2460
- return;
2461
- const init = prop.initializer;
2462
- if (ts.is.stringLiteral(init)) {
2463
- object[name] = init.text;
2464
- } else if (ts.is.numericLiteral(init)) {
2465
- object[name] = parseFloat(init.text);
2466
- } else {
2467
- return;
2468
- }
2469
- }
2470
- return object;
2471
- };
2472
-
2473
- var __getOwnPropSymbols$2 = Object.getOwnPropertySymbols;
2474
- var __hasOwnProp$2 = Object.prototype.hasOwnProperty;
2475
- var __propIsEnum$2 = Object.prototype.propertyIsEnumerable;
2476
- var __objRest = (source, exclude) => {
2477
- var target = {};
2478
- for (var prop in source)
2479
- if (__hasOwnProp$2.call(source, prop) && exclude.indexOf(prop) < 0)
2480
- target[prop] = source[prop];
2481
- if (source != null && __getOwnPropSymbols$2)
2482
- for (var prop of __getOwnPropSymbols$2(source)) {
2483
- if (exclude.indexOf(prop) < 0 && __propIsEnum$2.call(source, prop))
2484
- target[prop] = source[prop];
2485
- }
2486
- return target;
2487
- };
2488
- const renameTable = async (_a) => {
2489
- var _b = _a, {
2490
- ast,
2491
- logger
2492
- } = _b, params = __objRest(_b, [
2493
- "ast",
2494
- "logger"
2495
- ]);
2496
- var _a2;
2497
- const tablePath = params.tablePath(orchidCore.toCamelCase(ast.from));
2498
- const content = await fs.readFile(tablePath, "utf-8").catch(() => void 0);
2499
- if (!content)
2500
- return;
2501
- const changes = new FileChanges(content);
2502
- const statements = ts.getStatements(content);
2503
- const className = orchidCore.toPascalCase(ast.from) + "Table";
2504
- const changeSchema = ast.fromSchema !== ast.toSchema;
2505
- for (const node of ts.class.iterate(statements)) {
2506
- if (((_a2 = node.name) == null ? void 0 : _a2.escapedText) !== className)
2507
- continue;
2508
- const addSchema = changeSchema && ast.toSchema && !node.members.some((member) => ts.prop.getName(member) === "schema");
2509
- if (addSchema && ast.toSchema) {
2510
- changes.add(
2511
- node.members.pos,
2512
- `
2513
- schema = ${orchidCore.singleQuote(ast.toSchema)};`
2514
- );
2515
- }
2516
- for (const member of node.members) {
2517
- const name = ts.prop.getName(member);
2518
- if (name !== "table" && !(changeSchema && name === "schema"))
2519
- continue;
2520
- const { initializer: value } = member;
2521
- if (!value)
2522
- continue;
2523
- if (name === "schema") {
2524
- if (ast.toSchema) {
2525
- changes.replace(
2526
- value.pos,
2527
- value.end,
2528
- ` ${orchidCore.singleQuote(ast.toSchema)}`
2529
- );
2530
- } else {
2531
- changes.remove(member.pos, member.end);
2532
- }
2533
- } else {
2534
- changes.replace(value.pos, value.end, ` ${orchidCore.singleQuote(ast.to)}`);
2535
- }
2536
- }
2537
- }
2538
- await fs.writeFile(tablePath, changes.apply());
2539
- logger == null ? void 0 : logger.log(`Updated ${orchidCore.pathToLog(tablePath)}`);
2540
- };
2541
-
2542
- var __defProp$1 = Object.defineProperty;
2543
- var __defProps$1 = Object.defineProperties;
2544
- var __getOwnPropDescs$1 = Object.getOwnPropertyDescriptors;
2545
- var __getOwnPropSymbols$1 = Object.getOwnPropertySymbols;
2546
- var __hasOwnProp$1 = Object.prototype.hasOwnProperty;
2547
- var __propIsEnum$1 = Object.prototype.propertyIsEnumerable;
2548
- var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
2549
- var __spreadValues$1 = (a, b) => {
2550
- for (var prop in b || (b = {}))
2551
- if (__hasOwnProp$1.call(b, prop))
2552
- __defNormalProp$1(a, prop, b[prop]);
2553
- if (__getOwnPropSymbols$1)
2554
- for (var prop of __getOwnPropSymbols$1(b)) {
2555
- if (__propIsEnum$1.call(b, prop))
2556
- __defNormalProp$1(a, prop, b[prop]);
2557
- }
2558
- return a;
2559
- };
2560
- var __spreadProps$1 = (a, b) => __defProps$1(a, __getOwnPropDescs$1(b));
2561
- const updateTableFile = async (params) => {
2562
- const { ast } = params;
2563
- if (ast.type === "table" && ast.action === "create") {
2564
- await createTable(__spreadProps$1(__spreadValues$1({}, params), { ast }));
2565
- } else if (ast.type === "changeTable") {
2566
- await changeTable(__spreadProps$1(__spreadValues$1({}, params), { ast }));
2567
- } else if (ast.type === "renameTable") {
2568
- await renameTable(__spreadProps$1(__spreadValues$1({}, params), { ast }));
2569
- } else if (ast.type === "constraint" && ast.references) {
2570
- const ref = ast.references;
2571
- if (typeof ref.fnOrTable === "string") {
2572
- await handleForeignKey({
2573
- getTable: params.getTable,
2574
- relations: params.relations,
2575
- tableName: ast.tableName,
2576
- columns: ref.columns,
2577
- foreignTableName: ref.fnOrTable,
2578
- foreignColumns: ref.foreignColumns
2579
- });
2580
- }
2581
- }
2582
- };
2583
-
2584
- const createBaseTableFile = async ({
2585
- baseTable,
2586
- logger
2587
- }) => {
2588
- await fs.mkdir(path.dirname(baseTable.filePath), { recursive: true });
2589
- await fs.writeFile(
2590
- baseTable.filePath,
2591
- `import { createBaseTable } from 'orchid-orm';
2592
-
2593
- export const ${baseTable.name} = createBaseTable();
2594
- `,
2595
- {
2596
- flag: "wx"
2597
- }
2598
- ).then(() => {
2599
- logger == null ? void 0 : logger.log(`Created ${orchidCore.pathToLog(baseTable.filePath)}`);
2600
- }).catch((err) => {
2601
- if (err.code === "EEXIST")
2602
- return;
2603
- throw err;
2604
- });
2605
- };
2606
-
2607
- const updateRelations = async ({
2608
- relations,
2609
- logger
2610
- }) => {
2611
- await Promise.all(
2612
- Object.entries(relations).map(
2613
- ([tableName, item]) => updateRelationItem(tableName, item, logger)
2614
- )
2615
- );
2616
- };
2617
- const updateRelationItem = async (tableName, item, logger) => {
2618
- var _a;
2619
- const content = await fs.readFile(item.path, "utf-8").catch(() => void 0);
2620
- if (!content)
2621
- return;
2622
- const changes = new FileChanges(content);
2623
- const statements = ts.getStatements(content);
2624
- const dirName = path.dirname(item.path);
2625
- const imports = {};
2626
- for (const relation of item.relations) {
2627
- if (!imports[relation.path]) {
2628
- imports[relation.path] = relation.className;
2629
- }
2630
- }
2631
- let importsEnd = 0;
2632
- for (const node of ts.import.iterate(statements)) {
2633
- const source = ts.import.getSource(node);
2634
- const full = path.join(dirName, source + ".ts");
2635
- if (imports[full]) {
2636
- delete imports[full];
2637
- }
2638
- importsEnd = node.end;
2639
- }
2640
- const addImports = Object.entries(imports).map(
2641
- ([path2, name]) => `import { ${name} } from '${orchidCore.getImportPath(item.path, path2)}';`
2642
- ).join("\n");
2643
- if (addImports) {
2644
- changes.add(importsEnd, `
2645
- ${addImports}`);
2646
- }
2647
- const targetClass = findClassByTableName(statements, tableName);
2648
- if (targetClass) {
2649
- const relationsMember = findRelationsMember(targetClass.members);
2650
- if (relationsMember) {
2651
- const { initializer } = relationsMember;
2652
- const takenKeys = {};
2653
- if (ts.is.objectLiteral(initializer)) {
2654
- const props = initializer.properties;
2655
- for (const prop of props) {
2656
- const name = (_a = prop.name) == null ? void 0 : _a.getText();
2657
- if (name)
2658
- takenKeys[name] = true;
2659
- }
2660
- const addRelations = [];
2661
- for (const rel of item.relations) {
2662
- if (!checkRelation(rel))
2663
- continue;
2664
- const name = makeRelationName(rel);
2665
- if (takenKeys[name])
2666
- continue;
2667
- addRelations.push(relationToCode(rel));
2668
- }
2669
- if (addRelations.length) {
2670
- const pos = props.end;
2671
- changes.add(pos, addRelations.join(""));
2672
- }
2673
- }
2674
- } else {
2675
- changes.add(
2676
- targetClass.end - 1,
2677
- `
2678
- relations = {${item.relations.filter(checkRelation).map((rel) => relationToCode(rel)).join("")}
2679
- };
2680
- `
2681
- );
2682
- }
2683
- }
2684
- await fs.writeFile(item.path, changes.apply());
2685
- logger == null ? void 0 : logger.log(`Updated ${orchidCore.pathToLog(item.path)}`);
2686
- };
2687
- const findClassByTableName = (statements, tableName) => {
2688
- for (const node of ts.class.iterate(statements)) {
2689
- for (const member of node.members) {
2690
- const name = ts.prop.getName(member);
2691
- if (name !== "table")
2692
- continue;
2693
- const { initializer: value } = member;
2694
- if (!value || !ts.is.stringLiteral(value))
2695
- continue;
2696
- if (value.text === tableName) {
2697
- return node;
2698
- }
2699
- }
2700
- }
2701
- return;
2702
- };
2703
- const findRelationsMember = (members) => {
2704
- for (const member of members) {
2705
- const name = ts.prop.getName(member);
2706
- if (name === "relations")
2707
- return member;
2708
- }
2709
- return;
2710
- };
2711
- const checkRelation = (rel) => {
2712
- return rel.columns.length === 1 && rel.foreignColumns.length === 1;
2713
- };
2714
- const makeRelationName = (rel) => {
2715
- return inflection.pluralize(
2716
- rel.className[0].toLowerCase() + rel.className.slice(1).replace(/Table$/, "")
2717
- );
2718
- };
2719
- const relationToCode = (rel, name = makeRelationName(rel)) => {
2720
- const code = [`
2721
- ${name}: this.${rel.kind}(() => ${rel.className}, {`];
2722
- const pk = rel[rel.kind === "hasMany" ? "columns" : "foreignColumns"][0];
2723
- const fk = rel[rel.kind === "hasMany" ? "foreignColumns" : "columns"][0];
2724
- code.push(
2725
- ` primaryKey: '${pk}',`,
2726
- ` foreignKey: '${fk}',`,
2727
- " }),"
2728
- );
2729
- return code.join("\n");
2730
- };
2731
-
2732
- var __defProp = Object.defineProperty;
2733
- var __defProps = Object.defineProperties;
2734
- var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
2735
- var __getOwnPropSymbols = Object.getOwnPropertySymbols;
2736
- var __hasOwnProp = Object.prototype.hasOwnProperty;
2737
- var __propIsEnum = Object.prototype.propertyIsEnumerable;
2738
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
2739
- var __spreadValues = (a, b) => {
2740
- for (var prop in b || (b = {}))
2741
- if (__hasOwnProp.call(b, prop))
2742
- __defNormalProp(a, prop, b[prop]);
2743
- if (__getOwnPropSymbols)
2744
- for (var prop of __getOwnPropSymbols(b)) {
2745
- if (__propIsEnum.call(b, prop))
2746
- __defNormalProp(a, prop, b[prop]);
2747
- }
2748
- return a;
2749
- };
2750
- var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
2751
- class AppCodeUpdaterError extends Error {
2752
- }
2753
- const makeGetTable = (path2, ormExportedAs, tables) => {
2754
- let orm;
2755
- return async (tableName) => {
2756
- if (tables[tableName])
2757
- return tables[tableName];
2758
- if (!orm) {
2759
- orm = (await import(path2))[ormExportedAs];
2760
- if (!orm) {
2761
- throw new Error(`ORM is not exported as ${ormExportedAs} from ${path2}`);
2762
- }
2763
- }
2764
- for (const key in orm) {
2765
- const table = orm[key];
2766
- if (table && typeof table === "object" && table instanceof pqb.Db && table.table === tableName) {
2767
- const tableInfo = {
2768
- key,
2769
- name: table.name,
2770
- path: table.filePath
2771
- };
2772
- return tables[tableName] = tableInfo;
2773
- }
2774
- }
2775
- return;
2776
- };
2777
- };
2778
- const appCodeUpdater = ({
2779
- tablePath,
2780
- ormPath,
2781
- ormExportedAs = "db"
2782
- }) => ({
2783
- async process({
2784
- ast,
2785
- options,
2786
- basePath,
2787
- cache: cacheObject,
2788
- logger,
2789
- baseTable
2790
- }) {
2791
- var _a, _b;
2792
- const params = {
2793
- tablePath(name) {
2794
- const file = tablePath(name);
2795
- return resolvePath(basePath, file);
2796
- },
2797
- ormPath: resolvePath(basePath, ormPath),
2798
- ormExportedAs,
2799
- logger
2800
- };
2801
- const cache = cacheObject;
2802
- (_a = cache.relations) != null ? _a : cache.relations = {};
2803
- (_b = cache.tables) != null ? _b : cache.tables = {};
2804
- const getTable = makeGetTable(params.ormPath, ormExportedAs, cache.tables);
2805
- const promises = [
2806
- updateMainFile(params.ormPath, params.tablePath, ast, options, logger),
2807
- updateTableFile(__spreadProps(__spreadValues({}, params), {
2808
- ast,
2809
- baseTable,
2810
- getTable,
2811
- relations: cache.relations,
2812
- tables: cache.tables
2813
- }))
2814
- ];
2815
- if (!cache.createdBaseTable) {
2816
- promises.push(
2817
- createBaseTableFile({ logger: params.logger, baseTable }).then(() => {
2818
- cache.createdBaseTable = true;
2819
- })
2820
- );
2821
- }
2822
- await Promise.all(promises);
2823
- },
2824
- async afterAll({ cache, logger }) {
2825
- const { relations } = cache;
2826
- if (!relations)
2827
- return;
2828
- await updateRelations({
2829
- relations,
2830
- logger
2831
- });
2832
- }
2833
- });
2834
- const resolvePath = (basePath, filePath) => path__namespace.isAbsolute(filePath) ? filePath : path__namespace.resolve(basePath, filePath);
2835
-
2836
1458
  Object.defineProperty(exports, 'OrchidOrmError', {
2837
1459
  enumerable: true,
2838
1460
  get: function () { return pqb.OrchidOrmError; }
@@ -2849,8 +1471,6 @@ Object.defineProperty(exports, 'testTransaction', {
2849
1471
  enumerable: true,
2850
1472
  get: function () { return pqb.testTransaction; }
2851
1473
  });
2852
- exports.AppCodeUpdaterError = AppCodeUpdaterError;
2853
- exports.appCodeUpdater = appCodeUpdater;
2854
1474
  exports.createBaseTable = createBaseTable;
2855
1475
  exports.createRepo = createRepo;
2856
1476
  exports.orchidORM = orchidORM;