typeorm 0.3.7-dev.ec23922 → 0.3.7
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.
- package/browser/cache/DbQueryResultCache.d.ts +1 -1
- package/browser/cache/DbQueryResultCache.js +5 -1
- package/browser/cache/DbQueryResultCache.js.map +1 -1
- package/browser/cli-ts-node-commonjs.js +0 -0
- package/browser/cli-ts-node-esm.js +0 -0
- package/browser/data-source/DataSource.d.ts +4 -3
- package/browser/data-source/DataSource.js.map +1 -1
- package/browser/driver/better-sqlite3/BetterSqlite3ConnectionOptions.d.ts +4 -0
- package/browser/driver/better-sqlite3/BetterSqlite3ConnectionOptions.js.map +1 -1
- package/browser/driver/better-sqlite3/BetterSqlite3Driver.d.ts +1 -1
- package/browser/driver/better-sqlite3/BetterSqlite3Driver.js +4 -3
- package/browser/driver/better-sqlite3/BetterSqlite3Driver.js.map +1 -1
- package/browser/driver/sap/SapQueryRunner.d.ts +7 -0
- package/browser/driver/sap/SapQueryRunner.js +24 -2
- package/browser/driver/sap/SapQueryRunner.js.map +1 -1
- package/browser/entity-manager/EntityManager.d.ts +9 -8
- package/browser/entity-manager/EntityManager.js.map +1 -1
- package/browser/entity-manager/MongoEntityManager.d.ts +1 -1
- package/browser/entity-manager/MongoEntityManager.js.map +1 -1
- package/browser/globals.d.ts +5 -4
- package/browser/globals.js.map +1 -1
- package/browser/query-builder/RelationIdLoader.d.ts +1 -1
- package/browser/query-builder/RelationIdLoader.js.map +1 -1
- package/browser/query-builder/SoftDeleteQueryBuilder.d.ts +2 -2
- package/browser/query-builder/SoftDeleteQueryBuilder.js.map +1 -1
- package/browser/query-builder/UpdateQueryBuilder.d.ts +1 -1
- package/browser/query-builder/UpdateQueryBuilder.js.map +1 -1
- package/browser/query-builder/transformer/DocumentToEntityTransformer.js +1 -1
- package/browser/query-builder/transformer/DocumentToEntityTransformer.js.map +1 -1
- package/browser/query-builder/transformer/PlainObjectToNewEntityTransformer.d.ts +1 -1
- package/browser/query-builder/transformer/PlainObjectToNewEntityTransformer.js.map +1 -1
- package/browser/query-builder/transformer/RawSqlResultsToEntityTransformer.js +2 -1
- package/browser/query-builder/transformer/RawSqlResultsToEntityTransformer.js.map +1 -1
- package/browser/repository/AbstractRepository.d.ts +3 -3
- package/browser/repository/AbstractRepository.js.map +1 -1
- package/browser/repository/TreeRepository.d.ts +2 -1
- package/browser/repository/TreeRepository.js.map +1 -1
- package/cache/DbQueryResultCache.d.ts +1 -1
- package/cache/DbQueryResultCache.js +5 -1
- package/cache/DbQueryResultCache.js.map +1 -1
- package/cli-ts-node-commonjs.js +0 -0
- package/cli-ts-node-esm.js +0 -0
- package/cli.js +0 -0
- package/commands/CacheClearCommand.js +1 -1
- package/commands/CacheClearCommand.js.map +1 -1
- package/commands/MigrationRevertCommand.js +1 -1
- package/commands/MigrationRevertCommand.js.map +1 -1
- package/commands/MigrationRunCommand.js +1 -1
- package/commands/MigrationRunCommand.js.map +1 -1
- package/commands/MigrationShowCommand.js +1 -1
- package/commands/MigrationShowCommand.js.map +1 -1
- package/commands/QueryCommand.js +1 -1
- package/commands/QueryCommand.js.map +1 -1
- package/commands/SchemaDropCommand.js +1 -1
- package/commands/SchemaDropCommand.js.map +1 -1
- package/commands/SchemaSyncCommand.js +1 -1
- package/commands/SchemaSyncCommand.js.map +1 -1
- package/data-source/DataSource.d.ts +4 -3
- package/data-source/DataSource.js.map +1 -1
- package/driver/better-sqlite3/BetterSqlite3ConnectionOptions.d.ts +4 -0
- package/driver/better-sqlite3/BetterSqlite3ConnectionOptions.js.map +1 -1
- package/driver/better-sqlite3/BetterSqlite3Driver.d.ts +1 -1
- package/driver/better-sqlite3/BetterSqlite3Driver.js +6 -5
- package/driver/better-sqlite3/BetterSqlite3Driver.js.map +1 -1
- package/driver/sap/SapQueryRunner.d.ts +7 -0
- package/driver/sap/SapQueryRunner.js +24 -2
- package/driver/sap/SapQueryRunner.js.map +1 -1
- package/entity-manager/EntityManager.d.ts +9 -8
- package/entity-manager/EntityManager.js.map +1 -1
- package/entity-manager/MongoEntityManager.d.ts +1 -1
- package/entity-manager/MongoEntityManager.js.map +1 -1
- package/globals.d.ts +5 -4
- package/globals.js.map +1 -1
- package/package.json +274 -1
- package/query-builder/RelationIdLoader.d.ts +1 -1
- package/query-builder/RelationIdLoader.js.map +1 -1
- package/query-builder/SoftDeleteQueryBuilder.d.ts +2 -2
- package/query-builder/SoftDeleteQueryBuilder.js.map +1 -1
- package/query-builder/UpdateQueryBuilder.d.ts +1 -1
- package/query-builder/UpdateQueryBuilder.js.map +1 -1
- package/query-builder/transformer/DocumentToEntityTransformer.js +1 -1
- package/query-builder/transformer/DocumentToEntityTransformer.js.map +1 -1
- package/query-builder/transformer/PlainObjectToNewEntityTransformer.d.ts +1 -1
- package/query-builder/transformer/PlainObjectToNewEntityTransformer.js.map +1 -1
- package/query-builder/transformer/RawSqlResultsToEntityTransformer.js +2 -1
- package/query-builder/transformer/RawSqlResultsToEntityTransformer.js.map +1 -1
- package/repository/AbstractRepository.d.ts +3 -3
- package/repository/AbstractRepository.js.map +1 -1
- package/repository/TreeRepository.d.ts +2 -1
- package/repository/TreeRepository.js.map +1 -1
|
@@ -48,5 +48,5 @@ export declare class DbQueryResultCache implements QueryResultCache {
|
|
|
48
48
|
/**
|
|
49
49
|
* Gets a query runner to work with.
|
|
50
50
|
*/
|
|
51
|
-
protected getQueryRunner(queryRunner
|
|
51
|
+
protected getQueryRunner(queryRunner?: QueryRunner): QueryRunner;
|
|
52
52
|
}
|
|
@@ -226,8 +226,9 @@ export class DbQueryResultCache {
|
|
|
226
226
|
* Removes all cached results by given identifiers from cache.
|
|
227
227
|
*/
|
|
228
228
|
async remove(identifiers, queryRunner) {
|
|
229
|
+
let _queryRunner = queryRunner || this.getQueryRunner();
|
|
229
230
|
await Promise.all(identifiers.map((identifier) => {
|
|
230
|
-
const qb =
|
|
231
|
+
const qb = _queryRunner.manager.createQueryBuilder();
|
|
231
232
|
return qb
|
|
232
233
|
.delete()
|
|
233
234
|
.from(this.queryResultCacheTable)
|
|
@@ -236,6 +237,9 @@ export class DbQueryResultCache {
|
|
|
236
237
|
})
|
|
237
238
|
.execute();
|
|
238
239
|
}));
|
|
240
|
+
if (!queryRunner) {
|
|
241
|
+
await _queryRunner.release();
|
|
242
|
+
}
|
|
239
243
|
}
|
|
240
244
|
// -------------------------------------------------------------------------
|
|
241
245
|
// Protected Methods
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../browser/src/cache/DbQueryResultCache.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,cAAc,EAAE,MAAM,oCAAoC,CAAA;AAEnE,OAAO,EAAE,KAAK,EAAE,MAAM,+BAA+B,CAAA;AAGrD,OAAO,EAAE,EAAE,IAAI,MAAM,EAAE,MAAM,MAAM,CAAA;AAEnC;;GAEG;AACH,MAAM,OAAO,kBAAkB;IAW3B,4EAA4E;IAC5E,cAAc;IACd,4EAA4E;IAE5E,YAAsB,UAAsB;QAAtB,eAAU,GAAV,UAAU,CAAY;QACxC,MAAM,EAAE,MAAM,EAAE,GAAG,IAAI,CAAC,UAAU,CAAC,MAAM,CAAC,OAAc,CAAA;QACxD,MAAM,QAAQ,GAAG,IAAI,CAAC,UAAU,CAAC,MAAM,CAAC,QAAQ,CAAA;QAChD,MAAM,YAAY,GACd,OAAO,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC,KAAK,KAAK,QAAQ;YAC7C,CAAC,CAAC,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC,KAAK;YAC/B,CAAC,CAAC,EAAE,CAAA;QACZ,MAAM,cAAc,GAAG,YAAY,CAAC,SAAS,IAAI,oBAAoB,CAAA;QAErE,IAAI,CAAC,wBAAwB,GAAG,QAAQ,CAAA;QACxC,IAAI,CAAC,sBAAsB,GAAG,MAAM,CAAA;QACpC,IAAI,CAAC,qBAAqB,GAAG,IAAI,CAAC,UAAU,CAAC,MAAM,CAAC,cAAc,CAC9D,cAAc,EACd,MAA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uB,EAAE;YACzB,MAAM,WAAW,CAAC,OAAO,EAAE,CAAA;SAC9B;IACL,CAAC;IAED;;OAEG;IACH,KAAK,CAAC,KAAK,CAAC,WAAwB;QAChC,OAAO,IAAI,CAAC,cAAc,CAAC,WAAW,CAAC,CAAC,UAAU,CAC9C,IAAI,CAAC,qBAAqB,CAC7B,CAAA;IACL,CAAC;IAED;;OAEG;IACH,KAAK,CAAC,MAAM,CACR,WAAqB,EACrB,WAAyB;QAEzB,MAAM,OAAO,CAAC,GAAG,CACb,WAAW,CAAC,GAAG,CAAC,CAAC,UAAU,EAAE,EAAE;YAC3B,MAAM,EAAE,GACJ,IAAI,CAAC,cAAc,CACf,WAAW,CACd,CAAC,OAAO,CAAC,kBAAkB,EAAE,CAAA;YAClC,OAAO,EAAE;iBACJ,MAAM,EAAE;iBACR,IAAI,CAAC,IAAI,CAAC,qBAAqB,CAAC;iBAChC,KAAK,CAAC,GAAG,EAAE,CAAC,MAAM,CAAC,YAAY,CAAC,gBAAgB,EAAE;gBAC/C,UAAU;aACb,CAAC;iBACD,OAAO,EAAE,CAAA;QAClB,CAAC,CAAC,CACL,CAAA;IACL,CAAC;IAED,4EAA4E;IAC5E,oBAAoB;IACpB,4EAA4E;IAE5E;;OAEG;IACO,cAAc,CACpB,WAAoC;QAEpC,IAAI,WAAW;YAAE,OAAO,WAAW,CAAA;QAEnC,OAAO,IAAI,CAAC,UAAU,CAAC,iBAAiB,EAAE,CAAA;IAC9C,CAAC;CACJ","file":"DbQueryResultCache.js","sourcesContent":["import { ObjectLiteral } from \"../common/ObjectLiteral\"\nimport { DataSource } from \"../data-source/DataSource\"\nimport { MssqlParameter } from \"../driver/sqlserver/MssqlParameter\"\nimport { QueryRunner } from \"../query-runner/QueryRunner\"\nimport { Table } from \"../schema-builder/table/Table\"\nimport { QueryResultCache } from \"./QueryResultCache\"\nimport { QueryResultCacheOptions } from \"./QueryResultCacheOptions\"\nimport { v4 as uuidv4 } from \"uuid\"\n\n/**\n * Caches query result into current database, into separate table called \"query-result-cache\".\n */\nexport class DbQueryResultCache implements QueryResultCache {\n // -------------------------------------------------------------------------\n // Private properties\n // -------------------------------------------------------------------------\n\n private queryResultCacheTable: string\n\n private queryResultCacheDatabase?: string\n\n private queryResultCacheSchema?: string\n\n // -------------------------------------------------------------------------\n // Constructor\n // -------------------------------------------------------------------------\n\n constructor(protected connection: DataSource) {\n const { schema } = this.connection.driver.options as any\n const database = this.connection.driver.database\n const cacheOptions =\n typeof this.connection.options.cache === \"object\"\n ? this.connection.options.cache\n : {}\n const cacheTableName = cacheOptions.tableName || \"query-result-cache\"\n\n this.queryResultCacheDatabase = database\n this.queryResultCacheSchema = schema\n this.queryResultCacheTable = this.connection.driver.buildTableName(\n cacheTableName,\n schema,\n database,\n )\n }\n\n // -------------------------------------------------------------------------\n // Public Methods\n // -------------------------------------------------------------------------\n\n /**\n * Creates a connection with given cache provider.\n */\n async connect(): Promise<void> {}\n\n /**\n * Disconnects with given cache provider.\n */\n async disconnect(): Promise<void> {}\n\n /**\n * Creates table for storing cache if it does not exist yet.\n */\n async synchronize(queryRunner?: QueryRunner): Promise<void> {\n queryRunner = this.getQueryRunner(queryRunner)\n const driver = this.connection.driver\n const tableExist = await queryRunner.hasTable(\n this.queryResultCacheTable,\n ) // todo: table name should be configurable\n if (tableExist) return\n\n await queryRunner.createTable(\n new Table({\n database: this.queryResultCacheDatabase,\n schema: this.queryResultCacheSchema,\n name: this.queryResultCacheTable,\n columns: [\n {\n name: \"id\",\n isPrimary: true,\n isNullable: false,\n type: driver.normalizeType({\n type: driver.mappedDataTypes.cacheId,\n }),\n generationStrategy:\n driver.options.type === \"spanner\"\n ? \"uuid\"\n : \"increment\",\n isGenerated: true,\n },\n {\n name: \"identifier\",\n type: driver.normalizeType({\n type: driver.mappedDataTypes.cacheIdentifier,\n }),\n isNullable: true,\n },\n {\n name: \"time\",\n type: driver.normalizeType({\n type: driver.mappedDataTypes.cacheTime,\n }),\n isPrimary: false,\n isNullable: false,\n },\n {\n name: \"duration\",\n type: driver.normalizeType({\n type: driver.mappedDataTypes.cacheDuration,\n }),\n isPrimary: false,\n isNullable: false,\n },\n {\n name: \"query\",\n type: driver.normalizeType({\n type: driver.mappedDataTypes.cacheQuery,\n }),\n isPrimary: false,\n isNullable: false,\n },\n {\n name: \"result\",\n type: driver.normalizeType({\n type: driver.mappedDataTypes.cacheResult,\n }),\n isNullable: false,\n },\n ],\n }),\n )\n }\n\n /**\n * Caches given query result.\n * Returns cache result if found.\n * Returns undefined if result is not cached.\n */\n getFromCache(\n options: QueryResultCacheOptions,\n queryRunner?: QueryRunner,\n ): Promise<QueryResultCacheOptions | undefined> {\n queryRunner = this.getQueryRunner(queryRunner)\n const qb = this.connection\n .createQueryBuilder(queryRunner)\n .select()\n .from(this.queryResultCacheTable, \"cache\")\n\n if (options.identifier) {\n return qb\n .where(\n `${qb.escape(\"cache\")}.${qb.escape(\n \"identifier\",\n )} = :identifier`,\n )\n .setParameters({\n identifier:\n this.connection.driver.options.type === \"mssql\"\n ? new MssqlParameter(options.identifier, \"nvarchar\")\n : options.identifier,\n })\n .getRawOne()\n } else if (options.query) {\n if (this.connection.driver.options.type === \"oracle\") {\n return qb\n .where(\n `dbms_lob.compare(${qb.escape(\"cache\")}.${qb.escape(\n \"query\",\n )}, :query) = 0`,\n { query: options.query },\n )\n .getRawOne()\n }\n\n return qb\n .where(`${qb.escape(\"cache\")}.${qb.escape(\"query\")} = :query`)\n .setParameters({\n query:\n this.connection.driver.options.type === \"mssql\"\n ? new MssqlParameter(options.query, \"nvarchar\")\n : options.query,\n })\n .getRawOne()\n }\n\n return Promise.resolve(undefined)\n }\n\n /**\n * Checks if cache is expired or not.\n */\n isExpired(savedCache: QueryResultCacheOptions): boolean {\n const duration =\n typeof savedCache.duration === \"string\"\n ? parseInt(savedCache.duration)\n : savedCache.duration\n return (\n (typeof savedCache.time === \"string\"\n ? parseInt(savedCache.time as any)\n : savedCache.time)! +\n duration <\n new Date().getTime()\n )\n }\n\n /**\n * Stores given query result in the cache.\n */\n async storeInCache(\n options: QueryResultCacheOptions,\n savedCache: QueryResultCacheOptions | undefined,\n queryRunner?: QueryRunner,\n ): Promise<void> {\n const shouldCreateQueryRunner =\n queryRunner === undefined ||\n queryRunner?.getReplicationMode() === \"slave\"\n\n if (queryRunner === undefined || shouldCreateQueryRunner) {\n queryRunner = this.connection.createQueryRunner(\"master\")\n }\n\n let insertedValues: ObjectLiteral = options\n if (this.connection.driver.options.type === \"mssql\") {\n // todo: bad abstraction, re-implement this part, probably better if we create an entity metadata for cache table\n insertedValues = {\n identifier: new MssqlParameter(options.identifier, \"nvarchar\"),\n time: new MssqlParameter(options.time, \"bigint\"),\n duration: new MssqlParameter(options.duration, \"int\"),\n query: new MssqlParameter(options.query, \"nvarchar\"),\n result: new MssqlParameter(options.result, \"nvarchar\"),\n }\n }\n\n if (savedCache && savedCache.identifier) {\n // if exist then update\n const qb = queryRunner.manager\n .createQueryBuilder()\n .update(this.queryResultCacheTable)\n .set(insertedValues)\n\n qb.where(`${qb.escape(\"identifier\")} = :condition`, {\n condition: insertedValues.identifier,\n })\n await qb.execute()\n } else if (savedCache && savedCache.query) {\n // if exist then update\n const qb = queryRunner.manager\n .createQueryBuilder()\n .update(this.queryResultCacheTable)\n .set(insertedValues)\n\n if (this.connection.driver.options.type === \"oracle\") {\n qb.where(`dbms_lob.compare(\"query\", :condition) = 0`, {\n condition: insertedValues.query,\n })\n } else {\n qb.where(`${qb.escape(\"query\")} = :condition`, {\n condition: insertedValues.query,\n })\n }\n\n await qb.execute()\n } else {\n // Spanner does not support auto-generated columns\n if (\n this.connection.driver.options.type === \"spanner\" &&\n !insertedValues.id\n ) {\n insertedValues.id = uuidv4()\n }\n\n // otherwise insert\n await queryRunner.manager\n .createQueryBuilder()\n .insert()\n .into(this.queryResultCacheTable)\n .values(insertedValues)\n .execute()\n }\n\n if (shouldCreateQueryRunner) {\n await queryRunner.release()\n }\n }\n\n /**\n * Clears everything stored in the cache.\n */\n async clear(queryRunner: QueryRunner): Promise<void> {\n return this.getQueryRunner(queryRunner).clearTable(\n this.queryResultCacheTable,\n )\n }\n\n /**\n * Removes all cached results by given identifiers from cache.\n */\n async remove(\n identifiers: string[],\n queryRunner?: QueryRunner,\n ): Promise<void> {\n await Promise.all(\n identifiers.map((identifier) => {\n const qb =\n this.getQueryRunner(\n queryRunner,\n ).manager.createQueryBuilder()\n return qb\n .delete()\n .from(this.queryResultCacheTable)\n .where(`${qb.escape(\"identifier\")} = :identifier`, {\n identifier,\n })\n .execute()\n }),\n )\n }\n\n // -------------------------------------------------------------------------\n // Protected Methods\n // -------------------------------------------------------------------------\n\n /**\n * Gets a query runner to work with.\n */\n protected getQueryRunner(\n queryRunner: QueryRunner | undefined,\n ): QueryRunner {\n if (queryRunner) return queryRunner\n\n return this.connection.createQueryRunner()\n }\n}\n"],"sourceRoot":".."}
|
|
1
|
+
{"version":3,"sources":["../browser/src/cache/DbQueryResultCache.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,cAAc,EAAE,MAAM,oCAAoC,CAAA;AAEnE,OAAO,EAAE,KAAK,EAAE,MAAM,+BAA+B,CAAA;AAGrD,OAAO,EAAE,EAAE,IAAI,MAAM,EAAE,MAAM,MAAM,CAAA;AAEnC;;GAEG;AACH,MAAM,OAAO,kBAAkB;IAW3B,4EAA4E;IAC5E,cAAc;IACd,4EAA4E;IAE5E,YAAsB,UAAsB;QAAtB,eAAU,GAAV,UAAU,CAAY;QACxC,MAAM,EAAE,MAAM,EAAE,GAAG,IAAI,CAAC,UAAU,CAAC,MAAM,CAAC,OAAc,CAAA;QACxD,MAAM,QAAQ,GAAG,IAAI,CAAC,UAAU,CAAC,MAAM,CAAC,QAAQ,CAAA;QAChD,MAAM,YAAY,GACd,OAAO,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC,KAAK,KAAK,QAAQ;YAC7C,CAAC,CAAC,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC,KAAK;YAC/B,CAAC,CAAC,EAA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AAI,CAAC,UAAU,CAAC,iBAAiB,EAAE,CAAA;IAC9C,CAAC;CACJ","file":"DbQueryResultCache.js","sourcesContent":["import { ObjectLiteral } from \"../common/ObjectLiteral\"\nimport { DataSource } from \"../data-source/DataSource\"\nimport { MssqlParameter } from \"../driver/sqlserver/MssqlParameter\"\nimport { QueryRunner } from \"../query-runner/QueryRunner\"\nimport { Table } from \"../schema-builder/table/Table\"\nimport { QueryResultCache } from \"./QueryResultCache\"\nimport { QueryResultCacheOptions } from \"./QueryResultCacheOptions\"\nimport { v4 as uuidv4 } from \"uuid\"\n\n/**\n * Caches query result into current database, into separate table called \"query-result-cache\".\n */\nexport class DbQueryResultCache implements QueryResultCache {\n // -------------------------------------------------------------------------\n // Private properties\n // -------------------------------------------------------------------------\n\n private queryResultCacheTable: string\n\n private queryResultCacheDatabase?: string\n\n private queryResultCacheSchema?: string\n\n // -------------------------------------------------------------------------\n // Constructor\n // -------------------------------------------------------------------------\n\n constructor(protected connection: DataSource) {\n const { schema } = this.connection.driver.options as any\n const database = this.connection.driver.database\n const cacheOptions =\n typeof this.connection.options.cache === \"object\"\n ? this.connection.options.cache\n : {}\n const cacheTableName = cacheOptions.tableName || \"query-result-cache\"\n\n this.queryResultCacheDatabase = database\n this.queryResultCacheSchema = schema\n this.queryResultCacheTable = this.connection.driver.buildTableName(\n cacheTableName,\n schema,\n database,\n )\n }\n\n // -------------------------------------------------------------------------\n // Public Methods\n // -------------------------------------------------------------------------\n\n /**\n * Creates a connection with given cache provider.\n */\n async connect(): Promise<void> {}\n\n /**\n * Disconnects with given cache provider.\n */\n async disconnect(): Promise<void> {}\n\n /**\n * Creates table for storing cache if it does not exist yet.\n */\n async synchronize(queryRunner?: QueryRunner): Promise<void> {\n queryRunner = this.getQueryRunner(queryRunner)\n const driver = this.connection.driver\n const tableExist = await queryRunner.hasTable(\n this.queryResultCacheTable,\n ) // todo: table name should be configurable\n if (tableExist) return\n\n await queryRunner.createTable(\n new Table({\n database: this.queryResultCacheDatabase,\n schema: this.queryResultCacheSchema,\n name: this.queryResultCacheTable,\n columns: [\n {\n name: \"id\",\n isPrimary: true,\n isNullable: false,\n type: driver.normalizeType({\n type: driver.mappedDataTypes.cacheId,\n }),\n generationStrategy:\n driver.options.type === \"spanner\"\n ? \"uuid\"\n : \"increment\",\n isGenerated: true,\n },\n {\n name: \"identifier\",\n type: driver.normalizeType({\n type: driver.mappedDataTypes.cacheIdentifier,\n }),\n isNullable: true,\n },\n {\n name: \"time\",\n type: driver.normalizeType({\n type: driver.mappedDataTypes.cacheTime,\n }),\n isPrimary: false,\n isNullable: false,\n },\n {\n name: \"duration\",\n type: driver.normalizeType({\n type: driver.mappedDataTypes.cacheDuration,\n }),\n isPrimary: false,\n isNullable: false,\n },\n {\n name: \"query\",\n type: driver.normalizeType({\n type: driver.mappedDataTypes.cacheQuery,\n }),\n isPrimary: false,\n isNullable: false,\n },\n {\n name: \"result\",\n type: driver.normalizeType({\n type: driver.mappedDataTypes.cacheResult,\n }),\n isNullable: false,\n },\n ],\n }),\n )\n }\n\n /**\n * Caches given query result.\n * Returns cache result if found.\n * Returns undefined if result is not cached.\n */\n getFromCache(\n options: QueryResultCacheOptions,\n queryRunner?: QueryRunner,\n ): Promise<QueryResultCacheOptions | undefined> {\n queryRunner = this.getQueryRunner(queryRunner)\n const qb = this.connection\n .createQueryBuilder(queryRunner)\n .select()\n .from(this.queryResultCacheTable, \"cache\")\n\n if (options.identifier) {\n return qb\n .where(\n `${qb.escape(\"cache\")}.${qb.escape(\n \"identifier\",\n )} = :identifier`,\n )\n .setParameters({\n identifier:\n this.connection.driver.options.type === \"mssql\"\n ? new MssqlParameter(options.identifier, \"nvarchar\")\n : options.identifier,\n })\n .getRawOne()\n } else if (options.query) {\n if (this.connection.driver.options.type === \"oracle\") {\n return qb\n .where(\n `dbms_lob.compare(${qb.escape(\"cache\")}.${qb.escape(\n \"query\",\n )}, :query) = 0`,\n { query: options.query },\n )\n .getRawOne()\n }\n\n return qb\n .where(`${qb.escape(\"cache\")}.${qb.escape(\"query\")} = :query`)\n .setParameters({\n query:\n this.connection.driver.options.type === \"mssql\"\n ? new MssqlParameter(options.query, \"nvarchar\")\n : options.query,\n })\n .getRawOne()\n }\n\n return Promise.resolve(undefined)\n }\n\n /**\n * Checks if cache is expired or not.\n */\n isExpired(savedCache: QueryResultCacheOptions): boolean {\n const duration =\n typeof savedCache.duration === \"string\"\n ? parseInt(savedCache.duration)\n : savedCache.duration\n return (\n (typeof savedCache.time === \"string\"\n ? parseInt(savedCache.time as any)\n : savedCache.time)! +\n duration <\n new Date().getTime()\n )\n }\n\n /**\n * Stores given query result in the cache.\n */\n async storeInCache(\n options: QueryResultCacheOptions,\n savedCache: QueryResultCacheOptions | undefined,\n queryRunner?: QueryRunner,\n ): Promise<void> {\n const shouldCreateQueryRunner =\n queryRunner === undefined ||\n queryRunner?.getReplicationMode() === \"slave\"\n\n if (queryRunner === undefined || shouldCreateQueryRunner) {\n queryRunner = this.connection.createQueryRunner(\"master\")\n }\n\n let insertedValues: ObjectLiteral = options\n if (this.connection.driver.options.type === \"mssql\") {\n // todo: bad abstraction, re-implement this part, probably better if we create an entity metadata for cache table\n insertedValues = {\n identifier: new MssqlParameter(options.identifier, \"nvarchar\"),\n time: new MssqlParameter(options.time, \"bigint\"),\n duration: new MssqlParameter(options.duration, \"int\"),\n query: new MssqlParameter(options.query, \"nvarchar\"),\n result: new MssqlParameter(options.result, \"nvarchar\"),\n }\n }\n\n if (savedCache && savedCache.identifier) {\n // if exist then update\n const qb = queryRunner.manager\n .createQueryBuilder()\n .update(this.queryResultCacheTable)\n .set(insertedValues)\n\n qb.where(`${qb.escape(\"identifier\")} = :condition`, {\n condition: insertedValues.identifier,\n })\n await qb.execute()\n } else if (savedCache && savedCache.query) {\n // if exist then update\n const qb = queryRunner.manager\n .createQueryBuilder()\n .update(this.queryResultCacheTable)\n .set(insertedValues)\n\n if (this.connection.driver.options.type === \"oracle\") {\n qb.where(`dbms_lob.compare(\"query\", :condition) = 0`, {\n condition: insertedValues.query,\n })\n } else {\n qb.where(`${qb.escape(\"query\")} = :condition`, {\n condition: insertedValues.query,\n })\n }\n\n await qb.execute()\n } else {\n // Spanner does not support auto-generated columns\n if (\n this.connection.driver.options.type === \"spanner\" &&\n !insertedValues.id\n ) {\n insertedValues.id = uuidv4()\n }\n\n // otherwise insert\n await queryRunner.manager\n .createQueryBuilder()\n .insert()\n .into(this.queryResultCacheTable)\n .values(insertedValues)\n .execute()\n }\n\n if (shouldCreateQueryRunner) {\n await queryRunner.release()\n }\n }\n\n /**\n * Clears everything stored in the cache.\n */\n async clear(queryRunner: QueryRunner): Promise<void> {\n return this.getQueryRunner(queryRunner).clearTable(\n this.queryResultCacheTable,\n )\n }\n\n /**\n * Removes all cached results by given identifiers from cache.\n */\n async remove(\n identifiers: string[],\n queryRunner?: QueryRunner,\n ): Promise<void> {\n let _queryRunner: QueryRunner = queryRunner || this.getQueryRunner()\n await Promise.all(\n identifiers.map((identifier) => {\n const qb = _queryRunner.manager.createQueryBuilder()\n return qb\n .delete()\n .from(this.queryResultCacheTable)\n .where(`${qb.escape(\"identifier\")} = :identifier`, {\n identifier,\n })\n .execute()\n }),\n )\n\n if (!queryRunner) {\n await _queryRunner.release()\n }\n }\n\n // -------------------------------------------------------------------------\n // Protected Methods\n // -------------------------------------------------------------------------\n\n /**\n * Gets a query runner to work with.\n */\n protected getQueryRunner(queryRunner?: QueryRunner): QueryRunner {\n if (queryRunner) return queryRunner\n\n return this.connection.createQueryRunner()\n }\n}\n"],"sourceRoot":".."}
|
|
File without changes
|
|
File without changes
|
|
@@ -21,6 +21,7 @@ import { RelationLoader } from "../query-builder/RelationLoader";
|
|
|
21
21
|
import { IsolationLevel } from "../driver/types/IsolationLevel";
|
|
22
22
|
import { ReplicationMode } from "../driver/types/ReplicationMode";
|
|
23
23
|
import { RelationIdLoader } from "../query-builder/RelationIdLoader";
|
|
24
|
+
import { ObjectLiteral } from "../common/ObjectLiteral";
|
|
24
25
|
/**
|
|
25
26
|
* DataSource is a pre-defined connection configuration to a specific database.
|
|
26
27
|
* You can have multiple data sources connected (with multiple connections in it),
|
|
@@ -181,17 +182,17 @@ export declare class DataSource {
|
|
|
181
182
|
/**
|
|
182
183
|
* Gets repository for the given entity.
|
|
183
184
|
*/
|
|
184
|
-
getRepository<Entity>(target: EntityTarget<Entity>): Repository<Entity>;
|
|
185
|
+
getRepository<Entity extends ObjectLiteral>(target: EntityTarget<Entity>): Repository<Entity>;
|
|
185
186
|
/**
|
|
186
187
|
* Gets tree repository for the given entity class or name.
|
|
187
188
|
* Only tree-type entities can have a TreeRepository, like ones decorated with @Tree decorator.
|
|
188
189
|
*/
|
|
189
|
-
getTreeRepository<Entity>(target: EntityTarget<Entity>): TreeRepository<Entity>;
|
|
190
|
+
getTreeRepository<Entity extends ObjectLiteral>(target: EntityTarget<Entity>): TreeRepository<Entity>;
|
|
190
191
|
/**
|
|
191
192
|
* Gets mongodb-specific repository for the given entity class or name.
|
|
192
193
|
* Works only if connection is mongodb-specific.
|
|
193
194
|
*/
|
|
194
|
-
getMongoRepository<Entity>(target: EntityTarget<Entity>): MongoRepository<Entity>;
|
|
195
|
+
getMongoRepository<Entity extends ObjectLiteral>(target: EntityTarget<Entity>): MongoRepository<Entity>;
|
|
195
196
|
/**
|
|
196
197
|
* Gets custom entity repository marked with @EntityRepository decorator.
|
|
197
198
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../browser/src/data-source/DataSource.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,qBAAqB,EAAE,MAAM,0CAA0C,CAAA;AAChF,OAAO,EACH,kCAAkC,EAClC,8BAA8B,EAC9B,2BAA2B,EAC3B,uCAAuC,GAC1C,MAAM,UAAU,CAAA;AAMjB,OAAO,EAAE,iBAAiB,EAAE,MAAM,gCAAgC,CAAA;AAIlE,OAAO,EAAE,uBAAuB,EAAE,MAAM,6CAA6C,CAAA;AAErF,OAAO,EAAE,oBAAoB,EAAE,MAAM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AAM,UAAU,GAAG,MAAM,yBAAyB,CAAC,eAAe,CAC9D,mBAAmB,CACtB,CAAA;QACD,WAAW,CAAC,MAAM,CAAC,IAAI,EAAE,EAAE,UAAU,EAAE,UAAU,EAAE,CAAC,CAAA;QAEpD,iGAAiG;QACjG,uBAAuB,CAAC,YAAY,CAChC,IAAI,CAAC,eAAe,CAAC,MAAM,CACvB,CAAC,QAAQ,EAAE,EAAE,CAAC,QAAQ,CAAC,SAAS,KAAK,MAAM,CAC9C,EACD,IAAI,CAAC,MAAM,CACd,CAAA;QAED,0CAA0C;QAC1C,KAAK,IAAI,cAAc,IAAI,eAAe,EAAE;YACxC,IACI,eAAe,CAAC,uBAAuB,CAAC,cAAc,CAAC,MAAM,CAAC,EAChE;gBACE,cAAc,CAAC,MAAM,CAAC,aAAa,CAAC,IAAI,CAAC,CAAA;aAC5C;SACJ;IACL,CAAC;CACJ","file":"DataSource.js","sourcesContent":["import { Driver } from \"../driver/Driver\"\nimport { Repository } from \"../repository/Repository\"\nimport { EntitySubscriberInterface } from \"../subscriber/EntitySubscriberInterface\"\nimport { EntityTarget } from \"../common/EntityTarget\"\nimport { ObjectType } from \"../common/ObjectType\"\nimport { EntityManager } from \"../entity-manager/EntityManager\"\nimport { DefaultNamingStrategy } from \"../naming-strategy/DefaultNamingStrategy\"\nimport {\n CannotConnectAlreadyConnectedError,\n CannotExecuteNotConnectedError,\n EntityMetadataNotFoundError,\n QueryRunnerProviderAlreadyReleasedError,\n} from \"../error\"\nimport { TreeRepository } from \"../repository/TreeRepository\"\nimport { NamingStrategyInterface } from \"../naming-strategy/NamingStrategyInterface\"\nimport { EntityMetadata } from \"../metadata/EntityMetadata\"\nimport { Logger } from \"../logger/Logger\"\nimport { MigrationInterface } from \"../migration/MigrationInterface\"\nimport { MigrationExecutor } from \"../migration/MigrationExecutor\"\nimport { Migration } from \"../migration/Migration\"\nimport { MongoRepository } from \"../repository/MongoRepository\"\nimport { MongoEntityManager } from \"../entity-manager/MongoEntityManager\"\nimport { EntityMetadataValidator } from \"../metadata-builder/EntityMetadataValidator\"\nimport { DataSourceOptions } from \"./DataSourceOptions\"\nimport { EntityManagerFactory } from \"../entity-manager/EntityManagerFactory\"\nimport { DriverFactory } from \"../driver/DriverFactory\"\nimport { ConnectionMetadataBuilder } from \"../connection/ConnectionMetadataBuilder\"\nimport { QueryRunner } from \"../query-runner/QueryRunner\"\nimport { SelectQueryBuilder } from \"../query-builder/SelectQueryBuilder\"\nimport { LoggerFactory } from \"../logger/LoggerFactory\"\nimport { QueryResultCacheFactory } from \"../cache/QueryResultCacheFactory\"\nimport { QueryResultCache } from \"../cache/QueryResultCache\"\nimport { SqljsEntityManager } from \"../entity-manager/SqljsEntityManager\"\nimport { RelationLoader } from \"../query-builder/RelationLoader\"\nimport { ObjectUtils } from \"../util/ObjectUtils\"\nimport { IsolationLevel } from \"../driver/types/IsolationLevel\"\nimport { ReplicationMode } from \"../driver/types/ReplicationMode\"\nimport { TypeORMError } from \"../error\"\nimport { RelationIdLoader } from \"../query-builder/RelationIdLoader\"\nimport { DriverUtils } from \"../driver/DriverUtils\"\nimport { InstanceChecker } from \"../util/InstanceChecker\"\n\n/**\n * DataSource is a pre-defined connection configuration to a specific database.\n * You can have multiple data sources connected (with multiple connections in it),\n * connected to multiple databases in your application.\n *\n * Before, it was called `Connection`, but now `Connection` is deprecated\n * because `Connection` isn't the best name for what it's actually is.\n */\nexport class DataSource {\n readonly \"@instanceof\" = Symbol.for(\"DataSource\")\n\n // -------------------------------------------------------------------------\n // Public Readonly Properties\n // -------------------------------------------------------------------------\n\n /**\n * Connection name.\n *\n * @deprecated we don't need names anymore since we are going to drop all related methods relying on this property.\n */\n readonly name: string\n\n /**\n * Connection options.\n */\n readonly options: DataSourceOptions\n\n /**\n * Indicates if DataSource is initialized or not.\n */\n readonly isInitialized: boolean\n\n /**\n * Database driver used by this connection.\n */\n driver: Driver\n\n /**\n * EntityManager of this connection.\n */\n readonly manager: EntityManager\n\n /**\n * Naming strategy used in the connection.\n */\n namingStrategy: NamingStrategyInterface\n\n /**\n * Name for the metadata table\n */\n readonly metadataTableName: string\n\n /**\n * Logger used to log orm events.\n */\n logger: Logger\n\n /**\n * Migration instances that are registered for this connection.\n */\n readonly migrations: MigrationInterface[] = []\n\n /**\n * Entity subscriber instances that are registered for this connection.\n */\n readonly subscribers: EntitySubscriberInterface<any>[] = []\n\n /**\n * All entity metadatas that are registered for this connection.\n */\n readonly entityMetadatas: EntityMetadata[] = []\n\n /**\n * Used to work with query result cache.\n */\n queryResultCache?: QueryResultCache\n\n /**\n * Used to load relations and work with lazy relations.\n */\n readonly relationLoader: RelationLoader\n\n readonly relationIdLoader: RelationIdLoader\n\n // -------------------------------------------------------------------------\n // Constructor\n // -------------------------------------------------------------------------\n\n constructor(options: DataSourceOptions) {\n this.name = options.name || \"default\"\n this.options = options\n this.logger = new LoggerFactory().create(\n this.options.logger,\n this.options.logging,\n )\n this.driver = new DriverFactory().create(this)\n this.manager = this.createEntityManager()\n this.namingStrategy =\n options.namingStrategy || new DefaultNamingStrategy()\n this.metadataTableName = options.metadataTableName || \"typeorm_metadata\"\n this.queryResultCache = options.cache\n ? new QueryResultCacheFactory(this).create()\n : undefined\n this.relationLoader = new RelationLoader(this)\n this.relationIdLoader = new RelationIdLoader(this)\n this.isInitialized = false\n }\n\n // -------------------------------------------------------------------------\n // Public Accessors\n // -------------------------------------------------------------------------\n\n /**\n Indicates if DataSource is initialized or not.\n *\n * @deprecated use .isInitialized instead\n */\n get isConnected() {\n return this.isInitialized\n }\n\n /**\n * Gets the mongodb entity manager that allows to perform mongodb-specific repository operations\n * with any entity in this connection.\n *\n * Available only in mongodb connections.\n */\n get mongoManager(): MongoEntityManager {\n if (!InstanceChecker.isMongoEntityManager(this.manager))\n throw new TypeORMError(\n `MongoEntityManager is only available for MongoDB databases.`,\n )\n\n return this.manager as MongoEntityManager\n }\n\n /**\n * Gets a sql.js specific Entity Manager that allows to perform special load and save operations\n *\n * Available only in connection with the sqljs driver.\n */\n get sqljsManager(): SqljsEntityManager {\n if (!InstanceChecker.isSqljsEntityManager(this.manager))\n throw new TypeORMError(\n `SqljsEntityManager is only available for Sqljs databases.`,\n )\n\n return this.manager\n }\n\n // -------------------------------------------------------------------------\n // Public Methods\n // -------------------------------------------------------------------------\n /**\n * Updates current connection options with provided options.\n */\n setOptions(options: Partial<DataSourceOptions>): this {\n Object.assign(this.options, options)\n\n if (options.logger || options.logging) {\n this.logger = new LoggerFactory().create(\n options.logger || this.options.logger,\n options.logging || this.options.logging,\n )\n }\n\n if (options.namingStrategy) {\n this.namingStrategy = options.namingStrategy\n }\n\n if (options.cache) {\n this.queryResultCache = new QueryResultCacheFactory(this).create()\n }\n\n return this\n }\n\n /**\n * Performs connection to the database.\n * This method should be called once on application bootstrap.\n * This method not necessarily creates database connection (depend on database type),\n * but it also can setup a connection pool with database to use.\n */\n async initialize(): Promise<this> {\n if (this.isInitialized)\n throw new CannotConnectAlreadyConnectedError(this.name)\n\n // connect to the database via its driver\n await this.driver.connect()\n\n // connect to the cache-specific database if cache is enabled\n if (this.queryResultCache) await this.queryResultCache.connect()\n\n // set connected status for the current connection\n ObjectUtils.assign(this, { isInitialized: true })\n\n try {\n // build all metadatas registered in the current connection\n await this.buildMetadatas()\n\n await this.driver.afterConnect()\n\n // if option is set - drop schema once connection is done\n if (this.options.dropSchema) await this.dropDatabase()\n\n // if option is set - automatically synchronize a schema\n if (this.options.migrationsRun)\n await this.runMigrations({\n transaction: this.options.migrationsTransactionMode,\n })\n\n // if option is set - automatically synchronize a schema\n if (this.options.synchronize) await this.synchronize()\n } catch (error) {\n // if for some reason build metadata fail (for example validation error during entity metadata check)\n // connection needs to be closed\n await this.close()\n throw error\n }\n\n return this\n }\n\n /**\n * Performs connection to the database.\n * This method should be called once on application bootstrap.\n * This method not necessarily creates database connection (depend on database type),\n * but it also can setup a connection pool with database to use.\n *\n * @deprecated use .initialize method instead\n */\n async connect(): Promise<this> {\n return this.initialize()\n }\n\n /**\n * Closes connection with the database.\n * Once connection is closed, you cannot use repositories or perform any operations except opening connection again.\n */\n async destroy(): Promise<void> {\n if (!this.isInitialized)\n throw new CannotExecuteNotConnectedError(this.name)\n\n await this.driver.disconnect()\n\n // disconnect from the cache-specific database if cache was enabled\n if (this.queryResultCache) await this.queryResultCache.disconnect()\n\n ObjectUtils.assign(this, { isInitialized: false })\n }\n\n /**\n * Closes connection with the database.\n * Once connection is closed, you cannot use repositories or perform any operations except opening connection again.\n *\n * @deprecated use .destroy method instead\n */\n async close(): Promise<void> {\n return this.destroy()\n }\n\n /**\n * Creates database schema for all entities registered in this connection.\n * Can be used only after connection to the database is established.\n *\n * @param dropBeforeSync If set to true then it drops the database with all its tables and data\n */\n async synchronize(dropBeforeSync: boolean = false): Promise<void> {\n if (!this.isInitialized)\n throw new CannotExecuteNotConnectedError(this.name)\n\n if (dropBeforeSync) await this.dropDatabase()\n\n const schemaBuilder = this.driver.createSchemaBuilder()\n await schemaBuilder.build()\n }\n\n /**\n * Drops the database and all its data.\n * Be careful with this method on production since this method will erase all your database tables and their data.\n * Can be used only after connection to the database is established.\n */\n // TODO rename\n async dropDatabase(): Promise<void> {\n const queryRunner = this.createQueryRunner()\n try {\n if (\n this.driver.options.type === \"mssql\" ||\n DriverUtils.isMySQLFamily(this.driver) ||\n this.driver.options.type === \"aurora-mysql\" ||\n DriverUtils.isSQLiteFamily(this.driver)\n ) {\n const databases: string[] = []\n this.entityMetadatas.forEach((metadata) => {\n if (\n metadata.database &&\n databases.indexOf(metadata.database) === -1\n )\n databases.push(metadata.database)\n })\n if (databases.length === 0 && this.driver.database) {\n databases.push(this.driver.database)\n }\n\n if (databases.length === 0) {\n await queryRunner.clearDatabase()\n } else {\n for (const database of databases) {\n await queryRunner.clearDatabase(database)\n }\n }\n } else {\n await queryRunner.clearDatabase()\n }\n } finally {\n await queryRunner.release()\n }\n }\n\n /**\n * Runs all pending migrations.\n * Can be used only after connection to the database is established.\n */\n async runMigrations(options?: {\n transaction?: \"all\" | \"none\" | \"each\"\n }): Promise<Migration[]> {\n if (!this.isInitialized)\n throw new CannotExecuteNotConnectedError(this.name)\n\n const migrationExecutor = new MigrationExecutor(this)\n migrationExecutor.transaction =\n (options && options.transaction) || \"all\"\n\n const successMigrations =\n await migrationExecutor.executePendingMigrations()\n return successMigrations\n }\n\n /**\n * Reverts last executed migration.\n * Can be used only after connection to the database is established.\n */\n async undoLastMigration(options?: {\n transaction?: \"all\" | \"none\" | \"each\"\n }): Promise<void> {\n if (!this.isInitialized)\n throw new CannotExecuteNotConnectedError(this.name)\n\n const migrationExecutor = new MigrationExecutor(this)\n migrationExecutor.transaction =\n (options && options.transaction) || \"all\"\n\n await migrationExecutor.undoLastMigration()\n }\n\n /**\n * Lists all migrations and whether they have been run.\n * Returns true if there are pending migrations\n */\n async showMigrations(): Promise<boolean> {\n if (!this.isInitialized) {\n throw new CannotExecuteNotConnectedError(this.name)\n }\n const migrationExecutor = new MigrationExecutor(this)\n return await migrationExecutor.showMigrations()\n }\n\n /**\n * Checks if entity metadata exist for the given entity class, target name or table name.\n */\n hasMetadata(target: EntityTarget<any>): boolean {\n return !!this.findMetadata(target)\n }\n\n /**\n * Gets entity metadata for the given entity class or schema name.\n */\n getMetadata(target: EntityTarget<any>): EntityMetadata {\n const metadata = this.findMetadata(target)\n if (!metadata) throw new EntityMetadataNotFoundError(target)\n\n return metadata\n }\n\n /**\n * Gets repository for the given entity.\n */\n getRepository<Entity>(target: EntityTarget<Entity>): Repository<Entity> {\n return this.manager.getRepository(target)\n }\n\n /**\n * Gets tree repository for the given entity class or name.\n * Only tree-type entities can have a TreeRepository, like ones decorated with @Tree decorator.\n */\n getTreeRepository<Entity>(\n target: EntityTarget<Entity>,\n ): TreeRepository<Entity> {\n return this.manager.getTreeRepository(target)\n }\n\n /**\n * Gets mongodb-specific repository for the given entity class or name.\n * Works only if connection is mongodb-specific.\n */\n getMongoRepository<Entity>(\n target: EntityTarget<Entity>,\n ): MongoRepository<Entity> {\n if (!(this.driver.options.type === \"mongodb\"))\n throw new TypeORMError(\n `You can use getMongoRepository only for MongoDB connections.`,\n )\n\n return this.manager.getRepository(target) as any\n }\n\n /**\n * Gets custom entity repository marked with @EntityRepository decorator.\n *\n * @deprecated use Repository.extend function to create a custom repository\n */\n getCustomRepository<T>(customRepository: ObjectType<T>): T {\n return this.manager.getCustomRepository(customRepository)\n }\n\n /**\n * Wraps given function execution (and all operations made there) into a transaction.\n * All database operations must be executed using provided entity manager.\n */\n async transaction<T>(\n runInTransaction: (entityManager: EntityManager) => Promise<T>,\n ): Promise<T>\n async transaction<T>(\n isolationLevel: IsolationLevel,\n runInTransaction: (entityManager: EntityManager) => Promise<T>,\n ): Promise<T>\n async transaction<T>(\n isolationOrRunInTransaction:\n | IsolationLevel\n | ((entityManager: EntityManager) => Promise<T>),\n runInTransactionParam?: (entityManager: EntityManager) => Promise<T>,\n ): Promise<any> {\n return this.manager.transaction(\n isolationOrRunInTransaction as any,\n runInTransactionParam as any,\n )\n }\n\n /**\n * Executes raw SQL query and returns raw database results.\n */\n async query(\n query: string,\n parameters?: any[],\n queryRunner?: QueryRunner,\n ): Promise<any> {\n if (InstanceChecker.isMongoEntityManager(this.manager))\n throw new TypeORMError(`Queries aren't supported by MongoDB.`)\n\n if (queryRunner && queryRunner.isReleased)\n throw new QueryRunnerProviderAlreadyReleasedError()\n\n const usedQueryRunner = queryRunner || this.createQueryRunner()\n\n try {\n return await usedQueryRunner.query(query, parameters) // await is needed here because we are using finally\n } finally {\n if (!queryRunner) await usedQueryRunner.release()\n }\n }\n\n /**\n * Creates a new query builder that can be used to build a SQL query.\n */\n createQueryBuilder<Entity>(\n entityClass: EntityTarget<Entity>,\n alias: string,\n queryRunner?: QueryRunner,\n ): SelectQueryBuilder<Entity>\n\n /**\n * Creates a new query builder that can be used to build a SQL query.\n */\n createQueryBuilder(queryRunner?: QueryRunner): SelectQueryBuilder<any>\n\n /**\n * Creates a new query builder that can be used to build a SQL query.\n */\n createQueryBuilder<Entity>(\n entityOrRunner?: EntityTarget<Entity> | QueryRunner,\n alias?: string,\n queryRunner?: QueryRunner,\n ): SelectQueryBuilder<Entity> {\n if (InstanceChecker.isMongoEntityManager(this.manager))\n throw new TypeORMError(`Query Builder is not supported by MongoDB.`)\n\n if (alias) {\n alias = DriverUtils.buildAlias(this.driver, alias)\n const metadata = this.getMetadata(\n entityOrRunner as EntityTarget<Entity>,\n )\n return new SelectQueryBuilder(this, queryRunner)\n .select(alias)\n .from(metadata.target, alias)\n } else {\n return new SelectQueryBuilder(\n this,\n entityOrRunner as QueryRunner | undefined,\n )\n }\n }\n\n /**\n * Creates a query runner used for perform queries on a single database connection.\n * Using query runners you can control your queries to execute using single database connection and\n * manually control your database transaction.\n *\n * Mode is used in replication mode and indicates whatever you want to connect\n * to master database or any of slave databases.\n * If you perform writes you must use master database,\n * if you perform reads you can use slave databases.\n */\n createQueryRunner(mode: ReplicationMode = \"master\"): QueryRunner {\n const queryRunner = this.driver.createQueryRunner(mode)\n const manager = this.createEntityManager(queryRunner)\n Object.assign(queryRunner, { manager: manager })\n return queryRunner\n }\n\n /**\n * Gets entity metadata of the junction table (many-to-many table).\n */\n getManyToManyMetadata(\n entityTarget: EntityTarget<any>,\n relationPropertyPath: string,\n ) {\n const relationMetadata =\n this.getMetadata(entityTarget).findRelationWithPropertyPath(\n relationPropertyPath,\n )\n if (!relationMetadata)\n throw new TypeORMError(\n `Relation \"${relationPropertyPath}\" was not found in ${entityTarget} entity.`,\n )\n if (!relationMetadata.isManyToMany)\n throw new TypeORMError(\n `Relation \"${entityTarget}#${relationPropertyPath}\" does not have a many-to-many relationship.` +\n `You can use this method only on many-to-many relations.`,\n )\n\n return relationMetadata.junctionEntityMetadata\n }\n\n /**\n * Creates an Entity Manager for the current connection with the help of the EntityManagerFactory.\n */\n createEntityManager(queryRunner?: QueryRunner): EntityManager {\n return new EntityManagerFactory().create(this, queryRunner)\n }\n\n // -------------------------------------------------------------------------\n // Protected Methods\n // -------------------------------------------------------------------------\n\n /**\n * Finds exist entity metadata by the given entity class, target name or table name.\n */\n protected findMetadata(\n target: EntityTarget<any>,\n ): EntityMetadata | undefined {\n return this.entityMetadatas.find((metadata) => {\n if (metadata.target === target) return true\n if (InstanceChecker.isEntitySchema(target)) {\n return metadata.name === target.options.name\n }\n if (typeof target === \"string\") {\n if (target.indexOf(\".\") !== -1) {\n return metadata.tablePath === target\n } else {\n return (\n metadata.name === target ||\n metadata.tableName === target\n )\n }\n }\n if (\n ObjectUtils.isObject(target) &&\n typeof target.name === \"string\"\n ) {\n if (target.name.indexOf(\".\") !== -1) {\n return metadata.tablePath === target.name\n } else {\n return (\n metadata.name === target.name ||\n metadata.tableName === target.name\n )\n }\n }\n\n return false\n })\n }\n\n /**\n * Builds metadatas for all registered classes inside this connection.\n */\n protected async buildMetadatas(): Promise<void> {\n const connectionMetadataBuilder = new ConnectionMetadataBuilder(this)\n const entityMetadataValidator = new EntityMetadataValidator()\n\n // create subscribers instances if they are not disallowed from high-level (for example they can disallowed from migrations run process)\n const flattenedSubscribers = ObjectUtils.mixedListToArray(\n this.options.subscribers || [],\n )\n const subscribers = await connectionMetadataBuilder.buildSubscribers(\n flattenedSubscribers,\n )\n ObjectUtils.assign(this, { subscribers: subscribers })\n\n // build entity metadatas\n const flattenedEntities = ObjectUtils.mixedListToArray(\n this.options.entities || [],\n )\n const entityMetadatas =\n await connectionMetadataBuilder.buildEntityMetadatas(\n flattenedEntities,\n )\n ObjectUtils.assign(this, { entityMetadatas: entityMetadatas })\n\n // create migration instances\n const flattenedMigrations = ObjectUtils.mixedListToArray(\n this.options.migrations || [],\n )\n const migrations = await connectionMetadataBuilder.buildMigrations(\n flattenedMigrations,\n )\n ObjectUtils.assign(this, { migrations: migrations })\n\n // validate all created entity metadatas to make sure user created entities are valid and correct\n entityMetadataValidator.validateMany(\n this.entityMetadatas.filter(\n (metadata) => metadata.tableType !== \"view\",\n ),\n this.driver,\n )\n\n // set current data source to the entities\n for (let entityMetadata of entityMetadatas) {\n if (\n InstanceChecker.isBaseEntityConstructor(entityMetadata.target)\n ) {\n entityMetadata.target.useDataSource(this)\n }\n }\n }\n}\n"],"sourceRoot":".."}
|
|
1
|
+
{"version":3,"sources":["../browser/src/data-source/DataSource.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,qBAAqB,EAAE,MAAM,0CAA0C,CAAA;AAChF,OAAO,EACH,kCAAkC,EAClC,8BAA8B,EAC9B,2BAA2B,EAC3B,uCAAuC,GAC1C,MAAM,UAAU,CAAA;AAMjB,OAAO,EAAE,iBAAiB,EAAE,MAAM,gCAAgC,CAAA;AAIlE,OAAO,EAAE,uBAAuB,EAAE,MAAM,6CAA6C,CAAA;AAErF,OAAO,EAAE,oBAAoB,EAAE,MAAM,wCAAwC,CAAA;AAC7E,OAAO,EAAE,aAAa,EAAE,MAAM,yBAAyB,CAAA;AACvD,OAAO,EAAE,yBAAyB,EAAE,MAAM,yCAAyC,CAAA;AAEnF,OAAO,EAAE,kBAAkB,EAAE,MAAM,qCAAqC,CAAA;AACxE,OAAO,EAAE,aAAa,EAAE,MAAM,yBAAyB,CAAA;AACvD,OAAO,EAAE,uBAAuB,EAAE,MAAM,kCAAkC,CAAA;AAG1E,OAAO,EAAE,cAAc,EAAE,MAAM,iCAAiC,CAAA;AAChE,OAAO,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAA;AAGjD,OAAO,EAAE,YAAY,EAAE,MAAM,UAAU,CAAA;AACvC,OAAO,EAAE,gBAAgB,EAAE,MAAM,mCAAmC,CAAA;AACpE,OAAO,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAA;AACnD,OAAO,EAAE,eAAe,EAAE,MAAM,yBAAyB,CAAA;AAGzD;;;;;;;GAOG;AACH,MAAM,OAAO,UAAU;IA4EnB,4EAA4E;IAC5E,cAAc;IACd,4EAA4E;IAE5E,YAAY,OAA0B;QA/E7B,mBAAa,GAAG,MAAM,CAAC,GAAG,CAAC,YAAY,CAAC,CAAA;QAgDjD;;WAEG;QACM,eAAU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AAW,EAAE,WAAW,EAAE,CAAC,CAAA;QAEtD,yBAAyB;QACzB,MAAM,iBAAiB,GAAG,WAAW,CAAC,gBAAgB,CAClD,IAAI,CAAC,OAAO,CAAC,QAAQ,IAAI,EAAE,CAC9B,CAAA;QACD,MAAM,eAAe,GACjB,MAAM,yBAAyB,CAAC,oBAAoB,CAChD,iBAAiB,CACpB,CAAA;QACL,WAAW,CAAC,MAAM,CAAC,IAAI,EAAE,EAAE,eAAe,EAAE,eAAe,EAAE,CAAC,CAAA;QAE9D,6BAA6B;QAC7B,MAAM,mBAAmB,GAAG,WAAW,CAAC,gBAAgB,CACpD,IAAI,CAAC,OAAO,CAAC,UAAU,IAAI,EAAE,CAChC,CAAA;QACD,MAAM,UAAU,GAAG,MAAM,yBAAyB,CAAC,eAAe,CAC9D,mBAAmB,CACtB,CAAA;QACD,WAAW,CAAC,MAAM,CAAC,IAAI,EAAE,EAAE,UAAU,EAAE,UAAU,EAAE,CAAC,CAAA;QAEpD,iGAAiG;QACjG,uBAAuB,CAAC,YAAY,CAChC,IAAI,CAAC,eAAe,CAAC,MAAM,CACvB,CAAC,QAAQ,EAAE,EAAE,CAAC,QAAQ,CAAC,SAAS,KAAK,MAAM,CAC9C,EACD,IAAI,CAAC,MAAM,CACd,CAAA;QAED,0CAA0C;QAC1C,KAAK,IAAI,cAAc,IAAI,eAAe,EAAE;YACxC,IACI,eAAe,CAAC,uBAAuB,CAAC,cAAc,CAAC,MAAM,CAAC,EAChE;gBACE,cAAc,CAAC,MAAM,CAAC,aAAa,CAAC,IAAI,CAAC,CAAA;aAC5C;SACJ;IACL,CAAC;CACJ","file":"DataSource.js","sourcesContent":["import { Driver } from \"../driver/Driver\"\nimport { Repository } from \"../repository/Repository\"\nimport { EntitySubscriberInterface } from \"../subscriber/EntitySubscriberInterface\"\nimport { EntityTarget } from \"../common/EntityTarget\"\nimport { ObjectType } from \"../common/ObjectType\"\nimport { EntityManager } from \"../entity-manager/EntityManager\"\nimport { DefaultNamingStrategy } from \"../naming-strategy/DefaultNamingStrategy\"\nimport {\n CannotConnectAlreadyConnectedError,\n CannotExecuteNotConnectedError,\n EntityMetadataNotFoundError,\n QueryRunnerProviderAlreadyReleasedError,\n} from \"../error\"\nimport { TreeRepository } from \"../repository/TreeRepository\"\nimport { NamingStrategyInterface } from \"../naming-strategy/NamingStrategyInterface\"\nimport { EntityMetadata } from \"../metadata/EntityMetadata\"\nimport { Logger } from \"../logger/Logger\"\nimport { MigrationInterface } from \"../migration/MigrationInterface\"\nimport { MigrationExecutor } from \"../migration/MigrationExecutor\"\nimport { Migration } from \"../migration/Migration\"\nimport { MongoRepository } from \"../repository/MongoRepository\"\nimport { MongoEntityManager } from \"../entity-manager/MongoEntityManager\"\nimport { EntityMetadataValidator } from \"../metadata-builder/EntityMetadataValidator\"\nimport { DataSourceOptions } from \"./DataSourceOptions\"\nimport { EntityManagerFactory } from \"../entity-manager/EntityManagerFactory\"\nimport { DriverFactory } from \"../driver/DriverFactory\"\nimport { ConnectionMetadataBuilder } from \"../connection/ConnectionMetadataBuilder\"\nimport { QueryRunner } from \"../query-runner/QueryRunner\"\nimport { SelectQueryBuilder } from \"../query-builder/SelectQueryBuilder\"\nimport { LoggerFactory } from \"../logger/LoggerFactory\"\nimport { QueryResultCacheFactory } from \"../cache/QueryResultCacheFactory\"\nimport { QueryResultCache } from \"../cache/QueryResultCache\"\nimport { SqljsEntityManager } from \"../entity-manager/SqljsEntityManager\"\nimport { RelationLoader } from \"../query-builder/RelationLoader\"\nimport { ObjectUtils } from \"../util/ObjectUtils\"\nimport { IsolationLevel } from \"../driver/types/IsolationLevel\"\nimport { ReplicationMode } from \"../driver/types/ReplicationMode\"\nimport { TypeORMError } from \"../error\"\nimport { RelationIdLoader } from \"../query-builder/RelationIdLoader\"\nimport { DriverUtils } from \"../driver/DriverUtils\"\nimport { InstanceChecker } from \"../util/InstanceChecker\"\nimport { ObjectLiteral } from \"../common/ObjectLiteral\"\n\n/**\n * DataSource is a pre-defined connection configuration to a specific database.\n * You can have multiple data sources connected (with multiple connections in it),\n * connected to multiple databases in your application.\n *\n * Before, it was called `Connection`, but now `Connection` is deprecated\n * because `Connection` isn't the best name for what it's actually is.\n */\nexport class DataSource {\n readonly \"@instanceof\" = Symbol.for(\"DataSource\")\n\n // -------------------------------------------------------------------------\n // Public Readonly Properties\n // -------------------------------------------------------------------------\n\n /**\n * Connection name.\n *\n * @deprecated we don't need names anymore since we are going to drop all related methods relying on this property.\n */\n readonly name: string\n\n /**\n * Connection options.\n */\n readonly options: DataSourceOptions\n\n /**\n * Indicates if DataSource is initialized or not.\n */\n readonly isInitialized: boolean\n\n /**\n * Database driver used by this connection.\n */\n driver: Driver\n\n /**\n * EntityManager of this connection.\n */\n readonly manager: EntityManager\n\n /**\n * Naming strategy used in the connection.\n */\n namingStrategy: NamingStrategyInterface\n\n /**\n * Name for the metadata table\n */\n readonly metadataTableName: string\n\n /**\n * Logger used to log orm events.\n */\n logger: Logger\n\n /**\n * Migration instances that are registered for this connection.\n */\n readonly migrations: MigrationInterface[] = []\n\n /**\n * Entity subscriber instances that are registered for this connection.\n */\n readonly subscribers: EntitySubscriberInterface<any>[] = []\n\n /**\n * All entity metadatas that are registered for this connection.\n */\n readonly entityMetadatas: EntityMetadata[] = []\n\n /**\n * Used to work with query result cache.\n */\n queryResultCache?: QueryResultCache\n\n /**\n * Used to load relations and work with lazy relations.\n */\n readonly relationLoader: RelationLoader\n\n readonly relationIdLoader: RelationIdLoader\n\n // -------------------------------------------------------------------------\n // Constructor\n // -------------------------------------------------------------------------\n\n constructor(options: DataSourceOptions) {\n this.name = options.name || \"default\"\n this.options = options\n this.logger = new LoggerFactory().create(\n this.options.logger,\n this.options.logging,\n )\n this.driver = new DriverFactory().create(this)\n this.manager = this.createEntityManager()\n this.namingStrategy =\n options.namingStrategy || new DefaultNamingStrategy()\n this.metadataTableName = options.metadataTableName || \"typeorm_metadata\"\n this.queryResultCache = options.cache\n ? new QueryResultCacheFactory(this).create()\n : undefined\n this.relationLoader = new RelationLoader(this)\n this.relationIdLoader = new RelationIdLoader(this)\n this.isInitialized = false\n }\n\n // -------------------------------------------------------------------------\n // Public Accessors\n // -------------------------------------------------------------------------\n\n /**\n Indicates if DataSource is initialized or not.\n *\n * @deprecated use .isInitialized instead\n */\n get isConnected() {\n return this.isInitialized\n }\n\n /**\n * Gets the mongodb entity manager that allows to perform mongodb-specific repository operations\n * with any entity in this connection.\n *\n * Available only in mongodb connections.\n */\n get mongoManager(): MongoEntityManager {\n if (!InstanceChecker.isMongoEntityManager(this.manager))\n throw new TypeORMError(\n `MongoEntityManager is only available for MongoDB databases.`,\n )\n\n return this.manager as MongoEntityManager\n }\n\n /**\n * Gets a sql.js specific Entity Manager that allows to perform special load and save operations\n *\n * Available only in connection with the sqljs driver.\n */\n get sqljsManager(): SqljsEntityManager {\n if (!InstanceChecker.isSqljsEntityManager(this.manager))\n throw new TypeORMError(\n `SqljsEntityManager is only available for Sqljs databases.`,\n )\n\n return this.manager\n }\n\n // -------------------------------------------------------------------------\n // Public Methods\n // -------------------------------------------------------------------------\n /**\n * Updates current connection options with provided options.\n */\n setOptions(options: Partial<DataSourceOptions>): this {\n Object.assign(this.options, options)\n\n if (options.logger || options.logging) {\n this.logger = new LoggerFactory().create(\n options.logger || this.options.logger,\n options.logging || this.options.logging,\n )\n }\n\n if (options.namingStrategy) {\n this.namingStrategy = options.namingStrategy\n }\n\n if (options.cache) {\n this.queryResultCache = new QueryResultCacheFactory(this).create()\n }\n\n return this\n }\n\n /**\n * Performs connection to the database.\n * This method should be called once on application bootstrap.\n * This method not necessarily creates database connection (depend on database type),\n * but it also can setup a connection pool with database to use.\n */\n async initialize(): Promise<this> {\n if (this.isInitialized)\n throw new CannotConnectAlreadyConnectedError(this.name)\n\n // connect to the database via its driver\n await this.driver.connect()\n\n // connect to the cache-specific database if cache is enabled\n if (this.queryResultCache) await this.queryResultCache.connect()\n\n // set connected status for the current connection\n ObjectUtils.assign(this, { isInitialized: true })\n\n try {\n // build all metadatas registered in the current connection\n await this.buildMetadatas()\n\n await this.driver.afterConnect()\n\n // if option is set - drop schema once connection is done\n if (this.options.dropSchema) await this.dropDatabase()\n\n // if option is set - automatically synchronize a schema\n if (this.options.migrationsRun)\n await this.runMigrations({\n transaction: this.options.migrationsTransactionMode,\n })\n\n // if option is set - automatically synchronize a schema\n if (this.options.synchronize) await this.synchronize()\n } catch (error) {\n // if for some reason build metadata fail (for example validation error during entity metadata check)\n // connection needs to be closed\n await this.close()\n throw error\n }\n\n return this\n }\n\n /**\n * Performs connection to the database.\n * This method should be called once on application bootstrap.\n * This method not necessarily creates database connection (depend on database type),\n * but it also can setup a connection pool with database to use.\n *\n * @deprecated use .initialize method instead\n */\n async connect(): Promise<this> {\n return this.initialize()\n }\n\n /**\n * Closes connection with the database.\n * Once connection is closed, you cannot use repositories or perform any operations except opening connection again.\n */\n async destroy(): Promise<void> {\n if (!this.isInitialized)\n throw new CannotExecuteNotConnectedError(this.name)\n\n await this.driver.disconnect()\n\n // disconnect from the cache-specific database if cache was enabled\n if (this.queryResultCache) await this.queryResultCache.disconnect()\n\n ObjectUtils.assign(this, { isInitialized: false })\n }\n\n /**\n * Closes connection with the database.\n * Once connection is closed, you cannot use repositories or perform any operations except opening connection again.\n *\n * @deprecated use .destroy method instead\n */\n async close(): Promise<void> {\n return this.destroy()\n }\n\n /**\n * Creates database schema for all entities registered in this connection.\n * Can be used only after connection to the database is established.\n *\n * @param dropBeforeSync If set to true then it drops the database with all its tables and data\n */\n async synchronize(dropBeforeSync: boolean = false): Promise<void> {\n if (!this.isInitialized)\n throw new CannotExecuteNotConnectedError(this.name)\n\n if (dropBeforeSync) await this.dropDatabase()\n\n const schemaBuilder = this.driver.createSchemaBuilder()\n await schemaBuilder.build()\n }\n\n /**\n * Drops the database and all its data.\n * Be careful with this method on production since this method will erase all your database tables and their data.\n * Can be used only after connection to the database is established.\n */\n // TODO rename\n async dropDatabase(): Promise<void> {\n const queryRunner = this.createQueryRunner()\n try {\n if (\n this.driver.options.type === \"mssql\" ||\n DriverUtils.isMySQLFamily(this.driver) ||\n this.driver.options.type === \"aurora-mysql\" ||\n DriverUtils.isSQLiteFamily(this.driver)\n ) {\n const databases: string[] = []\n this.entityMetadatas.forEach((metadata) => {\n if (\n metadata.database &&\n databases.indexOf(metadata.database) === -1\n )\n databases.push(metadata.database)\n })\n if (databases.length === 0 && this.driver.database) {\n databases.push(this.driver.database)\n }\n\n if (databases.length === 0) {\n await queryRunner.clearDatabase()\n } else {\n for (const database of databases) {\n await queryRunner.clearDatabase(database)\n }\n }\n } else {\n await queryRunner.clearDatabase()\n }\n } finally {\n await queryRunner.release()\n }\n }\n\n /**\n * Runs all pending migrations.\n * Can be used only after connection to the database is established.\n */\n async runMigrations(options?: {\n transaction?: \"all\" | \"none\" | \"each\"\n }): Promise<Migration[]> {\n if (!this.isInitialized)\n throw new CannotExecuteNotConnectedError(this.name)\n\n const migrationExecutor = new MigrationExecutor(this)\n migrationExecutor.transaction =\n (options && options.transaction) || \"all\"\n\n const successMigrations =\n await migrationExecutor.executePendingMigrations()\n return successMigrations\n }\n\n /**\n * Reverts last executed migration.\n * Can be used only after connection to the database is established.\n */\n async undoLastMigration(options?: {\n transaction?: \"all\" | \"none\" | \"each\"\n }): Promise<void> {\n if (!this.isInitialized)\n throw new CannotExecuteNotConnectedError(this.name)\n\n const migrationExecutor = new MigrationExecutor(this)\n migrationExecutor.transaction =\n (options && options.transaction) || \"all\"\n\n await migrationExecutor.undoLastMigration()\n }\n\n /**\n * Lists all migrations and whether they have been run.\n * Returns true if there are pending migrations\n */\n async showMigrations(): Promise<boolean> {\n if (!this.isInitialized) {\n throw new CannotExecuteNotConnectedError(this.name)\n }\n const migrationExecutor = new MigrationExecutor(this)\n return await migrationExecutor.showMigrations()\n }\n\n /**\n * Checks if entity metadata exist for the given entity class, target name or table name.\n */\n hasMetadata(target: EntityTarget<any>): boolean {\n return !!this.findMetadata(target)\n }\n\n /**\n * Gets entity metadata for the given entity class or schema name.\n */\n getMetadata(target: EntityTarget<any>): EntityMetadata {\n const metadata = this.findMetadata(target)\n if (!metadata) throw new EntityMetadataNotFoundError(target)\n\n return metadata\n }\n\n /**\n * Gets repository for the given entity.\n */\n getRepository<Entity extends ObjectLiteral>(\n target: EntityTarget<Entity>,\n ): Repository<Entity> {\n return this.manager.getRepository(target)\n }\n\n /**\n * Gets tree repository for the given entity class or name.\n * Only tree-type entities can have a TreeRepository, like ones decorated with @Tree decorator.\n */\n getTreeRepository<Entity extends ObjectLiteral>(\n target: EntityTarget<Entity>,\n ): TreeRepository<Entity> {\n return this.manager.getTreeRepository(target)\n }\n\n /**\n * Gets mongodb-specific repository for the given entity class or name.\n * Works only if connection is mongodb-specific.\n */\n getMongoRepository<Entity extends ObjectLiteral>(\n target: EntityTarget<Entity>,\n ): MongoRepository<Entity> {\n if (!(this.driver.options.type === \"mongodb\"))\n throw new TypeORMError(\n `You can use getMongoRepository only for MongoDB connections.`,\n )\n\n return this.manager.getRepository(target) as any\n }\n\n /**\n * Gets custom entity repository marked with @EntityRepository decorator.\n *\n * @deprecated use Repository.extend function to create a custom repository\n */\n getCustomRepository<T>(customRepository: ObjectType<T>): T {\n return this.manager.getCustomRepository(customRepository)\n }\n\n /**\n * Wraps given function execution (and all operations made there) into a transaction.\n * All database operations must be executed using provided entity manager.\n */\n async transaction<T>(\n runInTransaction: (entityManager: EntityManager) => Promise<T>,\n ): Promise<T>\n async transaction<T>(\n isolationLevel: IsolationLevel,\n runInTransaction: (entityManager: EntityManager) => Promise<T>,\n ): Promise<T>\n async transaction<T>(\n isolationOrRunInTransaction:\n | IsolationLevel\n | ((entityManager: EntityManager) => Promise<T>),\n runInTransactionParam?: (entityManager: EntityManager) => Promise<T>,\n ): Promise<any> {\n return this.manager.transaction(\n isolationOrRunInTransaction as any,\n runInTransactionParam as any,\n )\n }\n\n /**\n * Executes raw SQL query and returns raw database results.\n */\n async query(\n query: string,\n parameters?: any[],\n queryRunner?: QueryRunner,\n ): Promise<any> {\n if (InstanceChecker.isMongoEntityManager(this.manager))\n throw new TypeORMError(`Queries aren't supported by MongoDB.`)\n\n if (queryRunner && queryRunner.isReleased)\n throw new QueryRunnerProviderAlreadyReleasedError()\n\n const usedQueryRunner = queryRunner || this.createQueryRunner()\n\n try {\n return await usedQueryRunner.query(query, parameters) // await is needed here because we are using finally\n } finally {\n if (!queryRunner) await usedQueryRunner.release()\n }\n }\n\n /**\n * Creates a new query builder that can be used to build a SQL query.\n */\n createQueryBuilder<Entity>(\n entityClass: EntityTarget<Entity>,\n alias: string,\n queryRunner?: QueryRunner,\n ): SelectQueryBuilder<Entity>\n\n /**\n * Creates a new query builder that can be used to build a SQL query.\n */\n createQueryBuilder(queryRunner?: QueryRunner): SelectQueryBuilder<any>\n\n /**\n * Creates a new query builder that can be used to build a SQL query.\n */\n createQueryBuilder<Entity>(\n entityOrRunner?: EntityTarget<Entity> | QueryRunner,\n alias?: string,\n queryRunner?: QueryRunner,\n ): SelectQueryBuilder<Entity> {\n if (InstanceChecker.isMongoEntityManager(this.manager))\n throw new TypeORMError(`Query Builder is not supported by MongoDB.`)\n\n if (alias) {\n alias = DriverUtils.buildAlias(this.driver, alias)\n const metadata = this.getMetadata(\n entityOrRunner as EntityTarget<Entity>,\n )\n return new SelectQueryBuilder(this, queryRunner)\n .select(alias)\n .from(metadata.target, alias)\n } else {\n return new SelectQueryBuilder(\n this,\n entityOrRunner as QueryRunner | undefined,\n )\n }\n }\n\n /**\n * Creates a query runner used for perform queries on a single database connection.\n * Using query runners you can control your queries to execute using single database connection and\n * manually control your database transaction.\n *\n * Mode is used in replication mode and indicates whatever you want to connect\n * to master database or any of slave databases.\n * If you perform writes you must use master database,\n * if you perform reads you can use slave databases.\n */\n createQueryRunner(mode: ReplicationMode = \"master\"): QueryRunner {\n const queryRunner = this.driver.createQueryRunner(mode)\n const manager = this.createEntityManager(queryRunner)\n Object.assign(queryRunner, { manager: manager })\n return queryRunner\n }\n\n /**\n * Gets entity metadata of the junction table (many-to-many table).\n */\n getManyToManyMetadata(\n entityTarget: EntityTarget<any>,\n relationPropertyPath: string,\n ) {\n const relationMetadata =\n this.getMetadata(entityTarget).findRelationWithPropertyPath(\n relationPropertyPath,\n )\n if (!relationMetadata)\n throw new TypeORMError(\n `Relation \"${relationPropertyPath}\" was not found in ${entityTarget} entity.`,\n )\n if (!relationMetadata.isManyToMany)\n throw new TypeORMError(\n `Relation \"${entityTarget}#${relationPropertyPath}\" does not have a many-to-many relationship.` +\n `You can use this method only on many-to-many relations.`,\n )\n\n return relationMetadata.junctionEntityMetadata\n }\n\n /**\n * Creates an Entity Manager for the current connection with the help of the EntityManagerFactory.\n */\n createEntityManager(queryRunner?: QueryRunner): EntityManager {\n return new EntityManagerFactory().create(this, queryRunner)\n }\n\n // -------------------------------------------------------------------------\n // Protected Methods\n // -------------------------------------------------------------------------\n\n /**\n * Finds exist entity metadata by the given entity class, target name or table name.\n */\n protected findMetadata(\n target: EntityTarget<any>,\n ): EntityMetadata | undefined {\n return this.entityMetadatas.find((metadata) => {\n if (metadata.target === target) return true\n if (InstanceChecker.isEntitySchema(target)) {\n return metadata.name === target.options.name\n }\n if (typeof target === \"string\") {\n if (target.indexOf(\".\") !== -1) {\n return metadata.tablePath === target\n } else {\n return (\n metadata.name === target ||\n metadata.tableName === target\n )\n }\n }\n if (\n ObjectUtils.isObject(target) &&\n typeof target.name === \"string\"\n ) {\n if (target.name.indexOf(\".\") !== -1) {\n return metadata.tablePath === target.name\n } else {\n return (\n metadata.name === target.name ||\n metadata.tableName === target.name\n )\n }\n }\n\n return false\n })\n }\n\n /**\n * Builds metadatas for all registered classes inside this connection.\n */\n protected async buildMetadatas(): Promise<void> {\n const connectionMetadataBuilder = new ConnectionMetadataBuilder(this)\n const entityMetadataValidator = new EntityMetadataValidator()\n\n // create subscribers instances if they are not disallowed from high-level (for example they can disallowed from migrations run process)\n const flattenedSubscribers = ObjectUtils.mixedListToArray(\n this.options.subscribers || [],\n )\n const subscribers = await connectionMetadataBuilder.buildSubscribers(\n flattenedSubscribers,\n )\n ObjectUtils.assign(this, { subscribers: subscribers })\n\n // build entity metadatas\n const flattenedEntities = ObjectUtils.mixedListToArray(\n this.options.entities || [],\n )\n const entityMetadatas =\n await connectionMetadataBuilder.buildEntityMetadatas(\n flattenedEntities,\n )\n ObjectUtils.assign(this, { entityMetadatas: entityMetadatas })\n\n // create migration instances\n const flattenedMigrations = ObjectUtils.mixedListToArray(\n this.options.migrations || [],\n )\n const migrations = await connectionMetadataBuilder.buildMigrations(\n flattenedMigrations,\n )\n ObjectUtils.assign(this, { migrations: migrations })\n\n // validate all created entity metadatas to make sure user created entities are valid and correct\n entityMetadataValidator.validateMany(\n this.entityMetadatas.filter(\n (metadata) => metadata.tableType !== \"view\",\n ),\n this.driver,\n )\n\n // set current data source to the entities\n for (let entityMetadata of entityMetadatas) {\n if (\n InstanceChecker.isBaseEntityConstructor(entityMetadata.target)\n ) {\n entityMetadata.target.useDataSource(this)\n }\n }\n }\n}\n"],"sourceRoot":".."}
|
|
@@ -52,4 +52,8 @@ export interface BetterSqlite3ConnectionOptions extends BaseDataSourceOptions {
|
|
|
52
52
|
* Provide a function that gets called with every SQL string executed by the database connection.
|
|
53
53
|
*/
|
|
54
54
|
readonly verbose?: Function;
|
|
55
|
+
/**
|
|
56
|
+
* Relative or absolute path to the native addon (better_sqlite3.node).
|
|
57
|
+
*/
|
|
58
|
+
readonly nativeBinding?: string;
|
|
55
59
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../browser/src/driver/better-sqlite3/BetterSqlite3ConnectionOptions.ts"],"names":[],"mappings":"","file":"BetterSqlite3ConnectionOptions.js","sourcesContent":["import { BaseDataSourceOptions } from \"../../data-source/BaseDataSourceOptions\"\n\n/**\n * Sqlite-specific connection options.\n */\nexport interface BetterSqlite3ConnectionOptions extends BaseDataSourceOptions {\n /**\n * Database type.\n */\n readonly type: \"better-sqlite3\"\n\n /**\n * Storage type or path to the storage.\n */\n readonly database: string\n\n /**\n * The driver object\n * This defaults to require(\"better-sqlite3\")\n */\n readonly driver?: any\n\n /**\n * Encryption key for for SQLCipher.\n */\n readonly key?: string\n\n /**\n * Cache size of sqlite statement to speed up queries.\n * Default: 100.\n */\n readonly statementCacheSize?: number\n\n /**\n * Function to run before a database is used in typeorm.\n * You can set pragmas, register plugins or register\n * functions or aggregates in this function.\n */\n readonly prepareDatabase?: (db: any) => void | Promise<void>\n\n /**\n * Open the database connection in readonly mode.\n * Default: false.\n */\n readonly readonly?: boolean\n\n /**\n * If the database does not exist, an Error will be thrown instead of creating a new file.\n * This option does not affect in-memory or readonly database connections.\n * Default: false.\n */\n readonly fileMustExist?: boolean\n\n /**\n * The number of milliseconds to wait when executing queries\n * on a locked database, before throwing a SQLITE_BUSY error.\n * Default: 5000.\n */\n readonly timeout?: number\n\n /**\n * Provide a function that gets called with every SQL string executed by the database connection.\n */\n readonly verbose?: Function\n}\n"],"sourceRoot":"../.."}
|
|
1
|
+
{"version":3,"sources":["../browser/src/driver/better-sqlite3/BetterSqlite3ConnectionOptions.ts"],"names":[],"mappings":"","file":"BetterSqlite3ConnectionOptions.js","sourcesContent":["import { BaseDataSourceOptions } from \"../../data-source/BaseDataSourceOptions\"\n\n/**\n * Sqlite-specific connection options.\n */\nexport interface BetterSqlite3ConnectionOptions extends BaseDataSourceOptions {\n /**\n * Database type.\n */\n readonly type: \"better-sqlite3\"\n\n /**\n * Storage type or path to the storage.\n */\n readonly database: string\n\n /**\n * The driver object\n * This defaults to require(\"better-sqlite3\")\n */\n readonly driver?: any\n\n /**\n * Encryption key for for SQLCipher.\n */\n readonly key?: string\n\n /**\n * Cache size of sqlite statement to speed up queries.\n * Default: 100.\n */\n readonly statementCacheSize?: number\n\n /**\n * Function to run before a database is used in typeorm.\n * You can set pragmas, register plugins or register\n * functions or aggregates in this function.\n */\n readonly prepareDatabase?: (db: any) => void | Promise<void>\n\n /**\n * Open the database connection in readonly mode.\n * Default: false.\n */\n readonly readonly?: boolean\n\n /**\n * If the database does not exist, an Error will be thrown instead of creating a new file.\n * This option does not affect in-memory or readonly database connections.\n * Default: false.\n */\n readonly fileMustExist?: boolean\n\n /**\n * The number of milliseconds to wait when executing queries\n * on a locked database, before throwing a SQLITE_BUSY error.\n * Default: 5000.\n */\n readonly timeout?: number\n\n /**\n * Provide a function that gets called with every SQL string executed by the database connection.\n */\n readonly verbose?: Function\n\n /**\n * Relative or absolute path to the native addon (better_sqlite3.node).\n */\n readonly nativeBinding?: string\n}\n"],"sourceRoot":"../.."}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { DataSource } from "../../data-source
|
|
1
|
+
import { DataSource } from "../../data-source";
|
|
2
2
|
import { ColumnType } from "../types/ColumnTypes";
|
|
3
3
|
import { QueryRunner } from "../../query-runner/QueryRunner";
|
|
4
4
|
import { AbstractSqliteDriver } from "../sqlite-abstract/AbstractSqliteDriver";
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import mkdirp from "mkdirp";
|
|
2
2
|
import path from "path";
|
|
3
|
-
import { DriverPackageNotInstalledError } from "../../error
|
|
4
|
-
import { DriverOptionNotSetError } from "../../error
|
|
3
|
+
import { DriverPackageNotInstalledError } from "../../error";
|
|
4
|
+
import { DriverOptionNotSetError } from "../../error";
|
|
5
5
|
import { PlatformTools } from "../../platform/PlatformTools";
|
|
6
6
|
import { AbstractSqliteDriver } from "../sqlite-abstract/AbstractSqliteDriver";
|
|
7
7
|
import { BetterSqlite3QueryRunner } from "./BetterSqlite3QueryRunner";
|
|
@@ -84,12 +84,13 @@ export class BetterSqlite3Driver extends AbstractSqliteDriver {
|
|
|
84
84
|
// not to create database directory if is in memory
|
|
85
85
|
if (this.options.database !== ":memory:")
|
|
86
86
|
await this.createDatabaseDirectory(path.dirname(this.options.database));
|
|
87
|
-
const { database, readonly = false, fileMustExist = false, timeout = 5000, verbose = null, prepareDatabase, } = this.options;
|
|
87
|
+
const { database, readonly = false, fileMustExist = false, timeout = 5000, verbose = null, nativeBinding = null, prepareDatabase, } = this.options;
|
|
88
88
|
const databaseConnection = this.sqlite(database, {
|
|
89
89
|
readonly,
|
|
90
90
|
fileMustExist,
|
|
91
91
|
timeout,
|
|
92
92
|
verbose,
|
|
93
|
+
nativeBinding,
|
|
93
94
|
});
|
|
94
95
|
// in the options, if encryption key for SQLCipher is setted.
|
|
95
96
|
// Must invoke key pragma before trying to do any other interaction with the database.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../browser/src/driver/better-sqlite3/BetterSqlite3Driver.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,QAAQ,CAAA;AAC3B,OAAO,IAAI,MAAM,MAAM,CAAA;AACvB,OAAO,EAAE,8BAA8B,EAAE,MAAM,4CAA4C,CAAA;AAC3F,OAAO,EAAE,uBAAuB,EAAE,MAAM,qCAAqC,CAAA;AAC7E,OAAO,EAAE,aAAa,EAAE,MAAM,8BAA8B,CAAA;AAI5D,OAAO,EAAE,oBAAoB,EAAE,MAAM,yCAAyC,CAAA;AAE9E,OAAO,EAAE,wBAAwB,EAAE,MAAM,4BAA4B,CAAA;AAErE,OAAO,EAAE,cAAc,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAA;AAEjE;;GAEG;AACH,MAAM,OAAO,mBAAoB,SAAQ,oBAAoB;IAezD,4EAA4E;IAC5E,cAAc;IACd,4EAA4E;IAE5E,YAAY,UAAsB;QAC9B,KAAK,CAAC,UAAU,CAAC,CAAA;QAEjB,IAAI,CAAC,UAAU,GAAG,UAAU,CAAA;QAC5B,IAAI,CAAC,OAAO,GAAG,UAAU,CAAC,OAAyC,CAAA;QACnE,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAA;QAErC,kDAAkD;QAClD,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,QAAQ;YACtB,MAAM,IAAI,uBAAuB,CAAC,UAAU,CAAC,CAAA;QAEjD,sBAAsB;QACtB,IAAI,CAAC,gBAAgB,E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AAA;IAC7B,CAAC;IAED;;OAEG;IACO,gBAAgB;QACtB,IAAI;YACA,MAAM,MAAM,GACR,IAAI,CAAC,OAAO,CAAC,MAAM,IAAI,aAAa,CAAC,IAAI,CAAC,gBAAgB,CAAC,CAAA;YAC/D,IAAI,CAAC,MAAM,GAAG,MAAM,CAAA;SACvB;QAAC,OAAO,CAAC,EAAE;YACR,MAAM,IAAI,8BAA8B,CAAC,QAAQ,EAAE,gBAAgB,CAAC,CAAA;SACvE;IACL,CAAC;IAED;;OAEG;IACO,KAAK,CAAC,uBAAuB,CAAC,MAAc;QAClD,MAAM,MAAM,CAAC,MAAM,CAAC,CAAA;IACxB,CAAC;IAED;;;;;OAKG;IACO,KAAK,CAAC,eAAe;QAC3B,kIAAkI;QAClI,IAAI,KAAK,EAAE,MAAM,EACb,YAAY,EACZ,sBAAsB,GACzB,IAAI,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,iBAAiB,CAAC,EAAE;YACxC,MAAM,IAAI,CAAC,uBAAuB,CAC9B,IAAI,CAAC,OAAO,CAAC,sBAAsB,CAAC,CACvC,CAAA;YACD,MAAM,IAAI,CAAC,UAAU,CAAC,KAAK,CACvB,WAAW,sBAAsB,SAAS,YAAY,GAAG,CAC5D,CAAA;SACJ;IACL,CAAC;IAES,mBAAmB;QACzB,MAAM,SAAS,GAAG,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAA;QACvC,OAAO,IAAI,CAAC,OAAO,CACf,UAAU,CAAC,SAAS,CAAC;YACjB,CAAC,CAAC,SAAS;YACX,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,aAAc,EAAE,SAAS,CAAC,CAC1D,CAAA;IACL,CAAC;CACJ","file":"BetterSqlite3Driver.js","sourcesContent":["import mkdirp from \"mkdirp\"\nimport path from \"path\"\nimport { DriverPackageNotInstalledError } from \"../../error/DriverPackageNotInstalledError\"\nimport { DriverOptionNotSetError } from \"../../error/DriverOptionNotSetError\"\nimport { PlatformTools } from \"../../platform/PlatformTools\"\nimport { DataSource } from \"../../data-source/DataSource\"\nimport { ColumnType } from \"../types/ColumnTypes\"\nimport { QueryRunner } from \"../../query-runner/QueryRunner\"\nimport { AbstractSqliteDriver } from \"../sqlite-abstract/AbstractSqliteDriver\"\nimport { BetterSqlite3ConnectionOptions } from \"./BetterSqlite3ConnectionOptions\"\nimport { BetterSqlite3QueryRunner } from \"./BetterSqlite3QueryRunner\"\nimport { ReplicationMode } from \"../types/ReplicationMode\"\nimport { filepathToName, isAbsolute } from \"../../util/PathUtils\"\n\n/**\n * Organizes communication with sqlite DBMS.\n */\nexport class BetterSqlite3Driver extends AbstractSqliteDriver {\n // -------------------------------------------------------------------------\n // Public Implemented Properties\n // -------------------------------------------------------------------------\n\n /**\n * Connection options.\n */\n options: BetterSqlite3ConnectionOptions\n\n /**\n * SQLite underlying library.\n */\n sqlite: any\n\n // -------------------------------------------------------------------------\n // Constructor\n // -------------------------------------------------------------------------\n\n constructor(connection: DataSource) {\n super(connection)\n\n this.connection = connection\n this.options = connection.options as BetterSqlite3ConnectionOptions\n this.database = this.options.database\n\n // validate options to make sure everything is set\n if (!this.options.database)\n throw new DriverOptionNotSetError(\"database\")\n\n // load sqlite package\n this.loadDependencies()\n }\n\n // -------------------------------------------------------------------------\n // Public Methods\n // -------------------------------------------------------------------------\n\n /**\n * Closes connection with database.\n */\n async disconnect(): Promise<void> {\n this.queryRunner = undefined\n this.databaseConnection.close()\n }\n\n /**\n * Creates a query runner used to execute database queries.\n */\n createQueryRunner(mode: ReplicationMode): QueryRunner {\n if (!this.queryRunner)\n this.queryRunner = new BetterSqlite3QueryRunner(this)\n\n return this.queryRunner\n }\n\n normalizeType(column: {\n type?: ColumnType\n length?: number | string\n precision?: number | null\n scale?: number\n }): string {\n if ((column.type as any) === Buffer) {\n return \"blob\"\n }\n\n return super.normalizeType(column)\n }\n\n async afterConnect(): Promise<void> {\n return this.attachDatabases()\n }\n\n /**\n * For SQLite, the database may be added in the decorator metadata. It will be a filepath to a database file.\n */\n buildTableName(\n tableName: string,\n _schema?: string,\n database?: string,\n ): string {\n if (!database) return tableName\n if (this.getAttachedDatabaseHandleByRelativePath(database))\n return `${this.getAttachedDatabaseHandleByRelativePath(\n database,\n )}.${tableName}`\n\n if (database === this.options.database) return tableName\n\n // we use the decorated name as supplied when deriving attach handle (ideally without non-portable absolute path)\n const identifierHash = filepathToName(database)\n // decorated name will be assumed relative to main database file when non absolute. Paths supplied as absolute won't be portable\n const absFilepath = isAbsolute(database)\n ? database\n : path.join(this.getMainDatabasePath(), database)\n\n this.attachedDatabases[database] = {\n attachFilepathAbsolute: absFilepath,\n attachFilepathRelative: database,\n attachHandle: identifierHash,\n }\n\n return `${identifierHash}.${tableName}`\n }\n\n // -------------------------------------------------------------------------\n // Protected Methods\n // -------------------------------------------------------------------------\n\n /**\n * Creates connection with the database.\n */\n protected async createDatabaseConnection() {\n // not to create database directory if is in memory\n if (this.options.database !== \":memory:\")\n await this.createDatabaseDirectory(\n path.dirname(this.options.database),\n )\n\n const {\n database,\n readonly = false,\n fileMustExist = false,\n timeout = 5000,\n verbose = null,\n prepareDatabase,\n } = this.options\n const databaseConnection = this.sqlite(database, {\n readonly,\n fileMustExist,\n timeout,\n verbose,\n })\n // in the options, if encryption key for SQLCipher is setted.\n // Must invoke key pragma before trying to do any other interaction with the database.\n if (this.options.key) {\n databaseConnection.exec(\n `PRAGMA key = ${JSON.stringify(this.options.key)}`,\n )\n }\n\n // function to run before a database is used in typeorm.\n if (typeof prepareDatabase === \"function\") {\n prepareDatabase(databaseConnection)\n }\n\n // we need to enable foreign keys in sqlite to make sure all foreign key related features\n // working properly. this also makes onDelete to work with sqlite.\n databaseConnection.exec(`PRAGMA foreign_keys = ON`)\n\n // turn on WAL mode to enhance performance\n databaseConnection.exec(`PRAGMA journal_mode = WAL`)\n\n return databaseConnection\n }\n\n /**\n * If driver dependency is not given explicitly, then try to load it via \"require\".\n */\n protected loadDependencies(): void {\n try {\n const sqlite =\n this.options.driver || PlatformTools.load(\"better-sqlite3\")\n this.sqlite = sqlite\n } catch (e) {\n throw new DriverPackageNotInstalledError(\"SQLite\", \"better-sqlite3\")\n }\n }\n\n /**\n * Auto creates database directory if it does not exist.\n */\n protected async createDatabaseDirectory(dbPath: string): Promise<void> {\n await mkdirp(dbPath)\n }\n\n /**\n * Performs the attaching of the database files. The attachedDatabase should have been populated during calls to #buildTableName\n * during EntityMetadata production (see EntityMetadata#buildTablePath)\n *\n * https://sqlite.org/lang_attach.html\n */\n protected async attachDatabases() {\n // @todo - possibly check number of databases (but unqueriable at runtime sadly) - https://www.sqlite.org/limits.html#max_attached\n for await (const {\n attachHandle,\n attachFilepathAbsolute,\n } of Object.values(this.attachedDatabases)) {\n await this.createDatabaseDirectory(\n path.dirname(attachFilepathAbsolute),\n )\n await this.connection.query(\n `ATTACH \"${attachFilepathAbsolute}\" AS \"${attachHandle}\"`,\n )\n }\n }\n\n protected getMainDatabasePath(): string {\n const optionsDb = this.options.database\n return path.dirname(\n isAbsolute(optionsDb)\n ? optionsDb\n : path.join(this.options.baseDirectory!, optionsDb),\n )\n }\n}\n"],"sourceRoot":"../.."}
|
|
1
|
+
{"version":3,"sources":["../browser/src/driver/better-sqlite3/BetterSqlite3Driver.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,QAAQ,CAAA;AAC3B,OAAO,IAAI,MAAM,MAAM,CAAA;AACvB,OAAO,EAAE,8BAA8B,EAAE,MAAM,aAAa,CAAA;AAC5D,OAAO,EAAE,uBAAuB,EAAE,MAAM,aAAa,CAAA;AACrD,OAAO,EAAE,aAAa,EAAE,MAAM,8BAA8B,CAAA;AAI5D,OAAO,EAAE,oBAAoB,EAAE,MAAM,yCAAyC,CAAA;AAE9E,OAAO,EAAE,wBAAwB,EAAE,MAAM,4BAA4B,CAAA;AAErE,OAAO,EAAE,cAAc,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAA;AAEjE;;GAEG;AACH,MAAM,OAAO,mBA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,YAAY,GAAG,CAC5D,CAAA;SACJ;IACL,CAAC;IAES,mBAAmB;QACzB,MAAM,SAAS,GAAG,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAA;QACvC,OAAO,IAAI,CAAC,OAAO,CACf,UAAU,CAAC,SAAS,CAAC;YACjB,CAAC,CAAC,SAAS;YACX,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,aAAc,EAAE,SAAS,CAAC,CAC1D,CAAA;IACL,CAAC;CACJ","file":"BetterSqlite3Driver.js","sourcesContent":["import mkdirp from \"mkdirp\"\nimport path from \"path\"\nimport { DriverPackageNotInstalledError } from \"../../error\"\nimport { DriverOptionNotSetError } from \"../../error\"\nimport { PlatformTools } from \"../../platform/PlatformTools\"\nimport { DataSource } from \"../../data-source\"\nimport { ColumnType } from \"../types/ColumnTypes\"\nimport { QueryRunner } from \"../../query-runner/QueryRunner\"\nimport { AbstractSqliteDriver } from \"../sqlite-abstract/AbstractSqliteDriver\"\nimport { BetterSqlite3ConnectionOptions } from \"./BetterSqlite3ConnectionOptions\"\nimport { BetterSqlite3QueryRunner } from \"./BetterSqlite3QueryRunner\"\nimport { ReplicationMode } from \"../types/ReplicationMode\"\nimport { filepathToName, isAbsolute } from \"../../util/PathUtils\"\n\n/**\n * Organizes communication with sqlite DBMS.\n */\nexport class BetterSqlite3Driver extends AbstractSqliteDriver {\n // -------------------------------------------------------------------------\n // Public Implemented Properties\n // -------------------------------------------------------------------------\n\n /**\n * Connection options.\n */\n options: BetterSqlite3ConnectionOptions\n\n /**\n * SQLite underlying library.\n */\n sqlite: any\n\n // -------------------------------------------------------------------------\n // Constructor\n // -------------------------------------------------------------------------\n\n constructor(connection: DataSource) {\n super(connection)\n\n this.connection = connection\n this.options = connection.options as BetterSqlite3ConnectionOptions\n this.database = this.options.database\n\n // validate options to make sure everything is set\n if (!this.options.database)\n throw new DriverOptionNotSetError(\"database\")\n\n // load sqlite package\n this.loadDependencies()\n }\n\n // -------------------------------------------------------------------------\n // Public Methods\n // -------------------------------------------------------------------------\n\n /**\n * Closes connection with database.\n */\n async disconnect(): Promise<void> {\n this.queryRunner = undefined\n this.databaseConnection.close()\n }\n\n /**\n * Creates a query runner used to execute database queries.\n */\n createQueryRunner(mode: ReplicationMode): QueryRunner {\n if (!this.queryRunner)\n this.queryRunner = new BetterSqlite3QueryRunner(this)\n\n return this.queryRunner\n }\n\n normalizeType(column: {\n type?: ColumnType\n length?: number | string\n precision?: number | null\n scale?: number\n }): string {\n if ((column.type as any) === Buffer) {\n return \"blob\"\n }\n\n return super.normalizeType(column)\n }\n\n async afterConnect(): Promise<void> {\n return this.attachDatabases()\n }\n\n /**\n * For SQLite, the database may be added in the decorator metadata. It will be a filepath to a database file.\n */\n buildTableName(\n tableName: string,\n _schema?: string,\n database?: string,\n ): string {\n if (!database) return tableName\n if (this.getAttachedDatabaseHandleByRelativePath(database))\n return `${this.getAttachedDatabaseHandleByRelativePath(\n database,\n )}.${tableName}`\n\n if (database === this.options.database) return tableName\n\n // we use the decorated name as supplied when deriving attach handle (ideally without non-portable absolute path)\n const identifierHash = filepathToName(database)\n // decorated name will be assumed relative to main database file when non absolute. Paths supplied as absolute won't be portable\n const absFilepath = isAbsolute(database)\n ? database\n : path.join(this.getMainDatabasePath(), database)\n\n this.attachedDatabases[database] = {\n attachFilepathAbsolute: absFilepath,\n attachFilepathRelative: database,\n attachHandle: identifierHash,\n }\n\n return `${identifierHash}.${tableName}`\n }\n\n // -------------------------------------------------------------------------\n // Protected Methods\n // -------------------------------------------------------------------------\n\n /**\n * Creates connection with the database.\n */\n protected async createDatabaseConnection() {\n // not to create database directory if is in memory\n if (this.options.database !== \":memory:\")\n await this.createDatabaseDirectory(\n path.dirname(this.options.database),\n )\n\n const {\n database,\n readonly = false,\n fileMustExist = false,\n timeout = 5000,\n verbose = null,\n nativeBinding = null,\n prepareDatabase,\n } = this.options\n const databaseConnection = this.sqlite(database, {\n readonly,\n fileMustExist,\n timeout,\n verbose,\n nativeBinding,\n })\n // in the options, if encryption key for SQLCipher is setted.\n // Must invoke key pragma before trying to do any other interaction with the database.\n if (this.options.key) {\n databaseConnection.exec(\n `PRAGMA key = ${JSON.stringify(this.options.key)}`,\n )\n }\n\n // function to run before a database is used in typeorm.\n if (typeof prepareDatabase === \"function\") {\n prepareDatabase(databaseConnection)\n }\n\n // we need to enable foreign keys in sqlite to make sure all foreign key related features\n // working properly. this also makes onDelete to work with sqlite.\n databaseConnection.exec(`PRAGMA foreign_keys = ON`)\n\n // turn on WAL mode to enhance performance\n databaseConnection.exec(`PRAGMA journal_mode = WAL`)\n\n return databaseConnection\n }\n\n /**\n * If driver dependency is not given explicitly, then try to load it via \"require\".\n */\n protected loadDependencies(): void {\n try {\n const sqlite =\n this.options.driver || PlatformTools.load(\"better-sqlite3\")\n this.sqlite = sqlite\n } catch (e) {\n throw new DriverPackageNotInstalledError(\"SQLite\", \"better-sqlite3\")\n }\n }\n\n /**\n * Auto creates database directory if it does not exist.\n */\n protected async createDatabaseDirectory(dbPath: string): Promise<void> {\n await mkdirp(dbPath)\n }\n\n /**\n * Performs the attaching of the database files. The attachedDatabase should have been populated during calls to #buildTableName\n * during EntityMetadata production (see EntityMetadata#buildTablePath)\n *\n * https://sqlite.org/lang_attach.html\n */\n protected async attachDatabases() {\n // @todo - possibly check number of databases (but unqueriable at runtime sadly) - https://www.sqlite.org/limits.html#max_attached\n for await (const {\n attachHandle,\n attachFilepathAbsolute,\n } of Object.values(this.attachedDatabases)) {\n await this.createDatabaseDirectory(\n path.dirname(attachFilepathAbsolute),\n )\n await this.connection.query(\n `ATTACH \"${attachFilepathAbsolute}\" AS \"${attachHandle}\"`,\n )\n }\n }\n\n protected getMainDatabasePath(): string {\n const optionsDb = this.options.database\n return path.dirname(\n isAbsolute(optionsDb)\n ? optionsDb\n : path.join(this.options.baseDirectory!, optionsDb),\n )\n }\n}\n"],"sourceRoot":"../.."}
|
|
@@ -52,6 +52,13 @@ export declare class SapQueryRunner extends BaseQueryRunner implements QueryRunn
|
|
|
52
52
|
* Error will be thrown if transaction was not started.
|
|
53
53
|
*/
|
|
54
54
|
rollbackTransaction(): Promise<void>;
|
|
55
|
+
/**
|
|
56
|
+
* @description Switches on/off AUTOCOMMIT mode
|
|
57
|
+
* @link https://help.sap.com/docs/HANA_SERVICE_CF/7c78579ce9b14a669c1f3295b0d8ca16/d538d11053bd4f3f847ec5ce817a3d4c.html?locale=en-US
|
|
58
|
+
*/
|
|
59
|
+
setAutoCommit(options: {
|
|
60
|
+
status: "on" | "off";
|
|
61
|
+
}): Promise<void>;
|
|
55
62
|
/**
|
|
56
63
|
* Executes a given SQL query.
|
|
57
64
|
*/
|
|
@@ -17,6 +17,7 @@ import { QueryResult } from "../../query-runner/QueryResult";
|
|
|
17
17
|
import { QueryLock } from "../../query-runner/QueryLock";
|
|
18
18
|
import { MetadataTableType } from "../types/MetadataTableType";
|
|
19
19
|
import { InstanceChecker } from "../../util/InstanceChecker";
|
|
20
|
+
import { promisify } from "util";
|
|
20
21
|
/**
|
|
21
22
|
* Runs queries on a single SQL Server database connection.
|
|
22
23
|
*/
|
|
@@ -67,6 +68,11 @@ export class SapQueryRunner extends BaseQueryRunner {
|
|
|
67
68
|
throw new TransactionAlreadyStartedError();
|
|
68
69
|
await this.broadcaster.broadcast("BeforeTransactionStart");
|
|
69
70
|
this.isTransactionActive = true;
|
|
71
|
+
/**
|
|
72
|
+
* Disable AUTOCOMMIT while running transaction.
|
|
73
|
+
* Otherwise, COMMIT/ROLLBACK doesn't work in autocommit mode.
|
|
74
|
+
*/
|
|
75
|
+
await this.setAutoCommit({ status: "off" });
|
|
70
76
|
if (isolationLevel) {
|
|
71
77
|
await this.query(`SET TRANSACTION ISOLATION LEVEL ${isolationLevel || ""}`);
|
|
72
78
|
}
|
|
@@ -84,6 +90,7 @@ export class SapQueryRunner extends BaseQueryRunner {
|
|
|
84
90
|
await this.broadcaster.broadcast("BeforeTransactionCommit");
|
|
85
91
|
await this.query("COMMIT");
|
|
86
92
|
this.isTransactionActive = false;
|
|
93
|
+
await this.setAutoCommit({ status: "on" });
|
|
87
94
|
await this.broadcaster.broadcast("AfterTransactionCommit");
|
|
88
95
|
}
|
|
89
96
|
/**
|
|
@@ -98,8 +105,25 @@ export class SapQueryRunner extends BaseQueryRunner {
|
|
|
98
105
|
await this.broadcaster.broadcast("BeforeTransactionRollback");
|
|
99
106
|
await this.query("ROLLBACK");
|
|
100
107
|
this.isTransactionActive = false;
|
|
108
|
+
await this.setAutoCommit({ status: "on" });
|
|
101
109
|
await this.broadcaster.broadcast("AfterTransactionRollback");
|
|
102
110
|
}
|
|
111
|
+
/**
|
|
112
|
+
* @description Switches on/off AUTOCOMMIT mode
|
|
113
|
+
* @link https://help.sap.com/docs/HANA_SERVICE_CF/7c78579ce9b14a669c1f3295b0d8ca16/d538d11053bd4f3f847ec5ce817a3d4c.html?locale=en-US
|
|
114
|
+
*/
|
|
115
|
+
async setAutoCommit(options) {
|
|
116
|
+
const connection = await this.connect();
|
|
117
|
+
const execute = promisify(connection.exec.bind(connection));
|
|
118
|
+
connection.setAutoCommit(options.status === "on");
|
|
119
|
+
const query = `SET TRANSACTION AUTOCOMMIT DDL ${options.status.toUpperCase()};`;
|
|
120
|
+
try {
|
|
121
|
+
await execute(query);
|
|
122
|
+
}
|
|
123
|
+
catch (error) {
|
|
124
|
+
throw new QueryFailedError(query, [], error);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
103
127
|
/**
|
|
104
128
|
* Executes a given SQL query.
|
|
105
129
|
*/
|
|
@@ -111,8 +135,6 @@ export class SapQueryRunner extends BaseQueryRunner {
|
|
|
111
135
|
const result = new QueryResult();
|
|
112
136
|
try {
|
|
113
137
|
const databaseConnection = await this.connect();
|
|
114
|
-
// we disable autocommit because ROLLBACK does not work in autocommit mode
|
|
115
|
-
databaseConnection.setAutoCommit(!this.isTransactionActive);
|
|
116
138
|
this.driver.connection.logger.logQuery(query, parameters, this);
|
|
117
139
|
const queryStartTime = +new Date();
|
|
118
140
|
const isInsertQuery = query.substr(0, 11) === "INSERT INTO";
|