/
storage.js
87 lines (75 loc) · 2 KB
/
storage.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
const invariant = require('invariant')
const { get } = require('lodash')
function tableDoesNotExist (err, table) {
return (
err.code === 'ER_NO_SUCH_TABLE' ||
new RegExp(`relation "${table}" does not exist`).test(err.message) ||
new RegExp(`no such table: ${table}`).test(err.message)
)
}
module.exports = class KnexStorage {
constructor (options) {
this.knex = options.connection
this.tableName = get(
this.knex,
'client.config.migrations.tableName',
'knex_migrations'
)
invariant(
this.knex,
"The option 'options.storageOptions.connection' is required."
)
}
ensureTable () {
return this.knex(this.tableName)
.count('id')
.catch(err => {
if (tableDoesNotExist(err, this.tableName)) {
return this.knex.schema.createTable(this.tableName, table => {
table.increments()
table.string('name')
table.integer('batch')
table.dateTime('migration_time')
})
}
throw err
})
}
async logMigration (migrationName) {
if (typeof this.currentBatch === 'undefined') {
this.currentBatch = this.getCurrentBatch()
}
const currentBatch = await this.currentBatch
return this.knex(this.tableName).insert({
name: migrationName,
batch: currentBatch + 1,
migration_time: new Date() // eslint-disable-line camelcase
})
}
unlogMigration (migrationName) {
return this.knex(this.tableName)
.where('name', migrationName)
.del()
}
migrations () {
return this.knex(this.tableName)
.select()
.orderBy('id', 'asc')
}
executed () {
return this.knex(this.tableName)
.orderBy('id', 'asc')
.pluck('name')
.catch(err => {
if (tableDoesNotExist(err, this.tableName)) {
return []
}
throw err
})
}
getCurrentBatch () {
return this.knex(this.tableName)
.max('batch as max_batch')
.then(obj => obj[0].max_batch || 0)
}
}