typeorm 0.2.39-dev.2c861af → 0.2.39-dev.6558295

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 (63) hide show
  1. package/browser/driver/cockroachdb/CockroachDriver.js +23 -14
  2. package/browser/driver/cockroachdb/CockroachDriver.js.map +1 -1
  3. package/browser/driver/cockroachdb/CockroachQueryRunner.js +63 -69
  4. package/browser/driver/cockroachdb/CockroachQueryRunner.js.map +1 -1
  5. package/browser/driver/cordova/CordovaDriver.d.ts +1 -1
  6. package/browser/driver/cordova/CordovaDriver.js +25 -18
  7. package/browser/driver/cordova/CordovaDriver.js.map +1 -1
  8. package/browser/driver/cordova/CordovaQueryRunner.js +50 -43
  9. package/browser/driver/cordova/CordovaQueryRunner.js.map +1 -1
  10. package/browser/driver/postgres/PostgresDriver.d.ts +2 -2
  11. package/browser/driver/postgres/PostgresDriver.js +31 -40
  12. package/browser/driver/postgres/PostgresDriver.js.map +1 -1
  13. package/browser/driver/postgres/PostgresQueryRunner.js +7 -15
  14. package/browser/driver/postgres/PostgresQueryRunner.js.map +1 -1
  15. package/browser/driver/sap/SapQueryRunner.js +10 -28
  16. package/browser/driver/sap/SapQueryRunner.js.map +1 -1
  17. package/browser/driver/sqljs/SqljsDriver.js +5 -22
  18. package/browser/driver/sqljs/SqljsDriver.js.map +1 -1
  19. package/browser/driver/sqljs/SqljsQueryRunner.js +9 -10
  20. package/browser/driver/sqljs/SqljsQueryRunner.js.map +1 -1
  21. package/browser/migration/MigrationExecutor.d.ts +1 -1
  22. package/browser/migration/MigrationExecutor.js +6 -14
  23. package/browser/migration/MigrationExecutor.js.map +1 -1
  24. package/browser/persistence/SubjectExecutor.js +3 -3
  25. package/browser/persistence/SubjectExecutor.js.map +1 -1
  26. package/browser/persistence/subject-builder/OneToManySubjectBuilder.js +10 -4
  27. package/browser/persistence/subject-builder/OneToManySubjectBuilder.js.map +1 -1
  28. package/browser/query-builder/transformer/RawSqlResultsToEntityTransformer.js +2 -8
  29. package/browser/query-builder/transformer/RawSqlResultsToEntityTransformer.js.map +1 -1
  30. package/browser/query-runner/BaseQueryRunner.js +3 -2
  31. package/browser/query-runner/BaseQueryRunner.js.map +1 -1
  32. package/driver/cockroachdb/CockroachDriver.js +23 -14
  33. package/driver/cockroachdb/CockroachDriver.js.map +1 -1
  34. package/driver/cockroachdb/CockroachQueryRunner.js +63 -69
  35. package/driver/cockroachdb/CockroachQueryRunner.js.map +1 -1
  36. package/driver/cordova/CordovaDriver.d.ts +1 -1
  37. package/driver/cordova/CordovaDriver.js +25 -18
  38. package/driver/cordova/CordovaDriver.js.map +1 -1
  39. package/driver/cordova/CordovaQueryRunner.js +50 -43
  40. package/driver/cordova/CordovaQueryRunner.js.map +1 -1
  41. package/driver/postgres/PostgresDriver.d.ts +2 -2
  42. package/driver/postgres/PostgresDriver.js +31 -40
  43. package/driver/postgres/PostgresDriver.js.map +1 -1
  44. package/driver/postgres/PostgresQueryRunner.js +7 -15
  45. package/driver/postgres/PostgresQueryRunner.js.map +1 -1
  46. package/driver/sap/SapQueryRunner.js +10 -28
  47. package/driver/sap/SapQueryRunner.js.map +1 -1
  48. package/driver/sqljs/SqljsDriver.js +5 -22
  49. package/driver/sqljs/SqljsDriver.js.map +1 -1
  50. package/driver/sqljs/SqljsQueryRunner.js +9 -10
  51. package/driver/sqljs/SqljsQueryRunner.js.map +1 -1
  52. package/migration/MigrationExecutor.d.ts +1 -1
  53. package/migration/MigrationExecutor.js +6 -14
  54. package/migration/MigrationExecutor.js.map +1 -1
  55. package/package.json +1 -1
  56. package/persistence/SubjectExecutor.js +3 -3
  57. package/persistence/SubjectExecutor.js.map +1 -1
  58. package/persistence/subject-builder/OneToManySubjectBuilder.js +10 -4
  59. package/persistence/subject-builder/OneToManySubjectBuilder.js.map +1 -1
  60. package/query-builder/transformer/RawSqlResultsToEntityTransformer.js +2 -8
  61. package/query-builder/transformer/RawSqlResultsToEntityTransformer.js.map +1 -1
  62. package/query-runner/BaseQueryRunner.js +3 -2
  63. package/query-runner/BaseQueryRunner.js.map +1 -1
@@ -48,18 +48,10 @@ var SqljsDriver = /** @class */ (function (_super) {
48
48
  */
49
49
  SqljsDriver.prototype.disconnect = function () {
50
50
  return __awaiter(this, void 0, void 0, function () {
51
- var _this = this;
52
51
  return __generator(this, function (_a) {
53
- return [2 /*return*/, new Promise(function (ok, fail) {
54
- try {
55
- _this.queryRunner = undefined;
56
- _this.databaseConnection.close();
57
- ok();
58
- }
59
- catch (e) {
60
- fail(e);
61
- }
62
- })];
52
+ this.queryRunner = undefined;
53
+ this.databaseConnection.close();
54
+ return [2 /*return*/];
63
55
  });
64
56
  });
65
57
  };
@@ -262,7 +254,6 @@ var SqljsDriver = /** @class */ (function (_super) {
262
254
  SqljsDriver.prototype.createDatabaseConnectionWithImport = function (database) {
263
255
  return __awaiter(this, void 0, void 0, function () {
264
256
  var isLegacyVersion, sqlite, _a;
265
- var _this = this;
266
257
  return __generator(this, function (_b) {
267
258
  switch (_b.label) {
268
259
  case 0:
@@ -282,16 +273,8 @@ var SqljsDriver = /** @class */ (function (_super) {
282
273
  else {
283
274
  this.databaseConnection = new sqlite.Database();
284
275
  }
285
- // Enable foreign keys for database
286
- return [2 /*return*/, new Promise(function (ok, fail) {
287
- try {
288
- _this.databaseConnection.exec("PRAGMA foreign_keys = ON;");
289
- ok(_this.databaseConnection);
290
- }
291
- catch (e) {
292
- fail(e);
293
- }
294
- })];
276
+ this.databaseConnection.exec("PRAGMA foreign_keys = ON;");
277
+ return [2 /*return*/, this.databaseConnection];
295
278
  }
296
279
  });
297
280
  });
@@ -1 +1 @@
1
- {"version":3,"sources":["../browser/src/driver/sqljs/SqljsDriver.ts"],"names":[],"mappings":";AAAA,OAAO,EAAC,oBAAoB,EAAC,MAAM,yCAAyC,CAAC;AAE7E,OAAO,EAAC,gBAAgB,EAAC,MAAM,oBAAoB,CAAC;AAGpD,OAAO,EAAC,8BAA8B,EAAC,MAAM,4CAA4C,CAAC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AA2C,CAAA;;;wBAApF,MAAM,KAA8E;wBAC1F,IAAI,QAAQ,IAAI,QAAQ,CAAC,MAAM,GAAG,CAAC,EAAE;4BACjC,IAAI,CAAC,kBAAkB,GAAG,IAAI,MAAM,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC;yBAC3D;6BACI;4BACD,IAAI,CAAC,kBAAkB,GAAG,IAAI,MAAM,CAAC,QAAQ,EAAE,CAAC;yBACnD;wBAED,mCAAmC;wBACnC,sBAAO,IAAI,OAAO,CAAM,UAAC,EAAE,EAAE,IAAI;gCAC7B,IAAI;oCACA,KAAI,CAAC,kBAAkB,CAAC,IAAI,CAAC,2BAA2B,CAAC,CAAC;oCAC1D,EAAE,CAAC,KAAI,CAAC,kBAAkB,CAAC,CAAC;iCAC/B;gCACD,OAAO,CAAC,EAAE;oCACN,IAAI,CAAC,CAAC,CAAC,CAAC;iCACX;4BACL,CAAC,CAAC,EAAC;;;;KACN;IAED;;OAEG;IACO,sCAAgB,GAA1B;QACI,IAAI,aAAa,CAAC,IAAI,KAAK,SAAS,EAAE;YAClC,IAAM,MAAM,GAAG,IAAI,CAAC,OAAO,CAAC,MAAM,IAAI,MAAM,CAAC,GAAG,CAAC;YACjD,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;SACxB;aACI;YACD,IAAI;gBACA,IAAM,MAAM,GAAG,IAAI,CAAC,OAAO,CAAC,MAAM,IAAI,aAAa,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;gBACnE,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;aAExB;YAAC,OAAO,CAAC,EAAE;gBACR,MAAM,IAAI,8BAA8B,CAAC,QAAQ,EAAE,QAAQ,CAAC,CAAC;aAChE;SACJ;IACL,CAAC;IACL,kBAAC;AAAD,CA7QA,AA6QC,CA7QgC,oBAAoB,GA6QpD","file":"SqljsDriver.js","sourcesContent":["import {AbstractSqliteDriver} from \"../sqlite-abstract/AbstractSqliteDriver\";\nimport {SqljsConnectionOptions} from \"./SqljsConnectionOptions\";\nimport {SqljsQueryRunner} from \"./SqljsQueryRunner\";\nimport {QueryRunner} from \"../../query-runner/QueryRunner\";\nimport {Connection} from \"../../connection/Connection\";\nimport {DriverPackageNotInstalledError} from \"../../error/DriverPackageNotInstalledError\";\nimport {DriverOptionNotSetError} from \"../../error/DriverOptionNotSetError\";\nimport {PlatformTools} from \"../../platform/PlatformTools\";\nimport {EntityMetadata} from \"../../metadata/EntityMetadata\";\nimport {OrmUtils} from \"../../util/OrmUtils\";\nimport {ObjectLiteral} from \"../../common/ObjectLiteral\";\nimport {ReplicationMode} from \"../types/ReplicationMode\";\nimport { TypeORMError } from \"../../error\";\n\n// This is needed to satisfy the typescript compiler.\ninterface Window {\n SQL: any;\n localforage: any;\n}\ndeclare let window: Window;\n\nexport class SqljsDriver extends AbstractSqliteDriver {\n // The driver specific options.\n options: SqljsConnectionOptions;\n\n // -------------------------------------------------------------------------\n // Constructor\n // -------------------------------------------------------------------------\n\n constructor(connection: Connection) {\n super(connection);\n\n // If autoSave is enabled by user, location or autoSaveCallback have to be set\n // because either autoSave saves to location or calls autoSaveCallback.\n if (this.options.autoSave && !this.options.location && !this.options.autoSaveCallback) {\n throw new DriverOptionNotSetError(`location or autoSaveCallback`);\n }\n\n // load sql.js package\n this.loadDependencies();\n }\n\n\n // -------------------------------------------------------------------------\n // Public Methods\n // -------------------------------------------------------------------------\n\n /**\n * Performs connection to the database.\n */\n async connect(): Promise<void> {\n this.databaseConnection = await this.createDatabaseConnection();\n }\n\n /**\n * Closes connection with database.\n */\n async disconnect(): Promise<void> {\n return new Promise<void>((ok, fail) => {\n try {\n this.queryRunner = undefined;\n this.databaseConnection.close();\n ok();\n }\n catch (e) {\n fail(e);\n }\n });\n }\n\n /**\n * Creates a query runner used to execute database queries.\n */\n createQueryRunner(mode: ReplicationMode): QueryRunner {\n if (!this.queryRunner)\n this.queryRunner = new SqljsQueryRunner(this);\n\n return this.queryRunner;\n }\n\n /**\n * Loads a database from a given file (Node.js), local storage key (browser) or array.\n * This will delete the current database!\n */\n async load(fileNameOrLocalStorageOrData: string | Uint8Array, checkIfFileOrLocalStorageExists: boolean = true): Promise<any> {\n if (typeof fileNameOrLocalStorageOrData === \"string\") {\n // content has to be loaded\n if (PlatformTools.type === \"node\") {\n // Node.js\n // fileNameOrLocalStorageOrData should be a path to the file\n if (PlatformTools.fileExist(fileNameOrLocalStorageOrData)) {\n const database = PlatformTools.readFileSync(fileNameOrLocalStorageOrData);\n return this.createDatabaseConnectionWithImport(database);\n }\n else if (checkIfFileOrLocalStorageExists) {\n throw new TypeORMError(`File ${fileNameOrLocalStorageOrData} does not exist`);\n }\n else {\n // File doesn't exist and checkIfFileOrLocalStorageExists is set to false.\n // Therefore open a database without importing an existing file.\n // File will be written on first write operation.\n return this.createDatabaseConnectionWithImport();\n }\n }\n else {\n // browser\n // fileNameOrLocalStorageOrData should be a local storage / indexedDB key\n let localStorageContent = null;\n if (this.options.useLocalForage) {\n if (window.localforage) {\n localStorageContent = await window.localforage.getItem(fileNameOrLocalStorageOrData);\n } else {\n throw new TypeORMError(`localforage is not defined - please import localforage.js into your site`);\n }\n } else {\n localStorageContent = PlatformTools.getGlobalVariable().localStorage.getItem(fileNameOrLocalStorageOrData);\n }\n\n if (localStorageContent != null) {\n // localStorage value exists.\n return this.createDatabaseConnectionWithImport(JSON.parse(localStorageContent));\n }\n else if (checkIfFileOrLocalStorageExists) {\n throw new TypeORMError(`File ${fileNameOrLocalStorageOrData} does not exist`);\n }\n else {\n // localStorage value doesn't exist and checkIfFileOrLocalStorageExists is set to false.\n // Therefore open a database without importing anything.\n // localStorage value will be written on first write operation.\n return this.createDatabaseConnectionWithImport();\n }\n }\n }\n else {\n return this.createDatabaseConnectionWithImport(fileNameOrLocalStorageOrData);\n }\n }\n\n /**\n * Saved the current database to the given file (Node.js), local storage key (browser) or\n * indexedDB key (browser with enabled useLocalForage option).\n * If no location path is given, the location path in the options (if specified) will be used.\n */\n async save(location?: string) {\n if (!location && !this.options.location) {\n throw new TypeORMError(`No location is set, specify a location parameter or add the location option to your configuration`);\n }\n\n let path = \"\";\n if (location) {\n path = location;\n }\n else if (this.options.location) {\n path = this.options.location;\n }\n\n if (PlatformTools.type === \"node\") {\n try {\n const content = Buffer.from(this.databaseConnection.export());\n await PlatformTools.writeFile(path, content);\n }\n catch (e) {\n throw new TypeORMError(`Could not save database, error: ${e}`);\n }\n }\n else {\n const database: Uint8Array = this.databaseConnection.export();\n // convert Uint8Array to number array to improve local-storage storage\n const databaseArray = [].slice.call(database);\n if (this.options.useLocalForage) {\n if (window.localforage) {\n await window.localforage.setItem(path, JSON.stringify(databaseArray));\n } else {\n throw new TypeORMError(`localforage is not defined - please import localforage.js into your site`);\n }\n } else {\n PlatformTools.getGlobalVariable().localStorage.setItem(path, JSON.stringify(databaseArray));\n }\n }\n }\n\n /**\n * This gets called by the QueryRunner when a change to the database is made.\n * If a custom autoSaveCallback is specified, it get's called with the database as Uint8Array,\n * otherwise the save method is called which saves it to file (Node.js), local storage (browser)\n * or indexedDB (browser with enabled useLocalForage option).\n */\n async autoSave() {\n if (this.options.autoSave) {\n if (this.options.autoSaveCallback) {\n await this.options.autoSaveCallback(this.export());\n }\n else {\n await this.save();\n }\n }\n }\n\n /**\n * Returns the current database as Uint8Array.\n */\n export(): Uint8Array {\n return this.databaseConnection.export();\n }\n\n /**\n * Creates generated map of values generated or returned by database after INSERT query.\n */\n createGeneratedMap(metadata: EntityMetadata, insertResult: any) {\n const generatedMap = metadata.generatedColumns.reduce((map, generatedColumn) => {\n // seems to be the only way to get the inserted id, see https://github.com/kripken/sql.js/issues/77\n if (generatedColumn.isPrimary && generatedColumn.generationStrategy === \"increment\") {\n const query = \"SELECT last_insert_rowid()\";\n try {\n let result = this.databaseConnection.exec(query);\n this.connection.logger.logQuery(query);\n return OrmUtils.mergeDeep(map, generatedColumn.createValueMap(result[0].values[0][0]));\n }\n catch (e) {\n this.connection.logger.logQueryError(e, query, []);\n }\n }\n\n return map;\n }, {} as ObjectLiteral);\n\n return Object.keys(generatedMap).length > 0 ? generatedMap : undefined;\n }\n\n // -------------------------------------------------------------------------\n // Protected Methods\n // -------------------------------------------------------------------------\n\n /**\n * Creates connection with the database.\n * If the location option is set, the database is loaded first.\n */\n protected createDatabaseConnection(): Promise<any> {\n if (this.options.location) {\n return this.load(this.options.location, false);\n }\n\n return this.createDatabaseConnectionWithImport(this.options.database);\n }\n\n /**\n * Creates connection with an optional database.\n * If database is specified it is loaded, otherwise a new empty database is created.\n */\n protected async createDatabaseConnectionWithImport(database?: Uint8Array): Promise<any> {\n // sql.js < 1.0 exposes an object with a `Database` method.\n const isLegacyVersion = typeof this.sqlite.Database === \"function\";\n const sqlite = isLegacyVersion ? this.sqlite : await this.sqlite(this.options.sqlJsConfig);\n if (database && database.length > 0) {\n this.databaseConnection = new sqlite.Database(database);\n }\n else {\n this.databaseConnection = new sqlite.Database();\n }\n\n // Enable foreign keys for database\n return new Promise<any>((ok, fail) => {\n try {\n this.databaseConnection.exec(`PRAGMA foreign_keys = ON;`);\n ok(this.databaseConnection);\n }\n catch (e) {\n fail(e);\n }\n });\n }\n\n /**\n * If driver dependency is not given explicitly, then try to load it via \"require\".\n */\n protected loadDependencies(): void {\n if (PlatformTools.type === \"browser\") {\n const sqlite = this.options.driver || window.SQL;\n this.sqlite = sqlite;\n }\n else {\n try {\n const sqlite = this.options.driver || PlatformTools.load(\"sql.js\");\n this.sqlite = sqlite;\n\n } catch (e) {\n throw new DriverPackageNotInstalledError(\"sql.js\", \"sql.js\");\n }\n }\n }\n}\n"],"sourceRoot":"../.."}
1
+ {"version":3,"sources":["../browser/src/driver/sqljs/SqljsDriver.ts"],"names":[],"mappings":";AAAA,OAAO,EAAC,oBAAoB,EAAC,MAAM,yCAAyC,CAAC;AAE7E,OAAO,EAAC,gBAAgB,EAAC,MAAM,oBAAoB,CAAC;AAGpD,OAAO,EAAC,8BAA8B,EAAC,MAAM,4CAA4C,CAAC;AAC1F,OAAO,EAAC,uBAAuB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AAkB,GAAG,IAAI,MAAM,CAAC,QAAQ,EAAE,CAAC;yBACnD;wBAED,IAAI,CAAC,kBAAkB,CAAC,IAAI,CAAC,2BAA2B,CAAC,CAAC;wBAE1D,sBAAO,IAAI,CAAC,kBAAkB,EAAC;;;;KAClC;IAED;;OAEG;IACO,sCAAgB,GAA1B;QACI,IAAI,aAAa,CAAC,IAAI,KAAK,SAAS,EAAE;YAClC,IAAM,MAAM,GAAG,IAAI,CAAC,OAAO,CAAC,MAAM,IAAI,MAAM,CAAC,GAAG,CAAC;YACjD,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;SACxB;aACI;YACD,IAAI;gBACA,IAAM,MAAM,GAAG,IAAI,CAAC,OAAO,CAAC,MAAM,IAAI,aAAa,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;gBACnE,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;aAExB;YAAC,OAAO,CAAC,EAAE;gBACR,MAAM,IAAI,8BAA8B,CAAC,QAAQ,EAAE,QAAQ,CAAC,CAAC;aAChE;SACJ;IACL,CAAC;IACL,kBAAC;AAAD,CA9PA,AA8PC,CA9PgC,oBAAoB,GA8PpD","file":"SqljsDriver.js","sourcesContent":["import {AbstractSqliteDriver} from \"../sqlite-abstract/AbstractSqliteDriver\";\nimport {SqljsConnectionOptions} from \"./SqljsConnectionOptions\";\nimport {SqljsQueryRunner} from \"./SqljsQueryRunner\";\nimport {QueryRunner} from \"../../query-runner/QueryRunner\";\nimport {Connection} from \"../../connection/Connection\";\nimport {DriverPackageNotInstalledError} from \"../../error/DriverPackageNotInstalledError\";\nimport {DriverOptionNotSetError} from \"../../error/DriverOptionNotSetError\";\nimport {PlatformTools} from \"../../platform/PlatformTools\";\nimport {EntityMetadata} from \"../../metadata/EntityMetadata\";\nimport {OrmUtils} from \"../../util/OrmUtils\";\nimport {ObjectLiteral} from \"../../common/ObjectLiteral\";\nimport {ReplicationMode} from \"../types/ReplicationMode\";\nimport { TypeORMError } from \"../../error\";\n\n// This is needed to satisfy the typescript compiler.\ninterface Window {\n SQL: any;\n localforage: any;\n}\ndeclare let window: Window;\n\nexport class SqljsDriver extends AbstractSqliteDriver {\n // The driver specific options.\n options: SqljsConnectionOptions;\n\n // -------------------------------------------------------------------------\n // Constructor\n // -------------------------------------------------------------------------\n\n constructor(connection: Connection) {\n super(connection);\n\n // If autoSave is enabled by user, location or autoSaveCallback have to be set\n // because either autoSave saves to location or calls autoSaveCallback.\n if (this.options.autoSave && !this.options.location && !this.options.autoSaveCallback) {\n throw new DriverOptionNotSetError(`location or autoSaveCallback`);\n }\n\n // load sql.js package\n this.loadDependencies();\n }\n\n\n // -------------------------------------------------------------------------\n // Public Methods\n // -------------------------------------------------------------------------\n\n /**\n * Performs connection to the database.\n */\n async connect(): Promise<void> {\n this.databaseConnection = await this.createDatabaseConnection();\n }\n\n /**\n * Closes connection with database.\n */\n async disconnect(): Promise<void> {\n this.queryRunner = undefined;\n this.databaseConnection.close();\n }\n\n /**\n * Creates a query runner used to execute database queries.\n */\n createQueryRunner(mode: ReplicationMode): QueryRunner {\n if (!this.queryRunner)\n this.queryRunner = new SqljsQueryRunner(this);\n\n return this.queryRunner;\n }\n\n /**\n * Loads a database from a given file (Node.js), local storage key (browser) or array.\n * This will delete the current database!\n */\n async load(fileNameOrLocalStorageOrData: string | Uint8Array, checkIfFileOrLocalStorageExists: boolean = true): Promise<any> {\n if (typeof fileNameOrLocalStorageOrData === \"string\") {\n // content has to be loaded\n if (PlatformTools.type === \"node\") {\n // Node.js\n // fileNameOrLocalStorageOrData should be a path to the file\n if (PlatformTools.fileExist(fileNameOrLocalStorageOrData)) {\n const database = PlatformTools.readFileSync(fileNameOrLocalStorageOrData);\n return this.createDatabaseConnectionWithImport(database);\n }\n else if (checkIfFileOrLocalStorageExists) {\n throw new TypeORMError(`File ${fileNameOrLocalStorageOrData} does not exist`);\n }\n else {\n // File doesn't exist and checkIfFileOrLocalStorageExists is set to false.\n // Therefore open a database without importing an existing file.\n // File will be written on first write operation.\n return this.createDatabaseConnectionWithImport();\n }\n }\n else {\n // browser\n // fileNameOrLocalStorageOrData should be a local storage / indexedDB key\n let localStorageContent = null;\n if (this.options.useLocalForage) {\n if (window.localforage) {\n localStorageContent = await window.localforage.getItem(fileNameOrLocalStorageOrData);\n } else {\n throw new TypeORMError(`localforage is not defined - please import localforage.js into your site`);\n }\n } else {\n localStorageContent = PlatformTools.getGlobalVariable().localStorage.getItem(fileNameOrLocalStorageOrData);\n }\n\n if (localStorageContent != null) {\n // localStorage value exists.\n return this.createDatabaseConnectionWithImport(JSON.parse(localStorageContent));\n }\n else if (checkIfFileOrLocalStorageExists) {\n throw new TypeORMError(`File ${fileNameOrLocalStorageOrData} does not exist`);\n }\n else {\n // localStorage value doesn't exist and checkIfFileOrLocalStorageExists is set to false.\n // Therefore open a database without importing anything.\n // localStorage value will be written on first write operation.\n return this.createDatabaseConnectionWithImport();\n }\n }\n }\n else {\n return this.createDatabaseConnectionWithImport(fileNameOrLocalStorageOrData);\n }\n }\n\n /**\n * Saved the current database to the given file (Node.js), local storage key (browser) or\n * indexedDB key (browser with enabled useLocalForage option).\n * If no location path is given, the location path in the options (if specified) will be used.\n */\n async save(location?: string) {\n if (!location && !this.options.location) {\n throw new TypeORMError(`No location is set, specify a location parameter or add the location option to your configuration`);\n }\n\n let path = \"\";\n if (location) {\n path = location;\n }\n else if (this.options.location) {\n path = this.options.location;\n }\n\n if (PlatformTools.type === \"node\") {\n try {\n const content = Buffer.from(this.databaseConnection.export());\n await PlatformTools.writeFile(path, content);\n }\n catch (e) {\n throw new TypeORMError(`Could not save database, error: ${e}`);\n }\n }\n else {\n const database: Uint8Array = this.databaseConnection.export();\n // convert Uint8Array to number array to improve local-storage storage\n const databaseArray = [].slice.call(database);\n if (this.options.useLocalForage) {\n if (window.localforage) {\n await window.localforage.setItem(path, JSON.stringify(databaseArray));\n } else {\n throw new TypeORMError(`localforage is not defined - please import localforage.js into your site`);\n }\n } else {\n PlatformTools.getGlobalVariable().localStorage.setItem(path, JSON.stringify(databaseArray));\n }\n }\n }\n\n /**\n * This gets called by the QueryRunner when a change to the database is made.\n * If a custom autoSaveCallback is specified, it get's called with the database as Uint8Array,\n * otherwise the save method is called which saves it to file (Node.js), local storage (browser)\n * or indexedDB (browser with enabled useLocalForage option).\n */\n async autoSave() {\n if (this.options.autoSave) {\n if (this.options.autoSaveCallback) {\n await this.options.autoSaveCallback(this.export());\n }\n else {\n await this.save();\n }\n }\n }\n\n /**\n * Returns the current database as Uint8Array.\n */\n export(): Uint8Array {\n return this.databaseConnection.export();\n }\n\n /**\n * Creates generated map of values generated or returned by database after INSERT query.\n */\n createGeneratedMap(metadata: EntityMetadata, insertResult: any) {\n const generatedMap = metadata.generatedColumns.reduce((map, generatedColumn) => {\n // seems to be the only way to get the inserted id, see https://github.com/kripken/sql.js/issues/77\n if (generatedColumn.isPrimary && generatedColumn.generationStrategy === \"increment\") {\n const query = \"SELECT last_insert_rowid()\";\n try {\n let result = this.databaseConnection.exec(query);\n this.connection.logger.logQuery(query);\n return OrmUtils.mergeDeep(map, generatedColumn.createValueMap(result[0].values[0][0]));\n }\n catch (e) {\n this.connection.logger.logQueryError(e, query, []);\n }\n }\n\n return map;\n }, {} as ObjectLiteral);\n\n return Object.keys(generatedMap).length > 0 ? generatedMap : undefined;\n }\n\n // -------------------------------------------------------------------------\n // Protected Methods\n // -------------------------------------------------------------------------\n\n /**\n * Creates connection with the database.\n * If the location option is set, the database is loaded first.\n */\n protected createDatabaseConnection(): Promise<any> {\n if (this.options.location) {\n return this.load(this.options.location, false);\n }\n\n return this.createDatabaseConnectionWithImport(this.options.database);\n }\n\n /**\n * Creates connection with an optional database.\n * If database is specified it is loaded, otherwise a new empty database is created.\n */\n protected async createDatabaseConnectionWithImport(database?: Uint8Array): Promise<any> {\n // sql.js < 1.0 exposes an object with a `Database` method.\n const isLegacyVersion = typeof this.sqlite.Database === \"function\";\n const sqlite = isLegacyVersion ? this.sqlite : await this.sqlite(this.options.sqlJsConfig);\n if (database && database.length > 0) {\n this.databaseConnection = new sqlite.Database(database);\n }\n else {\n this.databaseConnection = new sqlite.Database();\n }\n\n this.databaseConnection.exec(`PRAGMA foreign_keys = ON;`);\n\n return this.databaseConnection;\n }\n\n /**\n * If driver dependency is not given explicitly, then try to load it via \"require\".\n */\n protected loadDependencies(): void {\n if (PlatformTools.type === \"browser\") {\n const sqlite = this.options.driver || window.SQL;\n this.sqlite = sqlite;\n }\n else {\n try {\n const sqlite = this.options.driver || PlatformTools.load(\"sql.js\");\n this.sqlite = sqlite;\n\n } catch (e) {\n throw new DriverPackageNotInstalledError(\"sql.js\", \"sql.js\");\n }\n }\n }\n}\n"],"sourceRoot":"../.."}
@@ -77,15 +77,14 @@ var SqljsQueryRunner = /** @class */ (function (_super) {
77
77
  * Executes a given SQL query.
78
78
  */
79
79
  SqljsQueryRunner.prototype.query = function (query, parameters, useStructuredResult) {
80
- var _this = this;
81
80
  if (parameters === void 0) { parameters = []; }
82
81
  if (useStructuredResult === void 0) { useStructuredResult = false; }
83
- if (this.isReleased)
84
- throw new QueryRunnerAlreadyReleasedError();
85
- var command = query.trim().split(" ", 1)[0];
86
- return new Promise(function (ok, fail) { return __awaiter(_this, void 0, void 0, function () {
87
- var databaseConnection, queryStartTime, statement, maxQueryExecutionTime, queryEndTime, queryExecutionTime, records, result;
82
+ return __awaiter(this, void 0, void 0, function () {
83
+ var command, databaseConnection, queryStartTime, statement, maxQueryExecutionTime, queryEndTime, queryExecutionTime, records, result;
88
84
  return __generator(this, function (_a) {
85
+ if (this.isReleased)
86
+ throw new QueryRunnerAlreadyReleasedError();
87
+ command = query.trim().split(" ", 1)[0];
89
88
  databaseConnection = this.driver.databaseConnection;
90
89
  this.driver.connection.logger.logQuery(query, parameters, this);
91
90
  queryStartTime = +new Date();
@@ -113,10 +112,10 @@ var SqljsQueryRunner = /** @class */ (function (_super) {
113
112
  this.isDirty = true;
114
113
  }
115
114
  if (useStructuredResult) {
116
- ok(result);
115
+ return [2 /*return*/, result];
117
116
  }
118
117
  else {
119
- ok(result.raw);
118
+ return [2 /*return*/, result.raw];
120
119
  }
121
120
  }
122
121
  catch (e) {
@@ -124,11 +123,11 @@ var SqljsQueryRunner = /** @class */ (function (_super) {
124
123
  statement.free();
125
124
  }
126
125
  this.driver.connection.logger.logQueryError(e, query, parameters, this);
127
- fail(new QueryFailedError(query, parameters, e));
126
+ throw new QueryFailedError(query, parameters, e);
128
127
  }
129
128
  return [2 /*return*/];
130
129
  });
131
- }); });
130
+ });
132
131
  };
133
132
  return SqljsQueryRunner;
134
133
  }(AbstractSqliteQueryRunner));
@@ -1 +1 @@
1
- {"version":3,"sources":["../browser/src/driver/sqljs/SqljsQueryRunner.ts"],"names":[],"mappings":";AAAA,OAAO,EAAC,+BAA+B,EAAC,MAAM,6CAA6C,CAAC;AAC5F,OAAO,EAAC,yBAAyB,EAAC,MAAM,8CAA8C,CAAC;AAEvF,OAAO,EAAC,WAAW,EAAC,MAAM,8BAA8B,CAAC;AACzD,OAAO,EAAC,gBAAgB,EAAC,MAAM,8BAA8B,CAAC;AAC9D,OAAO,EAAE,WAAW,EAAE,MAAM,gCAAgC,CAAC;AAE7D;;GAEG;AACH;IAAsC,oCAAyB;IAY3D,4EAA4E;IAC5E,cAAc;IACd,4EAA4E;IAE5E,0BAAY,MAAmB;QAA/B,YACI,iBAAO,SAIV;QAnBD;;WAEG;QACK,aAAO,GAAG,KAAK,CAAC;QAapB,KAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,KAAI,CAAC,UAAU,GAAG,MAAM,CAAC,UAAU,CAAC;QACpC,KAAI,CAAC,WAAW,GAAG,IAAI,WAAW,CAAC,KAAI,CAAC,CAAC;;IAC7C,CAAC;IAED,4EAA4E;IAC5E,iBAAiB;IACjB,4EAA4E;IAE9D,gCAAK,GAAnB;;;;;6BACQ,IAAI,CAAC,OAAO,EAAZ,wBAAY;wBACZ,qBAAM,IAAI,CAAC,MAAM,CAAC,QAAQ,EAAE,EAAA;;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K,EAAE,UAAU,EAAE,IAAI,CAAC,CAAC;oBACxE,IAAI,CAAC,IAAI,gBAAgB,CAAC,KAAK,EAAE,UAAU,EAAE,CAAC,CAAC,CAAC,CAAC;iBACpD;;;aACJ,CAAC,CAAC;IACP,CAAC;IACL,uBAAC;AAAD,CA9GA,AA8GC,CA9GqC,yBAAyB,GA8G9D","file":"SqljsQueryRunner.js","sourcesContent":["import {QueryRunnerAlreadyReleasedError} from \"../../error/QueryRunnerAlreadyReleasedError\";\nimport {AbstractSqliteQueryRunner} from \"../sqlite-abstract/AbstractSqliteQueryRunner\";\nimport {SqljsDriver} from \"./SqljsDriver\";\nimport {Broadcaster} from \"../../subscriber/Broadcaster\";\nimport {QueryFailedError} from \"../../error/QueryFailedError\";\nimport { QueryResult } from \"../../query-runner/QueryResult\";\n\n/**\n * Runs queries on a single sqlite database connection.\n */\nexport class SqljsQueryRunner extends AbstractSqliteQueryRunner {\n\n /**\n * Flag to determine if a modification has happened since the last time this query runner has requested a save.\n */\n private isDirty = false;\n\n /**\n * Database driver used by connection.\n */\n driver: SqljsDriver;\n\n // -------------------------------------------------------------------------\n // Constructor\n // -------------------------------------------------------------------------\n\n constructor(driver: SqljsDriver) {\n super();\n this.driver = driver;\n this.connection = driver.connection;\n this.broadcaster = new Broadcaster(this);\n }\n\n // -------------------------------------------------------------------------\n // Public methods\n // -------------------------------------------------------------------------\n\n private async flush() {\n if (this.isDirty) {\n await this.driver.autoSave();\n this.isDirty = false;\n }\n }\n\n async release(): Promise<void> {\n await this.flush();\n return super.release();\n }\n\n /**\n * Commits transaction.\n * Error will be thrown if transaction was not started.\n */\n async commitTransaction(): Promise<void> {\n await super.commitTransaction();\n await this.flush();\n }\n\n /**\n * Executes a given SQL query.\n */\n query(query: string, parameters: any[] = [], useStructuredResult = false): Promise<any> {\n if (this.isReleased)\n throw new QueryRunnerAlreadyReleasedError();\n\n const command = query.trim().split(\" \", 1)[0];\n\n return new Promise(async (ok, fail) => {\n const databaseConnection = this.driver.databaseConnection;\n this.driver.connection.logger.logQuery(query, parameters, this);\n const queryStartTime = +new Date();\n let statement: any;\n try {\n statement = databaseConnection.prepare(query);\n if (parameters) {\n parameters = parameters.map(p => typeof p !== 'undefined' ? p : null);\n\n statement.bind(parameters);\n }\n\n // log slow queries if maxQueryExecution time is set\n const maxQueryExecutionTime = this.driver.options.maxQueryExecutionTime;\n const queryEndTime = +new Date();\n const queryExecutionTime = queryEndTime - queryStartTime;\n if (maxQueryExecutionTime && queryExecutionTime > maxQueryExecutionTime)\n this.driver.connection.logger.logQuerySlow(queryExecutionTime, query, parameters, this);\n\n const records: any[] = [];\n\n while (statement.step()) {\n records.push(statement.getAsObject());\n }\n\n const result = new QueryResult();\n\n result.affected = databaseConnection.getRowsModified();\n result.records = records;\n result.raw = records;\n\n statement.free();\n\n if (command !== \"SELECT\") {\n this.isDirty = true;\n }\n\n if (useStructuredResult) {\n ok(result);\n } else {\n ok(result.raw);\n }\n } catch (e) {\n if (statement) {\n statement.free();\n }\n\n this.driver.connection.logger.logQueryError(e, query, parameters, this);\n fail(new QueryFailedError(query, parameters, e));\n }\n });\n }\n}\n"],"sourceRoot":"../.."}
1
+ {"version":3,"sources":["../browser/src/driver/sqljs/SqljsQueryRunner.ts"],"names":[],"mappings":";AAAA,OAAO,EAAC,+BAA+B,EAAC,MAAM,6CAA6C,CAAC;AAC5F,OAAO,EAAC,yBAAyB,EAAC,MAAM,8CAA8C,CAAC;AAEvF,OAAO,EAAC,WAAW,EAAC,MAAM,8BAA8B,CAAC;AACzD,OAAO,EAAC,gBAAgB,EAAC,MAAM,8BAA8B,CAAC;AAC9D,OAAO,EAAE,WAAW,EAAE,MAAM,gCAAgC,CAAC;AAE7D;;GAEG;AACH;IAAsC,oCAAyB;IAY3D,4EAA4E;IAC5E,cAAc;IACd,4EAA4E;IAE5E,0BAAY,MAAmB;QAA/B,YACI,iBAAO,SAIV;QAnBD;;WAEG;QACK,aAAO,GAAG,KAAK,CAAC;QAapB,KAAI,CAA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jB;yBAAM;wBACH,sBAAO,MAAM,CAAC,GAAG,EAAC;qBACrB;iBACJ;gBAAC,OAAO,CAAC,EAAE;oBACR,IAAI,SAAS,EAAE;wBACX,SAAS,CAAC,IAAI,EAAE,CAAC;qBACpB;oBAED,IAAI,CAAC,MAAM,CAAC,UAAU,CAAC,MAAM,CAAC,aAAa,CAAC,CAAC,EAAE,KAAK,EAAE,UAAU,EAAE,IAAI,CAAC,CAAC;oBACxE,MAAM,IAAI,gBAAgB,CAAC,KAAK,EAAE,UAAU,EAAE,CAAC,CAAC,CAAC;iBACpD;;;;KACJ;IACL,uBAAC;AAAD,CA5GA,AA4GC,CA5GqC,yBAAyB,GA4G9D","file":"SqljsQueryRunner.js","sourcesContent":["import {QueryRunnerAlreadyReleasedError} from \"../../error/QueryRunnerAlreadyReleasedError\";\nimport {AbstractSqliteQueryRunner} from \"../sqlite-abstract/AbstractSqliteQueryRunner\";\nimport {SqljsDriver} from \"./SqljsDriver\";\nimport {Broadcaster} from \"../../subscriber/Broadcaster\";\nimport {QueryFailedError} from \"../../error/QueryFailedError\";\nimport { QueryResult } from \"../../query-runner/QueryResult\";\n\n/**\n * Runs queries on a single sqlite database connection.\n */\nexport class SqljsQueryRunner extends AbstractSqliteQueryRunner {\n\n /**\n * Flag to determine if a modification has happened since the last time this query runner has requested a save.\n */\n private isDirty = false;\n\n /**\n * Database driver used by connection.\n */\n driver: SqljsDriver;\n\n // -------------------------------------------------------------------------\n // Constructor\n // -------------------------------------------------------------------------\n\n constructor(driver: SqljsDriver) {\n super();\n this.driver = driver;\n this.connection = driver.connection;\n this.broadcaster = new Broadcaster(this);\n }\n\n // -------------------------------------------------------------------------\n // Public methods\n // -------------------------------------------------------------------------\n\n private async flush() {\n if (this.isDirty) {\n await this.driver.autoSave();\n this.isDirty = false;\n }\n }\n\n async release(): Promise<void> {\n await this.flush();\n return super.release();\n }\n\n /**\n * Commits transaction.\n * Error will be thrown if transaction was not started.\n */\n async commitTransaction(): Promise<void> {\n await super.commitTransaction();\n await this.flush();\n }\n\n /**\n * Executes a given SQL query.\n */\n async query(query: string, parameters: any[] = [], useStructuredResult = false): Promise<any> {\n if (this.isReleased)\n throw new QueryRunnerAlreadyReleasedError();\n\n const command = query.trim().split(\" \", 1)[0];\n\n const databaseConnection = this.driver.databaseConnection;\n this.driver.connection.logger.logQuery(query, parameters, this);\n const queryStartTime = +new Date();\n let statement: any;\n try {\n statement = databaseConnection.prepare(query);\n if (parameters) {\n parameters = parameters.map(p => typeof p !== 'undefined' ? p : null);\n\n statement.bind(parameters);\n }\n\n // log slow queries if maxQueryExecution time is set\n const maxQueryExecutionTime = this.driver.options.maxQueryExecutionTime;\n const queryEndTime = +new Date();\n const queryExecutionTime = queryEndTime - queryStartTime;\n if (maxQueryExecutionTime && queryExecutionTime > maxQueryExecutionTime)\n this.driver.connection.logger.logQuerySlow(queryExecutionTime, query, parameters, this);\n\n const records: any[] = [];\n\n while (statement.step()) {\n records.push(statement.getAsObject());\n }\n\n const result = new QueryResult();\n\n result.affected = databaseConnection.getRowsModified();\n result.records = records;\n result.raw = records;\n\n statement.free();\n\n if (command !== \"SELECT\") {\n this.isDirty = true;\n }\n\n if (useStructuredResult) {\n return result;\n } else {\n return result.raw;\n }\n } catch (e) {\n if (statement) {\n statement.free();\n }\n\n this.driver.connection.logger.logQueryError(e, query, parameters, this);\n throw new QueryFailedError(query, parameters, e);\n }\n }\n}\n"],"sourceRoot":"../.."}
@@ -87,5 +87,5 @@ export declare class MigrationExecutor {
87
87
  * Delete previously executed migration's data from the migrations table.
88
88
  */
89
89
  protected deleteExecutedMigration(queryRunner: QueryRunner, migration: Migration): Promise<void>;
90
- protected withQueryRunner<T extends any>(callback: (queryRunner: QueryRunner) => T): Promise<T>;
90
+ protected withQueryRunner<T extends any>(callback: (queryRunner: QueryRunner) => T | Promise<T>): Promise<T>;
91
91
  }
@@ -120,26 +120,14 @@ var MigrationExecutor = /** @class */ (function () {
120
120
  */
121
121
  MigrationExecutor.prototype.insertMigration = function (migration) {
122
122
  var _this = this;
123
- return new Promise(function (resolve, reject) {
124
- _this.withQueryRunner(function (queryRunner) {
125
- _this.insertExecutedMigration(queryRunner, migration)
126
- .then(resolve)
127
- .catch(reject);
128
- });
129
- });
123
+ return this.withQueryRunner(function (q) { return _this.insertExecutedMigration(q, migration); });
130
124
  };
131
125
  /**
132
126
  * Deletes an executed migration.
133
127
  */
134
128
  MigrationExecutor.prototype.deleteMigration = function (migration) {
135
129
  var _this = this;
136
- return new Promise(function (resolve, reject) {
137
- _this.withQueryRunner(function (queryRunner) {
138
- _this.deleteExecutedMigration(queryRunner, migration)
139
- .then(resolve)
140
- .catch(reject);
141
- });
142
- });
130
+ return this.withQueryRunner(function (q) { return _this.deleteExecutedMigration(q, migration); });
143
131
  };
144
132
  /**
145
133
  * Lists all migrations and whether they have been executed or not
@@ -267,6 +255,10 @@ var MigrationExecutor = /** @class */ (function () {
267
255
  transactionStartedByUs = true;
268
256
  _c.label = 2;
269
257
  case 2: return [4 /*yield*/, migration.instance.up(queryRunner)
258
+ .catch(function (error) {
259
+ _this.connection.logger.logMigration("Migration \"" + migration.name + "\" has been failed, error: " + (error === null || error === void 0 ? void 0 : error.message));
260
+ throw error;
261
+ })
270
262
  .then(function () { return __awaiter(_this, void 0, void 0, function () {
271
263
  return __generator(this, function (_a) {
272
264
  switch (_a.label) {
@@ -1 +1 @@
1
- {"version":3,"sources":["../browser/src/migration/MigrationExecutor.ts"],"names":[],"mappings":";AAAA,OAAO,EAAC,KAAK,EAAC,MAAM,+BAA+B,CAAC;AAEpD,OAAO,EAAC,SAAS,EAAC,MAAM,aAAa,CAAC;AAGtC,OAAO,EAAC,eAAe,EAAC,MAAM,qCAAqC,CAAC;AACpE,OAAO,EAAC,cAAc,EAAC,MAAM,oCAAoC,CAAC;AAClE,OAAO,EAAC,WAAW,EAAC,MAAM,+BAA+B,CAAC;AAE1D,OAAO,EAAE,YAAY,EAAE,MAAM,UAAU,CAAC;AAExC;;GAEG;AACH;IA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,MAAM,CAAC,MAAM,CAAC,aAAU,CAAC;iCACxC,aAAa,CAAC,UAAU,CAAC;iCACzB,OAAO,EAAE,EAAA;;wBALd,SAKc,CAAC;;;;;;KAGtB;IAEe,2CAAe,GAA/B,UAA+C,QAAyC;;;;;;wBAC9E,WAAW,GAAG,IAAI,CAAC,WAAW,IAAI,IAAI,CAAC,UAAU,CAAC,iBAAiB,EAAE,CAAC;;;;wBAGxE,sBAAO,QAAQ,CAAC,WAAW,CAAC,EAAC;;6BAEzB,CAAC,IAAI,CAAC,WAAW,EAAjB,wBAAiB;wBACjB,qBAAM,WAAW,CAAC,OAAO,EAAE,EAAA;;wBAA3B,SAA2B,CAAC;;;;;;;KAGvC;IACL,wBAAC;AAAD,CAnfA,AAmfC,IAAA","file":"MigrationExecutor.js","sourcesContent":["import {Table} from \"../schema-builder/table/Table\";\nimport {Connection} from \"../connection/Connection\";\nimport {Migration} from \"./Migration\";\nimport {ObjectLiteral} from \"../common/ObjectLiteral\";\nimport {QueryRunner} from \"../query-runner/QueryRunner\";\nimport {SqlServerDriver} from \"../driver/sqlserver/SqlServerDriver\";\nimport {MssqlParameter} from \"../driver/sqlserver/MssqlParameter\";\nimport {MongoDriver} from \"../driver/mongodb/MongoDriver\";\nimport {MongoQueryRunner} from \"../driver/mongodb/MongoQueryRunner\";\nimport { TypeORMError } from \"../error\";\n\n/**\n * Executes migrations: runs pending and reverts previously executed migrations.\n */\nexport class MigrationExecutor {\n\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 // 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(protected connection: Connection,\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 = connection.options.migrationsTableName || \"migrations\";\n this.migrationsTable = this.connection.driver.buildTableName(this.migrationsTableName, schema, database);\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 await (migration.instance as any).up(queryRunner);\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(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 new Promise((resolve, reject) => {\n this.withQueryRunner(queryRunner => {\n this.insertExecutedMigration(queryRunner, migration)\n .then(resolve)\n .catch(reject);\n });\n });\n }\n\n /**\n * Deletes an executed migration.\n */\n public deleteMigration(migration: Migration): Promise<void> {\n return new Promise((resolve, reject) => {\n this.withQueryRunner(queryRunner => {\n this.deleteExecutedMigration(queryRunner, migration)\n .then(resolve)\n .catch(reject);\n });\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 = this.queryRunner || this.connection.createQueryRunner();\n // create migrations table if its not created yet\n await this.createMigrationsTableIfNotExist(queryRunner);\n // get all migrations that are executed and saved in the database\n const executedMigrations = await this.loadExecutedMigrations(queryRunner);\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(executedMigration => executedMigration.name === migration.name);\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\n const queryRunner = this.queryRunner || this.connection.createQueryRunner();\n // create migrations table if its not created yet\n await this.createMigrationsTableIfNotExist(queryRunner);\n // get all migrations that are executed and saved in the database\n const executedMigrations = await this.loadExecutedMigrations(queryRunner);\n\n // get the time when last migration was executed\n let lastTimeExecutedMigration = 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 successefuly\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(executedMigration => executedMigration.name === migration.name);\n if (executedMigration)\n 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)\n await queryRunner.release();\n return [];\n }\n\n // log information about migration execution\n this.connection.logger.logSchemaBuild(`${executedMigrations.length} migrations are already loaded in the database.`);\n this.connection.logger.logSchemaBuild(`${allMigrations.length} migrations were found in the source code.`);\n if (lastTimeExecutedMigration)\n this.connection.logger.logSchemaBuild(`${lastTimeExecutedMigration.name} is the last executed migration. It was executed on ${new Date(lastTimeExecutedMigration.timestamp).toString()}.`);\n this.connection.logger.logSchemaBuild(`${pendingMigrations.length} migrations are new migrations that needs to be executed.`);\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.transaction === \"each\" && !queryRunner.isTransactionActive) {\n await queryRunner.startTransaction();\n transactionStartedByUs = true;\n }\n\n await migration.instance!.up(queryRunner)\n .then(async () => { // now when migration is executed we need to insert record about it into the database\n await this.insertExecutedMigration(queryRunner, migration);\n // commit transaction if we started it\n if (this.transaction === \"each\" && transactionStartedByUs)\n await queryRunner.commitTransaction();\n })\n .then(() => { // informative log about migration success\n successMigrations.push(migration);\n this.connection.logger.logSchemaBuild(`Migration ${migration.name} has been executed successfully.`);\n });\n }\n\n // commit transaction if we started it\n if (this.transaction === \"all\" && transactionStartedByUs)\n await queryRunner.commitTransaction();\n\n } catch (err) { // rollback transaction if we started it\n if (transactionStartedByUs) {\n try { // we throw original error even if rollback thrown an error\n await queryRunner.rollbackTransaction();\n } catch (rollbackError) { }\n }\n\n throw err;\n\n } finally {\n\n // if query runner was created by us then release it\n if (!this.queryRunner)\n await queryRunner.release();\n }\n return successMigrations;\n\n }\n\n /**\n * Reverts last migration that were run.\n */\n async undoLastMigration(): Promise<void> {\n\n const queryRunner = this.queryRunner || this.connection.createQueryRunner();\n\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(queryRunner);\n\n // get the time when last migration was executed\n let lastTimeExecutedMigration = this.getLatestExecutedMigration(executedMigrations);\n\n // if no migrations found in the database then nothing to revert\n if (!lastTimeExecutedMigration) {\n this.connection.logger.logSchemaBuild(`No migrations was found in the database. Nothing to revert!`);\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(migration => migration.name === lastTimeExecutedMigration!.name);\n\n // if no migrations found in the database then nothing to revert\n if (!migrationToRevert)\n throw new TypeORMError(`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 // log information about migration execution\n this.connection.logger.logSchemaBuild(`${executedMigrations.length} migrations are already loaded in the database.`);\n this.connection.logger.logSchemaBuild(`${lastTimeExecutedMigration.name} is the last executed migration. It was executed on ${new Date(lastTimeExecutedMigration.timestamp).toString()}.`);\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 await migrationToRevert.instance!.down(queryRunner);\n await this.deleteExecutedMigration(queryRunner, migrationToRevert);\n this.connection.logger.logSchemaBuild(`Migration ${migrationToRevert.name} has been reverted successfully.`);\n\n // commit transaction if we started it\n if (transactionStartedByUs)\n await queryRunner.commitTransaction();\n\n } catch (err) { // rollback transaction if we started it\n if (transactionStartedByUs) {\n try { // we throw original error even if rollback thrown an error\n await queryRunner.rollbackTransaction();\n } catch (rollbackError) { }\n }\n\n throw err;\n\n } finally {\n\n // if query runner was created by us then release it\n if (!this.queryRunner)\n 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(queryRunner: QueryRunner): Promise<void> {\n // If driver is mongo no need to create\n if (this.connection.driver instanceof MongoDriver) {\n return;\n }\n const tableExist = await queryRunner.hasTable(this.migrationsTable); // todo: table name should be configurable\n if (!tableExist) {\n await queryRunner.createTable(new Table(\n {\n database: this.migrationsDatabase,\n schema: this.migrationsSchema,\n name: this.migrationsTable,\n columns: [\n {\n name: \"id\",\n type: this.connection.driver.normalizeType({type: this.connection.driver.mappedDataTypes.migrationId}),\n isGenerated: true,\n generationStrategy: \"increment\",\n isPrimary: true,\n isNullable: false\n },\n {\n name: \"timestamp\",\n type: this.connection.driver.normalizeType({type: this.connection.driver.mappedDataTypes.migrationTimestamp}),\n isPrimary: false,\n isNullable: false\n },\n {\n name: \"name\",\n type: this.connection.driver.normalizeType({type: this.connection.driver.mappedDataTypes.migrationName}),\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(queryRunner: QueryRunner): Promise<Migration[]> {\n if (this.connection.driver instanceof MongoDriver) {\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(parseInt(migrationRaw[\"id\"]), parseInt(migrationRaw[\"timestamp\"]), migrationRaw[\"name\"]);\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 = migration.name || (migration.constructor as any).name;\n const migrationTimestamp = parseInt(migrationClassName.substr(-13), 10);\n if (!migrationTimestamp || isNaN(migrationTimestamp)) {\n throw new TypeORMError(`${migrationClassName} migration name is wrong. Migration class name should have a JavaScript timestamp appended.`);\n }\n\n return new Migration(undefined, migrationTimestamp, migrationClassName, migration);\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(new Set(migrationNames.filter((migrationName, index) => migrationNames.indexOf(migrationName) < index)));\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(migrations: Migration[]): Migration|undefined {\n const sortedMigrations = migrations.map(migration => migration).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(sortedMigrations: Migration[]): 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(queryRunner: QueryRunner, migration: Migration): Promise<void> {\n const values: ObjectLiteral = {};\n if (this.connection.driver instanceof SqlServerDriver) {\n values[\"timestamp\"] = new MssqlParameter(migration.timestamp, this.connection.driver.normalizeType({ type: this.connection.driver.mappedDataTypes.migrationTimestamp }) as any);\n values[\"name\"] = new MssqlParameter(migration.name, this.connection.driver.normalizeType({ type: this.connection.driver.mappedDataTypes.migrationName }) as any);\n } else {\n values[\"timestamp\"] = migration.timestamp;\n values[\"name\"] = migration.name;\n }\n if (this.connection.driver instanceof MongoDriver) {\n const mongoRunner = queryRunner as MongoQueryRunner;\n await mongoRunner.databaseConnection.db(this.connection.driver.database!).collection(this.migrationsTableName).insertOne(values);\n } else {\n const qb = queryRunner.manager.createQueryBuilder();\n await qb.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(queryRunner: QueryRunner, migration: Migration): Promise<void> {\n\n const conditions: ObjectLiteral = {};\n if (this.connection.driver instanceof SqlServerDriver) {\n conditions[\"timestamp\"] = new MssqlParameter(migration.timestamp, this.connection.driver.normalizeType({ type: this.connection.driver.mappedDataTypes.migrationTimestamp }) as any);\n conditions[\"name\"] = new MssqlParameter(migration.name, this.connection.driver.normalizeType({ type: this.connection.driver.mappedDataTypes.migrationName }) as any);\n } else {\n conditions[\"timestamp\"] = migration.timestamp;\n conditions[\"name\"] = migration.name;\n }\n\n if (this.connection.driver instanceof MongoDriver) {\n const mongoRunner = queryRunner as MongoQueryRunner;\n await mongoRunner.databaseConnection.db(this.connection.driver.database!).collection(this.migrationsTableName).deleteOne(conditions);\n } else {\n const qb = queryRunner.manager.createQueryBuilder();\n await qb.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\n protected async withQueryRunner<T extends any>(callback: (queryRunner: QueryRunner) => T) {\n const queryRunner = 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,EAAC,KAAK,EAAC,MAAM,+BAA+B,CAAC;AAEpD,OAAO,EAAC,SAAS,EAAC,MAAM,aAAa,CAAC;AAGtC,OAAO,EAAC,eAAe,EAAC,MAAM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,IAAI,CAAC,IAAI,CAAC,eAAe,CAAC;iCAC1B,KAAK,CAAI,EAAE,CAAC,MAAM,CAAC,WAAW,CAAC,kBAAe,CAAC;iCAC/C,QAAQ,CAAI,EAAE,CAAC,MAAM,CAAC,MAAM,CAAC,aAAU,CAAC;iCACxC,aAAa,CAAC,UAAU,CAAC;iCACzB,OAAO,EAAE,EAAA;;wBALd,SAKc,CAAC;;;;;;KAGtB;IAEe,2CAAe,GAA/B,UAA+C,QAAsD;;;;;;wBAC3F,WAAW,GAAG,IAAI,CAAC,WAAW,IAAI,IAAI,CAAC,UAAU,CAAC,iBAAiB,EAAE,CAAC;;;;wBAGxE,sBAAO,QAAQ,CAAC,WAAW,CAAC,EAAC;;6BAEzB,CAAC,IAAI,CAAC,WAAW,EAAjB,wBAAiB;wBACjB,qBAAM,WAAW,CAAC,OAAO,EAAE,EAAA;;wBAA3B,SAA2B,CAAC;;;;;;;KAGvC;IACL,wBAAC;AAAD,CA3eA,AA2eC,IAAA","file":"MigrationExecutor.js","sourcesContent":["import {Table} from \"../schema-builder/table/Table\";\nimport {Connection} from \"../connection/Connection\";\nimport {Migration} from \"./Migration\";\nimport {ObjectLiteral} from \"../common/ObjectLiteral\";\nimport {QueryRunner} from \"../query-runner/QueryRunner\";\nimport {SqlServerDriver} from \"../driver/sqlserver/SqlServerDriver\";\nimport {MssqlParameter} from \"../driver/sqlserver/MssqlParameter\";\nimport {MongoDriver} from \"../driver/mongodb/MongoDriver\";\nimport {MongoQueryRunner} from \"../driver/mongodb/MongoQueryRunner\";\nimport { TypeORMError } from \"../error\";\n\n/**\n * Executes migrations: runs pending and reverts previously executed migrations.\n */\nexport class MigrationExecutor {\n\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 // 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(protected connection: Connection,\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 = connection.options.migrationsTableName || \"migrations\";\n this.migrationsTable = this.connection.driver.buildTableName(this.migrationsTableName, schema, database);\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 await (migration.instance as any).up(queryRunner);\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(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 => this.insertExecutedMigration(q, migration));\n }\n\n /**\n * Deletes an executed migration.\n */\n public deleteMigration(migration: Migration): Promise<void> {\n return this.withQueryRunner(q => this.deleteExecutedMigration(q, migration));\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 = this.queryRunner || this.connection.createQueryRunner();\n // create migrations table if its not created yet\n await this.createMigrationsTableIfNotExist(queryRunner);\n // get all migrations that are executed and saved in the database\n const executedMigrations = await this.loadExecutedMigrations(queryRunner);\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(executedMigration => executedMigration.name === migration.name);\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\n const queryRunner = this.queryRunner || this.connection.createQueryRunner();\n // create migrations table if its not created yet\n await this.createMigrationsTableIfNotExist(queryRunner);\n // get all migrations that are executed and saved in the database\n const executedMigrations = await this.loadExecutedMigrations(queryRunner);\n\n // get the time when last migration was executed\n let lastTimeExecutedMigration = 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 successefuly\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(executedMigration => executedMigration.name === migration.name);\n if (executedMigration)\n 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)\n await queryRunner.release();\n return [];\n }\n\n // log information about migration execution\n this.connection.logger.logSchemaBuild(`${executedMigrations.length} migrations are already loaded in the database.`);\n this.connection.logger.logSchemaBuild(`${allMigrations.length} migrations were found in the source code.`);\n if (lastTimeExecutedMigration)\n this.connection.logger.logSchemaBuild(`${lastTimeExecutedMigration.name} is the last executed migration. It was executed on ${new Date(lastTimeExecutedMigration.timestamp).toString()}.`);\n this.connection.logger.logSchemaBuild(`${pendingMigrations.length} migrations are new migrations that needs to be executed.`);\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.transaction === \"each\" && !queryRunner.isTransactionActive) {\n await queryRunner.startTransaction();\n transactionStartedByUs = true;\n }\n\n await migration.instance!.up(queryRunner)\n .catch(error => { // informative log about migration failure\n this.connection.logger.logMigration(`Migration \"${migration.name}\" has been failed, error: ${error?.message}`);\n throw error;\n })\n .then(async () => { // now when migration is executed we need to insert record about it into the database\n await this.insertExecutedMigration(queryRunner, migration);\n // commit transaction if we started it\n if (this.transaction === \"each\" && transactionStartedByUs)\n await queryRunner.commitTransaction();\n })\n .then(() => { // informative log about migration success\n successMigrations.push(migration);\n this.connection.logger.logSchemaBuild(`Migration ${migration.name} has been executed successfully.`);\n });\n }\n\n // commit transaction if we started it\n if (this.transaction === \"all\" && transactionStartedByUs)\n await queryRunner.commitTransaction();\n\n } catch (err) { // rollback transaction if we started it\n if (transactionStartedByUs) {\n try { // we throw original error even if rollback thrown an error\n await queryRunner.rollbackTransaction();\n } catch (rollbackError) { }\n }\n\n throw err;\n\n } finally {\n\n // if query runner was created by us then release it\n if (!this.queryRunner)\n await queryRunner.release();\n }\n return successMigrations;\n\n }\n\n /**\n * Reverts last migration that were run.\n */\n async undoLastMigration(): Promise<void> {\n\n const queryRunner = this.queryRunner || this.connection.createQueryRunner();\n\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(queryRunner);\n\n // get the time when last migration was executed\n let lastTimeExecutedMigration = this.getLatestExecutedMigration(executedMigrations);\n\n // if no migrations found in the database then nothing to revert\n if (!lastTimeExecutedMigration) {\n this.connection.logger.logSchemaBuild(`No migrations was found in the database. Nothing to revert!`);\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(migration => migration.name === lastTimeExecutedMigration!.name);\n\n // if no migrations found in the database then nothing to revert\n if (!migrationToRevert)\n throw new TypeORMError(`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 // log information about migration execution\n this.connection.logger.logSchemaBuild(`${executedMigrations.length} migrations are already loaded in the database.`);\n this.connection.logger.logSchemaBuild(`${lastTimeExecutedMigration.name} is the last executed migration. It was executed on ${new Date(lastTimeExecutedMigration.timestamp).toString()}.`);\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 await migrationToRevert.instance!.down(queryRunner);\n await this.deleteExecutedMigration(queryRunner, migrationToRevert);\n this.connection.logger.logSchemaBuild(`Migration ${migrationToRevert.name} has been reverted successfully.`);\n\n // commit transaction if we started it\n if (transactionStartedByUs)\n await queryRunner.commitTransaction();\n\n } catch (err) { // rollback transaction if we started it\n if (transactionStartedByUs) {\n try { // we throw original error even if rollback thrown an error\n await queryRunner.rollbackTransaction();\n } catch (rollbackError) { }\n }\n\n throw err;\n\n } finally {\n\n // if query runner was created by us then release it\n if (!this.queryRunner)\n 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(queryRunner: QueryRunner): Promise<void> {\n // If driver is mongo no need to create\n if (this.connection.driver instanceof MongoDriver) {\n return;\n }\n const tableExist = await queryRunner.hasTable(this.migrationsTable); // todo: table name should be configurable\n if (!tableExist) {\n await queryRunner.createTable(new Table(\n {\n database: this.migrationsDatabase,\n schema: this.migrationsSchema,\n name: this.migrationsTable,\n columns: [\n {\n name: \"id\",\n type: this.connection.driver.normalizeType({type: this.connection.driver.mappedDataTypes.migrationId}),\n isGenerated: true,\n generationStrategy: \"increment\",\n isPrimary: true,\n isNullable: false\n },\n {\n name: \"timestamp\",\n type: this.connection.driver.normalizeType({type: this.connection.driver.mappedDataTypes.migrationTimestamp}),\n isPrimary: false,\n isNullable: false\n },\n {\n name: \"name\",\n type: this.connection.driver.normalizeType({type: this.connection.driver.mappedDataTypes.migrationName}),\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(queryRunner: QueryRunner): Promise<Migration[]> {\n if (this.connection.driver instanceof MongoDriver) {\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(parseInt(migrationRaw[\"id\"]), parseInt(migrationRaw[\"timestamp\"]), migrationRaw[\"name\"]);\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 = migration.name || (migration.constructor as any).name;\n const migrationTimestamp = parseInt(migrationClassName.substr(-13), 10);\n if (!migrationTimestamp || isNaN(migrationTimestamp)) {\n throw new TypeORMError(`${migrationClassName} migration name is wrong. Migration class name should have a JavaScript timestamp appended.`);\n }\n\n return new Migration(undefined, migrationTimestamp, migrationClassName, migration);\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(new Set(migrationNames.filter((migrationName, index) => migrationNames.indexOf(migrationName) < index)));\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(migrations: Migration[]): Migration|undefined {\n const sortedMigrations = migrations.map(migration => migration).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(sortedMigrations: Migration[]): 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(queryRunner: QueryRunner, migration: Migration): Promise<void> {\n const values: ObjectLiteral = {};\n if (this.connection.driver instanceof SqlServerDriver) {\n values[\"timestamp\"] = new MssqlParameter(migration.timestamp, this.connection.driver.normalizeType({ type: this.connection.driver.mappedDataTypes.migrationTimestamp }) as any);\n values[\"name\"] = new MssqlParameter(migration.name, this.connection.driver.normalizeType({ type: this.connection.driver.mappedDataTypes.migrationName }) as any);\n } else {\n values[\"timestamp\"] = migration.timestamp;\n values[\"name\"] = migration.name;\n }\n if (this.connection.driver instanceof MongoDriver) {\n const mongoRunner = queryRunner as MongoQueryRunner;\n await mongoRunner.databaseConnection.db(this.connection.driver.database!).collection(this.migrationsTableName).insertOne(values);\n } else {\n const qb = queryRunner.manager.createQueryBuilder();\n await qb.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(queryRunner: QueryRunner, migration: Migration): Promise<void> {\n\n const conditions: ObjectLiteral = {};\n if (this.connection.driver instanceof SqlServerDriver) {\n conditions[\"timestamp\"] = new MssqlParameter(migration.timestamp, this.connection.driver.normalizeType({ type: this.connection.driver.mappedDataTypes.migrationTimestamp }) as any);\n conditions[\"name\"] = new MssqlParameter(migration.name, this.connection.driver.normalizeType({ type: this.connection.driver.mappedDataTypes.migrationName }) as any);\n } else {\n conditions[\"timestamp\"] = migration.timestamp;\n conditions[\"name\"] = migration.name;\n }\n\n if (this.connection.driver instanceof MongoDriver) {\n const mongoRunner = queryRunner as MongoQueryRunner;\n await mongoRunner.databaseConnection.db(this.connection.driver.database!).collection(this.migrationsTableName).deleteOne(conditions);\n } else {\n const qb = queryRunner.manager.createQueryBuilder();\n await qb.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\n protected async withQueryRunner<T extends any>(callback: (queryRunner: QueryRunner) => T | Promise<T>) {\n const queryRunner = 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":".."}
@@ -528,7 +528,7 @@ var SubjectExecutor = /** @class */ (function () {
528
528
  }
529
529
  finally { if (e_3) throw e_3.error; }
530
530
  }
531
- nestedSetPromise = new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () {
531
+ nestedSetPromise = new Promise(function (ok, fail) { return __awaiter(_this, void 0, void 0, function () {
532
532
  var nestedSetSubjects_1, nestedSetSubjects_1_1, subject, error_1, e_4_1;
533
533
  var e_4, _a;
534
534
  return __generator(this, function (_b) {
@@ -549,7 +549,7 @@ var SubjectExecutor = /** @class */ (function () {
549
549
  return [3 /*break*/, 5];
550
550
  case 4:
551
551
  error_1 = _b.sent();
552
- reject(error_1);
552
+ fail(error_1);
553
553
  return [3 /*break*/, 5];
554
554
  case 5:
555
555
  nestedSetSubjects_1_1 = nestedSetSubjects_1.next();
@@ -566,7 +566,7 @@ var SubjectExecutor = /** @class */ (function () {
566
566
  finally { if (e_4) throw e_4.error; }
567
567
  return [7 /*endfinally*/];
568
568
  case 9:
569
- resolve();
569
+ ok();
570
570
  return [2 /*return*/];
571
571
  }
572
572
  });