@uql/core 3.1.0 → 3.1.2

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 (170) hide show
  1. package/CHANGELOG.md +134 -176
  2. package/README.md +413 -0
  3. package/package.json +31 -26
  4. package/dist/package.json +0 -131
  5. package/src/@types/index.d.ts +0 -1
  6. package/src/@types/jest.d.ts +0 -6
  7. package/src/browser/http/bus.spec.ts +0 -22
  8. package/src/browser/http/bus.ts +0 -17
  9. package/src/browser/http/http.spec.ts +0 -70
  10. package/src/browser/http/http.ts +0 -55
  11. package/src/browser/http/index.ts +0 -2
  12. package/src/browser/index.ts +0 -4
  13. package/src/browser/options.spec.ts +0 -37
  14. package/src/browser/options.ts +0 -18
  15. package/src/browser/querier/genericClientRepository.spec.ts +0 -105
  16. package/src/browser/querier/genericClientRepository.ts +0 -49
  17. package/src/browser/querier/httpQuerier.ts +0 -82
  18. package/src/browser/querier/index.ts +0 -3
  19. package/src/browser/querier/querier.util.spec.ts +0 -35
  20. package/src/browser/querier/querier.util.ts +0 -18
  21. package/src/browser/type/clientQuerier.ts +0 -45
  22. package/src/browser/type/clientQuerierPool.ts +0 -5
  23. package/src/browser/type/clientRepository.ts +0 -22
  24. package/src/browser/type/index.ts +0 -4
  25. package/src/browser/type/request.ts +0 -25
  26. package/src/dialect/abstractDialect.ts +0 -28
  27. package/src/dialect/abstractSqlDialect-spec.ts +0 -1309
  28. package/src/dialect/abstractSqlDialect.ts +0 -805
  29. package/src/dialect/index.ts +0 -3
  30. package/src/dialect/namingStrategy.spec.ts +0 -52
  31. package/src/dialect/queryContext.ts +0 -69
  32. package/src/entity/decorator/definition.spec.ts +0 -736
  33. package/src/entity/decorator/definition.ts +0 -265
  34. package/src/entity/decorator/entity.ts +0 -8
  35. package/src/entity/decorator/field.ts +0 -9
  36. package/src/entity/decorator/id.ts +0 -9
  37. package/src/entity/decorator/index.ts +0 -5
  38. package/src/entity/decorator/relation.spec.ts +0 -41
  39. package/src/entity/decorator/relation.ts +0 -34
  40. package/src/entity/index.ts +0 -1
  41. package/src/express/@types/express.d.ts +0 -8
  42. package/src/express/@types/index.d.ts +0 -1
  43. package/src/express/index.ts +0 -2
  44. package/src/express/querierMiddleware.ts +0 -217
  45. package/src/express/query.util.spec.ts +0 -40
  46. package/src/express/query.util.ts +0 -21
  47. package/src/index.ts +0 -9
  48. package/src/maria/index.ts +0 -3
  49. package/src/maria/mariaDialect.spec.ts +0 -207
  50. package/src/maria/mariaDialect.ts +0 -42
  51. package/src/maria/mariaQuerierPool.test.ts +0 -23
  52. package/src/maria/mariadbQuerier.test.ts +0 -23
  53. package/src/maria/mariadbQuerier.ts +0 -45
  54. package/src/maria/mariadbQuerierPool.ts +0 -21
  55. package/src/migrate/cli.ts +0 -301
  56. package/src/migrate/generator/index.ts +0 -4
  57. package/src/migrate/generator/mongoSchemaGenerator.spec.ts +0 -112
  58. package/src/migrate/generator/mongoSchemaGenerator.ts +0 -115
  59. package/src/migrate/generator/mysqlSchemaGenerator.spec.ts +0 -34
  60. package/src/migrate/generator/mysqlSchemaGenerator.ts +0 -92
  61. package/src/migrate/generator/postgresSchemaGenerator.spec.ts +0 -44
  62. package/src/migrate/generator/postgresSchemaGenerator.ts +0 -127
  63. package/src/migrate/generator/sqliteSchemaGenerator.spec.ts +0 -33
  64. package/src/migrate/generator/sqliteSchemaGenerator.ts +0 -81
  65. package/src/migrate/index.ts +0 -41
  66. package/src/migrate/introspection/index.ts +0 -4
  67. package/src/migrate/introspection/mongoIntrospector.spec.ts +0 -75
  68. package/src/migrate/introspection/mongoIntrospector.ts +0 -47
  69. package/src/migrate/introspection/mysqlIntrospector.spec.ts +0 -113
  70. package/src/migrate/introspection/mysqlIntrospector.ts +0 -278
  71. package/src/migrate/introspection/postgresIntrospector.spec.ts +0 -112
  72. package/src/migrate/introspection/postgresIntrospector.ts +0 -329
  73. package/src/migrate/introspection/sqliteIntrospector.spec.ts +0 -112
  74. package/src/migrate/introspection/sqliteIntrospector.ts +0 -296
  75. package/src/migrate/migrator-mongo.test.ts +0 -54
  76. package/src/migrate/migrator.spec.ts +0 -255
  77. package/src/migrate/migrator.test.ts +0 -94
  78. package/src/migrate/migrator.ts +0 -719
  79. package/src/migrate/namingStrategy.spec.ts +0 -22
  80. package/src/migrate/schemaGenerator-advanced.spec.ts +0 -138
  81. package/src/migrate/schemaGenerator.spec.ts +0 -190
  82. package/src/migrate/schemaGenerator.ts +0 -478
  83. package/src/migrate/storage/databaseStorage.spec.ts +0 -69
  84. package/src/migrate/storage/databaseStorage.ts +0 -100
  85. package/src/migrate/storage/index.ts +0 -2
  86. package/src/migrate/storage/jsonStorage.ts +0 -58
  87. package/src/migrate/type.ts +0 -1
  88. package/src/mongo/index.ts +0 -3
  89. package/src/mongo/mongoDialect.spec.ts +0 -251
  90. package/src/mongo/mongoDialect.ts +0 -238
  91. package/src/mongo/mongodbQuerier.test.ts +0 -45
  92. package/src/mongo/mongodbQuerier.ts +0 -256
  93. package/src/mongo/mongodbQuerierPool.test.ts +0 -25
  94. package/src/mongo/mongodbQuerierPool.ts +0 -24
  95. package/src/mysql/index.ts +0 -3
  96. package/src/mysql/mysql2Querier.test.ts +0 -20
  97. package/src/mysql/mysql2Querier.ts +0 -49
  98. package/src/mysql/mysql2QuerierPool.test.ts +0 -20
  99. package/src/mysql/mysql2QuerierPool.ts +0 -21
  100. package/src/mysql/mysqlDialect.spec.ts +0 -20
  101. package/src/mysql/mysqlDialect.ts +0 -16
  102. package/src/namingStrategy/defaultNamingStrategy.ts +0 -18
  103. package/src/namingStrategy/index.spec.ts +0 -36
  104. package/src/namingStrategy/index.ts +0 -2
  105. package/src/namingStrategy/snakeCaseNamingStrategy.ts +0 -15
  106. package/src/options.spec.ts +0 -41
  107. package/src/options.ts +0 -18
  108. package/src/postgres/index.ts +0 -3
  109. package/src/postgres/manual-types.d.ts +0 -4
  110. package/src/postgres/pgQuerier.test.ts +0 -25
  111. package/src/postgres/pgQuerier.ts +0 -45
  112. package/src/postgres/pgQuerierPool.test.ts +0 -28
  113. package/src/postgres/pgQuerierPool.ts +0 -21
  114. package/src/postgres/postgresDialect.spec.ts +0 -428
  115. package/src/postgres/postgresDialect.ts +0 -144
  116. package/src/querier/abstractQuerier-test.ts +0 -584
  117. package/src/querier/abstractQuerier.ts +0 -353
  118. package/src/querier/abstractQuerierPool-test.ts +0 -20
  119. package/src/querier/abstractQuerierPool.ts +0 -18
  120. package/src/querier/abstractSqlQuerier-spec.ts +0 -979
  121. package/src/querier/abstractSqlQuerier-test.ts +0 -21
  122. package/src/querier/abstractSqlQuerier.ts +0 -138
  123. package/src/querier/decorator/index.ts +0 -3
  124. package/src/querier/decorator/injectQuerier.spec.ts +0 -74
  125. package/src/querier/decorator/injectQuerier.ts +0 -45
  126. package/src/querier/decorator/serialized.spec.ts +0 -98
  127. package/src/querier/decorator/serialized.ts +0 -13
  128. package/src/querier/decorator/transactional.spec.ts +0 -240
  129. package/src/querier/decorator/transactional.ts +0 -56
  130. package/src/querier/index.ts +0 -4
  131. package/src/repository/genericRepository.spec.ts +0 -111
  132. package/src/repository/genericRepository.ts +0 -74
  133. package/src/repository/index.ts +0 -1
  134. package/src/sqlite/index.ts +0 -3
  135. package/src/sqlite/manual-types.d.ts +0 -4
  136. package/src/sqlite/sqliteDialect.spec.ts +0 -155
  137. package/src/sqlite/sqliteDialect.ts +0 -76
  138. package/src/sqlite/sqliteQuerier.spec.ts +0 -36
  139. package/src/sqlite/sqliteQuerier.test.ts +0 -21
  140. package/src/sqlite/sqliteQuerier.ts +0 -37
  141. package/src/sqlite/sqliteQuerierPool.test.ts +0 -12
  142. package/src/sqlite/sqliteQuerierPool.ts +0 -38
  143. package/src/test/entityMock.ts +0 -375
  144. package/src/test/index.ts +0 -3
  145. package/src/test/it.util.ts +0 -69
  146. package/src/test/spec.util.ts +0 -57
  147. package/src/type/entity.ts +0 -218
  148. package/src/type/index.ts +0 -9
  149. package/src/type/migration.ts +0 -241
  150. package/src/type/namingStrategy.ts +0 -17
  151. package/src/type/querier.ts +0 -143
  152. package/src/type/querierPool.ts +0 -26
  153. package/src/type/query.ts +0 -506
  154. package/src/type/repository.ts +0 -142
  155. package/src/type/universalQuerier.ts +0 -133
  156. package/src/type/utility.ts +0 -21
  157. package/src/util/dialect.util-extra.spec.ts +0 -96
  158. package/src/util/dialect.util.spec.ts +0 -23
  159. package/src/util/dialect.util.ts +0 -134
  160. package/src/util/index.ts +0 -5
  161. package/src/util/object.util.spec.ts +0 -29
  162. package/src/util/object.util.ts +0 -27
  163. package/src/util/raw.ts +0 -11
  164. package/src/util/sql.util-extra.spec.ts +0 -17
  165. package/src/util/sql.util.spec.ts +0 -208
  166. package/src/util/sql.util.ts +0 -104
  167. package/src/util/string.util.spec.ts +0 -46
  168. package/src/util/string.util.ts +0 -35
  169. package/tsconfig.build.json +0 -5
  170. package/tsconfig.json +0 -8
@@ -1,719 +0,0 @@
1
- import { readdir } from 'node:fs/promises';
2
- import { basename, extname, join } from 'node:path';
3
- import { pathToFileURL } from 'node:url';
4
- import { getEntities, getMeta } from '../entity/index.js';
5
- import type {
6
- Dialect,
7
- Migration,
8
- MigrationDefinition,
9
- MigrationResult,
10
- MigrationStorage,
11
- MigratorOptions,
12
- MongoQuerier,
13
- NamingStrategy,
14
- Querier,
15
- QuerierPool,
16
- SchemaDiff,
17
- SchemaGenerator,
18
- SchemaIntrospector,
19
- Type,
20
- } from '../type/index.js';
21
- import { isSqlQuerier } from '../type/index.js';
22
- import {
23
- MariadbSchemaGenerator,
24
- MongoSchemaGenerator,
25
- MysqlSchemaGenerator,
26
- PostgresSchemaGenerator,
27
- SqliteSchemaGenerator,
28
- } from './generator/index.js';
29
- import {
30
- MariadbSchemaIntrospector,
31
- MongoSchemaIntrospector,
32
- MysqlSchemaIntrospector,
33
- PostgresSchemaIntrospector,
34
- SqliteSchemaIntrospector,
35
- } from './introspection/index.js';
36
- import { DatabaseMigrationStorage } from './storage/databaseStorage.js';
37
-
38
- /**
39
- * Main class for managing database migrations
40
- */
41
- export class Migrator {
42
- private readonly storage: MigrationStorage;
43
- private readonly migrationsPath: string;
44
- private readonly logger: (message: string) => void;
45
- private readonly entities: Type<unknown>[];
46
- private readonly dialect: Dialect;
47
- private schemaGenerator?: SchemaGenerator;
48
- public schemaIntrospector?: SchemaIntrospector;
49
-
50
- constructor(
51
- private readonly querierPool: QuerierPool,
52
- options: MigratorOptions = {},
53
- ) {
54
- this.dialect = options.dialect ?? querierPool.dialect ?? 'postgres';
55
- this.storage =
56
- options.storage ??
57
- new DatabaseMigrationStorage(querierPool, {
58
- tableName: options.tableName,
59
- });
60
- this.migrationsPath = options.migrationsPath ?? './migrations';
61
- this.logger = options.logger ?? (() => {});
62
- this.entities = options.entities ?? [];
63
- this.schemaIntrospector = this.createIntrospector();
64
- this.schemaGenerator = options.schemaGenerator ?? this.createGenerator(options.namingStrategy);
65
- }
66
-
67
- /**
68
- * Set the schema generator for DDL operations
69
- */
70
- setSchemaGenerator(generator: SchemaGenerator): void {
71
- this.schemaGenerator = generator;
72
- }
73
-
74
- private createIntrospector(): SchemaIntrospector | undefined {
75
- switch (this.dialect) {
76
- case 'postgres':
77
- return new PostgresSchemaIntrospector(this.querierPool);
78
- case 'mysql':
79
- return new MysqlSchemaIntrospector(this.querierPool);
80
- case 'mariadb':
81
- return new MariadbSchemaIntrospector(this.querierPool);
82
- case 'sqlite':
83
- return new SqliteSchemaIntrospector(this.querierPool);
84
- case 'mongodb':
85
- return new MongoSchemaIntrospector(this.querierPool);
86
- default:
87
- return undefined;
88
- }
89
- }
90
-
91
- private createGenerator(namingStrategy?: NamingStrategy): SchemaGenerator | undefined {
92
- switch (this.dialect) {
93
- case 'postgres':
94
- return new PostgresSchemaGenerator(namingStrategy);
95
- case 'mysql':
96
- return new MysqlSchemaGenerator(namingStrategy);
97
- case 'mariadb':
98
- return new MariadbSchemaGenerator(namingStrategy);
99
- case 'sqlite':
100
- return new SqliteSchemaGenerator(namingStrategy);
101
- case 'mongodb':
102
- return new MongoSchemaGenerator(namingStrategy);
103
- default:
104
- return undefined;
105
- }
106
- }
107
-
108
- /**
109
- * Get the SQL dialect
110
- */
111
- getDialect(): Dialect {
112
- return this.dialect;
113
- }
114
-
115
- /**
116
- * Get all discovered migrations from the migrations directory
117
- */
118
- async getMigrations(): Promise<Migration[]> {
119
- const files = await this.getMigrationFiles();
120
- const migrations: Migration[] = [];
121
-
122
- for (const file of files) {
123
- const migration = await this.loadMigration(file);
124
- if (migration) {
125
- migrations.push(migration);
126
- }
127
- }
128
-
129
- // Sort by name (which typically includes timestamp)
130
- return migrations.sort((a: any, b: any) => a.name.localeCompare(b.name));
131
- }
132
-
133
- /**
134
- * Get list of pending migrations (not yet executed)
135
- */
136
- async pending(): Promise<Migration[]> {
137
- const [migrations, executed] = await Promise.all([this.getMigrations(), this.storage.executed()]);
138
-
139
- const executedSet = new Set(executed);
140
- return migrations.filter((m: any) => !executedSet.has(m.name));
141
- }
142
-
143
- /**
144
- * Get list of executed migrations
145
- */
146
- async executed(): Promise<string[]> {
147
- return this.storage.executed();
148
- }
149
-
150
- /**
151
- * Run all pending migrations
152
- */
153
- async up(options: { to?: string; step?: number } = {}): Promise<MigrationResult[]> {
154
- const pendingMigrations = await this.pending();
155
- const results: MigrationResult[] = [];
156
-
157
- let migrationsToRun = pendingMigrations;
158
-
159
- if (options.to) {
160
- const toIndex = migrationsToRun.findIndex((m: any) => m.name === options.to);
161
- if (toIndex === -1) {
162
- throw new Error(`Migration '${options.to}' not found`);
163
- }
164
- migrationsToRun = migrationsToRun.slice(0, toIndex + 1);
165
- }
166
-
167
- if (options.step !== undefined) {
168
- migrationsToRun = migrationsToRun.slice(0, options.step);
169
- }
170
-
171
- for (const migration of migrationsToRun) {
172
- const result = await this.runMigration(migration, 'up');
173
- results.push(result);
174
-
175
- if (!result.success) {
176
- break; // Stop on first failure
177
- }
178
- }
179
-
180
- return results;
181
- }
182
-
183
- /**
184
- * Rollback migrations
185
- */
186
- async down(options: { to?: string; step?: number } = {}): Promise<MigrationResult[]> {
187
- const [migrations, executed] = await Promise.all([this.getMigrations(), this.storage.executed()]);
188
-
189
- const executedSet = new Set(executed);
190
- const executedMigrations = migrations.filter((m: any) => executedSet.has(m.name)).reverse(); // Rollback in reverse order
191
-
192
- const results: MigrationResult[] = [];
193
- let migrationsToRun = executedMigrations;
194
-
195
- if (options.to) {
196
- const toIndex = migrationsToRun.findIndex((m: any) => m.name === options.to);
197
- if (toIndex === -1) {
198
- throw new Error(`Migration '${options.to}' not found`);
199
- }
200
- migrationsToRun = migrationsToRun.slice(0, toIndex + 1);
201
- }
202
-
203
- if (options.step !== undefined) {
204
- migrationsToRun = migrationsToRun.slice(0, options.step);
205
- }
206
-
207
- for (const migration of migrationsToRun) {
208
- const result = await this.runMigration(migration, 'down');
209
- results.push(result);
210
-
211
- if (!result.success) {
212
- break; // Stop on first failure
213
- }
214
- }
215
-
216
- return results;
217
- }
218
-
219
- /**
220
- * Run a single migration within a transaction
221
- */
222
- private async runMigration(migration: Migration, direction: 'up' | 'down'): Promise<MigrationResult> {
223
- const startTime = Date.now();
224
- const querier = await this.querierPool.getQuerier();
225
-
226
- if (!isSqlQuerier(querier)) {
227
- await querier.release();
228
- throw new Error('Migrator requires a SQL-based querier');
229
- }
230
-
231
- try {
232
- this.logger(`${direction === 'up' ? 'Running' : 'Reverting'} migration: ${migration.name}`);
233
-
234
- await querier.beginTransaction();
235
-
236
- if (direction === 'up') {
237
- await migration.up(querier);
238
- // Log within the same transaction
239
- await this.storage.logWithQuerier(querier, migration.name);
240
- } else {
241
- await migration.down(querier);
242
- // Unlog within the same transaction
243
- await this.storage.unlogWithQuerier(querier, migration.name);
244
- }
245
-
246
- await querier.commitTransaction();
247
-
248
- const duration = Date.now() - startTime;
249
- this.logger(`Migration ${migration.name} ${direction === 'up' ? 'applied' : 'reverted'} in ${duration}ms`);
250
-
251
- return {
252
- name: migration.name,
253
- direction,
254
- duration,
255
- success: true,
256
- };
257
- } catch (error) {
258
- await querier.rollbackTransaction();
259
-
260
- const duration = Date.now() - startTime;
261
- this.logger(`Migration ${migration.name} failed: ${(error as Error).message}`);
262
-
263
- return {
264
- name: migration.name,
265
- direction,
266
- duration,
267
- success: false,
268
- error: error as Error,
269
- };
270
- } finally {
271
- await querier.release();
272
- }
273
- }
274
-
275
- /**
276
- * Generate a new migration file
277
- */
278
- async generate(name: string): Promise<string> {
279
- const timestamp = this.getTimestamp();
280
- const fileName = `${timestamp}_${this.slugify(name)}.ts`;
281
- const filePath = join(this.migrationsPath, fileName);
282
-
283
- const content = this.generateMigrationContent(name);
284
-
285
- const { writeFile, mkdir } = await import('node:fs/promises');
286
- await mkdir(this.migrationsPath, { recursive: true });
287
- await writeFile(filePath, content, 'utf-8');
288
-
289
- this.logger(`Created migration: ${filePath}`);
290
- return filePath;
291
- }
292
-
293
- /**
294
- * Generate a migration based on entity schema differences
295
- */
296
- async generateFromEntities(name: string): Promise<string> {
297
- if (!this.schemaGenerator) {
298
- throw new Error('Schema generator not set. Call setSchemaGenerator() first.');
299
- }
300
-
301
- const diffs = await this.getDiffs();
302
- const upStatements: string[] = [];
303
- const downStatements: string[] = [];
304
-
305
- for (const diff of diffs) {
306
- if (diff.type === 'create') {
307
- const entity = this.findEntityForTable(diff.tableName);
308
- if (entity) {
309
- upStatements.push(this.schemaGenerator.generateCreateTable(entity));
310
- downStatements.push(this.schemaGenerator.generateDropTable(entity));
311
- }
312
- } else if (diff.type === 'alter') {
313
- const alterStatements = this.schemaGenerator.generateAlterTable(diff);
314
- upStatements.push(...alterStatements);
315
-
316
- const alterDownStatements = this.schemaGenerator.generateAlterTableDown(diff);
317
- downStatements.push(...alterDownStatements);
318
- }
319
- }
320
-
321
- if (upStatements.length === 0) {
322
- this.logger('No schema changes detected.');
323
- return '';
324
- }
325
-
326
- const timestamp = this.getTimestamp();
327
- const fileName = `${timestamp}_${this.slugify(name)}.ts`;
328
- const filePath = join(this.migrationsPath, fileName);
329
-
330
- const content = this.generateMigrationContentWithStatements(name, upStatements, downStatements.reverse());
331
-
332
- const { writeFile, mkdir } = await import('node:fs/promises');
333
- await mkdir(this.migrationsPath, { recursive: true });
334
- await writeFile(filePath, content, 'utf-8');
335
-
336
- this.logger(`Created migration from entities: ${filePath}`);
337
- return filePath;
338
- }
339
-
340
- /**
341
- * Get all schema differences between entities and database
342
- */
343
- async getDiffs(): Promise<SchemaDiff[]> {
344
- if (!this.schemaGenerator || !this.schemaIntrospector) {
345
- throw new Error('Schema generator and introspector must be set');
346
- }
347
-
348
- const entities = this.entities.length > 0 ? this.entities : getEntities();
349
- const diffs: SchemaDiff[] = [];
350
-
351
- for (const entity of entities) {
352
- const meta = getMeta(entity);
353
- const tableName = this.schemaGenerator.resolveTableName(entity, meta);
354
- const currentSchema = await this.schemaIntrospector.getTableSchema(tableName);
355
- const diff = this.schemaGenerator.diffSchema(entity, currentSchema);
356
- if (diff) {
357
- diffs.push(diff);
358
- }
359
- }
360
-
361
- return diffs;
362
- }
363
-
364
- private findEntityForTable(tableName: string): Type<unknown> | undefined {
365
- const entities = this.entities.length > 0 ? this.entities : getEntities();
366
- for (const entity of entities) {
367
- const meta = getMeta(entity);
368
- const name = this.schemaGenerator.resolveTableName(entity, meta);
369
- if (name === tableName) {
370
- return entity;
371
- }
372
- }
373
- return undefined;
374
- }
375
-
376
- /**
377
- * Sync schema directly (for development only - not for production!)
378
- */
379
- async sync(options: { force?: boolean } = {}): Promise<void> {
380
- if (options.force) {
381
- return this.syncForce();
382
- }
383
- return this.autoSync({ safe: true });
384
- }
385
-
386
- /**
387
- * Drops and recreates all tables (Development only!)
388
- */
389
- public async syncForce(): Promise<void> {
390
- if (!this.schemaGenerator) {
391
- throw new Error('Schema generator not set. Call setSchemaGenerator() first.');
392
- }
393
-
394
- const entities = this.entities.length > 0 ? this.entities : getEntities();
395
- const querier = await this.querierPool.getQuerier();
396
-
397
- if (!isSqlQuerier(querier)) {
398
- await querier.release();
399
- throw new Error('Migrator requires a SQL-based querier');
400
- }
401
-
402
- try {
403
- await querier.beginTransaction();
404
-
405
- // Drop all tables first (in reverse order for foreign keys)
406
- for (const entity of [...entities].reverse()) {
407
- const dropSql = this.schemaGenerator.generateDropTable(entity);
408
- this.logger(`Executing: ${dropSql}`);
409
- await querier.run(dropSql);
410
- }
411
-
412
- // Create all tables
413
- for (const entity of entities) {
414
- const createSql = this.schemaGenerator.generateCreateTable(entity);
415
- this.logger(`Executing: ${createSql}`);
416
- await querier.run(createSql);
417
- }
418
-
419
- await querier.commitTransaction();
420
- this.logger('Schema sync (force) completed');
421
- } catch (error) {
422
- await querier.rollbackTransaction();
423
- throw error;
424
- } finally {
425
- await querier.release();
426
- }
427
- }
428
-
429
- /**
430
- * Safely synchronizes the schema by only adding missing tables and columns.
431
- */
432
- async autoSync(options: { safe?: boolean; drop?: boolean; logging?: boolean } = {}): Promise<void> {
433
- if (!this.schemaGenerator || !this.schemaIntrospector) {
434
- throw new Error('Schema generator and introspector must be set');
435
- }
436
-
437
- const diffs = await this.getDiffs();
438
- const statements: string[] = [];
439
-
440
- for (const diff of diffs) {
441
- if (diff.type === 'create') {
442
- const entity = this.findEntityForTable(diff.tableName);
443
- if (entity) {
444
- statements.push(this.schemaGenerator.generateCreateTable(entity));
445
- }
446
- } else if (diff.type === 'alter') {
447
- const filteredDiff = this.filterDiff(diff, options);
448
- const alterStatements = this.schemaGenerator.generateAlterTable(filteredDiff);
449
- statements.push(...alterStatements);
450
- }
451
- }
452
-
453
- if (statements.length === 0) {
454
- if (options.logging) this.logger('Schema is already in sync.');
455
- return;
456
- }
457
-
458
- await this.executeSyncStatements(statements, options);
459
- }
460
-
461
- private filterDiff(diff: SchemaDiff, options: { safe?: boolean; drop?: boolean }): SchemaDiff {
462
- const filteredDiff = { ...diff } as { -readonly [K in keyof SchemaDiff]: SchemaDiff[K] };
463
- if (options.safe !== false) {
464
- // In safe mode, we only allow additions
465
- delete filteredDiff.columnsToDrop;
466
- delete filteredDiff.indexesToDrop;
467
- delete filteredDiff.foreignKeysToDrop;
468
- }
469
- if (!options.drop) {
470
- delete filteredDiff.columnsToDrop;
471
- }
472
- return filteredDiff;
473
- }
474
-
475
- private async executeSyncStatements(statements: string[], options: { logging?: boolean }): Promise<void> {
476
- const querier = await this.querierPool.getQuerier();
477
- try {
478
- if (this.dialect === 'mongodb') {
479
- await this.executeMongoSyncStatements(statements, options, querier as MongoQuerier);
480
- } else {
481
- await this.executeSqlSyncStatements(statements, options, querier);
482
- }
483
- if (options.logging) this.logger('Schema synchronization completed');
484
- } catch (error) {
485
- if (this.dialect !== 'mongodb' && isSqlQuerier(querier)) {
486
- await querier.rollbackTransaction();
487
- }
488
- throw error;
489
- } finally {
490
- await querier.release();
491
- }
492
- }
493
-
494
- private async executeMongoSyncStatements(
495
- statements: string[],
496
- options: { logging?: boolean },
497
- querier: MongoQuerier,
498
- ): Promise<void> {
499
- const db = querier.db;
500
- for (const stmt of statements) {
501
- const cmd = JSON.parse(stmt) as {
502
- action: string;
503
- name?: string;
504
- collection?: string;
505
- indexes?: { name: string; columns: string[]; unique?: boolean }[];
506
- key?: Record<string, number>;
507
- options?: any;
508
- };
509
- if (options.logging) this.logger(`Executing MongoDB: ${stmt}`);
510
-
511
- const collectionName = cmd.name || cmd.collection;
512
- if (!collectionName) {
513
- throw new Error(`MongoDB command missing collection name: ${stmt}`);
514
- }
515
- const collection = db.collection(collectionName);
516
-
517
- if (cmd.action === 'createCollection') {
518
- await db.createCollection(cmd.name);
519
- if (cmd.indexes?.length) {
520
- for (const idx of cmd.indexes) {
521
- const key = Object.fromEntries(idx.columns.map((c: string) => [c, 1]));
522
- await collection.createIndex(key, { unique: idx.unique, name: idx.name });
523
- }
524
- }
525
- } else if (cmd.action === 'dropCollection') {
526
- await collection.drop();
527
- } else if (cmd.action === 'createIndex') {
528
- await collection.createIndex(cmd.key, cmd.options);
529
- } else if (cmd.action === 'dropIndex') {
530
- await collection.dropIndex(cmd.name);
531
- }
532
- }
533
- }
534
-
535
- private async executeSqlSyncStatements(
536
- statements: string[],
537
- options: { logging?: boolean },
538
- querier: Querier,
539
- ): Promise<void> {
540
- if (!isSqlQuerier(querier)) {
541
- throw new Error('Migrator requires a SQL-based querier for this dialect');
542
- }
543
- await querier.beginTransaction();
544
- for (const sql of statements) {
545
- if (options.logging) this.logger(`Executing: ${sql}`);
546
- await querier.run(sql);
547
- }
548
- await querier.commitTransaction();
549
- }
550
-
551
- /**
552
- * Get migration status
553
- */
554
- async status(): Promise<{ pending: string[]; executed: string[] }> {
555
- const [pending, executed] = await Promise.all([this.pending().then((m) => m.map((x) => x.name)), this.executed()]);
556
-
557
- return { pending, executed };
558
- }
559
-
560
- /**
561
- * Get migration files from the migrations directory
562
- */
563
- private async getMigrationFiles(): Promise<string[]> {
564
- try {
565
- const files = await readdir(this.migrationsPath);
566
- return files
567
- .filter((f) => /\.(ts|js|mjs)$/.test(f))
568
- .filter((f) => !f.endsWith('.d.ts'))
569
- .sort();
570
- } catch (error) {
571
- if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
572
- return [];
573
- }
574
- throw error;
575
- }
576
- }
577
-
578
- /**
579
- * Load a migration from a file
580
- */
581
- private async loadMigration(fileName: string): Promise<Migration | undefined> {
582
- const filePath = join(this.migrationsPath, fileName);
583
- const fileUrl = pathToFileURL(filePath).href;
584
-
585
- try {
586
- const module = await import(fileUrl);
587
- const migration = module.default ?? module;
588
-
589
- if (this.isMigration(migration)) {
590
- return {
591
- name: this.getMigrationName(fileName),
592
- up: migration.up.bind(migration),
593
- down: migration.down.bind(migration),
594
- };
595
- }
596
-
597
- this.logger(`Warning: ${fileName} is not a valid migration`);
598
- return undefined;
599
- } catch (error) {
600
- this.logger(`Error loading migration ${fileName}: ${(error as Error).message}`);
601
- return undefined;
602
- }
603
- }
604
-
605
- /**
606
- * Check if an object is a valid migration
607
- */
608
- private isMigration(obj: unknown): obj is MigrationDefinition {
609
- return (
610
- typeof obj === 'object' &&
611
- obj !== undefined &&
612
- obj !== null &&
613
- typeof (obj as MigrationDefinition).up === 'function' &&
614
- typeof (obj as MigrationDefinition).down === 'function'
615
- );
616
- }
617
-
618
- /**
619
- * Extract migration name from filename
620
- */
621
- private getMigrationName(fileName: string): string {
622
- return basename(fileName, extname(fileName));
623
- }
624
-
625
- /**
626
- * Generate timestamp string for migration names
627
- */
628
- private getTimestamp(): string {
629
- const now = new Date();
630
- return [
631
- now.getFullYear(),
632
- String(now.getMonth() + 1).padStart(2, '0'),
633
- String(now.getDate()).padStart(2, '0'),
634
- String(now.getHours()).padStart(2, '0'),
635
- String(now.getMinutes()).padStart(2, '0'),
636
- String(now.getSeconds()).padStart(2, '0'),
637
- ].join('');
638
- }
639
-
640
- /**
641
- * Convert a string to a slug for filenames
642
- */
643
- private slugify(text: string): string {
644
- return text
645
- .toLowerCase()
646
- .replace(/[^a-z0-9]+/g, '_')
647
- .replace(/^_+|_+$/g, '');
648
- }
649
-
650
- /**
651
- * Generate migration file content
652
- */
653
- private generateMigrationContent(name: string): string {
654
- return /*ts*/ `import type { SqlQuerier } from '@uql/migrate';
655
-
656
- /**
657
- * Migration: ${name}
658
- * Created: ${new Date().toISOString()}
659
- */
660
- export default {
661
- async up(querier: SqlQuerier): Promise<void> {
662
- // Add your migration logic here
663
- // Example:
664
- // await querier.run(\`
665
- // CREATE TABLE "users" (
666
- // "id" SERIAL PRIMARY KEY,
667
- // "name" VARCHAR(255) NOT NULL,
668
- // "email" VARCHAR(255) UNIQUE NOT NULL,
669
- // "createdAt" TIMESTAMP DEFAULT CURRENT_TIMESTAMP
670
- // )
671
- // \`);
672
- },
673
-
674
- async down(querier: SqlQuerier): Promise<void> {
675
- // Add your rollback logic here
676
- // Example:
677
- // await querier.run(\`DROP TABLE IF EXISTS "users"\`);
678
- },
679
- };
680
- `;
681
- }
682
-
683
- /**
684
- * Generate migration file content with SQL statements
685
- */
686
- private generateMigrationContentWithStatements(
687
- name: string,
688
- upStatements: string[],
689
- downStatements: string[],
690
- ): string {
691
- const upSql = upStatements.map((s) => /*ts*/ ` await querier.run(\`${s}\`);`).join('\n');
692
- const downSql = downStatements.map((s) => /*ts*/ ` await querier.run(\`${s}\`);`).join('\n');
693
-
694
- return /*ts*/ `import type { SqlQuerier } from '@uql/migrate';
695
-
696
- /**
697
- * Migration: ${name}
698
- * Created: ${new Date().toISOString()}
699
- * Generated from entity definitions
700
- */
701
- export default {
702
- async up(querier: SqlQuerier): Promise<void> {
703
- ${upSql}
704
- },
705
-
706
- async down(querier: SqlQuerier): Promise<void> {
707
- ${downSql}
708
- },
709
- };
710
- `;
711
- }
712
- }
713
-
714
- /**
715
- * Helper function to define a migration with proper typing
716
- */
717
- export function defineMigration(migration: MigrationDefinition): MigrationDefinition {
718
- return migration;
719
- }