forked from rickbergfalk/postgrator
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpostgrator.js
More file actions
436 lines (371 loc) · 13.5 KB
/
postgrator.js
File metadata and controls
436 lines (371 loc) · 13.5 KB
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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
/*
API:
var postgrator = require('postgrator');
postgrator.setConfig({
driver: 'pg', // or pg.js, mysql, mssql, tedious
migrationDirectory: '',
logProgress: true,
schemaTable: '', // default is 'schemaversion'
host: '',
database: '',
username: '',
password: ''
});
postgrator.migrate(version, function (err, migrations) {
// handle the error, and if you want end the connection
postgrator.endConnection();
});
NOTES:
If the table specified by config.schemaTable is not present, it will be created automatically!
If no migration version is supplied, no migration is performed
THINGS TO IMPLEMENT SOMEDAY (MAYBE)
postgrator.migrate('max', callback); // migrate to the latest migration available
================================================================= */
var fs = require('fs');
var crypto = require('crypto');
var createCommonClient = require('./lib/create-common-client.js');
var commonClient;
var currentVersion;
var targetVersion;
var migrations = []; // array of objects like: {version: n, action: 'do', direction: 'up', filename: '0001.up.sql'}
var config = {};
exports.config = config;
/* Set Config
================================================================= */
exports.setConfig = function (configuration) {
config = configuration;
config.schemaTable = config.schemaTable || 'schemaversion';
commonClient = createCommonClient(config);
};
/* Migration Sorting Functions
================================================================= */
var sortMigrationsAsc = function (a,b) {
if (a.version < b.version)
return -1;
if (a.version > b.version)
return 1;
return 0;
};
var sortMigrationsDesc = function (a, b) {
if (a.version < b.version)
return 1;
if (a.version > b.version)
return -1;
return 0;
};
/*
getMigrations()
Internal function
Reads the migration directory for all the migration files.
It is SYNC out of laziness and simplicity
================================================================= */
var getMigrations = function () {
migrations = [];
var migrationFiles = fs.readdirSync(config.migrationDirectory);
migrationFiles.forEach(function(file) {
var m = file.split('.');
var name = m.length >= 3 ? m.slice(2, m.length - 1).join('.') : file;
if (m[m.length - 1] === 'sql') {
migrations.push({
version: Number(m[0]),
direction: m[1],
action: m[1],
filename: file,
name: name,
md5: fileChecksum(config.migrationDirectory + "/" + file, config.newline)
});
}
});
};
/* runQuery
connects the database driver if it is not currently connected.
Executes an arbitrary sql query using the common client
================================================================= */
function runQuery (query, cb) {
if (commonClient.connected) {
commonClient.runQuery(query, cb);
} else {
// connect common client
commonClient.createConnection(function (err) {
if (err) cb(err);
else {
commonClient.connected = true;
commonClient.runQuery(query, cb);
}
});
}
}
exports.runQuery = runQuery;
/* endConnection
Ends the commonClient's connection to the database
================================================================= */
function endConnection (cb) {
if (commonClient.connected) {
commonClient.endConnection(function () {
commonClient.connected = false;
cb();
});
} else {
cb();
}
}
exports.endConnection = endConnection;
/*
getCurrentVersion(callback)
Internal & External function
Gets the current version of the schema from the database.
================================================================= */
var getCurrentVersion = function (callback) {
runQuery(commonClient.queries.getCurrentVersion, function(err, result) {
if (err) { // means the table probably doesn't exist yet. To lazy to check.
console.error('something went wrong getting the Current Version from the ' + config.schemaTable + ' table');
} else {
if (result.rows.length > 0) currentVersion = result.rows[0].version;
else currentVersion = 0;
}
callback(err, currentVersion);
});
};
exports.getCurrentVersion = getCurrentVersion;
/*
getVersions(callback)
Internal & External function
Returns an object with the current applied version of the schema from
the database and the max version of migration available.
================================================================= */
var getVersions = function (callback) {
var versions = {};
getMigrations()
versions.max = Math.max.apply(null, migrations.map(function (migration) { return migration.version; }));
getCurrentVersion(function(err, version) {
if (err) {
console.log('Error in postgrator{isLatestVersion}');
console.log('Error:' + err)
} else {
versions.current = version;
}
callback(err, versions);
});
};
exports.getVersions = getVersions;
/*
runMigrations(migrations, finishedCallback)
Internal function
Runs the migrations in the order provided, using a recursive kind of approach
For each migration run:
- the contents of the script is read (sync because I'm lazy)
- script is run.
if error, the callback is called and we don't run anything else
if success, we then add/remove a record from the config.schemaTable to keep track of the migration we just ran
- if all goes as planned, we run the next migration
- once all migrations have been run, we call the callback.
================================================================= */
var runMigrations = function (migrations, currentVersion, targetVersion, finishedCallback) {
var runNext = function (i) {
var sql = fs.readFileSync((config.migrationDirectory + '/' + migrations[i].filename), 'utf8');
if (migrations[i].md5Sql) {
console.log('verifying checksum of migration ' + migrations[i].filename);
runQuery(migrations[i].md5Sql, function (err, result) {
if (err) {
console.log('Error in runMigrations() while retrieving existing migrations');
if (finishedCallback) {
finishedCallback(err, migrations);
}
} else {
if (result.rows[0].md5 && result.rows[0].md5 !== migrations[i].md5) {
console.log('Error in runMigrations() while verifying checksums of existing migrations');
if (finishedCallback) {
finishedCallback(new Error("For migration [" + migrations[i].version + "], expected MD5 checksum [" + migrations[i].md5 + "] but got [" + result.rows[0].md5 + "]"), migrations);
}
} else {
i = i + 1;
if (i < migrations.length) {
runNext(i);
} else {
if (finishedCallback) {
finishedCallback(null, migrations);
}
}
}
}
});
} else {
console.log('running ' + migrations[i].filename);
runQuery(sql, function (err, result) {
if (err) {
console.log('Error in runMigrations()');
if (finishedCallback) {
finishedCallback(err, migrations);
}
} else {
// migration ran successfully
// add version to config.schemaTable table.
runQuery(migrations[i].schemaVersionSQL, function (err, result) {
if (err) {
// SQL to update config.schemaTable failed.
console.log('error updating the ' + config.schemaTable + ' table');
console.log(err);
} else {
// config.schemaTable successfully recorded.
// move on to next migration
i = i + 1;
if (i < migrations.length) {
runNext(i);
} else {
// We are done running the migrations.
// run the finished callback if supplied.
if (finishedCallback) {
finishedCallback(null, migrations);
}
}
}
});
}
});
}
};
runNext(0);
};
/*
.getRelevantMigrations(currentVersion, targetVersion)
returns an array of relevant migrations based on the target and current version passed.
returned array is sorted in the order it needs to be run
================================================================= */
var getRelevantMigrations = function (currentVersion, targetVersion) {
var relevantMigrations = [];
if (targetVersion >= currentVersion) {
// we are migrating up
// get all up migrations > currentVersion and <= targetVersion
console.log('migrating up to ' + targetVersion);
migrations.forEach(function(migration) {
if (migration.action == 'do' && migration.version > 0 && migration.version <= currentVersion && (config.driver === 'pg' || config.driver === 'pg.js')) {
migration.md5Sql = 'SELECT md5 FROM ' + config.schemaTable + ' WHERE version = ' + migration.version + ';';
relevantMigrations.push(migration);
}
if (migration.action == 'do' && migration.version > currentVersion && migration.version <= targetVersion) {
migration.schemaVersionSQL = config.driver === 'pg' || config.driver === 'pg.js' ? "INSERT INTO "+config.schemaTable+" (version, name, md5) VALUES (" + migration.version + ", '" + migration.name + "', '" + migration.md5 + "');" : "INSERT INTO " + config.schemaTable + " (version) VALUES (" + migration.version + ");";
relevantMigrations.push(migration);
}
});
relevantMigrations = relevantMigrations.sort(sortMigrationsAsc);
} else if (targetVersion < currentVersion) {
// we are going to migrate down
console.log('migrating down to ' + targetVersion);
migrations.forEach(function(migration) {
if (migration.action == 'undo' && migration.version <= currentVersion && migration.version > targetVersion) {
migration.schemaVersionSQL = 'DELETE FROM ' + config.schemaTable + ' WHERE version = ' + migration.version + ';';
relevantMigrations.push(migration);
}
});
relevantMigrations = relevantMigrations.sort(sortMigrationsDesc);
}
return relevantMigrations;
};
/*
.migrate(target, callback)
Main method to move a schema to a particular version.
A target must be specified, otherwise nothing is run.
target - version to migrate to as string or number (will be handled as numbers internally)
callback - callback to run after migrations have finished. function (err, migrations) {}
================================================================= */
function migrate (target, finishedCallback) {
prep(function(err) {
if (err) {
if (finishedCallback) finishedCallback(err);
}
getMigrations();
if (target && target === 'max') {
targetVersion = Math.max.apply(null, migrations.map(function (migration) { return migration.version; }));
} else if (target) {
targetVersion = Number(target);
}
getCurrentVersion(function(err, currentVersion) {
if (err) {
console.log('error getting current version');
if (finishedCallback) finishedCallback(err);
} else {
console.log('version of database is: ' + currentVersion);
if (targetVersion === undefined) {
console.log('no target version supplied - no migrations performed');
} else {
var relevantMigrations = getRelevantMigrations(currentVersion, targetVersion);
if (relevantMigrations.length > 0) {
runMigrations(relevantMigrations, currentVersion, targetVersion, function(err, migrations) {
finishedCallback(err, migrations);
});
} else {
if (finishedCallback) finishedCallback(err);
}
}
}
}); // get current version
}); // prep
}
exports.migrate = migrate;
/*
.prep(callback)
Creates the table required for Postgrator to keep track of which migrations have been run.
callback - function called after schema version table is built. function (err, results) {}
================================================================= */
function prep (callback) {
runQuery(commonClient.queries.checkTable, function(err, result) {
if (err) {
err.helpfulDescription = 'Prep() table CHECK query Failed';
callback(err);
} else {
if (result.rows && result.rows.length > 0) {
if (config.driver === 'pg' || config.driver === 'pg.js') {
// config.schemaTable exists, does it have the md5 column? (PostgreSQL only)
runQuery("SELECT column_name, data_type, character_maximum_length FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = '" + config.schemaTable + "' AND column_name = 'md5';", function (err, result) {
if (err) {
err.helpfulDescription = 'Prep() table CHECK MD5 COLUMN query Failed';
callback(err);
} else {
if (!result.rows || result.rows.length === 0) {
// md5 column doesn't exist, add it
runQuery("ALTER TABLE " + config.schemaTable + " ADD COLUMN md5 text DEFAULT '';", function (err, result) {
if (err) {
err.helpfulDescription = 'Prep() table ADD MD5 COLUMN query Failed';
callback(err);
} else {
callback();
}
});
} else {
callback();
}
}
});
} else {
callback();
}
} else {
console.log('table ' + config.schemaTable + ' does not exist - creating it.');
runQuery(commonClient.queries.makeTable, function(err, result) {
if (err) {
err.helpfulDescription = 'Prep() table BUILD query Failed';
callback(err);
} else {
callback();
}
});
}
}
});
}
/*
.fileChecksum(filename)
Calculate checksum of file to detect changes to migrations that have already run.
filename - calculate MD5 checksum of contents of this file
================================================================= */
function fileChecksum (filename, newline) {
return checksum(fs.readFileSync(filename, 'utf8'), newline);
}
function checksum (str, nl) {
if (nl) {
var newline = require('newline');
console.log('Converting newline from: ', newline.detect(str), 'to:', nl);
str = newline.set(str, nl);
}
return crypto.createHash('md5').update(str, 'utf8').digest('hex');
}