This repository has been archived by the owner on Mar 18, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 12
/
migrate.ts
201 lines (172 loc) · 5.38 KB
/
migrate.ts
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
'use strict';
require('dotenv').config();
import * as path from 'path';
import * as childProcess from 'child_process';
import * as Promise from 'bluebird';
import { databaseConfig } from "./src/modules/common/config/database";
import { Sequelize } from "sequelize-typescript";
const Umzug = require('umzug');
const DB_NAME = process.env.DB_NAME;
const DB_USER = process.env.DB_USER;
let config;
switch (process.env.NODE_ENV) {
case 'prod':
case 'production':
config = databaseConfig.production;
case 'dev':
case 'development':
config = databaseConfig.development;
case 'test':
config = databaseConfig.test;
default:
config = databaseConfig.development;
}
const sequelize = new Sequelize(config);
const umzug = new Umzug({
storage: 'sequelize',
storageOptions: { sequelize },
// see: https://github.com/sequelize/umzug/issues/17
migrations: {
params: [
sequelize,
sequelize.constructor, // DataTypes
function () {
throw new Error('Migration tried to use old style "done" callback. Please upgrade to "umzug" and return a promise instead.');
}
],
path: './src/modules/common/migrations',
pattern: /\.ts$/
},
logging: function () {
console.log.apply(null, arguments);
}
});
function logUmzugEvent (eventName) {
return function (name, migration) {
console.log(`${ name } ${ eventName }`);
};
}
umzug.on('migrating', logUmzugEvent('migrating'));
umzug.on('migrated', logUmzugEvent('migrated'));
umzug.on('reverting', logUmzugEvent('reverting'));
umzug.on('reverted', logUmzugEvent('reverted'));
function cmdStatus () {
let result: any = {};
return umzug.executed()
.then(executed => {
result.executed = executed;
return umzug.pending();
}).then(pending => {
result.pending = pending;
return result;
}).then(({ executed, pending }) => {
executed = executed.map(m => {
m.name = path.basename(m.file, '.ts');
return m;
});
pending = pending.map(m => {
m.name = path.basename(m.file, '.ts');
return m;
});
const current = executed.length > 0 ? executed[0].file : '<NO_MIGRATIONS>';
const status = {
current: current,
executed: executed.map(m => m.file),
pending: pending.map(m => m.file)
};
console.log(JSON.stringify(status, null, 2));
return { executed, pending };
});
}
function cmdMigrate () {
return umzug.up();
}
function cmdMigrateNext () {
return cmdStatus()
.then(({ executed, pending }) => {
if (pending.length === 0) {
return Promise.reject(new Error('No pending migrations'));
}
const next = pending[0].name;
return umzug.up({ to: next });
});
}
function cmdReset () {
return umzug.down({ to: 0 });
}
function cmdResetPrev () {
return cmdStatus()
.then(({ executed, pending }) => {
if (executed.length === 0) {
return Promise.reject(new Error('Already at initial state'));
}
const prev = executed[executed.length - 1].name;
return umzug.down({ to: prev });
});
}
function cmdHardReset () {
return new Promise((resolve, reject) => {
setImmediate(() => {
try {
console.log(`dropdb ${ DB_NAME }`);
childProcess.spawnSync(`dropdb ${ DB_NAME }`);
console.log(`createdb ${ DB_NAME } --username ${ DB_USER }`);
childProcess.spawnSync(`createdb ${ DB_NAME } --username ${ DB_USER }`);
resolve();
} catch (e) {
console.log(e);
reject(e);
}
});
});
}
const cmd = process.argv[2].trim();
let executedCmd;
console.log(`${ cmd.toUpperCase() } BEGIN`);
switch (cmd) {
case 'status':
executedCmd = cmdStatus();
break;
case 'up':
case 'migrate':
executedCmd = cmdMigrate();
break;
case 'next':
case 'migrate-next':
executedCmd = cmdMigrateNext();
break;
case 'down':
case 'reset':
executedCmd = cmdReset();
break;
case 'prev':
case 'reset-prev':
executedCmd = cmdResetPrev();
break;
case 'reset-hard':
executedCmd = cmdHardReset();
break;
default:
console.log(`invalid cmd: ${ cmd }`);
process.exit(1);
}
executedCmd
.then((result) => {
const doneStr = `${ cmd.toUpperCase() } DONE`;
console.log(doneStr);
console.log('==============================================================================');
})
.catch(err => {
const errorStr = `${ cmd.toUpperCase() } ERROR`;
console.log(errorStr);
console.log('==============================================================================');
console.log(err);
console.log('==============================================================================');
})
.then(() => {
if (cmd !== 'status' && cmd !== 'reset-hard') {
return cmdStatus();
}
return Promise.resolve();
})
.then(() => process.exit(0));