-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmigrate.js
More file actions
51 lines (43 loc) · 1.31 KB
/
migrate.js
File metadata and controls
51 lines (43 loc) · 1.31 KB
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
const Postgrator = require('postgrator')
const fs = require('fs')
console.info(`DATABASE_URL: ${process.env.DATABASE_URL}`)
const postgrator = new Postgrator({
driver: 'pg',
connectionString: process.env.DATABASE_URL,
ssl: false,
migrationDirectory: __dirname + '/migrations'
})
const action = process.argv[2]
const arg = process.argv[3]
let version = 0
try {
version = parseInt(
fs.readdirSync('migrations')
.filter(f => f.endsWith('sql'))
.sort()
.reverse()[0]
.slice(0, 3)
)
} catch (e) {}
if (action == 'migrate') {
const to = (arg || version.toString()).padStart(3, '0')
console.info(`migrating to ${to}`)
postgrator.migrate(to).then(console.info).catch(console.error)
} else if (action == 'create') {
console.info('creating migration')
const newVersion = (version + 1).toString().padStart(3, '0')
if (!arg) {
throw new Error('no name provided')
}
fs.writeFileSync(`./migrations/${newVersion}.do.${arg}.sql`, '')
fs.writeFileSync(`./migrations/${newVersion}.undo.${arg}.sql`, '')
} else if (action == 'drop') {
postgrator.runQuery(`
DROP SCHEMA public CASCADE;
CREATE SCHEMA public;
GRANT ALL ON SCHEMA public TO postgres;
GRANT ALL ON SCHEMA public TO public;
`).then(console.info).catch(console.error)
} else {
console.error('no argument supplied')
}