orchid-orm 1.9.22 → 1.9.24

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