-
Notifications
You must be signed in to change notification settings - Fork 70
/
postgrator.js
291 lines (265 loc) · 8.84 KB
/
postgrator.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
import EventEmitter from "events";
import fs from "fs";
import { glob } from "glob";
import path from "path";
import { pathToFileURL } from "url";
import createClient from "./lib/createClient.js";
import {
fileChecksum,
sortMigrationsAsc,
sortMigrationsDesc,
} from "./lib/utils.js";
const DEFAULT_CONFIG = {
schemaTable: "schemaversion",
validateChecksums: true,
};
class Postgrator extends EventEmitter {
constructor(config) {
super();
this.config = Object.assign({}, DEFAULT_CONFIG, config);
this.migrations = [];
this.commonClient = createClient(this.config);
}
/**
* Reads all migrations from directory
*
* @returns {Promise} array of migration objects
*/
async getMigrations() {
const { migrationPattern, newline } = this.config;
const migrationFiles = await glob(migrationPattern);
let migrations = await Promise.all(
migrationFiles
.filter(
(file) =>
[".sql", ".js", ".mjs", ".cjs"].indexOf(path.extname(file)) >= 0
)
.sort()
.map(async (filename) => {
const basename = path.basename(filename);
const ext = path.extname(basename);
const basenameNoExt = path.basename(filename, ext);
let [version, action, name = ""] = basenameNoExt.split(".");
version = Number(version);
if (ext === ".sql") {
return {
version,
action,
filename,
name,
md5: fileChecksum(filename, newline),
getSql: () => fs.readFileSync(filename, "utf8"),
};
}
if (ext === ".js" || ext === ".cjs" || ext === ".mjs") {
const jsModule = await import(pathToFileURL(filename));
return {
version,
action,
filename,
name,
// JS files are dynamic, so resulting content could change
// Prettier and JS trends mean that formatting could also change over time
// Considering these things, md5 hashing for JS will be skipped.
md5: undefined,
getSql: () => jsModule.generateSql(),
};
}
})
);
migrations = migrations.filter((migration) => !isNaN(migration.version));
const getMigrationKey = (migration) =>
`${migration.version}:${migration.action}`;
const migrationKeys = new Set();
migrations.forEach((migration) => {
const newKey = getMigrationKey(migration);
if (migrationKeys.has(newKey)) {
throw new Error(
`Two migrations found with version ${migration.version} and action ${migration.action}`
);
}
migrationKeys.add(newKey);
});
this.migrations = migrations;
return migrations;
}
/**
* Executes sql query using the commonClient runQuery function
*
* @returns {Promise} result of query
* @param {String} query sql query to execute
*/
async runQuery(query) {
return this.commonClient.runQuery(query);
}
/**
* Executes db migration script consisting of multiple SQL statements
* using the commonClient runSqlScript function
*
* @returns {Promise} void
* @param {String} sqlScript sql queries to execute
*/
async runSqlScript(sqlScript) {
return this.commonClient.runSqlScript(sqlScript);
}
/**
* Gets the database version of the schema from the database.
* Otherwise 0 if no version has been run
*
* @returns {Promise} database schema version
*/
async getDatabaseVersion() {
const versionSql = this.commonClient.getDatabaseVersionSql();
const initialized = await this.commonClient.hasVersionTable();
if (!initialized) {
return 0;
}
const result = await this.commonClient.runQuery(versionSql);
const version = result.rows.length > 0 ? result.rows[0].version : 0;
return parseInt(version);
}
/**
* Returns an object with max version of migration available
*
* @returns {Promise}
*/
async getMaxVersion() {
let { migrations } = this;
if (!this.migrations.length) {
migrations = await this.getMigrations();
}
const versions = migrations.map((migration) => migration.version);
return Math.max.apply(null, versions);
}
/**
* Validate md5 checksums for applied migrations
*
* @returns {Promise}
* @param {Number} databaseVersion
*/
async validateMigrations(databaseVersion) {
const migrations = await this.getMigrations();
const validateMigrations = migrations.filter(
(migration) =>
migration.action === "do" &&
migration.version > 0 &&
migration.version <= databaseVersion
);
for (const migration of validateMigrations) {
this.emit("validation-started", migration);
const sql = this.commonClient.getMd5Sql(migration);
const results = await this.commonClient.runQuery(sql);
const md5 = results.rows && results.rows[0] && results.rows[0].md5;
// IF md5 exists in DB and on migration, it means we should validate the md5
// (JS migrations no longer generate an md5 because they can be so dynamic.
// Deleting an md5 from database could be useful for skipping a problematic check)
if (md5 && migration.md5 && md5 !== migration.md5) {
const msg = `MD5 checksum failed for migration [${migration.version}]`;
throw new Error(msg);
}
this.emit("validation-finished", migration);
}
return validateMigrations;
}
/**
* Runs the migrations in the order to reach target version
*
* @returns {Promise} - Array of migration objects to appled to database
* @param {Array} migrations - Array of migration objects to apply to database
*/
async runMigrations(migrations = []) {
const { commonClient } = this;
const appliedMigrations = [];
try {
for (const migration of migrations) {
this.emit("migration-started", migration);
const sql = await migration.getSql();
await commonClient.runSqlScript(sql);
await commonClient.runQuery(commonClient.persistActionSql(migration));
appliedMigrations.push(migration);
this.emit("migration-finished", migration);
}
} catch (error) {
error.appliedMigrations = appliedMigrations;
throw error;
}
return appliedMigrations;
}
/**
* returns an array of relevant migrations based on the target and database version passed.
* returned array is sorted in the order it needs to be run
*
* @returns {Array} Sorted array of relevant migration objects
* @param {Number} databaseVersion
* @param {Number} targetVersion
*/
getRunnableMigrations(databaseVersion, targetVersion) {
const { migrations } = this;
if (targetVersion >= databaseVersion) {
return migrations
.filter(
(migration) =>
migration.action === "do" &&
migration.version > databaseVersion &&
migration.version <= targetVersion
)
.sort(sortMigrationsAsc);
}
if (targetVersion < databaseVersion) {
return migrations
.filter(
(migration) =>
migration.action === "undo" &&
migration.version <= databaseVersion &&
migration.version > targetVersion
)
.sort(sortMigrationsDesc);
}
return [];
}
/**
* Main method to move a schema to a particular version.
* A target must be specified, otherwise the schema will be moved to the maximum available version.
*
* @returns {Promise}
* @param {String} target - version to migrate as string or number (handled as numbers internally)
*/
async migrate(target = "") {
const { commonClient, config } = this;
const data = {};
try {
await commonClient.ensureTable();
await this.getMigrations();
let targetVersion;
const cleaned = target.toLowerCase().trim();
if (cleaned === "max" || cleaned === "") {
targetVersion = await this.getMaxVersion();
} else {
targetVersion = Number(target);
}
data.targetVersion = targetVersion;
if (target === undefined) {
throw new Error("targetVersion undefined");
}
const databaseVersion = await this.getDatabaseVersion();
data.databaseVersion = databaseVersion;
if (config.validateChecksums && data.targetVersion >= databaseVersion) {
await this.validateMigrations(databaseVersion);
}
const runnableMigrations = await this.getRunnableMigrations(
data.databaseVersion,
data.targetVersion
);
const migrations = await this.runMigrations(runnableMigrations);
return migrations;
} catch (error) {
// Decorate error with empty appliedMigrations if not yet exist
// Rethrow error to module user
if (!error.appliedMigrations) {
error.appliedMigrations = [];
}
throw error;
}
}
}
export default Postgrator;