UNPKG

33.9 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3var tslib_1 = require("tslib");
4var EntityNotFoundError_1 = require("../error/EntityNotFoundError");
5var QueryRunnerProviderAlreadyReleasedError_1 = require("../error/QueryRunnerProviderAlreadyReleasedError");
6var NoNeedToReleaseEntityManagerError_1 = require("../error/NoNeedToReleaseEntityManagerError");
7var TreeRepository_1 = require("../repository/TreeRepository");
8var Repository_1 = require("../repository/Repository");
9var FindOptionsUtils_1 = require("../find-options/FindOptionsUtils");
10var PlainObjectToNewEntityTransformer_1 = require("../query-builder/transformer/PlainObjectToNewEntityTransformer");
11var PlainObjectToDatabaseEntityTransformer_1 = require("../query-builder/transformer/PlainObjectToDatabaseEntityTransformer");
12var CustomRepositoryNotFoundError_1 = require("../error/CustomRepositoryNotFoundError");
13var index_1 = require("../index");
14var AbstractRepository_1 = require("../repository/AbstractRepository");
15var CustomRepositoryCannotInheritRepositoryError_1 = require("../error/CustomRepositoryCannotInheritRepositoryError");
16var MongoDriver_1 = require("../driver/mongodb/MongoDriver");
17var RepositoryNotFoundError_1 = require("../error/RepositoryNotFoundError");
18var RepositoryNotTreeError_1 = require("../error/RepositoryNotTreeError");
19var RepositoryFactory_1 = require("../repository/RepositoryFactory");
20var TreeRepositoryNotSupportedError_1 = require("../error/TreeRepositoryNotSupportedError");
21var EntityPersistExecutor_1 = require("../persistence/EntityPersistExecutor");
22var OracleDriver_1 = require("../driver/oracle/OracleDriver");
23var ObjectUtils_1 = require("../util/ObjectUtils");
24/**
25 * Entity manager supposed to work with any entity, automatically find its repository and call its methods,
26 * whatever entity type are you passing.
27 */
28var EntityManager = /** @class */ (function () {
29 // -------------------------------------------------------------------------
30 // Constructor
31 // -------------------------------------------------------------------------
32 function EntityManager(connection, queryRunner) {
33 // -------------------------------------------------------------------------
34 // Protected Properties
35 // -------------------------------------------------------------------------
36 /**
37 * Once created and then reused by en repositories.
38 */
39 this.repositories = [];
40 /**
41 * Plain to object transformer used in create and merge operations.
42 */
43 this.plainObjectToEntityTransformer = new PlainObjectToNewEntityTransformer_1.PlainObjectToNewEntityTransformer();
44 this.connection = connection;
45 if (queryRunner) {
46 this.queryRunner = queryRunner;
47 // dynamic: this.queryRunner = manager;
48 ObjectUtils_1.ObjectUtils.assign(this.queryRunner, { manager: this });
49 }
50 }
51 /**
52 * Wraps given function execution (and all operations made there) in a transaction.
53 * All database operations must be executed using provided entity manager.
54 */
55 EntityManager.prototype.transaction = function (isolationOrRunInTransaction, runInTransactionParam) {
56 return tslib_1.__awaiter(this, void 0, void 0, function () {
57 var isolation, runInTransaction, queryRunner, result, err_1, rollbackError_1;
58 return tslib_1.__generator(this, function (_a) {
59 switch (_a.label) {
60 case 0:
61 isolation = typeof isolationOrRunInTransaction === "string" ? isolationOrRunInTransaction : undefined;
62 runInTransaction = typeof isolationOrRunInTransaction === "function" ? isolationOrRunInTransaction : runInTransactionParam;
63 if (!runInTransaction) {
64 throw new Error("Transaction method requires callback in second paramter if isolation level is supplied.");
65 }
66 if (this.connection.driver instanceof MongoDriver_1.MongoDriver)
67 throw new Error("Transactions aren't supported by MongoDB.");
68 if (this.queryRunner && this.queryRunner.isReleased)
69 throw new QueryRunnerProviderAlreadyReleasedError_1.QueryRunnerProviderAlreadyReleasedError();
70 if (this.queryRunner && this.queryRunner.isTransactionActive)
71 throw new Error("Cannot start transaction because its already started");
72 queryRunner = this.queryRunner || this.connection.createQueryRunner("master");
73 _a.label = 1;
74 case 1:
75 _a.trys.push([1, 8, 13, 16]);
76 if (!isolation) return [3 /*break*/, 3];
77 return [4 /*yield*/, queryRunner.startTransaction(isolation)];
78 case 2:
79 _a.sent();
80 return [3 /*break*/, 5];
81 case 3: return [4 /*yield*/, queryRunner.startTransaction()];
82 case 4:
83 _a.sent();
84 _a.label = 5;
85 case 5: return [4 /*yield*/, runInTransaction(queryRunner.manager)];
86 case 6:
87 result = _a.sent();
88 return [4 /*yield*/, queryRunner.commitTransaction()];
89 case 7:
90 _a.sent();
91 return [2 /*return*/, result];
92 case 8:
93 err_1 = _a.sent();
94 _a.label = 9;
95 case 9:
96 _a.trys.push([9, 11, , 12]);
97 return [4 /*yield*/, queryRunner.rollbackTransaction()];
98 case 10:
99 _a.sent();
100 return [3 /*break*/, 12];
101 case 11:
102 rollbackError_1 = _a.sent();
103 return [3 /*break*/, 12];
104 case 12: throw err_1;
105 case 13:
106 if (!!this.queryRunner) return [3 /*break*/, 15];
107 return [4 /*yield*/, queryRunner.release()];
108 case 14:
109 _a.sent();
110 _a.label = 15;
111 case 15: return [7 /*endfinally*/];
112 case 16: return [2 /*return*/];
113 }
114 });
115 });
116 };
117 /**
118 * Executes raw SQL query and returns raw database results.
119 */
120 EntityManager.prototype.query = function (query, parameters) {
121 return tslib_1.__awaiter(this, void 0, void 0, function () {
122 return tslib_1.__generator(this, function (_a) {
123 return [2 /*return*/, this.connection.query(query, parameters, this.queryRunner)];
124 });
125 });
126 };
127 /**
128 * Creates a new query builder that can be used to build a sql query.
129 */
130 EntityManager.prototype.createQueryBuilder = function (entityClass, alias, queryRunner) {
131 if (alias) {
132 return this.connection.createQueryBuilder(entityClass, alias, queryRunner || this.queryRunner);
133 }
134 else {
135 return this.connection.createQueryBuilder(entityClass || queryRunner || this.queryRunner);
136 }
137 };
138 /**
139 * Checks if entity has an id by its Function type or schema name.
140 */
141 EntityManager.prototype.hasId = function (targetOrEntity, maybeEntity) {
142 var target = arguments.length === 2 ? targetOrEntity : targetOrEntity.constructor;
143 var entity = arguments.length === 2 ? maybeEntity : targetOrEntity;
144 var metadata = this.connection.getMetadata(target);
145 return metadata.hasId(entity);
146 };
147 /**
148 * Gets entity mixed id.
149 */
150 EntityManager.prototype.getId = function (targetOrEntity, maybeEntity) {
151 var target = arguments.length === 2 ? targetOrEntity : targetOrEntity.constructor;
152 var entity = arguments.length === 2 ? maybeEntity : targetOrEntity;
153 var metadata = this.connection.getMetadata(target);
154 return metadata.getEntityIdMixedMap(entity);
155 };
156 /**
157 * Creates a new entity instance or instances.
158 * Can copy properties from the given object into new entities.
159 */
160 EntityManager.prototype.create = function (entityClass, plainObjectOrObjects) {
161 var _this = this;
162 var metadata = this.connection.getMetadata(entityClass);
163 if (!plainObjectOrObjects)
164 return metadata.create(this.queryRunner);
165 if (plainObjectOrObjects instanceof Array)
166 return plainObjectOrObjects.map(function (plainEntityLike) { return _this.create(entityClass, plainEntityLike); });
167 var mergeIntoEntity = metadata.create(this.queryRunner);
168 this.plainObjectToEntityTransformer.transform(mergeIntoEntity, plainObjectOrObjects, metadata, true);
169 return mergeIntoEntity;
170 };
171 /**
172 * Merges two entities into one new entity.
173 */
174 EntityManager.prototype.merge = function (entityClass, mergeIntoEntity) {
175 var _this = this;
176 var entityLikes = [];
177 for (var _i = 2; _i < arguments.length; _i++) {
178 entityLikes[_i - 2] = arguments[_i];
179 }
180 var metadata = this.connection.getMetadata(entityClass);
181 entityLikes.forEach(function (object) { return _this.plainObjectToEntityTransformer.transform(mergeIntoEntity, object, metadata); });
182 return mergeIntoEntity;
183 };
184 /**
185 * Creates a new entity from the given plan javascript object. If entity already exist in the database, then
186 * it loads it (and everything related to it), replaces all values with the new ones from the given object
187 * and returns this new entity. This new entity is actually a loaded from the db entity with all properties
188 * replaced from the new object.
189 */
190 EntityManager.prototype.preload = function (entityClass, entityLike) {
191 return tslib_1.__awaiter(this, void 0, void 0, function () {
192 var metadata, plainObjectToDatabaseEntityTransformer, transformedEntity;
193 return tslib_1.__generator(this, function (_a) {
194 switch (_a.label) {
195 case 0:
196 metadata = this.connection.getMetadata(entityClass);
197 plainObjectToDatabaseEntityTransformer = new PlainObjectToDatabaseEntityTransformer_1.PlainObjectToDatabaseEntityTransformer(this.connection.manager);
198 return [4 /*yield*/, plainObjectToDatabaseEntityTransformer.transform(entityLike, metadata)];
199 case 1:
200 transformedEntity = _a.sent();
201 if (transformedEntity)
202 return [2 /*return*/, this.merge(entityClass, transformedEntity, entityLike)];
203 return [2 /*return*/, undefined];
204 }
205 });
206 });
207 };
208 /**
209 * Saves a given entity in the database.
210 */
211 EntityManager.prototype.save = function (targetOrEntity, maybeEntityOrOptions, maybeOptions) {
212 // normalize mixed parameters
213 var target = (arguments.length > 1 && (targetOrEntity instanceof Function || targetOrEntity instanceof index_1.EntitySchema || typeof targetOrEntity === "string")) ? targetOrEntity : undefined;
214 var entity = target ? maybeEntityOrOptions : targetOrEntity;
215 var options = target ? maybeOptions : maybeEntityOrOptions;
216 if (target instanceof index_1.EntitySchema)
217 target = target.options.name;
218 // if user passed empty array of entities then we don't need to do anything
219 if (entity instanceof Array && entity.length === 0)
220 return Promise.resolve(entity);
221 // execute save operation
222 return new EntityPersistExecutor_1.EntityPersistExecutor(this.connection, this.queryRunner, "save", target, entity, options)
223 .execute()
224 .then(function () { return entity; });
225 };
226 /**
227 * Removes a given entity from the database.
228 */
229 EntityManager.prototype.remove = function (targetOrEntity, maybeEntityOrOptions, maybeOptions) {
230 // normalize mixed parameters
231 var target = (arguments.length > 1 && (targetOrEntity instanceof Function || typeof targetOrEntity === "string")) ? targetOrEntity : undefined;
232 var entity = target ? maybeEntityOrOptions : targetOrEntity;
233 var options = target ? maybeOptions : maybeEntityOrOptions;
234 // if user passed empty array of entities then we don't need to do anything
235 if (entity instanceof Array && entity.length === 0)
236 return Promise.resolve(entity);
237 // execute save operation
238 return new EntityPersistExecutor_1.EntityPersistExecutor(this.connection, this.queryRunner, "remove", target, entity, options)
239 .execute()
240 .then(function () { return entity; });
241 };
242 /**
243 * Inserts a given entity into the database.
244 * Unlike save method executes a primitive operation without cascades, relations and other operations included.
245 * Executes fast and efficient INSERT query.
246 * Does not check if entity exist in the database, so query will fail if duplicate entity is being inserted.
247 * You can execute bulk inserts using this method.
248 */
249 EntityManager.prototype.insert = function (target, entity) {
250 return tslib_1.__awaiter(this, void 0, void 0, function () {
251 var results;
252 var _this = this;
253 return tslib_1.__generator(this, function (_a) {
254 switch (_a.label) {
255 case 0:
256 if (!(this.connection.driver instanceof OracleDriver_1.OracleDriver && entity instanceof Array)) return [3 /*break*/, 2];
257 return [4 /*yield*/, Promise.all(entity.map(function (entity) { return _this.insert(target, entity); }))];
258 case 1:
259 results = _a.sent();
260 return [2 /*return*/, results.reduce(function (mergedResult, result) { return Object.assign(mergedResult, result); }, {})];
261 case 2: return [2 /*return*/, this.createQueryBuilder()
262 .insert()
263 .into(target)
264 .values(entity)
265 .execute()];
266 }
267 });
268 });
269 };
270 /**
271 * Updates entity partially. Entity can be found by a given condition(s).
272 * Unlike save method executes a primitive operation without cascades, relations and other operations included.
273 * Executes fast and efficient UPDATE query.
274 * Does not check if entity exist in the database.
275 * Condition(s) cannot be empty.
276 */
277 EntityManager.prototype.update = function (target, criteria, partialEntity) {
278 // if user passed empty criteria or empty list of criterias, then throw an error
279 if (criteria === undefined ||
280 criteria === null ||
281 criteria === "" ||
282 (criteria instanceof Array && criteria.length === 0)) {
283 return Promise.reject(new Error("Empty criteria(s) are not allowed for the update method."));
284 }
285 if (typeof criteria === "string" ||
286 typeof criteria === "number" ||
287 criteria instanceof Date ||
288 criteria instanceof Array) {
289 return this.createQueryBuilder()
290 .update(target)
291 .set(partialEntity)
292 .whereInIds(criteria)
293 .execute();
294 }
295 else {
296 return this.createQueryBuilder()
297 .update(target)
298 .set(partialEntity)
299 .where(criteria)
300 .execute();
301 }
302 };
303 /**
304 * Deletes entities by a given condition(s).
305 * Unlike save method executes a primitive operation without cascades, relations and other operations included.
306 * Executes fast and efficient DELETE query.
307 * Does not check if entity exist in the database.
308 * Condition(s) cannot be empty.
309 */
310 EntityManager.prototype.delete = function (targetOrEntity, criteria) {
311 // if user passed empty criteria or empty list of criterias, then throw an error
312 if (criteria === undefined ||
313 criteria === null ||
314 criteria === "" ||
315 (criteria instanceof Array && criteria.length === 0)) {
316 return Promise.reject(new Error("Empty criteria(s) are not allowed for the delete method."));
317 }
318 if (typeof criteria === "string" ||
319 typeof criteria === "number" ||
320 criteria instanceof Date ||
321 criteria instanceof Array) {
322 return this.createQueryBuilder()
323 .delete()
324 .from(targetOrEntity)
325 .whereInIds(criteria)
326 .execute();
327 }
328 else {
329 return this.createQueryBuilder()
330 .delete()
331 .from(targetOrEntity)
332 .where(criteria)
333 .execute();
334 }
335 };
336 /**
337 * Counts entities that match given find options or conditions.
338 * Useful for pagination.
339 */
340 EntityManager.prototype.count = function (entityClass, optionsOrConditions) {
341 return tslib_1.__awaiter(this, void 0, void 0, function () {
342 var metadata, qb;
343 return tslib_1.__generator(this, function (_a) {
344 metadata = this.connection.getMetadata(entityClass);
345 qb = this.createQueryBuilder(entityClass, FindOptionsUtils_1.FindOptionsUtils.extractFindManyOptionsAlias(optionsOrConditions) || metadata.name);
346 return [2 /*return*/, FindOptionsUtils_1.FindOptionsUtils.applyFindManyOptionsOrConditionsToQueryBuilder(qb, optionsOrConditions).getCount()];
347 });
348 });
349 };
350 /**
351 * Finds entities that match given find options or conditions.
352 */
353 EntityManager.prototype.find = function (entityClass, optionsOrConditions) {
354 return tslib_1.__awaiter(this, void 0, void 0, function () {
355 var metadata, qb;
356 return tslib_1.__generator(this, function (_a) {
357 metadata = this.connection.getMetadata(entityClass);
358 qb = this.createQueryBuilder(entityClass, FindOptionsUtils_1.FindOptionsUtils.extractFindManyOptionsAlias(optionsOrConditions) || metadata.name);
359 if (!FindOptionsUtils_1.FindOptionsUtils.isFindManyOptions(optionsOrConditions) || optionsOrConditions.loadEagerRelations !== false)
360 FindOptionsUtils_1.FindOptionsUtils.joinEagerRelations(qb, qb.alias, metadata);
361 return [2 /*return*/, FindOptionsUtils_1.FindOptionsUtils.applyFindManyOptionsOrConditionsToQueryBuilder(qb, optionsOrConditions).getMany()];
362 });
363 });
364 };
365 /**
366 * Finds entities that match given find options and conditions.
367 * Also counts all entities that match given conditions,
368 * but ignores pagination settings (from and take options).
369 */
370 EntityManager.prototype.findAndCount = function (entityClass, optionsOrConditions) {
371 return tslib_1.__awaiter(this, void 0, void 0, function () {
372 var metadata, qb;
373 return tslib_1.__generator(this, function (_a) {
374 metadata = this.connection.getMetadata(entityClass);
375 qb = this.createQueryBuilder(entityClass, FindOptionsUtils_1.FindOptionsUtils.extractFindManyOptionsAlias(optionsOrConditions) || metadata.name);
376 if (!FindOptionsUtils_1.FindOptionsUtils.isFindManyOptions(optionsOrConditions) || optionsOrConditions.loadEagerRelations !== false)
377 FindOptionsUtils_1.FindOptionsUtils.joinEagerRelations(qb, qb.alias, metadata);
378 return [2 /*return*/, FindOptionsUtils_1.FindOptionsUtils.applyFindManyOptionsOrConditionsToQueryBuilder(qb, optionsOrConditions).getManyAndCount()];
379 });
380 });
381 };
382 /**
383 * Finds entities with ids.
384 * Optionally find options or conditions can be applied.
385 */
386 EntityManager.prototype.findByIds = function (entityClass, ids, optionsOrConditions) {
387 return tslib_1.__awaiter(this, void 0, void 0, function () {
388 var metadata, qb;
389 return tslib_1.__generator(this, function (_a) {
390 // if no ids passed, no need to execute a query - just return an empty array of values
391 if (!ids.length)
392 return [2 /*return*/, Promise.resolve([])];
393 metadata = this.connection.getMetadata(entityClass);
394 qb = this.createQueryBuilder(entityClass, FindOptionsUtils_1.FindOptionsUtils.extractFindManyOptionsAlias(optionsOrConditions) || metadata.name);
395 FindOptionsUtils_1.FindOptionsUtils.applyFindManyOptionsOrConditionsToQueryBuilder(qb, optionsOrConditions);
396 if (!FindOptionsUtils_1.FindOptionsUtils.isFindManyOptions(optionsOrConditions) || optionsOrConditions.loadEagerRelations !== false)
397 FindOptionsUtils_1.FindOptionsUtils.joinEagerRelations(qb, qb.alias, metadata);
398 return [2 /*return*/, qb.andWhereInIds(ids).getMany()];
399 });
400 });
401 };
402 /**
403 * Finds first entity that matches given conditions.
404 */
405 EntityManager.prototype.findOne = function (entityClass, idOrOptionsOrConditions, maybeOptions) {
406 return tslib_1.__awaiter(this, void 0, void 0, function () {
407 var findOptions, options, metadata, alias, qb;
408 return tslib_1.__generator(this, function (_a) {
409 findOptions = undefined;
410 if (FindOptionsUtils_1.FindOptionsUtils.isFindOneOptions(idOrOptionsOrConditions)) {
411 findOptions = idOrOptionsOrConditions;
412 }
413 else if (maybeOptions && FindOptionsUtils_1.FindOptionsUtils.isFindOneOptions(maybeOptions)) {
414 findOptions = maybeOptions;
415 }
416 options = undefined;
417 if (idOrOptionsOrConditions instanceof Object && !FindOptionsUtils_1.FindOptionsUtils.isFindOneOptions(idOrOptionsOrConditions))
418 options = idOrOptionsOrConditions;
419 metadata = this.connection.getMetadata(entityClass);
420 alias = metadata.name;
421 if (findOptions && findOptions.join) {
422 alias = findOptions.join.alias;
423 }
424 else if (maybeOptions && FindOptionsUtils_1.FindOptionsUtils.isFindOneOptions(maybeOptions) && maybeOptions.join) {
425 alias = maybeOptions.join.alias;
426 }
427 qb = this.createQueryBuilder(entityClass, alias);
428 if (!findOptions || findOptions.loadEagerRelations !== false)
429 FindOptionsUtils_1.FindOptionsUtils.joinEagerRelations(qb, qb.alias, qb.expressionMap.mainAlias.metadata);
430 findOptions = tslib_1.__assign({}, (findOptions || {}), { take: 1 });
431 FindOptionsUtils_1.FindOptionsUtils.applyOptionsToQueryBuilder(qb, findOptions);
432 if (options) {
433 qb.where(options);
434 }
435 else if (typeof idOrOptionsOrConditions === "string" || typeof idOrOptionsOrConditions === "number" || idOrOptionsOrConditions instanceof Date) {
436 qb.andWhereInIds(metadata.ensureEntityIdMap(idOrOptionsOrConditions));
437 }
438 return [2 /*return*/, qb.getOne()];
439 });
440 });
441 };
442 /**
443 * Finds first entity that matches given conditions or rejects the returned promise on error.
444 */
445 EntityManager.prototype.findOneOrFail = function (entityClass, idOrOptionsOrConditions, maybeOptions) {
446 return tslib_1.__awaiter(this, void 0, void 0, function () {
447 return tslib_1.__generator(this, function (_a) {
448 return [2 /*return*/, this.findOne(entityClass, idOrOptionsOrConditions, maybeOptions).then(function (value) {
449 if (value === undefined) {
450 return Promise.reject(new EntityNotFoundError_1.EntityNotFoundError(entityClass, idOrOptionsOrConditions));
451 }
452 return Promise.resolve(value);
453 })];
454 });
455 });
456 };
457 /**
458 * Clears all the data from the given table (truncates/drops it).
459 *
460 * Note: this method uses TRUNCATE and may not work as you expect in transactions on some platforms.
461 * @see https://stackoverflow.com/a/5972738/925151
462 */
463 EntityManager.prototype.clear = function (entityClass) {
464 return tslib_1.__awaiter(this, void 0, void 0, function () {
465 var metadata, queryRunner;
466 return tslib_1.__generator(this, function (_a) {
467 switch (_a.label) {
468 case 0:
469 metadata = this.connection.getMetadata(entityClass);
470 queryRunner = this.queryRunner || this.connection.createQueryRunner("master");
471 _a.label = 1;
472 case 1:
473 _a.trys.push([1, , 3, 6]);
474 return [4 /*yield*/, queryRunner.clearTable(metadata.tablePath)];
475 case 2: return [2 /*return*/, _a.sent()]; // await is needed here because we are using finally
476 case 3:
477 if (!!this.queryRunner) return [3 /*break*/, 5];
478 return [4 /*yield*/, queryRunner.release()];
479 case 4:
480 _a.sent();
481 _a.label = 5;
482 case 5: return [7 /*endfinally*/];
483 case 6: return [2 /*return*/];
484 }
485 });
486 });
487 };
488 /**
489 * Increments some column by provided value of the entities matched given conditions.
490 */
491 EntityManager.prototype.increment = function (entityClass, conditions, propertyPath, value) {
492 return tslib_1.__awaiter(this, void 0, void 0, function () {
493 var metadata, column, values;
494 var _this = this;
495 return tslib_1.__generator(this, function (_a) {
496 metadata = this.connection.getMetadata(entityClass);
497 column = metadata.findColumnWithPropertyPath(propertyPath);
498 if (!column)
499 throw new Error("Column " + propertyPath + " was not found in " + metadata.targetName + " entity.");
500 if (isNaN(Number(value)))
501 throw new Error("Value \"" + value + "\" is not a number.");
502 values = propertyPath
503 .split(".")
504 .reduceRight(function (value, key) {
505 var _a;
506 return (_a = {}, _a[key] = value, _a);
507 }, function () { return _this.connection.driver.escape(column.databaseName) + " + " + value; });
508 return [2 /*return*/, this
509 .createQueryBuilder(entityClass, "entity")
510 .update(entityClass)
511 .set(values)
512 .where(conditions)
513 .execute()];
514 });
515 });
516 };
517 /**
518 * Decrements some column by provided value of the entities matched given conditions.
519 */
520 EntityManager.prototype.decrement = function (entityClass, conditions, propertyPath, value) {
521 return tslib_1.__awaiter(this, void 0, void 0, function () {
522 var metadata, column, values;
523 var _this = this;
524 return tslib_1.__generator(this, function (_a) {
525 metadata = this.connection.getMetadata(entityClass);
526 column = metadata.findColumnWithPropertyPath(propertyPath);
527 if (!column)
528 throw new Error("Column " + propertyPath + " was not found in " + metadata.targetName + " entity.");
529 if (isNaN(Number(value)))
530 throw new Error("Value \"" + value + "\" is not a number.");
531 values = propertyPath
532 .split(".")
533 .reduceRight(function (value, key) {
534 var _a;
535 return (_a = {}, _a[key] = value, _a);
536 }, function () { return _this.connection.driver.escape(column.databaseName) + " - " + value; });
537 return [2 /*return*/, this
538 .createQueryBuilder(entityClass, "entity")
539 .update(entityClass)
540 .set(values)
541 .where(conditions)
542 .execute()];
543 });
544 });
545 };
546 /**
547 * Gets repository for the given entity class or name.
548 * If single database connection mode is used, then repository is obtained from the
549 * repository aggregator, where each repository is individually created for this entity manager.
550 * When single database connection is not used, repository is being obtained from the connection.
551 */
552 EntityManager.prototype.getRepository = function (target) {
553 // throw exception if there is no repository with this target registered
554 if (!this.connection.hasMetadata(target))
555 throw new RepositoryNotFoundError_1.RepositoryNotFoundError(this.connection.name, target);
556 // find already created repository instance and return it if found
557 var metadata = this.connection.getMetadata(target);
558 var repository = this.repositories.find(function (repository) { return repository.metadata === metadata; });
559 if (repository)
560 return repository;
561 // if repository was not found then create it, store its instance and return it
562 var newRepository = new RepositoryFactory_1.RepositoryFactory().create(this, metadata, this.queryRunner);
563 this.repositories.push(newRepository);
564 return newRepository;
565 };
566 /**
567 * Gets tree repository for the given entity class or name.
568 * If single database connection mode is used, then repository is obtained from the
569 * repository aggregator, where each repository is individually created for this entity manager.
570 * When single database connection is not used, repository is being obtained from the connection.
571 */
572 EntityManager.prototype.getTreeRepository = function (target) {
573 // tree tables aren't supported by some drivers (mongodb)
574 if (this.connection.driver.treeSupport === false)
575 throw new TreeRepositoryNotSupportedError_1.TreeRepositoryNotSupportedError(this.connection.driver);
576 // check if repository is real tree repository
577 var repository = this.getRepository(target);
578 if (!(repository instanceof TreeRepository_1.TreeRepository))
579 throw new RepositoryNotTreeError_1.RepositoryNotTreeError(target);
580 return repository;
581 };
582 /**
583 * Gets mongodb repository for the given entity class.
584 */
585 EntityManager.prototype.getMongoRepository = function (target) {
586 return this.connection.getMongoRepository(target);
587 };
588 /**
589 * Gets custom entity repository marked with @EntityRepository decorator.
590 */
591 EntityManager.prototype.getCustomRepository = function (customRepository) {
592 var entityRepositoryMetadataArgs = index_1.getMetadataArgsStorage().entityRepositories.find(function (repository) {
593 return repository.target === (customRepository instanceof Function ? customRepository : customRepository.constructor);
594 });
595 if (!entityRepositoryMetadataArgs)
596 throw new CustomRepositoryNotFoundError_1.CustomRepositoryNotFoundError(customRepository);
597 var entityMetadata = entityRepositoryMetadataArgs.entity ? this.connection.getMetadata(entityRepositoryMetadataArgs.entity) : undefined;
598 var entityRepositoryInstance = new entityRepositoryMetadataArgs.target(this, entityMetadata);
599 // NOTE: dynamic access to protected properties. We need this to prevent unwanted properties in those classes to be exposed,
600 // however we need these properties for internal work of the class
601 if (entityRepositoryInstance instanceof AbstractRepository_1.AbstractRepository) {
602 if (!entityRepositoryInstance["manager"])
603 entityRepositoryInstance["manager"] = this;
604 }
605 if (entityRepositoryInstance instanceof Repository_1.Repository) {
606 if (!entityMetadata)
607 throw new CustomRepositoryCannotInheritRepositoryError_1.CustomRepositoryCannotInheritRepositoryError(customRepository);
608 entityRepositoryInstance["manager"] = this;
609 entityRepositoryInstance["metadata"] = entityMetadata;
610 }
611 return entityRepositoryInstance;
612 };
613 /**
614 * Releases all resources used by entity manager.
615 * This is used when entity manager is created with a single query runner,
616 * and this single query runner needs to be released after job with entity manager is done.
617 */
618 EntityManager.prototype.release = function () {
619 return tslib_1.__awaiter(this, void 0, void 0, function () {
620 return tslib_1.__generator(this, function (_a) {
621 if (!this.queryRunner)
622 throw new NoNeedToReleaseEntityManagerError_1.NoNeedToReleaseEntityManagerError();
623 return [2 /*return*/, this.queryRunner.release()];
624 });
625 });
626 };
627 return EntityManager;
628}());
629exports.EntityManager = EntityManager;
630
631//# sourceMappingURL=EntityManager.js.map