-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmigrate.ts
More file actions
81 lines (71 loc) · 2.18 KB
/
migrate.ts
File metadata and controls
81 lines (71 loc) · 2.18 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
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
import appRootPath from 'app-root-path';
import 'dotenv-flow/config';
import { promises as fs } from 'fs';
import { FileMigrationProvider, MigrationResult, Migrator } from 'kysely';
import * as path from 'path';
import { db } from './src/db/database';
function getMigrator() {
return new Migrator({
db,
provider: new FileMigrationProvider({
fs,
path,
// This needs to be an absolute path.
migrationFolder: path.resolve(appRootPath.path, 'src', 'db', 'migrations'),
}),
});
}
async function migrateDown() {
const migrator = getMigrator();
const { error, results } = await migrator.migrateDown();
results?.forEach((it) => {
if (it.status === 'Success') {
console.log(`down migration "${it.migrationName}" was executed successfully`);
} else if (it.status === 'Error') {
console.error(`failed to execute down migration "${it.migrationName}"`);
}
});
if (error) {
console.error('failed to migrate');
console.error(error);
process.exit(1);
}
}
async function migrateToLatest(steps?: number) {
const migrator = getMigrator();
let error: unknown,
results: MigrationResult[] | undefined = [];
if (steps !== undefined) {
for (let i = 0; i < steps; i++) {
const { error: innerError, results: innerResults } = await migrator.migrateUp();
if (innerResults) {
results.push(...innerResults);
}
if (innerError) {
error = innerError;
break;
}
}
} else {
({ error, results } = await migrator.migrateToLatest());
}
results?.forEach((it) => {
if (it.status === 'Success') {
console.log(`migration "${it.migrationName}" was executed successfully`);
} else if (it.status === 'Error') {
console.error(`failed to execute migration "${it.migrationName}"`);
}
});
if (error) {
console.error('failed to migrate');
console.error(error);
process.exit(1);
}
}
if (!process.argv[2]) {
migrateToLatest().then(() => db.destroy());
} else if (process.argv[2] === 'down') {
migrateDown().then(() => db.destroy());
} else if (process.argv[2] && !isNaN(+process.argv[2])) {
migrateToLatest(+process.argv[2]).then(() => db.destroy());
}