@lakutata/orm 0.0.0-stage → 3.0.0-beta.0

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.
Files changed (209) hide show
  1. package/LICENSE +23 -0
  2. package/README.md +463 -2
  3. package/THIRD_PARTY_NOTICES.md +36 -0
  4. package/dist/cjs/components/Database.d.ts +333 -0
  5. package/dist/cjs/components/Database.js +381 -0
  6. package/dist/cjs/decorators/orm/AfterInsert.d.ts +1 -0
  7. package/dist/cjs/decorators/orm/AfterInsert.js +5 -0
  8. package/dist/cjs/decorators/orm/AfterLoad.d.ts +1 -0
  9. package/dist/cjs/decorators/orm/AfterLoad.js +5 -0
  10. package/dist/cjs/decorators/orm/AfterRecover.d.ts +1 -0
  11. package/dist/cjs/decorators/orm/AfterRecover.js +5 -0
  12. package/dist/cjs/decorators/orm/AfterRemove.d.ts +1 -0
  13. package/dist/cjs/decorators/orm/AfterRemove.js +5 -0
  14. package/dist/cjs/decorators/orm/AfterSoftRemove.d.ts +1 -0
  15. package/dist/cjs/decorators/orm/AfterSoftRemove.js +5 -0
  16. package/dist/cjs/decorators/orm/AfterUpdate.d.ts +1 -0
  17. package/dist/cjs/decorators/orm/AfterUpdate.js +5 -0
  18. package/dist/cjs/decorators/orm/BeforeInsert.d.ts +1 -0
  19. package/dist/cjs/decorators/orm/BeforeInsert.js +5 -0
  20. package/dist/cjs/decorators/orm/BeforeRecover.d.ts +1 -0
  21. package/dist/cjs/decorators/orm/BeforeRecover.js +5 -0
  22. package/dist/cjs/decorators/orm/BeforeRemove.d.ts +1 -0
  23. package/dist/cjs/decorators/orm/BeforeRemove.js +5 -0
  24. package/dist/cjs/decorators/orm/BeforeSoftRemove.d.ts +1 -0
  25. package/dist/cjs/decorators/orm/BeforeSoftRemove.js +5 -0
  26. package/dist/cjs/decorators/orm/BeforeUpdate.d.ts +1 -0
  27. package/dist/cjs/decorators/orm/BeforeUpdate.js +5 -0
  28. package/dist/cjs/decorators/orm/Check.d.ts +1 -0
  29. package/dist/cjs/decorators/orm/Check.js +5 -0
  30. package/dist/cjs/decorators/orm/ChildEntity.d.ts +1 -0
  31. package/dist/cjs/decorators/orm/ChildEntity.js +5 -0
  32. package/dist/cjs/decorators/orm/Column.d.ts +1 -0
  33. package/dist/cjs/decorators/orm/Column.js +5 -0
  34. package/dist/cjs/decorators/orm/CreateDateColumn.d.ts +1 -0
  35. package/dist/cjs/decorators/orm/CreateDateColumn.js +5 -0
  36. package/dist/cjs/decorators/orm/DeleteDateColumn.d.ts +1 -0
  37. package/dist/cjs/decorators/orm/DeleteDateColumn.js +5 -0
  38. package/dist/cjs/decorators/orm/Entity.d.ts +1 -0
  39. package/dist/cjs/decorators/orm/Entity.js +5 -0
  40. package/dist/cjs/decorators/orm/EventSubscriber.d.ts +1 -0
  41. package/dist/cjs/decorators/orm/EventSubscriber.js +5 -0
  42. package/dist/cjs/decorators/orm/Exclusion.d.ts +1 -0
  43. package/dist/cjs/decorators/orm/Exclusion.js +5 -0
  44. package/dist/cjs/decorators/orm/Generated.d.ts +1 -0
  45. package/dist/cjs/decorators/orm/Generated.js +5 -0
  46. package/dist/cjs/decorators/orm/Index.d.ts +1 -0
  47. package/dist/cjs/decorators/orm/Index.js +5 -0
  48. package/dist/cjs/decorators/orm/JoinColumn.d.ts +1 -0
  49. package/dist/cjs/decorators/orm/JoinColumn.js +5 -0
  50. package/dist/cjs/decorators/orm/JoinTable.d.ts +1 -0
  51. package/dist/cjs/decorators/orm/JoinTable.js +5 -0
  52. package/dist/cjs/decorators/orm/ManyToMany.d.ts +1 -0
  53. package/dist/cjs/decorators/orm/ManyToMany.js +5 -0
  54. package/dist/cjs/decorators/orm/ManyToOne.d.ts +1 -0
  55. package/dist/cjs/decorators/orm/ManyToOne.js +5 -0
  56. package/dist/cjs/decorators/orm/ObjectIdColumn.d.ts +1 -0
  57. package/dist/cjs/decorators/orm/ObjectIdColumn.js +5 -0
  58. package/dist/cjs/decorators/orm/OneToMany.d.ts +1 -0
  59. package/dist/cjs/decorators/orm/OneToMany.js +5 -0
  60. package/dist/cjs/decorators/orm/OneToOne.d.ts +1 -0
  61. package/dist/cjs/decorators/orm/OneToOne.js +5 -0
  62. package/dist/cjs/decorators/orm/PrimaryColumn.d.ts +1 -0
  63. package/dist/cjs/decorators/orm/PrimaryColumn.js +5 -0
  64. package/dist/cjs/decorators/orm/PrimaryGeneratedColumn.d.ts +1 -0
  65. package/dist/cjs/decorators/orm/PrimaryGeneratedColumn.js +5 -0
  66. package/dist/cjs/decorators/orm/RelationId.d.ts +1 -0
  67. package/dist/cjs/decorators/orm/RelationId.js +5 -0
  68. package/dist/cjs/decorators/orm/TableInheritance.d.ts +1 -0
  69. package/dist/cjs/decorators/orm/TableInheritance.js +5 -0
  70. package/dist/cjs/decorators/orm/Tree.d.ts +1 -0
  71. package/dist/cjs/decorators/orm/Tree.js +5 -0
  72. package/dist/cjs/decorators/orm/TreeChildren.d.ts +1 -0
  73. package/dist/cjs/decorators/orm/TreeChildren.js +5 -0
  74. package/dist/cjs/decorators/orm/TreeLevelColumn.d.ts +1 -0
  75. package/dist/cjs/decorators/orm/TreeLevelColumn.js +5 -0
  76. package/dist/cjs/decorators/orm/TreeParent.d.ts +1 -0
  77. package/dist/cjs/decorators/orm/TreeParent.js +5 -0
  78. package/dist/cjs/decorators/orm/Unique.d.ts +1 -0
  79. package/dist/cjs/decorators/orm/Unique.js +5 -0
  80. package/dist/cjs/decorators/orm/UpdateDateColumn.d.ts +1 -0
  81. package/dist/cjs/decorators/orm/UpdateDateColumn.js +5 -0
  82. package/dist/cjs/decorators/orm/VersionColumn.d.ts +1 -0
  83. package/dist/cjs/decorators/orm/VersionColumn.js +5 -0
  84. package/dist/cjs/decorators/orm/ViewColumn.d.ts +1 -0
  85. package/dist/cjs/decorators/orm/ViewColumn.js +5 -0
  86. package/dist/cjs/decorators/orm/ViewEntity.d.ts +1 -0
  87. package/dist/cjs/decorators/orm/ViewEntity.js +5 -0
  88. package/dist/cjs/decorators/orm/VirtualColumn.d.ts +1 -0
  89. package/dist/cjs/decorators/orm/VirtualColumn.js +5 -0
  90. package/dist/cjs/exports/DatabaseComponent.d.ts +3 -0
  91. package/dist/cjs/exports/DatabaseComponent.js +21 -0
  92. package/dist/cjs/exports/DatabaseProvider.d.ts +3 -0
  93. package/dist/cjs/exports/DatabaseProvider.js +21 -0
  94. package/dist/cjs/exports/ORM.d.ts +193 -0
  95. package/dist/cjs/exports/ORM.js +166 -0
  96. package/dist/cjs/exports/ORMDecorators.d.ts +43 -0
  97. package/dist/cjs/exports/ORMDecorators.js +91 -0
  98. package/dist/cjs/package.json +1 -0
  99. package/dist/cjs/providers/Database.d.ts +326 -0
  100. package/dist/cjs/providers/Database.js +376 -0
  101. package/dist/cjs/providers/migration/ExecuteMigration.d.ts +40 -0
  102. package/dist/cjs/providers/migration/ExecuteMigration.js +143 -0
  103. package/dist/cjs/providers/migration/GenerateMigration.d.ts +59 -0
  104. package/dist/cjs/providers/migration/GenerateMigration.js +303 -0
  105. package/dist/cjs/types/MigrationRunOptions.d.ts +19 -0
  106. package/dist/cjs/types/MigrationRunOptions.js +2 -0
  107. package/dist/esm/components/Database.js +344 -0
  108. package/dist/esm/decorators/orm/AfterInsert.js +1 -0
  109. package/dist/esm/decorators/orm/AfterLoad.js +1 -0
  110. package/dist/esm/decorators/orm/AfterRecover.js +1 -0
  111. package/dist/esm/decorators/orm/AfterRemove.js +1 -0
  112. package/dist/esm/decorators/orm/AfterSoftRemove.js +1 -0
  113. package/dist/esm/decorators/orm/AfterUpdate.js +1 -0
  114. package/dist/esm/decorators/orm/BeforeInsert.js +1 -0
  115. package/dist/esm/decorators/orm/BeforeRecover.js +1 -0
  116. package/dist/esm/decorators/orm/BeforeRemove.js +1 -0
  117. package/dist/esm/decorators/orm/BeforeSoftRemove.js +1 -0
  118. package/dist/esm/decorators/orm/BeforeUpdate.js +1 -0
  119. package/dist/esm/decorators/orm/Check.js +1 -0
  120. package/dist/esm/decorators/orm/ChildEntity.js +1 -0
  121. package/dist/esm/decorators/orm/Column.js +1 -0
  122. package/dist/esm/decorators/orm/CreateDateColumn.js +1 -0
  123. package/dist/esm/decorators/orm/DeleteDateColumn.js +1 -0
  124. package/dist/esm/decorators/orm/Entity.js +1 -0
  125. package/dist/esm/decorators/orm/EventSubscriber.js +1 -0
  126. package/dist/esm/decorators/orm/Exclusion.js +1 -0
  127. package/dist/esm/decorators/orm/Generated.js +1 -0
  128. package/dist/esm/decorators/orm/Index.js +1 -0
  129. package/dist/esm/decorators/orm/JoinColumn.js +1 -0
  130. package/dist/esm/decorators/orm/JoinTable.js +1 -0
  131. package/dist/esm/decorators/orm/ManyToMany.js +1 -0
  132. package/dist/esm/decorators/orm/ManyToOne.js +1 -0
  133. package/dist/esm/decorators/orm/ObjectIdColumn.js +1 -0
  134. package/dist/esm/decorators/orm/OneToMany.js +1 -0
  135. package/dist/esm/decorators/orm/OneToOne.js +1 -0
  136. package/dist/esm/decorators/orm/PrimaryColumn.js +1 -0
  137. package/dist/esm/decorators/orm/PrimaryGeneratedColumn.js +1 -0
  138. package/dist/esm/decorators/orm/RelationId.js +1 -0
  139. package/dist/esm/decorators/orm/TableInheritance.js +1 -0
  140. package/dist/esm/decorators/orm/Tree.js +1 -0
  141. package/dist/esm/decorators/orm/TreeChildren.js +1 -0
  142. package/dist/esm/decorators/orm/TreeLevelColumn.js +1 -0
  143. package/dist/esm/decorators/orm/TreeParent.js +1 -0
  144. package/dist/esm/decorators/orm/Unique.js +1 -0
  145. package/dist/esm/decorators/orm/UpdateDateColumn.js +1 -0
  146. package/dist/esm/decorators/orm/VersionColumn.js +1 -0
  147. package/dist/esm/decorators/orm/ViewColumn.js +1 -0
  148. package/dist/esm/decorators/orm/ViewEntity.js +1 -0
  149. package/dist/esm/decorators/orm/VirtualColumn.js +1 -0
  150. package/dist/esm/exports/DatabaseComponent.js +2 -0
  151. package/dist/esm/exports/DatabaseProvider.js +2 -0
  152. package/dist/esm/exports/ORM.js +120 -0
  153. package/dist/esm/exports/ORMDecorators.js +43 -0
  154. package/dist/esm/providers/Database.js +339 -0
  155. package/dist/esm/providers/migration/ExecuteMigration.js +137 -0
  156. package/dist/esm/providers/migration/GenerateMigration.js +297 -0
  157. package/dist/esm/types/MigrationRunOptions.js +1 -0
  158. package/dist/types/components/Database.d.ts +333 -0
  159. package/dist/types/decorators/orm/AfterInsert.d.ts +1 -0
  160. package/dist/types/decorators/orm/AfterLoad.d.ts +1 -0
  161. package/dist/types/decorators/orm/AfterRecover.d.ts +1 -0
  162. package/dist/types/decorators/orm/AfterRemove.d.ts +1 -0
  163. package/dist/types/decorators/orm/AfterSoftRemove.d.ts +1 -0
  164. package/dist/types/decorators/orm/AfterUpdate.d.ts +1 -0
  165. package/dist/types/decorators/orm/BeforeInsert.d.ts +1 -0
  166. package/dist/types/decorators/orm/BeforeRecover.d.ts +1 -0
  167. package/dist/types/decorators/orm/BeforeRemove.d.ts +1 -0
  168. package/dist/types/decorators/orm/BeforeSoftRemove.d.ts +1 -0
  169. package/dist/types/decorators/orm/BeforeUpdate.d.ts +1 -0
  170. package/dist/types/decorators/orm/Check.d.ts +1 -0
  171. package/dist/types/decorators/orm/ChildEntity.d.ts +1 -0
  172. package/dist/types/decorators/orm/Column.d.ts +1 -0
  173. package/dist/types/decorators/orm/CreateDateColumn.d.ts +1 -0
  174. package/dist/types/decorators/orm/DeleteDateColumn.d.ts +1 -0
  175. package/dist/types/decorators/orm/Entity.d.ts +1 -0
  176. package/dist/types/decorators/orm/EventSubscriber.d.ts +1 -0
  177. package/dist/types/decorators/orm/Exclusion.d.ts +1 -0
  178. package/dist/types/decorators/orm/Generated.d.ts +1 -0
  179. package/dist/types/decorators/orm/Index.d.ts +1 -0
  180. package/dist/types/decorators/orm/JoinColumn.d.ts +1 -0
  181. package/dist/types/decorators/orm/JoinTable.d.ts +1 -0
  182. package/dist/types/decorators/orm/ManyToMany.d.ts +1 -0
  183. package/dist/types/decorators/orm/ManyToOne.d.ts +1 -0
  184. package/dist/types/decorators/orm/ObjectIdColumn.d.ts +1 -0
  185. package/dist/types/decorators/orm/OneToMany.d.ts +1 -0
  186. package/dist/types/decorators/orm/OneToOne.d.ts +1 -0
  187. package/dist/types/decorators/orm/PrimaryColumn.d.ts +1 -0
  188. package/dist/types/decorators/orm/PrimaryGeneratedColumn.d.ts +1 -0
  189. package/dist/types/decorators/orm/RelationId.d.ts +1 -0
  190. package/dist/types/decorators/orm/TableInheritance.d.ts +1 -0
  191. package/dist/types/decorators/orm/Tree.d.ts +1 -0
  192. package/dist/types/decorators/orm/TreeChildren.d.ts +1 -0
  193. package/dist/types/decorators/orm/TreeLevelColumn.d.ts +1 -0
  194. package/dist/types/decorators/orm/TreeParent.d.ts +1 -0
  195. package/dist/types/decorators/orm/Unique.d.ts +1 -0
  196. package/dist/types/decorators/orm/UpdateDateColumn.d.ts +1 -0
  197. package/dist/types/decorators/orm/VersionColumn.d.ts +1 -0
  198. package/dist/types/decorators/orm/ViewColumn.d.ts +1 -0
  199. package/dist/types/decorators/orm/ViewEntity.d.ts +1 -0
  200. package/dist/types/decorators/orm/VirtualColumn.d.ts +1 -0
  201. package/dist/types/exports/DatabaseComponent.d.ts +3 -0
  202. package/dist/types/exports/DatabaseProvider.d.ts +3 -0
  203. package/dist/types/exports/ORM.d.ts +193 -0
  204. package/dist/types/exports/ORMDecorators.d.ts +43 -0
  205. package/dist/types/providers/Database.d.ts +326 -0
  206. package/dist/types/providers/migration/ExecuteMigration.d.ts +40 -0
  207. package/dist/types/providers/migration/GenerateMigration.d.ts +59 -0
  208. package/dist/types/types/MigrationRunOptions.d.ts +19 -0
  209. package/package.json +81 -4
@@ -0,0 +1,137 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __metadata = (this && this.__metadata) || function (k, v) {
8
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
9
+ };
10
+ import { Provider, DTO, Application } from '@lakutata/core';
11
+ import { Configurable, Transient } from '@lakutata/core/decorator/di';
12
+ import { DataSource } from 'typeorm/data-source/DataSource.js';
13
+ import { MigrationExecutor } from 'typeorm/migration/MigrationExecutor.js';
14
+ import ansi from 'ansis';
15
+ /**
16
+ * The executor of the migrations, giving the migrations of the options of the database
17
+ */
18
+ class Executor extends MigrationExecutor {
19
+ /**
20
+ * The migrations of the options of the database, in their order
21
+ */
22
+ sourceMigrations() {
23
+ return this.getMigrations();
24
+ }
25
+ }
26
+ /**
27
+ * Run, revert or show the migrations of a database of the application, with its options (MIGRATION_RUN, MIGRATION_REVERT,
28
+ * MIGRATION_SHOW): the database is connected without synchronizing its schema nor running its migrations, the action
29
+ * done, then the application exits (with the code 1 when the action fails)
30
+ */
31
+ let ExecuteMigration = class ExecuteMigration extends Provider {
32
+ /**
33
+ * The transactions of the migrations: MIGRATION_TRANSACTION, else the migrationsTransactionMode of the database, else
34
+ * one for all
35
+ */
36
+ get transactionMode() {
37
+ return this.transaction ?? this.dataSource.migrationsTransactionMode ?? 'all';
38
+ }
39
+ /**
40
+ * The prefix of the messages: the name of the database
41
+ */
42
+ get prefix() {
43
+ return this.dataSourceName ? `[${this.dataSourceName}] ` : '';
44
+ }
45
+ /**
46
+ * Initializer
47
+ * @protected
48
+ */
49
+ async init() {
50
+ const app = await this.getObject(Application);
51
+ const dataSource = new DataSource({ ...this.dataSource, synchronize: false, migrationsRun: false, dropSchema: false });
52
+ let failed = false;
53
+ try {
54
+ await dataSource.initialize();
55
+ await this.handle(dataSource);
56
+ }
57
+ catch (error) {
58
+ console.error(ansi.red `${this.prefix}The migrations could not be ${this.action === 'show' ? 'shown' : this.action === 'run' ? 'run' : 'reverted'}:`, error);
59
+ failed = true;
60
+ }
61
+ finally {
62
+ if (dataSource.isInitialized)
63
+ await dataSource.destroy();
64
+ }
65
+ //A failure stops the actions on the other databases
66
+ if (failed)
67
+ return app.exit(1);
68
+ if (this.exitProcess)
69
+ return app.exit(0);
70
+ }
71
+ /**
72
+ * Do the action on the database
73
+ * @param dataSource
74
+ * @protected
75
+ */
76
+ async handle(dataSource) {
77
+ const executor = new Executor(dataSource);
78
+ switch (this.action) {
79
+ case 'run': {
80
+ const pending = await executor.getPendingMigrations();
81
+ const ran = await dataSource.runMigrations({ transaction: this.transactionMode, fake: this.fake });
82
+ //The migrations marked as run are not given back by TypeORM
83
+ const executed = this.fake ? pending : ran;
84
+ if (!executed.length)
85
+ return console.log(ansi.green `${this.prefix}No pending migration`);
86
+ for (const migration of executed)
87
+ console.log(ansi.green `${this.prefix}Migration ${ansi.blue(migration.name)} has been ${this.fake ? 'marked as run' : 'run'}`);
88
+ return;
89
+ }
90
+ case 'revert': {
91
+ const [last] = (await executor.getExecutedMigrations()).sort((a, b) => (b.id ?? 0) - (a.id ?? 0));
92
+ if (!last)
93
+ return console.log(ansi.yellow `${this.prefix}No migration to revert`);
94
+ await dataSource.undoLastMigration({ transaction: this.transactionMode, fake: this.fake });
95
+ return console.log(ansi.green `${this.prefix}Migration ${ansi.blue(last.name)} has been ${this.fake ? 'marked as reverted' : 'reverted'}`);
96
+ }
97
+ case 'show': {
98
+ const executed = new Set((await executor.getExecutedMigrations()).map((migration) => migration.name));
99
+ const migrations = executor.sourceMigrations();
100
+ if (!migrations.length)
101
+ return console.log(ansi.yellow `${this.prefix}No migration in the options of the database`);
102
+ for (const migration of migrations)
103
+ console.log(`${this.prefix}${executed.has(migration.name) ? ansi.green `[X]` : ansi.yellow `[ ]`} ${migration.name}`);
104
+ const pending = migrations.filter((migration) => !executed.has(migration.name)).length;
105
+ return console.log(pending ? ansi.yellow `${this.prefix}${pending} pending migration${pending > 1 ? 's' : ''}` : ansi.green `${this.prefix}No pending migration`);
106
+ }
107
+ }
108
+ }
109
+ };
110
+ __decorate([
111
+ Configurable(DTO.String().valid('run', 'revert', 'show').required()),
112
+ __metadata("design:type", String)
113
+ ], ExecuteMigration.prototype, "action", void 0);
114
+ __decorate([
115
+ Configurable(DTO.String().allow('').optional().default('')),
116
+ __metadata("design:type", String)
117
+ ], ExecuteMigration.prototype, "dataSourceName", void 0);
118
+ __decorate([
119
+ Configurable(),
120
+ __metadata("design:type", Object)
121
+ ], ExecuteMigration.prototype, "dataSource", void 0);
122
+ __decorate([
123
+ Configurable(DTO.String().valid('all', 'none', 'each').optional()),
124
+ __metadata("design:type", String)
125
+ ], ExecuteMigration.prototype, "transaction", void 0);
126
+ __decorate([
127
+ Configurable(DTO.Boolean().optional().default(false)),
128
+ __metadata("design:type", Boolean)
129
+ ], ExecuteMigration.prototype, "fake", void 0);
130
+ __decorate([
131
+ Configurable(DTO.Boolean().optional().default(true)),
132
+ __metadata("design:type", Boolean)
133
+ ], ExecuteMigration.prototype, "exitProcess", void 0);
134
+ ExecuteMigration = __decorate([
135
+ Transient()
136
+ ], ExecuteMigration);
137
+ export { ExecuteMigration };
@@ -0,0 +1,297 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __metadata = (this && this.__metadata) || function (k, v) {
8
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
9
+ };
10
+ var GenerateMigration_1;
11
+ /*
12
+ * The generation of the migrations, rewritten from the command migration:generate of TypeORM (Copyright (c) 2015-2025
13
+ * TypeORM, MIT License, see THIRD_PARTY_NOTICES.md)
14
+ */
15
+ import { Provider, DTO, Application } from '@lakutata/core';
16
+ import { Configurable, Transient } from '@lakutata/core/decorator/di';
17
+ import path from 'path';
18
+ import { readFileSync } from 'fs';
19
+ import { DataSource } from 'typeorm/data-source/DataSource.js';
20
+ import { format } from '@sqltools/formatter/lib/sqlFormatter.js';
21
+ import { camelCase } from 'typeorm/util/StringUtils.js';
22
+ import { PlatformTools } from 'typeorm/platform/PlatformTools.js';
23
+ import { CommandUtils } from 'typeorm/commands/CommandUtils.js';
24
+ import ansi from 'ansis';
25
+ let GenerateMigration = class GenerateMigration extends Provider {
26
+ static { GenerateMigration_1 = this; }
27
+ get extension() {
28
+ return this.outputJs ? '.js' : '.ts';
29
+ }
30
+ get filename() {
31
+ return this.timestamp + '-' + (this.dataSourceName ? this.dataSourceName : path.basename(this.path)) + this.extension;
32
+ }
33
+ #app;
34
+ #dataSource;
35
+ /**
36
+ * Initializer
37
+ * @protected
38
+ */
39
+ /**
40
+ * The migrations generated by the run (its databases share the process)
41
+ */
42
+ static { this.generated = 0; }
43
+ async init() {
44
+ this.#app = await this.getObject(Application);
45
+ this.#dataSource = new DataSource(this.dataSource);
46
+ this.#dataSource.setOptions({
47
+ synchronize: false,
48
+ migrationsRun: false,
49
+ dropSchema: false,
50
+ logging: false
51
+ });
52
+ this.#dataSource = await this.#dataSource.initialize();
53
+ await this.handle();
54
+ }
55
+ /**
56
+ * Destroyer
57
+ * @protected
58
+ */
59
+ async destroy() {
60
+ //The data source is destroyed once the schema is read
61
+ if (this.#dataSource?.isInitialized)
62
+ await this.#dataSource.destroy();
63
+ }
64
+ async handle() {
65
+ try {
66
+ const upSqls = [], downSqls = [];
67
+ try {
68
+ const sqlInMemory = await this.#dataSource.driver
69
+ .createSchemaBuilder()
70
+ .log();
71
+ if (this.pretty) {
72
+ sqlInMemory.upQueries.forEach((upQuery) => {
73
+ upQuery.query = GenerateMigration_1.prettifyQuery(upQuery.query);
74
+ });
75
+ sqlInMemory.downQueries.forEach((downQuery) => {
76
+ downQuery.query =
77
+ GenerateMigration_1.prettifyQuery(downQuery.query);
78
+ });
79
+ }
80
+ sqlInMemory.upQueries.forEach((upQuery) => {
81
+ upSqls.push(' await queryRunner.query(`' +
82
+ GenerateMigration_1.escapeTemplateLiteral(upQuery.query) +
83
+ '`' +
84
+ GenerateMigration_1.queryParams(upQuery.parameters) +
85
+ ');');
86
+ });
87
+ sqlInMemory.downQueries.forEach((downQuery) => {
88
+ downSqls.push(' await queryRunner.query(`' +
89
+ GenerateMigration_1.escapeTemplateLiteral(downQuery.query) +
90
+ '`' +
91
+ GenerateMigration_1.queryParams(downQuery.parameters) +
92
+ ');');
93
+ });
94
+ }
95
+ finally {
96
+ await this.#dataSource.destroy();
97
+ }
98
+ if (!upSqls.length) {
99
+ if (this.check) {
100
+ console.log(ansi.green `No changes in database schema were found`);
101
+ if (this.exitProcess) {
102
+ return this.#app.exit(0);
103
+ }
104
+ else {
105
+ return;
106
+ }
107
+ }
108
+ else {
109
+ console.log(ansi.yellow `No changes in database schema were found`);
110
+ if (this.exitProcess) {
111
+ //The code 1 when no database of the run had a change
112
+ return this.#app.exit(GenerateMigration_1.generated ? 0 : 1);
113
+ }
114
+ else {
115
+ return;
116
+ }
117
+ }
118
+ }
119
+ else if (!this.path) {
120
+ console.log(ansi.yellow `Please specify a migration path`);
121
+ return this.#app.exit(1);
122
+ }
123
+ const fileContent = this.outputJs
124
+ ? GenerateMigration_1.getJavascriptTemplate(path.basename(this.path), this.timestamp, upSqls, downSqls.reverse(), this.esm)
125
+ : GenerateMigration_1.getTemplate(path.basename(this.path), this.timestamp, upSqls, downSqls.reverse());
126
+ if (this.check) {
127
+ console.log(ansi.yellow `Unexpected changes in database schema were found in check mode:\n\n${ansi.white(fileContent)}`);
128
+ //Changes found in check mode: the code 1, as the check of TypeORM
129
+ return this.#app.exit(1);
130
+ }
131
+ GenerateMigration_1.generated++;
132
+ if (this.dryRun) {
133
+ console.log(ansi.green(`Migration ${ansi.blue(this.path + this.extension)} has content:\n\n${ansi.white(fileContent)}`));
134
+ if (this.exitProcess)
135
+ return this.#app.exit(0);
136
+ }
137
+ else {
138
+ const migrationFileName = path.isAbsolute(this.path) ? path.join(this.path, this.filename) : path.join(process.cwd(), this.path, this.filename);
139
+ await CommandUtils.createFile(migrationFileName, fileContent);
140
+ console.log(ansi.green `Migration ${ansi.blue(migrationFileName)} has been generated successfully.`);
141
+ if (this.exitProcess) {
142
+ return this.#app.exit(0);
143
+ }
144
+ else {
145
+ return;
146
+ }
147
+ }
148
+ }
149
+ catch (err) {
150
+ PlatformTools.logCmdErr('Error during migration generation:', err);
151
+ return this.#app.exit(1);
152
+ }
153
+ }
154
+ /**
155
+ * The module the migrations import their types from: @lakutata/orm when the project depends on it, otherwise
156
+ * lakutata/orm (the migrations of the projects depending on lakutata)
157
+ */
158
+ static migrationModule() {
159
+ try {
160
+ const pkg = JSON.parse(readFileSync(path.join(process.cwd(), 'package.json'), 'utf8'));
161
+ if (pkg.dependencies?.['@lakutata/orm'] || pkg.devDependencies?.['@lakutata/orm'])
162
+ return '@lakutata/orm';
163
+ }
164
+ catch {
165
+ //No package.json
166
+ }
167
+ return 'lakutata/orm';
168
+ }
169
+ /**
170
+ * Escape a query for a template literal of the migration: its backslashes, its backticks and its interpolations
171
+ * (the defaults and the comments of the columns are in the queries)
172
+ * @param query
173
+ */
174
+ static escapeTemplateLiteral(query) {
175
+ return query.replace(/\\/g, '\\\\').replace(/`/g, '\\`').replace(/\$\{/g, '\\${');
176
+ }
177
+ /**
178
+ * Formats query parameters for migration queries if parameters actually exist
179
+ */
180
+ static queryParams(parameters) {
181
+ if (!parameters || !parameters.length) {
182
+ return '';
183
+ }
184
+ return `, ${JSON.stringify(parameters)}`;
185
+ }
186
+ /**
187
+ * Gets contents of the migration file.
188
+ */
189
+ static getTemplate(name, timestamp, upSqls, downSqls) {
190
+ const migrationName = `${camelCase(name, true)}${timestamp}`;
191
+ return `import { MigrationInterface, QueryRunner } from "${GenerateMigration_1.migrationModule()}";
192
+
193
+ export class ${migrationName} implements MigrationInterface {
194
+ name = '${migrationName}'
195
+
196
+ public async up(queryRunner: QueryRunner): Promise<void> {
197
+ ${upSqls.join(`
198
+ `)}
199
+ }
200
+
201
+ public async down(queryRunner: QueryRunner): Promise<void> {
202
+ ${downSqls.join(`
203
+ `)}
204
+ }
205
+
206
+ }
207
+ `;
208
+ }
209
+ /**
210
+ * Gets contents of the migration file in Javascript.
211
+ */
212
+ static getJavascriptTemplate(name, timestamp, upSqls, downSqls, esm) {
213
+ const migrationName = `${camelCase(name, true)}${timestamp}`;
214
+ const exportMethod = esm ? 'export' : 'module.exports =';
215
+ const migrationModule = GenerateMigration_1.migrationModule();
216
+ return `/**
217
+ * @typedef {import('${migrationModule}').MigrationInterface} MigrationInterface
218
+ * @typedef {import('${migrationModule}').QueryRunner} QueryRunner
219
+ */
220
+
221
+ /**
222
+ * @class
223
+ * @implements {MigrationInterface}
224
+ */
225
+ ${exportMethod} class ${migrationName} {
226
+ name = '${migrationName}'
227
+
228
+ /**
229
+ * @param {QueryRunner} queryRunner
230
+ */
231
+ async up(queryRunner) {
232
+ ${upSqls.join(`
233
+ `)}
234
+ }
235
+
236
+ /**
237
+ * @param {QueryRunner} queryRunner
238
+ */
239
+ async down(queryRunner) {
240
+ ${downSqls.join(`
241
+ `)}
242
+ }
243
+ }
244
+ `;
245
+ }
246
+ /**
247
+ *
248
+ */
249
+ static prettifyQuery(query) {
250
+ const formattedQuery = format(query, { indent: ' ' });
251
+ return ('\n' + formattedQuery.replace(/^/gm, ' ') + '\n ');
252
+ }
253
+ };
254
+ __decorate([
255
+ Configurable(DTO.String().required()),
256
+ __metadata("design:type", String)
257
+ ], GenerateMigration.prototype, "path", void 0);
258
+ __decorate([
259
+ Configurable(DTO.String().allow('').optional().default('')),
260
+ __metadata("design:type", String)
261
+ ], GenerateMigration.prototype, "dataSourceName", void 0);
262
+ __decorate([
263
+ Configurable(),
264
+ __metadata("design:type", Object)
265
+ ], GenerateMigration.prototype, "dataSource", void 0);
266
+ __decorate([
267
+ Configurable(DTO.Boolean().optional().default(true)),
268
+ __metadata("design:type", Boolean)
269
+ ], GenerateMigration.prototype, "pretty", void 0);
270
+ __decorate([
271
+ Configurable(DTO.Boolean().optional().default(false)),
272
+ __metadata("design:type", Boolean)
273
+ ], GenerateMigration.prototype, "outputJs", void 0);
274
+ __decorate([
275
+ Configurable(DTO.Boolean().optional().default(false)),
276
+ __metadata("design:type", Boolean)
277
+ ], GenerateMigration.prototype, "esm", void 0);
278
+ __decorate([
279
+ Configurable(DTO.Boolean().optional().default(false)),
280
+ __metadata("design:type", Boolean)
281
+ ], GenerateMigration.prototype, "dryRun", void 0);
282
+ __decorate([
283
+ Configurable(DTO.Boolean().optional().default(false)),
284
+ __metadata("design:type", Boolean)
285
+ ], GenerateMigration.prototype, "check", void 0);
286
+ __decorate([
287
+ Configurable(DTO.Number().optional().default(() => Date.now())),
288
+ __metadata("design:type", Number)
289
+ ], GenerateMigration.prototype, "timestamp", void 0);
290
+ __decorate([
291
+ Configurable(DTO.Boolean().optional().default(true)),
292
+ __metadata("design:type", Boolean)
293
+ ], GenerateMigration.prototype, "exitProcess", void 0);
294
+ GenerateMigration = GenerateMigration_1 = __decorate([
295
+ Transient()
296
+ ], GenerateMigration);
297
+ export { GenerateMigration };
@@ -0,0 +1 @@
1
+ export {};