forked from afloyd/mongo-migrate
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
399 lines (346 loc) · 9.02 KB
/
index.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
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
/**
* Arguments.
*/
var args = process.argv.slice(2);
/**
* Module dependencies.
*/
var migrate = require('./lib/migrate'),
path = require('path'),
join = path.join,
fs = require('fs'),
verror = require('verror');
/**
* Option defaults.
*/
var options = { args: [] };
/**
* Current working directory.
*/
var previousWorkingDirectory = process.cwd();
var configFileName = 'default-config.json',
dbConfig = null,
dbProperty = 'mongoAppDb',
trackingCollection = "migrations";
/**
* Usage information.
*/
var usage = [
''
, ' Usage: migrate [options] [command]'
, ''
, ' Options:'
, ''
, ' -runmm, --runMongoMigrate Run the migration from the command line'
, ' -dbc, --dbConfig JSON string containing db settings (overrides -c, -cfg, & -dbn)'
, ' --trackingCollection <collection_name> Change collction name to track already executed migrations'
, ' -c, --chdir <path> Change the working directory'
, ' -cfg, --config <path> DB config file name'
, ' -dbn, --dbPropName <string> Property name for database connection in config file'
, ''
, ' Commands:'
, ''
, ' down [name] migrate down till given migration'
, ' up [name] migrate up till given migration (the default command)'
, ' create [title] create a new migration file with optional [title]'
, ''
].join('\n');
/**
* Migration template.
*/
var template = [
''
, 'var mongodb = require(\'mongodb\');'
, ''
, 'exports.up = function(db, next){'
, ' next();'
, '};'
, ''
, 'exports.down = function(db, next){'
, ' next();'
, '};'
, ''
].join('\n');
/**
* require an argument
* @returns {*}
*/
function required() {
if (args.length) return args.shift();
abort(arg + ' requires an argument');
}
/**
* abort with a message
* @param msg
*/
function abort(msg) {
console.error(' %s', msg);
process.exit(1);
}
/**
* Log a keyed message.
*/
function log(key, msg) {
console.log(' \033[90m%s :\033[0m \033[36m%s\033[0m', key, msg);
}
/**
* Slugify the given `str`.
*/
function slugify(str) {
return str.replace(/\s+/g, '-');
}
/**
* Pad the given number.
*
* @param {Number} n
* @return {String}
*/
function pad(n) {
return Array(5 - n.toString().length).join('0') + n;
}
function runMongoMigrate(direction, migrationEnd, next) {
if (direction) {
options.command = direction;
}
if (migrationEnd) {
options.args.push(migrationEnd);
}
if (next) {
options.args.push(next);
}
/**
* Load migrations.
* @param {String} direction
* @param {Number} lastMigrationNum
* @param {Number} migrateTo
*/
function migrations(direction, lastMigrationNum, migrateTo) {
var isDirectionUp = direction === 'up',
hasMigrateTo = !!migrateTo,
migrateToNum = hasMigrateTo ? parseInt(migrateTo, 10) : undefined,
migrateToFound = !hasMigrateTo;
var migrationsToRun = fs.readdirSync('migrations')
.filter(function (file) {
var formatCorrect = file.match(/^\d+.*\.js$/),
migrationNum = formatCorrect && parseInt(file.match(/^\d+/)[0], 10),
isRunnable = formatCorrect && isDirectionUp ? migrationNum > lastMigrationNum : migrationNum <= lastMigrationNum,
isFile = fs.statSync(path.join('migrations', file)).isFile();
if (isFile && !formatCorrect) {
console.log('"' + file + '" ignored. Does not match migration naming schema');
}
return formatCorrect && isRunnable && isFile;
}).sort(function (a, b) {
var aMigrationNum = parseInt(a.match(/^\d+/)[0], 10),
bMigrationNum = parseInt(b.match(/^\d+/)[0], 10);
if (aMigrationNum > bMigrationNum) {
return isDirectionUp ? 1 : -1;
}
if (aMigrationNum < bMigrationNum) {
return isDirectionUp ? -1 : 1;
}
return 0;
}).filter(function(file){
var formatCorrect = file.match(/^\d+.*\.js$/),
migrationNum = formatCorrect && parseInt(file.match(/^\d+/)[0], 10),
isRunnable = formatCorrect && isDirectionUp ? migrationNum > lastMigrationNum : migrationNum <= lastMigrationNum;
if (hasMigrateTo) {
if (migrateToNum === migrationNum) {
migrateToFound = true;
}
if (isDirectionUp) {
isRunnable = isRunnable && migrateToNum >= migrationNum;
} else {
isRunnable = isRunnable && migrateToNum < migrationNum;
}
}
return formatCorrect && isRunnable;
}).map(function(file){
return 'migrations/' + file;
});
if (!migrateToFound) {
return abort('migration `'+ migrateTo + '` not found!');
}
return migrationsToRun;
}
// create ./migrations
try {
fs.mkdirSync('migrations', 0774);
} catch (err) {
// ignore
}
// commands
var commands = {
/**
* up
*/
up: function(migrateTo, next){
performMigration('up', migrateTo, next);
},
/**
* down
*/
down: function(migrateTo, next){
performMigration('down', migrateTo, next);
},
/**
* create [title]
*/
create: function(){
var migrations = fs.readdirSync('migrations').filter(function(file){
return file.match(/^\d+/);
}).map(function(file){
return parseInt(file.match(/^(\d+)/)[1], 10);
}).sort(function(a, b){
return a - b;
});
var curr = pad((migrations.pop() || 0) + 5),
title = slugify([].slice.call(arguments).join(' '));
title = title ? curr + '-' + title : curr;
create(title);
}
};
/**
* Create a migration with the given `name`.
*
* @param {String} name
*/
function create(name) {
var path = 'migrations/' + name + '.js';
log('create', join(process.cwd(), path));
fs.writeFileSync(path, template);
}
/**
* Perform a migration in the given `direction`.
*
* @param {String} direction
*/
function performMigration(direction, migrateTo, next) {
if (!next &&
Object.prototype.toString.call(migrateTo) === '[object Function]') {
next = migrateTo;
migrateTo = undefined;
}
if (!next) {
next = function(err) {
if (err) {
console.error(err);
process.exit(1);
} else {
process.exit();
}
}
}
var db = require('./lib/db');
db.getConnection(trackingCollection, dbConfig || require(process.cwd() + path.sep + configFileName)[dbProperty], function (err, db) {
if (err) {
return next(new verror.WError(err, 'Error connecting to database'));
}
var migrationCollection = db.migrationCollection,
dbConnection = db.connection;
migrationCollection.find({}).sort({num: -1}).limit(1).toArray(function (err, migrationsRun) {
if (err) {
return next(new verror.WError(err, 'Error querying migration collection'));
}
var lastMigration = migrationsRun[0],
lastMigrationNum = lastMigration ? lastMigration.num : 0;
migrate({
migrationTitle: 'migrations/.migrate',
db: dbConnection,
migrationCollection: migrationCollection
});
migrations(direction, lastMigrationNum, migrateTo).forEach(function(path){
var mod = require(process.cwd() + '/' + path);
migrate({
num: parseInt(path.split('/')[1].match(/^(\d+)/)[0], 10),
title: path,
up: mod.up,
down: mod.down});
});
//Revert working directory to previous state
process.chdir(previousWorkingDirectory);
var set = migrate();
set.on('migration', function(migration, direction){
log(direction, migration.title);
});
set.on('save', function(){
log('migration', 'complete');
return next();
});
set[direction](null, lastMigrationNum);
});
});
}
// invoke command
var command = options.command || 'up';
if (!(command in commands)) abort('unknown command "' + command + '"');
command = commands[command];
command.apply(this, options.args);
}
function chdir(dir) {
process.chdir(dir);
}
function setConfigFilename(filename) {
configFileName = filename;
}
function setConfigFileProperty(propertyName) {
dbProperty = propertyName;
}
function setDbConfig(conf) {
dbConfig = JSON.parse(conf);
}
function setTrackingCollection(collectionName) {
trackingCollection = collectionName;
}
var runmmIdx = args.indexOf('-runmm'),
runMongoMigrateIdx = args.indexOf('--runMongoMigrate');
if (runmmIdx > -1 || runMongoMigrateIdx > -1) {
args.splice(runmmIdx > -1 ? runmmIdx : runMongoMigrateIdx, 1);
// parse arguments
var arg;
while (args.length) {
arg = args.shift();
switch (arg) {
case '-h':
case '--help':
case 'help':
console.log(usage);
process.exit();
break;
case '-dbc':
case '--dbConfig':
setDbConfig(required());
break;
case '-c':
case '--chdir':
chdir(required());
break;
case '-cfg':
case '--config':
setConfigFilename(required());
break;
case '-dbn':
case '--dbPropName':
setConfigFileProperty(required());
break;
case '--trackingCollection':
setTrackingCollection(required());
break;
default:
if (options.command) {
options.args.push(arg);
} else {
options.command = arg;
}
}
}
runMongoMigrate();
} else {
module.exports = {
run: runMongoMigrate,
changeWorkingDirectory: chdir,
setDbConfig: setDbConfig,
setConfigFilename: setConfigFilename,
setConfigFileProp: setConfigFileProperty,
trackingCollection: setTrackingCollection
};
}