typeorm 0.3.11-dev.f07fb2c → 0.3.11

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 (165) hide show
  1. package/browser/cli-ts-node-commonjs.js +0 -0
  2. package/browser/cli-ts-node-esm.js +0 -0
  3. package/browser/decorator/options/JoinTableMultipleColumnsOptions.d.ts +6 -0
  4. package/browser/decorator/options/JoinTableMultipleColumnsOptions.js.map +1 -1
  5. package/browser/decorator/options/JoinTableOptions.d.ts +6 -0
  6. package/browser/decorator/options/JoinTableOptions.js.map +1 -1
  7. package/browser/decorator/relations/JoinTable.js +1 -0
  8. package/browser/decorator/relations/JoinTable.js.map +1 -1
  9. package/browser/driver/Driver.d.ts +4 -0
  10. package/browser/driver/Driver.js.map +1 -1
  11. package/browser/driver/cordova/CordovaDriver.d.ts +1 -0
  12. package/browser/driver/cordova/CordovaDriver.js +1 -0
  13. package/browser/driver/cordova/CordovaDriver.js.map +1 -1
  14. package/browser/driver/oracle/OracleDriver.d.ts +1 -0
  15. package/browser/driver/oracle/OracleDriver.js +1 -0
  16. package/browser/driver/oracle/OracleDriver.js.map +1 -1
  17. package/browser/driver/postgres/PostgresConnectionOptions.d.ts +16 -0
  18. package/browser/driver/postgres/PostgresConnectionOptions.js.map +1 -1
  19. package/browser/driver/postgres/PostgresDriver.js +11 -1
  20. package/browser/driver/postgres/PostgresDriver.js.map +1 -1
  21. package/browser/driver/postgres/PostgresQueryRunner.d.ts +17 -1
  22. package/browser/driver/postgres/PostgresQueryRunner.js +99 -1
  23. package/browser/driver/postgres/PostgresQueryRunner.js.map +1 -1
  24. package/browser/driver/sap/SapDriver.d.ts +1 -0
  25. package/browser/driver/sap/SapDriver.js +1 -0
  26. package/browser/driver/sap/SapDriver.js.map +1 -1
  27. package/browser/driver/sqlite/SqliteConnectionOptions.d.ts +6 -0
  28. package/browser/driver/sqlite/SqliteConnectionOptions.js.map +1 -1
  29. package/browser/driver/sqlite/SqliteDriver.js +18 -6
  30. package/browser/driver/sqlite/SqliteDriver.js.map +1 -1
  31. package/browser/entity-manager/EntityManager.d.ts +4 -0
  32. package/browser/entity-manager/EntityManager.js +14 -1
  33. package/browser/entity-manager/EntityManager.js.map +1 -1
  34. package/browser/error/ForbiddenTransactionModeOverrideError.d.ts +8 -0
  35. package/browser/error/ForbiddenTransactionModeOverrideError.js +12 -0
  36. package/browser/error/ForbiddenTransactionModeOverrideError.js.map +1 -0
  37. package/browser/error/index.d.ts +1 -0
  38. package/browser/error/index.js +1 -0
  39. package/browser/error/index.js.map +1 -1
  40. package/browser/metadata-args/JoinTableMetadataArgs.d.ts +6 -0
  41. package/browser/metadata-args/JoinTableMetadataArgs.js.map +1 -1
  42. package/browser/metadata-builder/JunctionEntityMetadataBuilder.js +1 -0
  43. package/browser/metadata-builder/JunctionEntityMetadataBuilder.js.map +1 -1
  44. package/browser/migration/Migration.d.ts +5 -1
  45. package/browser/migration/Migration.js +2 -1
  46. package/browser/migration/Migration.js.map +1 -1
  47. package/browser/migration/MigrationExecutor.js +39 -6
  48. package/browser/migration/MigrationExecutor.js.map +1 -1
  49. package/browser/migration/MigrationInterface.d.ts +7 -0
  50. package/browser/migration/MigrationInterface.js.map +1 -1
  51. package/browser/naming-strategy/NamingStrategyInterface.d.ts +2 -1
  52. package/browser/naming-strategy/NamingStrategyInterface.js.map +1 -1
  53. package/browser/persistence/EntityPersistExecutor.js +2 -1
  54. package/browser/persistence/EntityPersistExecutor.js.map +1 -1
  55. package/browser/query-builder/InsertOrUpdateOptions.d.ts +7 -0
  56. package/browser/query-builder/InsertOrUpdateOptions.js.map +1 -1
  57. package/browser/query-builder/InsertQueryBuilder.js +10 -1
  58. package/browser/query-builder/InsertQueryBuilder.js.map +1 -1
  59. package/browser/query-builder/QueryBuilder.d.ts +1 -0
  60. package/browser/query-builder/QueryBuilder.js +13 -0
  61. package/browser/query-builder/QueryBuilder.js.map +1 -1
  62. package/browser/query-builder/QueryExpressionMap.d.ts +1 -0
  63. package/browser/query-builder/QueryExpressionMap.js.map +1 -1
  64. package/browser/query-builder/SelectQueryBuilder.d.ts +19 -0
  65. package/browser/query-builder/SelectQueryBuilder.js +75 -3
  66. package/browser/query-builder/SelectQueryBuilder.js.map +1 -1
  67. package/browser/query-runner/BaseQueryRunner.d.ts +1 -1
  68. package/browser/query-runner/BaseQueryRunner.js.map +1 -1
  69. package/browser/repository/Repository.d.ts +4 -0
  70. package/browser/repository/Repository.js +6 -0
  71. package/browser/repository/Repository.js.map +1 -1
  72. package/browser/repository/UpsertOptions.d.ts +5 -2
  73. package/browser/repository/UpsertOptions.js.map +1 -1
  74. package/browser/schema-builder/RdbmsSchemaBuilder.d.ts +4 -0
  75. package/browser/schema-builder/RdbmsSchemaBuilder.js +74 -2
  76. package/browser/schema-builder/RdbmsSchemaBuilder.js.map +1 -1
  77. package/browser/schema-builder/view/View.d.ts +13 -1
  78. package/browser/schema-builder/view/View.js +16 -0
  79. package/browser/schema-builder/view/View.js.map +1 -1
  80. package/cli-ts-node-commonjs.js +0 -0
  81. package/cli-ts-node-esm.js +0 -0
  82. package/cli.js +0 -0
  83. package/commands/InitCommand.js +32 -5
  84. package/commands/InitCommand.js.map +1 -1
  85. package/commands/MigrationGenerateCommand.js +1 -0
  86. package/commands/MigrationGenerateCommand.js.map +1 -1
  87. package/decorator/options/JoinTableMultipleColumnsOptions.d.ts +6 -0
  88. package/decorator/options/JoinTableMultipleColumnsOptions.js.map +1 -1
  89. package/decorator/options/JoinTableOptions.d.ts +6 -0
  90. package/decorator/options/JoinTableOptions.js.map +1 -1
  91. package/decorator/relations/JoinTable.js +1 -0
  92. package/decorator/relations/JoinTable.js.map +1 -1
  93. package/driver/Driver.d.ts +4 -0
  94. package/driver/Driver.js.map +1 -1
  95. package/driver/cordova/CordovaDriver.d.ts +1 -0
  96. package/driver/cordova/CordovaDriver.js +1 -0
  97. package/driver/cordova/CordovaDriver.js.map +1 -1
  98. package/driver/oracle/OracleDriver.d.ts +1 -0
  99. package/driver/oracle/OracleDriver.js +1 -0
  100. package/driver/oracle/OracleDriver.js.map +1 -1
  101. package/driver/postgres/PostgresConnectionOptions.d.ts +16 -0
  102. package/driver/postgres/PostgresConnectionOptions.js.map +1 -1
  103. package/driver/postgres/PostgresDriver.js +11 -1
  104. package/driver/postgres/PostgresDriver.js.map +1 -1
  105. package/driver/postgres/PostgresQueryRunner.d.ts +17 -1
  106. package/driver/postgres/PostgresQueryRunner.js +99 -1
  107. package/driver/postgres/PostgresQueryRunner.js.map +1 -1
  108. package/driver/sap/SapDriver.d.ts +1 -0
  109. package/driver/sap/SapDriver.js +1 -0
  110. package/driver/sap/SapDriver.js.map +1 -1
  111. package/driver/sqlite/SqliteConnectionOptions.d.ts +6 -0
  112. package/driver/sqlite/SqliteConnectionOptions.js.map +1 -1
  113. package/driver/sqlite/SqliteDriver.js +18 -6
  114. package/driver/sqlite/SqliteDriver.js.map +1 -1
  115. package/entity-manager/EntityManager.d.ts +4 -0
  116. package/entity-manager/EntityManager.js +14 -1
  117. package/entity-manager/EntityManager.js.map +1 -1
  118. package/error/ForbiddenTransactionModeOverrideError.d.ts +8 -0
  119. package/error/ForbiddenTransactionModeOverrideError.js +16 -0
  120. package/error/ForbiddenTransactionModeOverrideError.js.map +1 -0
  121. package/error/index.d.ts +1 -0
  122. package/error/index.js +1 -0
  123. package/error/index.js.map +1 -1
  124. package/index.mjs +2 -0
  125. package/metadata-args/JoinTableMetadataArgs.d.ts +6 -0
  126. package/metadata-args/JoinTableMetadataArgs.js.map +1 -1
  127. package/metadata-builder/JunctionEntityMetadataBuilder.js +1 -0
  128. package/metadata-builder/JunctionEntityMetadataBuilder.js.map +1 -1
  129. package/migration/Migration.d.ts +5 -1
  130. package/migration/Migration.js +2 -1
  131. package/migration/Migration.js.map +1 -1
  132. package/migration/MigrationExecutor.js +38 -5
  133. package/migration/MigrationExecutor.js.map +1 -1
  134. package/migration/MigrationInterface.d.ts +7 -0
  135. package/migration/MigrationInterface.js.map +1 -1
  136. package/naming-strategy/NamingStrategyInterface.d.ts +2 -1
  137. package/naming-strategy/NamingStrategyInterface.js.map +1 -1
  138. package/package.json +274 -1
  139. package/persistence/EntityPersistExecutor.js +2 -1
  140. package/persistence/EntityPersistExecutor.js.map +1 -1
  141. package/query-builder/InsertOrUpdateOptions.d.ts +7 -0
  142. package/query-builder/InsertOrUpdateOptions.js.map +1 -1
  143. package/query-builder/InsertQueryBuilder.js +10 -1
  144. package/query-builder/InsertQueryBuilder.js.map +1 -1
  145. package/query-builder/QueryBuilder.d.ts +1 -0
  146. package/query-builder/QueryBuilder.js +13 -0
  147. package/query-builder/QueryBuilder.js.map +1 -1
  148. package/query-builder/QueryExpressionMap.d.ts +1 -0
  149. package/query-builder/QueryExpressionMap.js.map +1 -1
  150. package/query-builder/SelectQueryBuilder.d.ts +19 -0
  151. package/query-builder/SelectQueryBuilder.js +75 -3
  152. package/query-builder/SelectQueryBuilder.js.map +1 -1
  153. package/query-runner/BaseQueryRunner.d.ts +1 -1
  154. package/query-runner/BaseQueryRunner.js.map +1 -1
  155. package/repository/Repository.d.ts +4 -0
  156. package/repository/Repository.js +6 -0
  157. package/repository/Repository.js.map +1 -1
  158. package/repository/UpsertOptions.d.ts +5 -2
  159. package/repository/UpsertOptions.js.map +1 -1
  160. package/schema-builder/RdbmsSchemaBuilder.d.ts +4 -0
  161. package/schema-builder/RdbmsSchemaBuilder.js +74 -2
  162. package/schema-builder/RdbmsSchemaBuilder.js.map +1 -1
  163. package/schema-builder/view/View.d.ts +13 -1
  164. package/schema-builder/view/View.js +16 -0
  165. package/schema-builder/view/View.js.map +1 -1
@@ -20,5 +20,9 @@ export declare class Migration {
20
20
  * Migration instance that needs to be run.
21
21
  */
22
22
  instance?: MigrationInterface;
23
- constructor(id: number | undefined, timestamp: number, name: string, instance?: MigrationInterface);
23
+ /**
24
+ * Whether to run this migration within a transaction
25
+ */
26
+ transaction?: boolean;
27
+ constructor(id: number | undefined, timestamp: number, name: string, instance?: MigrationInterface, transaction?: boolean);
24
28
  }
@@ -5,11 +5,12 @@ export class Migration {
5
5
  // -------------------------------------------------------------------------
6
6
  // Constructor
7
7
  // -------------------------------------------------------------------------
8
- constructor(id, timestamp, name, instance) {
8
+ constructor(id, timestamp, name, instance, transaction) {
9
9
  this.id = id;
10
10
  this.timestamp = timestamp;
11
11
  this.name = name;
12
12
  this.instance = instance;
13
+ this.transaction = transaction;
13
14
  }
14
15
  }
15
16
 
@@ -1 +1 @@
1
- {"version":3,"sources":["../browser/src/migration/Migration.ts"],"names":[],"mappings":"AAEA;;GAEG;AACH,MAAM,OAAO,SAAS;IA0BlB,4EAA4E;IAC5E,cAAc;IACd,4EAA4E;IAE5E,YACI,EAAsB,EACtB,SAAiB,EACjB,IAAY,EACZ,QAA6B;QAE7B,IAAI,CAAC,EAAE,GAAG,EAAE,CAAA;QACZ,IAAI,CAAC,SAAS,GAAG,SAAS,CAAA;QAC1B,IAAI,CAAC,IAAI,GAAG,IAAI,CAAA;QAChB,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAA;IAC5B,CAAC;CACJ","file":"Migration.js","sourcesContent":["import { MigrationInterface } from \"./MigrationInterface\"\n\n/**\n * Represents entity of the migration in the database.\n */\nexport class Migration {\n // -------------------------------------------------------------------------\n // Public Properties\n // -------------------------------------------------------------------------\n\n /**\n * Migration id.\n * Indicates order of the executed migrations.\n */\n id: number | undefined\n\n /**\n * Timestamp of the migration.\n */\n timestamp: number\n\n /**\n * Name of the migration (class name).\n */\n name: string\n\n /**\n * Migration instance that needs to be run.\n */\n instance?: MigrationInterface\n\n // -------------------------------------------------------------------------\n // Constructor\n // -------------------------------------------------------------------------\n\n constructor(\n id: number | undefined,\n timestamp: number,\n name: string,\n instance?: MigrationInterface,\n ) {\n this.id = id\n this.timestamp = timestamp\n this.name = name\n this.instance = instance\n }\n}\n"],"sourceRoot":".."}
1
+ {"version":3,"sources":["../browser/src/migration/Migration.ts"],"names":[],"mappings":"AAEA;;GAEG;AACH,MAAM,OAAO,SAAS;IA+BlB,4EAA4E;IAC5E,cAAc;IACd,4EAA4E;IAE5E,YACI,EAAsB,EACtB,SAAiB,EACjB,IAAY,EACZ,QAA6B,EAC7B,WAAqB;QAErB,IAAI,CAAC,EAAE,GAAG,EAAE,CAAA;QACZ,IAAI,CAAC,SAAS,GAAG,SAAS,CAAA;QAC1B,IAAI,CAAC,IAAI,GAAG,IAAI,CAAA;QAChB,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAA;QACxB,IAAI,CAAC,WAAW,GAAG,WAAW,CAAA;IAClC,CAAC;CACJ","file":"Migration.js","sourcesContent":["import { MigrationInterface } from \"./MigrationInterface\"\n\n/**\n * Represents entity of the migration in the database.\n */\nexport class Migration {\n // -------------------------------------------------------------------------\n // Public Properties\n // -------------------------------------------------------------------------\n\n /**\n * Migration id.\n * Indicates order of the executed migrations.\n */\n id: number | undefined\n\n /**\n * Timestamp of the migration.\n */\n timestamp: number\n\n /**\n * Name of the migration (class name).\n */\n name: string\n\n /**\n * Migration instance that needs to be run.\n */\n instance?: MigrationInterface\n\n /**\n * Whether to run this migration within a transaction\n */\n transaction?: boolean\n\n // -------------------------------------------------------------------------\n // Constructor\n // -------------------------------------------------------------------------\n\n constructor(\n id: number | undefined,\n timestamp: number,\n name: string,\n instance?: MigrationInterface,\n transaction?: boolean,\n ) {\n this.id = id\n this.timestamp = timestamp\n this.name = name\n this.instance = instance\n this.transaction = transaction\n }\n}\n"],"sourceRoot":".."}
@@ -1,7 +1,7 @@
1
1
  import { Table } from "../schema-builder/table/Table";
2
2
  import { Migration } from "./Migration";
3
3
  import { MssqlParameter } from "../driver/sqlserver/MssqlParameter";
4
- import { TypeORMError } from "../error";
4
+ import { ForbiddenTransactionModeOverrideError, TypeORMError } from "../error";
5
5
  import { InstanceChecker } from "../util/InstanceChecker";
6
6
  /**
7
7
  * Executes migrations: runs pending and reverts previously executed migrations.
@@ -103,7 +103,7 @@ export class MigrationExecutor {
103
103
  for (const migration of allMigrations) {
104
104
  const executedMigration = executedMigrations.find((executedMigration) => executedMigration.name === migration.name);
105
105
  if (executedMigration) {
106
- this.connection.logger.logSchemaBuild(`[X] ${migration.name}`);
106
+ this.connection.logger.logSchemaBuild(`[X] ${executedMigration.id} ${migration.name}`);
107
107
  }
108
108
  else {
109
109
  hasUnappliedMigrations = true;
@@ -163,6 +163,41 @@ export class MigrationExecutor {
163
163
  if (lastTimeExecutedMigration)
164
164
  this.connection.logger.logSchemaBuild(`${lastTimeExecutedMigration.name} is the last executed migration. It was executed on ${new Date(lastTimeExecutedMigration.timestamp).toString()}.`);
165
165
  this.connection.logger.logSchemaBuild(`${pendingMigrations.length} migrations are new migrations must be executed.`);
166
+ if (this.transaction === "all") {
167
+ // If we desire to run all migrations in a single transaction
168
+ // but there is a migration that explicitly overrides the transaction mode
169
+ // then we have to fail since we cannot properly resolve that intent
170
+ // In theory we could support overrides that are set to `true`,
171
+ // however to keep the interface more rigid, we fail those too
172
+ const migrationsOverridingTransactionMode = pendingMigrations.filter((migration) => { var _a; return !(((_a = migration.instance) === null || _a === void 0 ? void 0 : _a.transaction) === undefined); });
173
+ if (migrationsOverridingTransactionMode.length > 0) {
174
+ const error = new ForbiddenTransactionModeOverrideError(migrationsOverridingTransactionMode);
175
+ this.connection.logger.logMigration(`Migrations failed, error: ${error.message}`);
176
+ throw error;
177
+ }
178
+ }
179
+ // Set the per-migration defaults for the transaction mode
180
+ // so that we have one centralized place that controls this behavior
181
+ // When transaction mode is `each` the default is to run in a transaction
182
+ // When transaction mode is `none` the default is to not run in a transaction
183
+ // When transaction mode is `all` the default is to not run in a transaction
184
+ // since all the migrations are already running in one single transaction
185
+ const txModeDefault = {
186
+ each: true,
187
+ none: false,
188
+ all: false,
189
+ }[this.transaction];
190
+ for (const migration of pendingMigrations) {
191
+ if (migration.instance) {
192
+ const instanceTx = migration.instance.transaction;
193
+ if (instanceTx === undefined) {
194
+ migration.transaction = txModeDefault;
195
+ }
196
+ else {
197
+ migration.transaction = instanceTx;
198
+ }
199
+ }
200
+ }
166
201
  // start transaction if its not started yet
167
202
  let transactionStartedByUs = false;
168
203
  if (this.transaction === "all" && !queryRunner.isTransactionActive) {
@@ -178,8 +213,7 @@ export class MigrationExecutor {
178
213
  // nothing else needs to be done, continue to next migration
179
214
  continue;
180
215
  }
181
- if (this.transaction === "each" &&
182
- !queryRunner.isTransactionActive) {
216
+ if (migration.transaction && !queryRunner.isTransactionActive) {
183
217
  await queryRunner.startTransaction();
184
218
  transactionStartedByUs = true;
185
219
  }
@@ -194,8 +228,7 @@ export class MigrationExecutor {
194
228
  // now when migration is executed we need to insert record about it into the database
195
229
  await this.insertExecutedMigration(queryRunner, migration);
196
230
  // commit transaction if we started it
197
- if (this.transaction === "each" &&
198
- transactionStartedByUs)
231
+ if (migration.transaction && transactionStartedByUs)
199
232
  await queryRunner.commitTransaction();
200
233
  })
201
234
  .then(() => {
@@ -1 +1 @@
1
- {"version":3,"sources":["../browser/src/migration/MigrationExecutor.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,+BAA+B,CAAA;AAErD,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAA;AAGvC,OAAO,EAAE,cAAc,EAAE,MAAM,oCAAoC,CAAA;AAEnE,OAAO,EAAE,YAAY,EAAE,MAAM,UAAU,CAAA;AACvC,OAAO,EAAE,eAAe,EAAE,MAAM,yBAAyB,CAAA;AAEzD;;GAEG;AACH,MAAM,OAAO,iBAAiB;IA+B1B,4EAA4E;IAC5E,cAAc;IACd,4EAA4E;IAE5E,YACc,UAAsB,EACtB,WAAyB;QADzB,eAAU,GAAV,UAAU,CAAY;QACtB,gBAAW,GAAX,WAAW,CAAc;QApCvC,4EAA4E;QAC5E,oBAAoB;QACpB,4EAA4E;QAE5E;;;;;WAKG;QACH,gBAAW,GAA4B,KAAK,CAAA;QA4BxC,MAAM,EAAE,MAAM,EAAE,GAAG,IAAI,CAAC,UAAU,CAAC,MAAM,CAAC,OAAc,CAAA;QACxD,MAAM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,MAAM,WAAW,CAAC,kBAAkB;iBAC/B,EAAE,CAAC,IAAI,CAAC,UAAU,CAAC,MAAM,CAAC,QAAS,CAAC;iBACpC,UAAU,CAAC,IAAI,CAAC,mBAAmB,CAAC;iBACpC,SAAS,CAAC,UAAU,CAAC,CAAA;SAC7B;aAAM;YACH,MAAM,EAAE,GAAG,WAAW,CAAC,OAAO,CAAC,kBAAkB,EAAE,CAAA;YACnD,MAAM,EAAE;iBACH,MAAM,EAAE;iBACR,IAAI,CAAC,IAAI,CAAC,eAAe,CAAC;iBAC1B,KAAK,CAAC,GAAG,EAAE,CAAC,MAAM,CAAC,WAAW,CAAC,eAAe,CAAC;iBAC/C,QAAQ,CAAC,GAAG,EAAE,CAAC,MAAM,CAAC,MAAM,CAAC,UAAU,CAAC;iBACxC,aAAa,CAAC,UAAU,CAAC;iBACzB,OAAO,EAAE,CAAA;SACjB;IACL,CAAC;IAES,KAAK,CAAC,eAAe,CAC3B,QAAsD;QAEtD,MAAM,WAAW,GACb,IAAI,CAAC,WAAW,IAAI,IAAI,CAAC,UAAU,CAAC,iBAAiB,EAAE,CAAA;QAE3D,IAAI;YACA,OAAO,QAAQ,CAAC,WAAW,CAAC,CAAA;SAC/B;gBAAS;YACN,IAAI,CAAC,IAAI,CAAC,WAAW,EAAE;gBACnB,MAAM,WAAW,CAAC,OAAO,EAAE,CAAA;aAC9B;SACJ;IACL,CAAC;CACJ","file":"MigrationExecutor.js","sourcesContent":["import { Table } from \"../schema-builder/table/Table\"\nimport { DataSource } from \"../data-source/DataSource\"\nimport { Migration } from \"./Migration\"\nimport { ObjectLiteral } from \"../common/ObjectLiteral\"\nimport { QueryRunner } from \"../query-runner/QueryRunner\"\nimport { MssqlParameter } from \"../driver/sqlserver/MssqlParameter\"\nimport { MongoQueryRunner } from \"../driver/mongodb/MongoQueryRunner\"\nimport { TypeORMError } from \"../error\"\nimport { InstanceChecker } from \"../util/InstanceChecker\"\n\n/**\n * Executes migrations: runs pending and reverts previously executed migrations.\n */\nexport class MigrationExecutor {\n // -------------------------------------------------------------------------\n // Public Properties\n // -------------------------------------------------------------------------\n\n /**\n * Indicates how migrations should be run in transactions.\n * all: all migrations are run in a single transaction\n * none: all migrations are run without a transaction\n * each: each migration is run in a separate transaction\n */\n transaction: \"all\" | \"none\" | \"each\" = \"all\"\n\n /**\n * Option to fake-run or fake-revert a migration, adding to the\n * executed migrations table, but not actually running it. This feature is\n * useful for when migrations are added after the fact or for\n * interoperability between applications which are desired to each keep\n * a consistent migration history.\n */\n fake: boolean\n\n // -------------------------------------------------------------------------\n // Private Properties\n // -------------------------------------------------------------------------\n\n private readonly migrationsDatabase?: string\n private readonly migrationsSchema?: string\n private readonly migrationsTable: string\n private readonly migrationsTableName: string\n\n // -------------------------------------------------------------------------\n // Constructor\n // -------------------------------------------------------------------------\n\n constructor(\n protected connection: DataSource,\n protected queryRunner?: QueryRunner,\n ) {\n const { schema } = this.connection.driver.options as any\n const database = this.connection.driver.database\n this.migrationsDatabase = database\n this.migrationsSchema = schema\n this.migrationsTableName =\n connection.options.migrationsTableName || \"migrations\"\n this.migrationsTable = this.connection.driver.buildTableName(\n this.migrationsTableName,\n schema,\n database,\n )\n }\n\n // -------------------------------------------------------------------------\n // Public Methods\n // -------------------------------------------------------------------------\n\n /**\n * Tries to execute a single migration given.\n */\n public async executeMigration(migration: Migration): Promise<Migration> {\n return this.withQueryRunner(async (queryRunner) => {\n await this.createMigrationsTableIfNotExist(queryRunner)\n\n // create typeorm_metadata table if it's not created yet\n const schemaBuilder = this.connection.driver.createSchemaBuilder()\n if (InstanceChecker.isRdbmsSchemaBuilder(schemaBuilder)) {\n await schemaBuilder.createMetadataTableIfNecessary(queryRunner)\n }\n\n await queryRunner.beforeMigration()\n await (migration.instance as any).up(queryRunner)\n await queryRunner.afterMigration()\n await this.insertExecutedMigration(queryRunner, migration)\n\n return migration\n })\n }\n\n /**\n * Returns an array of all migrations.\n */\n public async getAllMigrations(): Promise<Migration[]> {\n return Promise.resolve(this.getMigrations())\n }\n\n /**\n * Returns an array of all executed migrations.\n */\n public async getExecutedMigrations(): Promise<Migration[]> {\n return this.withQueryRunner(async (queryRunner) => {\n await this.createMigrationsTableIfNotExist(queryRunner)\n\n return await this.loadExecutedMigrations(queryRunner)\n })\n }\n\n /**\n * Returns an array of all pending migrations.\n */\n public async getPendingMigrations(): Promise<Migration[]> {\n const allMigrations = await this.getAllMigrations()\n const executedMigrations = await this.getExecutedMigrations()\n\n return allMigrations.filter(\n (migration) =>\n !executedMigrations.find(\n (executedMigration) =>\n executedMigration.name === migration.name,\n ),\n )\n }\n\n /**\n * Inserts an executed migration.\n */\n public insertMigration(migration: Migration): Promise<void> {\n return this.withQueryRunner((q) =>\n this.insertExecutedMigration(q, migration),\n )\n }\n\n /**\n * Deletes an executed migration.\n */\n public deleteMigration(migration: Migration): Promise<void> {\n return this.withQueryRunner((q) =>\n this.deleteExecutedMigration(q, migration),\n )\n }\n\n /**\n * Lists all migrations and whether they have been executed or not\n * returns true if there are unapplied migrations\n */\n async showMigrations(): Promise<boolean> {\n let hasUnappliedMigrations = false\n const queryRunner =\n this.queryRunner || this.connection.createQueryRunner()\n // create migrations table if its not created yet\n await this.createMigrationsTableIfNotExist(queryRunner)\n\n // get all migrations that are executed and saved in the database\n const executedMigrations = await this.loadExecutedMigrations(\n queryRunner,\n )\n\n // get all user's migrations in the source code\n const allMigrations = this.getMigrations()\n\n for (const migration of allMigrations) {\n const executedMigration = executedMigrations.find(\n (executedMigration) =>\n executedMigration.name === migration.name,\n )\n\n if (executedMigration) {\n this.connection.logger.logSchemaBuild(`[X] ${migration.name}`)\n } else {\n hasUnappliedMigrations = true\n this.connection.logger.logSchemaBuild(`[ ] ${migration.name}`)\n }\n }\n\n // if query runner was created by us then release it\n if (!this.queryRunner) {\n await queryRunner.release()\n }\n\n return hasUnappliedMigrations\n }\n\n /**\n * Executes all pending migrations. Pending migrations are migrations that are not yet executed,\n * thus not saved in the database.\n */\n async executePendingMigrations(): Promise<Migration[]> {\n const queryRunner =\n this.queryRunner || this.connection.createQueryRunner()\n // create migrations table if it's not created yet\n await this.createMigrationsTableIfNotExist(queryRunner)\n\n // create the typeorm_metadata table if it's not created yet\n const schemaBuilder = this.connection.driver.createSchemaBuilder()\n if (InstanceChecker.isRdbmsSchemaBuilder(schemaBuilder)) {\n await schemaBuilder.createMetadataTableIfNecessary(queryRunner)\n }\n\n // get all migrations that are executed and saved in the database\n const executedMigrations = await this.loadExecutedMigrations(\n queryRunner,\n )\n\n // get the time when last migration was executed\n let lastTimeExecutedMigration =\n this.getLatestTimestampMigration(executedMigrations)\n\n // get all user's migrations in the source code\n const allMigrations = this.getMigrations()\n\n // variable to store all migrations we did successfully\n const successMigrations: Migration[] = []\n\n // find all migrations that needs to be executed\n const pendingMigrations = allMigrations.filter((migration) => {\n // check if we already have executed migration\n const executedMigration = executedMigrations.find(\n (executedMigration) =>\n executedMigration.name === migration.name,\n )\n if (executedMigration) return false\n\n // migration is new and not executed. now check if its timestamp is correct\n // if (lastTimeExecutedMigration && migration.timestamp < lastTimeExecutedMigration.timestamp)\n // throw new TypeORMError(`New migration found: ${migration.name}, however this migration's timestamp is not valid. Migration's timestamp should not be older then migrations already executed in the database.`);\n\n // every check is passed means that migration was not run yet and we need to run it\n return true\n })\n\n // if no migrations are pending then nothing to do here\n if (!pendingMigrations.length) {\n this.connection.logger.logSchemaBuild(`No migrations are pending`)\n // if query runner was created by us then release it\n if (!this.queryRunner) await queryRunner.release()\n return []\n }\n\n // log information about migration execution\n this.connection.logger.logSchemaBuild(\n `${executedMigrations.length} migrations are already loaded in the database.`,\n )\n this.connection.logger.logSchemaBuild(\n `${allMigrations.length} migrations were found in the source code.`,\n )\n if (lastTimeExecutedMigration)\n this.connection.logger.logSchemaBuild(\n `${\n lastTimeExecutedMigration.name\n } is the last executed migration. It was executed on ${new Date(\n lastTimeExecutedMigration.timestamp,\n ).toString()}.`,\n )\n this.connection.logger.logSchemaBuild(\n `${pendingMigrations.length} migrations are new migrations must be executed.`,\n )\n\n // start transaction if its not started yet\n let transactionStartedByUs = false\n if (this.transaction === \"all\" && !queryRunner.isTransactionActive) {\n await queryRunner.startTransaction()\n transactionStartedByUs = true\n }\n\n // run all pending migrations in a sequence\n try {\n for (const migration of pendingMigrations) {\n if (this.fake) {\n // directly insert migration record into the database if it is fake\n await this.insertExecutedMigration(queryRunner, migration)\n\n // nothing else needs to be done, continue to next migration\n continue\n }\n\n if (\n this.transaction === \"each\" &&\n !queryRunner.isTransactionActive\n ) {\n await queryRunner.startTransaction()\n transactionStartedByUs = true\n }\n\n await migration\n .instance!.up(queryRunner)\n .catch((error) => {\n // informative log about migration failure\n this.connection.logger.logMigration(\n `Migration \"${migration.name}\" failed, error: ${error?.message}`,\n )\n throw error\n })\n .then(async () => {\n // now when migration is executed we need to insert record about it into the database\n await this.insertExecutedMigration(\n queryRunner,\n migration,\n )\n // commit transaction if we started it\n if (\n this.transaction === \"each\" &&\n transactionStartedByUs\n )\n await queryRunner.commitTransaction()\n })\n .then(() => {\n // informative log about migration success\n successMigrations.push(migration)\n this.connection.logger.logSchemaBuild(\n `Migration ${migration.name} has been ${\n this.fake ? \"(fake)\" : \"\"\n } executed successfully.`,\n )\n })\n }\n\n // commit transaction if we started it\n if (this.transaction === \"all\" && transactionStartedByUs)\n await queryRunner.commitTransaction()\n } catch (err) {\n // rollback transaction if we started it\n if (transactionStartedByUs) {\n try {\n // we throw original error even if rollback thrown an error\n await queryRunner.rollbackTransaction()\n } catch (rollbackError) {}\n }\n\n throw err\n } finally {\n // if query runner was created by us then release it\n if (!this.queryRunner) await queryRunner.release()\n }\n return successMigrations\n }\n\n /**\n * Reverts last migration that were run.\n */\n async undoLastMigration(): Promise<void> {\n const queryRunner =\n this.queryRunner || this.connection.createQueryRunner()\n\n // create migrations table if it's not created yet\n await this.createMigrationsTableIfNotExist(queryRunner)\n\n // create typeorm_metadata table if it's not created yet\n const schemaBuilder = this.connection.driver.createSchemaBuilder()\n if (InstanceChecker.isRdbmsSchemaBuilder(schemaBuilder)) {\n await schemaBuilder.createMetadataTableIfNecessary(queryRunner)\n }\n\n // get all migrations that are executed and saved in the database\n const executedMigrations = await this.loadExecutedMigrations(\n queryRunner,\n )\n\n // get the time when last migration was executed\n let lastTimeExecutedMigration =\n this.getLatestExecutedMigration(executedMigrations)\n\n // if no migrations found in the database then nothing to revert\n if (!lastTimeExecutedMigration) {\n this.connection.logger.logSchemaBuild(\n `No migrations was found in the database. Nothing to revert!`,\n )\n return\n }\n\n // get all user's migrations in the source code\n const allMigrations = this.getMigrations()\n\n // find the instance of the migration we need to remove\n const migrationToRevert = allMigrations.find(\n (migration) => migration.name === lastTimeExecutedMigration!.name,\n )\n\n // if no migrations found in the database then nothing to revert\n if (!migrationToRevert)\n throw new TypeORMError(\n `No migration ${lastTimeExecutedMigration.name} was found in the source code. Make sure you have this migration in your codebase and its included in the connection options.`,\n )\n\n // log information about migration execution\n this.connection.logger.logSchemaBuild(\n `${executedMigrations.length} migrations are already loaded in the database.`,\n )\n this.connection.logger.logSchemaBuild(\n `${\n lastTimeExecutedMigration.name\n } is the last executed migration. It was executed on ${new Date(\n lastTimeExecutedMigration.timestamp,\n ).toString()}.`,\n )\n this.connection.logger.logSchemaBuild(`Now reverting it...`)\n\n // start transaction if its not started yet\n let transactionStartedByUs = false\n if (this.transaction !== \"none\" && !queryRunner.isTransactionActive) {\n await queryRunner.startTransaction()\n transactionStartedByUs = true\n }\n\n try {\n if (!this.fake) {\n await queryRunner.beforeMigration()\n await migrationToRevert.instance!.down(queryRunner)\n await queryRunner.afterMigration()\n }\n\n await this.deleteExecutedMigration(queryRunner, migrationToRevert)\n this.connection.logger.logSchemaBuild(\n `Migration ${migrationToRevert.name} has been ${\n this.fake ? \"(fake)\" : \"\"\n } reverted successfully.`,\n )\n\n // commit transaction if we started it\n if (transactionStartedByUs) await queryRunner.commitTransaction()\n } catch (err) {\n // rollback transaction if we started it\n if (transactionStartedByUs) {\n try {\n // we throw original error even if rollback thrown an error\n await queryRunner.rollbackTransaction()\n } catch (rollbackError) {}\n }\n\n throw err\n } finally {\n // if query runner was created by us then release it\n if (!this.queryRunner) await queryRunner.release()\n }\n }\n\n // -------------------------------------------------------------------------\n // Protected Methods\n // -------------------------------------------------------------------------\n\n /**\n * Creates table \"migrations\" that will store information about executed migrations.\n */\n protected async createMigrationsTableIfNotExist(\n queryRunner: QueryRunner,\n ): Promise<void> {\n // If driver is mongo no need to create\n if (this.connection.driver.options.type === \"mongodb\") {\n return\n }\n const tableExist = await queryRunner.hasTable(this.migrationsTable) // todo: table name should be configurable\n if (!tableExist) {\n await queryRunner.createTable(\n new Table({\n database: this.migrationsDatabase,\n schema: this.migrationsSchema,\n name: this.migrationsTable,\n columns: [\n {\n name: \"id\",\n type: this.connection.driver.normalizeType({\n type: this.connection.driver.mappedDataTypes\n .migrationId,\n }),\n isGenerated: true,\n generationStrategy: \"increment\",\n isPrimary: true,\n isNullable: false,\n },\n {\n name: \"timestamp\",\n type: this.connection.driver.normalizeType({\n type: this.connection.driver.mappedDataTypes\n .migrationTimestamp,\n }),\n isPrimary: false,\n isNullable: false,\n },\n {\n name: \"name\",\n type: this.connection.driver.normalizeType({\n type: this.connection.driver.mappedDataTypes\n .migrationName,\n }),\n isNullable: false,\n },\n ],\n }),\n )\n }\n }\n\n /**\n * Loads all migrations that were executed and saved into the database (sorts by id).\n */\n protected async loadExecutedMigrations(\n queryRunner: QueryRunner,\n ): Promise<Migration[]> {\n if (this.connection.driver.options.type === \"mongodb\") {\n const mongoRunner = queryRunner as MongoQueryRunner\n return await mongoRunner.databaseConnection\n .db(this.connection.driver.database!)\n .collection(this.migrationsTableName)\n .find<Migration>()\n .sort({ _id: -1 })\n .toArray()\n } else {\n const migrationsRaw: ObjectLiteral[] = await this.connection.manager\n .createQueryBuilder(queryRunner)\n .select()\n .orderBy(this.connection.driver.escape(\"id\"), \"DESC\")\n .from(this.migrationsTable, this.migrationsTableName)\n .getRawMany()\n return migrationsRaw.map((migrationRaw) => {\n return new Migration(\n parseInt(migrationRaw[\"id\"]),\n parseInt(migrationRaw[\"timestamp\"]),\n migrationRaw[\"name\"],\n )\n })\n }\n }\n\n /**\n * Gets all migrations that setup for this connection.\n */\n protected getMigrations(): Migration[] {\n const migrations = this.connection.migrations.map((migration) => {\n const migrationClassName =\n migration.name || (migration.constructor as any).name\n const migrationTimestamp = parseInt(\n migrationClassName.substr(-13),\n 10,\n )\n if (!migrationTimestamp || isNaN(migrationTimestamp)) {\n throw new TypeORMError(\n `${migrationClassName} migration name is wrong. Migration class name should have a JavaScript timestamp appended.`,\n )\n }\n\n return new Migration(\n undefined,\n migrationTimestamp,\n migrationClassName,\n migration,\n )\n })\n\n this.checkForDuplicateMigrations(migrations)\n\n // sort them by timestamp\n return migrations.sort((a, b) => a.timestamp - b.timestamp)\n }\n\n protected checkForDuplicateMigrations(migrations: Migration[]) {\n const migrationNames = migrations.map((migration) => migration.name)\n const duplicates = Array.from(\n new Set(\n migrationNames.filter(\n (migrationName, index) =>\n migrationNames.indexOf(migrationName) < index,\n ),\n ),\n )\n if (duplicates.length > 0) {\n throw Error(`Duplicate migrations: ${duplicates.join(\", \")}`)\n }\n }\n\n /**\n * Finds the latest migration (sorts by timestamp) in the given array of migrations.\n */\n protected getLatestTimestampMigration(\n migrations: Migration[],\n ): Migration | undefined {\n const sortedMigrations = migrations\n .map((migration) => migration)\n .sort((a, b) => (a.timestamp - b.timestamp) * -1)\n return sortedMigrations.length > 0 ? sortedMigrations[0] : undefined\n }\n\n /**\n * Finds the latest migration in the given array of migrations.\n * PRE: Migration array must be sorted by descending id.\n */\n protected getLatestExecutedMigration(\n sortedMigrations: Migration[],\n ): Migration | undefined {\n return sortedMigrations.length > 0 ? sortedMigrations[0] : undefined\n }\n\n /**\n * Inserts new executed migration's data into migrations table.\n */\n protected async insertExecutedMigration(\n queryRunner: QueryRunner,\n migration: Migration,\n ): Promise<void> {\n const values: ObjectLiteral = {}\n if (this.connection.driver.options.type === \"mssql\") {\n values[\"timestamp\"] = new MssqlParameter(\n migration.timestamp,\n this.connection.driver.normalizeType({\n type: this.connection.driver.mappedDataTypes\n .migrationTimestamp,\n }) as any,\n )\n values[\"name\"] = new MssqlParameter(\n migration.name,\n this.connection.driver.normalizeType({\n type: this.connection.driver.mappedDataTypes.migrationName,\n }) as any,\n )\n } else {\n values[\"timestamp\"] = migration.timestamp\n values[\"name\"] = migration.name\n }\n if (this.connection.driver.options.type === \"mongodb\") {\n const mongoRunner = queryRunner as MongoQueryRunner\n await mongoRunner.databaseConnection\n .db(this.connection.driver.database!)\n .collection(this.migrationsTableName)\n .insertOne(values)\n } else {\n const qb = queryRunner.manager.createQueryBuilder()\n await qb\n .insert()\n .into(this.migrationsTable)\n .values(values)\n .execute()\n }\n }\n\n /**\n * Delete previously executed migration's data from the migrations table.\n */\n protected async deleteExecutedMigration(\n queryRunner: QueryRunner,\n migration: Migration,\n ): Promise<void> {\n const conditions: ObjectLiteral = {}\n if (this.connection.driver.options.type === \"mssql\") {\n conditions[\"timestamp\"] = new MssqlParameter(\n migration.timestamp,\n this.connection.driver.normalizeType({\n type: this.connection.driver.mappedDataTypes\n .migrationTimestamp,\n }) as any,\n )\n conditions[\"name\"] = new MssqlParameter(\n migration.name,\n this.connection.driver.normalizeType({\n type: this.connection.driver.mappedDataTypes.migrationName,\n }) as any,\n )\n } else {\n conditions[\"timestamp\"] = migration.timestamp\n conditions[\"name\"] = migration.name\n }\n\n if (this.connection.driver.options.type === \"mongodb\") {\n const mongoRunner = queryRunner as MongoQueryRunner\n await mongoRunner.databaseConnection\n .db(this.connection.driver.database!)\n .collection(this.migrationsTableName)\n .deleteOne(conditions)\n } else {\n const qb = queryRunner.manager.createQueryBuilder()\n await qb\n .delete()\n .from(this.migrationsTable)\n .where(`${qb.escape(\"timestamp\")} = :timestamp`)\n .andWhere(`${qb.escape(\"name\")} = :name`)\n .setParameters(conditions)\n .execute()\n }\n }\n\n protected async withQueryRunner<T extends any>(\n callback: (queryRunner: QueryRunner) => T | Promise<T>,\n ) {\n const queryRunner =\n this.queryRunner || this.connection.createQueryRunner()\n\n try {\n return callback(queryRunner)\n } finally {\n if (!this.queryRunner) {\n await queryRunner.release()\n }\n }\n }\n}\n"],"sourceRoot":".."}
1
+ {"version":3,"sources":["../browser/src/migration/MigrationExecutor.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,+BAA+B,CAAA;AAErD,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAA;AAGvC,OAAO,EAAE,cAAc,EAAE,MAAM,oCAAoC,CAAA;AAEnE,OAAO,EAAE,qCAAqC,EAAE,YAAY,EAAE,MAAM,UAAU,CAAA;AAC9E,OAAO,EAAE,eAAe,EAAE,MAAM,yBAAyB,CAAA;AAEzD;;GAEG;AACH,MAAM,OAAO,iBAAiB;IA+B1B,4EAA4E;IAC5E,cAAc;IACd,4EAA4E;IAE5E,YACc,UAAsB,EACtB,WAAyB;QADzB,eAAU,GAAV,UAAU,CAAY;QACtB,gBAAW,GAAX,WAAW,CAAc;QApCvC,4EAA4E;QAC5E,oBAAoB;QACpB,4EAA4E;QAE5E;;;;;WAKG;QACH,gBAAW,GAA4B,KAAK,CAAA;QA4BxC,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,IAAI,CAAC,kBAAkB,GAAG,QAAQ,CAAA;QAClC,IAAI,CAAC,gBAAgB,GAAG,MAAM,CAAA;QAC9B,IAAI,CAAC,mBAAmB;YACpB,UAAU,CAAC,OAAO,CAAC,mBAAmB,IAAI,YAAY,CAAA;QAC1D,IAAI,CAAC,eAAe,GAAG,IAAI,CAAC,UAAU,CAAC,MAAM,CAAC,cAAc,CACxD,IAAI,CAAC,mBAAmB,EACxB,MAAM,EACN,QAAQ,CACX,CAAA;IACL,CAAC;IAED,4EAA4E;IAC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AE,CAAA;SACjB;IACL,CAAC;IAES,KAAK,CAAC,eAAe,CAC3B,QAAsD;QAEtD,MAAM,WAAW,GACb,IAAI,CAAC,WAAW,IAAI,IAAI,CAAC,UAAU,CAAC,iBAAiB,EAAE,CAAA;QAE3D,IAAI;YACA,OAAO,QAAQ,CAAC,WAAW,CAAC,CAAA;SAC/B;gBAAS;YACN,IAAI,CAAC,IAAI,CAAC,WAAW,EAAE;gBACnB,MAAM,WAAW,CAAC,OAAO,EAAE,CAAA;aAC9B;SACJ;IACL,CAAC;CACJ","file":"MigrationExecutor.js","sourcesContent":["import { Table } from \"../schema-builder/table/Table\"\nimport { DataSource } from \"../data-source/DataSource\"\nimport { Migration } from \"./Migration\"\nimport { ObjectLiteral } from \"../common/ObjectLiteral\"\nimport { QueryRunner } from \"../query-runner/QueryRunner\"\nimport { MssqlParameter } from \"../driver/sqlserver/MssqlParameter\"\nimport { MongoQueryRunner } from \"../driver/mongodb/MongoQueryRunner\"\nimport { ForbiddenTransactionModeOverrideError, TypeORMError } from \"../error\"\nimport { InstanceChecker } from \"../util/InstanceChecker\"\n\n/**\n * Executes migrations: runs pending and reverts previously executed migrations.\n */\nexport class MigrationExecutor {\n // -------------------------------------------------------------------------\n // Public Properties\n // -------------------------------------------------------------------------\n\n /**\n * Indicates how migrations should be run in transactions.\n * all: all migrations are run in a single transaction\n * none: all migrations are run without a transaction\n * each: each migration is run in a separate transaction\n */\n transaction: \"all\" | \"none\" | \"each\" = \"all\"\n\n /**\n * Option to fake-run or fake-revert a migration, adding to the\n * executed migrations table, but not actually running it. This feature is\n * useful for when migrations are added after the fact or for\n * interoperability between applications which are desired to each keep\n * a consistent migration history.\n */\n fake: boolean\n\n // -------------------------------------------------------------------------\n // Private Properties\n // -------------------------------------------------------------------------\n\n private readonly migrationsDatabase?: string\n private readonly migrationsSchema?: string\n private readonly migrationsTable: string\n private readonly migrationsTableName: string\n\n // -------------------------------------------------------------------------\n // Constructor\n // -------------------------------------------------------------------------\n\n constructor(\n protected connection: DataSource,\n protected queryRunner?: QueryRunner,\n ) {\n const { schema } = this.connection.driver.options as any\n const database = this.connection.driver.database\n this.migrationsDatabase = database\n this.migrationsSchema = schema\n this.migrationsTableName =\n connection.options.migrationsTableName || \"migrations\"\n this.migrationsTable = this.connection.driver.buildTableName(\n this.migrationsTableName,\n schema,\n database,\n )\n }\n\n // -------------------------------------------------------------------------\n // Public Methods\n // -------------------------------------------------------------------------\n\n /**\n * Tries to execute a single migration given.\n */\n public async executeMigration(migration: Migration): Promise<Migration> {\n return this.withQueryRunner(async (queryRunner) => {\n await this.createMigrationsTableIfNotExist(queryRunner)\n\n // create typeorm_metadata table if it's not created yet\n const schemaBuilder = this.connection.driver.createSchemaBuilder()\n if (InstanceChecker.isRdbmsSchemaBuilder(schemaBuilder)) {\n await schemaBuilder.createMetadataTableIfNecessary(queryRunner)\n }\n\n await queryRunner.beforeMigration()\n await (migration.instance as any).up(queryRunner)\n await queryRunner.afterMigration()\n await this.insertExecutedMigration(queryRunner, migration)\n\n return migration\n })\n }\n\n /**\n * Returns an array of all migrations.\n */\n public async getAllMigrations(): Promise<Migration[]> {\n return Promise.resolve(this.getMigrations())\n }\n\n /**\n * Returns an array of all executed migrations.\n */\n public async getExecutedMigrations(): Promise<Migration[]> {\n return this.withQueryRunner(async (queryRunner) => {\n await this.createMigrationsTableIfNotExist(queryRunner)\n\n return await this.loadExecutedMigrations(queryRunner)\n })\n }\n\n /**\n * Returns an array of all pending migrations.\n */\n public async getPendingMigrations(): Promise<Migration[]> {\n const allMigrations = await this.getAllMigrations()\n const executedMigrations = await this.getExecutedMigrations()\n\n return allMigrations.filter(\n (migration) =>\n !executedMigrations.find(\n (executedMigration) =>\n executedMigration.name === migration.name,\n ),\n )\n }\n\n /**\n * Inserts an executed migration.\n */\n public insertMigration(migration: Migration): Promise<void> {\n return this.withQueryRunner((q) =>\n this.insertExecutedMigration(q, migration),\n )\n }\n\n /**\n * Deletes an executed migration.\n */\n public deleteMigration(migration: Migration): Promise<void> {\n return this.withQueryRunner((q) =>\n this.deleteExecutedMigration(q, migration),\n )\n }\n\n /**\n * Lists all migrations and whether they have been executed or not\n * returns true if there are unapplied migrations\n */\n async showMigrations(): Promise<boolean> {\n let hasUnappliedMigrations = false\n const queryRunner =\n this.queryRunner || this.connection.createQueryRunner()\n // create migrations table if its not created yet\n await this.createMigrationsTableIfNotExist(queryRunner)\n\n // get all migrations that are executed and saved in the database\n const executedMigrations = await this.loadExecutedMigrations(\n queryRunner,\n )\n\n // get all user's migrations in the source code\n const allMigrations = this.getMigrations()\n\n for (const migration of allMigrations) {\n const executedMigration = executedMigrations.find(\n (executedMigration) =>\n executedMigration.name === migration.name,\n )\n\n if (executedMigration) {\n this.connection.logger.logSchemaBuild(\n `[X] ${executedMigration.id} ${migration.name}`,\n )\n } else {\n hasUnappliedMigrations = true\n this.connection.logger.logSchemaBuild(`[ ] ${migration.name}`)\n }\n }\n\n // if query runner was created by us then release it\n if (!this.queryRunner) {\n await queryRunner.release()\n }\n\n return hasUnappliedMigrations\n }\n\n /**\n * Executes all pending migrations. Pending migrations are migrations that are not yet executed,\n * thus not saved in the database.\n */\n async executePendingMigrations(): Promise<Migration[]> {\n const queryRunner =\n this.queryRunner || this.connection.createQueryRunner()\n // create migrations table if it's not created yet\n await this.createMigrationsTableIfNotExist(queryRunner)\n\n // create the typeorm_metadata table if it's not created yet\n const schemaBuilder = this.connection.driver.createSchemaBuilder()\n if (InstanceChecker.isRdbmsSchemaBuilder(schemaBuilder)) {\n await schemaBuilder.createMetadataTableIfNecessary(queryRunner)\n }\n\n // get all migrations that are executed and saved in the database\n const executedMigrations = await this.loadExecutedMigrations(\n queryRunner,\n )\n\n // get the time when last migration was executed\n let lastTimeExecutedMigration =\n this.getLatestTimestampMigration(executedMigrations)\n\n // get all user's migrations in the source code\n const allMigrations = this.getMigrations()\n\n // variable to store all migrations we did successfully\n const successMigrations: Migration[] = []\n\n // find all migrations that needs to be executed\n const pendingMigrations = allMigrations.filter((migration) => {\n // check if we already have executed migration\n const executedMigration = executedMigrations.find(\n (executedMigration) =>\n executedMigration.name === migration.name,\n )\n if (executedMigration) return false\n\n // migration is new and not executed. now check if its timestamp is correct\n // if (lastTimeExecutedMigration && migration.timestamp < lastTimeExecutedMigration.timestamp)\n // throw new TypeORMError(`New migration found: ${migration.name}, however this migration's timestamp is not valid. Migration's timestamp should not be older then migrations already executed in the database.`);\n\n // every check is passed means that migration was not run yet and we need to run it\n return true\n })\n\n // if no migrations are pending then nothing to do here\n if (!pendingMigrations.length) {\n this.connection.logger.logSchemaBuild(`No migrations are pending`)\n // if query runner was created by us then release it\n if (!this.queryRunner) await queryRunner.release()\n return []\n }\n\n // log information about migration execution\n this.connection.logger.logSchemaBuild(\n `${executedMigrations.length} migrations are already loaded in the database.`,\n )\n this.connection.logger.logSchemaBuild(\n `${allMigrations.length} migrations were found in the source code.`,\n )\n if (lastTimeExecutedMigration)\n this.connection.logger.logSchemaBuild(\n `${\n lastTimeExecutedMigration.name\n } is the last executed migration. It was executed on ${new Date(\n lastTimeExecutedMigration.timestamp,\n ).toString()}.`,\n )\n this.connection.logger.logSchemaBuild(\n `${pendingMigrations.length} migrations are new migrations must be executed.`,\n )\n\n if (this.transaction === \"all\") {\n // If we desire to run all migrations in a single transaction\n // but there is a migration that explicitly overrides the transaction mode\n // then we have to fail since we cannot properly resolve that intent\n // In theory we could support overrides that are set to `true`,\n // however to keep the interface more rigid, we fail those too\n const migrationsOverridingTransactionMode =\n pendingMigrations.filter(\n (migration) =>\n !(migration.instance?.transaction === undefined),\n )\n\n if (migrationsOverridingTransactionMode.length > 0) {\n const error = new ForbiddenTransactionModeOverrideError(\n migrationsOverridingTransactionMode,\n )\n this.connection.logger.logMigration(\n `Migrations failed, error: ${error.message}`,\n )\n throw error\n }\n }\n\n // Set the per-migration defaults for the transaction mode\n // so that we have one centralized place that controls this behavior\n\n // When transaction mode is `each` the default is to run in a transaction\n // When transaction mode is `none` the default is to not run in a transaction\n // When transaction mode is `all` the default is to not run in a transaction\n // since all the migrations are already running in one single transaction\n\n const txModeDefault = {\n each: true,\n none: false,\n all: false,\n }[this.transaction]\n\n for (const migration of pendingMigrations) {\n if (migration.instance) {\n const instanceTx = migration.instance.transaction\n\n if (instanceTx === undefined) {\n migration.transaction = txModeDefault\n } else {\n migration.transaction = instanceTx\n }\n }\n }\n\n // start transaction if its not started yet\n let transactionStartedByUs = false\n if (this.transaction === \"all\" && !queryRunner.isTransactionActive) {\n await queryRunner.startTransaction()\n transactionStartedByUs = true\n }\n\n // run all pending migrations in a sequence\n try {\n for (const migration of pendingMigrations) {\n if (this.fake) {\n // directly insert migration record into the database if it is fake\n await this.insertExecutedMigration(queryRunner, migration)\n\n // nothing else needs to be done, continue to next migration\n continue\n }\n\n if (migration.transaction && !queryRunner.isTransactionActive) {\n await queryRunner.startTransaction()\n transactionStartedByUs = true\n }\n\n await migration\n .instance!.up(queryRunner)\n .catch((error) => {\n // informative log about migration failure\n this.connection.logger.logMigration(\n `Migration \"${migration.name}\" failed, error: ${error?.message}`,\n )\n throw error\n })\n .then(async () => {\n // now when migration is executed we need to insert record about it into the database\n await this.insertExecutedMigration(\n queryRunner,\n migration,\n )\n // commit transaction if we started it\n if (migration.transaction && transactionStartedByUs)\n await queryRunner.commitTransaction()\n })\n .then(() => {\n // informative log about migration success\n successMigrations.push(migration)\n this.connection.logger.logSchemaBuild(\n `Migration ${migration.name} has been ${\n this.fake ? \"(fake)\" : \"\"\n } executed successfully.`,\n )\n })\n }\n\n // commit transaction if we started it\n if (this.transaction === \"all\" && transactionStartedByUs)\n await queryRunner.commitTransaction()\n } catch (err) {\n // rollback transaction if we started it\n if (transactionStartedByUs) {\n try {\n // we throw original error even if rollback thrown an error\n await queryRunner.rollbackTransaction()\n } catch (rollbackError) {}\n }\n\n throw err\n } finally {\n // if query runner was created by us then release it\n if (!this.queryRunner) await queryRunner.release()\n }\n return successMigrations\n }\n\n /**\n * Reverts last migration that were run.\n */\n async undoLastMigration(): Promise<void> {\n const queryRunner =\n this.queryRunner || this.connection.createQueryRunner()\n\n // create migrations table if it's not created yet\n await this.createMigrationsTableIfNotExist(queryRunner)\n\n // create typeorm_metadata table if it's not created yet\n const schemaBuilder = this.connection.driver.createSchemaBuilder()\n if (InstanceChecker.isRdbmsSchemaBuilder(schemaBuilder)) {\n await schemaBuilder.createMetadataTableIfNecessary(queryRunner)\n }\n\n // get all migrations that are executed and saved in the database\n const executedMigrations = await this.loadExecutedMigrations(\n queryRunner,\n )\n\n // get the time when last migration was executed\n let lastTimeExecutedMigration =\n this.getLatestExecutedMigration(executedMigrations)\n\n // if no migrations found in the database then nothing to revert\n if (!lastTimeExecutedMigration) {\n this.connection.logger.logSchemaBuild(\n `No migrations was found in the database. Nothing to revert!`,\n )\n return\n }\n\n // get all user's migrations in the source code\n const allMigrations = this.getMigrations()\n\n // find the instance of the migration we need to remove\n const migrationToRevert = allMigrations.find(\n (migration) => migration.name === lastTimeExecutedMigration!.name,\n )\n\n // if no migrations found in the database then nothing to revert\n if (!migrationToRevert)\n throw new TypeORMError(\n `No migration ${lastTimeExecutedMigration.name} was found in the source code. Make sure you have this migration in your codebase and its included in the connection options.`,\n )\n\n // log information about migration execution\n this.connection.logger.logSchemaBuild(\n `${executedMigrations.length} migrations are already loaded in the database.`,\n )\n this.connection.logger.logSchemaBuild(\n `${\n lastTimeExecutedMigration.name\n } is the last executed migration. It was executed on ${new Date(\n lastTimeExecutedMigration.timestamp,\n ).toString()}.`,\n )\n this.connection.logger.logSchemaBuild(`Now reverting it...`)\n\n // start transaction if its not started yet\n let transactionStartedByUs = false\n if (this.transaction !== \"none\" && !queryRunner.isTransactionActive) {\n await queryRunner.startTransaction()\n transactionStartedByUs = true\n }\n\n try {\n if (!this.fake) {\n await queryRunner.beforeMigration()\n await migrationToRevert.instance!.down(queryRunner)\n await queryRunner.afterMigration()\n }\n\n await this.deleteExecutedMigration(queryRunner, migrationToRevert)\n this.connection.logger.logSchemaBuild(\n `Migration ${migrationToRevert.name} has been ${\n this.fake ? \"(fake)\" : \"\"\n } reverted successfully.`,\n )\n\n // commit transaction if we started it\n if (transactionStartedByUs) await queryRunner.commitTransaction()\n } catch (err) {\n // rollback transaction if we started it\n if (transactionStartedByUs) {\n try {\n // we throw original error even if rollback thrown an error\n await queryRunner.rollbackTransaction()\n } catch (rollbackError) {}\n }\n\n throw err\n } finally {\n // if query runner was created by us then release it\n if (!this.queryRunner) await queryRunner.release()\n }\n }\n\n // -------------------------------------------------------------------------\n // Protected Methods\n // -------------------------------------------------------------------------\n\n /**\n * Creates table \"migrations\" that will store information about executed migrations.\n */\n protected async createMigrationsTableIfNotExist(\n queryRunner: QueryRunner,\n ): Promise<void> {\n // If driver is mongo no need to create\n if (this.connection.driver.options.type === \"mongodb\") {\n return\n }\n const tableExist = await queryRunner.hasTable(this.migrationsTable) // todo: table name should be configurable\n if (!tableExist) {\n await queryRunner.createTable(\n new Table({\n database: this.migrationsDatabase,\n schema: this.migrationsSchema,\n name: this.migrationsTable,\n columns: [\n {\n name: \"id\",\n type: this.connection.driver.normalizeType({\n type: this.connection.driver.mappedDataTypes\n .migrationId,\n }),\n isGenerated: true,\n generationStrategy: \"increment\",\n isPrimary: true,\n isNullable: false,\n },\n {\n name: \"timestamp\",\n type: this.connection.driver.normalizeType({\n type: this.connection.driver.mappedDataTypes\n .migrationTimestamp,\n }),\n isPrimary: false,\n isNullable: false,\n },\n {\n name: \"name\",\n type: this.connection.driver.normalizeType({\n type: this.connection.driver.mappedDataTypes\n .migrationName,\n }),\n isNullable: false,\n },\n ],\n }),\n )\n }\n }\n\n /**\n * Loads all migrations that were executed and saved into the database (sorts by id).\n */\n protected async loadExecutedMigrations(\n queryRunner: QueryRunner,\n ): Promise<Migration[]> {\n if (this.connection.driver.options.type === \"mongodb\") {\n const mongoRunner = queryRunner as MongoQueryRunner\n return await mongoRunner.databaseConnection\n .db(this.connection.driver.database!)\n .collection(this.migrationsTableName)\n .find<Migration>()\n .sort({ _id: -1 })\n .toArray()\n } else {\n const migrationsRaw: ObjectLiteral[] = await this.connection.manager\n .createQueryBuilder(queryRunner)\n .select()\n .orderBy(this.connection.driver.escape(\"id\"), \"DESC\")\n .from(this.migrationsTable, this.migrationsTableName)\n .getRawMany()\n return migrationsRaw.map((migrationRaw) => {\n return new Migration(\n parseInt(migrationRaw[\"id\"]),\n parseInt(migrationRaw[\"timestamp\"]),\n migrationRaw[\"name\"],\n )\n })\n }\n }\n\n /**\n * Gets all migrations that setup for this connection.\n */\n protected getMigrations(): Migration[] {\n const migrations = this.connection.migrations.map((migration) => {\n const migrationClassName =\n migration.name || (migration.constructor as any).name\n const migrationTimestamp = parseInt(\n migrationClassName.substr(-13),\n 10,\n )\n if (!migrationTimestamp || isNaN(migrationTimestamp)) {\n throw new TypeORMError(\n `${migrationClassName} migration name is wrong. Migration class name should have a JavaScript timestamp appended.`,\n )\n }\n\n return new Migration(\n undefined,\n migrationTimestamp,\n migrationClassName,\n migration,\n )\n })\n\n this.checkForDuplicateMigrations(migrations)\n\n // sort them by timestamp\n return migrations.sort((a, b) => a.timestamp - b.timestamp)\n }\n\n protected checkForDuplicateMigrations(migrations: Migration[]) {\n const migrationNames = migrations.map((migration) => migration.name)\n const duplicates = Array.from(\n new Set(\n migrationNames.filter(\n (migrationName, index) =>\n migrationNames.indexOf(migrationName) < index,\n ),\n ),\n )\n if (duplicates.length > 0) {\n throw Error(`Duplicate migrations: ${duplicates.join(\", \")}`)\n }\n }\n\n /**\n * Finds the latest migration (sorts by timestamp) in the given array of migrations.\n */\n protected getLatestTimestampMigration(\n migrations: Migration[],\n ): Migration | undefined {\n const sortedMigrations = migrations\n .map((migration) => migration)\n .sort((a, b) => (a.timestamp - b.timestamp) * -1)\n return sortedMigrations.length > 0 ? sortedMigrations[0] : undefined\n }\n\n /**\n * Finds the latest migration in the given array of migrations.\n * PRE: Migration array must be sorted by descending id.\n */\n protected getLatestExecutedMigration(\n sortedMigrations: Migration[],\n ): Migration | undefined {\n return sortedMigrations.length > 0 ? sortedMigrations[0] : undefined\n }\n\n /**\n * Inserts new executed migration's data into migrations table.\n */\n protected async insertExecutedMigration(\n queryRunner: QueryRunner,\n migration: Migration,\n ): Promise<void> {\n const values: ObjectLiteral = {}\n if (this.connection.driver.options.type === \"mssql\") {\n values[\"timestamp\"] = new MssqlParameter(\n migration.timestamp,\n this.connection.driver.normalizeType({\n type: this.connection.driver.mappedDataTypes\n .migrationTimestamp,\n }) as any,\n )\n values[\"name\"] = new MssqlParameter(\n migration.name,\n this.connection.driver.normalizeType({\n type: this.connection.driver.mappedDataTypes.migrationName,\n }) as any,\n )\n } else {\n values[\"timestamp\"] = migration.timestamp\n values[\"name\"] = migration.name\n }\n if (this.connection.driver.options.type === \"mongodb\") {\n const mongoRunner = queryRunner as MongoQueryRunner\n await mongoRunner.databaseConnection\n .db(this.connection.driver.database!)\n .collection(this.migrationsTableName)\n .insertOne(values)\n } else {\n const qb = queryRunner.manager.createQueryBuilder()\n await qb\n .insert()\n .into(this.migrationsTable)\n .values(values)\n .execute()\n }\n }\n\n /**\n * Delete previously executed migration's data from the migrations table.\n */\n protected async deleteExecutedMigration(\n queryRunner: QueryRunner,\n migration: Migration,\n ): Promise<void> {\n const conditions: ObjectLiteral = {}\n if (this.connection.driver.options.type === \"mssql\") {\n conditions[\"timestamp\"] = new MssqlParameter(\n migration.timestamp,\n this.connection.driver.normalizeType({\n type: this.connection.driver.mappedDataTypes\n .migrationTimestamp,\n }) as any,\n )\n conditions[\"name\"] = new MssqlParameter(\n migration.name,\n this.connection.driver.normalizeType({\n type: this.connection.driver.mappedDataTypes.migrationName,\n }) as any,\n )\n } else {\n conditions[\"timestamp\"] = migration.timestamp\n conditions[\"name\"] = migration.name\n }\n\n if (this.connection.driver.options.type === \"mongodb\") {\n const mongoRunner = queryRunner as MongoQueryRunner\n await mongoRunner.databaseConnection\n .db(this.connection.driver.database!)\n .collection(this.migrationsTableName)\n .deleteOne(conditions)\n } else {\n const qb = queryRunner.manager.createQueryBuilder()\n await qb\n .delete()\n .from(this.migrationsTable)\n .where(`${qb.escape(\"timestamp\")} = :timestamp`)\n .andWhere(`${qb.escape(\"name\")} = :name`)\n .setParameters(conditions)\n .execute()\n }\n }\n\n protected async withQueryRunner<T extends any>(\n callback: (queryRunner: QueryRunner) => T | Promise<T>,\n ) {\n const queryRunner =\n this.queryRunner || this.connection.createQueryRunner()\n\n try {\n return callback(queryRunner)\n } finally {\n if (!this.queryRunner) {\n await queryRunner.release()\n }\n }\n }\n}\n"],"sourceRoot":".."}
@@ -7,6 +7,13 @@ export interface MigrationInterface {
7
7
  * Optional migration name, defaults to class name.
8
8
  */
9
9
  name?: string;
10
+ /**
11
+ * Optional flag to determine whether to run the migration in a transaction or not.
12
+ * Can only be used when `migrationsTransactionMode` is either "each" or "none"
13
+ * Defaults to `true` when `migrationsTransactionMode` is "each"
14
+ * Defaults to `false` when `migrationsTransactionMode` is "none"
15
+ */
16
+ transaction?: boolean;
10
17
  /**
11
18
  * Run the migrations.
12
19
  */
@@ -1 +1 @@
1
- {"version":3,"sources":["../browser/src/migration/MigrationInterface.ts"],"names":[],"mappings":"","file":"MigrationInterface.js","sourcesContent":["import { QueryRunner } from \"../query-runner/QueryRunner\"\n\n/**\n * Migrations should implement this interface and all its methods.\n */\nexport interface MigrationInterface {\n /**\n * Optional migration name, defaults to class name.\n */\n name?: string\n\n /**\n * Run the migrations.\n */\n up(queryRunner: QueryRunner): Promise<any>\n\n /**\n * Reverse the migrations.\n */\n down(queryRunner: QueryRunner): Promise<any>\n}\n"],"sourceRoot":".."}
1
+ {"version":3,"sources":["../browser/src/migration/MigrationInterface.ts"],"names":[],"mappings":"","file":"MigrationInterface.js","sourcesContent":["import { QueryRunner } from \"../query-runner/QueryRunner\"\n\n/**\n * Migrations should implement this interface and all its methods.\n */\nexport interface MigrationInterface {\n /**\n * Optional migration name, defaults to class name.\n */\n name?: string\n\n /**\n * Optional flag to determine whether to run the migration in a transaction or not.\n * Can only be used when `migrationsTransactionMode` is either \"each\" or \"none\"\n * Defaults to `true` when `migrationsTransactionMode` is \"each\"\n * Defaults to `false` when `migrationsTransactionMode` is \"none\"\n */\n transaction?: boolean\n\n /**\n * Run the migrations.\n */\n up(queryRunner: QueryRunner): Promise<any>\n\n /**\n * Reverse the migrations.\n */\n down(queryRunner: QueryRunner): Promise<any>\n}\n"],"sourceRoot":".."}
@@ -1,4 +1,5 @@
1
1
  import { Table } from "../schema-builder/table/Table";
2
+ import { View } from "../schema-builder/view/View";
2
3
  /**
3
4
  * Naming strategy defines how auto-generated names for such things like table name, or table column gonna be
4
5
  * generated.
@@ -53,7 +54,7 @@ export interface NamingStrategyInterface {
53
54
  /**
54
55
  * Gets the name of the index - simple and compose index.
55
56
  */
56
- indexName(tableOrName: Table | string, columns: string[], where?: string): string;
57
+ indexName(tableOrName: Table | View | string, columns: string[], where?: string): string;
57
58
  /**
58
59
  * Gets the name of the check constraint.
59
60
  *
@@ -1 +1 @@
1
- {"version":3,"sources":["../browser/src/naming-strategy/NamingStrategyInterface.ts"],"names":[],"mappings":"","file":"NamingStrategyInterface.js","sourcesContent":["import { Table } from \"../schema-builder/table/Table\"\n\n/**\n * Naming strategy defines how auto-generated names for such things like table name, or table column gonna be\n * generated.\n */\nexport interface NamingStrategyInterface {\n /**\n * Naming strategy name.\n */\n name?: string\n\n /**\n * Normalizes table name.\n *\n * @param targetName Name of the target entity that can be used to generate a table name.\n * @param userSpecifiedName For example if user specified a table name in a decorator, e.g. @Entity(\"name\")\n */\n tableName(targetName: string, userSpecifiedName: string | undefined): string\n\n /**\n * Creates a table name for a junction table of a closure table.\n *\n * @param originalClosureTableName Name of the closure table which owns this junction table.\n */\n closureJunctionTableName(originalClosureTableName: string): string\n\n /**\n * Gets the table's column name from the given property name.\n */\n columnName(\n propertyName: string,\n customName: string | undefined,\n embeddedPrefixes: string[],\n ): string\n\n /**\n * Gets the table's relation name from the given property name.\n */\n relationName(propertyName: string): string\n\n /**\n * Gets the table's primary key name from the given table name and column names.\n */\n primaryKeyName(tableOrName: Table | string, columnNames: string[]): string\n\n /**\n * Gets the table's unique constraint name from the given table name and column names.\n */\n uniqueConstraintName(\n tableOrName: Table | string,\n columnNames: string[],\n ): string\n\n /**\n * Gets the relation constraint (UNIQUE or UNIQUE INDEX) name from the given table name, column names\n * and WHERE condition, if UNIQUE INDEX used.\n */\n relationConstraintName(\n tableOrName: Table | string,\n columnNames: string[],\n where?: string,\n ): string\n\n /**\n * Gets the table's default constraint name from the given table name and column name.\n */\n defaultConstraintName(\n tableOrName: Table | string,\n columnName: string,\n ): string\n\n /**\n * Gets the name of the foreign key.\n */\n foreignKeyName(\n tableOrName: Table | string,\n columnNames: string[],\n referencedTablePath?: string,\n referencedColumnNames?: string[],\n ): string\n\n /**\n * Gets the name of the index - simple and compose index.\n */\n indexName(\n tableOrName: Table | string,\n columns: string[],\n where?: string,\n ): string\n\n /**\n * Gets the name of the check constraint.\n *\n * \"isEnum\" parameter is used to indicate if this check constraint used\n * to handle \"simple-enum\" type for databases that are not supporting \"enum\"\n * type out of the box. If \"true\", constraint is ignored during CHECK constraints\n * synchronization.\n */\n checkConstraintName(\n tableOrName: Table | string,\n expression: string,\n isEnum?: boolean,\n ): string\n\n /**\n * Gets the name of the exclusion constraint.\n */\n exclusionConstraintName(\n tableOrName: Table | string,\n expression: string,\n ): string\n\n /**\n * Gets the name of the join column used in the one-to-one and many-to-one relations.\n */\n joinColumnName(relationName: string, referencedColumnName: string): string\n\n /**\n * Gets the name of the join table used in the many-to-many relations.\n */\n joinTableName(\n firstTableName: string,\n secondTableName: string,\n firstPropertyName: string,\n secondPropertyName: string,\n ): string\n\n /**\n * Columns in join tables can have duplicate names in case of self-referencing.\n * This method provide a resolution for such column names.\n */\n joinTableColumnDuplicationPrefix(columnName: string, index: number): string\n\n /**\n * Gets the name of the column used for columns in the junction tables.\n *\n * The reverse?:boolean parameter denotes if the joinTableColumnName is called for the junctionColumn (false)\n * or the inverseJunctionColumns (true)\n */\n joinTableColumnName(\n tableName: string,\n propertyName: string,\n columnName?: string,\n ): string\n\n /**\n * Gets the name of the column used for columns in the junction tables from the invers side of the relationship.\n */\n joinTableInverseColumnName(\n tableName: string,\n propertyName: string,\n columnName?: string,\n ): string\n\n /**\n * Adds globally set prefix to the table name.\n * This method is executed no matter if prefix was set or not.\n * Table name is either user's given table name, either name generated from entity target.\n * Note that table name comes here already normalized by #tableName method.\n */\n prefixTableName(prefix: string, tableName: string): string\n\n /**\n * Gets the name of the alias used for relation joins.\n */\n eagerJoinRelationAlias(alias: string, propertyPath: string): string\n\n /**\n * Column names for nested sets.\n */\n nestedSetColumnNames: { left: string; right: string }\n\n /**\n * Column name for materialized paths.\n */\n materializedPathColumnName: string\n}\n"],"sourceRoot":".."}
1
+ {"version":3,"sources":["../browser/src/naming-strategy/NamingStrategyInterface.ts"],"names":[],"mappings":"","file":"NamingStrategyInterface.js","sourcesContent":["import { Table } from \"../schema-builder/table/Table\"\nimport { View } from \"../schema-builder/view/View\"\n\n/**\n * Naming strategy defines how auto-generated names for such things like table name, or table column gonna be\n * generated.\n */\nexport interface NamingStrategyInterface {\n /**\n * Naming strategy name.\n */\n name?: string\n\n /**\n * Normalizes table name.\n *\n * @param targetName Name of the target entity that can be used to generate a table name.\n * @param userSpecifiedName For example if user specified a table name in a decorator, e.g. @Entity(\"name\")\n */\n tableName(targetName: string, userSpecifiedName: string | undefined): string\n\n /**\n * Creates a table name for a junction table of a closure table.\n *\n * @param originalClosureTableName Name of the closure table which owns this junction table.\n */\n closureJunctionTableName(originalClosureTableName: string): string\n\n /**\n * Gets the table's column name from the given property name.\n */\n columnName(\n propertyName: string,\n customName: string | undefined,\n embeddedPrefixes: string[],\n ): string\n\n /**\n * Gets the table's relation name from the given property name.\n */\n relationName(propertyName: string): string\n\n /**\n * Gets the table's primary key name from the given table name and column names.\n */\n primaryKeyName(tableOrName: Table | string, columnNames: string[]): string\n\n /**\n * Gets the table's unique constraint name from the given table name and column names.\n */\n uniqueConstraintName(\n tableOrName: Table | string,\n columnNames: string[],\n ): string\n\n /**\n * Gets the relation constraint (UNIQUE or UNIQUE INDEX) name from the given table name, column names\n * and WHERE condition, if UNIQUE INDEX used.\n */\n relationConstraintName(\n tableOrName: Table | string,\n columnNames: string[],\n where?: string,\n ): string\n\n /**\n * Gets the table's default constraint name from the given table name and column name.\n */\n defaultConstraintName(\n tableOrName: Table | string,\n columnName: string,\n ): string\n\n /**\n * Gets the name of the foreign key.\n */\n foreignKeyName(\n tableOrName: Table | string,\n columnNames: string[],\n referencedTablePath?: string,\n referencedColumnNames?: string[],\n ): string\n\n /**\n * Gets the name of the index - simple and compose index.\n */\n indexName(\n tableOrName: Table | View | string,\n columns: string[],\n where?: string,\n ): string\n\n /**\n * Gets the name of the check constraint.\n *\n * \"isEnum\" parameter is used to indicate if this check constraint used\n * to handle \"simple-enum\" type for databases that are not supporting \"enum\"\n * type out of the box. If \"true\", constraint is ignored during CHECK constraints\n * synchronization.\n */\n checkConstraintName(\n tableOrName: Table | string,\n expression: string,\n isEnum?: boolean,\n ): string\n\n /**\n * Gets the name of the exclusion constraint.\n */\n exclusionConstraintName(\n tableOrName: Table | string,\n expression: string,\n ): string\n\n /**\n * Gets the name of the join column used in the one-to-one and many-to-one relations.\n */\n joinColumnName(relationName: string, referencedColumnName: string): string\n\n /**\n * Gets the name of the join table used in the many-to-many relations.\n */\n joinTableName(\n firstTableName: string,\n secondTableName: string,\n firstPropertyName: string,\n secondPropertyName: string,\n ): string\n\n /**\n * Columns in join tables can have duplicate names in case of self-referencing.\n * This method provide a resolution for such column names.\n */\n joinTableColumnDuplicationPrefix(columnName: string, index: number): string\n\n /**\n * Gets the name of the column used for columns in the junction tables.\n *\n * The reverse?:boolean parameter denotes if the joinTableColumnName is called for the junctionColumn (false)\n * or the inverseJunctionColumns (true)\n */\n joinTableColumnName(\n tableName: string,\n propertyName: string,\n columnName?: string,\n ): string\n\n /**\n * Gets the name of the column used for columns in the junction tables from the invers side of the relationship.\n */\n joinTableInverseColumnName(\n tableName: string,\n propertyName: string,\n columnName?: string,\n ): string\n\n /**\n * Adds globally set prefix to the table name.\n * This method is executed no matter if prefix was set or not.\n * Table name is either user's given table name, either name generated from entity target.\n * Note that table name comes here already normalized by #tableName method.\n */\n prefixTableName(prefix: string, tableName: string): string\n\n /**\n * Gets the name of the alias used for relation joins.\n */\n eagerJoinRelationAlias(alias: string, propertyPath: string): string\n\n /**\n * Column names for nested sets.\n */\n nestedSetColumnNames: { left: string; right: string }\n\n /**\n * Column name for materialized paths.\n */\n materializedPathColumnName: string\n}\n"],"sourceRoot":".."}
@@ -132,7 +132,8 @@ export class EntityPersistExecutor {
132
132
  try {
133
133
  // open transaction if its not opened yet
134
134
  if (!queryRunner.isTransactionActive) {
135
- if (!this.options || this.options.transaction !== false) {
135
+ if (this.connection.driver.transactionSupport !== "none" &&
136
+ (!this.options || this.options.transaction !== false)) {
136
137
  // start transaction until it was not explicitly disabled
137
138
  isTransactionStartedByUs = true;
138
139
  await queryRunner.startTransaction();
@@ -1 +1 @@
1
- {"version":3,"sources":["../browser/src/persistence/EntityPersistExecutor.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,iBAAiB,EAAE,MAAM,4BAA4B,CAAA;AAC9D,OAAO,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAA;AACnD,OAAO,EAAE,0BAA0B,EAAE,MAAM,qCAAqC,CAAA;AAGhF,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAA;AACnC,OAAO,EAAE,uBAAuB,EAAE,MAAM,2CAA2C,CAAA;AACnF,OAAO,EAAE,iCAAiC,EAAE,MAAM,qDAAqD,CAAA;AACvG,OAAO,EAAE,wBAAwB,EAAE,MAAM,4CAA4C,CAAA;AACrF,OAAO,EAAE,2BAA2B,EAAE,MAAM,+BAA+B,CAAA;AAC3E,OAAO,EAAE,sBAAsB,EAAE,MAAM,0CAA0C,CAAA;AACjF,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAA;AAE3C;;GAEG;AACH,MAAM,OAAO,q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AAI,wBAAwB,EAAE;oBAC1B,IAAI;wBACA,MAAM,WAAW,CAAC,mBAAmB,EAAE,CAAA;qBAC1C;oBAAC,OAAO,aAAa,EAAE,GAAE;iBAC7B;gBACD,MAAM,KAAK,CAAA;aACd;SACJ;gBAAS;YACN,WAAW,CAAC,IAAI,GAAG,kBAAkB,CAAA;YAErC,iDAAiD;YACjD,IAAI,CAAC,IAAI,CAAC,WAAW;gBAAE,MAAM,WAAW,CAAC,OAAO,EAAE,CAAA;SACrD;IACL,CAAC;CACJ","file":"EntityPersistExecutor.js","sourcesContent":["import { ObjectLiteral } from \"../common/ObjectLiteral\"\nimport { SaveOptions } from \"../repository/SaveOptions\"\nimport { RemoveOptions } from \"../repository/RemoveOptions\"\nimport { MustBeEntityError } from \"../error/MustBeEntityError\"\nimport { SubjectExecutor } from \"./SubjectExecutor\"\nimport { CannotDetermineEntityError } from \"../error/CannotDetermineEntityError\"\nimport { QueryRunner } from \"../query-runner/QueryRunner\"\nimport { DataSource } from \"../data-source/DataSource\"\nimport { Subject } from \"./Subject\"\nimport { OneToManySubjectBuilder } from \"./subject-builder/OneToManySubjectBuilder\"\nimport { OneToOneInverseSideSubjectBuilder } from \"./subject-builder/OneToOneInverseSideSubjectBuilder\"\nimport { ManyToManySubjectBuilder } from \"./subject-builder/ManyToManySubjectBuilder\"\nimport { SubjectDatabaseEntityLoader } from \"./SubjectDatabaseEntityLoader\"\nimport { CascadesSubjectBuilder } from \"./subject-builder/CascadesSubjectBuilder\"\nimport { OrmUtils } from \"../util/OrmUtils\"\n\n/**\n * Persists a single entity or multiple entities - saves or removes them.\n */\nexport class EntityPersistExecutor {\n // -------------------------------------------------------------------------\n // Constructor\n // -------------------------------------------------------------------------\n\n constructor(\n protected connection: DataSource,\n protected queryRunner: QueryRunner | undefined,\n protected mode: \"save\" | \"remove\" | \"soft-remove\" | \"recover\",\n protected target: Function | string | undefined,\n protected entity: ObjectLiteral | ObjectLiteral[],\n protected options?: SaveOptions & RemoveOptions,\n ) {}\n\n // -------------------------------------------------------------------------\n // Public Methods\n // -------------------------------------------------------------------------\n\n /**\n * Executes persistence operation ob given entity or entities.\n */\n async execute(): Promise<void> {\n // check if entity we are going to save is valid and is an object\n if (!this.entity || typeof this.entity !== \"object\")\n return Promise.reject(new MustBeEntityError(this.mode, this.entity))\n\n // we MUST call \"fake\" resolve here to make sure all properties of lazily loaded relations are resolved\n await Promise.resolve()\n\n // if query runner is already defined in this class, it means this entity manager was already created for a single connection\n // if its not defined we create a new query runner - single connection where we'll execute all our operations\n const queryRunner =\n this.queryRunner || this.connection.createQueryRunner()\n\n // save data in the query runner - this is useful functionality to share data from outside of the world\n // with third classes - like subscribers and listener methods\n let oldQueryRunnerData = queryRunner.data\n if (this.options && this.options.data) {\n queryRunner.data = this.options.data\n }\n\n try {\n // collect all operate subjects\n const entities: ObjectLiteral[] = Array.isArray(this.entity)\n ? this.entity\n : [this.entity]\n const entitiesInChunks =\n this.options && this.options.chunk && this.options.chunk > 0\n ? OrmUtils.chunk(entities, this.options.chunk)\n : [entities]\n\n // console.time(\"building subject executors...\");\n const executors = await Promise.all(\n entitiesInChunks.map(async (entities) => {\n const subjects: Subject[] = []\n\n // create subjects for all entities we received for the persistence\n entities.forEach((entity) => {\n const entityTarget = this.target\n ? this.target\n : entity.constructor\n if (entityTarget === Object)\n throw new CannotDetermineEntityError(this.mode)\n\n let metadata = this.connection.getMetadata(entityTarget)\n\n // Check for single table inheritance and find the correct metadata in that case.\n // Goal is to use the correct discriminator as we could have a repository\n // for an (abstract) base class and thus the target would not match.\n if (\n metadata.inheritancePattern === \"STI\" &&\n metadata.childEntityMetadatas.length > 0\n ) {\n const matchingChildMetadata =\n metadata.childEntityMetadatas.find(\n (meta) =>\n entity.constructor === meta.target,\n )\n if (matchingChildMetadata) {\n metadata = matchingChildMetadata\n }\n }\n\n subjects.push(\n new Subject({\n metadata,\n entity: entity,\n canBeInserted: this.mode === \"save\",\n canBeUpdated: this.mode === \"save\",\n mustBeRemoved: this.mode === \"remove\",\n canBeSoftRemoved: this.mode === \"soft-remove\",\n canBeRecovered: this.mode === \"recover\",\n }),\n )\n })\n\n // console.time(\"building cascades...\");\n // go through each entity with metadata and create subjects and subjects by cascades for them\n const cascadesSubjectBuilder = new CascadesSubjectBuilder(\n subjects,\n )\n subjects.forEach((subject) => {\n // next step we build list of subjects we will operate with\n // these subjects are subjects that we need to insert or update alongside with main persisted entity\n cascadesSubjectBuilder.build(subject, this.mode)\n })\n // console.timeEnd(\"building cascades...\");\n\n // load database entities for all subjects we have\n // next step is to load database entities for all operate subjects\n // console.time(\"loading...\");\n await new SubjectDatabaseEntityLoader(\n queryRunner,\n subjects,\n ).load(this.mode)\n // console.timeEnd(\"loading...\");\n\n // console.time(\"other subjects...\");\n // build all related subjects and change maps\n if (\n this.mode === \"save\" ||\n this.mode === \"soft-remove\" ||\n this.mode === \"recover\"\n ) {\n new OneToManySubjectBuilder(subjects).build()\n new OneToOneInverseSideSubjectBuilder(subjects).build()\n new ManyToManySubjectBuilder(subjects).build()\n } else {\n subjects.forEach((subject) => {\n if (subject.mustBeRemoved) {\n new ManyToManySubjectBuilder(\n subjects,\n ).buildForAllRemoval(subject)\n }\n })\n }\n // console.timeEnd(\"other subjects...\");\n // console.timeEnd(\"building subjects...\");\n // console.log(\"subjects\", subjects);\n\n // create a subject executor\n return new SubjectExecutor(\n queryRunner,\n subjects,\n this.options,\n )\n }),\n )\n // console.timeEnd(\"building subject executors...\");\n\n // make sure we have at least one executable operation before we create a transaction and proceed\n // if we don't have operations it means we don't really need to update or remove something\n const executorsWithExecutableOperations = executors.filter(\n (executor) => executor.hasExecutableOperations,\n )\n if (executorsWithExecutableOperations.length === 0) return\n\n // start execute queries in a transaction\n // if transaction is already opened in this query runner then we don't touch it\n // if its not opened yet then we open it here, and once we finish - we close it\n let isTransactionStartedByUs = false\n try {\n // open transaction if its not opened yet\n if (!queryRunner.isTransactionActive) {\n if (!this.options || this.options.transaction !== false) {\n // start transaction until it was not explicitly disabled\n isTransactionStartedByUs = true\n await queryRunner.startTransaction()\n }\n }\n\n // execute all persistence operations for all entities we have\n // console.time(\"executing subject executors...\");\n for (const executor of executorsWithExecutableOperations) {\n await executor.execute()\n }\n // console.timeEnd(\"executing subject executors...\");\n\n // commit transaction if it was started by us\n // console.time(\"commit\");\n if (isTransactionStartedByUs === true)\n await queryRunner.commitTransaction()\n // console.timeEnd(\"commit\");\n } catch (error) {\n // rollback transaction if it was started by us\n if (isTransactionStartedByUs) {\n try {\n await queryRunner.rollbackTransaction()\n } catch (rollbackError) {}\n }\n throw error\n }\n } finally {\n queryRunner.data = oldQueryRunnerData\n\n // release query runner only if its created by us\n if (!this.queryRunner) await queryRunner.release()\n }\n }\n}\n"],"sourceRoot":".."}
1
+ {"version":3,"sources":["../browser/src/persistence/EntityPersistExecutor.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,iBAAiB,EAAE,MAAM,4BAA4B,CAAA;AAC9D,OAAO,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAA;AACnD,OAAO,EAAE,0BAA0B,EAAE,MAAM,qCAAqC,CAAA;AAGhF,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAA;AACnC,OAAO,EAAE,uBAAuB,EAAE,MAAM,2CAA2C,CAAA;AACnF,OAAO,EAAE,iCAAiC,EAAE,MAAM,qDAAqD,CAAA;AACvG,OAAO,EAAE,wBAAwB,EAAE,MAAM,4CAA4C,CAAA;AACrF,OAAO,EAAE,2BAA2B,EAAE,MAAM,+BAA+B,CAAA;AAC3E,OAAO,EAAE,sBAAsB,EAAE,MAAM,0CAA0C,CAAA;AACjF,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAA;AAE3C;;GAEG;AACH,MAAM,OAAO,qBAAqB;IAC9B,4EAA4E;IAC5E,cAAc;IACd,4EAA4E;IAE5E,YACc,UAAsB,EACtB,WAAoC,EACpC,IAAmD,EACnD,MAAqC,EACrC,MAAuC,EACvC,OAAqC;QALrC,eAAU,GAA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;qBAC1C;oBAAC,OAAO,aAAa,EAAE,GAAE;iBAC7B;gBACD,MAAM,KAAK,CAAA;aACd;SACJ;gBAAS;YACN,WAAW,CAAC,IAAI,GAAG,kBAAkB,CAAA;YAErC,iDAAiD;YACjD,IAAI,CAAC,IAAI,CAAC,WAAW;gBAAE,MAAM,WAAW,CAAC,OAAO,EAAE,CAAA;SACrD;IACL,CAAC;CACJ","file":"EntityPersistExecutor.js","sourcesContent":["import { ObjectLiteral } from \"../common/ObjectLiteral\"\nimport { SaveOptions } from \"../repository/SaveOptions\"\nimport { RemoveOptions } from \"../repository/RemoveOptions\"\nimport { MustBeEntityError } from \"../error/MustBeEntityError\"\nimport { SubjectExecutor } from \"./SubjectExecutor\"\nimport { CannotDetermineEntityError } from \"../error/CannotDetermineEntityError\"\nimport { QueryRunner } from \"../query-runner/QueryRunner\"\nimport { DataSource } from \"../data-source/DataSource\"\nimport { Subject } from \"./Subject\"\nimport { OneToManySubjectBuilder } from \"./subject-builder/OneToManySubjectBuilder\"\nimport { OneToOneInverseSideSubjectBuilder } from \"./subject-builder/OneToOneInverseSideSubjectBuilder\"\nimport { ManyToManySubjectBuilder } from \"./subject-builder/ManyToManySubjectBuilder\"\nimport { SubjectDatabaseEntityLoader } from \"./SubjectDatabaseEntityLoader\"\nimport { CascadesSubjectBuilder } from \"./subject-builder/CascadesSubjectBuilder\"\nimport { OrmUtils } from \"../util/OrmUtils\"\n\n/**\n * Persists a single entity or multiple entities - saves or removes them.\n */\nexport class EntityPersistExecutor {\n // -------------------------------------------------------------------------\n // Constructor\n // -------------------------------------------------------------------------\n\n constructor(\n protected connection: DataSource,\n protected queryRunner: QueryRunner | undefined,\n protected mode: \"save\" | \"remove\" | \"soft-remove\" | \"recover\",\n protected target: Function | string | undefined,\n protected entity: ObjectLiteral | ObjectLiteral[],\n protected options?: SaveOptions & RemoveOptions,\n ) {}\n\n // -------------------------------------------------------------------------\n // Public Methods\n // -------------------------------------------------------------------------\n\n /**\n * Executes persistence operation ob given entity or entities.\n */\n async execute(): Promise<void> {\n // check if entity we are going to save is valid and is an object\n if (!this.entity || typeof this.entity !== \"object\")\n return Promise.reject(new MustBeEntityError(this.mode, this.entity))\n\n // we MUST call \"fake\" resolve here to make sure all properties of lazily loaded relations are resolved\n await Promise.resolve()\n\n // if query runner is already defined in this class, it means this entity manager was already created for a single connection\n // if its not defined we create a new query runner - single connection where we'll execute all our operations\n const queryRunner =\n this.queryRunner || this.connection.createQueryRunner()\n\n // save data in the query runner - this is useful functionality to share data from outside of the world\n // with third classes - like subscribers and listener methods\n let oldQueryRunnerData = queryRunner.data\n if (this.options && this.options.data) {\n queryRunner.data = this.options.data\n }\n\n try {\n // collect all operate subjects\n const entities: ObjectLiteral[] = Array.isArray(this.entity)\n ? this.entity\n : [this.entity]\n const entitiesInChunks =\n this.options && this.options.chunk && this.options.chunk > 0\n ? OrmUtils.chunk(entities, this.options.chunk)\n : [entities]\n\n // console.time(\"building subject executors...\");\n const executors = await Promise.all(\n entitiesInChunks.map(async (entities) => {\n const subjects: Subject[] = []\n\n // create subjects for all entities we received for the persistence\n entities.forEach((entity) => {\n const entityTarget = this.target\n ? this.target\n : entity.constructor\n if (entityTarget === Object)\n throw new CannotDetermineEntityError(this.mode)\n\n let metadata = this.connection.getMetadata(entityTarget)\n\n // Check for single table inheritance and find the correct metadata in that case.\n // Goal is to use the correct discriminator as we could have a repository\n // for an (abstract) base class and thus the target would not match.\n if (\n metadata.inheritancePattern === \"STI\" &&\n metadata.childEntityMetadatas.length > 0\n ) {\n const matchingChildMetadata =\n metadata.childEntityMetadatas.find(\n (meta) =>\n entity.constructor === meta.target,\n )\n if (matchingChildMetadata) {\n metadata = matchingChildMetadata\n }\n }\n\n subjects.push(\n new Subject({\n metadata,\n entity: entity,\n canBeInserted: this.mode === \"save\",\n canBeUpdated: this.mode === \"save\",\n mustBeRemoved: this.mode === \"remove\",\n canBeSoftRemoved: this.mode === \"soft-remove\",\n canBeRecovered: this.mode === \"recover\",\n }),\n )\n })\n\n // console.time(\"building cascades...\");\n // go through each entity with metadata and create subjects and subjects by cascades for them\n const cascadesSubjectBuilder = new CascadesSubjectBuilder(\n subjects,\n )\n subjects.forEach((subject) => {\n // next step we build list of subjects we will operate with\n // these subjects are subjects that we need to insert or update alongside with main persisted entity\n cascadesSubjectBuilder.build(subject, this.mode)\n })\n // console.timeEnd(\"building cascades...\");\n\n // load database entities for all subjects we have\n // next step is to load database entities for all operate subjects\n // console.time(\"loading...\");\n await new SubjectDatabaseEntityLoader(\n queryRunner,\n subjects,\n ).load(this.mode)\n // console.timeEnd(\"loading...\");\n\n // console.time(\"other subjects...\");\n // build all related subjects and change maps\n if (\n this.mode === \"save\" ||\n this.mode === \"soft-remove\" ||\n this.mode === \"recover\"\n ) {\n new OneToManySubjectBuilder(subjects).build()\n new OneToOneInverseSideSubjectBuilder(subjects).build()\n new ManyToManySubjectBuilder(subjects).build()\n } else {\n subjects.forEach((subject) => {\n if (subject.mustBeRemoved) {\n new ManyToManySubjectBuilder(\n subjects,\n ).buildForAllRemoval(subject)\n }\n })\n }\n // console.timeEnd(\"other subjects...\");\n // console.timeEnd(\"building subjects...\");\n // console.log(\"subjects\", subjects);\n\n // create a subject executor\n return new SubjectExecutor(\n queryRunner,\n subjects,\n this.options,\n )\n }),\n )\n // console.timeEnd(\"building subject executors...\");\n\n // make sure we have at least one executable operation before we create a transaction and proceed\n // if we don't have operations it means we don't really need to update or remove something\n const executorsWithExecutableOperations = executors.filter(\n (executor) => executor.hasExecutableOperations,\n )\n if (executorsWithExecutableOperations.length === 0) return\n\n // start execute queries in a transaction\n // if transaction is already opened in this query runner then we don't touch it\n // if its not opened yet then we open it here, and once we finish - we close it\n let isTransactionStartedByUs = false\n try {\n // open transaction if its not opened yet\n if (!queryRunner.isTransactionActive) {\n if (\n this.connection.driver.transactionSupport !== \"none\" &&\n (!this.options || this.options.transaction !== false)\n ) {\n // start transaction until it was not explicitly disabled\n isTransactionStartedByUs = true\n await queryRunner.startTransaction()\n }\n }\n\n // execute all persistence operations for all entities we have\n // console.time(\"executing subject executors...\");\n for (const executor of executorsWithExecutableOperations) {\n await executor.execute()\n }\n // console.timeEnd(\"executing subject executors...\");\n\n // commit transaction if it was started by us\n // console.time(\"commit\");\n if (isTransactionStartedByUs === true)\n await queryRunner.commitTransaction()\n // console.timeEnd(\"commit\");\n } catch (error) {\n // rollback transaction if it was started by us\n if (isTransactionStartedByUs) {\n try {\n await queryRunner.rollbackTransaction()\n } catch (rollbackError) {}\n }\n throw error\n }\n } finally {\n queryRunner.data = oldQueryRunnerData\n\n // release query runner only if its created by us\n if (!this.queryRunner) await queryRunner.release()\n }\n }\n}\n"],"sourceRoot":".."}
@@ -1,3 +1,10 @@
1
1
  export declare type InsertOrUpdateOptions = {
2
+ /**
3
+ * If true, postgres will skip the update if no values would be changed (reduces writes)
4
+ */
2
5
  skipUpdateIfNoValuesChanged?: boolean;
6
+ /**
7
+ * If included, postgres will apply the index predicate to a conflict target (partial index)
8
+ */
9
+ indexPredicate?: string;
3
10
  };
@@ -1 +1 @@
1
- {"version":3,"sources":["../browser/src/query-builder/InsertOrUpdateOptions.ts"],"names":[],"mappings":"","file":"InsertOrUpdateOptions.js","sourcesContent":["export type InsertOrUpdateOptions = {\n skipUpdateIfNoValuesChanged?: boolean\n}\n"],"sourceRoot":".."}
1
+ {"version":3,"sources":["../browser/src/query-builder/InsertOrUpdateOptions.ts"],"names":[],"mappings":"","file":"InsertOrUpdateOptions.js","sourcesContent":["export type InsertOrUpdateOptions = {\n /**\n * If true, postgres will skip the update if no values would be changed (reduces writes)\n */\n skipUpdateIfNoValuesChanged?: boolean\n /**\n * If included, postgres will apply the index predicate to a conflict target (partial index)\n */\n indexPredicate?: string\n}\n"],"sourceRoot":".."}
@@ -228,6 +228,7 @@ export class InsertQueryBuilder extends QueryBuilder {
228
228
  overwrite: statementOrOverwrite,
229
229
  conflict: conflictTarget,
230
230
  skipUpdateIfNoValuesChanged: orUpdateOptions === null || orUpdateOptions === void 0 ? void 0 : orUpdateOptions.skipUpdateIfNoValuesChanged,
231
+ indexPredicate: orUpdateOptions === null || orUpdateOptions === void 0 ? void 0 : orUpdateOptions.indexPredicate,
231
232
  };
232
233
  return this;
233
234
  }
@@ -300,12 +301,20 @@ export class InsertQueryBuilder extends QueryBuilder {
300
301
  query += ` ON CONFLICT ${this.expressionMap.onConflict} `;
301
302
  }
302
303
  else if (this.expressionMap.onUpdate) {
303
- const { overwrite, columns, conflict, skipUpdateIfNoValuesChanged, } = this.expressionMap.onUpdate;
304
+ const { overwrite, columns, conflict, skipUpdateIfNoValuesChanged, indexPredicate, } = this.expressionMap.onUpdate;
304
305
  let conflictTarget = "ON CONFLICT";
305
306
  if (Array.isArray(conflict)) {
306
307
  conflictTarget += ` ( ${conflict
307
308
  .map((column) => this.escape(column))
308
309
  .join(", ")} )`;
310
+ if (indexPredicate &&
311
+ !DriverUtils.isPostgresFamily(this.connection.driver)) {
312
+ throw new TypeORMError(`indexPredicate option is not supported by the current database driver`);
313
+ }
314
+ if (indexPredicate &&
315
+ DriverUtils.isPostgresFamily(this.connection.driver)) {
316
+ conflictTarget += ` WHERE ( ${this.escape(indexPredicate)} )`;
317
+ }
309
318
  }
310
319
  else if (conflict) {
311
320
  conflictTarget += ` ON CONSTRAINT ${this.escape(conflict)}`;