-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
196 lines (172 loc) · 5.83 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
const fs = require('fs')
const path = require('path')
const _ = require('lodash')
const debug = require('debug')('marv:better-sqlite3-driver')
const pkg = require('./package.json')
const format = require('util').format
const supportedDirectives = ['audit', 'comment', 'skip']
module.exports = function(options) {
const config = _.merge({ table: 'migrations', connection: {} }, _.omit(options, 'logger'))
const logger = options.logger || console
const SQL = {
ensureMigrationsTables: load('ensure-migrations-tables.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'),
insertMigration: load('insert-migration.sql')
}
const sqlite3 = config.sqlite3 || require('better-sqlite3')
let lockClient
let migrationClient
let userClient
function connect(cb) {
const { path, options } = config.connection
lockClient = new sqlite3(path, options)
migrationClient = new sqlite3(path, options)
userClient = new sqlite3(path, options)
debug('Connecting to %s', getLoggableUrl())
attachDatabases(cb)
}
function disconnect(cb) {
debug('Disconnecting from %s', getLoggableUrl())
detachDatabases()
lockClient.close(),
migrationClient.close(),
userClient.close()
cb()
}
function attachDatabases(cb) {
const { databases } = config.connection
if (databases && _.isArray(databases)) {
for (let db of databases) {
const { path, as } = db
userClient.exec(`ATTACH DATABASE '${path}' as "${as}";`)
}
}
cb()
}
function detachDatabases(cb) {
const { databases } = config.connection
if (databases && _.isArray(databases)) {
for (let db of databases) {
const { as } = db
userClient.exec(`DETACH DATABASE "${as}";`)
}
}
if (cb) {
cb()
}
}
function dropMigrations(cb) {
try {
debug('Drop migrations ...')
migrationClient.exec(SQL.dropMigrationsTables)
cb(null)
} catch (err) {
return cb(err)
}
}
function ensureMigrations(cb) {
try {
debug('Ensure migrations ...')
migrationClient.exec(SQL.ensureMigrationsTables)
cb(null)
} catch (err) {
cb(err)
}
}
function lockMigrations(cb) {
try {
debug('Lock migrations ...')
lockClient.exec(SQL.lockMigrationsLockTable)
cb(null)
} catch (err) {
cb(err)
}
}
function unlockMigrations(cb) {
try {
debug('Unlock migrations ...')
lockClient.exec(SQL.unlockMigrationsLockTable)
setTimeout(() => {
cb()
}, 0)
} catch (err) {
cb(err)
}
}
function getMigrations(cb) {
try {
const rows = migrationClient.prepare(SQL.retrieveMigrations).all();
const result = rows.map(item => {
return {
...item,
timestamp: new Date(item.timestamp)
};
});
cb(null, result)
} catch (err) {
return cb(err)
}
}
function runMigration(migration, cb) {
_.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)
try {
userClient.exec(migration.script)
if (auditable(migration)) {
const stmt = migrationClient.prepare(SQL.insertMigration);
stmt.run(
migration.level,
migration.directives.comment || migration.comment,
migration.timestamp.getTime(),
migration.checksum,
migration.namespace || 'default'
);
}
cb()
} catch (err) {
cb(decorate(err, migration))
}
}
function checkDirectives(directives) {
var 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 (migration.hasOwnProperty('directives')) return !/^false$/i.test(migration.directives.audit)
if (migration.hasOwnProperty('audit')) {
if (!config.quiet) logger.warn("The 'audit' option is deprecated. Please use 'directives.audit' instead.")
return migration.audit !== false
}
return true
}
function load(filename) {
return fs.readFileSync(path.join(__dirname, 'sql', filename), 'utf-8').replace(/migrations/g, config.table)
}
function decorate(err, migration) {
return _.merge(err, { migration: migration })
}
function getLoggableUrl() {
return format('sqlite3:%s', userClient.memory ? ':memory:' : userClient.name)
}
return {
connect,
disconnect,
dropMigrations,
ensureMigrations,
lockMigrations,
unlockMigrations,
getMigrations,
runMigration
}
}