@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,303 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ 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;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ var GenerateMigration_1;
15
+ Object.defineProperty(exports, "__esModule", { value: true });
16
+ exports.GenerateMigration = void 0;
17
+ /*
18
+ * The generation of the migrations, rewritten from the command migration:generate of TypeORM (Copyright (c) 2015-2025
19
+ * TypeORM, MIT License, see THIRD_PARTY_NOTICES.md)
20
+ */
21
+ const core_1 = require("@lakutata/core");
22
+ const di_1 = require("@lakutata/core/decorator/di");
23
+ const path_1 = __importDefault(require("path"));
24
+ const fs_1 = require("fs");
25
+ const DataSource_js_1 = require("typeorm/data-source/DataSource.js");
26
+ const sqlFormatter_js_1 = require("@sqltools/formatter/lib/sqlFormatter.js");
27
+ const StringUtils_js_1 = require("typeorm/util/StringUtils.js");
28
+ const PlatformTools_js_1 = require("typeorm/platform/PlatformTools.js");
29
+ const CommandUtils_js_1 = require("typeorm/commands/CommandUtils.js");
30
+ const ansis_1 = __importDefault(require("ansis"));
31
+ let GenerateMigration = class GenerateMigration extends core_1.Provider {
32
+ static { GenerateMigration_1 = this; }
33
+ get extension() {
34
+ return this.outputJs ? '.js' : '.ts';
35
+ }
36
+ get filename() {
37
+ return this.timestamp + '-' + (this.dataSourceName ? this.dataSourceName : path_1.default.basename(this.path)) + this.extension;
38
+ }
39
+ #app;
40
+ #dataSource;
41
+ /**
42
+ * Initializer
43
+ * @protected
44
+ */
45
+ /**
46
+ * The migrations generated by the run (its databases share the process)
47
+ */
48
+ static { this.generated = 0; }
49
+ async init() {
50
+ this.#app = await this.getObject(core_1.Application);
51
+ this.#dataSource = new DataSource_js_1.DataSource(this.dataSource);
52
+ this.#dataSource.setOptions({
53
+ synchronize: false,
54
+ migrationsRun: false,
55
+ dropSchema: false,
56
+ logging: false
57
+ });
58
+ this.#dataSource = await this.#dataSource.initialize();
59
+ await this.handle();
60
+ }
61
+ /**
62
+ * Destroyer
63
+ * @protected
64
+ */
65
+ async destroy() {
66
+ //The data source is destroyed once the schema is read
67
+ if (this.#dataSource?.isInitialized)
68
+ await this.#dataSource.destroy();
69
+ }
70
+ async handle() {
71
+ try {
72
+ const upSqls = [], downSqls = [];
73
+ try {
74
+ const sqlInMemory = await this.#dataSource.driver
75
+ .createSchemaBuilder()
76
+ .log();
77
+ if (this.pretty) {
78
+ sqlInMemory.upQueries.forEach((upQuery) => {
79
+ upQuery.query = GenerateMigration_1.prettifyQuery(upQuery.query);
80
+ });
81
+ sqlInMemory.downQueries.forEach((downQuery) => {
82
+ downQuery.query =
83
+ GenerateMigration_1.prettifyQuery(downQuery.query);
84
+ });
85
+ }
86
+ sqlInMemory.upQueries.forEach((upQuery) => {
87
+ upSqls.push(' await queryRunner.query(`' +
88
+ GenerateMigration_1.escapeTemplateLiteral(upQuery.query) +
89
+ '`' +
90
+ GenerateMigration_1.queryParams(upQuery.parameters) +
91
+ ');');
92
+ });
93
+ sqlInMemory.downQueries.forEach((downQuery) => {
94
+ downSqls.push(' await queryRunner.query(`' +
95
+ GenerateMigration_1.escapeTemplateLiteral(downQuery.query) +
96
+ '`' +
97
+ GenerateMigration_1.queryParams(downQuery.parameters) +
98
+ ');');
99
+ });
100
+ }
101
+ finally {
102
+ await this.#dataSource.destroy();
103
+ }
104
+ if (!upSqls.length) {
105
+ if (this.check) {
106
+ console.log(ansis_1.default.green `No changes in database schema were found`);
107
+ if (this.exitProcess) {
108
+ return this.#app.exit(0);
109
+ }
110
+ else {
111
+ return;
112
+ }
113
+ }
114
+ else {
115
+ console.log(ansis_1.default.yellow `No changes in database schema were found`);
116
+ if (this.exitProcess) {
117
+ //The code 1 when no database of the run had a change
118
+ return this.#app.exit(GenerateMigration_1.generated ? 0 : 1);
119
+ }
120
+ else {
121
+ return;
122
+ }
123
+ }
124
+ }
125
+ else if (!this.path) {
126
+ console.log(ansis_1.default.yellow `Please specify a migration path`);
127
+ return this.#app.exit(1);
128
+ }
129
+ const fileContent = this.outputJs
130
+ ? GenerateMigration_1.getJavascriptTemplate(path_1.default.basename(this.path), this.timestamp, upSqls, downSqls.reverse(), this.esm)
131
+ : GenerateMigration_1.getTemplate(path_1.default.basename(this.path), this.timestamp, upSqls, downSqls.reverse());
132
+ if (this.check) {
133
+ console.log(ansis_1.default.yellow `Unexpected changes in database schema were found in check mode:\n\n${ansis_1.default.white(fileContent)}`);
134
+ //Changes found in check mode: the code 1, as the check of TypeORM
135
+ return this.#app.exit(1);
136
+ }
137
+ GenerateMigration_1.generated++;
138
+ if (this.dryRun) {
139
+ console.log(ansis_1.default.green(`Migration ${ansis_1.default.blue(this.path + this.extension)} has content:\n\n${ansis_1.default.white(fileContent)}`));
140
+ if (this.exitProcess)
141
+ return this.#app.exit(0);
142
+ }
143
+ else {
144
+ const migrationFileName = path_1.default.isAbsolute(this.path) ? path_1.default.join(this.path, this.filename) : path_1.default.join(process.cwd(), this.path, this.filename);
145
+ await CommandUtils_js_1.CommandUtils.createFile(migrationFileName, fileContent);
146
+ console.log(ansis_1.default.green `Migration ${ansis_1.default.blue(migrationFileName)} has been generated successfully.`);
147
+ if (this.exitProcess) {
148
+ return this.#app.exit(0);
149
+ }
150
+ else {
151
+ return;
152
+ }
153
+ }
154
+ }
155
+ catch (err) {
156
+ PlatformTools_js_1.PlatformTools.logCmdErr('Error during migration generation:', err);
157
+ return this.#app.exit(1);
158
+ }
159
+ }
160
+ /**
161
+ * The module the migrations import their types from: @lakutata/orm when the project depends on it, otherwise
162
+ * lakutata/orm (the migrations of the projects depending on lakutata)
163
+ */
164
+ static migrationModule() {
165
+ try {
166
+ const pkg = JSON.parse((0, fs_1.readFileSync)(path_1.default.join(process.cwd(), 'package.json'), 'utf8'));
167
+ if (pkg.dependencies?.['@lakutata/orm'] || pkg.devDependencies?.['@lakutata/orm'])
168
+ return '@lakutata/orm';
169
+ }
170
+ catch {
171
+ //No package.json
172
+ }
173
+ return 'lakutata/orm';
174
+ }
175
+ /**
176
+ * Escape a query for a template literal of the migration: its backslashes, its backticks and its interpolations
177
+ * (the defaults and the comments of the columns are in the queries)
178
+ * @param query
179
+ */
180
+ static escapeTemplateLiteral(query) {
181
+ return query.replace(/\\/g, '\\\\').replace(/`/g, '\\`').replace(/\$\{/g, '\\${');
182
+ }
183
+ /**
184
+ * Formats query parameters for migration queries if parameters actually exist
185
+ */
186
+ static queryParams(parameters) {
187
+ if (!parameters || !parameters.length) {
188
+ return '';
189
+ }
190
+ return `, ${JSON.stringify(parameters)}`;
191
+ }
192
+ /**
193
+ * Gets contents of the migration file.
194
+ */
195
+ static getTemplate(name, timestamp, upSqls, downSqls) {
196
+ const migrationName = `${(0, StringUtils_js_1.camelCase)(name, true)}${timestamp}`;
197
+ return `import { MigrationInterface, QueryRunner } from "${GenerateMigration_1.migrationModule()}";
198
+
199
+ export class ${migrationName} implements MigrationInterface {
200
+ name = '${migrationName}'
201
+
202
+ public async up(queryRunner: QueryRunner): Promise<void> {
203
+ ${upSqls.join(`
204
+ `)}
205
+ }
206
+
207
+ public async down(queryRunner: QueryRunner): Promise<void> {
208
+ ${downSqls.join(`
209
+ `)}
210
+ }
211
+
212
+ }
213
+ `;
214
+ }
215
+ /**
216
+ * Gets contents of the migration file in Javascript.
217
+ */
218
+ static getJavascriptTemplate(name, timestamp, upSqls, downSqls, esm) {
219
+ const migrationName = `${(0, StringUtils_js_1.camelCase)(name, true)}${timestamp}`;
220
+ const exportMethod = esm ? 'export' : 'module.exports =';
221
+ const migrationModule = GenerateMigration_1.migrationModule();
222
+ return `/**
223
+ * @typedef {import('${migrationModule}').MigrationInterface} MigrationInterface
224
+ * @typedef {import('${migrationModule}').QueryRunner} QueryRunner
225
+ */
226
+
227
+ /**
228
+ * @class
229
+ * @implements {MigrationInterface}
230
+ */
231
+ ${exportMethod} class ${migrationName} {
232
+ name = '${migrationName}'
233
+
234
+ /**
235
+ * @param {QueryRunner} queryRunner
236
+ */
237
+ async up(queryRunner) {
238
+ ${upSqls.join(`
239
+ `)}
240
+ }
241
+
242
+ /**
243
+ * @param {QueryRunner} queryRunner
244
+ */
245
+ async down(queryRunner) {
246
+ ${downSqls.join(`
247
+ `)}
248
+ }
249
+ }
250
+ `;
251
+ }
252
+ /**
253
+ *
254
+ */
255
+ static prettifyQuery(query) {
256
+ const formattedQuery = (0, sqlFormatter_js_1.format)(query, { indent: ' ' });
257
+ return ('\n' + formattedQuery.replace(/^/gm, ' ') + '\n ');
258
+ }
259
+ };
260
+ exports.GenerateMigration = GenerateMigration;
261
+ __decorate([
262
+ (0, di_1.Configurable)(core_1.DTO.String().required()),
263
+ __metadata("design:type", String)
264
+ ], GenerateMigration.prototype, "path", void 0);
265
+ __decorate([
266
+ (0, di_1.Configurable)(core_1.DTO.String().allow('').optional().default('')),
267
+ __metadata("design:type", String)
268
+ ], GenerateMigration.prototype, "dataSourceName", void 0);
269
+ __decorate([
270
+ (0, di_1.Configurable)(),
271
+ __metadata("design:type", Object)
272
+ ], GenerateMigration.prototype, "dataSource", void 0);
273
+ __decorate([
274
+ (0, di_1.Configurable)(core_1.DTO.Boolean().optional().default(true)),
275
+ __metadata("design:type", Boolean)
276
+ ], GenerateMigration.prototype, "pretty", void 0);
277
+ __decorate([
278
+ (0, di_1.Configurable)(core_1.DTO.Boolean().optional().default(false)),
279
+ __metadata("design:type", Boolean)
280
+ ], GenerateMigration.prototype, "outputJs", void 0);
281
+ __decorate([
282
+ (0, di_1.Configurable)(core_1.DTO.Boolean().optional().default(false)),
283
+ __metadata("design:type", Boolean)
284
+ ], GenerateMigration.prototype, "esm", void 0);
285
+ __decorate([
286
+ (0, di_1.Configurable)(core_1.DTO.Boolean().optional().default(false)),
287
+ __metadata("design:type", Boolean)
288
+ ], GenerateMigration.prototype, "dryRun", void 0);
289
+ __decorate([
290
+ (0, di_1.Configurable)(core_1.DTO.Boolean().optional().default(false)),
291
+ __metadata("design:type", Boolean)
292
+ ], GenerateMigration.prototype, "check", void 0);
293
+ __decorate([
294
+ (0, di_1.Configurable)(core_1.DTO.Number().optional().default(() => Date.now())),
295
+ __metadata("design:type", Number)
296
+ ], GenerateMigration.prototype, "timestamp", void 0);
297
+ __decorate([
298
+ (0, di_1.Configurable)(core_1.DTO.Boolean().optional().default(true)),
299
+ __metadata("design:type", Boolean)
300
+ ], GenerateMigration.prototype, "exitProcess", void 0);
301
+ exports.GenerateMigration = GenerateMigration = GenerateMigration_1 = __decorate([
302
+ (0, di_1.Transient)()
303
+ ], GenerateMigration);
@@ -0,0 +1,19 @@
1
+ /**
2
+ * How {@link Database.runMigrations} and {@link Database.undoLastMigration} run the migrations: in transactions or not,
3
+ * for real or only recorded.
4
+ */
5
+ export type MigrationRunOptions = {
6
+ /**
7
+ * The transactions wrapping the migrations: `'all'` runs them all in one transaction (one failure rolls them all
8
+ * back), `'each'` runs each one in its own transaction (the ones before a failure stay applied), `'none'` runs them
9
+ * without a transaction. A migration may override it with its own `transaction` property.
10
+ * @default The `migrationsTransactionMode` of the connection options for `runMigrations()`, else `'all'`
11
+ */
12
+ transaction?: 'all' | 'none' | 'each';
13
+ /**
14
+ * Record the migrations as run (or remove them as reverted) in the migrations table without running their `up()`
15
+ * (or `down()`): for a database whose schema is already up to date.
16
+ * @default false
17
+ */
18
+ fake?: boolean;
19
+ };
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,344 @@
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 { Configurable, Singleton } from '@lakutata/core/decorator/di';
11
+ import { Component } from '@lakutata/core';
12
+ import { DataSource } from 'typeorm/data-source/DataSource.js';
13
+ /**
14
+ * Build the registration of a {@link Database} component, for the `components` of the application options: the
15
+ * component class with its TypeORM connection options.
16
+ * @param options The TypeORM connection options (`DataSourceOptions`): the driver `type`, the connection settings, the
17
+ * `entities`, the `migrations`, `synchronize`, `migrationsRun`, `logging`… Passed to TypeORM as they are.
18
+ * @returns The registration `{class: Database, options}`.
19
+ * @example
20
+ * ```typescript
21
+ * import {Application} from 'lakutata'
22
+ * import {buildDatabaseOptions} from 'lakutata/com/database'
23
+ * import {Column, Entity, PrimaryGeneratedColumn} from 'lakutata/decorator/orm'
24
+ *
25
+ * @Entity()
26
+ * class User {
27
+ * @PrimaryGeneratedColumn()
28
+ * public id: number
29
+ *
30
+ * @Column()
31
+ * public name: string
32
+ * }
33
+ *
34
+ * Application.run(() => ({
35
+ * id: 'com.example.app',
36
+ * name: 'Example',
37
+ * components: {
38
+ * //A PostgreSQL connection (the pg package installed), the component named db
39
+ * db: buildDatabaseOptions({
40
+ * type: 'postgres',
41
+ * host: 'localhost',
42
+ * port: 5432,
43
+ * username: 'postgres',
44
+ * password: 'secret',
45
+ * database: 'example',
46
+ * entities: [User]
47
+ * })
48
+ * },
49
+ * //Connected while the application launches: a connection failure stops it
50
+ * bootstrap: ['db']
51
+ * }))
52
+ * ```
53
+ */
54
+ export const buildDatabaseOptions = (options) => ({
55
+ class: Database,
56
+ options: options
57
+ });
58
+ /**
59
+ * A database connection shared by the whole application: a singleton component wrapping a TypeORM `DataSource`.
60
+ *
61
+ * Register it in the `components` of the application options with {@link buildDatabaseOptions}, then inject it by its
62
+ * name (`@Inject('db')`) or get it with `getObject('db')`. It connects when it is created (while the application
63
+ * launches when it is listed in `bootstrap`, otherwise on its first use): a connection failure rejects its creation
64
+ * with the driver error. TypeORM applies `synchronize` and `migrationsRun` of the options while connecting. It
65
+ * disconnects when the application stops.
66
+ *
67
+ * An application may register several of them (one per database), each under its own name. Their names are the ones
68
+ * the migration commands of the application (`MIGRATION_GENERATE`, `MIGRATION_RUN`…) select with `MIGRATION_DATABASE`.
69
+ * @example
70
+ * ```typescript
71
+ * import {Application, Component} from 'lakutata'
72
+ * import {Inject} from 'lakutata/decorator/di'
73
+ * import {buildDatabaseOptions, Database} from 'lakutata/com/database'
74
+ * import {Column, Entity, PrimaryGeneratedColumn} from 'lakutata/decorator/orm'
75
+ *
76
+ * @Entity()
77
+ * class Account {
78
+ * @PrimaryGeneratedColumn()
79
+ * public id: number
80
+ *
81
+ * @Column('integer', {default: 0})
82
+ * public balance: number
83
+ * }
84
+ *
85
+ * class Bank extends Component {
86
+ * @Inject('db')
87
+ * protected readonly db: Database
88
+ *
89
+ * public async balance(id: number): Promise<number> {
90
+ * const account: Account | null = await this.db.getRepository(Account).findOneBy({id: id})
91
+ * return account ? account.balance : 0
92
+ * }
93
+ *
94
+ * //Both updates are committed, or none when one fails
95
+ * public async transfer(from: number, to: number, amount: number): Promise<void> {
96
+ * await this.db.transaction(async (manager): Promise<void> => {
97
+ * await manager.decrement(Account, {id: from}, 'balance', amount)
98
+ * await manager.increment(Account, {id: to}, 'balance', amount)
99
+ * })
100
+ * }
101
+ * }
102
+ *
103
+ * Application.run(() => ({
104
+ * id: 'com.example.bank',
105
+ * name: 'Bank',
106
+ * components: {
107
+ * db: buildDatabaseOptions({type: 'postgres', url: 'postgres://postgres:secret@localhost:5432/bank', entities: [Account]}),
108
+ * bank: {class: Bank}
109
+ * },
110
+ * bootstrap: ['db']
111
+ * }))
112
+ * ```
113
+ */
114
+ let Database = class Database extends Component {
115
+ /**
116
+ * Load the provider generating the migrations of the database. The application calls it when it is started with
117
+ * `MIGRATION_GENERATE`: the applications do not call it.
118
+ * @returns The migration generator provider class.
119
+ */
120
+ static { this.migrationGenerator = async () => (await import('../providers/migration/GenerateMigration.js')).GenerateMigration; }
121
+ /**
122
+ * Load the provider running, reverting or showing the migrations of the database. The application calls it when it
123
+ * is started with `MIGRATION_RUN`, `MIGRATION_REVERT` or `MIGRATION_SHOW`: the applications do not call it.
124
+ * @returns The migration executor provider class.
125
+ */
126
+ static { this.migrationExecutor = async () => (await import('../providers/migration/ExecuteMigration.js')).ExecuteMigration; }
127
+ #datasource;
128
+ /**
129
+ * The TypeORM `DataSource` of the connection, for the subclasses needing what this class does not expose.
130
+ */
131
+ get datasource() {
132
+ return this.#datasource;
133
+ }
134
+ /**
135
+ * The TypeORM driver of the connection (PostgreSQL, MySQL, SQLite…).
136
+ */
137
+ get driver() {
138
+ return this.datasource.driver;
139
+ }
140
+ /**
141
+ * The entity manager of the connection: the TypeORM operations on any entity (`find`, `save`, `delete`…) outside a
142
+ * transaction.
143
+ */
144
+ get manager() {
145
+ return this.datasource.manager;
146
+ }
147
+ /**
148
+ * Replace the naming strategy of the connection, which names the tables, the columns and the constraints of the
149
+ * entities. Set it before the metadata is used: the names already built are not renamed.
150
+ * @param instance The naming strategy.
151
+ */
152
+ set namingStrategy(instance) {
153
+ this.datasource.namingStrategy = instance;
154
+ }
155
+ /**
156
+ * The naming strategy of the connection, which names the tables, the columns and the constraints of the entities.
157
+ * @default TypeORM's `DefaultNamingStrategy`, unless the options set `namingStrategy`
158
+ */
159
+ get namingStrategy() {
160
+ return this.datasource.namingStrategy;
161
+ }
162
+ /**
163
+ * The entity subscribers registered on the connection (the `subscribers` of the options).
164
+ */
165
+ get subscribers() {
166
+ return this.datasource.subscribers;
167
+ }
168
+ /**
169
+ * The metadata of every entity registered on the connection.
170
+ */
171
+ get entityMetadatas() {
172
+ return this.datasource.entityMetadatas;
173
+ }
174
+ /**
175
+ * The metadata of every entity registered on the connection, by entity target (class, name or schema): the same as
176
+ * {@link Database.entityMetadatas}, for fast lookups.
177
+ */
178
+ get entityMetadatasMap() {
179
+ return this.datasource.entityMetadatasMap;
180
+ }
181
+ /**
182
+ * The query result cache of the connection, `undefined` unless the options enable `cache`.
183
+ */
184
+ get queryResultCache() {
185
+ return this.datasource.queryResultCache;
186
+ }
187
+ /**
188
+ * Connect to the database with the options.
189
+ * @protected
190
+ */
191
+ async init() {
192
+ this.#datasource = await (new DataSource(this.options)).initialize();
193
+ }
194
+ /**
195
+ * Disconnect from the database.
196
+ * @protected
197
+ */
198
+ async destroy() {
199
+ await this.datasource.destroy();
200
+ }
201
+ /**
202
+ * Create or update the database schema from the registered entities (the tables, columns, indices and foreign
203
+ * keys). Meant for development: the migrations change the schema of a production database.
204
+ * @param dropBeforeSync Drop every table of the database schema, with its data (also the tables of no entity),
205
+ * before creating the schema. Defaults to `false`.
206
+ * @returns Resolves once the schema is built.
207
+ * @throws {CannotExecuteNotConnectedError} When the connection is closed.
208
+ */
209
+ async synchronize(dropBeforeSync) {
210
+ return await this.datasource.synchronize(dropBeforeSync);
211
+ }
212
+ /**
213
+ * Run the pending migrations (the `migrations` of the options not yet recorded in the migrations table), in their
214
+ * timestamp order.
215
+ * @param options The transactions of the migrations, and whether they are only recorded (`fake`).
216
+ * @returns The migrations run, an empty array when none is pending.
217
+ * @throws {CannotExecuteNotConnectedError} When the connection is closed.
218
+ * @throws {Error} The error of a failed migration, once its transaction (`'all'` or `'each'`) is rolled back.
219
+ */
220
+ async runMigrations(options) {
221
+ return await this.datasource.runMigrations(options);
222
+ }
223
+ /**
224
+ * Revert the last migration run (its `down()`), and remove it from the migrations table. Does nothing when no
225
+ * migration was run.
226
+ * @param options The transaction of the migration (`'all'` by default, `migrationsTransactionMode` not applying),
227
+ * and whether it is only removed from the migrations table (`fake`).
228
+ * @returns Resolves once the migration is reverted.
229
+ * @throws {CannotExecuteNotConnectedError} When the connection is closed.
230
+ */
231
+ async undoLastMigration(options) {
232
+ return await this.datasource.undoLastMigration(options);
233
+ }
234
+ /**
235
+ * Log each migration of the options with whether it was run (`[X]`) or not (`[ ]`), through the logger of the
236
+ * connection (shown when its `logging` includes `schema`).
237
+ * @returns Whether a migration is pending.
238
+ */
239
+ async showMigrations() {
240
+ return await this.datasource.showMigrations();
241
+ }
242
+ /**
243
+ * Whether an entity is registered on the connection.
244
+ * @param target The entity class, its name, or its table name.
245
+ * @returns `true` when the connection has its metadata.
246
+ */
247
+ hasMetadata(target) {
248
+ return this.datasource.hasMetadata(target);
249
+ }
250
+ /**
251
+ * The metadata of a registered entity: its table, columns, relations…
252
+ * @param target The entity class, its name, or its table name.
253
+ * @returns The metadata of the entity.
254
+ * @throws {EntityMetadataNotFoundError} When the entity is not registered on the connection.
255
+ */
256
+ getMetadata(target) {
257
+ return this.datasource.getMetadata(target);
258
+ }
259
+ /**
260
+ * The repository of an entity, created once per entity: its `find`, `save`, `delete`… operations outside a
261
+ * transaction (in a transaction, use the entity manager given to the callback).
262
+ * @param target The entity class, its name, or its `EntitySchema`.
263
+ * @returns The repository of the entity (a `MongoRepository` on a MongoDB connection).
264
+ * @throws {EntityMetadataNotFoundError} From the repository operations, when the entity is not registered.
265
+ */
266
+ getRepository(target) {
267
+ return this.datasource.getRepository(target);
268
+ }
269
+ /**
270
+ * The tree repository of an entity decorated with `@Tree()`: the operations on its ancestors and descendants
271
+ * (`findTrees`, `findDescendants`…).
272
+ * @param target The tree entity class, or its name.
273
+ * @returns The tree repository of the entity.
274
+ * @throws {TreeRepositoryNotSupportedError} On a driver without tree support (MongoDB).
275
+ */
276
+ getTreeRepository(target) {
277
+ return this.datasource.getTreeRepository(target);
278
+ }
279
+ /**
280
+ * The MongoDB repository of an entity: the repository operations plus the MongoDB ones (`aggregate`, `bulkWrite`…).
281
+ * @param target The entity class, or its name.
282
+ * @returns The MongoDB repository of the entity.
283
+ * @throws {TypeORMError} When the connection is not a MongoDB one.
284
+ */
285
+ getMongoRepository(target) {
286
+ return this.datasource.getMongoRepository(target);
287
+ }
288
+ async transaction(inp1, inp2) {
289
+ return inp2 ? await this.datasource.transaction(inp1, inp2) : await this.datasource.transaction(inp1);
290
+ }
291
+ /**
292
+ * Run a raw SQL query.
293
+ * @param query The SQL, its parameters as placeholders: `$1`, `$2`… for PostgreSQL, `?` for MySQL and SQLite.
294
+ * @param parameters The values of the placeholders, escaped by the driver.
295
+ * @param queryRunner The query runner to run it on (a transaction of {@link Database.createQueryRunner}), a
296
+ * connection of the pool otherwise.
297
+ * @returns The raw result of the driver: the rows of a `SELECT` (an array of objects).
298
+ * @throws {QueryFailedError} When the database rejects the query.
299
+ */
300
+ async query(query, parameters, queryRunner) {
301
+ return await this.datasource.query(query, parameters, queryRunner);
302
+ }
303
+ createQueryBuilder(inp1, inp2, inp3) {
304
+ return arguments.length > 1 ? this.datasource.createQueryBuilder(inp1, inp2, inp3) : this.datasource.createQueryBuilder(inp1);
305
+ }
306
+ /**
307
+ * Create a query runner: one connection taken from the pool, to run several queries on the same connection and
308
+ * control its transaction by hand (`connect()`, `startTransaction()`, `commitTransaction()`,
309
+ * `rollbackTransaction()`). The caller must `release()` it, or the connection stays taken.
310
+ * @param mode With replication, `'master'` (the default) for the writes, `'slave'` for the reads on a replica.
311
+ * @returns The query runner, not connected until its first query or `connect()`.
312
+ */
313
+ createQueryRunner(mode) {
314
+ return this.datasource.createQueryRunner(mode);
315
+ }
316
+ /**
317
+ * The metadata of the junction table of a many-to-many relation.
318
+ * @param entityTarget The entity owning the relation.
319
+ * @param relationPropertyPath The property of the relation (`'tags'`, or a path such as `'profile.tags'`).
320
+ * @returns The metadata of the junction table.
321
+ * @throws {EntityMetadataNotFoundError} When the entity is not registered.
322
+ * @throws {TypeORMError} When the entity has no such relation, or the relation is not a many-to-many one.
323
+ */
324
+ getManyToManyMetadata(entityTarget, relationPropertyPath) {
325
+ return this.datasource.getManyToManyMetadata(entityTarget, relationPropertyPath);
326
+ }
327
+ /**
328
+ * Create an entity manager on the connection, bound to a query runner when given (its operations then run on the
329
+ * runner's connection and transaction).
330
+ * @param queryRunner The query runner the manager uses, a connection of the pool per operation otherwise.
331
+ * @returns The entity manager.
332
+ */
333
+ createEntityManager(queryRunner) {
334
+ return this.datasource.createEntityManager(queryRunner);
335
+ }
336
+ };
337
+ __decorate([
338
+ Configurable(),
339
+ __metadata("design:type", Object)
340
+ ], Database.prototype, "options", void 0);
341
+ Database = __decorate([
342
+ Singleton()
343
+ ], Database);
344
+ export { Database };
@@ -0,0 +1 @@
1
+ export { AfterInsert } from 'typeorm/decorator/listeners/AfterInsert.js';
@@ -0,0 +1 @@
1
+ export { AfterLoad } from 'typeorm/decorator/listeners/AfterLoad.js';
@@ -0,0 +1 @@
1
+ export { AfterRecover } from 'typeorm/decorator/listeners/AfterRecover.js';
@@ -0,0 +1 @@
1
+ export { AfterRemove } from 'typeorm/decorator/listeners/AfterRemove.js';
@@ -0,0 +1 @@
1
+ export { AfterSoftRemove } from 'typeorm/decorator/listeners/AfterSoftRemove.js';