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