typeorm 0.3.23-dev.184f463 → 0.3.23-dev.24a0369
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.js +1 -1
- package/browser/cache/DbQueryResultCache.js.map +1 -1
- package/browser/cache/RedisQueryResultCache.js +1 -1
- package/browser/cache/RedisQueryResultCache.js.map +1 -1
- package/browser/data-source/BaseDataSourceOptions.d.ts +1 -1
- package/browser/data-source/BaseDataSourceOptions.js.map +1 -1
- package/browser/driver/better-sqlite3/BetterSqlite3QueryRunner.js +2 -2
- package/browser/driver/better-sqlite3/BetterSqlite3QueryRunner.js.map +1 -1
- package/browser/driver/cockroachdb/CockroachQueryRunner.js +2 -2
- package/browser/driver/cockroachdb/CockroachQueryRunner.js.map +1 -1
- package/browser/driver/cordova/CordovaQueryRunner.js +2 -2
- package/browser/driver/cordova/CordovaQueryRunner.js.map +1 -1
- package/browser/driver/expo/ExpoQueryRunner.js +2 -2
- package/browser/driver/expo/ExpoQueryRunner.js.map +1 -1
- package/browser/driver/expo/legacy/ExpoLegacyQueryRunner.js +2 -2
- package/browser/driver/expo/legacy/ExpoLegacyQueryRunner.js.map +1 -1
- package/browser/driver/mysql/MysqlQueryRunner.js +2 -2
- package/browser/driver/mysql/MysqlQueryRunner.js.map +1 -1
- package/browser/driver/nativescript/NativescriptQueryRunner.js +2 -2
- package/browser/driver/nativescript/NativescriptQueryRunner.js.map +1 -1
- package/browser/driver/oracle/OracleQueryRunner.js +2 -2
- package/browser/driver/oracle/OracleQueryRunner.js.map +1 -1
- package/browser/driver/postgres/PostgresQueryRunner.js +2 -2
- package/browser/driver/postgres/PostgresQueryRunner.js.map +1 -1
- package/browser/driver/react-native/ReactNativeQueryRunner.js +2 -2
- package/browser/driver/react-native/ReactNativeQueryRunner.js.map +1 -1
- package/browser/driver/sap/SapQueryRunner.js +2 -2
- package/browser/driver/sap/SapQueryRunner.js.map +1 -1
- package/browser/driver/spanner/SpannerQueryRunner.js +4 -4
- package/browser/driver/spanner/SpannerQueryRunner.js.map +1 -1
- package/browser/driver/sqlite/SqliteQueryRunner.js +2 -2
- package/browser/driver/sqlite/SqliteQueryRunner.js.map +1 -1
- package/browser/driver/sqljs/SqljsQueryRunner.js +2 -2
- package/browser/driver/sqljs/SqljsQueryRunner.js.map +1 -1
- package/browser/driver/sqlserver/SqlServerQueryRunner.js +2 -2
- package/browser/driver/sqlserver/SqlServerQueryRunner.js.map +1 -1
- package/browser/driver/types/GeoJsonTypes.d.ts +20 -15
- package/browser/driver/types/GeoJsonTypes.js.map +1 -1
- package/browser/index.d.ts +1 -0
- package/browser/index.js +1 -0
- package/browser/index.js.map +1 -1
- package/browser/logger/AbstractLogger.d.ts +1 -1
- package/browser/logger/AbstractLogger.js +5 -1
- package/browser/logger/AbstractLogger.js.map +1 -1
- package/browser/logger/FormattedConsoleLogger.d.ts +13 -0
- package/browser/logger/FormattedConsoleLogger.js +55 -0
- package/browser/logger/FormattedConsoleLogger.js.map +1 -0
- package/browser/logger/Logger.d.ts +1 -0
- package/browser/logger/Logger.js.map +1 -1
- package/browser/logger/LoggerFactory.d.ts +1 -1
- package/browser/logger/LoggerFactory.js +3 -0
- package/browser/logger/LoggerFactory.js.map +1 -1
- package/browser/platform/PlatformTools.d.ts +5 -0
- package/browser/platform/PlatformTools.js +16 -0
- package/browser/platform/PlatformTools.js.map +1 -1
- package/browser/query-builder/SelectQueryBuilder.js +1 -1
- package/browser/query-builder/SelectQueryBuilder.js.map +1 -1
- package/browser/repository/MongoRepository.d.ts +1 -1
- package/browser/repository/MongoRepository.js.map +1 -1
- package/cache/DbQueryResultCache.js +1 -1
- package/cache/DbQueryResultCache.js.map +1 -1
- package/cache/RedisQueryResultCache.js +1 -1
- package/cache/RedisQueryResultCache.js.map +1 -1
- package/data-source/BaseDataSourceOptions.d.ts +1 -1
- package/data-source/BaseDataSourceOptions.js.map +1 -1
- package/driver/better-sqlite3/BetterSqlite3QueryRunner.js +2 -2
- package/driver/better-sqlite3/BetterSqlite3QueryRunner.js.map +1 -1
- package/driver/cockroachdb/CockroachQueryRunner.js +2 -2
- package/driver/cockroachdb/CockroachQueryRunner.js.map +1 -1
- package/driver/cordova/CordovaQueryRunner.js +2 -2
- package/driver/cordova/CordovaQueryRunner.js.map +1 -1
- package/driver/expo/ExpoQueryRunner.js +2 -2
- package/driver/expo/ExpoQueryRunner.js.map +1 -1
- package/driver/expo/legacy/ExpoLegacyQueryRunner.js +2 -2
- package/driver/expo/legacy/ExpoLegacyQueryRunner.js.map +1 -1
- package/driver/mysql/MysqlQueryRunner.js +2 -2
- package/driver/mysql/MysqlQueryRunner.js.map +1 -1
- package/driver/nativescript/NativescriptQueryRunner.js +2 -2
- package/driver/nativescript/NativescriptQueryRunner.js.map +1 -1
- package/driver/oracle/OracleQueryRunner.js +2 -2
- package/driver/oracle/OracleQueryRunner.js.map +1 -1
- package/driver/postgres/PostgresQueryRunner.js +2 -2
- package/driver/postgres/PostgresQueryRunner.js.map +1 -1
- package/driver/react-native/ReactNativeQueryRunner.js +2 -2
- package/driver/react-native/ReactNativeQueryRunner.js.map +1 -1
- package/driver/sap/SapQueryRunner.js +2 -2
- package/driver/sap/SapQueryRunner.js.map +1 -1
- package/driver/spanner/SpannerQueryRunner.js +4 -4
- package/driver/spanner/SpannerQueryRunner.js.map +1 -1
- package/driver/sqlite/SqliteQueryRunner.js +2 -2
- package/driver/sqlite/SqliteQueryRunner.js.map +1 -1
- package/driver/sqljs/SqljsQueryRunner.js +2 -2
- package/driver/sqljs/SqljsQueryRunner.js.map +1 -1
- package/driver/sqlserver/SqlServerQueryRunner.js +2 -2
- package/driver/sqlserver/SqlServerQueryRunner.js.map +1 -1
- package/driver/types/GeoJsonTypes.d.ts +20 -15
- package/driver/types/GeoJsonTypes.js.map +1 -1
- package/index.d.ts +1 -0
- package/index.js +1 -0
- package/index.js.map +1 -1
- package/index.mjs +2 -0
- package/logger/AbstractLogger.d.ts +1 -1
- package/logger/AbstractLogger.js +5 -1
- package/logger/AbstractLogger.js.map +1 -1
- package/logger/FormattedConsoleLogger.d.ts +13 -0
- package/logger/FormattedConsoleLogger.js +59 -0
- package/logger/FormattedConsoleLogger.js.map +1 -0
- package/logger/Logger.d.ts +1 -0
- package/logger/Logger.js.map +1 -1
- package/logger/LoggerFactory.d.ts +1 -1
- package/logger/LoggerFactory.js +3 -0
- package/logger/LoggerFactory.js.map +1 -1
- package/package.json +1 -1
- package/platform/PlatformTools.d.ts +5 -0
- package/platform/PlatformTools.js +16 -0
- package/platform/PlatformTools.js.map +1 -1
- package/query-builder/SelectQueryBuilder.js +1 -1
- package/query-builder/SelectQueryBuilder.js.map +1 -1
- package/repository/MongoRepository.d.ts +1 -1
- package/repository/MongoRepository.js.map +1 -1
|
@@ -97,7 +97,7 @@ export declare class MongoRepository<Entity extends ObjectLiteral> extends Repos
|
|
|
97
97
|
/**
|
|
98
98
|
* Execute an aggregation framework pipeline against the collection.
|
|
99
99
|
*/
|
|
100
|
-
aggregate<R = any>(pipeline: ObjectLiteral[], options?: AggregateOptions): AggregationCursor<
|
|
100
|
+
aggregate<R = any>(pipeline: ObjectLiteral[], options?: AggregateOptions): AggregationCursor<R>;
|
|
101
101
|
/**
|
|
102
102
|
* Execute an aggregation framework pipeline against the collection.
|
|
103
103
|
* This returns modified version of cursor that transforms each result into Entity model.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../browser/src/repository/MongoRepository.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAA;AAKzC,OAAO,EAAE,YAAY,EAAE,MAAM,uBAAuB,CAAA;AA2CpD;;GAEG;AACH,MAAM,OAAO,eAEX,SAAQ,UAAkB;IAUxB,4EAA4E;IAC5E,qBAAqB;IACrB,4EAA4E;IAE5E;;;OAGG;IACH,KAAK,CAAC,KAAa,EAAE,UAAkB;QACnC,MAAM,IAAI,YAAY,CAAC,sCAAsC,CAAC,CAAA;IAClE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G;IACH,qBAAqB,CAAC,OAA4B;QAC9C,OAAO,IAAI,CAAC,OAAO,CAAC,qBAAqB,CACrC,IAAI,CAAC,QAAQ,CAAC,SAAS,EACvB,OAAO,CACV,CAAA;IACL,CAAC;IAED;;OAEG;IACH,MAAM,CACF,OAAe,EACf,OAAkC;QAElC,OAAO,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC,SAAS,EAAE,OAAO,EAAE,OAAO,CAAC,CAAA;IACzE,CAAC;IAED;;OAEG;IACH,UAAU,CACN,KAAoB,EACpB,GAAkB,EAClB,OAAwB;QAExB,OAAO,IAAI,CAAC,OAAO,CAAC,UAAU,CAC1B,IAAI,CAAC,QAAQ,CAAC,SAAS,EACvB,KAAK,EACL,GAAG,EACH,OAAO,CACV,CAAA;IACL,CAAC;IAED;;OAEG;IACH,KAAK,CAAC,OAA0B;QAC5B,OAAO,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC,QAAQ,CAAC,SAAS,EAAE,OAAO,CAAC,CAAA;IAC/D,CAAC;IAED;;OAEG;IACH,UAAU,CACN,KAAoB,EACpB,MAA8B,EAC9B,OAAuB;QAEvB,OAAO,IAAI,CAAC,OAAO,CAAC,UAAU,CAC1B,IAAI,CAAC,QAAQ,CAAC,SAAS,EACvB,KAAK,EACL,MAAM,EACN,OAAO,CACV,CAAA;IACL,CAAC;IAED;;OAEG;IACH,SAAS,CACL,KAAoB,EACpB,MAA8B,EAC9B,OAAuB;QAEvB,OAAO,IAAI,CAAC,OAAO,CAAC,SAAS,CACzB,IAAI,CAAC,QAAQ,CAAC,SAAS,EACvB,KAAK,EACL,MAAM,EACN,OAAO,CACV,CAAA;IACL,CAAC;CACJ","file":"MongoRepository.js","sourcesContent":["import { ObjectLiteral } from \"../common/ObjectLiteral\"\nimport { Repository } from \"./Repository\"\nimport { MongoFindManyOptions } from \"../find-options/mongodb/MongoFindManyOptions\"\nimport { MongoEntityManager } from \"../entity-manager/MongoEntityManager\"\nimport { QueryRunner } from \"../query-runner/QueryRunner\"\nimport { SelectQueryBuilder } from \"../query-builder/SelectQueryBuilder\"\nimport { TypeORMError } from \"../error/TypeORMError\"\nimport { MongoFindOneOptions } from \"../find-options/mongodb/MongoFindOneOptions\"\nimport { FindOneOptions } from \"../find-options/FindOneOptions\"\n\nimport {\n CreateIndexesOptions,\n ObjectId,\n ReplaceOptions,\n //\n AggregateOptions,\n AggregationCursor,\n AnyBulkWriteOperation,\n BulkWriteOptions,\n BulkWriteResult,\n Collection,\n CollStats,\n CollStatsOptions,\n CommandOperationOptions,\n CountOptions,\n DeleteOptions,\n DeleteResult,\n Document,\n Filter,\n FilterOperators,\n FindCursor,\n FindOneAndDeleteOptions,\n FindOneAndReplaceOptions,\n FindOneAndUpdateOptions,\n IndexDescription,\n InsertManyResult,\n InsertOneOptions,\n InsertOneResult,\n ListIndexesCursor,\n ListIndexesOptions,\n OrderedBulkOperation,\n UnorderedBulkOperation,\n UpdateFilter,\n UpdateOptions,\n UpdateResult,\n CountDocumentsOptions,\n} from \"../driver/mongodb/typings\"\nimport { FindManyOptions } from \"../find-options/FindManyOptions\"\n\n/**\n * Repository used to manage mongodb documents of a single entity type.\n */\nexport class MongoRepository<\n Entity extends ObjectLiteral,\n> extends Repository<Entity> {\n // -------------------------------------------------------------------------\n // Public Properties\n // -------------------------------------------------------------------------\n\n /**\n * Entity Manager used by this repository.\n */\n readonly manager: MongoEntityManager\n\n // -------------------------------------------------------------------------\n // Overridden Methods\n // -------------------------------------------------------------------------\n\n /**\n * Raw SQL query execution is not supported by MongoDB.\n * Calling this method will return an error.\n */\n query(query: string, parameters?: any[]): Promise<any> {\n throw new TypeORMError(`Queries aren't supported by MongoDB.`)\n }\n\n /**\n * Using Query Builder with MongoDB is not supported yet.\n * Calling this method will return an error.\n */\n createQueryBuilder(\n alias: string,\n queryRunner?: QueryRunner,\n ): SelectQueryBuilder<Entity> {\n throw new TypeORMError(`Query Builder is not supported by MongoDB.`)\n }\n\n /**\n * Finds entities that match given find options or conditions.\n */\n find(\n options?:\n | FindManyOptions<Entity>\n | Partial<Entity>\n | FilterOperators<Entity>,\n ): Promise<Entity[]> {\n return this.manager.find(this.metadata.target, options)\n }\n\n /**\n * Finds entities that match given find options or conditions.\n */\n findBy(where: any): Promise<Entity[]> {\n return this.manager.findBy(this.metadata.target, where)\n }\n\n /**\n * Finds entities that match given find options or conditions.\n * Also counts all entities that match given conditions,\n * but ignores pagination settings (from and take options).\n */\n findAndCount(\n options?: MongoFindManyOptions<Entity>,\n ): Promise<[Entity[], number]> {\n return this.manager.findAndCount(this.metadata.target, options)\n }\n\n /**\n * Finds entities that match given find options or conditions.\n * Also counts all entities that match given conditions,\n * but ignores pagination settings (from and take options).\n */\n findAndCountBy(where: any): Promise<[Entity[], number]> {\n return this.manager.findAndCountBy(this.metadata.target, where)\n }\n\n /**\n * Finds entities by ids.\n * Optionally find options can be applied.\n *\n * @deprecated use `findBy` method instead in conjunction with `In` operator, for example:\n *\n * .findBy({\n * id: In([1, 2, 3])\n * })\n */\n findByIds(ids: any[], options?: any): Promise<Entity[]> {\n return this.manager.findByIds(this.metadata.target, ids, options)\n }\n\n /**\n * Finds first entity that matches given find options.\n */\n async findOne(\n options: MongoFindOneOptions<Entity>,\n ): Promise<Entity | null> {\n return this.manager.findOne(this.metadata.target, options)\n }\n\n /**\n * Finds first entity that matches given WHERE conditions.\n */\n async findOneBy(where: any): Promise<Entity | null> {\n return this.manager.findOneBy(this.metadata.target, where)\n }\n\n /**\n * Finds entity that matches given id.\n *\n * @deprecated use `findOneBy` method instead in conjunction with `In` operator, for example:\n *\n * .findOneBy({\n * id: 1 // where \"id\" is your primary column name\n * })\n */\n async findOneById(\n id: string | number | Date | ObjectId,\n ): Promise<Entity | null> {\n return this.manager.findOneById(this.metadata.target, id)\n }\n\n /**\n * Finds first entity by a given find options.\n * If entity was not found in the database - rejects with error.\n */\n async findOneOrFail(options: FindOneOptions<Entity>): Promise<Entity> {\n return this.manager.findOneOrFail(this.metadata.target, options)\n }\n\n /**\n * Finds first entity that matches given where condition.\n * If entity was not found in the database - rejects with error.\n */\n async findOneByOrFail(where: any): Promise<Entity> {\n return this.manager.findOneByOrFail(this.metadata.target, where)\n }\n\n /**\n * Creates a cursor for a query that can be used to iterate over results from MongoDB.\n */\n createCursor<T = any>(query?: Filter<Entity>): FindCursor<T> {\n return this.manager.createCursor(this.metadata.target, query)\n }\n\n /**\n * Creates a cursor for a query that can be used to iterate over results from MongoDB.\n * This returns modified version of cursor that transforms each result into Entity model.\n */\n createEntityCursor(query?: Filter<Entity>): FindCursor<Entity> {\n return this.manager.createEntityCursor(this.metadata.target, query)\n }\n\n /**\n * Execute an aggregation framework pipeline against the collection.\n */\n aggregate<R = any>(\n pipeline: ObjectLiteral[],\n options?: AggregateOptions,\n ): AggregationCursor<Entity> {\n return this.manager.aggregate<R>(\n this.metadata.target,\n pipeline,\n options,\n )\n }\n\n /**\n * Execute an aggregation framework pipeline against the collection.\n * This returns modified version of cursor that transforms each result into Entity model.\n */\n aggregateEntity(\n pipeline: ObjectLiteral[],\n options?: AggregateOptions,\n ): AggregationCursor<Entity> {\n return this.manager.aggregateEntity(\n this.metadata.target,\n pipeline,\n options,\n )\n }\n /**\n * Perform a bulkWrite operation without a fluent API.\n */\n bulkWrite(\n operations: AnyBulkWriteOperation[],\n options?: BulkWriteOptions,\n ): Promise<BulkWriteResult> {\n return this.manager.bulkWrite(this.metadata.target, operations, options)\n }\n\n /**\n * Count number of matching documents in the db to a query.\n */\n count(query?: ObjectLiteral, options?: CountOptions): Promise<number> {\n return this.manager.count(this.metadata.target, query || {}, options)\n }\n\n /**\n * Count number of matching documents in the db to a query.\n */\n countDocuments(\n query?: ObjectLiteral,\n options?: CountDocumentsOptions,\n ): Promise<number> {\n return this.manager.countDocuments(\n this.metadata.target,\n query || {},\n options,\n )\n }\n\n /**\n * Count number of matching documents in the db to a query.\n */\n countBy(query?: ObjectLiteral, options?: CountOptions): Promise<number> {\n return this.manager.countBy(this.metadata.target, query, options)\n }\n\n /**\n * Creates an index on the db and collection.\n */\n createCollectionIndex(\n fieldOrSpec: string | any,\n options?: CreateIndexesOptions,\n ): Promise<string> {\n return this.manager.createCollectionIndex(\n this.metadata.target,\n fieldOrSpec,\n options,\n )\n }\n\n /**\n * Creates multiple indexes in the collection, this method is only supported for MongoDB 2.6 or higher.\n * Earlier version of MongoDB will throw a command not supported error.\n * Index specifications are defined at http://docs.mongodb.org/manual/reference/command/createIndexes/.\n */\n createCollectionIndexes(indexSpecs: IndexDescription[]): Promise<string[]> {\n return this.manager.createCollectionIndexes(\n this.metadata.target,\n indexSpecs,\n )\n }\n\n /**\n * Delete multiple documents on MongoDB.\n */\n deleteMany(\n query: ObjectLiteral,\n options?: DeleteOptions,\n ): Promise<DeleteResult> {\n return this.manager.deleteMany(this.metadata.tableName, query, options)\n }\n\n /**\n * Delete a document on MongoDB.\n */\n deleteOne(\n query: ObjectLiteral,\n options?: DeleteOptions,\n ): Promise<DeleteResult> {\n return this.manager.deleteOne(this.metadata.tableName, query, options)\n }\n\n /**\n * The distinct command returns returns a list of distinct values for the given key across a collection.\n */\n distinct(\n key: string,\n query: ObjectLiteral,\n options?: CommandOperationOptions,\n ): Promise<any> {\n return this.manager.distinct(\n this.metadata.tableName,\n key,\n query,\n options,\n )\n }\n\n /**\n * Drops an index from this collection.\n */\n dropCollectionIndex(\n indexName: string,\n options?: CommandOperationOptions,\n ): Promise<any> {\n return this.manager.dropCollectionIndex(\n this.metadata.tableName,\n indexName,\n options,\n )\n }\n\n /**\n * Drops all indexes from the collection.\n */\n dropCollectionIndexes(): Promise<any> {\n return this.manager.dropCollectionIndexes(this.metadata.tableName)\n }\n\n /**\n * Find a document and delete it in one atomic operation, requires a write lock for the duration of the operation.\n */\n findOneAndDelete(\n query: ObjectLiteral,\n options?: FindOneAndDeleteOptions,\n ): Promise<Document | null> {\n return this.manager.findOneAndDelete(\n this.metadata.tableName,\n query,\n options,\n )\n }\n\n /**\n * Find a document and replace it in one atomic operation, requires a write lock for the duration of the operation.\n */\n findOneAndReplace(\n query: ObjectLiteral,\n replacement: Object,\n options?: FindOneAndReplaceOptions,\n ): Promise<Document | null> {\n return this.manager.findOneAndReplace(\n this.metadata.tableName,\n query,\n replacement,\n options,\n )\n }\n\n /**\n * Find a document and update it in one atomic operation, requires a write lock for the duration of the operation.\n */\n findOneAndUpdate(\n query: ObjectLiteral,\n update: Object,\n options?: FindOneAndUpdateOptions,\n ): Promise<Document | null> {\n return this.manager.findOneAndUpdate(\n this.metadata.tableName,\n query,\n update,\n options,\n )\n }\n\n /**\n * Retrieve all the indexes on the collection.\n */\n collectionIndexes(): Promise<any> {\n return this.manager.collectionIndexes(this.metadata.tableName)\n }\n\n /**\n * Retrieve all the indexes on the collection.\n */\n collectionIndexExists(indexes: string | string[]): Promise<boolean> {\n return this.manager.collectionIndexExists(\n this.metadata.tableName,\n indexes,\n )\n }\n\n /**\n * Retrieves this collections index info.\n */\n collectionIndexInformation(options?: { full: boolean }): Promise<any> {\n return this.manager.collectionIndexInformation(\n this.metadata.tableName,\n options,\n )\n }\n\n /**\n * Initiate an In order bulk write operation, operations will be serially executed in the order they are added, creating a new operation for each switch in types.\n */\n initializeOrderedBulkOp(options?: BulkWriteOptions): OrderedBulkOperation {\n return this.manager.initializeOrderedBulkOp(\n this.metadata.tableName,\n options,\n )\n }\n\n /**\n * Initiate a Out of order batch write operation. All operations will be buffered into insert/update/remove commands executed out of order.\n */\n initializeUnorderedBulkOp(\n options?: BulkWriteOptions,\n ): UnorderedBulkOperation {\n return this.manager.initializeUnorderedBulkOp(\n this.metadata.tableName,\n options,\n )\n }\n\n /**\n * Inserts an array of documents into MongoDB.\n */\n insertMany(\n docs: ObjectLiteral[],\n options?: BulkWriteOptions,\n ): Promise<InsertManyResult<Document>> {\n return this.manager.insertMany(this.metadata.tableName, docs, options)\n }\n\n /**\n * Inserts a single document into MongoDB.\n */\n insertOne(\n doc: ObjectLiteral,\n options?: InsertOneOptions,\n ): Promise<InsertOneResult> {\n return this.manager.insertOne(this.metadata.tableName, doc, options)\n }\n\n /**\n * Returns if the collection is a capped collection.\n */\n isCapped(): Promise<any> {\n return this.manager.isCapped(this.metadata.tableName)\n }\n\n /**\n * Get the list of all indexes information for the collection.\n */\n listCollectionIndexes(options?: ListIndexesOptions): ListIndexesCursor {\n return this.manager.listCollectionIndexes(\n this.metadata.tableName,\n options,\n )\n }\n\n /**\n * Reindex all indexes on the collection Warning: reIndex is a blocking operation (indexes are rebuilt in the foreground) and will be slow for large collections.\n */\n rename(\n newName: string,\n options?: { dropTarget?: boolean },\n ): Promise<Collection<Document>> {\n return this.manager.rename(this.metadata.tableName, newName, options)\n }\n\n /**\n * Replace a document on MongoDB.\n */\n replaceOne(\n query: ObjectLiteral,\n doc: ObjectLiteral,\n options?: ReplaceOptions,\n ): Promise<Document | UpdateResult> {\n return this.manager.replaceOne(\n this.metadata.tableName,\n query,\n doc,\n options,\n )\n }\n\n /**\n * Get all the collection statistics.\n */\n stats(options?: CollStatsOptions): Promise<CollStats> {\n return this.manager.stats(this.metadata.tableName, options)\n }\n\n /**\n * Update multiple documents on MongoDB.\n */\n updateMany(\n query: ObjectLiteral,\n update: UpdateFilter<Document>,\n options?: UpdateOptions,\n ): Promise<Document | UpdateResult> {\n return this.manager.updateMany(\n this.metadata.tableName,\n query,\n update,\n options,\n )\n }\n\n /**\n * Update a single document on MongoDB.\n */\n updateOne(\n query: ObjectLiteral,\n update: UpdateFilter<Document>,\n options?: UpdateOptions,\n ): Promise<Document | UpdateResult> {\n return this.manager.updateOne(\n this.metadata.tableName,\n query,\n update,\n options,\n )\n }\n}\n"],"sourceRoot":".."}
|
|
1
|
+
{"version":3,"sources":["../browser/src/repository/MongoRepository.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAA;AAKzC,OAAO,EAAE,YAAY,EAAE,MAAM,uBAAuB,CAAA;AA2CpD;;GAEG;AACH,MAAM,OAAO,e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L,CAAC;CACJ","file":"MongoRepository.js","sourcesContent":["import { ObjectLiteral } from \"../common/ObjectLiteral\"\nimport { Repository } from \"./Repository\"\nimport { MongoFindManyOptions } from \"../find-options/mongodb/MongoFindManyOptions\"\nimport { MongoEntityManager } from \"../entity-manager/MongoEntityManager\"\nimport { QueryRunner } from \"../query-runner/QueryRunner\"\nimport { SelectQueryBuilder } from \"../query-builder/SelectQueryBuilder\"\nimport { TypeORMError } from \"../error/TypeORMError\"\nimport { MongoFindOneOptions } from \"../find-options/mongodb/MongoFindOneOptions\"\nimport { FindOneOptions } from \"../find-options/FindOneOptions\"\n\nimport {\n CreateIndexesOptions,\n ObjectId,\n ReplaceOptions,\n //\n AggregateOptions,\n AggregationCursor,\n AnyBulkWriteOperation,\n BulkWriteOptions,\n BulkWriteResult,\n Collection,\n CollStats,\n CollStatsOptions,\n CommandOperationOptions,\n CountOptions,\n DeleteOptions,\n DeleteResult,\n Document,\n Filter,\n FilterOperators,\n FindCursor,\n FindOneAndDeleteOptions,\n FindOneAndReplaceOptions,\n FindOneAndUpdateOptions,\n IndexDescription,\n InsertManyResult,\n InsertOneOptions,\n InsertOneResult,\n ListIndexesCursor,\n ListIndexesOptions,\n OrderedBulkOperation,\n UnorderedBulkOperation,\n UpdateFilter,\n UpdateOptions,\n UpdateResult,\n CountDocumentsOptions,\n} from \"../driver/mongodb/typings\"\nimport { FindManyOptions } from \"../find-options/FindManyOptions\"\n\n/**\n * Repository used to manage mongodb documents of a single entity type.\n */\nexport class MongoRepository<\n Entity extends ObjectLiteral,\n> extends Repository<Entity> {\n // -------------------------------------------------------------------------\n // Public Properties\n // -------------------------------------------------------------------------\n\n /**\n * Entity Manager used by this repository.\n */\n readonly manager: MongoEntityManager\n\n // -------------------------------------------------------------------------\n // Overridden Methods\n // -------------------------------------------------------------------------\n\n /**\n * Raw SQL query execution is not supported by MongoDB.\n * Calling this method will return an error.\n */\n query(query: string, parameters?: any[]): Promise<any> {\n throw new TypeORMError(`Queries aren't supported by MongoDB.`)\n }\n\n /**\n * Using Query Builder with MongoDB is not supported yet.\n * Calling this method will return an error.\n */\n createQueryBuilder(\n alias: string,\n queryRunner?: QueryRunner,\n ): SelectQueryBuilder<Entity> {\n throw new TypeORMError(`Query Builder is not supported by MongoDB.`)\n }\n\n /**\n * Finds entities that match given find options or conditions.\n */\n find(\n options?:\n | FindManyOptions<Entity>\n | Partial<Entity>\n | FilterOperators<Entity>,\n ): Promise<Entity[]> {\n return this.manager.find(this.metadata.target, options)\n }\n\n /**\n * Finds entities that match given find options or conditions.\n */\n findBy(where: any): Promise<Entity[]> {\n return this.manager.findBy(this.metadata.target, where)\n }\n\n /**\n * Finds entities that match given find options or conditions.\n * Also counts all entities that match given conditions,\n * but ignores pagination settings (from and take options).\n */\n findAndCount(\n options?: MongoFindManyOptions<Entity>,\n ): Promise<[Entity[], number]> {\n return this.manager.findAndCount(this.metadata.target, options)\n }\n\n /**\n * Finds entities that match given find options or conditions.\n * Also counts all entities that match given conditions,\n * but ignores pagination settings (from and take options).\n */\n findAndCountBy(where: any): Promise<[Entity[], number]> {\n return this.manager.findAndCountBy(this.metadata.target, where)\n }\n\n /**\n * Finds entities by ids.\n * Optionally find options can be applied.\n *\n * @deprecated use `findBy` method instead in conjunction with `In` operator, for example:\n *\n * .findBy({\n * id: In([1, 2, 3])\n * })\n */\n findByIds(ids: any[], options?: any): Promise<Entity[]> {\n return this.manager.findByIds(this.metadata.target, ids, options)\n }\n\n /**\n * Finds first entity that matches given find options.\n */\n async findOne(\n options: MongoFindOneOptions<Entity>,\n ): Promise<Entity | null> {\n return this.manager.findOne(this.metadata.target, options)\n }\n\n /**\n * Finds first entity that matches given WHERE conditions.\n */\n async findOneBy(where: any): Promise<Entity | null> {\n return this.manager.findOneBy(this.metadata.target, where)\n }\n\n /**\n * Finds entity that matches given id.\n *\n * @deprecated use `findOneBy` method instead in conjunction with `In` operator, for example:\n *\n * .findOneBy({\n * id: 1 // where \"id\" is your primary column name\n * })\n */\n async findOneById(\n id: string | number | Date | ObjectId,\n ): Promise<Entity | null> {\n return this.manager.findOneById(this.metadata.target, id)\n }\n\n /**\n * Finds first entity by a given find options.\n * If entity was not found in the database - rejects with error.\n */\n async findOneOrFail(options: FindOneOptions<Entity>): Promise<Entity> {\n return this.manager.findOneOrFail(this.metadata.target, options)\n }\n\n /**\n * Finds first entity that matches given where condition.\n * If entity was not found in the database - rejects with error.\n */\n async findOneByOrFail(where: any): Promise<Entity> {\n return this.manager.findOneByOrFail(this.metadata.target, where)\n }\n\n /**\n * Creates a cursor for a query that can be used to iterate over results from MongoDB.\n */\n createCursor<T = any>(query?: Filter<Entity>): FindCursor<T> {\n return this.manager.createCursor(this.metadata.target, query)\n }\n\n /**\n * Creates a cursor for a query that can be used to iterate over results from MongoDB.\n * This returns modified version of cursor that transforms each result into Entity model.\n */\n createEntityCursor(query?: Filter<Entity>): FindCursor<Entity> {\n return this.manager.createEntityCursor(this.metadata.target, query)\n }\n\n /**\n * Execute an aggregation framework pipeline against the collection.\n */\n aggregate<R = any>(\n pipeline: ObjectLiteral[],\n options?: AggregateOptions,\n ): AggregationCursor<R> {\n return this.manager.aggregate<R>(\n this.metadata.target,\n pipeline,\n options,\n )\n }\n\n /**\n * Execute an aggregation framework pipeline against the collection.\n * This returns modified version of cursor that transforms each result into Entity model.\n */\n aggregateEntity(\n pipeline: ObjectLiteral[],\n options?: AggregateOptions,\n ): AggregationCursor<Entity> {\n return this.manager.aggregateEntity(\n this.metadata.target,\n pipeline,\n options,\n )\n }\n /**\n * Perform a bulkWrite operation without a fluent API.\n */\n bulkWrite(\n operations: AnyBulkWriteOperation[],\n options?: BulkWriteOptions,\n ): Promise<BulkWriteResult> {\n return this.manager.bulkWrite(this.metadata.target, operations, options)\n }\n\n /**\n * Count number of matching documents in the db to a query.\n */\n count(query?: ObjectLiteral, options?: CountOptions): Promise<number> {\n return this.manager.count(this.metadata.target, query || {}, options)\n }\n\n /**\n * Count number of matching documents in the db to a query.\n */\n countDocuments(\n query?: ObjectLiteral,\n options?: CountDocumentsOptions,\n ): Promise<number> {\n return this.manager.countDocuments(\n this.metadata.target,\n query || {},\n options,\n )\n }\n\n /**\n * Count number of matching documents in the db to a query.\n */\n countBy(query?: ObjectLiteral, options?: CountOptions): Promise<number> {\n return this.manager.countBy(this.metadata.target, query, options)\n }\n\n /**\n * Creates an index on the db and collection.\n */\n createCollectionIndex(\n fieldOrSpec: string | any,\n options?: CreateIndexesOptions,\n ): Promise<string> {\n return this.manager.createCollectionIndex(\n this.metadata.target,\n fieldOrSpec,\n options,\n )\n }\n\n /**\n * Creates multiple indexes in the collection, this method is only supported for MongoDB 2.6 or higher.\n * Earlier version of MongoDB will throw a command not supported error.\n * Index specifications are defined at http://docs.mongodb.org/manual/reference/command/createIndexes/.\n */\n createCollectionIndexes(indexSpecs: IndexDescription[]): Promise<string[]> {\n return this.manager.createCollectionIndexes(\n this.metadata.target,\n indexSpecs,\n )\n }\n\n /**\n * Delete multiple documents on MongoDB.\n */\n deleteMany(\n query: ObjectLiteral,\n options?: DeleteOptions,\n ): Promise<DeleteResult> {\n return this.manager.deleteMany(this.metadata.tableName, query, options)\n }\n\n /**\n * Delete a document on MongoDB.\n */\n deleteOne(\n query: ObjectLiteral,\n options?: DeleteOptions,\n ): Promise<DeleteResult> {\n return this.manager.deleteOne(this.metadata.tableName, query, options)\n }\n\n /**\n * The distinct command returns returns a list of distinct values for the given key across a collection.\n */\n distinct(\n key: string,\n query: ObjectLiteral,\n options?: CommandOperationOptions,\n ): Promise<any> {\n return this.manager.distinct(\n this.metadata.tableName,\n key,\n query,\n options,\n )\n }\n\n /**\n * Drops an index from this collection.\n */\n dropCollectionIndex(\n indexName: string,\n options?: CommandOperationOptions,\n ): Promise<any> {\n return this.manager.dropCollectionIndex(\n this.metadata.tableName,\n indexName,\n options,\n )\n }\n\n /**\n * Drops all indexes from the collection.\n */\n dropCollectionIndexes(): Promise<any> {\n return this.manager.dropCollectionIndexes(this.metadata.tableName)\n }\n\n /**\n * Find a document and delete it in one atomic operation, requires a write lock for the duration of the operation.\n */\n findOneAndDelete(\n query: ObjectLiteral,\n options?: FindOneAndDeleteOptions,\n ): Promise<Document | null> {\n return this.manager.findOneAndDelete(\n this.metadata.tableName,\n query,\n options,\n )\n }\n\n /**\n * Find a document and replace it in one atomic operation, requires a write lock for the duration of the operation.\n */\n findOneAndReplace(\n query: ObjectLiteral,\n replacement: Object,\n options?: FindOneAndReplaceOptions,\n ): Promise<Document | null> {\n return this.manager.findOneAndReplace(\n this.metadata.tableName,\n query,\n replacement,\n options,\n )\n }\n\n /**\n * Find a document and update it in one atomic operation, requires a write lock for the duration of the operation.\n */\n findOneAndUpdate(\n query: ObjectLiteral,\n update: Object,\n options?: FindOneAndUpdateOptions,\n ): Promise<Document | null> {\n return this.manager.findOneAndUpdate(\n this.metadata.tableName,\n query,\n update,\n options,\n )\n }\n\n /**\n * Retrieve all the indexes on the collection.\n */\n collectionIndexes(): Promise<any> {\n return this.manager.collectionIndexes(this.metadata.tableName)\n }\n\n /**\n * Retrieve all the indexes on the collection.\n */\n collectionIndexExists(indexes: string | string[]): Promise<boolean> {\n return this.manager.collectionIndexExists(\n this.metadata.tableName,\n indexes,\n )\n }\n\n /**\n * Retrieves this collections index info.\n */\n collectionIndexInformation(options?: { full: boolean }): Promise<any> {\n return this.manager.collectionIndexInformation(\n this.metadata.tableName,\n options,\n )\n }\n\n /**\n * Initiate an In order bulk write operation, operations will be serially executed in the order they are added, creating a new operation for each switch in types.\n */\n initializeOrderedBulkOp(options?: BulkWriteOptions): OrderedBulkOperation {\n return this.manager.initializeOrderedBulkOp(\n this.metadata.tableName,\n options,\n )\n }\n\n /**\n * Initiate a Out of order batch write operation. All operations will be buffered into insert/update/remove commands executed out of order.\n */\n initializeUnorderedBulkOp(\n options?: BulkWriteOptions,\n ): UnorderedBulkOperation {\n return this.manager.initializeUnorderedBulkOp(\n this.metadata.tableName,\n options,\n )\n }\n\n /**\n * Inserts an array of documents into MongoDB.\n */\n insertMany(\n docs: ObjectLiteral[],\n options?: BulkWriteOptions,\n ): Promise<InsertManyResult<Document>> {\n return this.manager.insertMany(this.metadata.tableName, docs, options)\n }\n\n /**\n * Inserts a single document into MongoDB.\n */\n insertOne(\n doc: ObjectLiteral,\n options?: InsertOneOptions,\n ): Promise<InsertOneResult> {\n return this.manager.insertOne(this.metadata.tableName, doc, options)\n }\n\n /**\n * Returns if the collection is a capped collection.\n */\n isCapped(): Promise<any> {\n return this.manager.isCapped(this.metadata.tableName)\n }\n\n /**\n * Get the list of all indexes information for the collection.\n */\n listCollectionIndexes(options?: ListIndexesOptions): ListIndexesCursor {\n return this.manager.listCollectionIndexes(\n this.metadata.tableName,\n options,\n )\n }\n\n /**\n * Reindex all indexes on the collection Warning: reIndex is a blocking operation (indexes are rebuilt in the foreground) and will be slow for large collections.\n */\n rename(\n newName: string,\n options?: { dropTarget?: boolean },\n ): Promise<Collection<Document>> {\n return this.manager.rename(this.metadata.tableName, newName, options)\n }\n\n /**\n * Replace a document on MongoDB.\n */\n replaceOne(\n query: ObjectLiteral,\n doc: ObjectLiteral,\n options?: ReplaceOptions,\n ): Promise<Document | UpdateResult> {\n return this.manager.replaceOne(\n this.metadata.tableName,\n query,\n doc,\n options,\n )\n }\n\n /**\n * Get all the collection statistics.\n */\n stats(options?: CollStatsOptions): Promise<CollStats> {\n return this.manager.stats(this.metadata.tableName, options)\n }\n\n /**\n * Update multiple documents on MongoDB.\n */\n updateMany(\n query: ObjectLiteral,\n update: UpdateFilter<Document>,\n options?: UpdateOptions,\n ): Promise<Document | UpdateResult> {\n return this.manager.updateMany(\n this.metadata.tableName,\n query,\n update,\n options,\n )\n }\n\n /**\n * Update a single document on MongoDB.\n */\n updateOne(\n query: ObjectLiteral,\n update: UpdateFilter<Document>,\n options?: UpdateOptions,\n ): Promise<Document | UpdateResult> {\n return this.manager.updateOne(\n this.metadata.tableName,\n query,\n update,\n options,\n )\n }\n}\n"],"sourceRoot":".."}
|
|
@@ -1 +1 @@
|
|
|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Ac,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,YAAY,GAAgB,WAAW,IAAI,IAAI,CAAC,cAAc,EAAE,CAAA;QACtE,MAAM,OAAO,CAAC,GAAG,CACb,WAAW,CAAC,GAAG,CAAC,CAAC,UAAU,EAAE,EAAE;YAC3B,MAAM,EAAE,GAAG,YAAY,CAAC,OAAO,CAAC,kBAAkB,EAAE,CAAA;YACpD,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;QAED,IAAI,CAAC,WAAW,EAAE,CAAC;YACf,MAAM,YAAY,CAAC,OAAO,EAAE,CAAA;QAChC,CAAC;IACL,CAAC;IAED,4EAA4E;IAC5E,oBAAoB;IACpB,4EAA4E;IAE5E;;OAEG;IACO,cAAc,CAAC,WAAyB;QAC9C,IAAI,WAAW;YAAE,OAAO,WAAW,CAAA;QAEnC,OAAO,IAAI,CAAC,UAAU,CAAC,iBAAiB,EAAE,CAAA;IAC9C,CAAC;CACJ;AAlUD,gDAkUC","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 * Get data from cache.\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 .cache(false) // disable cache to avoid infinite loops when cache is alwaysEnable\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 .cache(false) // disable cache to avoid infinite loops when cache is alwaysEnable\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 .cache(false) // disable cache to avoid infinite loops when cache is alwaysEnable\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 const _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":".."}
|
|
1
|
+
{"version":3,"sources":["../../src/cache/DbQueryResultCache.ts"],"names":[],"mappings":";;;AAEA,uEAAmE;AAEnE,yDAAqD;AAGrD,+BAAmC;AAEnC;;GAEG;AACH,MAAa,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,OAA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ACb,CAAC;iBACD,OAAO,EAAE,CAAA;QAClB,CAAC,CAAC,CACL,CAAA;QAED,IAAI,CAAC,WAAW,EAAE,CAAC;YACf,MAAM,YAAY,CAAC,OAAO,EAAE,CAAA;QAChC,CAAC;IACL,CAAC;IAED,4EAA4E;IAC5E,oBAAoB;IACpB,4EAA4E;IAE5E;;OAEG;IACO,cAAc,CAAC,WAAyB;QAC9C,IAAI,WAAW;YAAE,OAAO,WAAW,CAAA;QAEnC,OAAO,IAAI,CAAC,UAAU,CAAC,iBAAiB,EAAE,CAAA;IAC9C,CAAC;CACJ;AAlUD,gDAkUC","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 * Get data from cache.\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 .cache(false) // disable cache to avoid infinite loops when cache is alwaysEnable\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 .cache(false) // disable cache to avoid infinite loops when cache is alwaysEnable\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 .cache(false) // disable cache to avoid infinite loops when cache is alwaysEnable\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 Date.now()\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 const _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":".."}
|
|
@@ -117,7 +117,7 @@ class RedisQueryResultCache {
|
|
|
117
117
|
* Checks if cache is expired or not.
|
|
118
118
|
*/
|
|
119
119
|
isExpired(savedCache) {
|
|
120
|
-
return savedCache.time + savedCache.duration <
|
|
120
|
+
return savedCache.time + savedCache.duration < Date.now();
|
|
121
121
|
}
|
|
122
122
|
/**
|
|
123
123
|
* Stores given query result in the cache.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/cache/RedisQueryResultCache.ts"],"names":[],"mappings":";;;AAEA,6DAAyD;AAGzD,wDAAoD;AAEpD;;GAEG;AACH,MAAa,qBAAqB;IAoB9B,4EAA4E;IAC5E,cAAc;IACd,4EAA4E;IAE5E,YACc,UAAsB,EAChC,UAAmD;QADzC,eAAU,GAAV,UAAU,CAAY;QAGhC,IAAI,CAAC,UAAU,GAAG,UAAU,CAAA;QAC5B,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,SAAS,EAAE,CAAA;IACjC,CAAC;IAED,4EAA4E;IAC5E,iBAAiB;IACjB,4EAA4E;IAE5E;;OAEG;IACH,KAAK,CAAC,OAAO;QACT,MAAM,YAAY,GAAQ,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC,KAAK,CAAA;QACvD,IAAI,IAAI,CAAC,UAAU,KAAK,OAAO,EAAE,CAAC;YAC9B,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,YAAY,CAAC;gBAClC,GAAG,YAAY,EAAE,OAAO;gBACxB,UAAU,EAAE,IAAI;aACnB,CAAC,CAAA;YACF,IACI,OAAO,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC,KAAK,KAAK,QAAQ;gBACjD,IAAI,CAAC,UAAU,CAAC,OAAO,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AC,CAAA;QACN,CAAC,CAAC,CAAA;IACN,CAAC;IAED;;OAEG;IACO,SAAS;QACf,IAAI,CAAC;YACD,IAAI,IAAI,CAAC,UAAU,KAAK,iBAAiB,EAAE,CAAC;gBACxC,OAAO,6BAAa,CAAC,IAAI,CAAC,SAAS,CAAC,CAAA;YACxC,CAAC;iBAAM,CAAC;gBACJ,OAAO,6BAAa,CAAC,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,CAAA;YAC9C,CAAC;QACL,CAAC;QAAC,OAAO,CAAC,EAAE,CAAC;YACT,MAAM,IAAI,2BAAY,CAClB,4BAA4B,IAAI,CAAC,UAAU,wCAAwC,IAAI,CAAC,UAAU,WAAW,CAChH,CAAA;QACL,CAAC;IACL,CAAC;CACJ;AAhPD,sDAgPC","file":"RedisQueryResultCache.js","sourcesContent":["import { QueryResultCache } from \"./QueryResultCache\"\nimport { QueryResultCacheOptions } from \"./QueryResultCacheOptions\"\nimport { PlatformTools } from \"../platform/PlatformTools\"\nimport { DataSource } from \"../data-source/DataSource\"\nimport { QueryRunner } from \"../query-runner/QueryRunner\"\nimport { TypeORMError } from \"../error/TypeORMError\"\n\n/**\n * Caches query result into Redis database.\n */\nexport class RedisQueryResultCache implements QueryResultCache {\n // -------------------------------------------------------------------------\n // Protected Properties\n // -------------------------------------------------------------------------\n\n /**\n * Redis module instance loaded dynamically.\n */\n protected redis: any\n\n /**\n * Connected redis client.\n */\n protected client: any\n\n /**\n * Type of the Redis Client (redis or ioredis).\n */\n protected clientType: \"redis\" | \"ioredis\" | \"ioredis/cluster\"\n\n // -------------------------------------------------------------------------\n // Constructor\n // -------------------------------------------------------------------------\n\n constructor(\n protected connection: DataSource,\n clientType: \"redis\" | \"ioredis\" | \"ioredis/cluster\",\n ) {\n this.clientType = clientType\n this.redis = this.loadRedis()\n }\n\n // -------------------------------------------------------------------------\n // Public Methods\n // -------------------------------------------------------------------------\n\n /**\n * Creates a connection with given cache provider.\n */\n async connect(): Promise<void> {\n const cacheOptions: any = this.connection.options.cache\n if (this.clientType === \"redis\") {\n this.client = this.redis.createClient({\n ...cacheOptions?.options,\n legacyMode: true,\n })\n if (\n typeof this.connection.options.cache === \"object\" &&\n this.connection.options.cache.ignoreErrors\n ) {\n this.client.on(\"error\", (err: any) => {\n this.connection.logger.log(\"warn\", err)\n })\n }\n if (\"connect\" in this.client) {\n await this.client.connect()\n }\n } else if (this.clientType === \"ioredis\") {\n if (cacheOptions && cacheOptions.port) {\n if (cacheOptions.options) {\n this.client = new this.redis(\n cacheOptions.port,\n cacheOptions.options,\n )\n } else {\n this.client = new this.redis(cacheOptions.port)\n }\n } else if (cacheOptions && cacheOptions.options) {\n this.client = new this.redis(cacheOptions.options)\n } else {\n this.client = new this.redis()\n }\n } else if (this.clientType === \"ioredis/cluster\") {\n if (\n cacheOptions &&\n cacheOptions.options &&\n Array.isArray(cacheOptions.options)\n ) {\n this.client = new this.redis.Cluster(cacheOptions.options)\n } else if (\n cacheOptions &&\n cacheOptions.options &&\n cacheOptions.options.startupNodes\n ) {\n this.client = new this.redis.Cluster(\n cacheOptions.options.startupNodes,\n cacheOptions.options.options,\n )\n } else {\n throw new TypeORMError(\n `options.startupNodes required for ${this.clientType}.`,\n )\n }\n }\n }\n\n /**\n * Disconnects the connection\n */\n async disconnect(): Promise<void> {\n return new Promise<void>((ok, fail) => {\n this.client.quit((err: any, result: any) => {\n if (err) return fail(err)\n ok()\n this.client = undefined\n })\n })\n }\n\n /**\n * Creates table for storing cache if it does not exist yet.\n */\n async synchronize(queryRunner: QueryRunner): Promise<void> {}\n\n /**\n * Get data from cache.\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 return new Promise<QueryResultCacheOptions | undefined>((ok, fail) => {\n if (options.identifier) {\n this.client.get(options.identifier, (err: any, result: any) => {\n if (err) return fail(err)\n ok(JSON.parse(result))\n })\n } else if (options.query) {\n this.client.get(options.query, (err: any, result: any) => {\n if (err) return fail(err)\n ok(JSON.parse(result))\n })\n } else {\n ok(undefined)\n }\n })\n }\n\n /**\n * Checks if cache is expired or not.\n */\n isExpired(savedCache: QueryResultCacheOptions): boolean {\n return savedCache.time! + savedCache.duration < new Date().getTime()\n }\n\n /**\n * Stores given query result in the cache.\n */\n async storeInCache(\n options: QueryResultCacheOptions,\n savedCache: QueryResultCacheOptions,\n queryRunner?: QueryRunner,\n ): Promise<void> {\n return new Promise<void>((ok, fail) => {\n if (options.identifier) {\n this.client.set(\n options.identifier,\n JSON.stringify(options),\n \"PX\",\n options.duration,\n (err: any, result: any) => {\n if (err) return fail(err)\n ok()\n },\n )\n } else if (options.query) {\n this.client.set(\n options.query,\n JSON.stringify(options),\n \"PX\",\n options.duration,\n (err: any, result: any) => {\n if (err) return fail(err)\n ok()\n },\n )\n }\n })\n }\n\n /**\n * Clears everything stored in the cache.\n */\n async clear(queryRunner?: QueryRunner): Promise<void> {\n return new Promise<void>((ok, fail) => {\n this.client.flushdb((err: any, result: any) => {\n if (err) return fail(err)\n ok()\n })\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 return this.deleteKey(identifier)\n }),\n )\n }\n\n // -------------------------------------------------------------------------\n // Protected Methods\n // -------------------------------------------------------------------------\n\n /**\n * Removes a single key from redis database.\n */\n protected deleteKey(key: string): Promise<void> {\n return new Promise<void>((ok, fail) => {\n this.client.del(key, (err: any, result: any) => {\n if (err) return fail(err)\n ok()\n })\n })\n }\n\n /**\n * Loads redis dependency.\n */\n protected loadRedis(): any {\n try {\n if (this.clientType === \"ioredis/cluster\") {\n return PlatformTools.load(\"ioredis\")\n } else {\n return PlatformTools.load(this.clientType)\n }\n } catch (e) {\n throw new TypeORMError(\n `Cannot use cache because ${this.clientType} is not installed. Please run \"npm i ${this.clientType} --save\".`,\n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CAAwC,IAAI,CAAC,UAAU,WAAW,CAChH,CAAA;QACL,CAAC;IACL,CAAC;CACJ;AAhPD,sDAgPC","file":"RedisQueryResultCache.js","sourcesContent":["import { QueryResultCache } from \"./QueryResultCache\"\nimport { QueryResultCacheOptions } from \"./QueryResultCacheOptions\"\nimport { PlatformTools } from \"../platform/PlatformTools\"\nimport { DataSource } from \"../data-source/DataSource\"\nimport { QueryRunner } from \"../query-runner/QueryRunner\"\nimport { TypeORMError } from \"../error/TypeORMError\"\n\n/**\n * Caches query result into Redis database.\n */\nexport class RedisQueryResultCache implements QueryResultCache {\n // -------------------------------------------------------------------------\n // Protected Properties\n // -------------------------------------------------------------------------\n\n /**\n * Redis module instance loaded dynamically.\n */\n protected redis: any\n\n /**\n * Connected redis client.\n */\n protected client: any\n\n /**\n * Type of the Redis Client (redis or ioredis).\n */\n protected clientType: \"redis\" | \"ioredis\" | \"ioredis/cluster\"\n\n // -------------------------------------------------------------------------\n // Constructor\n // -------------------------------------------------------------------------\n\n constructor(\n protected connection: DataSource,\n clientType: \"redis\" | \"ioredis\" | \"ioredis/cluster\",\n ) {\n this.clientType = clientType\n this.redis = this.loadRedis()\n }\n\n // -------------------------------------------------------------------------\n // Public Methods\n // -------------------------------------------------------------------------\n\n /**\n * Creates a connection with given cache provider.\n */\n async connect(): Promise<void> {\n const cacheOptions: any = this.connection.options.cache\n if (this.clientType === \"redis\") {\n this.client = this.redis.createClient({\n ...cacheOptions?.options,\n legacyMode: true,\n })\n if (\n typeof this.connection.options.cache === \"object\" &&\n this.connection.options.cache.ignoreErrors\n ) {\n this.client.on(\"error\", (err: any) => {\n this.connection.logger.log(\"warn\", err)\n })\n }\n if (\"connect\" in this.client) {\n await this.client.connect()\n }\n } else if (this.clientType === \"ioredis\") {\n if (cacheOptions && cacheOptions.port) {\n if (cacheOptions.options) {\n this.client = new this.redis(\n cacheOptions.port,\n cacheOptions.options,\n )\n } else {\n this.client = new this.redis(cacheOptions.port)\n }\n } else if (cacheOptions && cacheOptions.options) {\n this.client = new this.redis(cacheOptions.options)\n } else {\n this.client = new this.redis()\n }\n } else if (this.clientType === \"ioredis/cluster\") {\n if (\n cacheOptions &&\n cacheOptions.options &&\n Array.isArray(cacheOptions.options)\n ) {\n this.client = new this.redis.Cluster(cacheOptions.options)\n } else if (\n cacheOptions &&\n cacheOptions.options &&\n cacheOptions.options.startupNodes\n ) {\n this.client = new this.redis.Cluster(\n cacheOptions.options.startupNodes,\n cacheOptions.options.options,\n )\n } else {\n throw new TypeORMError(\n `options.startupNodes required for ${this.clientType}.`,\n )\n }\n }\n }\n\n /**\n * Disconnects the connection\n */\n async disconnect(): Promise<void> {\n return new Promise<void>((ok, fail) => {\n this.client.quit((err: any, result: any) => {\n if (err) return fail(err)\n ok()\n this.client = undefined\n })\n })\n }\n\n /**\n * Creates table for storing cache if it does not exist yet.\n */\n async synchronize(queryRunner: QueryRunner): Promise<void> {}\n\n /**\n * Get data from cache.\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 return new Promise<QueryResultCacheOptions | undefined>((ok, fail) => {\n if (options.identifier) {\n this.client.get(options.identifier, (err: any, result: any) => {\n if (err) return fail(err)\n ok(JSON.parse(result))\n })\n } else if (options.query) {\n this.client.get(options.query, (err: any, result: any) => {\n if (err) return fail(err)\n ok(JSON.parse(result))\n })\n } else {\n ok(undefined)\n }\n })\n }\n\n /**\n * Checks if cache is expired or not.\n */\n isExpired(savedCache: QueryResultCacheOptions): boolean {\n return savedCache.time! + savedCache.duration < Date.now()\n }\n\n /**\n * Stores given query result in the cache.\n */\n async storeInCache(\n options: QueryResultCacheOptions,\n savedCache: QueryResultCacheOptions,\n queryRunner?: QueryRunner,\n ): Promise<void> {\n return new Promise<void>((ok, fail) => {\n if (options.identifier) {\n this.client.set(\n options.identifier,\n JSON.stringify(options),\n \"PX\",\n options.duration,\n (err: any, result: any) => {\n if (err) return fail(err)\n ok()\n },\n )\n } else if (options.query) {\n this.client.set(\n options.query,\n JSON.stringify(options),\n \"PX\",\n options.duration,\n (err: any, result: any) => {\n if (err) return fail(err)\n ok()\n },\n )\n }\n })\n }\n\n /**\n * Clears everything stored in the cache.\n */\n async clear(queryRunner?: QueryRunner): Promise<void> {\n return new Promise<void>((ok, fail) => {\n this.client.flushdb((err: any, result: any) => {\n if (err) return fail(err)\n ok()\n })\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 return this.deleteKey(identifier)\n }),\n )\n }\n\n // -------------------------------------------------------------------------\n // Protected Methods\n // -------------------------------------------------------------------------\n\n /**\n * Removes a single key from redis database.\n */\n protected deleteKey(key: string): Promise<void> {\n return new Promise<void>((ok, fail) => {\n this.client.del(key, (err: any, result: any) => {\n if (err) return fail(err)\n ok()\n })\n })\n }\n\n /**\n * Loads redis dependency.\n */\n protected loadRedis(): any {\n try {\n if (this.clientType === \"ioredis/cluster\") {\n return PlatformTools.load(\"ioredis\")\n } else {\n return PlatformTools.load(this.clientType)\n }\n } catch (e) {\n throw new TypeORMError(\n `Cannot use cache because ${this.clientType} is not installed. Please run \"npm i ${this.clientType} --save\".`,\n )\n }\n }\n}\n"],"sourceRoot":".."}
|
|
@@ -63,7 +63,7 @@ export interface BaseDataSourceOptions {
|
|
|
63
63
|
/**
|
|
64
64
|
* Logger instance used to log queries and events in the ORM.
|
|
65
65
|
*/
|
|
66
|
-
readonly logger?: "advanced-console" | "simple-console" | "file" | "debug" | Logger;
|
|
66
|
+
readonly logger?: "advanced-console" | "simple-console" | "formatted-console" | "file" | "debug" | Logger;
|
|
67
67
|
/**
|
|
68
68
|
* Maximum number of milliseconds query should be executed before logger log a warning.
|
|
69
69
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/data-source/BaseDataSourceOptions.ts"],"names":[],"mappings":"","file":"BaseDataSourceOptions.js","sourcesContent":["import { EntitySchema } from \"../entity-schema/EntitySchema\"\nimport { LoggerOptions } from \"../logger/LoggerOptions\"\nimport { NamingStrategyInterface } from \"../naming-strategy/NamingStrategyInterface\"\nimport { DatabaseType } from \"../driver/types/DatabaseType\"\nimport { Logger } from \"../logger/Logger\"\nimport { DataSource } from \"../data-source/DataSource\"\nimport { QueryResultCache } from \"../cache/QueryResultCache\"\nimport { MixedList } from \"../common/MixedList\"\n\n/**\n * BaseDataSourceOptions is set of DataSourceOptions shared by all database types.\n */\nexport interface BaseDataSourceOptions {\n /**\n * Database type. This value is required.\n */\n readonly type: DatabaseType\n\n /**\n * Connection name. If connection name is not given then it will be called \"default\".\n * Different connections must have different names.\n *\n * @deprecated\n */\n readonly name?: string\n\n /**\n * Entities to be loaded for this connection.\n * Accepts both entity classes and directories where from entities need to be loaded.\n * Directories support glob patterns.\n */\n readonly entities?: MixedList<Function | string | EntitySchema>\n\n /**\n * Subscribers to be loaded for this connection.\n * Accepts both subscriber classes and directories where from subscribers need to be loaded.\n * Directories support glob patterns.\n */\n readonly subscribers?: MixedList<Function | string>\n\n /**\n * Migrations to be loaded for this connection.\n * Accepts both migration classes and glob patterns representing migration files.\n */\n readonly migrations?: MixedList<Function | string>\n\n /**\n * Migrations table name, in case of different name from \"migrations\".\n * Accepts single string name.\n */\n readonly migrationsTableName?: string\n\n /**\n * Transaction mode for migrations to run in\n */\n readonly migrationsTransactionMode?: \"all\" | \"none\" | \"each\"\n\n /**\n * Typeorm metadata table name, in case of different name from \"typeorm_metadata\".\n * Accepts single string name.\n */\n readonly metadataTableName?: string\n\n /**\n * Naming strategy to be used to name tables and columns in the database.\n */\n readonly namingStrategy?: NamingStrategyInterface\n\n /**\n * Logging options.\n */\n readonly logging?: LoggerOptions\n\n /**\n * Logger instance used to log queries and events in the ORM.\n */\n readonly logger?:\n | \"advanced-console\"\n | \"simple-console\"\n | \"file\"\n | \"debug\"\n | Logger\n\n /**\n * Maximum number of milliseconds query should be executed before logger log a warning.\n */\n readonly maxQueryExecutionTime?: number\n\n /**\n * Maximum number of clients the pool should contain.\n */\n readonly poolSize?: number\n\n /**\n * Indicates if database schema should be auto created on every application launch.\n * Be careful with this option and don't use this in production - otherwise you can lose production data.\n * This option is useful during debug and development.\n * Alternative to it, you can use CLI and run schema:sync command.\n *\n * Note that for MongoDB database it does not create schema, because MongoDB is schemaless.\n * Instead, it syncs just by creating indices.\n */\n readonly synchronize?: boolean\n\n /**\n * Indicates if migrations should be auto run on every application launch.\n * Alternative to it, you can use CLI and run migrations:run command.\n */\n readonly migrationsRun?: boolean\n\n /**\n * Drops the schema each time connection is being established.\n * Be careful with this option and don't use this in production - otherwise you'll lose all production data.\n * This option is useful during debug and development.\n */\n readonly dropSchema?: boolean\n\n /**\n * Prefix to use on all tables (collections) of this connection in the database.\n */\n readonly entityPrefix?: string\n\n /**\n * When creating new Entity instances, skip all constructors when true.\n */\n readonly entitySkipConstructor?: boolean\n\n /**\n * Extra connection options to be passed to the underlying driver.\n *\n * todo: deprecate this and move all database-specific types into hts own connection options object.\n */\n readonly extra?: any\n\n /**\n * Specifies how relations must be loaded - using \"joins\" or separate queries.\n * If you are loading too much data with nested joins it's better to load relations\n * using separate queries.\n *\n * Default strategy is \"join\", but this default can be changed here.\n * Also, strategy can be set per-query in FindOptions and QueryBuilder.\n */\n readonly relationLoadStrategy?: \"join\" | \"query\"\n\n /**\n * Optionally applied \"typename\" to the model.\n * If set, then each hydrated model will have this property with the target model / entity name inside.\n *\n * (works like a discriminator property).\n */\n readonly typename?: string\n\n /**\n * Holds reference to the baseDirectory where configuration file are expected.\n *\n * @internal\n */\n baseDirectory?: string\n\n /**\n * Allows to setup cache options.\n */\n readonly cache?:\n | boolean\n | {\n /**\n * Type of caching.\n *\n * - \"database\" means cached values will be stored in the separate table in database. This is default value.\n * - \"redis\" means cached values will be stored inside redis. You must provide redis connection options.\n */\n readonly type?:\n | \"database\"\n | \"redis\"\n | \"ioredis\"\n | \"ioredis/cluster\" // todo: add mongodb and other cache providers as well in the future\n\n /**\n * Factory function for custom cache providers that implement QueryResultCache.\n */\n readonly provider?: (connection: DataSource) => QueryResultCache\n\n /**\n * Configurable table name for \"database\" type cache.\n * Default value is \"query-result-cache\"\n */\n readonly tableName?: string\n\n /**\n * Used to provide redis connection options.\n */\n readonly options?: any\n\n /**\n * If set to true then queries (using find methods and QueryBuilder's methods) will always be cached.\n */\n readonly alwaysEnabled?: boolean\n\n /**\n * Time in milliseconds in which cache will expire.\n * This can be setup per-query.\n * Default value is 1000 which is equivalent to 1 second.\n */\n readonly duration?: number\n\n /**\n * Used to specify if cache errors should be ignored, and pass through the call to the Database.\n */\n readonly ignoreErrors?: boolean\n }\n\n /**\n * Allows automatic isolation of where clauses\n */\n readonly isolateWhereStatements?: boolean\n}\n"],"sourceRoot":".."}
|
|
1
|
+
{"version":3,"sources":["../../src/data-source/BaseDataSourceOptions.ts"],"names":[],"mappings":"","file":"BaseDataSourceOptions.js","sourcesContent":["import { EntitySchema } from \"../entity-schema/EntitySchema\"\nimport { LoggerOptions } from \"../logger/LoggerOptions\"\nimport { NamingStrategyInterface } from \"../naming-strategy/NamingStrategyInterface\"\nimport { DatabaseType } from \"../driver/types/DatabaseType\"\nimport { Logger } from \"../logger/Logger\"\nimport { DataSource } from \"../data-source/DataSource\"\nimport { QueryResultCache } from \"../cache/QueryResultCache\"\nimport { MixedList } from \"../common/MixedList\"\n\n/**\n * BaseDataSourceOptions is set of DataSourceOptions shared by all database types.\n */\nexport interface BaseDataSourceOptions {\n /**\n * Database type. This value is required.\n */\n readonly type: DatabaseType\n\n /**\n * Connection name. If connection name is not given then it will be called \"default\".\n * Different connections must have different names.\n *\n * @deprecated\n */\n readonly name?: string\n\n /**\n * Entities to be loaded for this connection.\n * Accepts both entity classes and directories where from entities need to be loaded.\n * Directories support glob patterns.\n */\n readonly entities?: MixedList<Function | string | EntitySchema>\n\n /**\n * Subscribers to be loaded for this connection.\n * Accepts both subscriber classes and directories where from subscribers need to be loaded.\n * Directories support glob patterns.\n */\n readonly subscribers?: MixedList<Function | string>\n\n /**\n * Migrations to be loaded for this connection.\n * Accepts both migration classes and glob patterns representing migration files.\n */\n readonly migrations?: MixedList<Function | string>\n\n /**\n * Migrations table name, in case of different name from \"migrations\".\n * Accepts single string name.\n */\n readonly migrationsTableName?: string\n\n /**\n * Transaction mode for migrations to run in\n */\n readonly migrationsTransactionMode?: \"all\" | \"none\" | \"each\"\n\n /**\n * Typeorm metadata table name, in case of different name from \"typeorm_metadata\".\n * Accepts single string name.\n */\n readonly metadataTableName?: string\n\n /**\n * Naming strategy to be used to name tables and columns in the database.\n */\n readonly namingStrategy?: NamingStrategyInterface\n\n /**\n * Logging options.\n */\n readonly logging?: LoggerOptions\n\n /**\n * Logger instance used to log queries and events in the ORM.\n */\n readonly logger?:\n | \"advanced-console\"\n | \"simple-console\"\n | \"formatted-console\"\n | \"file\"\n | \"debug\"\n | Logger\n\n /**\n * Maximum number of milliseconds query should be executed before logger log a warning.\n */\n readonly maxQueryExecutionTime?: number\n\n /**\n * Maximum number of clients the pool should contain.\n */\n readonly poolSize?: number\n\n /**\n * Indicates if database schema should be auto created on every application launch.\n * Be careful with this option and don't use this in production - otherwise you can lose production data.\n * This option is useful during debug and development.\n * Alternative to it, you can use CLI and run schema:sync command.\n *\n * Note that for MongoDB database it does not create schema, because MongoDB is schemaless.\n * Instead, it syncs just by creating indices.\n */\n readonly synchronize?: boolean\n\n /**\n * Indicates if migrations should be auto run on every application launch.\n * Alternative to it, you can use CLI and run migrations:run command.\n */\n readonly migrationsRun?: boolean\n\n /**\n * Drops the schema each time connection is being established.\n * Be careful with this option and don't use this in production - otherwise you'll lose all production data.\n * This option is useful during debug and development.\n */\n readonly dropSchema?: boolean\n\n /**\n * Prefix to use on all tables (collections) of this connection in the database.\n */\n readonly entityPrefix?: string\n\n /**\n * When creating new Entity instances, skip all constructors when true.\n */\n readonly entitySkipConstructor?: boolean\n\n /**\n * Extra connection options to be passed to the underlying driver.\n *\n * todo: deprecate this and move all database-specific types into hts own connection options object.\n */\n readonly extra?: any\n\n /**\n * Specifies how relations must be loaded - using \"joins\" or separate queries.\n * If you are loading too much data with nested joins it's better to load relations\n * using separate queries.\n *\n * Default strategy is \"join\", but this default can be changed here.\n * Also, strategy can be set per-query in FindOptions and QueryBuilder.\n */\n readonly relationLoadStrategy?: \"join\" | \"query\"\n\n /**\n * Optionally applied \"typename\" to the model.\n * If set, then each hydrated model will have this property with the target model / entity name inside.\n *\n * (works like a discriminator property).\n */\n readonly typename?: string\n\n /**\n * Holds reference to the baseDirectory where configuration file are expected.\n *\n * @internal\n */\n baseDirectory?: string\n\n /**\n * Allows to setup cache options.\n */\n readonly cache?:\n | boolean\n | {\n /**\n * Type of caching.\n *\n * - \"database\" means cached values will be stored in the separate table in database. This is default value.\n * - \"redis\" means cached values will be stored inside redis. You must provide redis connection options.\n */\n readonly type?:\n | \"database\"\n | \"redis\"\n | \"ioredis\"\n | \"ioredis/cluster\" // todo: add mongodb and other cache providers as well in the future\n\n /**\n * Factory function for custom cache providers that implement QueryResultCache.\n */\n readonly provider?: (connection: DataSource) => QueryResultCache\n\n /**\n * Configurable table name for \"database\" type cache.\n * Default value is \"query-result-cache\"\n */\n readonly tableName?: string\n\n /**\n * Used to provide redis connection options.\n */\n readonly options?: any\n\n /**\n * If set to true then queries (using find methods and QueryBuilder's methods) will always be cached.\n */\n readonly alwaysEnabled?: boolean\n\n /**\n * Time in milliseconds in which cache will expire.\n * This can be setup per-query.\n * Default value is 1000 which is equivalent to 1 second.\n */\n readonly duration?: number\n\n /**\n * Used to specify if cache errors should be ignored, and pass through the call to the Database.\n */\n readonly ignoreErrors?: boolean\n }\n\n /**\n * Allows automatic isolation of where clauses\n */\n readonly isolateWhereStatements?: boolean\n}\n"],"sourceRoot":".."}
|
|
@@ -73,7 +73,7 @@ class BetterSqlite3QueryRunner extends AbstractSqliteQueryRunner_1.AbstractSqlit
|
|
|
73
73
|
const broadcasterResult = new BroadcasterResult_1.BroadcasterResult();
|
|
74
74
|
this.driver.connection.logger.logQuery(query, parameters, this);
|
|
75
75
|
this.broadcaster.broadcastBeforeQueryEvent(broadcasterResult, query, parameters);
|
|
76
|
-
const queryStartTime =
|
|
76
|
+
const queryStartTime = Date.now();
|
|
77
77
|
const stmt = await this.getStmt(query);
|
|
78
78
|
try {
|
|
79
79
|
const result = new QueryResult_1.QueryResult();
|
|
@@ -91,7 +91,7 @@ class BetterSqlite3QueryRunner extends AbstractSqliteQueryRunner_1.AbstractSqlit
|
|
|
91
91
|
}
|
|
92
92
|
// log slow queries if maxQueryExecution time is set
|
|
93
93
|
const maxQueryExecutionTime = this.driver.options.maxQueryExecutionTime;
|
|
94
|
-
const queryEndTime =
|
|
94
|
+
const queryEndTime = Date.now();
|
|
95
95
|
const queryExecutionTime = queryEndTime - queryStartTime;
|
|
96
96
|
if (maxQueryExecutionTime &&
|
|
97
97
|
queryExecutionTime > maxQueryExecutionTime)
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/driver/better-sqlite3/BetterSqlite3QueryRunner.ts"],"names":[],"mappings":";;;AAAA,iGAA6F;AAC7F,mEAA+D;AAC/D,4FAAwF;AACxF,8DAA0D;AAE1D,gEAA4D;AAC5D,0EAAsE;AAEtE;;;;;GAKG;AACH,MAAa,wBAAyB,SAAQ,qDAAyB;IAMnE,4EAA4E;IAC5E,cAAc;IACd,4EAA4E;IAE5E,YAAY,MAA2B;QACnC,KAAK,EAAE,CAAA;QAYH,cAAS,GAAG,IAAI,GAAG,EAAe,CAAA;QAXtC,IAAI,CAAC,MAAM,GAAG,MAAM,CAAA;QACpB,IAAI,CAAC,UAAU,GAAG,MAAM,CAAC,UAAU,CAAA;QACnC,IAAI,CAAC,WAAW,GAAG,IAAI,yBAAW,CAAC,IAAI,CAAC,CAAA;QACxC,IAAI,OAAO,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,kBAAkB,K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AAQ,CAAC,CAAC,CAAC,GAAG,QAAQ,GAAG,CAAC,CAAC,CAAC,EAAE,eAAe,CACnD,oBAAoB,YAAY,UAC7B,YAAY,KAAK,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,UACxC,UAAU,SAAS,IAAI,CAC1B,CAAA;QACD,OAAO,GAAG,CAAA;IACd,CAAC;IACS,KAAK,CAAC,iBAAiB,CAAC,SAAiB,EAAE,MAAc;QAC/D,MAAM,CAAC,QAAQ,EAAE,SAAS,CAAC,GAAG,IAAI,CAAC,cAAc,CAAC,SAAS,CAAC,CAAA;QAC5D,MAAM,GAAG,GAAG,MAAM,IAAI,CAAC,KAAK,CACxB,UACI,QAAQ,CAAC,CAAC,CAAC,IAAI,QAAQ,IAAI,CAAC,CAAC,CAAC,EAClC,GAAG,MAAM,KAAK,SAAS,IAAI,CAC9B,CAAA;QACD,OAAO,GAAG,CAAA;IACd,CAAC;CACJ;AAvKD,4DAuKC","file":"BetterSqlite3QueryRunner.js","sourcesContent":["import { QueryRunnerAlreadyReleasedError } from \"../../error/QueryRunnerAlreadyReleasedError\"\nimport { QueryFailedError } from \"../../error/QueryFailedError\"\nimport { AbstractSqliteQueryRunner } from \"../sqlite-abstract/AbstractSqliteQueryRunner\"\nimport { Broadcaster } from \"../../subscriber/Broadcaster\"\nimport { BetterSqlite3Driver } from \"./BetterSqlite3Driver\"\nimport { QueryResult } from \"../../query-runner/QueryResult\"\nimport { BroadcasterResult } from \"../../subscriber/BroadcasterResult\"\n\n/**\n * Runs queries on a single sqlite database connection.\n *\n * Does not support compose primary keys with autoincrement field.\n * todo: need to throw exception for this case.\n */\nexport class BetterSqlite3QueryRunner extends AbstractSqliteQueryRunner {\n /**\n * Database driver used by connection.\n */\n driver: BetterSqlite3Driver\n\n // -------------------------------------------------------------------------\n // Constructor\n // -------------------------------------------------------------------------\n\n constructor(driver: BetterSqlite3Driver) {\n super()\n this.driver = driver\n this.connection = driver.connection\n this.broadcaster = new Broadcaster(this)\n if (typeof this.driver.options.statementCacheSize === \"number\") {\n this.cacheSize = this.driver.options.statementCacheSize\n } else {\n this.cacheSize = 100\n }\n }\n\n private cacheSize: number\n private stmtCache = new Map<string, any>()\n\n private async getStmt(query: string) {\n if (this.cacheSize > 0) {\n let stmt = this.stmtCache.get(query)\n if (!stmt) {\n const databaseConnection = await this.connect()\n stmt = databaseConnection.prepare(query)\n this.stmtCache.set(query, stmt)\n while (this.stmtCache.size > this.cacheSize) {\n // since es6 map keeps the insertion order,\n // it comes to be FIFO cache\n const key = this.stmtCache.keys().next().value!\n this.stmtCache.delete(key)\n }\n }\n return stmt\n } else {\n const databaseConnection = await this.connect()\n return databaseConnection.prepare(query)\n }\n }\n\n /**\n * Called before migrations are run.\n */\n async beforeMigration(): Promise<void> {\n await this.query(`PRAGMA foreign_keys = OFF`)\n }\n\n /**\n * Called after migrations are run.\n */\n async afterMigration(): Promise<void> {\n await this.query(`PRAGMA foreign_keys = ON`)\n }\n\n /**\n * Executes a given SQL query.\n */\n async query(\n query: string,\n parameters?: any[],\n useStructuredResult = false,\n ): Promise<any> {\n if (this.isReleased) throw new QueryRunnerAlreadyReleasedError()\n\n const connection = this.driver.connection\n\n const broadcasterResult = new BroadcasterResult()\n\n this.driver.connection.logger.logQuery(query, parameters, this)\n this.broadcaster.broadcastBeforeQueryEvent(\n broadcasterResult,\n query,\n parameters,\n )\n const queryStartTime = +new Date()\n\n const stmt = await this.getStmt(query)\n\n try {\n const result = new QueryResult()\n\n if (stmt.reader) {\n const raw = stmt.all.apply(stmt, parameters)\n\n result.raw = raw\n\n if (Array.isArray(raw)) {\n result.records = raw\n }\n } else {\n const raw = stmt.run.apply(stmt, parameters)\n result.affected = raw.changes\n result.raw = raw.lastInsertRowid\n }\n\n // log slow queries if maxQueryExecution time is set\n const maxQueryExecutionTime =\n this.driver.options.maxQueryExecutionTime\n const queryEndTime = +new Date()\n const queryExecutionTime = queryEndTime - queryStartTime\n if (\n maxQueryExecutionTime &&\n queryExecutionTime > maxQueryExecutionTime\n )\n connection.logger.logQuerySlow(\n queryExecutionTime,\n query,\n parameters,\n this,\n )\n\n this.broadcaster.broadcastAfterQueryEvent(\n broadcasterResult,\n query,\n parameters,\n true,\n queryExecutionTime,\n result.raw,\n undefined,\n )\n\n if (!useStructuredResult) {\n return result.raw\n }\n\n return result\n } catch (err) {\n connection.logger.logQueryError(err, query, parameters, this)\n throw new QueryFailedError(query, parameters, err)\n }\n }\n\n // -------------------------------------------------------------------------\n // Protected Methods\n // -------------------------------------------------------------------------\n\n protected async loadTableRecords(\n tablePath: string,\n tableOrIndex: \"table\" | \"index\",\n ) {\n const [database, tableName] = this.splitTablePath(tablePath)\n const res = await this.query(\n `SELECT ${\n database ? `'${database}'` : null\n } as database, * FROM ${this.escapePath(\n `${database ? `${database}.` : \"\"}sqlite_master`,\n )} WHERE \"type\" = '${tableOrIndex}' AND \"${\n tableOrIndex === \"table\" ? \"name\" : \"tbl_name\"\n }\" IN ('${tableName}')`,\n )\n return res\n }\n protected async loadPragmaRecords(tablePath: string, pragma: string) {\n const [database, tableName] = this.splitTablePath(tablePath)\n const res = await this.query(\n `PRAGMA ${\n database ? `\"${database}\".` : \"\"\n }${pragma}(\"${tableName}\")`,\n )\n return res\n }\n}\n"],"sourceRoot":"../.."}
|
|
1
|
+
{"version":3,"sources":["../../src/driver/better-sqlite3/BetterSqlite3QueryRunner.ts"],"names":[],"mappings":";;;AAAA,iGAA6F;AAC7F,mEAA+D;AAC/D,4FAAwF;AACxF,8DAA0D;AAE1D,gEAA4D;AAC5D,0EAAsE;AAEtE;;;;;GAKG;AACH,MAAa,wBAAyB,SAAQ,qDAAyB;IAMnE,4EAA4E;IAC5E,cAAc;IACd,4EAA4E;IAE5E,YAAY,MAA2B;QACnC,KAAK,EAAE,CAAA;QAYH,cAAS,GAAG,IAAI,GAAG,EAAe,CAAA;QAXtC,IAAI,CAAC,MAAM,GAAG,MAAM,CAAA;QACpB,IAAI,CAAC,UAAU,GAAG,MAAM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AG,GAAG,MAAM,IAAI,CAAC,KAAK,CACxB,UACI,QAAQ,CAAC,CAAC,CAAC,IAAI,QAAQ,GAAG,CAAC,CAAC,CAAC,IACjC,wBAAwB,IAAI,CAAC,UAAU,CACnC,GAAG,QAAQ,CAAC,CAAC,CAAC,GAAG,QAAQ,GAAG,CAAC,CAAC,CAAC,EAAE,eAAe,CACnD,oBAAoB,YAAY,UAC7B,YAAY,KAAK,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,UACxC,UAAU,SAAS,IAAI,CAC1B,CAAA;QACD,OAAO,GAAG,CAAA;IACd,CAAC;IACS,KAAK,CAAC,iBAAiB,CAAC,SAAiB,EAAE,MAAc;QAC/D,MAAM,CAAC,QAAQ,EAAE,SAAS,CAAC,GAAG,IAAI,CAAC,cAAc,CAAC,SAAS,CAAC,CAAA;QAC5D,MAAM,GAAG,GAAG,MAAM,IAAI,CAAC,KAAK,CACxB,UACI,QAAQ,CAAC,CAAC,CAAC,IAAI,QAAQ,IAAI,CAAC,CAAC,CAAC,EAClC,GAAG,MAAM,KAAK,SAAS,IAAI,CAC9B,CAAA;QACD,OAAO,GAAG,CAAA;IACd,CAAC;CACJ;AAvKD,4DAuKC","file":"BetterSqlite3QueryRunner.js","sourcesContent":["import { QueryRunnerAlreadyReleasedError } from \"../../error/QueryRunnerAlreadyReleasedError\"\nimport { QueryFailedError } from \"../../error/QueryFailedError\"\nimport { AbstractSqliteQueryRunner } from \"../sqlite-abstract/AbstractSqliteQueryRunner\"\nimport { Broadcaster } from \"../../subscriber/Broadcaster\"\nimport { BetterSqlite3Driver } from \"./BetterSqlite3Driver\"\nimport { QueryResult } from \"../../query-runner/QueryResult\"\nimport { BroadcasterResult } from \"../../subscriber/BroadcasterResult\"\n\n/**\n * Runs queries on a single sqlite database connection.\n *\n * Does not support compose primary keys with autoincrement field.\n * todo: need to throw exception for this case.\n */\nexport class BetterSqlite3QueryRunner extends AbstractSqliteQueryRunner {\n /**\n * Database driver used by connection.\n */\n driver: BetterSqlite3Driver\n\n // -------------------------------------------------------------------------\n // Constructor\n // -------------------------------------------------------------------------\n\n constructor(driver: BetterSqlite3Driver) {\n super()\n this.driver = driver\n this.connection = driver.connection\n this.broadcaster = new Broadcaster(this)\n if (typeof this.driver.options.statementCacheSize === \"number\") {\n this.cacheSize = this.driver.options.statementCacheSize\n } else {\n this.cacheSize = 100\n }\n }\n\n private cacheSize: number\n private stmtCache = new Map<string, any>()\n\n private async getStmt(query: string) {\n if (this.cacheSize > 0) {\n let stmt = this.stmtCache.get(query)\n if (!stmt) {\n const databaseConnection = await this.connect()\n stmt = databaseConnection.prepare(query)\n this.stmtCache.set(query, stmt)\n while (this.stmtCache.size > this.cacheSize) {\n // since es6 map keeps the insertion order,\n // it comes to be FIFO cache\n const key = this.stmtCache.keys().next().value!\n this.stmtCache.delete(key)\n }\n }\n return stmt\n } else {\n const databaseConnection = await this.connect()\n return databaseConnection.prepare(query)\n }\n }\n\n /**\n * Called before migrations are run.\n */\n async beforeMigration(): Promise<void> {\n await this.query(`PRAGMA foreign_keys = OFF`)\n }\n\n /**\n * Called after migrations are run.\n */\n async afterMigration(): Promise<void> {\n await this.query(`PRAGMA foreign_keys = ON`)\n }\n\n /**\n * Executes a given SQL query.\n */\n async query(\n query: string,\n parameters?: any[],\n useStructuredResult = false,\n ): Promise<any> {\n if (this.isReleased) throw new QueryRunnerAlreadyReleasedError()\n\n const connection = this.driver.connection\n\n const broadcasterResult = new BroadcasterResult()\n\n this.driver.connection.logger.logQuery(query, parameters, this)\n this.broadcaster.broadcastBeforeQueryEvent(\n broadcasterResult,\n query,\n parameters,\n )\n const queryStartTime = Date.now()\n\n const stmt = await this.getStmt(query)\n\n try {\n const result = new QueryResult()\n\n if (stmt.reader) {\n const raw = stmt.all.apply(stmt, parameters)\n\n result.raw = raw\n\n if (Array.isArray(raw)) {\n result.records = raw\n }\n } else {\n const raw = stmt.run.apply(stmt, parameters)\n result.affected = raw.changes\n result.raw = raw.lastInsertRowid\n }\n\n // log slow queries if maxQueryExecution time is set\n const maxQueryExecutionTime =\n this.driver.options.maxQueryExecutionTime\n const queryEndTime = Date.now()\n const queryExecutionTime = queryEndTime - queryStartTime\n if (\n maxQueryExecutionTime &&\n queryExecutionTime > maxQueryExecutionTime\n )\n connection.logger.logQuerySlow(\n queryExecutionTime,\n query,\n parameters,\n this,\n )\n\n this.broadcaster.broadcastAfterQueryEvent(\n broadcasterResult,\n query,\n parameters,\n true,\n queryExecutionTime,\n result.raw,\n undefined,\n )\n\n if (!useStructuredResult) {\n return result.raw\n }\n\n return result\n } catch (err) {\n connection.logger.logQueryError(err, query, parameters, this)\n throw new QueryFailedError(query, parameters, err)\n }\n }\n\n // -------------------------------------------------------------------------\n // Protected Methods\n // -------------------------------------------------------------------------\n\n protected async loadTableRecords(\n tablePath: string,\n tableOrIndex: \"table\" | \"index\",\n ) {\n const [database, tableName] = this.splitTablePath(tablePath)\n const res = await this.query(\n `SELECT ${\n database ? `'${database}'` : null\n } as database, * FROM ${this.escapePath(\n `${database ? `${database}.` : \"\"}sqlite_master`,\n )} WHERE \"type\" = '${tableOrIndex}' AND \"${\n tableOrIndex === \"table\" ? \"name\" : \"tbl_name\"\n }\" IN ('${tableName}')`,\n )\n return res\n }\n protected async loadPragmaRecords(tablePath: string, pragma: string) {\n const [database, tableName] = this.splitTablePath(tablePath)\n const res = await this.query(\n `PRAGMA ${\n database ? `\"${database}\".` : \"\"\n }${pragma}(\"${tableName}\")`,\n )\n return res\n }\n}\n"],"sourceRoot":"../.."}
|
|
@@ -199,7 +199,7 @@ class CockroachQueryRunner extends BaseQueryRunner_1.BaseQueryRunner {
|
|
|
199
199
|
const broadcasterResult = new BroadcasterResult_1.BroadcasterResult();
|
|
200
200
|
this.driver.connection.logger.logQuery(query, parameters, this);
|
|
201
201
|
this.broadcaster.broadcastBeforeQueryEvent(broadcasterResult, query, parameters);
|
|
202
|
-
const queryStartTime =
|
|
202
|
+
const queryStartTime = Date.now();
|
|
203
203
|
if (this.isTransactionActive && this.storeQueries) {
|
|
204
204
|
this.queries.push({ query, parameters });
|
|
205
205
|
}
|
|
@@ -209,7 +209,7 @@ class CockroachQueryRunner extends BaseQueryRunner_1.BaseQueryRunner {
|
|
|
209
209
|
});
|
|
210
210
|
// log slow queries if maxQueryExecution time is set
|
|
211
211
|
const maxQueryExecutionTime = this.driver.options.maxQueryExecutionTime;
|
|
212
|
-
const queryEndTime =
|
|
212
|
+
const queryEndTime = Date.now();
|
|
213
213
|
const queryExecutionTime = queryEndTime - queryStartTime;
|
|
214
214
|
if (maxQueryExecutionTime &&
|
|
215
215
|
queryExecutionTime > maxQueryExecutionTime) {
|