UNPKG

9.35 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3var tslib_1 = require("tslib");
4var ConnectionOptionsReader_1 = require("../connection/ConnectionOptionsReader");
5var CommandUtils_1 = require("./CommandUtils");
6var index_1 = require("../index");
7var MysqlDriver_1 = require("../driver/mysql/MysqlDriver");
8var StringUtils_1 = require("../util/StringUtils");
9var AuroraDataApiDriver_1 = require("../driver/aurora-data-api/AuroraDataApiDriver");
10var chalk = require("chalk");
11/**
12 * Generates a new migration file with sql needs to be executed to update schema.
13 */
14var MigrationGenerateCommand = /** @class */ (function () {
15 function MigrationGenerateCommand() {
16 this.command = "migration:generate";
17 this.describe = "Generates a new migration file with sql needs to be executed to update schema.";
18 this.aliases = "migrations:generate";
19 }
20 MigrationGenerateCommand.prototype.builder = function (args) {
21 return args
22 .option("c", {
23 alias: "connection",
24 default: "default",
25 describe: "Name of the connection on which run a query."
26 })
27 .option("n", {
28 alias: "name",
29 describe: "Name of the migration class.",
30 demand: true
31 })
32 .option("d", {
33 alias: "dir",
34 describe: "Directory where migration should be created."
35 })
36 .option("f", {
37 alias: "config",
38 default: "ormconfig",
39 describe: "Name of the file with connection configuration."
40 });
41 };
42 MigrationGenerateCommand.prototype.handler = function (args) {
43 return tslib_1.__awaiter(this, void 0, void 0, function () {
44 var timestamp, filename, directory, connectionOptionsReader, connectionOptions, err_1, connection, connectionOptionsReader, connectionOptions, sqlInMemory, upSqls_1, downSqls_1, fileContent, path, err_2;
45 return tslib_1.__generator(this, function (_a) {
46 switch (_a.label) {
47 case 0:
48 if (args._[0] === "migrations:generate") {
49 console.log("'migrations:generate' is deprecated, please use 'migration:generate' instead");
50 }
51 timestamp = new Date().getTime();
52 filename = timestamp + "-" + args.name + ".ts";
53 directory = args.dir;
54 if (!!directory) return [3 /*break*/, 4];
55 _a.label = 1;
56 case 1:
57 _a.trys.push([1, 3, , 4]);
58 connectionOptionsReader = new ConnectionOptionsReader_1.ConnectionOptionsReader({
59 root: process.cwd(),
60 configName: args.config
61 });
62 return [4 /*yield*/, connectionOptionsReader.get(args.connection)];
63 case 2:
64 connectionOptions = _a.sent();
65 directory = connectionOptions.cli ? connectionOptions.cli.migrationsDir : undefined;
66 return [3 /*break*/, 4];
67 case 3:
68 err_1 = _a.sent();
69 return [3 /*break*/, 4];
70 case 4:
71 connection = undefined;
72 _a.label = 5;
73 case 5:
74 _a.trys.push([5, 15, , 18]);
75 connectionOptionsReader = new ConnectionOptionsReader_1.ConnectionOptionsReader({
76 root: process.cwd(),
77 configName: args.config
78 });
79 return [4 /*yield*/, connectionOptionsReader.get(args.connection)];
80 case 6:
81 connectionOptions = _a.sent();
82 Object.assign(connectionOptions, {
83 synchronize: false,
84 migrationsRun: false,
85 dropSchema: false,
86 logging: false
87 });
88 return [4 /*yield*/, index_1.createConnection(connectionOptions)];
89 case 7:
90 connection = _a.sent();
91 return [4 /*yield*/, connection.driver.createSchemaBuilder().log()];
92 case 8:
93 sqlInMemory = _a.sent();
94 upSqls_1 = [], downSqls_1 = [];
95 // mysql is exceptional here because it uses ` character in to escape names in queries, that's why for mysql
96 // we are using simple quoted string instead of template string syntax
97 if (connection.driver instanceof MysqlDriver_1.MysqlDriver || connection.driver instanceof AuroraDataApiDriver_1.AuroraDataApiDriver) {
98 sqlInMemory.upQueries.forEach(function (upQuery) {
99 upSqls_1.push(" await queryRunner.query(\"" + upQuery.query.replace(new RegExp("\"", "g"), "\\\"") + "\", " + JSON.stringify(upQuery.parameters) + ");");
100 });
101 sqlInMemory.downQueries.forEach(function (downQuery) {
102 downSqls_1.push(" await queryRunner.query(\"" + downQuery.query.replace(new RegExp("\"", "g"), "\\\"") + "\", " + JSON.stringify(downQuery.parameters) + ");");
103 });
104 }
105 else {
106 sqlInMemory.upQueries.forEach(function (upQuery) {
107 upSqls_1.push(" await queryRunner.query(`" + upQuery.query.replace(new RegExp("`", "g"), "\\`") + "`, " + JSON.stringify(upQuery.parameters) + ");");
108 });
109 sqlInMemory.downQueries.forEach(function (downQuery) {
110 downSqls_1.push(" await queryRunner.query(`" + downQuery.query.replace(new RegExp("`", "g"), "\\`") + "`, " + JSON.stringify(downQuery.parameters) + ");");
111 });
112 }
113 if (!upSqls_1.length) return [3 /*break*/, 12];
114 if (!args.name) return [3 /*break*/, 10];
115 fileContent = MigrationGenerateCommand.getTemplate(args.name, timestamp, upSqls_1, downSqls_1.reverse());
116 path = process.cwd() + "/" + (directory ? (directory + "/") : "") + filename;
117 return [4 /*yield*/, CommandUtils_1.CommandUtils.createFile(path, fileContent)];
118 case 9:
119 _a.sent();
120 console.log(chalk.green("Migration " + chalk.blue(path) + " has been generated successfully."));
121 return [3 /*break*/, 11];
122 case 10:
123 console.log(chalk.yellow("Please specify migration name"));
124 _a.label = 11;
125 case 11: return [3 /*break*/, 13];
126 case 12:
127 console.log(chalk.yellow("No changes in database schema were found - cannot generate a migration. To create a new empty migration use \"typeorm migration:create\" command"));
128 _a.label = 13;
129 case 13: return [4 /*yield*/, connection.close()];
130 case 14:
131 _a.sent();
132 return [3 /*break*/, 18];
133 case 15:
134 err_2 = _a.sent();
135 if (!connection) return [3 /*break*/, 17];
136 return [4 /*yield*/, connection.close()];
137 case 16:
138 _a.sent();
139 _a.label = 17;
140 case 17:
141 console.log(chalk.black.bgRed("Error during migration generation:"));
142 console.error(err_2);
143 process.exit(1);
144 return [3 /*break*/, 18];
145 case 18: return [2 /*return*/];
146 }
147 });
148 });
149 };
150 // -------------------------------------------------------------------------
151 // Protected Static Methods
152 // -------------------------------------------------------------------------
153 /**
154 * Gets contents of the migration file.
155 */
156 MigrationGenerateCommand.getTemplate = function (name, timestamp, upSqls, downSqls) {
157 var migrationName = "" + StringUtils_1.camelCase(name, true) + timestamp;
158 return "import {MigrationInterface, QueryRunner} from \"typeorm\";\n\nexport class " + migrationName + " implements MigrationInterface {\n name = '" + migrationName + "'\n\n public async up(queryRunner: QueryRunner): Promise<any> {\n" + upSqls.join("\n") + "\n }\n\n public async down(queryRunner: QueryRunner): Promise<any> {\n" + downSqls.join("\n") + "\n }\n\n}\n";
159 };
160 return MigrationGenerateCommand;
161}());
162exports.MigrationGenerateCommand = MigrationGenerateCommand;
163
164//# sourceMappingURL=MigrationGenerateCommand.js.map