-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmigrate_down.js
More file actions
55 lines (50 loc) · 1.41 KB
/
migrate_down.js
File metadata and controls
55 lines (50 loc) · 1.41 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
52
53
54
55
import { readdir } from 'node:fs/promises'
import { closeDbConnection, runSql } from './lib/mysql'
import { cOk, cWarn, cError } from './lib/console'
//Getting all executed migrations
const [rows] = await runSql(() => `
SELECT *
FROM migrations
ORDER BY id DESC
LIMIT 1
`)
const executedMigrations = rows.map(item => item.migration)
if (executedMigrations.length > 0) {
const file = executedMigrations[0]
const { down } = await import(`./migrations/${file}`)
try {
if (typeof down() !== 'undefined' &&
down()?.replace(/[\n\r]+/g, '').replace(/\s{2,10}/g, ' ').length > 0) {
await runSql(down)
await runSql(() => `
DELETE
FROM migrations
WHERE migration = '${file}'
`)
cOk(`${file} migrate rollback!`)
} else {
cWarn(`${file} rollback migrate has empty sql!`)
const prompt = 'Continue? [y,N]'
process.stdout.write(prompt)
for await (const line of console) {
if (line === 'y') {
await runSql(() => `
DELETE
FROM migrations
WHERE migration = '${file}'
`)
cOk(`${file} migrate rollback!`)
}
break
}
}
} catch
(e) {
cError(`${file} migrate rollback is crashed!`)
console.table(e)
}
} else {
cWarn(`No one files to rollback!`)
}
//Closing mysql db connection for exit from this script
closeDbConnection()