@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,376 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
19
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
20
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
21
+ 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;
22
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
23
+ };
24
+ var __importStar = (this && this.__importStar) || (function () {
25
+ var ownKeys = function(o) {
26
+ ownKeys = Object.getOwnPropertyNames || function (o) {
27
+ var ar = [];
28
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
29
+ return ar;
30
+ };
31
+ return ownKeys(o);
32
+ };
33
+ return function (mod) {
34
+ if (mod && mod.__esModule) return mod;
35
+ var result = {};
36
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
37
+ __setModuleDefault(result, mod);
38
+ return result;
39
+ };
40
+ })();
41
+ var __metadata = (this && this.__metadata) || function (k, v) {
42
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
43
+ };
44
+ Object.defineProperty(exports, "__esModule", { value: true });
45
+ exports.Database = exports.buildDatabaseOptions = void 0;
46
+ const di_1 = require("@lakutata/core/decorator/di");
47
+ const DataSource_js_1 = require("typeorm/data-source/DataSource.js");
48
+ const core_1 = require("@lakutata/core");
49
+ const utils_1 = require("@lakutata/utils");
50
+ /**
51
+ * Build the registration of a {@link Database} provider, for the `providers` of the application options: the provider
52
+ * class with its TypeORM connection options. Its `entities` option, added to the entities of the connection options,
53
+ * is set by spreading the registration: `{...buildDatabaseOptions(options), entities: [User]}`.
54
+ * @param options The TypeORM connection options (`DataSourceOptions`): the driver `type`, the connection settings, the
55
+ * `entities`, the `migrations`, `synchronize`, `migrationsRun`, `logging`… Passed to TypeORM as they are.
56
+ * @returns The registration `{class: Database, options}`.
57
+ * @example
58
+ * ```typescript
59
+ * import {Application} from 'lakutata'
60
+ * import {buildDatabaseOptions} from 'lakutata/provider/database'
61
+ * import {Column, Entity, PrimaryGeneratedColumn} from 'lakutata/decorator/orm'
62
+ *
63
+ * @Entity()
64
+ * class Report {
65
+ * @PrimaryGeneratedColumn()
66
+ * public id: number
67
+ *
68
+ * @Column('text')
69
+ * public content: string
70
+ * }
71
+ *
72
+ * Application.run(() => ({
73
+ * id: 'com.example.reports',
74
+ * name: 'Reports',
75
+ * providers: {
76
+ * //A new PostgreSQL connection each time reports is resolved, closed with its owner
77
+ * reports: {
78
+ * ...buildDatabaseOptions({type: 'postgres', url: 'postgres://postgres:secret@localhost:5432/reports'}),
79
+ * entities: [Report]
80
+ * }
81
+ * }
82
+ * }))
83
+ * ```
84
+ */
85
+ const buildDatabaseOptions = (options) => ({
86
+ class: Database,
87
+ options: options
88
+ });
89
+ exports.buildDatabaseOptions = buildDatabaseOptions;
90
+ /**
91
+ * A database connection of its own: a transient provider wrapping a TypeORM `DataSource`, with the API of the
92
+ * `Database` component of `lakutata/com/database`.
93
+ *
94
+ * Register it in the `providers` of the application options with {@link buildDatabaseOptions}. Each resolution
95
+ * (`@Inject('reports')`, `getObject('reports')`) creates a new instance, even within one scope: it opens its own
96
+ * connection (its own pool) while it is created, and closes it when it is destroyed with the object or the container
97
+ * which created it. It suits a short use (a job, a script, a tenant database); the requests of a busy application
98
+ * share the `Database` component instead. A connection failure rejects its creation with the driver error.
99
+ *
100
+ * The entities of its `entities` option are added to the entities of its connection options.
101
+ * @example
102
+ * ```typescript
103
+ * import {Application} from 'lakutata'
104
+ * import {buildDatabaseOptions, Database} from 'lakutata/provider/database'
105
+ * import {Column, Entity, PrimaryGeneratedColumn} from 'lakutata/decorator/orm'
106
+ *
107
+ * @Entity()
108
+ * class Report {
109
+ * @PrimaryGeneratedColumn()
110
+ * public id: number
111
+ *
112
+ * @Column('text')
113
+ * public content: string
114
+ * }
115
+ *
116
+ * Application
117
+ * .run(() => ({
118
+ * id: 'com.example.reports',
119
+ * name: 'Reports',
120
+ * providers: {
121
+ * reports: {
122
+ * ...buildDatabaseOptions({type: 'postgres', url: 'postgres://postgres:secret@localhost:5432/reports', synchronize: true}),
123
+ * entities: [Report]
124
+ * }
125
+ * }
126
+ * }))
127
+ * .onLaunched(async (app: Application): Promise<void> => {
128
+ * //A connection opened for this use, closed with the application
129
+ * const database: Database = await app.getObject('reports')
130
+ * await database.transaction(async (manager): Promise<void> => {
131
+ * await manager.save(Report, {content: 'Daily report'})
132
+ * })
133
+ * console.log(await database.getRepository(Report).count())
134
+ * })
135
+ * ```
136
+ */
137
+ let Database = class Database extends core_1.Provider {
138
+ /**
139
+ * Load the provider generating the migrations of the database. The application calls it when it is started with
140
+ * `MIGRATION_GENERATE`: the applications do not call it.
141
+ * @returns The migration generator provider class.
142
+ */
143
+ static { this.migrationGenerator = async () => (await Promise.resolve().then(() => __importStar(require('./migration/GenerateMigration.js')))).GenerateMigration; }
144
+ /**
145
+ * Load the provider running, reverting or showing the migrations of the database. The application calls it when it
146
+ * is started with `MIGRATION_RUN`, `MIGRATION_REVERT` or `MIGRATION_SHOW`: the applications do not call it.
147
+ * @returns The migration executor provider class.
148
+ */
149
+ static { this.migrationExecutor = async () => (await Promise.resolve().then(() => __importStar(require('./migration/ExecuteMigration.js')))).ExecuteMigration; }
150
+ #datasource;
151
+ /**
152
+ * The TypeORM `DataSource` of the connection, for the subclasses needing what this class does not expose.
153
+ */
154
+ get datasource() {
155
+ return this.#datasource;
156
+ }
157
+ /**
158
+ * The TypeORM driver of the connection (PostgreSQL, MySQL, SQLite…).
159
+ */
160
+ get driver() {
161
+ return this.datasource.driver;
162
+ }
163
+ /**
164
+ * The entity manager of the connection: the TypeORM operations on any entity (`find`, `save`, `delete`…) outside a
165
+ * transaction.
166
+ */
167
+ get manager() {
168
+ return this.datasource.manager;
169
+ }
170
+ /**
171
+ * Replace the naming strategy of the connection, which names the tables, the columns and the constraints of the
172
+ * entities. Set it before the metadata is used: the names already built are not renamed.
173
+ * @param instance The naming strategy.
174
+ */
175
+ set namingStrategy(instance) {
176
+ this.datasource.namingStrategy = instance;
177
+ }
178
+ /**
179
+ * The naming strategy of the connection, which names the tables, the columns and the constraints of the entities.
180
+ * @default TypeORM's `DefaultNamingStrategy`, unless the options set `namingStrategy`
181
+ */
182
+ get namingStrategy() {
183
+ return this.datasource.namingStrategy;
184
+ }
185
+ /**
186
+ * The entity subscribers registered on the connection (the `subscribers` of the options).
187
+ */
188
+ get subscribers() {
189
+ return this.datasource.subscribers;
190
+ }
191
+ /**
192
+ * The metadata of every entity registered on the connection.
193
+ */
194
+ get entityMetadatas() {
195
+ return this.datasource.entityMetadatas;
196
+ }
197
+ /**
198
+ * The metadata of every entity registered on the connection, by entity target (class, name or schema): the same as
199
+ * {@link Database.entityMetadatas}, for fast lookups.
200
+ */
201
+ get entityMetadatasMap() {
202
+ return this.datasource.entityMetadatasMap;
203
+ }
204
+ /**
205
+ * The query result cache of the connection, `undefined` unless the options enable `cache`.
206
+ */
207
+ get queryResultCache() {
208
+ return this.datasource.queryResultCache;
209
+ }
210
+ /**
211
+ * Connect to the database with the options, their entities and the ones of the `entities` option.
212
+ * @protected
213
+ */
214
+ async init() {
215
+ const entities = this.entities ? this.entities : [];
216
+ const options = {
217
+ ...this.options,
218
+ entities: [...(0, utils_1.As)(this.options.entities ? this.options.entities : []), ...(0, utils_1.As)(entities)]
219
+ };
220
+ this.#datasource = await (new DataSource_js_1.DataSource(options)).initialize();
221
+ }
222
+ /**
223
+ * Disconnect from the database.
224
+ * @protected
225
+ */
226
+ async destroy() {
227
+ await this.datasource.destroy();
228
+ }
229
+ /**
230
+ * Create or update the database schema from the registered entities (the tables, columns, indices and foreign
231
+ * keys). Meant for development: the migrations change the schema of a production database.
232
+ * @param dropBeforeSync Drop every table of the database schema, with its data (also the tables of no entity),
233
+ * before creating the schema. Defaults to `false`.
234
+ * @returns Resolves once the schema is built.
235
+ * @throws {CannotExecuteNotConnectedError} When the connection is closed.
236
+ */
237
+ async synchronize(dropBeforeSync) {
238
+ return await this.datasource.synchronize(dropBeforeSync);
239
+ }
240
+ /**
241
+ * Run the pending migrations (the `migrations` of the options not yet recorded in the migrations table), in their
242
+ * timestamp order.
243
+ * @param options The transactions of the migrations, and whether they are only recorded (`fake`).
244
+ * @returns The migrations run, an empty array when none is pending.
245
+ * @throws {CannotExecuteNotConnectedError} When the connection is closed.
246
+ * @throws {Error} The error of a failed migration, once its transaction (`'all'` or `'each'`) is rolled back.
247
+ */
248
+ async runMigrations(options) {
249
+ return await this.datasource.runMigrations(options);
250
+ }
251
+ /**
252
+ * Revert the last migration run (its `down()`), and remove it from the migrations table. Does nothing when no
253
+ * migration was run.
254
+ * @param options The transaction of the migration (`'all'` by default, `migrationsTransactionMode` not applying),
255
+ * and whether it is only removed from the migrations table (`fake`).
256
+ * @returns Resolves once the migration is reverted.
257
+ * @throws {CannotExecuteNotConnectedError} When the connection is closed.
258
+ */
259
+ async undoLastMigration(options) {
260
+ return await this.datasource.undoLastMigration(options);
261
+ }
262
+ /**
263
+ * Log each migration of the options with whether it was run (`[X]`) or not (`[ ]`), through the logger of the
264
+ * connection (shown when its `logging` includes `schema`).
265
+ * @returns Whether a migration is pending.
266
+ */
267
+ async showMigrations() {
268
+ return await this.datasource.showMigrations();
269
+ }
270
+ /**
271
+ * Whether an entity is registered on the connection.
272
+ * @param target The entity class, its name, or its table name.
273
+ * @returns `true` when the connection has its metadata.
274
+ */
275
+ hasMetadata(target) {
276
+ return this.datasource.hasMetadata(target);
277
+ }
278
+ /**
279
+ * The metadata of a registered entity: its table, columns, relations…
280
+ * @param target The entity class, its name, or its table name.
281
+ * @returns The metadata of the entity.
282
+ * @throws {EntityMetadataNotFoundError} When the entity is not registered on the connection.
283
+ */
284
+ getMetadata(target) {
285
+ return this.datasource.getMetadata(target);
286
+ }
287
+ /**
288
+ * The repository of an entity, created once per entity: its `find`, `save`, `delete`… operations outside a
289
+ * transaction (in a transaction, use the entity manager given to the callback).
290
+ * @param target The entity class, its name, or its `EntitySchema`.
291
+ * @returns The repository of the entity (a `MongoRepository` on a MongoDB connection).
292
+ * @throws {EntityMetadataNotFoundError} From the repository operations, when the entity is not registered.
293
+ */
294
+ getRepository(target) {
295
+ return this.datasource.getRepository(target);
296
+ }
297
+ /**
298
+ * The tree repository of an entity decorated with `@Tree()`: the operations on its ancestors and descendants
299
+ * (`findTrees`, `findDescendants`…).
300
+ * @param target The tree entity class, or its name.
301
+ * @returns The tree repository of the entity.
302
+ * @throws {TreeRepositoryNotSupportedError} On a driver without tree support (MongoDB).
303
+ */
304
+ getTreeRepository(target) {
305
+ return this.datasource.getTreeRepository(target);
306
+ }
307
+ /**
308
+ * The MongoDB repository of an entity: the repository operations plus the MongoDB ones (`aggregate`, `bulkWrite`…).
309
+ * @param target The entity class, or its name.
310
+ * @returns The MongoDB repository of the entity.
311
+ * @throws {TypeORMError} When the connection is not a MongoDB one.
312
+ */
313
+ getMongoRepository(target) {
314
+ return this.datasource.getMongoRepository(target);
315
+ }
316
+ async transaction(inp1, inp2) {
317
+ return inp2 ? await this.datasource.transaction(inp1, inp2) : await this.datasource.transaction(inp1);
318
+ }
319
+ /**
320
+ * Run a raw SQL query.
321
+ * @param query The SQL, its parameters as placeholders: `$1`, `$2`… for PostgreSQL, `?` for MySQL and SQLite.
322
+ * @param parameters The values of the placeholders, escaped by the driver.
323
+ * @param queryRunner The query runner to run it on (a transaction of {@link Database.createQueryRunner}), a
324
+ * connection of the pool otherwise.
325
+ * @returns The raw result of the driver: the rows of a `SELECT` (an array of objects).
326
+ * @throws {QueryFailedError} When the database rejects the query.
327
+ */
328
+ async query(query, parameters, queryRunner) {
329
+ return await this.datasource.query(query, parameters, queryRunner);
330
+ }
331
+ createQueryBuilder(inp1, inp2, inp3) {
332
+ return arguments.length > 1 ? this.datasource.createQueryBuilder(inp1, inp2, inp3) : this.datasource.createQueryBuilder(inp1);
333
+ }
334
+ /**
335
+ * Create a query runner: one connection taken from the pool, to run several queries on the same connection and
336
+ * control its transaction by hand (`connect()`, `startTransaction()`, `commitTransaction()`,
337
+ * `rollbackTransaction()`). The caller must `release()` it, or the connection stays taken.
338
+ * @param mode With replication, `'master'` (the default) for the writes, `'slave'` for the reads on a replica.
339
+ * @returns The query runner, not connected until its first query or `connect()`.
340
+ */
341
+ createQueryRunner(mode) {
342
+ return this.datasource.createQueryRunner(mode);
343
+ }
344
+ /**
345
+ * The metadata of the junction table of a many-to-many relation.
346
+ * @param entityTarget The entity owning the relation.
347
+ * @param relationPropertyPath The property of the relation (`'tags'`, or a path such as `'profile.tags'`).
348
+ * @returns The metadata of the junction table.
349
+ * @throws {EntityMetadataNotFoundError} When the entity is not registered.
350
+ * @throws {TypeORMError} When the entity has no such relation, or the relation is not a many-to-many one.
351
+ */
352
+ getManyToManyMetadata(entityTarget, relationPropertyPath) {
353
+ return this.datasource.getManyToManyMetadata(entityTarget, relationPropertyPath);
354
+ }
355
+ /**
356
+ * Create an entity manager on the connection, bound to a query runner when given (its operations then run on the
357
+ * runner's connection and transaction).
358
+ * @param queryRunner The query runner the manager uses, a connection of the pool per operation otherwise.
359
+ * @returns The entity manager.
360
+ */
361
+ createEntityManager(queryRunner) {
362
+ return this.datasource.createEntityManager(queryRunner);
363
+ }
364
+ };
365
+ exports.Database = Database;
366
+ __decorate([
367
+ (0, di_1.Configurable)(),
368
+ __metadata("design:type", Object)
369
+ ], Database.prototype, "options", void 0);
370
+ __decorate([
371
+ (0, di_1.Configurable)(),
372
+ __metadata("design:type", Object)
373
+ ], Database.prototype, "entities", void 0);
374
+ exports.Database = Database = __decorate([
375
+ (0, di_1.Transient)()
376
+ ], Database);
@@ -0,0 +1,40 @@
1
+ import { Provider } from '@lakutata/core';
2
+ import { type DataSourceOptions } from 'typeorm/data-source/DataSourceOptions.js';
3
+ import { DataSource } from 'typeorm/data-source/DataSource.js';
4
+ /**
5
+ * The actions on the migrations of a database
6
+ */
7
+ export type MigrationAction = 'run' | 'revert' | 'show';
8
+ /**
9
+ * Run, revert or show the migrations of a database of the application, with its options (MIGRATION_RUN, MIGRATION_REVERT,
10
+ * MIGRATION_SHOW): the database is connected without synchronizing its schema nor running its migrations, the action
11
+ * done, then the application exits (with the code 1 when the action fails)
12
+ */
13
+ export declare class ExecuteMigration extends Provider {
14
+ protected readonly action: MigrationAction;
15
+ protected readonly dataSourceName: string;
16
+ protected readonly dataSource: DataSourceOptions;
17
+ protected readonly transaction?: 'all' | 'none' | 'each';
18
+ /**
19
+ * The transactions of the migrations: MIGRATION_TRANSACTION, else the migrationsTransactionMode of the database, else
20
+ * one for all
21
+ */
22
+ protected get transactionMode(): 'all' | 'none' | 'each';
23
+ protected readonly fake: boolean;
24
+ protected readonly exitProcess: boolean;
25
+ /**
26
+ * The prefix of the messages: the name of the database
27
+ */
28
+ protected get prefix(): string;
29
+ /**
30
+ * Initializer
31
+ * @protected
32
+ */
33
+ protected init(): Promise<void>;
34
+ /**
35
+ * Do the action on the database
36
+ * @param dataSource
37
+ * @protected
38
+ */
39
+ protected handle(dataSource: DataSource): Promise<void>;
40
+ }
@@ -0,0 +1,143 @@
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
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.ExecuteMigration = void 0;
16
+ const core_1 = require("@lakutata/core");
17
+ const di_1 = require("@lakutata/core/decorator/di");
18
+ const DataSource_js_1 = require("typeorm/data-source/DataSource.js");
19
+ const MigrationExecutor_js_1 = require("typeorm/migration/MigrationExecutor.js");
20
+ const ansis_1 = __importDefault(require("ansis"));
21
+ /**
22
+ * The executor of the migrations, giving the migrations of the options of the database
23
+ */
24
+ class Executor extends MigrationExecutor_js_1.MigrationExecutor {
25
+ /**
26
+ * The migrations of the options of the database, in their order
27
+ */
28
+ sourceMigrations() {
29
+ return this.getMigrations();
30
+ }
31
+ }
32
+ /**
33
+ * Run, revert or show the migrations of a database of the application, with its options (MIGRATION_RUN, MIGRATION_REVERT,
34
+ * MIGRATION_SHOW): the database is connected without synchronizing its schema nor running its migrations, the action
35
+ * done, then the application exits (with the code 1 when the action fails)
36
+ */
37
+ let ExecuteMigration = class ExecuteMigration extends core_1.Provider {
38
+ /**
39
+ * The transactions of the migrations: MIGRATION_TRANSACTION, else the migrationsTransactionMode of the database, else
40
+ * one for all
41
+ */
42
+ get transactionMode() {
43
+ return this.transaction ?? this.dataSource.migrationsTransactionMode ?? 'all';
44
+ }
45
+ /**
46
+ * The prefix of the messages: the name of the database
47
+ */
48
+ get prefix() {
49
+ return this.dataSourceName ? `[${this.dataSourceName}] ` : '';
50
+ }
51
+ /**
52
+ * Initializer
53
+ * @protected
54
+ */
55
+ async init() {
56
+ const app = await this.getObject(core_1.Application);
57
+ const dataSource = new DataSource_js_1.DataSource({ ...this.dataSource, synchronize: false, migrationsRun: false, dropSchema: false });
58
+ let failed = false;
59
+ try {
60
+ await dataSource.initialize();
61
+ await this.handle(dataSource);
62
+ }
63
+ catch (error) {
64
+ console.error(ansis_1.default.red `${this.prefix}The migrations could not be ${this.action === 'show' ? 'shown' : this.action === 'run' ? 'run' : 'reverted'}:`, error);
65
+ failed = true;
66
+ }
67
+ finally {
68
+ if (dataSource.isInitialized)
69
+ await dataSource.destroy();
70
+ }
71
+ //A failure stops the actions on the other databases
72
+ if (failed)
73
+ return app.exit(1);
74
+ if (this.exitProcess)
75
+ return app.exit(0);
76
+ }
77
+ /**
78
+ * Do the action on the database
79
+ * @param dataSource
80
+ * @protected
81
+ */
82
+ async handle(dataSource) {
83
+ const executor = new Executor(dataSource);
84
+ switch (this.action) {
85
+ case 'run': {
86
+ const pending = await executor.getPendingMigrations();
87
+ const ran = await dataSource.runMigrations({ transaction: this.transactionMode, fake: this.fake });
88
+ //The migrations marked as run are not given back by TypeORM
89
+ const executed = this.fake ? pending : ran;
90
+ if (!executed.length)
91
+ return console.log(ansis_1.default.green `${this.prefix}No pending migration`);
92
+ for (const migration of executed)
93
+ console.log(ansis_1.default.green `${this.prefix}Migration ${ansis_1.default.blue(migration.name)} has been ${this.fake ? 'marked as run' : 'run'}`);
94
+ return;
95
+ }
96
+ case 'revert': {
97
+ const [last] = (await executor.getExecutedMigrations()).sort((a, b) => (b.id ?? 0) - (a.id ?? 0));
98
+ if (!last)
99
+ return console.log(ansis_1.default.yellow `${this.prefix}No migration to revert`);
100
+ await dataSource.undoLastMigration({ transaction: this.transactionMode, fake: this.fake });
101
+ return console.log(ansis_1.default.green `${this.prefix}Migration ${ansis_1.default.blue(last.name)} has been ${this.fake ? 'marked as reverted' : 'reverted'}`);
102
+ }
103
+ case 'show': {
104
+ const executed = new Set((await executor.getExecutedMigrations()).map((migration) => migration.name));
105
+ const migrations = executor.sourceMigrations();
106
+ if (!migrations.length)
107
+ return console.log(ansis_1.default.yellow `${this.prefix}No migration in the options of the database`);
108
+ for (const migration of migrations)
109
+ console.log(`${this.prefix}${executed.has(migration.name) ? ansis_1.default.green `[X]` : ansis_1.default.yellow `[ ]`} ${migration.name}`);
110
+ const pending = migrations.filter((migration) => !executed.has(migration.name)).length;
111
+ return console.log(pending ? ansis_1.default.yellow `${this.prefix}${pending} pending migration${pending > 1 ? 's' : ''}` : ansis_1.default.green `${this.prefix}No pending migration`);
112
+ }
113
+ }
114
+ }
115
+ };
116
+ exports.ExecuteMigration = ExecuteMigration;
117
+ __decorate([
118
+ (0, di_1.Configurable)(core_1.DTO.String().valid('run', 'revert', 'show').required()),
119
+ __metadata("design:type", String)
120
+ ], ExecuteMigration.prototype, "action", void 0);
121
+ __decorate([
122
+ (0, di_1.Configurable)(core_1.DTO.String().allow('').optional().default('')),
123
+ __metadata("design:type", String)
124
+ ], ExecuteMigration.prototype, "dataSourceName", void 0);
125
+ __decorate([
126
+ (0, di_1.Configurable)(),
127
+ __metadata("design:type", Object)
128
+ ], ExecuteMigration.prototype, "dataSource", void 0);
129
+ __decorate([
130
+ (0, di_1.Configurable)(core_1.DTO.String().valid('all', 'none', 'each').optional()),
131
+ __metadata("design:type", String)
132
+ ], ExecuteMigration.prototype, "transaction", void 0);
133
+ __decorate([
134
+ (0, di_1.Configurable)(core_1.DTO.Boolean().optional().default(false)),
135
+ __metadata("design:type", Boolean)
136
+ ], ExecuteMigration.prototype, "fake", void 0);
137
+ __decorate([
138
+ (0, di_1.Configurable)(core_1.DTO.Boolean().optional().default(true)),
139
+ __metadata("design:type", Boolean)
140
+ ], ExecuteMigration.prototype, "exitProcess", void 0);
141
+ exports.ExecuteMigration = ExecuteMigration = __decorate([
142
+ (0, di_1.Transient)()
143
+ ], ExecuteMigration);
@@ -0,0 +1,59 @@
1
+ import { Provider } from '@lakutata/core';
2
+ import { type DataSourceOptions } from 'typeorm/data-source/DataSourceOptions.js';
3
+ export declare class GenerateMigration extends Provider {
4
+ #private;
5
+ protected readonly path: string;
6
+ protected readonly dataSourceName: string;
7
+ protected readonly dataSource: DataSourceOptions;
8
+ protected readonly pretty: boolean;
9
+ protected readonly outputJs: boolean;
10
+ protected readonly esm: boolean;
11
+ protected readonly dryRun: boolean;
12
+ protected readonly check: boolean;
13
+ protected readonly timestamp: number;
14
+ protected readonly exitProcess: boolean;
15
+ protected get extension(): string;
16
+ protected get filename(): string;
17
+ /**
18
+ * Initializer
19
+ * @protected
20
+ */
21
+ /**
22
+ * The migrations generated by the run (its databases share the process)
23
+ */
24
+ protected static generated: number;
25
+ protected init(): Promise<void>;
26
+ /**
27
+ * Destroyer
28
+ * @protected
29
+ */
30
+ protected destroy(): Promise<void>;
31
+ protected handle(): Promise<void>;
32
+ /**
33
+ * The module the migrations import their types from: @lakutata/orm when the project depends on it, otherwise
34
+ * lakutata/orm (the migrations of the projects depending on lakutata)
35
+ */
36
+ protected static migrationModule(): string;
37
+ /**
38
+ * Escape a query for a template literal of the migration: its backslashes, its backticks and its interpolations
39
+ * (the defaults and the comments of the columns are in the queries)
40
+ * @param query
41
+ */
42
+ protected static escapeTemplateLiteral(query: string): string;
43
+ /**
44
+ * Formats query parameters for migration queries if parameters actually exist
45
+ */
46
+ protected static queryParams(parameters: any[] | undefined): string;
47
+ /**
48
+ * Gets contents of the migration file.
49
+ */
50
+ protected static getTemplate(name: string, timestamp: number, upSqls: string[], downSqls: string[]): string;
51
+ /**
52
+ * Gets contents of the migration file in Javascript.
53
+ */
54
+ protected static getJavascriptTemplate(name: string, timestamp: number, upSqls: string[], downSqls: string[], esm: boolean): string;
55
+ /**
56
+ *
57
+ */
58
+ protected static prettifyQuery(query: string): string;
59
+ }