-
Notifications
You must be signed in to change notification settings - Fork 80
/
Copy pathdrop-db.js
46 lines (39 loc) · 1.16 KB
/
drop-db.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
const { createClient, getConfig, getEnv } = require('../server/db')
// See https://www.postgresql.org/docs/13/errcodes-appendix.html
const INVALID_CATALOG_NAME_ERROR = '3D000'
destroyDatabase()
async function destroyDatabase() {
const targetEnv = getEnv()
if (targetEnv === 'production') {
throw new Error('This script should not be used in production!')
}
const config = getConfig(targetEnv)
await dropDatabase(config)
}
async function dropDatabase(config) {
const { database } = config.connection
let db
try {
// Connect with system database selected
db = createClient({
...config,
connection: {
...config.connection,
database: 'postgres'
}
})
// Drop the database if it exists
await db.raw(`DROP DATABASE ${database}`)
console.log(`Dropped database "${database}"!`)
} catch (error) {
if (error.code === INVALID_CATALOG_NAME_ERROR) {
console.warn(`Error dropping database "${database}": it does not exist!`)
} else {
console.error(`Error dropping database "${database}": ${error.message}`)
throw error
}
} finally {
// Disconnect
await db.destroy()
}
}