orchid-orm 1.4.19 → 1.4.21

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.esm.js CHANGED
@@ -1,4 +1,8 @@
1
- import { getColumnTypes, addQueryOn, VirtualColumn, pushQueryValue, isQueryReturnsAll, getQueryAs, toSqlCacheKey, NotFoundError, relationQueryKey, Db, Adapter, anyShape, columnTypes, getClonedQueryData } from 'pqb';
1
+ import { getColumnTypes, addQueryOn, VirtualColumn, pushQueryValue, isQueryReturnsAll, getQueryAs, toSqlCacheKey, NotFoundError, relationQueryKey, Db, Adapter, anyShape, columnTypes, getClonedQueryData, singleQuote, columnsShapeToCode, codeToString, addCode, quoteObjectKey, primaryKeyToCode, indexToCode, foreignKeyToCode, columnDefaultArgumentToCode } from 'pqb';
2
+ import * as path from 'path';
3
+ import path__default from 'path';
4
+ import fs from 'fs/promises';
5
+ import { createSourceFile, ScriptTarget, SyntaxKind } from 'typescript';
2
6
 
3
7
  const createBaseTable = (options) => {
4
8
  return class BaseTable {
@@ -292,25 +296,25 @@ const hasRelationHandleUpdate = (q, ctx, set, key, primaryKey, nestedUpdate) =>
292
296
  });
293
297
  };
294
298
 
295
- var __defProp$4 = Object.defineProperty;
296
- var __defProps$2 = Object.defineProperties;
297
- var __getOwnPropDescs$2 = Object.getOwnPropertyDescriptors;
298
- var __getOwnPropSymbols$4 = Object.getOwnPropertySymbols;
299
- var __hasOwnProp$4 = Object.prototype.hasOwnProperty;
300
- var __propIsEnum$4 = Object.prototype.propertyIsEnumerable;
301
- var __defNormalProp$4 = (obj, key, value) => key in obj ? __defProp$4(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
302
- var __spreadValues$4 = (a, b) => {
299
+ var __defProp$6 = Object.defineProperty;
300
+ var __defProps$4 = Object.defineProperties;
301
+ var __getOwnPropDescs$4 = Object.getOwnPropertyDescriptors;
302
+ var __getOwnPropSymbols$9 = Object.getOwnPropertySymbols;
303
+ var __hasOwnProp$9 = Object.prototype.hasOwnProperty;
304
+ var __propIsEnum$9 = Object.prototype.propertyIsEnumerable;
305
+ var __defNormalProp$6 = (obj, key, value) => key in obj ? __defProp$6(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
306
+ var __spreadValues$6 = (a, b) => {
303
307
  for (var prop in b || (b = {}))
304
- if (__hasOwnProp$4.call(b, prop))
305
- __defNormalProp$4(a, prop, b[prop]);
306
- if (__getOwnPropSymbols$4)
307
- for (var prop of __getOwnPropSymbols$4(b)) {
308
- if (__propIsEnum$4.call(b, prop))
309
- __defNormalProp$4(a, prop, b[prop]);
308
+ if (__hasOwnProp$9.call(b, prop))
309
+ __defNormalProp$6(a, prop, b[prop]);
310
+ if (__getOwnPropSymbols$9)
311
+ for (var prop of __getOwnPropSymbols$9(b)) {
312
+ if (__propIsEnum$9.call(b, prop))
313
+ __defNormalProp$6(a, prop, b[prop]);
310
314
  }
311
315
  return a;
312
316
  };
313
- var __spreadProps$2 = (a, b) => __defProps$2(a, __getOwnPropDescs$2(b));
317
+ var __spreadProps$4 = (a, b) => __defProps$4(a, __getOwnPropDescs$4(b));
314
318
  class HasOneVirtualColumn extends VirtualColumn {
315
319
  constructor(key, state) {
316
320
  super();
@@ -443,7 +447,7 @@ const nestedInsert$2 = ({ query, primaryKey, foreignKey }) => {
443
447
  );
444
448
  if (create.length) {
445
449
  await t._count()._createMany(
446
- create.map(([selfData, item]) => __spreadValues$4({
450
+ create.map(([selfData, item]) => __spreadValues$6({
447
451
  [foreignKey]: selfData[primaryKey]
448
452
  }, "create" in item ? item.create : item.connectOrCreate.create))
449
453
  );
@@ -464,7 +468,7 @@ const nestedUpdate$2 = ({ query, primaryKey, foreignKey }) => {
464
468
  if (params.create || params.disconnect || params.set) {
465
469
  await currentRelationsQuery._update({ [foreignKey]: null });
466
470
  if (params.create) {
467
- await t._count()._create(__spreadProps$2(__spreadValues$4({}, params.create), {
471
+ await t._count()._create(__spreadProps$4(__spreadValues$6({}, params.create), {
468
472
  [foreignKey]: data[0][primaryKey]
469
473
  }));
470
474
  }
@@ -480,7 +484,7 @@ const nestedUpdate$2 = ({ query, primaryKey, foreignKey }) => {
480
484
  const updatedIds = await currentRelationsQuery._pluck(foreignKey)._update(update);
481
485
  if (updatedIds.length < ids.length) {
482
486
  await t.createMany(
483
- ids.filter((id) => !updatedIds.includes(id)).map((id) => __spreadProps$2(__spreadValues$4({}, create), {
487
+ ids.filter((id) => !updatedIds.includes(id)).map((id) => __spreadProps$4(__spreadValues$6({}, create), {
484
488
  [foreignKey]: id
485
489
  }))
486
490
  );
@@ -489,25 +493,25 @@ const nestedUpdate$2 = ({ query, primaryKey, foreignKey }) => {
489
493
  };
490
494
  };
491
495
 
492
- var __defProp$3 = Object.defineProperty;
493
- var __defProps$1 = Object.defineProperties;
494
- var __getOwnPropDescs$1 = Object.getOwnPropertyDescriptors;
495
- var __getOwnPropSymbols$3 = Object.getOwnPropertySymbols;
496
- var __hasOwnProp$3 = Object.prototype.hasOwnProperty;
497
- var __propIsEnum$3 = Object.prototype.propertyIsEnumerable;
498
- var __defNormalProp$3 = (obj, key, value) => key in obj ? __defProp$3(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
499
- var __spreadValues$3 = (a, b) => {
496
+ var __defProp$5 = Object.defineProperty;
497
+ var __defProps$3 = Object.defineProperties;
498
+ var __getOwnPropDescs$3 = Object.getOwnPropertyDescriptors;
499
+ var __getOwnPropSymbols$8 = Object.getOwnPropertySymbols;
500
+ var __hasOwnProp$8 = Object.prototype.hasOwnProperty;
501
+ var __propIsEnum$8 = Object.prototype.propertyIsEnumerable;
502
+ var __defNormalProp$5 = (obj, key, value) => key in obj ? __defProp$5(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
503
+ var __spreadValues$5 = (a, b) => {
500
504
  for (var prop in b || (b = {}))
501
- if (__hasOwnProp$3.call(b, prop))
502
- __defNormalProp$3(a, prop, b[prop]);
503
- if (__getOwnPropSymbols$3)
504
- for (var prop of __getOwnPropSymbols$3(b)) {
505
- if (__propIsEnum$3.call(b, prop))
506
- __defNormalProp$3(a, prop, b[prop]);
505
+ if (__hasOwnProp$8.call(b, prop))
506
+ __defNormalProp$5(a, prop, b[prop]);
507
+ if (__getOwnPropSymbols$8)
508
+ for (var prop of __getOwnPropSymbols$8(b)) {
509
+ if (__propIsEnum$8.call(b, prop))
510
+ __defNormalProp$5(a, prop, b[prop]);
507
511
  }
508
512
  return a;
509
513
  };
510
- var __spreadProps$1 = (a, b) => __defProps$1(a, __getOwnPropDescs$1(b));
514
+ var __spreadProps$3 = (a, b) => __defProps$3(a, __getOwnPropDescs$3(b));
511
515
  class HasManyVirtualColumn extends VirtualColumn {
512
516
  constructor(key, state) {
513
517
  super();
@@ -673,10 +677,10 @@ const nestedInsert$1 = ({ query, primaryKey, foreignKey }) => {
673
677
  await t._createMany(
674
678
  create.flatMap(([selfData, { create: create2 = [], connectOrCreate: connectOrCreate2 = [] }]) => {
675
679
  return [
676
- ...create2.map((item) => __spreadValues$3({
680
+ ...create2.map((item) => __spreadValues$5({
677
681
  [foreignKey]: selfData[primaryKey]
678
682
  }, item)),
679
- ...connectOrCreate2.filter(() => connected[connectedI++] === 0).map((item) => __spreadValues$3({
683
+ ...connectOrCreate2.filter(() => connected[connectedI++] === 0).map((item) => __spreadValues$5({
680
684
  [foreignKey]: selfData[primaryKey]
681
685
  }, item.create))
682
686
  ];
@@ -695,7 +699,7 @@ const nestedUpdate$1 = ({ query, primaryKey, foreignKey }) => {
695
699
  const t = query.transacting(q);
696
700
  if (params.create) {
697
701
  await t._count()._createMany(
698
- params.create.map((create) => __spreadProps$1(__spreadValues$3({}, create), {
702
+ params.create.map((create) => __spreadProps$3(__spreadValues$5({}, create), {
699
703
  [foreignKey]: data[0][primaryKey]
700
704
  }))
701
705
  );
@@ -738,19 +742,19 @@ const nestedUpdate$1 = ({ query, primaryKey, foreignKey }) => {
738
742
  };
739
743
  };
740
744
 
741
- var __defProp$2 = Object.defineProperty;
742
- var __getOwnPropSymbols$2 = Object.getOwnPropertySymbols;
743
- var __hasOwnProp$2 = Object.prototype.hasOwnProperty;
744
- var __propIsEnum$2 = Object.prototype.propertyIsEnumerable;
745
- var __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
746
- var __spreadValues$2 = (a, b) => {
745
+ var __defProp$4 = Object.defineProperty;
746
+ var __getOwnPropSymbols$7 = Object.getOwnPropertySymbols;
747
+ var __hasOwnProp$7 = Object.prototype.hasOwnProperty;
748
+ var __propIsEnum$7 = Object.prototype.propertyIsEnumerable;
749
+ var __defNormalProp$4 = (obj, key, value) => key in obj ? __defProp$4(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
750
+ var __spreadValues$4 = (a, b) => {
747
751
  for (var prop in b || (b = {}))
748
- if (__hasOwnProp$2.call(b, prop))
749
- __defNormalProp$2(a, prop, b[prop]);
750
- if (__getOwnPropSymbols$2)
751
- for (var prop of __getOwnPropSymbols$2(b)) {
752
- if (__propIsEnum$2.call(b, prop))
753
- __defNormalProp$2(a, prop, b[prop]);
752
+ if (__hasOwnProp$7.call(b, prop))
753
+ __defNormalProp$4(a, prop, b[prop]);
754
+ if (__getOwnPropSymbols$7)
755
+ for (var prop of __getOwnPropSymbols$7(b)) {
756
+ if (__propIsEnum$7.call(b, prop))
757
+ __defNormalProp$4(a, prop, b[prop]);
754
758
  }
755
759
  return a;
756
760
  };
@@ -803,7 +807,7 @@ const makeHasAndBelongsToManyMethod = (table, qb, relation, relationName, query)
803
807
  [afk]: query.shape[apk]
804
808
  };
805
809
  const subQuery = Object.create(__table);
806
- subQuery.query = __spreadValues$2({}, subQuery.query);
810
+ subQuery.query = __spreadValues$4({}, subQuery.query);
807
811
  const state = {
808
812
  relatedTableQuery: query,
809
813
  joinTableQuery: subQuery,
@@ -1237,33 +1241,33 @@ function transaction(fn) {
1237
1241
  });
1238
1242
  }
1239
1243
 
1240
- var __defProp$1 = Object.defineProperty;
1241
- var __defProps = Object.defineProperties;
1242
- var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
1243
- var __getOwnPropSymbols$1 = Object.getOwnPropertySymbols;
1244
- var __hasOwnProp$1 = Object.prototype.hasOwnProperty;
1245
- var __propIsEnum$1 = Object.prototype.propertyIsEnumerable;
1246
- var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1247
- var __spreadValues$1 = (a, b) => {
1244
+ var __defProp$3 = Object.defineProperty;
1245
+ var __defProps$2 = Object.defineProperties;
1246
+ var __getOwnPropDescs$2 = Object.getOwnPropertyDescriptors;
1247
+ var __getOwnPropSymbols$6 = Object.getOwnPropertySymbols;
1248
+ var __hasOwnProp$6 = Object.prototype.hasOwnProperty;
1249
+ var __propIsEnum$6 = Object.prototype.propertyIsEnumerable;
1250
+ var __defNormalProp$3 = (obj, key, value) => key in obj ? __defProp$3(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1251
+ var __spreadValues$3 = (a, b) => {
1248
1252
  for (var prop in b || (b = {}))
1249
- if (__hasOwnProp$1.call(b, prop))
1250
- __defNormalProp$1(a, prop, b[prop]);
1251
- if (__getOwnPropSymbols$1)
1252
- for (var prop of __getOwnPropSymbols$1(b)) {
1253
- if (__propIsEnum$1.call(b, prop))
1254
- __defNormalProp$1(a, prop, b[prop]);
1253
+ if (__hasOwnProp$6.call(b, prop))
1254
+ __defNormalProp$3(a, prop, b[prop]);
1255
+ if (__getOwnPropSymbols$6)
1256
+ for (var prop of __getOwnPropSymbols$6(b)) {
1257
+ if (__propIsEnum$6.call(b, prop))
1258
+ __defNormalProp$3(a, prop, b[prop]);
1255
1259
  }
1256
1260
  return a;
1257
1261
  };
1258
- var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
1259
- var __objRest = (source, exclude) => {
1262
+ var __spreadProps$2 = (a, b) => __defProps$2(a, __getOwnPropDescs$2(b));
1263
+ var __objRest$3 = (source, exclude) => {
1260
1264
  var target = {};
1261
1265
  for (var prop in source)
1262
- if (__hasOwnProp$1.call(source, prop) && exclude.indexOf(prop) < 0)
1266
+ if (__hasOwnProp$6.call(source, prop) && exclude.indexOf(prop) < 0)
1263
1267
  target[prop] = source[prop];
1264
- if (source != null && __getOwnPropSymbols$1)
1265
- for (var prop of __getOwnPropSymbols$1(source)) {
1266
- if (exclude.indexOf(prop) < 0 && __propIsEnum$1.call(source, prop))
1268
+ if (source != null && __getOwnPropSymbols$6)
1269
+ for (var prop of __getOwnPropSymbols$6(source)) {
1270
+ if (exclude.indexOf(prop) < 0 && __propIsEnum$6.call(source, prop))
1267
1271
  target[prop] = source[prop];
1268
1272
  }
1269
1273
  return target;
@@ -1274,7 +1278,7 @@ const orchidORM = (_a, tables) => {
1274
1278
  logger,
1275
1279
  autoPreparedStatements,
1276
1280
  noPrimaryKey = "error"
1277
- } = _b, options = __objRest(_b, [
1281
+ } = _b, options = __objRest$3(_b, [
1278
1282
  "log",
1279
1283
  "logger",
1280
1284
  "autoPreparedStatements",
@@ -1309,7 +1313,7 @@ const orchidORM = (_a, tables) => {
1309
1313
  }
1310
1314
  const table = new tables[key]();
1311
1315
  tableInstances[key] = table;
1312
- const options2 = __spreadProps(__spreadValues$1({}, commonOptions), {
1316
+ const options2 = __spreadProps$2(__spreadValues$3({}, commonOptions), {
1313
1317
  schema: table.schema
1314
1318
  });
1315
1319
  if (table.noPrimaryKey)
@@ -1330,24 +1334,24 @@ const orchidORM = (_a, tables) => {
1330
1334
  return result;
1331
1335
  };
1332
1336
 
1333
- var __defProp = Object.defineProperty;
1334
- var __getOwnPropSymbols = Object.getOwnPropertySymbols;
1335
- var __hasOwnProp = Object.prototype.hasOwnProperty;
1336
- var __propIsEnum = Object.prototype.propertyIsEnumerable;
1337
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1338
- var __spreadValues = (a, b) => {
1337
+ var __defProp$2 = Object.defineProperty;
1338
+ var __getOwnPropSymbols$5 = Object.getOwnPropertySymbols;
1339
+ var __hasOwnProp$5 = Object.prototype.hasOwnProperty;
1340
+ var __propIsEnum$5 = Object.prototype.propertyIsEnumerable;
1341
+ var __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1342
+ var __spreadValues$2 = (a, b) => {
1339
1343
  for (var prop in b || (b = {}))
1340
- if (__hasOwnProp.call(b, prop))
1341
- __defNormalProp(a, prop, b[prop]);
1342
- if (__getOwnPropSymbols)
1343
- for (var prop of __getOwnPropSymbols(b)) {
1344
- if (__propIsEnum.call(b, prop))
1345
- __defNormalProp(a, prop, b[prop]);
1344
+ if (__hasOwnProp$5.call(b, prop))
1345
+ __defNormalProp$2(a, prop, b[prop]);
1346
+ if (__getOwnPropSymbols$5)
1347
+ for (var prop of __getOwnPropSymbols$5(b)) {
1348
+ if (__propIsEnum$5.call(b, prop))
1349
+ __defNormalProp$2(a, prop, b[prop]);
1346
1350
  }
1347
1351
  return a;
1348
1352
  };
1349
1353
  const createRepo = (table, methods) => {
1350
- const queryMethods = __spreadValues(__spreadValues(__spreadValues(__spreadValues({}, methods.queryMethods), methods.queryOneMethods), methods.queryWithWhereMethods), methods.queryOneWithWhereMethods);
1354
+ const queryMethods = __spreadValues$2(__spreadValues$2(__spreadValues$2(__spreadValues$2({}, methods.queryMethods), methods.queryOneMethods), methods.queryWithWhereMethods), methods.queryOneWithWhereMethods);
1351
1355
  const plainMethods = methods.methods;
1352
1356
  const repo = (q2) => {
1353
1357
  const proto = Object.create(q2.__table);
@@ -1373,5 +1377,913 @@ const createRepo = (table, methods) => {
1373
1377
  });
1374
1378
  };
1375
1379
 
1376
- export { createBaseTable, createRepo, orchidORM };
1380
+ const toPascalCase = (s) => {
1381
+ const words = s.match(/(\w)(\w*)/g) || [];
1382
+ return words.map((word) => word[0].toUpperCase() + word.slice(1)).join("");
1383
+ };
1384
+ const toCamelCase = (s) => {
1385
+ const pascal = toPascalCase(s);
1386
+ return pascal[0].toLowerCase() + pascal.slice(1);
1387
+ };
1388
+
1389
+ class FileChanges {
1390
+ constructor(content) {
1391
+ this.content = content;
1392
+ this.ranges = [];
1393
+ }
1394
+ add(at, text, end = at) {
1395
+ if (this.ranges.length === 0) {
1396
+ this.ranges.push([0, at], text, [end, this.content.length]);
1397
+ } else {
1398
+ const last = this.ranges[this.ranges.length - 1];
1399
+ last[1] = at;
1400
+ this.ranges.push(text, [end, this.content.length]);
1401
+ }
1402
+ }
1403
+ replace(from, to, text) {
1404
+ this.add(from, text, to);
1405
+ }
1406
+ remove(from, to) {
1407
+ if (this.ranges.length === 0) {
1408
+ this.ranges.push([0, from], [to, this.content.length]);
1409
+ } else {
1410
+ const last = this.ranges[this.ranges.length - 1];
1411
+ last[1] = from;
1412
+ this.ranges.push([to, this.content.length]);
1413
+ }
1414
+ }
1415
+ apply() {
1416
+ return this.ranges.length ? this.ranges.map(
1417
+ (item) => typeof item === "string" ? item : this.content.slice(item[0], item[1])
1418
+ ).join("") : this.content;
1419
+ }
1420
+ }
1421
+
1422
+ const iterate = (kind) => {
1423
+ return function* (statements) {
1424
+ for (const node of statements) {
1425
+ if (node.kind === kind) {
1426
+ yield node;
1427
+ }
1428
+ }
1429
+ };
1430
+ };
1431
+ const isNode = (kind) => {
1432
+ return (node) => {
1433
+ return (node == null ? void 0 : node.kind) === kind;
1434
+ };
1435
+ };
1436
+ const ts = {
1437
+ getStatements(content) {
1438
+ const { statements } = createSourceFile(
1439
+ "file.ts",
1440
+ content,
1441
+ ScriptTarget.Latest,
1442
+ true
1443
+ );
1444
+ return statements;
1445
+ },
1446
+ is: {
1447
+ call: isNode(SyntaxKind.CallExpression),
1448
+ objectLiteral: isNode(
1449
+ SyntaxKind.ObjectLiteralExpression
1450
+ ),
1451
+ propertyAssignment: isNode(
1452
+ SyntaxKind.PropertyAssignment
1453
+ ),
1454
+ shorthandPropertyAssignment: isNode(
1455
+ SyntaxKind.ShorthandPropertyAssignment
1456
+ ),
1457
+ identifier: isNode(SyntaxKind.Identifier),
1458
+ stringLiteral: isNode(SyntaxKind.StringLiteral),
1459
+ arrayLiteral: isNode(
1460
+ SyntaxKind.ArrayLiteralExpression
1461
+ ),
1462
+ numericLiteral: isNode(SyntaxKind.NumericLiteral),
1463
+ computedPropertyName: isNode(
1464
+ SyntaxKind.ComputedPropertyName
1465
+ ),
1466
+ privateIdentifier: isNode(SyntaxKind.PrivateIdentifier),
1467
+ this: isNode(SyntaxKind.ThisKeyword),
1468
+ propertyAccess: isNode(
1469
+ SyntaxKind.PropertyAccessExpression
1470
+ ),
1471
+ arrowFunction: isNode(SyntaxKind.ArrowFunction),
1472
+ parenthesizedExpression: isNode(
1473
+ SyntaxKind.ParenthesizedExpression
1474
+ ),
1475
+ spreadAssignment: isNode(SyntaxKind.SpreadAssignment)
1476
+ },
1477
+ import: {
1478
+ iterate: iterate(SyntaxKind.ImportDeclaration),
1479
+ *iterateWithSource(statements, path) {
1480
+ for (const node of ts.import.iterate(statements)) {
1481
+ if (ts.import.getSource(node) !== path)
1482
+ continue;
1483
+ yield node;
1484
+ }
1485
+ },
1486
+ getSource(node) {
1487
+ return node.moduleSpecifier.getText().slice(1, -1);
1488
+ },
1489
+ getEndPos(statements) {
1490
+ let end = 0;
1491
+ for (const node of ts.import.iterate(statements)) {
1492
+ end = node.end;
1493
+ }
1494
+ return end;
1495
+ },
1496
+ getStatementsImportedName(statements, path, key) {
1497
+ for (const node of ts.import.iterateWithSource(statements, path)) {
1498
+ const name = ts.import.getImportName(node, key);
1499
+ if (name)
1500
+ return name;
1501
+ }
1502
+ return;
1503
+ },
1504
+ getImportName(node, key) {
1505
+ var _a, _b;
1506
+ if (!node.importClause)
1507
+ return;
1508
+ const elements = (_a = node.importClause.namedBindings) == null ? void 0 : _a.elements;
1509
+ if (!elements)
1510
+ return;
1511
+ for (const element of elements) {
1512
+ if (((_b = element.propertyName) == null ? void 0 : _b.escapedText) === key || element.name.escapedText === key) {
1513
+ return element.name.escapedText.toString();
1514
+ }
1515
+ }
1516
+ return;
1517
+ }
1518
+ },
1519
+ variable: {
1520
+ iterate: iterate(SyntaxKind.VariableStatement),
1521
+ *iterateDeclarations(statements) {
1522
+ for (const node of ts.variable.iterate(statements)) {
1523
+ for (const dec of node.declarationList.declarations) {
1524
+ yield dec;
1525
+ }
1526
+ }
1527
+ }
1528
+ },
1529
+ class: {
1530
+ iterate: iterate(SyntaxKind.ClassDeclaration)
1531
+ },
1532
+ prop: {
1533
+ getName({ name }) {
1534
+ if (ts.is.identifier(name)) {
1535
+ return name.escapedText;
1536
+ } else {
1537
+ return name == null ? void 0 : name.getText();
1538
+ }
1539
+ },
1540
+ getValue(prop) {
1541
+ if (ts.is.propertyAssignment(prop)) {
1542
+ return prop.initializer.getText();
1543
+ } else if (ts.is.shorthandPropertyAssignment(prop)) {
1544
+ return prop.name.escapedText.toString();
1545
+ } else {
1546
+ return;
1547
+ }
1548
+ }
1549
+ },
1550
+ spaces: {
1551
+ getAtLine(content, pos) {
1552
+ var _a;
1553
+ const lines = content.slice(0, pos).split("\n");
1554
+ const last = lines[lines.length - 1];
1555
+ return ((_a = last.match(/^\s+/)) == null ? void 0 : _a[0]) || "";
1556
+ }
1557
+ }
1558
+ };
1559
+
1560
+ const getRelativePath = (from, to) => {
1561
+ const rel = path__default.relative(path__default.dirname(from), to);
1562
+ return rel.startsWith("./") || rel.startsWith("../") ? rel : `./${rel}`;
1563
+ };
1564
+ const getImportPath = (from, to) => {
1565
+ return getRelativePath(from, to).replace(/\.[tj]s$/, "");
1566
+ };
1567
+
1568
+ const libraryName = "orchid-orm";
1569
+ const importKey = "orchidORM";
1570
+ const newFile = (options) => `import { orchidORM } from 'orchid-orm';
1571
+
1572
+ export const db = orchidORM(
1573
+ {
1574
+ ${optionsToString(options)}
1575
+ },
1576
+ {
1577
+ }
1578
+ );
1579
+ `;
1580
+ const optionsToString = (options) => {
1581
+ const lines = [];
1582
+ for (const key in options) {
1583
+ const value = options[key];
1584
+ if (typeof value !== "object" && typeof value !== "function") {
1585
+ lines.push(
1586
+ `${key}: ${typeof value === "string" ? singleQuote(value) : value},`
1587
+ );
1588
+ }
1589
+ }
1590
+ return lines.join("\n ");
1591
+ };
1592
+ const updateMainFile = async (filePath, tablePath, ast, options) => {
1593
+ const result = await fs.readFile(filePath, "utf-8").then(
1594
+ (content2) => ({ error: void 0, content: content2 }),
1595
+ (error) => {
1596
+ return { error, content: void 0 };
1597
+ }
1598
+ );
1599
+ if (result.error && result.error.code !== "ENOENT")
1600
+ throw result.error;
1601
+ const content = result.content || newFile(options);
1602
+ const statements = ts.getStatements(content);
1603
+ const importName = ts.import.getStatementsImportedName(
1604
+ statements,
1605
+ libraryName,
1606
+ importKey
1607
+ );
1608
+ if (!importName) {
1609
+ throw new AppCodeUpdaterError(
1610
+ `Main file does not contain import of orchid-orm`
1611
+ );
1612
+ }
1613
+ const object = getTablesListObject(importName, statements);
1614
+ if (!object) {
1615
+ throw new Error("List of tables is not found in main file");
1616
+ }
1617
+ const spaces = ts.spaces.getAtLine(content, object.end);
1618
+ const context = {
1619
+ filePath,
1620
+ tablePath,
1621
+ statements,
1622
+ object,
1623
+ content,
1624
+ spaces
1625
+ };
1626
+ let write;
1627
+ if (ast.type === "table") {
1628
+ if (ast.action === "create") {
1629
+ write = createTable$1(context, ast);
1630
+ } else {
1631
+ write = dropTable(context, ast);
1632
+ }
1633
+ }
1634
+ if (write) {
1635
+ if (result.error) {
1636
+ await fs.mkdir(path__default.dirname(filePath), { recursive: true });
1637
+ }
1638
+ await fs.writeFile(filePath, write);
1639
+ }
1640
+ };
1641
+ const createTable$1 = ({ filePath, tablePath, statements, object, content, spaces }, ast) => {
1642
+ const key = toCamelCase(ast.name);
1643
+ const value = toPascalCase(ast.name);
1644
+ const changes = new FileChanges(content);
1645
+ const importPath = getImportPath(filePath, tablePath(ast.name));
1646
+ const importPos = ts.import.getEndPos(statements);
1647
+ changes.add(
1648
+ importPos,
1649
+ `${importPos === 0 ? "" : "\n"}import { ${value} } from '${importPath}';`
1650
+ );
1651
+ let insert = `
1652
+ ${spaces} ${key}: ${value},`;
1653
+ if (object.properties.length && !object.properties.hasTrailingComma) {
1654
+ insert = `,${insert}`;
1655
+ }
1656
+ if (!content.slice(object.properties.end, object.end).includes("\n")) {
1657
+ insert += `
1658
+ ${spaces}`;
1659
+ }
1660
+ changes.add(object.properties.end, insert);
1661
+ return changes.apply();
1662
+ };
1663
+ const dropTable = ({ filePath, tablePath, statements, object, content }, ast) => {
1664
+ const changes = new FileChanges(content);
1665
+ const importPath = getImportPath(filePath, tablePath(ast.name));
1666
+ const tableClassName = toPascalCase(ast.name);
1667
+ const importNames = [];
1668
+ for (const node of ts.import.iterateWithSource(statements, importPath)) {
1669
+ changes.remove(node.pos, node.end);
1670
+ const name = ts.import.getImportName(node, tableClassName);
1671
+ if (name && !importNames.includes(name)) {
1672
+ importNames.push(name);
1673
+ }
1674
+ }
1675
+ for (const prop of object.properties) {
1676
+ const name = ts.prop.getValue(prop);
1677
+ if (!name || !importNames.includes(name))
1678
+ continue;
1679
+ let { end } = prop;
1680
+ if (content[end] === ",")
1681
+ end++;
1682
+ changes.remove(prop.pos, end);
1683
+ }
1684
+ return changes.apply();
1685
+ };
1686
+ const getTablesListObject = (importName, statements) => {
1687
+ for (const node of ts.variable.iterateDeclarations(statements)) {
1688
+ const call = node.initializer;
1689
+ if (!ts.is.call(call))
1690
+ continue;
1691
+ if (call.expression.getText() !== importName)
1692
+ continue;
1693
+ if (call.arguments.length !== 2) {
1694
+ throw new Error(
1695
+ "Invalid number of arguments when initializing orchid orm"
1696
+ );
1697
+ }
1698
+ const object = call.arguments[1];
1699
+ if (!ts.is.objectLiteral(object)) {
1700
+ throw new Error("Second argument of orchidORM must be an object literal");
1701
+ }
1702
+ return object;
1703
+ }
1704
+ return;
1705
+ };
1706
+
1707
+ var __getOwnPropSymbols$4 = Object.getOwnPropertySymbols;
1708
+ var __hasOwnProp$4 = Object.prototype.hasOwnProperty;
1709
+ var __propIsEnum$4 = Object.prototype.propertyIsEnumerable;
1710
+ var __objRest$2 = (source, exclude) => {
1711
+ var target = {};
1712
+ for (var prop in source)
1713
+ if (__hasOwnProp$4.call(source, prop) && exclude.indexOf(prop) < 0)
1714
+ target[prop] = source[prop];
1715
+ if (source != null && __getOwnPropSymbols$4)
1716
+ for (var prop of __getOwnPropSymbols$4(source)) {
1717
+ if (exclude.indexOf(prop) < 0 && __propIsEnum$4.call(source, prop))
1718
+ target[prop] = source[prop];
1719
+ }
1720
+ return target;
1721
+ };
1722
+ const createTable = async (_a) => {
1723
+ var _b = _a, {
1724
+ ast
1725
+ } = _b, params = __objRest$2(_b, [
1726
+ "ast"
1727
+ ]);
1728
+ const tablePath = params.tablePath(ast.name);
1729
+ const baseTablePath = getImportPath(tablePath, params.baseTablePath);
1730
+ const props = [`table = ${singleQuote(ast.name)};`];
1731
+ if (ast.noPrimaryKey === "ignore") {
1732
+ props.push("noPrimaryKey = true;");
1733
+ }
1734
+ props.push(
1735
+ "columns = this.setColumns((t) => ({",
1736
+ columnsShapeToCode(ast.shape, ast, "t"),
1737
+ "}));"
1738
+ );
1739
+ const code = [
1740
+ `import { ${params.baseTableName} } from '${baseTablePath}';
1741
+ `,
1742
+ `export class ${toPascalCase(ast.name)} extends ${params.baseTableName} {`,
1743
+ props,
1744
+ "}\n"
1745
+ ];
1746
+ await fs.mkdir(path__default.dirname(tablePath), { recursive: true });
1747
+ await fs.writeFile(tablePath, codeToString(code, "", " "));
1748
+ };
1749
+
1750
+ var __getOwnPropSymbols$3 = Object.getOwnPropertySymbols;
1751
+ var __hasOwnProp$3 = Object.prototype.hasOwnProperty;
1752
+ var __propIsEnum$3 = Object.prototype.propertyIsEnumerable;
1753
+ var __objRest$1 = (source, exclude) => {
1754
+ var target = {};
1755
+ for (var prop in source)
1756
+ if (__hasOwnProp$3.call(source, prop) && exclude.indexOf(prop) < 0)
1757
+ target[prop] = source[prop];
1758
+ if (source != null && __getOwnPropSymbols$3)
1759
+ for (var prop of __getOwnPropSymbols$3(source)) {
1760
+ if (exclude.indexOf(prop) < 0 && __propIsEnum$3.call(source, prop))
1761
+ target[prop] = source[prop];
1762
+ }
1763
+ return target;
1764
+ };
1765
+ const changeTable = async (_a) => {
1766
+ var _b = _a, {
1767
+ ast
1768
+ } = _b, params = __objRest$1(_b, [
1769
+ "ast"
1770
+ ]);
1771
+ const tablePath = params.tablePath(ast.name);
1772
+ const content = await fs.readFile(tablePath, "utf-8").catch(() => void 0);
1773
+ if (!content)
1774
+ return;
1775
+ const changes = new FileChanges(content);
1776
+ const statements = ts.getStatements(content);
1777
+ const className = toPascalCase(ast.name);
1778
+ for (const { t, object } of iterateColumnsShapes(statements, className)) {
1779
+ const context = makeChangeContext(changes, ast, content, object, t);
1780
+ prependSpaces(context);
1781
+ applySchemaChanges(context);
1782
+ appendTrailingComma(context);
1783
+ addColumns(context);
1784
+ addTableData(context);
1785
+ }
1786
+ await fs.writeFile(tablePath, changes.apply());
1787
+ };
1788
+ function* iterateColumnsShapes(statements, className) {
1789
+ var _a, _b;
1790
+ for (const node of ts.class.iterate(statements)) {
1791
+ if (((_a = node.name) == null ? void 0 : _a.escapedText) !== className)
1792
+ continue;
1793
+ for (const member of node.members) {
1794
+ const name = ts.prop.getName(member);
1795
+ const { initializer: call } = member;
1796
+ if (name !== "columns" || !call || !ts.is.call(call))
1797
+ continue;
1798
+ const { expression } = call;
1799
+ if (!ts.is.propertyAccess(expression) || !ts.is.this(expression.expression) || expression.name.escapedText !== "setColumns")
1800
+ continue;
1801
+ const [arg] = call.arguments;
1802
+ if (!ts.is.arrowFunction(arg))
1803
+ continue;
1804
+ const { parameters, body } = arg;
1805
+ const param = (_b = parameters[0]) == null ? void 0 : _b.name;
1806
+ if (!ts.is.identifier(param) || !ts.is.parenthesizedExpression(body))
1807
+ continue;
1808
+ const { expression: object } = body;
1809
+ if (!ts.is.objectLiteral(object))
1810
+ continue;
1811
+ yield { t: param.escapedText.toString(), object };
1812
+ }
1813
+ }
1814
+ }
1815
+ const makeChangeContext = (changes, ast, content, object, t) => {
1816
+ const add = {};
1817
+ const drop = {};
1818
+ const change = {};
1819
+ const { properties: props } = object;
1820
+ const existingColumns = getExistingColumns(props);
1821
+ for (const key in ast.shape) {
1822
+ const item = ast.shape[key];
1823
+ if (item.type === "add" && !existingColumns[key]) {
1824
+ add[key] = item.item;
1825
+ }
1826
+ if (!existingColumns[key])
1827
+ continue;
1828
+ if (item.type === "drop" && existingColumns[key]) {
1829
+ drop[key] = true;
1830
+ } else if (item.type === "change" && existingColumns[key]) {
1831
+ change[key] = item;
1832
+ }
1833
+ }
1834
+ const spaces = ts.spaces.getAtLine(content, object.end);
1835
+ const shape = { add, drop, change };
1836
+ return {
1837
+ changes,
1838
+ props,
1839
+ shape,
1840
+ spaces,
1841
+ t,
1842
+ object,
1843
+ add: ast.add,
1844
+ drop: ast.drop
1845
+ };
1846
+ };
1847
+ const getExistingColumns = (props) => {
1848
+ const existingColumns = {};
1849
+ props.map((prop) => ts.is.propertyAssignment(prop) && ts.prop.getName(prop)).filter((name) => !!name).forEach((name) => existingColumns[name] = true);
1850
+ for (const prop of props) {
1851
+ if (!ts.is.propertyAssignment(prop))
1852
+ continue;
1853
+ const name = ts.prop.getName(prop);
1854
+ if (name)
1855
+ existingColumns[name] = true;
1856
+ }
1857
+ return existingColumns;
1858
+ };
1859
+ const prependSpaces = ({
1860
+ props,
1861
+ shape: { add },
1862
+ changes,
1863
+ spaces
1864
+ }) => {
1865
+ if (Object.keys(add).length && props.pos === props.end) {
1866
+ changes.add(props.pos, `
1867
+ ${spaces}`);
1868
+ }
1869
+ };
1870
+ const applySchemaChanges = (context) => {
1871
+ const {
1872
+ props,
1873
+ shape: { drop: dropColumns, change: changeColumns },
1874
+ add,
1875
+ drop
1876
+ } = context;
1877
+ props.forEach((prop, i) => {
1878
+ if (ts.is.spreadAssignment(prop)) {
1879
+ const call = prop.expression;
1880
+ if (!ts.is.call(call))
1881
+ return;
1882
+ const access = call.expression;
1883
+ if (!ts.is.propertyAccess(access))
1884
+ return;
1885
+ const name = access.name.escapedText.toString();
1886
+ if (name === "primaryKey") {
1887
+ if (drop.primaryKey || add.primaryKey) {
1888
+ removeProp(context, prop, i);
1889
+ }
1890
+ } else if (name === "index") {
1891
+ dropMatchingIndexes(context, prop, i, call, drop.indexes);
1892
+ } else if (name === "foreignKey") {
1893
+ dropMatchingForeignKey(context, prop, i, call, drop.foreignKeys);
1894
+ }
1895
+ } else if (ts.is.propertyAssignment(prop)) {
1896
+ const name = ts.prop.getName(prop);
1897
+ if (!name)
1898
+ return;
1899
+ if (dropColumns[name]) {
1900
+ removeProp(context, prop, i);
1901
+ } else {
1902
+ const changeItem = changeColumns[name];
1903
+ if (changeItem) {
1904
+ changeColumn(context, changeItem, prop);
1905
+ }
1906
+ }
1907
+ }
1908
+ });
1909
+ };
1910
+ const removeProp = ({ props, changes }, prop, i) => {
1911
+ var _a;
1912
+ const end = ((_a = props[i + 1]) == null ? void 0 : _a.pos) || props.end;
1913
+ changes.remove(prop.pos, end);
1914
+ };
1915
+ const changeColumn = ({ changes, t, spaces }, changeItem, prop) => {
1916
+ const { from, to } = changeItem;
1917
+ if (from.type !== to.type && to.column) {
1918
+ changes.replace(
1919
+ prop.initializer.pos,
1920
+ prop.end,
1921
+ ` ${codeToString(to.column.toCode(t), spaces + " ", " ").trim()}`
1922
+ );
1923
+ return;
1924
+ }
1925
+ const items = [];
1926
+ let chain = prop.initializer;
1927
+ while (ts.is.call(chain) && ts.is.propertyAccess(chain.expression)) {
1928
+ items.push(chain);
1929
+ chain = chain.expression.expression;
1930
+ }
1931
+ const propsToChange = {};
1932
+ for (const key in from) {
1933
+ if (to[key] !== from[key]) {
1934
+ propsToChange[key] = true;
1935
+ }
1936
+ }
1937
+ for (const key in to) {
1938
+ if (to[key] !== from[key]) {
1939
+ propsToChange[key] = true;
1940
+ }
1941
+ }
1942
+ const changedProps = {};
1943
+ for (const item of items.reverse()) {
1944
+ if (!ts.is.propertyAccess(item.expression))
1945
+ continue;
1946
+ const { name } = item.expression;
1947
+ const key = name.escapedText.toString();
1948
+ if (!propsToChange[key])
1949
+ continue;
1950
+ const value = getColumnMethodArgs(to, key);
1951
+ if (value) {
1952
+ const code = [`${key}(`];
1953
+ addCode(code, value);
1954
+ addCode(code, ")");
1955
+ changes.replace(name.pos, item.end, codeToString(code, "", " ").trim());
1956
+ } else {
1957
+ changes.remove(item.expression.expression.end, item.end);
1958
+ }
1959
+ changedProps[key] = true;
1960
+ }
1961
+ let append = "";
1962
+ for (const key in propsToChange) {
1963
+ if (changedProps[key])
1964
+ continue;
1965
+ const value = getColumnMethodArgs(to, key);
1966
+ if (value !== void 0) {
1967
+ const code = [`.${key}(`];
1968
+ addCode(code, value);
1969
+ addCode(code, ")");
1970
+ append += codeToString(code, "", " ").trim();
1971
+ }
1972
+ }
1973
+ if (append) {
1974
+ changes.add(prop.end, append);
1975
+ }
1976
+ };
1977
+ const appendTrailingComma = ({ props, changes }) => {
1978
+ if (!props.hasTrailingComma) {
1979
+ const last = props[props.length - 1];
1980
+ if (last) {
1981
+ changes.add(last.end, ",");
1982
+ }
1983
+ }
1984
+ };
1985
+ const addColumns = ({
1986
+ shape: { add },
1987
+ changes,
1988
+ object,
1989
+ t,
1990
+ spaces
1991
+ }) => {
1992
+ const end = object.end - 1;
1993
+ for (const key in add) {
1994
+ const code = codeToString(add[key].toCode(t), spaces + " ", " ");
1995
+ changes.add(end, ` ${quoteObjectKey(key)}: ${code.trim()},
1996
+ ${spaces}`);
1997
+ }
1998
+ };
1999
+ const addTableData = ({ add, changes, object, t, spaces }) => {
2000
+ const end = object.end - 1;
2001
+ if (add.primaryKey) {
2002
+ const code = codeToString(
2003
+ primaryKeyToCode(add.primaryKey, t),
2004
+ spaces,
2005
+ " "
2006
+ );
2007
+ changes.add(end, ` ${code.trim()}
2008
+ ${spaces}`);
2009
+ }
2010
+ for (const item of add.indexes) {
2011
+ const code = codeToString(indexToCode(item, t), spaces + " ", " ");
2012
+ changes.add(end, ` ${code.trim()}
2013
+ ${spaces}`);
2014
+ }
2015
+ for (const item of add.foreignKeys) {
2016
+ const code = codeToString(foreignKeyToCode(item, t), spaces + " ", " ");
2017
+ changes.add(end, ` ${code.trim()}
2018
+ ${spaces}`);
2019
+ }
2020
+ };
2021
+ const getColumnMethodArgs = (to, key) => {
2022
+ const value = to[key];
2023
+ if (!value)
2024
+ return;
2025
+ if (key === "collate" || key === "compression") {
2026
+ return singleQuote(value);
2027
+ } else if (key === "default") {
2028
+ return columnDefaultArgumentToCode(value);
2029
+ } else if (key === "nullable" || key === "primaryKey") {
2030
+ return "";
2031
+ } else {
2032
+ return;
2033
+ }
2034
+ };
2035
+ const dropMatchingIndexes = (context, prop, i, call, items) => {
2036
+ if (!items.length)
2037
+ return;
2038
+ const [columnsNode, optionsNode] = call.arguments;
2039
+ const columns = [];
2040
+ if (ts.is.stringLiteral(columnsNode)) {
2041
+ columns.push({ column: columnsNode.text });
2042
+ } else if (ts.is.arrayLiteral(columnsNode)) {
2043
+ for (const node of columnsNode.elements) {
2044
+ if (ts.is.stringLiteral(node)) {
2045
+ columns.push({ column: node.text });
2046
+ } else if (ts.is.objectLiteral(node)) {
2047
+ const object = collectObjectFromCode(node);
2048
+ if (!object)
2049
+ return;
2050
+ columns.push(object);
2051
+ }
2052
+ }
2053
+ } else {
2054
+ return;
2055
+ }
2056
+ const options = ts.is.objectLiteral(optionsNode) && collectObjectFromCode(optionsNode) || {};
2057
+ for (const item of items) {
2058
+ if (deepCompare(columns, item.columns) && deepCompare(options, item.options)) {
2059
+ removeProp(context, prop, i);
2060
+ }
2061
+ }
2062
+ };
2063
+ const dropMatchingForeignKey = (context, prop, i, call, items) => {
2064
+ if (!items.length)
2065
+ return;
2066
+ const { arguments: args } = call;
2067
+ const columns = collectStringArrayFromCode(args[0]);
2068
+ if (!columns)
2069
+ return;
2070
+ const fnOrTableNode = args[1];
2071
+ let fnOrTable;
2072
+ if (ts.is.stringLiteral(fnOrTableNode)) {
2073
+ fnOrTable = fnOrTableNode.text;
2074
+ } else if (ts.is.arrowFunction(fnOrTableNode)) {
2075
+ fnOrTable = context.changes.content.slice(fnOrTableNode.pos, fnOrTableNode.end).replaceAll(/\s/g, "");
2076
+ } else {
2077
+ return;
2078
+ }
2079
+ const foreignColumns = collectStringArrayFromCode(args[2]);
2080
+ if (!foreignColumns)
2081
+ return;
2082
+ const options = ts.is.objectLiteral(args[3]) && collectObjectFromCode(args[3]) || {};
2083
+ for (const item of items) {
2084
+ const itemOptions = item.options;
2085
+ delete itemOptions.dropMode;
2086
+ if (deepCompare(columns, item.columns) && deepCompare(fnOrTable, item.fnOrTable.toString()) && deepCompare(foreignColumns, item.foreignColumns) && deepCompare(options, itemOptions)) {
2087
+ removeProp(context, prop, i);
2088
+ }
2089
+ }
2090
+ };
2091
+ const collectStringArrayFromCode = (node) => {
2092
+ if (!ts.is.arrayLiteral(node))
2093
+ return;
2094
+ const result = node.elements.filter(ts.is.stringLiteral).map((item) => item.text);
2095
+ return result.length === node.elements.length ? result : void 0;
2096
+ };
2097
+ const collectObjectFromCode = (node) => {
2098
+ const object = {};
2099
+ for (const prop of node.properties) {
2100
+ if (!ts.is.propertyAssignment(prop))
2101
+ return;
2102
+ const name = ts.prop.getName(prop);
2103
+ if (!name)
2104
+ return;
2105
+ const init = prop.initializer;
2106
+ if (ts.is.stringLiteral(init)) {
2107
+ object[name] = init.text;
2108
+ } else if (ts.is.numericLiteral(init)) {
2109
+ object[name] = parseFloat(init.text);
2110
+ } else {
2111
+ return;
2112
+ }
2113
+ }
2114
+ return object;
2115
+ };
2116
+ const deepCompare = (a, b) => {
2117
+ if (typeof a !== typeof b)
2118
+ return false;
2119
+ if (a === b)
2120
+ return true;
2121
+ if (typeof a === "object") {
2122
+ if (a === null)
2123
+ return b === null;
2124
+ if (Array.isArray(a)) {
2125
+ if (!Array.isArray(b) || a.length !== b.length)
2126
+ return false;
2127
+ return a.every((item, i) => deepCompare(item, b[i]));
2128
+ }
2129
+ for (const key in a) {
2130
+ if (!deepCompare(
2131
+ a[key],
2132
+ b[key]
2133
+ ))
2134
+ return false;
2135
+ }
2136
+ for (const key in b) {
2137
+ if (!(key in a))
2138
+ return false;
2139
+ }
2140
+ }
2141
+ return true;
2142
+ };
2143
+
2144
+ var __getOwnPropSymbols$2 = Object.getOwnPropertySymbols;
2145
+ var __hasOwnProp$2 = Object.prototype.hasOwnProperty;
2146
+ var __propIsEnum$2 = Object.prototype.propertyIsEnumerable;
2147
+ var __objRest = (source, exclude) => {
2148
+ var target = {};
2149
+ for (var prop in source)
2150
+ if (__hasOwnProp$2.call(source, prop) && exclude.indexOf(prop) < 0)
2151
+ target[prop] = source[prop];
2152
+ if (source != null && __getOwnPropSymbols$2)
2153
+ for (var prop of __getOwnPropSymbols$2(source)) {
2154
+ if (exclude.indexOf(prop) < 0 && __propIsEnum$2.call(source, prop))
2155
+ target[prop] = source[prop];
2156
+ }
2157
+ return target;
2158
+ };
2159
+ const renameTable = async (_a) => {
2160
+ var _b = _a, {
2161
+ ast
2162
+ } = _b, params = __objRest(_b, [
2163
+ "ast"
2164
+ ]);
2165
+ var _a2;
2166
+ const tablePath = params.tablePath(ast.from);
2167
+ const content = await fs.readFile(tablePath, "utf-8").catch(() => void 0);
2168
+ if (!content)
2169
+ return;
2170
+ const changes = new FileChanges(content);
2171
+ const statements = ts.getStatements(content);
2172
+ const className = toPascalCase(ast.from);
2173
+ for (const node of ts.class.iterate(statements)) {
2174
+ if (((_a2 = node.name) == null ? void 0 : _a2.escapedText) !== className)
2175
+ continue;
2176
+ for (const member of node.members) {
2177
+ const name = ts.prop.getName(member);
2178
+ if (name !== "table")
2179
+ continue;
2180
+ const { initializer: value } = member;
2181
+ if (!value)
2182
+ continue;
2183
+ changes.replace(value.pos, value.end, ` ${singleQuote(ast.to)}`);
2184
+ }
2185
+ }
2186
+ await fs.writeFile(params.tablePath(ast.to), changes.apply());
2187
+ };
2188
+
2189
+ var __defProp$1 = Object.defineProperty;
2190
+ var __defProps$1 = Object.defineProperties;
2191
+ var __getOwnPropDescs$1 = Object.getOwnPropertyDescriptors;
2192
+ var __getOwnPropSymbols$1 = Object.getOwnPropertySymbols;
2193
+ var __hasOwnProp$1 = Object.prototype.hasOwnProperty;
2194
+ var __propIsEnum$1 = Object.prototype.propertyIsEnumerable;
2195
+ var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
2196
+ var __spreadValues$1 = (a, b) => {
2197
+ for (var prop in b || (b = {}))
2198
+ if (__hasOwnProp$1.call(b, prop))
2199
+ __defNormalProp$1(a, prop, b[prop]);
2200
+ if (__getOwnPropSymbols$1)
2201
+ for (var prop of __getOwnPropSymbols$1(b)) {
2202
+ if (__propIsEnum$1.call(b, prop))
2203
+ __defNormalProp$1(a, prop, b[prop]);
2204
+ }
2205
+ return a;
2206
+ };
2207
+ var __spreadProps$1 = (a, b) => __defProps$1(a, __getOwnPropDescs$1(b));
2208
+ const updateTableFile = async (params) => {
2209
+ const { ast } = params;
2210
+ if (ast.type === "table" && ast.action === "create") {
2211
+ await createTable(__spreadProps$1(__spreadValues$1({}, params), { ast }));
2212
+ } else if (ast.type === "changeTable") {
2213
+ await changeTable(__spreadProps$1(__spreadValues$1({}, params), { ast }));
2214
+ } else if (ast.type === "renameTable") {
2215
+ await renameTable(__spreadProps$1(__spreadValues$1({}, params), { ast }));
2216
+ }
2217
+ };
2218
+
2219
+ const createBaseTableFile = async ({
2220
+ baseTableName,
2221
+ baseTablePath
2222
+ }) => {
2223
+ await fs.mkdir(path__default.dirname(baseTablePath), { recursive: true });
2224
+ await fs.writeFile(
2225
+ baseTablePath,
2226
+ `import { createBaseTable } from 'orchid-orm';
2227
+ import { columnTypes } from 'pqb';
2228
+
2229
+ export const ${baseTableName} = createBaseTable({
2230
+ columnTypes: {
2231
+ ...columnTypes,
2232
+ },
2233
+ });
2234
+ `,
2235
+ {
2236
+ flag: "wx"
2237
+ }
2238
+ ).catch((err) => {
2239
+ if (err.code === "EEXIST")
2240
+ return;
2241
+ throw err;
2242
+ });
2243
+ };
2244
+
2245
+ var __defProp = Object.defineProperty;
2246
+ var __defProps = Object.defineProperties;
2247
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
2248
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
2249
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
2250
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
2251
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
2252
+ var __spreadValues = (a, b) => {
2253
+ for (var prop in b || (b = {}))
2254
+ if (__hasOwnProp.call(b, prop))
2255
+ __defNormalProp(a, prop, b[prop]);
2256
+ if (__getOwnPropSymbols)
2257
+ for (var prop of __getOwnPropSymbols(b)) {
2258
+ if (__propIsEnum.call(b, prop))
2259
+ __defNormalProp(a, prop, b[prop]);
2260
+ }
2261
+ return a;
2262
+ };
2263
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
2264
+ class AppCodeUpdaterError extends Error {
2265
+ }
2266
+ const appCodeUpdater = (config) => {
2267
+ const params = __spreadProps(__spreadValues({}, config), {
2268
+ tablePath: (name) => path.resolve(config.tablePath(name)),
2269
+ mainFilePath: path.resolve(config.mainFilePath)
2270
+ });
2271
+ return async ({ ast, options, cache: cacheObject }) => {
2272
+ const promises = [
2273
+ updateMainFile(params.mainFilePath, params.tablePath, ast, options),
2274
+ updateTableFile(__spreadProps(__spreadValues({}, params), { ast }))
2275
+ ];
2276
+ const cache = cacheObject;
2277
+ if (!cache.createdBaseTable) {
2278
+ promises.push(
2279
+ createBaseTableFile(params).then(() => {
2280
+ cache.createdBaseTable = true;
2281
+ })
2282
+ );
2283
+ }
2284
+ await Promise.all(promises);
2285
+ };
2286
+ };
2287
+
2288
+ export { AppCodeUpdaterError, appCodeUpdater, createBaseTable, createRepo, orchidORM };
1377
2289
  //# sourceMappingURL=index.esm.js.map