typeorm 0.3.30 → 0.3.31

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/README.md +2 -2
  2. package/browser/data-source/BaseDataSourceOptions.d.ts +7 -20
  3. package/browser/data-source/BaseDataSourceOptions.js.map +1 -1
  4. package/browser/driver/types/InvalidFindOptionsWhereBehavior.d.ts +15 -0
  5. package/browser/driver/types/InvalidFindOptionsWhereBehavior.js +3 -0
  6. package/browser/driver/types/InvalidFindOptionsWhereBehavior.js.map +1 -0
  7. package/browser/entity-manager/EntityManager.d.ts +23 -0
  8. package/browser/entity-manager/EntityManager.js +79 -106
  9. package/browser/entity-manager/EntityManager.js.map +1 -1
  10. package/browser/metadata/types/ClosureTreeOptions.d.ts +1 -0
  11. package/browser/metadata/types/ClosureTreeOptions.js.map +1 -1
  12. package/browser/metadata-builder/ClosureJunctionEntityMetadataBuilder.js +6 -2
  13. package/browser/metadata-builder/ClosureJunctionEntityMetadataBuilder.js.map +1 -1
  14. package/browser/persistence/SubjectExecutor.js +0 -8
  15. package/browser/persistence/SubjectExecutor.js.map +1 -1
  16. package/browser/query-builder/QueryBuilder.js +17 -0
  17. package/browser/query-builder/QueryBuilder.js.map +1 -1
  18. package/browser/repository/TreeRepository.js +2 -2
  19. package/browser/repository/TreeRepository.js.map +1 -1
  20. package/browser/util/OrmUtils.d.ts +16 -9
  21. package/browser/util/OrmUtils.js +33 -13
  22. package/browser/util/OrmUtils.js.map +1 -1
  23. package/commands/MigrationGenerateCommand.d.ts +6 -0
  24. package/commands/MigrationGenerateCommand.js +13 -2
  25. package/commands/MigrationGenerateCommand.js.map +1 -1
  26. package/data-source/BaseDataSourceOptions.d.ts +7 -20
  27. package/data-source/BaseDataSourceOptions.js.map +1 -1
  28. package/driver/types/InvalidFindOptionsWhereBehavior.d.ts +15 -0
  29. package/driver/types/InvalidFindOptionsWhereBehavior.js +4 -0
  30. package/driver/types/InvalidFindOptionsWhereBehavior.js.map +1 -0
  31. package/entity-manager/EntityManager.d.ts +23 -0
  32. package/entity-manager/EntityManager.js +79 -106
  33. package/entity-manager/EntityManager.js.map +1 -1
  34. package/metadata/types/ClosureTreeOptions.d.ts +1 -0
  35. package/metadata/types/ClosureTreeOptions.js.map +1 -1
  36. package/metadata-builder/ClosureJunctionEntityMetadataBuilder.js +6 -2
  37. package/metadata-builder/ClosureJunctionEntityMetadataBuilder.js.map +1 -1
  38. package/package.json +18 -19
  39. package/persistence/SubjectExecutor.js +0 -8
  40. package/persistence/SubjectExecutor.js.map +1 -1
  41. package/query-builder/QueryBuilder.js +17 -0
  42. package/query-builder/QueryBuilder.js.map +1 -1
  43. package/repository/TreeRepository.js +2 -2
  44. package/repository/TreeRepository.js.map +1 -1
  45. package/util/OrmUtils.d.ts +16 -9
  46. package/util/OrmUtils.js +33 -13
  47. package/util/OrmUtils.js.map +1 -1
@@ -1,11 +1,12 @@
1
+ import { QueryResultCache } from "../cache/QueryResultCache";
2
+ import { MixedList } from "../common/MixedList";
3
+ import { DataSource } from "../data-source/DataSource";
4
+ import { DatabaseType } from "../driver/types/DatabaseType";
5
+ import type { InvalidFindOptionsWhereBehavior } from "../driver/types/InvalidFindOptionsWhereBehavior";
1
6
  import { EntitySchema } from "../entity-schema/EntitySchema";
7
+ import { Logger } from "../logger/Logger";
2
8
  import { LoggerOptions } from "../logger/LoggerOptions";
3
9
  import { NamingStrategyInterface } from "../naming-strategy/NamingStrategyInterface";
4
- import { DatabaseType } from "../driver/types/DatabaseType";
5
- import { Logger } from "../logger/Logger";
6
- import { DataSource } from "../data-source/DataSource";
7
- import { QueryResultCache } from "../cache/QueryResultCache";
8
- import { MixedList } from "../common/MixedList";
9
10
  /**
10
11
  * BaseDataSourceOptions is set of DataSourceOptions shared by all database types.
11
12
  */
@@ -169,19 +170,5 @@ export interface BaseDataSourceOptions {
169
170
  /**
170
171
  * Controls how null and undefined values are handled in find operations.
171
172
  */
172
- readonly invalidWhereValuesBehavior?: {
173
- /**
174
- * How to handle null values in where conditions.
175
- * - 'ignore': Skip null properties (default)
176
- * - 'sql-null': Transform null to SQL NULL
177
- * - 'throw': Throw an error when null is encountered
178
- */
179
- readonly null?: "ignore" | "sql-null" | "throw";
180
- /**
181
- * How to handle undefined values in where conditions.
182
- * - 'ignore': Skip undefined properties (default)
183
- * - 'throw': Throw an error when undefined is encountered
184
- */
185
- readonly undefined?: "ignore" | "throw";
186
- };
173
+ readonly invalidWhereValuesBehavior?: InvalidFindOptionsWhereBehavior;
187
174
  }
@@ -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 | \"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 /**\n * Controls how null and undefined values are handled in find operations.\n */\n readonly invalidWhereValuesBehavior?: {\n /**\n * How to handle null values in where conditions.\n * - 'ignore': Skip null properties (default)\n * - 'sql-null': Transform null to SQL NULL\n * - 'throw': Throw an error when null is encountered\n */\n readonly null?: \"ignore\" | \"sql-null\" | \"throw\"\n\n /**\n * How to handle undefined values in where conditions.\n * - 'ignore': Skip undefined properties (default)\n * - 'throw': Throw an error when undefined is encountered\n */\n readonly undefined?: \"ignore\" | \"throw\"\n }\n}\n"],"sourceRoot":".."}
1
+ {"version":3,"sources":["../../src/data-source/BaseDataSourceOptions.ts"],"names":[],"mappings":"","file":"BaseDataSourceOptions.js","sourcesContent":["import { QueryResultCache } from \"../cache/QueryResultCache\"\nimport { MixedList } from \"../common/MixedList\"\nimport { DataSource } from \"../data-source/DataSource\"\nimport { DatabaseType } from \"../driver/types/DatabaseType\"\nimport type { InvalidFindOptionsWhereBehavior } from \"../driver/types/InvalidFindOptionsWhereBehavior\"\nimport { EntitySchema } from \"../entity-schema/EntitySchema\"\nimport { Logger } from \"../logger/Logger\"\nimport { LoggerOptions } from \"../logger/LoggerOptions\"\nimport { NamingStrategyInterface } from \"../naming-strategy/NamingStrategyInterface\"\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 /**\n * Controls how null and undefined values are handled in find operations.\n */\n readonly invalidWhereValuesBehavior?: InvalidFindOptionsWhereBehavior\n}\n"],"sourceRoot":".."}
@@ -0,0 +1,15 @@
1
+ export type InvalidFindOptionsWhereBehavior = {
2
+ /**
3
+ * How to handle null values in where conditions.
4
+ * - 'ignore': Skip null properties (default)
5
+ * - 'sql-null': Transform null to SQL NULL
6
+ * - 'throw': Throw an error when null is encountered
7
+ */
8
+ readonly null?: "ignore" | "sql-null" | "throw";
9
+ /**
10
+ * How to handle undefined values in where conditions.
11
+ * - 'ignore': Skip undefined properties (default)
12
+ * - 'throw': Throw an error when undefined is encountered
13
+ */
14
+ readonly undefined?: "ignore" | "throw";
15
+ };
@@ -0,0 +1,4 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+
4
+ //# sourceMappingURL=InvalidFindOptionsWhereBehavior.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/driver/types/InvalidFindOptionsWhereBehavior.ts"],"names":[],"mappings":"","file":"InvalidFindOptionsWhereBehavior.js","sourcesContent":["export type InvalidFindOptionsWhereBehavior = {\n /**\n * How to handle null values in where conditions.\n * - 'ignore': Skip null properties (default)\n * - 'sql-null': Transform null to SQL NULL\n * - 'throw': Throw an error when null is encountered\n */\n readonly null?: \"ignore\" | \"sql-null\" | \"throw\"\n\n /**\n * How to handle undefined values in where conditions.\n * - 'ignore': Skip undefined properties (default)\n * - 'throw': Throw an error when undefined is encountered\n */\n readonly undefined?: \"ignore\" | \"throw\"\n}\n"],"sourceRoot":"../.."}
@@ -212,6 +212,23 @@ export declare class EntityManager {
212
212
  */
213
213
  insert<Entity extends ObjectLiteral>(target: EntityTarget<Entity>, entity: QueryDeepPartialEntity<Entity> | QueryDeepPartialEntity<Entity>[]): Promise<InsertResult>;
214
214
  upsert<Entity extends ObjectLiteral>(target: EntityTarget<Entity>, entityOrEntities: QueryDeepPartialEntity<Entity> | QueryDeepPartialEntity<Entity>[], conflictPathsOrOptions: string[] | UpsertOptions<Entity>): Promise<InsertResult>;
215
+ /**
216
+ * Shared by update/delete/softDelete/restore. Object criteria is normalized
217
+ * via {@link OrmUtils.normalizeWhereCriteria}, then rejected if it would
218
+ * produce no predicate and therefore render as an always-true `WHERE 1=1` —
219
+ * an empty object or array, an empty OR-branch, a bare primitive inside an
220
+ * OR-array, or a keyless object. Primitive id criteria is returned untouched
221
+ * for `whereInIds` (rejected only when wholly empty).
222
+ *
223
+ * @param criteria the raw criteria passed to the operation
224
+ * @param methodName the calling method, used in the error message
225
+ * @returns the criteria to build with, and whether to execute it via
226
+ * `whereInIds` (primitive) or `where` (object)
227
+ */
228
+ protected normalizeAndValidateWhereCriteria(criteria: any, methodName: string): {
229
+ criteria: any;
230
+ isPrimitive: boolean;
231
+ };
215
232
  /**
216
233
  * Updates entity partially. Entity can be found by a given condition(s).
217
234
  * Unlike save method executes a primitive operation without cascades, relations and other operations included.
@@ -372,6 +389,12 @@ export declare class EntityManager {
372
389
  * Decrements some column by provided value of the entities matched given conditions.
373
390
  */
374
391
  decrement<Entity extends ObjectLiteral>(entityClass: EntityTarget<Entity>, conditions: any, propertyPath: string, value: number | string): Promise<UpdateResult>;
392
+ /**
393
+ * Shared implementation of {@link increment} and {@link decrement}: builds a
394
+ * `column = column +/- value` UPDATE and delegates execution to {@link update},
395
+ * so the criteria handling stays aligned with the other write methods.
396
+ */
397
+ protected incrementOrDecrementBy<Entity extends ObjectLiteral>(operation: "increment" | "decrement", entityClass: EntityTarget<Entity>, conditions: any, propertyPath: string, value: number | string): Promise<UpdateResult>;
375
398
  /**
376
399
  * Gets repository for the given entity class or name.
377
400
  * If single database connection mode is used, then repository is obtained from the
@@ -339,6 +339,51 @@ class EntityManager {
339
339
  }
340
340
  return qb.execute();
341
341
  }
342
+ /**
343
+ * Shared by update/delete/softDelete/restore. Object criteria is normalized
344
+ * via {@link OrmUtils.normalizeWhereCriteria}, then rejected if it would
345
+ * produce no predicate and therefore render as an always-true `WHERE 1=1` —
346
+ * an empty object or array, an empty OR-branch, a bare primitive inside an
347
+ * OR-array, or a keyless object. Primitive id criteria is returned untouched
348
+ * for `whereInIds` (rejected only when wholly empty).
349
+ *
350
+ * @param criteria the raw criteria passed to the operation
351
+ * @param methodName the calling method, used in the error message
352
+ * @returns the criteria to build with, and whether to execute it via
353
+ * `whereInIds` (primitive) or `where` (object)
354
+ */
355
+ normalizeAndValidateWhereCriteria(criteria, methodName) {
356
+ const rejectEmpty = () => {
357
+ throw new error_1.TypeORMError(`Empty criteria(s) are not allowed for the ${methodName} method.`);
358
+ };
359
+ if (OrmUtils_1.OrmUtils.isPrimitiveCriteria(criteria)) {
360
+ if (OrmUtils_1.OrmUtils.isCriteriaNullOrEmpty(criteria))
361
+ rejectEmpty();
362
+ return { criteria, isPrimitive: true };
363
+ }
364
+ const normalizedCriteria = OrmUtils_1.OrmUtils.normalizeWhereCriteria(criteria, this.connection.options.invalidWhereValuesBehavior);
365
+ // On the object-criteria path, `.where()` builds a predicate only from
366
+ // an object's own keys. Anything else yields an empty predicate list
367
+ // that renders as an always-true `1=1`, so a criterion is unsafe unless
368
+ // it is a non-empty object. This must reject:
369
+ // - primitives (a bare number/string in a mixed OR-array like
370
+ // `[1, { id: 2 }]` — `.where(1)` produces no predicate),
371
+ // - empty plain objects (`{}`), empty arrays (`[]`), and
372
+ // - empty non-plain objects, e.g. an empty entity instance
373
+ // (`new Post()`), which isCriteriaNullOrEmpty does not catch.
374
+ // Value-type criteria (Date, Buffer) execute via the primitive branch
375
+ // and never reach here.
376
+ const rendersNoPredicate = (value) => value === null ||
377
+ typeof value !== "object" ||
378
+ Object.keys(value).length === 0;
379
+ const isEmpty = Array.isArray(normalizedCriteria)
380
+ ? normalizedCriteria.length === 0 ||
381
+ normalizedCriteria.some(rendersNoPredicate)
382
+ : rendersNoPredicate(normalizedCriteria);
383
+ if (isEmpty)
384
+ rejectEmpty();
385
+ return { criteria: normalizedCriteria, isPrimitive: false };
386
+ }
342
387
  /**
343
388
  * Updates entity partially. Entity can be found by a given condition(s).
344
389
  * Unlike save method executes a primitive operation without cascades, relations and other operations included.
@@ -346,32 +391,19 @@ class EntityManager {
346
391
  * Does not check if entity exist in the database.
347
392
  * Condition(s) cannot be empty.
348
393
  */
349
- update(target, criteria, partialEntity, options) {
350
- // if user passed empty criteria or empty list of criterias, then throw an error
351
- if (OrmUtils_1.OrmUtils.isCriteriaNullOrEmpty(criteria)) {
352
- return Promise.reject(new error_1.TypeORMError(`Empty criteria(s) are not allowed for the update method.`));
353
- }
354
- if (OrmUtils_1.OrmUtils.isPrimitiveCriteria(criteria)) {
355
- const qb = this.createQueryBuilder()
356
- .update(target)
357
- .set(partialEntity)
358
- .whereInIds(criteria);
359
- if (options?.returning !== undefined) {
360
- qb.returning(options.returning);
361
- }
362
- return qb.execute();
394
+ async update(target, criteria, partialEntity, options) {
395
+ const { criteria: whereCriteria, isPrimitive } = this.normalizeAndValidateWhereCriteria(criteria, "update");
396
+ const qb = this.createQueryBuilder().update(target).set(partialEntity);
397
+ if (isPrimitive) {
398
+ qb.whereInIds(whereCriteria);
363
399
  }
364
400
  else {
365
- const normalizedCriteria = OrmUtils_1.OrmUtils.normalizeWhereCriteria(criteria, this.connection.options.invalidWhereValuesBehavior);
366
- const qb = this.createQueryBuilder()
367
- .update(target)
368
- .set(partialEntity)
369
- .where(normalizedCriteria);
370
- if (options?.returning !== undefined) {
371
- qb.returning(options.returning);
372
- }
373
- return qb.execute();
401
+ qb.where(whereCriteria);
402
+ }
403
+ if (options?.returning !== undefined) {
404
+ qb.returning(options.returning);
374
405
  }
406
+ return qb.execute();
375
407
  }
376
408
  /**
377
409
  * Updates all entities of target type, setting fields from supplied partial entity.
@@ -394,26 +426,10 @@ class EntityManager {
394
426
  * Does not check if entity exist in the database.
395
427
  * Condition(s) cannot be empty.
396
428
  */
397
- delete(targetOrEntity, criteria) {
398
- // if user passed empty criteria or empty list of criterias, then throw an error
399
- if (OrmUtils_1.OrmUtils.isCriteriaNullOrEmpty(criteria)) {
400
- return Promise.reject(new error_1.TypeORMError(`Empty criteria(s) are not allowed for the delete method.`));
401
- }
402
- if (OrmUtils_1.OrmUtils.isPrimitiveCriteria(criteria)) {
403
- return this.createQueryBuilder()
404
- .delete()
405
- .from(targetOrEntity)
406
- .whereInIds(criteria)
407
- .execute();
408
- }
409
- else {
410
- const normalizedCriteria = OrmUtils_1.OrmUtils.normalizeWhereCriteria(criteria, this.connection.options.invalidWhereValuesBehavior);
411
- return this.createQueryBuilder()
412
- .delete()
413
- .from(targetOrEntity)
414
- .where(normalizedCriteria)
415
- .execute();
416
- }
429
+ async delete(targetOrEntity, criteria) {
430
+ const { criteria: whereCriteria, isPrimitive } = this.normalizeAndValidateWhereCriteria(criteria, "delete");
431
+ const qb = this.createQueryBuilder().delete().from(targetOrEntity);
432
+ return (isPrimitive ? qb.whereInIds(whereCriteria) : qb.where(whereCriteria)).execute();
417
433
  }
418
434
  /**
419
435
  * Deletes all entities of target type.
@@ -432,26 +448,10 @@ class EntityManager {
432
448
  * Does not check if entity exist in the database.
433
449
  * Condition(s) cannot be empty.
434
450
  */
435
- softDelete(targetOrEntity, criteria) {
436
- // if user passed empty criteria or empty list of criterias, then throw an error
437
- if (OrmUtils_1.OrmUtils.isCriteriaNullOrEmpty(criteria)) {
438
- return Promise.reject(new error_1.TypeORMError(`Empty criteria(s) are not allowed for the softDelete method.`));
439
- }
440
- if (OrmUtils_1.OrmUtils.isPrimitiveCriteria(criteria)) {
441
- return this.createQueryBuilder()
442
- .softDelete()
443
- .from(targetOrEntity)
444
- .whereInIds(criteria)
445
- .execute();
446
- }
447
- else {
448
- const normalizedCriteria = OrmUtils_1.OrmUtils.normalizeWhereCriteria(criteria, this.connection.options.invalidWhereValuesBehavior);
449
- return this.createQueryBuilder()
450
- .softDelete()
451
- .from(targetOrEntity)
452
- .where(normalizedCriteria)
453
- .execute();
454
- }
451
+ async softDelete(targetOrEntity, criteria) {
452
+ const { criteria: whereCriteria, isPrimitive } = this.normalizeAndValidateWhereCriteria(criteria, "softDelete");
453
+ const qb = this.createQueryBuilder().softDelete().from(targetOrEntity);
454
+ return (isPrimitive ? qb.whereInIds(whereCriteria) : qb.where(whereCriteria)).execute();
455
455
  }
456
456
  /**
457
457
  * Restores entities by a given condition(s).
@@ -460,26 +460,10 @@ class EntityManager {
460
460
  * Does not check if entity exist in the database.
461
461
  * Condition(s) cannot be empty.
462
462
  */
463
- restore(targetOrEntity, criteria) {
464
- // if user passed empty criteria or empty list of criterias, then throw an error
465
- if (OrmUtils_1.OrmUtils.isCriteriaNullOrEmpty(criteria)) {
466
- return Promise.reject(new error_1.TypeORMError(`Empty criteria(s) are not allowed for the restore method.`));
467
- }
468
- if (OrmUtils_1.OrmUtils.isPrimitiveCriteria(criteria)) {
469
- return this.createQueryBuilder()
470
- .restore()
471
- .from(targetOrEntity)
472
- .whereInIds(criteria)
473
- .execute();
474
- }
475
- else {
476
- const normalizedCriteria = OrmUtils_1.OrmUtils.normalizeWhereCriteria(criteria, this.connection.options.invalidWhereValuesBehavior);
477
- return this.createQueryBuilder()
478
- .restore()
479
- .from(targetOrEntity)
480
- .where(normalizedCriteria)
481
- .execute();
482
- }
463
+ async restore(targetOrEntity, criteria) {
464
+ const { criteria: whereCriteria, isPrimitive } = this.normalizeAndValidateWhereCriteria(criteria, "restore");
465
+ const qb = this.createQueryBuilder().restore().from(targetOrEntity);
466
+ return (isPrimitive ? qb.whereInIds(whereCriteria) : qb.where(whereCriteria)).execute();
483
467
  }
484
468
  /**
485
469
  * Checks whether any entity exists with the given options.
@@ -721,45 +705,34 @@ class EntityManager {
721
705
  * Increments some column by provided value of the entities matched given conditions.
722
706
  */
723
707
  async increment(entityClass, conditions, propertyPath, value) {
724
- const metadata = this.connection.getMetadata(entityClass);
725
- const column = metadata.findColumnWithPropertyPath(propertyPath);
726
- if (!column)
727
- throw new error_1.TypeORMError(`Column ${propertyPath} was not found in ${metadata.targetName} entity.`);
728
- if (isNaN(Number(value)))
729
- throw new error_1.TypeORMError(`Value "${value}" is not a number.`);
730
- // convert possible embedded path "social.likes" into object { social: { like: () => value } }
731
- const values = propertyPath
732
- .split(".")
733
- .reduceRight((value, key) => ({ [key]: value }), () => this.connection.driver.escape(column.databaseName) +
734
- " + " +
735
- value);
736
- return this.createQueryBuilder(entityClass, "entity")
737
- .update(entityClass)
738
- .set(values)
739
- .where(conditions)
740
- .execute();
708
+ return this.incrementOrDecrementBy("increment", entityClass, conditions, propertyPath, value);
741
709
  }
742
710
  /**
743
711
  * Decrements some column by provided value of the entities matched given conditions.
744
712
  */
745
713
  async decrement(entityClass, conditions, propertyPath, value) {
714
+ return this.incrementOrDecrementBy("decrement", entityClass, conditions, propertyPath, value);
715
+ }
716
+ /**
717
+ * Shared implementation of {@link increment} and {@link decrement}: builds a
718
+ * `column = column +/- value` UPDATE and delegates execution to {@link update},
719
+ * so the criteria handling stays aligned with the other write methods.
720
+ */
721
+ incrementOrDecrementBy(operation, entityClass, conditions, propertyPath, value) {
746
722
  const metadata = this.connection.getMetadata(entityClass);
747
723
  const column = metadata.findColumnWithPropertyPath(propertyPath);
748
724
  if (!column)
749
725
  throw new error_1.TypeORMError(`Column ${propertyPath} was not found in ${metadata.targetName} entity.`);
750
726
  if (isNaN(Number(value)))
751
727
  throw new error_1.TypeORMError(`Value "${value}" is not a number.`);
728
+ const operator = operation === "increment" ? "+" : "-";
752
729
  // convert possible embedded path "social.likes" into object { social: { like: () => value } }
753
730
  const values = propertyPath
754
731
  .split(".")
755
732
  .reduceRight((value, key) => ({ [key]: value }), () => this.connection.driver.escape(column.databaseName) +
756
- " - " +
733
+ ` ${operator} ` +
757
734
  value);
758
- return this.createQueryBuilder(entityClass, "entity")
759
- .update(entityClass)
760
- .set(values)
761
- .where(conditions)
762
- .execute();
735
+ return this.update(entityClass, conditions, values);
763
736
  }
764
737
  /**
765
738
  * Gets repository for the given entity class or name.