shyft
Version:
Model driven GraphQL API framework
410 lines (409 loc) • 19.8 kB
JavaScript
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.migrateI18nIndices = exports.fillMigrationsTable = exports.revertMigration = exports.runMigration = exports.generateMigration = void 0;
var _ = __importStar(require("lodash"));
var path = __importStar(require("path"));
var CommandUtils_1 = require("typeorm/commands/CommandUtils");
var MigrationExecutor_1 = require("typeorm/migration/MigrationExecutor");
var prettier_eslint_1 = __importDefault(require("prettier-eslint"));
var generator_1 = require("./generator");
var util_1 = require("./util");
var CustomMigrationExecuter = /** @class */ (function (_super) {
__extends(CustomMigrationExecuter, _super);
function CustomMigrationExecuter(connection) {
return _super.call(this, connection) || this;
}
CustomMigrationExecuter.prototype._createMigrationsTableIfNotExist = function (queryRunner) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.createMigrationsTableIfNotExist(queryRunner)];
case 1:
_a.sent();
return [2 /*return*/];
}
});
});
};
CustomMigrationExecuter.prototype._getMigrations = function () {
return this.getMigrations();
};
CustomMigrationExecuter.prototype._insertExecutedMigration = function (queryRunner, migration) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.insertExecutedMigration(queryRunner, migration)];
case 1:
_a.sent();
return [2 /*return*/];
}
});
});
};
return CustomMigrationExecuter;
}(MigrationExecutor_1.MigrationExecutor));
var defaultTemplate = function (migrationName, timestamp, upSqls, downSqls) {
return "\nexport class " + _.camelCase(migrationName) + timestamp + " {\n async up(queryRunner) {\n" + upSqls.join('\n') + "\n }\n\n async down(queryRunner) {\n" + downSqls.join('\n') + "\n }\n}\n";
};
var upgradeMigrationQuery = function (_query, isUpMigration) {
if (isUpMigration === void 0) { isUpMigration = false; }
var sqls = [];
var query = _query.query.replace(new RegExp('`', 'g'), '\\`');
var parameters = _query.parameters ? JSON.stringify(_query.parameters) : '';
var match = query.match(/ALTER TABLE "(\w+)" ADD "(\w+)" (.+) NOT NULL/);
if (match) {
var table = match[1], attribute = match[2], _type = match[3];
var type = _type.toLowerCase();
var defaultValue = void 0;
// user tracking
if (['created_by', 'updated_by'].includes(attribute)) {
defaultValue = 'get_machine_user()';
}
// time tracking
else if (['created_at', 'updated_at'].includes(attribute)) {
defaultValue = 'NOW()';
}
// general type based default values
else if (type.includes('timestamp')) {
defaultValue = 'NOW()';
}
else if (type.includes('time')) {
defaultValue = 'NOW()';
}
else if (type.includes('date')) {
defaultValue = 'NOW()';
}
else if (type.includes('bigint')) {
defaultValue = '0';
}
else if (type.includes('integer')) {
defaultValue = '0';
}
else if (type.includes('numeric')) {
defaultValue = '0.0';
}
else if (type.includes('double precision')) {
defaultValue = '0.0';
}
else if (type.includes('boolean')) {
defaultValue = false;
}
else if (type.includes('json') || type.includes('jsonb')) {
defaultValue = "\\'{}\\'";
}
else if (type.includes('text')) {
defaultValue = "\\'\\'";
}
else {
throw new Error("Cannot handle column addition default for: " + query);
}
var addColumnQuery = " await queryRunner.query('" + query + " DEFAULT " + defaultValue + "');";
var dropDefaultQuery = " await queryRunner.query('ALTER TABLE \"" + table + "\" ALTER COLUMN \"" + attribute + "\" DROP DEFAULT');";
if (isUpMigration) {
sqls.push(addColumnQuery);
sqls.push(dropDefaultQuery);
}
else {
sqls.push(dropDefaultQuery);
sqls.push(addColumnQuery);
}
}
else {
var reformatted = query
.replace(new RegExp('`', 'g'), '\\`')
.replace(new RegExp("'", 'g'), "\\'");
sqls.push(" await queryRunner.query(`" + reformatted + "`, " + parameters + ");");
}
return sqls;
};
var getMigrationsFullPath = function (connectionConfig) {
if (connectionConfig.migrations && connectionConfig.migrations[0]) {
return path.dirname(connectionConfig.migrations[0].indexOf('/') === 0
? connectionConfig.migrations[0]
: path.join(process.cwd(), connectionConfig.migrations[0]));
}
return path.join(process.cwd(), 'migrations');
};
var generateMigration = function (configuration, migrationName, customTemplate, includeI18n, enforce) {
if (includeI18n === void 0) { includeI18n = false; }
if (enforce === void 0) { enforce = false; }
return __awaiter(void 0, void 0, void 0, function () {
var connection, storageConfiguration, manager, connectionConfig, migrationsPath, timestamp, upSqls, downSqls, i18nMigrations, sqlInMemory, filename, template, fileContent, migrationPath, formatted;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, generator_1.connectStorage(configuration, false, false)];
case 1:
connection = _a.sent();
storageConfiguration = configuration.getStorageConfiguration();
manager = connection.manager;
connectionConfig = storageConfiguration.getConnectionConfig();
migrationsPath = getMigrationsFullPath(connectionConfig);
timestamp = new Date().getTime();
upSqls = [];
downSqls = [];
if (!includeI18n) return [3 /*break*/, 3];
return [4 /*yield*/, storageConfiguration.generateI18nIndicesMigration(configuration, manager)];
case 2:
i18nMigrations = _a.sent();
i18nMigrations.upQueries.forEach(function (query) {
upgradeMigrationQuery({ query: query }, true).map(function (sql) { return upSqls.push(sql); });
});
i18nMigrations.downQueries.forEach(function (query) {
upgradeMigrationQuery({ query: query }, false).map(function (sql) { return downSqls.push(sql); });
});
_a.label = 3;
case 3: return [4 /*yield*/, connection.driver.createSchemaBuilder().log()];
case 4:
sqlInMemory = _a.sent();
sqlInMemory.upQueries.forEach(function (query) {
upgradeMigrationQuery(query, true).map(function (sql) { return upSqls.push(sql); });
});
sqlInMemory.downQueries.forEach(function (query) {
upgradeMigrationQuery(query, false).map(function (sql) { return downSqls.push(sql); });
});
if (!(upSqls.length || downSqls.length || enforce)) return [3 /*break*/, 6];
if (!migrationName) {
throw new Error('Error: Please specify a migration name');
}
filename = timestamp + "-" + _.camelCase(migrationName) + ".js";
template = customTemplate || defaultTemplate;
fileContent = template(migrationName, timestamp, upSqls, downSqls.reverse());
migrationPath = path.join(migrationsPath, filename);
formatted = prettier_eslint_1.default({
text: fileContent,
filePath: migrationPath,
});
return [4 /*yield*/, CommandUtils_1.CommandUtils.createFile(migrationPath, formatted)];
case 5:
_a.sent();
console.log("Migration file '" + migrationPath + "' has been generated successfully.");
return [3 /*break*/, 7];
case 6:
console.log('No changes were found in database schema.');
_a.label = 7;
case 7: return [4 /*yield*/, generator_1.disconnectStorage(connection)];
case 8:
_a.sent();
return [2 /*return*/, upSqls.length || downSqls.length || enforce ? timestamp : null];
}
});
});
};
exports.generateMigration = generateMigration;
var runMigration = function (configuration) { return __awaiter(void 0, void 0, void 0, function () {
var connection, err_1;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, generator_1.connectStorage(configuration, false)];
case 1:
connection = _a.sent();
_a.label = 2;
case 2:
_a.trys.push([2, 4, , 6]);
return [4 /*yield*/, connection.runMigrations({
transaction: 'each',
})];
case 3:
_a.sent();
return [3 /*break*/, 6];
case 4:
err_1 = _a.sent();
console.error('Migration failed');
console.error(err_1);
return [4 /*yield*/, generator_1.disconnectStorage(connection)];
case 5:
_a.sent();
process.exit(1);
return [3 /*break*/, 6];
case 6: return [4 /*yield*/, generator_1.disconnectStorage(connection)];
case 7:
_a.sent();
return [2 /*return*/];
}
});
}); };
exports.runMigration = runMigration;
var revertMigration = function (configuration) { return __awaiter(void 0, void 0, void 0, function () {
var connection, err_2;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, generator_1.connectStorage(configuration, false)];
case 1:
connection = _a.sent();
_a.label = 2;
case 2:
_a.trys.push([2, 4, , 6]);
return [4 /*yield*/, connection.undoLastMigration({
transaction: 'each',
})];
case 3:
_a.sent();
return [3 /*break*/, 6];
case 4:
err_2 = _a.sent();
console.error('Migration reversion failed');
console.error(err_2);
return [4 /*yield*/, generator_1.disconnectStorage(connection)];
case 5:
_a.sent();
process.exit(1);
return [3 /*break*/, 6];
case 6: return [4 /*yield*/, generator_1.disconnectStorage(connection)];
case 7:
_a.sent();
return [2 /*return*/];
}
});
}); };
exports.revertMigration = revertMigration;
var fillMigrationsTable = function (connection) { return __awaiter(void 0, void 0, void 0, function () {
var queryRunner, migrationExecutor, allMigrations;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
queryRunner = connection.createQueryRunner();
migrationExecutor = new CustomMigrationExecuter(connection);
return [4 /*yield*/, migrationExecutor._createMigrationsTableIfNotExist(queryRunner)];
case 1:
_a.sent();
allMigrations = migrationExecutor._getMigrations();
return [4 /*yield*/, util_1.asyncForEach(allMigrations, function (migration) { return __awaiter(void 0, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, migrationExecutor._insertExecutedMigration(queryRunner, migration)];
case 1:
_a.sent();
return [2 /*return*/];
}
});
}); })];
case 2:
_a.sent();
return [2 /*return*/];
}
});
}); };
exports.fillMigrationsTable = fillMigrationsTable;
var migrateI18nIndices = function (configuration) { return __awaiter(void 0, void 0, void 0, function () {
var connection, storageConfiguration, manager, queryRunner, upQueries, err_3;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, generator_1.connectStorage(configuration, false)];
case 1:
connection = _a.sent();
storageConfiguration = configuration.getStorageConfiguration();
manager = connection.manager;
queryRunner = connection.createQueryRunner();
_a.label = 2;
case 2:
_a.trys.push([2, 8, , 10]);
return [4 /*yield*/, storageConfiguration.generateI18nIndicesMigration(configuration, manager)];
case 3:
upQueries = (_a.sent()).upQueries;
if (!upQueries.length) return [3 /*break*/, 7];
return [4 /*yield*/, queryRunner.startTransaction()];
case 4:
_a.sent();
return [4 /*yield*/, util_1.asyncForEach(upQueries, function (query) { return __awaiter(void 0, void 0, void 0, function () { return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, queryRunner.query(query)];
case 1: return [2 /*return*/, _a.sent()];
}
}); }); })];
case 5:
_a.sent();
return [4 /*yield*/, queryRunner.commitTransaction()];
case 6:
_a.sent();
_a.label = 7;
case 7: return [3 /*break*/, 10];
case 8:
err_3 = _a.sent();
console.error('I18n migration failed');
console.error(err_3);
return [4 /*yield*/, generator_1.disconnectStorage(connection)];
case 9:
_a.sent();
process.exit(1);
return [3 /*break*/, 10];
case 10: return [4 /*yield*/, generator_1.disconnectStorage(connection)];
case 11:
_a.sent();
return [2 /*return*/];
}
});
}); };
exports.migrateI18nIndices = migrateI18nIndices;