pg-migration-manager
Version:
The super simple migration manager for pg driver.
76 lines • 3.53 kB
JavaScript
;
var __asyncValues = (this && this.__asyncValues) || function (o) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var m = o[Symbol.asyncIterator], i;
return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
};
Object.defineProperty(exports, "__esModule", { value: true });
const fs = require("fs");
const path = require("path");
class MigrationManager {
constructor(connection, config) {
this.connection = connection;
this.tableName = config.migrationTableName || 'migrations';
this.pathToMigrations = config.pathToMigrations;
}
async getMigrations() {
try {
const fileNames = await fs.promises.readdir(this.pathToMigrations);
const migrationPromises = fileNames.map(async (fileName) => {
const filePath = path.resolve(this.pathToMigrations, fileName);
const { birthtimeMs } = await fs.promises.stat(filePath);
const { name: filename } = path.parse(fileName);
return {
filename,
datetime: +(birthtimeMs / 1000).toFixed(),
script: await fs.promises.readFile(filePath, { encoding: 'utf8' }),
};
});
this.migrations = (await Promise.all(migrationPromises)).sort((a, b) => (a.datetime < b.datetime && -1) || 1);
}
catch (e) {
throw new Error(`The error of migration files reading ---> ${e}`);
}
}
async createTable() {
await this.connection.query(`create table if not exists ${this.tableName}
(id serial primary key,
name text not null,
datetime integer not null,
created date not null default now())`);
}
async checkMigrationNameForExisting(name) {
const { rowCount } = await this.connection.query(`select name from ${this.tableName} where name = '${name}'`);
return !!rowCount;
}
async runMigrations() {
var e_1, _a;
await this.createTable();
await this.getMigrations();
try {
for (var _b = __asyncValues(this.migrations), _c; _c = await _b.next(), !_c.done;) {
const migration = _c.value;
if (await this.checkMigrationNameForExisting(migration.filename))
return new Error(`Double naming of migrations`);
await this.connection.query(`
begin;
${migration.script};
insert into ${this.tableName} (name, datetime)
values ('${migration.filename}', ${migration.datetime});
commit;
`);
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (_c && !_c.done && (_a = _b.return)) await _a.call(_b);
}
finally { if (e_1) throw e_1.error; }
}
}
}
exports.default = MigrationManager;
//# sourceMappingURL=MigrationManager.js.map