-
-
Notifications
You must be signed in to change notification settings - Fork 6.2k
/
Connection.ts
541 lines (453 loc) · 21 KB
/
Connection.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
import {Driver} from "../driver/Driver";
import {Repository} from "../repository/Repository";
import {EntitySubscriberInterface} from "../subscriber/EntitySubscriberInterface";
import {ObjectType} from "../common/ObjectType";
import {EntityManager} from "../entity-manager/EntityManager";
import {DefaultNamingStrategy} from "../naming-strategy/DefaultNamingStrategy";
import {CannotExecuteNotConnectedError} from "../error/CannotExecuteNotConnectedError";
import {CannotConnectAlreadyConnectedError} from "../error/CannotConnectAlreadyConnectedError";
import {TreeRepository} from "../repository/TreeRepository";
import {NamingStrategyInterface} from "../naming-strategy/NamingStrategyInterface";
import {EntityMetadata} from "../metadata/EntityMetadata";
import {Logger} from "../logger/Logger";
import {EntityMetadataNotFoundError} from "../error/EntityMetadataNotFoundError";
import {MigrationInterface} from "../migration/MigrationInterface";
import {MigrationExecutor} from "../migration/MigrationExecutor";
import {Migration} from "../migration/Migration";
import {MongoRepository} from "../repository/MongoRepository";
import {MongoDriver} from "../driver/mongodb/MongoDriver";
import {MongoEntityManager} from "../entity-manager/MongoEntityManager";
import {EntityMetadataValidator} from "../metadata-builder/EntityMetadataValidator";
import {ConnectionOptions} from "./ConnectionOptions";
import {QueryRunnerProviderAlreadyReleasedError} from "../error/QueryRunnerProviderAlreadyReleasedError";
import {EntityManagerFactory} from "../entity-manager/EntityManagerFactory";
import {DriverFactory} from "../driver/DriverFactory";
import {ConnectionMetadataBuilder} from "./ConnectionMetadataBuilder";
import {QueryRunner} from "../query-runner/QueryRunner";
import {SelectQueryBuilder} from "../query-builder/SelectQueryBuilder";
import {LoggerFactory} from "../logger/LoggerFactory";
import {QueryResultCacheFactory} from "../cache/QueryResultCacheFactory";
import {QueryResultCache} from "../cache/QueryResultCache";
import {SqljsEntityManager} from "../entity-manager/SqljsEntityManager";
import {RelationLoader} from "../query-builder/RelationLoader";
import {RelationIdLoader} from "../query-builder/RelationIdLoader";
import {EntitySchema} from "../";
import {SqlServerDriver} from "../driver/sqlserver/SqlServerDriver";
import {MysqlDriver} from "../driver/mysql/MysqlDriver";
import {ObjectUtils} from "../util/ObjectUtils";
import {PromiseUtils} from "../";
import {IsolationLevel} from "../driver/types/IsolationLevel";
import {AuroraDataApiDriver} from "../driver/aurora-data-api/AuroraDataApiDriver";
/**
* Connection is a single database ORM connection to a specific database.
* Its not required to be a database connection, depend on database type it can create connection pool.
* You can have multiple connections to multiple databases in your application.
*/
export class Connection {
// -------------------------------------------------------------------------
// Public Readonly Properties
// -------------------------------------------------------------------------
/**
* Connection name.
*/
readonly name: string;
/**
* Connection options.
*/
readonly options: ConnectionOptions;
/**
* Indicates if connection is initialized or not.
*/
readonly isConnected: boolean;
/**
* Database driver used by this connection.
*/
readonly driver: Driver;
/**
* EntityManager of this connection.
*/
readonly manager: EntityManager;
/**
* Naming strategy used in the connection.
*/
readonly namingStrategy: NamingStrategyInterface;
/**
* Logger used to log orm events.
*/
readonly logger: Logger;
/**
* Migration instances that are registered for this connection.
*/
readonly migrations: MigrationInterface[] = [];
/**
* Entity subscriber instances that are registered for this connection.
*/
readonly subscribers: EntitySubscriberInterface<any>[] = [];
/**
* All entity metadatas that are registered for this connection.
*/
readonly entityMetadatas: EntityMetadata[] = [];
/**
* Used to work with query result cache.
*/
readonly queryResultCache?: QueryResultCache;
/**
* Used to load relations and work with lazy relations.
*/
readonly relationLoader: RelationLoader;
/**
* Used to load relation ids of specific entity relations.
*/
readonly relationIdLoader: RelationIdLoader;
// -------------------------------------------------------------------------
// Constructor
// -------------------------------------------------------------------------
constructor(options: ConnectionOptions) {
this.name = options.name || "default";
this.options = options;
this.logger = new LoggerFactory().create(this.options.logger, this.options.logging);
this.driver = new DriverFactory().create(this);
this.manager = this.createEntityManager();
this.namingStrategy = options.namingStrategy || new DefaultNamingStrategy();
this.queryResultCache = options.cache ? new QueryResultCacheFactory(this).create() : undefined;
this.relationLoader = new RelationLoader(this);
this.relationIdLoader = new RelationIdLoader(this);
this.isConnected = false;
}
// -------------------------------------------------------------------------
// Public Accessors
// -------------------------------------------------------------------------
/**
* Gets the mongodb entity manager that allows to perform mongodb-specific repository operations
* with any entity in this connection.
*
* Available only in mongodb connections.
*/
get mongoManager(): MongoEntityManager {
if (!(this.manager instanceof MongoEntityManager))
throw new Error(`MongoEntityManager is only available for MongoDB databases.`);
return this.manager as MongoEntityManager;
}
/**
* Gets a sql.js specific Entity Manager that allows to perform special load and save operations
*
* Available only in connection with the sqljs driver.
*/
get sqljsManager(): SqljsEntityManager {
if (!(this.manager instanceof SqljsEntityManager))
throw new Error(`SqljsEntityManager is only available for Sqljs databases.`);
return this.manager as SqljsEntityManager;
}
// -------------------------------------------------------------------------
// Public Methods
// -------------------------------------------------------------------------
/**
* Performs connection to the database.
* This method should be called once on application bootstrap.
* This method not necessarily creates database connection (depend on database type),
* but it also can setup a connection pool with database to use.
*/
async connect(): Promise<this> {
if (this.isConnected)
throw new CannotConnectAlreadyConnectedError(this.name);
// connect to the database via its driver
await this.driver.connect();
// connect to the cache-specific database if cache is enabled
if (this.queryResultCache)
await this.queryResultCache.connect();
// set connected status for the current connection
ObjectUtils.assign(this, { isConnected: true });
try {
// build all metadatas registered in the current connection
this.buildMetadatas();
await this.driver.afterConnect();
// if option is set - drop schema once connection is done
if (this.options.dropSchema)
await this.dropDatabase();
// if option is set - automatically synchronize a schema
if (this.options.synchronize)
await this.synchronize();
// if option is set - automatically synchronize a schema
if (this.options.migrationsRun)
await this.runMigrations({ transaction: this.options.migrationsTransactionMode });
} catch (error) {
// if for some reason build metadata fail (for example validation error during entity metadata check)
// connection needs to be closed
await this.close();
throw error;
}
return this;
}
/**
* Closes connection with the database.
* Once connection is closed, you cannot use repositories or perform any operations except opening connection again.
*/
async close(): Promise<void> {
if (!this.isConnected)
throw new CannotExecuteNotConnectedError(this.name);
await this.driver.disconnect();
// disconnect from the cache-specific database if cache was enabled
if (this.queryResultCache)
await this.queryResultCache.disconnect();
ObjectUtils.assign(this, { isConnected: false });
}
/**
* Creates database schema for all entities registered in this connection.
* Can be used only after connection to the database is established.
*
* @param dropBeforeSync If set to true then it drops the database with all its tables and data
*/
async synchronize(dropBeforeSync: boolean = false): Promise<void> {
if (!this.isConnected)
throw new CannotExecuteNotConnectedError(this.name);
if (dropBeforeSync)
await this.dropDatabase();
const schemaBuilder = this.driver.createSchemaBuilder();
await schemaBuilder.build();
}
/**
* Drops the database and all its data.
* Be careful with this method on production since this method will erase all your database tables and their data.
* Can be used only after connection to the database is established.
*/
// TODO rename
async dropDatabase(): Promise<void> {
const queryRunner = this.createQueryRunner("master");
try {
if (this.driver instanceof SqlServerDriver || this.driver instanceof MysqlDriver || this.driver instanceof AuroraDataApiDriver) {
const databases: string[] = this.driver.database ? [this.driver.database] : [];
this.entityMetadatas.forEach(metadata => {
if (metadata.database && databases.indexOf(metadata.database) === -1)
databases.push(metadata.database);
});
await PromiseUtils.runInSequence(databases, database => queryRunner.clearDatabase(database));
} else {
await queryRunner.clearDatabase();
}
} finally {
await queryRunner.release();
}
}
/**
* Runs all pending migrations.
* Can be used only after connection to the database is established.
*/
async runMigrations(options?: { transaction?: "all" | "none" | "each" }): Promise<Migration[]> {
if (!this.isConnected)
throw new CannotExecuteNotConnectedError(this.name);
const migrationExecutor = new MigrationExecutor(this);
migrationExecutor.transaction = (options && options.transaction) || "all";
const successMigrations = await migrationExecutor.executePendingMigrations();
return successMigrations;
}
/**
* Reverts last executed migration.
* Can be used only after connection to the database is established.
*/
async undoLastMigration(options?: { transaction?: "all" | "none" | "each" }): Promise<void> {
if (!this.isConnected)
throw new CannotExecuteNotConnectedError(this.name);
const migrationExecutor = new MigrationExecutor(this);
migrationExecutor.transaction = (options && options.transaction) || "all";
await migrationExecutor.undoLastMigration();
}
/**
* Lists all migrations and whether they have been run.
* Returns true if there are pending migrations
*/
async showMigrations(): Promise<boolean> {
if (!this.isConnected) {
throw new CannotExecuteNotConnectedError(this.name);
}
const migrationExecutor = new MigrationExecutor(this);
return await migrationExecutor.showMigrations();
}
/**
* Checks if entity metadata exist for the given entity class, target name or table name.
*/
hasMetadata(target: Function|EntitySchema<any>|string): boolean {
return !!this.findMetadata(target);
}
/**
* Gets entity metadata for the given entity class or schema name.
*/
getMetadata(target: Function|EntitySchema<any>|string): EntityMetadata {
const metadata = this.findMetadata(target);
if (!metadata)
throw new EntityMetadataNotFoundError(target);
return metadata;
}
/**
* Gets repository for the given entity.
*/
getRepository<Entity>(target: ObjectType<Entity>|EntitySchema<Entity>|string): Repository<Entity> {
return this.manager.getRepository(target);
}
/**
* Gets tree repository for the given entity class or name.
* Only tree-type entities can have a TreeRepository, like ones decorated with @Tree decorator.
*/
getTreeRepository<Entity>(target: ObjectType<Entity>|EntitySchema<Entity>|string): TreeRepository<Entity> {
return this.manager.getTreeRepository(target);
}
/**
* Gets mongodb-specific repository for the given entity class or name.
* Works only if connection is mongodb-specific.
*/
getMongoRepository<Entity>(target: ObjectType<Entity>|EntitySchema<Entity>|string): MongoRepository<Entity> {
if (!(this.driver instanceof MongoDriver))
throw new Error(`You can use getMongoRepository only for MongoDB connections.`);
return this.manager.getRepository(target) as any;
}
/**
* Gets custom entity repository marked with @EntityRepository decorator.
*/
getCustomRepository<T>(customRepository: ObjectType<T>): T {
return this.manager.getCustomRepository(customRepository);
}
/**
* Wraps given function execution (and all operations made there) into a transaction.
* All database operations must be executed using provided entity manager.
*/
async transaction<T>(runInTransaction: (entityManager: EntityManager) => Promise<T>): Promise<T>;
async transaction<T>(isolationLevel: IsolationLevel, runInTransaction: (entityManager: EntityManager) => Promise<T>): Promise<T>;
async transaction<T>(
isolationOrRunInTransaction: IsolationLevel | ((entityManager: EntityManager) => Promise<T>),
runInTransactionParam?: (entityManager: EntityManager) => Promise<T>
): Promise<any> {
return this.manager.transaction(
isolationOrRunInTransaction as any,
runInTransactionParam as any
);
}
/**
* Executes raw SQL query and returns raw database results.
*/
async query(query: string, parameters?: any[], queryRunner?: QueryRunner): Promise<any> {
if (this instanceof MongoEntityManager)
throw new Error(`Queries aren't supported by MongoDB.`);
if (queryRunner && queryRunner.isReleased)
throw new QueryRunnerProviderAlreadyReleasedError();
const usedQueryRunner = queryRunner || this.createQueryRunner("master");
try {
return await usedQueryRunner.query(query, parameters); // await is needed here because we are using finally
} finally {
if (!queryRunner)
await usedQueryRunner.release();
}
}
/**
* Creates a new query builder that can be used to build a sql query.
*/
createQueryBuilder<Entity>(entityClass: ObjectType<Entity>|EntitySchema<Entity>|Function|string, alias: string, queryRunner?: QueryRunner): SelectQueryBuilder<Entity>;
/**
* Creates a new query builder that can be used to build a sql query.
*/
createQueryBuilder(queryRunner?: QueryRunner): SelectQueryBuilder<any>;
/**
* Creates a new query builder that can be used to build a sql query.
*/
createQueryBuilder<Entity>(entityOrRunner?: ObjectType<Entity>|EntitySchema<Entity>|Function|string|QueryRunner, alias?: string, queryRunner?: QueryRunner): SelectQueryBuilder<Entity> {
if (this instanceof MongoEntityManager)
throw new Error(`Query Builder is not supported by MongoDB.`);
if (alias) {
const metadata = this.getMetadata(entityOrRunner as Function|EntitySchema<Entity>|string);
return new SelectQueryBuilder(this, queryRunner)
.select(alias)
.from(metadata.target, alias);
} else {
return new SelectQueryBuilder(this, entityOrRunner as QueryRunner|undefined);
}
}
/**
* Creates a query runner used for perform queries on a single database connection.
* Using query runners you can control your queries to execute using single database connection and
* manually control your database transaction.
*
* Mode is used in replication mode and indicates whatever you want to connect
* to master database or any of slave databases.
* If you perform writes you must use master database,
* if you perform reads you can use slave databases.
*/
createQueryRunner(mode: "master"|"slave" = "master"): QueryRunner {
const queryRunner = this.driver.createQueryRunner(mode);
const manager = this.createEntityManager(queryRunner);
Object.assign(queryRunner, { manager: manager });
return queryRunner;
}
/**
* Gets entity metadata of the junction table (many-to-many table).
*/
getManyToManyMetadata(entityTarget: Function|string, relationPropertyPath: string) {
const relationMetadata = this.getMetadata(entityTarget).findRelationWithPropertyPath(relationPropertyPath);
if (!relationMetadata)
throw new Error(`Relation "${relationPropertyPath}" was not found in ${entityTarget} entity.`);
if (!relationMetadata.isManyToMany)
throw new Error(`Relation "${entityTarget}#${relationPropertyPath}" does not have a many-to-many relationship.` +
`You can use this method only on many-to-many relations.`);
return relationMetadata.junctionEntityMetadata;
}
/**
* Creates an Entity Manager for the current connection with the help of the EntityManagerFactory.
*/
createEntityManager(queryRunner?: QueryRunner): EntityManager {
return new EntityManagerFactory().create(this, queryRunner);
}
// -------------------------------------------------------------------------
// Protected Methods
// -------------------------------------------------------------------------
/**
* Finds exist entity metadata by the given entity class, target name or table name.
*/
protected findMetadata(target: Function|EntitySchema<any>|string): EntityMetadata|undefined {
return this.entityMetadatas.find(metadata => {
if (metadata.target === target)
return true;
if (target instanceof EntitySchema) {
return metadata.name === target.options.name;
}
if (typeof target === "string") {
if (target.indexOf(".") !== -1) {
return metadata.tablePath === target;
} else {
return metadata.name === target || metadata.tableName === target;
}
}
return false;
});
}
/**
* Builds metadatas for all registered classes inside this connection.
*/
protected buildMetadatas(): void {
const connectionMetadataBuilder = new ConnectionMetadataBuilder(this);
const entityMetadataValidator = new EntityMetadataValidator();
// create subscribers instances if they are not disallowed from high-level (for example they can disallowed from migrations run process)
const subscribers = connectionMetadataBuilder.buildSubscribers(this.options.subscribers || []);
ObjectUtils.assign(this, { subscribers: subscribers });
// build entity metadatas
const entityMetadatas = connectionMetadataBuilder.buildEntityMetadatas(this.options.entities || []);
ObjectUtils.assign(this, { entityMetadatas: entityMetadatas });
// create migration instances
const migrations = connectionMetadataBuilder.buildMigrations(this.options.migrations || []);
ObjectUtils.assign(this, { migrations: migrations });
this.driver.database = this.getDatabaseName();
// validate all created entity metadatas to make sure user created entities are valid and correct
entityMetadataValidator.validateMany(this.entityMetadatas.filter(metadata => metadata.tableType !== "view"), this.driver);
}
// This database name property is nested for replication configs.
protected getDatabaseName(): string {
const options = this.options;
switch (options.type) {
case "mysql" :
case "mariadb" :
case "postgres":
case "cockroachdb":
case "mssql":
case "oracle":
return (options.replication ? options.replication.master.database : options.database) as string;
default:
return options.database as string;
}
}
}