kanel-knex
Version:
Knex extension for Kanel
53 lines (52 loc) • 2.13 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const knex_1 = __importDefault(require("knex"));
const path_1 = require("path");
const knexImport_1 = __importDefault(require("./knexImport"));
const generateMigrationCheck = async (outputAcc, instantiatedConfig) => {
const connection = instantiatedConfig.connection;
const db = (0, knex_1.default)({ client: "postgres", connection });
const [{ name: sourceMigration }] = await db
.select("name")
.from("knex_migrations")
.orderBy("migration_time", "DESC")
.limit(1);
db.destroy();
const typeImports = [knexImport_1.default];
const lines = [
"/** This is the migration that was set when the types were generated. */",
`export const sourceMigration = '${sourceMigration}';`,
"",
"/** Gets the migration in the live database */",
"export const getCurrentMigration = async (knex: Knex): Promise<string> => {",
" const [{ name }] = await knex",
" .select('name')",
" .from('knex_migrations')",
" .orderBy('migration_time', 'DESC')",
" .limit(1);",
" return name;",
"};",
"",
"/** Check that the migration in the live database matches the code */",
"export const validateMigration = async (knex: Knex): Promise<void> => {",
" const currentMigration = await getCurrentMigration(knex);",
" if (currentMigration !== sourceMigration) {",
" throw new Error(`Current migration is ${currentMigration}, but source migration is ${sourceMigration}`);",
" }",
"};",
];
const declaration = {
declarationType: "generic",
typeImports,
lines,
};
const path = (0, path_1.join)(instantiatedConfig.outputPath, "migration-check");
return {
...outputAcc,
[path]: { declarations: [declaration] },
};
};
exports.default = generateMigrationCheck;