-
Notifications
You must be signed in to change notification settings - Fork 5
/
index.js
198 lines (172 loc) · 5.86 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
const fs = require('fs');
const path = require('path');
const _ = require('lodash');
const async = require('async');
const { format } = require('util');
const debug = require('debug')('marv:pg-driver');
const supportedDirectives = ['audit', 'comment', 'skip'];
const pkg = require('./package.json');
module.exports = (options) => {
const config = _.merge({ table: 'migrations', connection: {} }, _.omit(options, 'logger'));
const logger = options.logger || console;
const SQL = {
ensureMigrationsTables: load('ensure-migrations-tables.sql'),
checkNamespaceColumn: load('check-namespace-column.sql'),
addNamespaceColumn: load('add-namespace-column.sql'),
retrieveMigrations: load('retrieve-migrations.sql'),
dropMigrationsTables: load('drop-migrations-tables.sql'),
lockMigrationsLockTable: load('lock-migrations-lock-table.sql'),
unlockMigrationsLockTable: load('unlock-migrations-lock-table.sql'),
acquireLock: load('acquire-lock.sql'),
releaseLock: load('release-lock.sql'),
insertMigration: load('insert-migration.sql'),
};
const pg = config.pg || require('pg');
let lockClient;
let migrationClient;
let userClient;
function connect(cb) {
lockClient = new pg.Client(config.connection);
migrationClient = new pg.Client(config.connection);
userClient = new pg.Client(config.connection);
debug('Connecting to %s', getLoggableUrl());
// prettier-ignore
async.series([
lockClient.connect.bind(lockClient),
migrationClient.connect.bind(migrationClient),
userClient.connect.bind(userClient)
], guard(cb));
}
function disconnect(cb) {
debug('Disconnecting from %s', getLoggableUrl());
// prettier-ignore
async.series([
lockClient.end.bind(lockClient),
migrationClient.end.bind(migrationClient),
userClient.end.bind(userClient)
],guard(cb));
}
function dropMigrations(cb) {
migrationClient.query(SQL.dropMigrationsTables, guard(cb));
}
function ensureMigrations(cb) {
debug('Ensure migrations');
// prettier-ignore
async.series([
ensureMigrationsTables.bind(null, true),
lockMigrations,
migrationClient.query.bind(migrationClient, SQL.checkNamespaceColumn)
], ensureNamespace);
function ensureMigrationsTables(firstRun, cb) {
migrationClient.query(SQL.ensureMigrationsTables, (err) => {
if (firstRun && err && err.code === '23505') {
debug('Possible race condition when creating migration tables - retrying.');
setTimeout(ensureMigrationsTables.bind(null, false, cb), 100);
} else {
cb(err);
}
});
}
function ensureNamespace(err, results) {
if (err) return cb(err);
const steps = [];
if (_.last(results).rows.length === 0) {
debug('Adding namespace column');
steps.push(migrationClient.query.bind(migrationClient, SQL.addNamespaceColumn));
}
steps.push(unlockMigrations);
async.series(steps, guard(cb));
}
}
function lockMigrations(cb) {
lockClient.query(SQL.lockMigrationsLockTable, guard(cb));
}
function unlockMigrations(cb) {
lockClient.query(SQL.unlockMigrationsLockTable, guard(cb));
}
function getMigrations(cb) {
migrationClient.query(SQL.retrieveMigrations, (err, result) => {
if (err) return cb(err);
cb(null, result.rows);
});
}
function runMigration(migration, cb) {
debug('Run migration');
_.defaults(migration, { directives: {} });
checkDirectives(migration.directives);
if (/^true$/i.test(migration.directives.skip)) {
debug('Skipping migration %s: %s\n%s', migration.level, migration.comment, migration.script);
return cb();
}
debug('Run migration %s: %s\n%s', migration.level, migration.comment, migration.script);
userClient.query(migration.script, (err) => {
if (err) return cb(decorate(err, migration));
if (auditable(migration)) {
return migrationClient.query(
SQL.insertMigration,
[
migration.level,
migration.directives.comment || migration.comment,
migration.timestamp,
migration.checksum,
migration.namespace || 'default',
],
(err) => {
if (err) return cb(decorate(err, migration));
cb();
}
);
}
cb();
});
}
function checkDirectives(directives) {
const unsupportedDirectives = _.chain(directives).keys().difference(supportedDirectives).value();
if (unsupportedDirectives.length === 0) return;
if (!config.quiet) {
logger.warn('Ignoring unsupported directives: %s. Try upgrading %s.', unsupportedDirectives, pkg.name);
}
}
function auditable(migration) {
if (hasOwnProperty(migration, 'directives')) return !/^false$/i.test(migration.directives.audit);
if (hasOwnProperty(migration, 'audit')) {
if (!config.quiet) logger.warn("The 'audit' option is deprecated. Please use 'directives.audit' instead.");
return migration.audit !== false;
}
return true;
}
function getLoggableUrl() {
return format(
'postgres://%s:%s@%s:%s/%s',
userClient.connectionParameters.user,
'******',
userClient.connectionParameters.host,
userClient.connectionParameters.port,
userClient.connectionParameters.database
);
}
function load(filename) {
return fs.readFileSync(path.join(__dirname, 'sql', filename), 'utf-8').replace(/migrations/g, config.table);
}
function guard(cb) {
return (err) => {
cb(err);
};
}
function decorate(err, migration) {
return _.merge(err, { migration });
}
function hasOwnProperty(obj, prop) {
return Object.prototype.hasOwnProperty.call(obj, prop);
}
return {
connect,
disconnect,
dropMigrations,
ensureMigrations,
lockMigrations,
unlockMigrations,
getMigrations,
runMigration,
};
};