This repository has been archived by the owner on Dec 21, 2018. It is now read-only.
/
migrate.js
58 lines (45 loc) · 1.62 KB
/
migrate.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
var _ = require('underscore');
var fs = require('fs');
var path = require('path');
var existsSync = fs.existsSync || path.existsSync;
// Global config.
if (existsSync('./config.json')) {
config = require('./config.json');
}
config = _.extend({}, config || {});
if (config.pg.enabled) {
var pg = require('pg');
if (!config.pg.connstring) {
console.log("No connection string found. Checking for DATABASE_URL.");
config.pg.connstring = process.env.DATABASE_URL;
}
if (config.pg.connstring) {
console.log("Connecting to: " + config.pg.connstring);
var client = new pg.Client(config.pg.connstring);
client.connect();
}
if (client) {
var current = 0;
var query = client.query("SELECT id FROM pg_migrations " +
"ORDER BY id DESC LIMIT 1");
query.on('error', function(error) { /* Do nothing */ });
query.on('row', function(row) {
current = row.id;
});
query.on('end', function(result) {
current++;
while(existsSync('./migrations/' + current + '.js')) {
console.log('Running migration #' + current);
var migration = require('./migrations/' + current);
migration.upgrade(client);
client.query("INSERT INTO pg_migrations (id) values (" +
current + ")");
current++;
}
query = client.query("SELECT id FROM pg_migrations LIMIT 1");
query.on('end', function(result) {
client.end();
});
});
}
}