sonamu 0.0.3 → 0.0.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/dist/database/f9-base-model.d.ts +0 -39
- package/dist/database/f9-base-model.d.ts.map +0 -1
- package/dist/database/f9-base-model.js +0 -229
- package/dist/database/f9-base-model.js.map +0 -1
- package/dist/database/f9-db.d.ts +0 -23
- package/dist/database/f9-db.d.ts.map +0 -1
- package/dist/database/f9-db.js +0 -109
- package/dist/database/f9-db.js.map +0 -1
- package/dist/exceptions/exceptions.d.ts +0 -48
- package/dist/exceptions/exceptions.d.ts.map +0 -1
- package/dist/exceptions/exceptions.js +0 -105
- package/dist/exceptions/exceptions.js.map +0 -1
- package/dist/exceptions/f9-exception.d.ts +0 -48
- package/dist/exceptions/f9-exception.d.ts.map +0 -1
- package/dist/exceptions/f9-exception.js +0 -105
- package/dist/exceptions/f9-exception.js.map +0 -1
- package/dist/exceptions/index.d.ts +0 -3
- package/dist/exceptions/index.d.ts.map +0 -1
- package/dist/exceptions/index.js +0 -19
- package/dist/exceptions/index.js.map +0 -1
- package/dist/f9-md/f9-md.d.ts +0 -29
- package/dist/f9-md/f9-md.d.ts.map +0 -1
- package/dist/f9-md/f9-md.js +0 -148
- package/dist/f9-md/f9-md.js.map +0 -1
- package/dist/f9-md/index.d.ts +0 -5
- package/dist/f9-md/index.d.ts.map +0 -1
- package/dist/f9-md/index.js +0 -21
- package/dist/f9-md/index.js.map +0 -1
- package/dist/f9-md/md-utils.d.ts +0 -55
- package/dist/f9-md/md-utils.d.ts.map +0 -1
- package/dist/f9-md/md-utils.js +0 -104
- package/dist/f9-md/md-utils.js.map +0 -1
- package/dist/f9-md/migrator.d.ts +0 -79
- package/dist/f9-md/migrator.d.ts.map +0 -1
- package/dist/f9-md/migrator.js +0 -1084
- package/dist/f9-md/migrator.js.map +0 -1
- package/dist/f9-md/model-definition.d.ts +0 -40
- package/dist/f9-md/model-definition.d.ts.map +0 -1
- package/dist/f9-md/model-definition.js +0 -409
- package/dist/f9-md/model-definition.js.map +0 -1
- package/dist/templates/bridge.template.d.ts +0 -17
- package/dist/templates/bridge.template.d.ts.map +0 -1
- package/dist/templates/bridge.template.js +0 -79
- package/dist/templates/bridge.template.js.map +0 -1
- package/dist/templates/md.template.d.ts +0 -17
- package/dist/templates/md.template.d.ts.map +0 -1
- package/dist/templates/md.template.js +0 -45
- package/dist/templates/md.template.js.map +0 -1
- package/dist/testing/f9-fixture-manager.d.ts +0 -16
- package/dist/testing/f9-fixture-manager.d.ts.map +0 -1
- package/dist/testing/f9-fixture-manager.js +0 -211
- package/dist/testing/f9-fixture-manager.js.map +0 -1
- package/dist/types/index.d.ts +0 -2
- package/dist/types/index.d.ts.map +0 -1
- package/dist/types/index.js +0 -18
- package/dist/types/index.js.map +0 -1
- package/dist/types/shared.d.ts +0 -725
- package/dist/types/shared.d.ts.map +0 -1
- package/dist/types/shared.js +0 -288
- package/dist/types/shared.js.map +0 -1
- package/dist/utils/f9-cache.d.ts +0 -1
- package/dist/utils/f9-cache.d.ts.map +0 -1
- package/dist/utils/f9-cache.js +0 -113
- package/dist/utils/f9-cache.js.map +0 -1
- package/dist/utils/index.d.ts +0 -4
- package/dist/utils/index.d.ts.map +0 -1
- package/dist/utils/index.js +0 -20
- package/dist/utils/index.js.map +0 -1
- package/dist/utils/tf-utils.d.ts +0 -6
- package/dist/utils/tf-utils.d.ts.map +0 -1
- package/dist/utils/tf-utils.js +0 -67
- package/dist/utils/tf-utils.js.map +0 -1
package/dist/f9-md/migrator.js
DELETED
|
@@ -1,1084 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
3
|
-
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
4
|
-
return new (P || (P = Promise))(function (resolve, reject) {
|
|
5
|
-
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
6
|
-
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
7
|
-
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
8
|
-
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
9
|
-
});
|
|
10
|
-
};
|
|
11
|
-
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
12
|
-
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
13
|
-
};
|
|
14
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
15
|
-
exports.F9Migrator = void 0;
|
|
16
|
-
const lodash_1 = require("lodash");
|
|
17
|
-
const knex_1 = __importDefault(require("knex"));
|
|
18
|
-
const prettier_1 = __importDefault(require("prettier"));
|
|
19
|
-
const chalk_1 = __importDefault(require("chalk"));
|
|
20
|
-
const luxon_1 = require("luxon");
|
|
21
|
-
const fs_1 = require("fs");
|
|
22
|
-
const fast_deep_equal_1 = __importDefault(require("fast-deep-equal"));
|
|
23
|
-
const inflection_1 = require("inflection");
|
|
24
|
-
const prompts_1 = __importDefault(require("prompts"));
|
|
25
|
-
const child_process_1 = require("child_process");
|
|
26
|
-
const path_1 = __importDefault(require("path"));
|
|
27
|
-
const shared_1 = require("../types/shared");
|
|
28
|
-
const lodash_able_1 = require("../utils/lodash-able");
|
|
29
|
-
const smd_manager_1 = require("../smd/smd-manager");
|
|
30
|
-
class F9Migrator {
|
|
31
|
-
constructor(options) {
|
|
32
|
-
this.appRootPath = options.appRootPath;
|
|
33
|
-
this.knexfile = options.knexfile;
|
|
34
|
-
this.mode = options.mode;
|
|
35
|
-
if (this.mode === "dev") {
|
|
36
|
-
const devDB = (0, knex_1.default)(this.knexfile.development_master);
|
|
37
|
-
const testDB = (0, knex_1.default)(this.knexfile.test);
|
|
38
|
-
const fixtureLocalDB = (0, knex_1.default)(this.knexfile.fixture_local);
|
|
39
|
-
const applyDBs = [devDB, testDB, fixtureLocalDB];
|
|
40
|
-
if (this.knexfile.fixture_local.connection
|
|
41
|
-
.host !==
|
|
42
|
-
this.knexfile.fixture_remote.connection
|
|
43
|
-
.host) {
|
|
44
|
-
const fixtureRemoteDB = (0, knex_1.default)(this.knexfile.fixture_remote);
|
|
45
|
-
applyDBs.push(fixtureRemoteDB);
|
|
46
|
-
}
|
|
47
|
-
this.targets = {
|
|
48
|
-
compare: devDB,
|
|
49
|
-
pending: devDB,
|
|
50
|
-
shadow: testDB,
|
|
51
|
-
apply: applyDBs,
|
|
52
|
-
};
|
|
53
|
-
}
|
|
54
|
-
else if (this.mode === "deploy") {
|
|
55
|
-
const productionDB = (0, knex_1.default)(this.knexfile.production_master);
|
|
56
|
-
const testDB = (0, knex_1.default)(this.knexfile.test);
|
|
57
|
-
this.targets = {
|
|
58
|
-
pending: productionDB,
|
|
59
|
-
shadow: testDB,
|
|
60
|
-
apply: [productionDB],
|
|
61
|
-
};
|
|
62
|
-
}
|
|
63
|
-
else {
|
|
64
|
-
throw new Error(`잘못된 모드 ${this.mode} 입력`);
|
|
65
|
-
}
|
|
66
|
-
}
|
|
67
|
-
clearPendingList() {
|
|
68
|
-
return __awaiter(this, void 0, void 0, function* () {
|
|
69
|
-
const [, pendingList] = (yield this.targets.pending.migrate.list());
|
|
70
|
-
const migrationsDir = `${this.appRootPath}/api/src/migrations`;
|
|
71
|
-
const delList = pendingList.map((df) => {
|
|
72
|
-
return path_1.default.join(migrationsDir, df.file).replace(".js", ".ts");
|
|
73
|
-
});
|
|
74
|
-
for (let p of delList) {
|
|
75
|
-
if ((0, fs_1.existsSync)(p)) {
|
|
76
|
-
(0, fs_1.unlinkSync)(p);
|
|
77
|
-
}
|
|
78
|
-
}
|
|
79
|
-
yield this.cleanUpDist(true);
|
|
80
|
-
});
|
|
81
|
-
}
|
|
82
|
-
run() {
|
|
83
|
-
return __awaiter(this, void 0, void 0, function* () {
|
|
84
|
-
// pending 마이그레이션 확인
|
|
85
|
-
const [, pendingList] = yield this.targets.pending.migrate.list();
|
|
86
|
-
if (pendingList.length > 0) {
|
|
87
|
-
console.log(chalk_1.default.red("pending 된 마이그레이션이 존재합니다."), pendingList.map((pending) => pending.file));
|
|
88
|
-
// pending이 있는 경우 Shadow DB 테스트 진행 여부 컨펌
|
|
89
|
-
const answer = yield (0, prompts_1.default)({
|
|
90
|
-
type: "confirm",
|
|
91
|
-
name: "value",
|
|
92
|
-
message: "Shadow DB 테스트를 진행하시겠습니까?",
|
|
93
|
-
initial: true,
|
|
94
|
-
});
|
|
95
|
-
if (answer.value === false) {
|
|
96
|
-
return;
|
|
97
|
-
}
|
|
98
|
-
console.time(chalk_1.default.blue("F9Migrator - runShadowTest"));
|
|
99
|
-
const result = yield this.runShadowTest();
|
|
100
|
-
console.timeEnd(chalk_1.default.blue("F9Migrator - runShadowTest"));
|
|
101
|
-
if (result === true) {
|
|
102
|
-
yield Promise.all(this.targets.apply.map((applyDb) => __awaiter(this, void 0, void 0, function* () {
|
|
103
|
-
const label = chalk_1.default.green(`APPLIED ${applyDb.client.connectionSettings.host} ${applyDb.client.database()}`);
|
|
104
|
-
console.time(label);
|
|
105
|
-
const [,] = yield applyDb.migrate.latest();
|
|
106
|
-
console.timeEnd(label);
|
|
107
|
-
})));
|
|
108
|
-
}
|
|
109
|
-
return;
|
|
110
|
-
}
|
|
111
|
-
// MD-DB간 비교하여 코드 생성 리턴
|
|
112
|
-
const codes = yield this.compareMigrations();
|
|
113
|
-
if (codes.length === 0) {
|
|
114
|
-
console.log(chalk_1.default.green("\n현재 모두 싱크된 상태입니다."));
|
|
115
|
-
return;
|
|
116
|
-
}
|
|
117
|
-
// 현재 생성된 코드 표기
|
|
118
|
-
console.table(codes, ["type", "title"]);
|
|
119
|
-
/* 디버깅용 코드
|
|
120
|
-
console.log(codes[0].formatted);
|
|
121
|
-
process.exit();
|
|
122
|
-
*/
|
|
123
|
-
// 실제 파일 생성 프롬프트
|
|
124
|
-
const answer = yield (0, prompts_1.default)({
|
|
125
|
-
type: "confirm",
|
|
126
|
-
name: "value",
|
|
127
|
-
message: "마이그레이션 코드를 생성하시겠습니까?",
|
|
128
|
-
initial: false,
|
|
129
|
-
});
|
|
130
|
-
if (answer.value === false) {
|
|
131
|
-
return;
|
|
132
|
-
}
|
|
133
|
-
// 실제 코드 생성
|
|
134
|
-
const migrationsDir = `${this.appRootPath}/api/src/migrations`;
|
|
135
|
-
codes
|
|
136
|
-
.filter((code) => code.formatted)
|
|
137
|
-
.map((code, index) => {
|
|
138
|
-
const dateTag = luxon_1.DateTime.local()
|
|
139
|
-
.plus({ seconds: index })
|
|
140
|
-
.toFormat("yyyyMMddHHmmss");
|
|
141
|
-
const filePath = `${migrationsDir}/${dateTag}_${code.title}.ts`;
|
|
142
|
-
(0, fs_1.writeFileSync)(filePath, code.formatted);
|
|
143
|
-
console.log(chalk_1.default.green(`MIGRTAION CRETATED ${filePath}`));
|
|
144
|
-
});
|
|
145
|
-
});
|
|
146
|
-
}
|
|
147
|
-
rollback() {
|
|
148
|
-
return __awaiter(this, void 0, void 0, function* () {
|
|
149
|
-
console.time(chalk_1.default.red("rollback:"));
|
|
150
|
-
const rollbackAllResult = yield Promise.all(this.targets.apply.map((db) => __awaiter(this, void 0, void 0, function* () {
|
|
151
|
-
yield db.migrate.forceFreeMigrationsLock();
|
|
152
|
-
return db.migrate.rollback(undefined, false);
|
|
153
|
-
})));
|
|
154
|
-
console.dir({ rollbackAllResult }, { depth: null });
|
|
155
|
-
console.timeEnd(chalk_1.default.red("rollback:"));
|
|
156
|
-
});
|
|
157
|
-
}
|
|
158
|
-
cleanUpDist(force = false) {
|
|
159
|
-
return __awaiter(this, void 0, void 0, function* () {
|
|
160
|
-
const files = ["src", "dist"].reduce((r, which) => {
|
|
161
|
-
const migrationPath = path_1.default.join(this.appRootPath, "api", which, "migrations");
|
|
162
|
-
if ((0, fs_1.existsSync)(migrationPath) === false) {
|
|
163
|
-
(0, fs_1.mkdirSync)(migrationPath, {
|
|
164
|
-
recursive: true,
|
|
165
|
-
});
|
|
166
|
-
}
|
|
167
|
-
const files = (0, fs_1.readdirSync)(migrationPath).filter((filename) => filename.startsWith(".") === false);
|
|
168
|
-
r[which] = files;
|
|
169
|
-
return r;
|
|
170
|
-
}, {
|
|
171
|
-
src: [],
|
|
172
|
-
dist: [],
|
|
173
|
-
});
|
|
174
|
-
const diffOnSrc = (0, lodash_1.differenceBy)(files.src, files.dist, (filename) => filename.split(".")[0]);
|
|
175
|
-
if (diffOnSrc.length > 0) {
|
|
176
|
-
throw new Error("컴파일 되지 않은 파일이 있습니다.\n" + diffOnSrc.join("\n"));
|
|
177
|
-
}
|
|
178
|
-
const diffOnDist = (0, lodash_1.differenceBy)(files.dist, files.src, (filename) => filename.split(".")[0]);
|
|
179
|
-
if (diffOnDist.length > 0) {
|
|
180
|
-
console.log(chalk_1.default.red("원본 ts파일을 찾을 수 없는 js파일이 있습니다."));
|
|
181
|
-
console.log(diffOnDist);
|
|
182
|
-
if (!force) {
|
|
183
|
-
const answer = yield (0, prompts_1.default)({
|
|
184
|
-
type: "confirm",
|
|
185
|
-
name: "value",
|
|
186
|
-
message: "삭제를 진행하시겠습니까?",
|
|
187
|
-
initial: true,
|
|
188
|
-
});
|
|
189
|
-
if (answer.value === false) {
|
|
190
|
-
return;
|
|
191
|
-
}
|
|
192
|
-
}
|
|
193
|
-
const filesToRm = diffOnDist.map((filename) => {
|
|
194
|
-
return path_1.default.join(this.appRootPath, "api", "dist", "migrations", filename);
|
|
195
|
-
});
|
|
196
|
-
filesToRm.map((filePath) => {
|
|
197
|
-
(0, fs_1.unlinkSync)(filePath);
|
|
198
|
-
});
|
|
199
|
-
console.log(chalk_1.default.green(`${filesToRm.length}건 삭제되었습니다!`));
|
|
200
|
-
}
|
|
201
|
-
});
|
|
202
|
-
}
|
|
203
|
-
runShadowTest() {
|
|
204
|
-
return __awaiter(this, void 0, void 0, function* () {
|
|
205
|
-
// ShadowDB 생성 후 테스트 진행
|
|
206
|
-
const tdb = (0, knex_1.default)(this.knexfile.test);
|
|
207
|
-
const tdbConn = this.knexfile.test.connection;
|
|
208
|
-
const shadowDatabase = tdbConn.database + "__migration_shadow";
|
|
209
|
-
const tmpSqlPath = `/tmp/${shadowDatabase}.sql`;
|
|
210
|
-
// 테스트DB 덤프 후 Database명 치환
|
|
211
|
-
console.log(chalk_1.default.magenta(`${tdbConn.database}의 데이터 ${tmpSqlPath}로 덤프`));
|
|
212
|
-
(0, child_process_1.execSync)(`mysqldump -h${tdbConn.host} -u${tdbConn.user} -p'${tdbConn.password}' ${tdbConn.database} --single-transaction --no-create-db --triggers > ${tmpSqlPath};`);
|
|
213
|
-
(0, child_process_1.execSync)(`sed -i'' -e 's/\`${tdbConn.database}\`/\`${shadowDatabase}\`/g' ${tmpSqlPath};`);
|
|
214
|
-
// 기존 ShadowDB 리셋
|
|
215
|
-
console.log(chalk_1.default.magenta(`${shadowDatabase} 리셋`));
|
|
216
|
-
yield tdb.raw(`DROP DATABASE IF EXISTS ${shadowDatabase};`);
|
|
217
|
-
yield tdb.raw(`CREATE DATABASE ${shadowDatabase};`);
|
|
218
|
-
// ShadowDB 테이블 + 데이터 생성
|
|
219
|
-
console.log(chalk_1.default.magenta(`${shadowDatabase} 데이터베이스 생성`));
|
|
220
|
-
(0, child_process_1.execSync)(`mysql -h${tdbConn.host} -u${tdbConn.user} -p'${tdbConn.password}' ${shadowDatabase} < ${tmpSqlPath};`);
|
|
221
|
-
// tdb 연결 종료
|
|
222
|
-
yield tdb.destroy();
|
|
223
|
-
// shadow db 테스트 진행
|
|
224
|
-
const sdb = (0, knex_1.default)(Object.assign(Object.assign({}, this.knexfile.test), { connection: Object.assign(Object.assign({}, tdbConn), { database: shadowDatabase }) }));
|
|
225
|
-
try {
|
|
226
|
-
const [batchNo, log] = yield sdb.migrate.latest();
|
|
227
|
-
console.log(chalk_1.default.green("Shadow DB 테스트에 성공했습니다!"), {
|
|
228
|
-
batchNo,
|
|
229
|
-
log,
|
|
230
|
-
});
|
|
231
|
-
// 생성한 Shadow DB 삭제
|
|
232
|
-
console.log(chalk_1.default.magenta(`${shadowDatabase} 삭제`));
|
|
233
|
-
yield sdb.raw(`DROP DATABASE IF EXISTS ${shadowDatabase};`);
|
|
234
|
-
return true;
|
|
235
|
-
}
|
|
236
|
-
catch (e) {
|
|
237
|
-
console.error(chalk_1.default.red("Shadow DB 테스트 진행 중 에러"), e);
|
|
238
|
-
return false;
|
|
239
|
-
}
|
|
240
|
-
finally {
|
|
241
|
-
yield sdb.destroy();
|
|
242
|
-
}
|
|
243
|
-
});
|
|
244
|
-
}
|
|
245
|
-
resetAll() {
|
|
246
|
-
return __awaiter(this, void 0, void 0, function* () {
|
|
247
|
-
const answer = yield (0, prompts_1.default)({
|
|
248
|
-
type: "confirm",
|
|
249
|
-
name: "value",
|
|
250
|
-
message: "모든 DB를 롤백하고 전체 마이그레이션 파일을 삭제하시겠습니까?",
|
|
251
|
-
initial: false,
|
|
252
|
-
});
|
|
253
|
-
if (answer.value === false) {
|
|
254
|
-
return;
|
|
255
|
-
}
|
|
256
|
-
console.time(chalk_1.default.red("rollback-all:"));
|
|
257
|
-
const rollbackAllResult = yield Promise.all(this.targets.apply.map((db) => __awaiter(this, void 0, void 0, function* () {
|
|
258
|
-
yield db.migrate.forceFreeMigrationsLock();
|
|
259
|
-
return db.migrate.rollback(undefined, true);
|
|
260
|
-
})));
|
|
261
|
-
console.log({ rollbackAllResult });
|
|
262
|
-
console.timeEnd(chalk_1.default.red("rollback-all:"));
|
|
263
|
-
const migrationsDir = `${this.appRootPath}/api/src/migrations`;
|
|
264
|
-
console.time(chalk_1.default.red("delete migration files"));
|
|
265
|
-
(0, child_process_1.execSync)(`rm -f ${migrationsDir}/*`);
|
|
266
|
-
(0, child_process_1.execSync)(`rm -f ${migrationsDir.replace("/src/", "/dist/")}/*`);
|
|
267
|
-
console.timeEnd(chalk_1.default.red("delete migration files"));
|
|
268
|
-
});
|
|
269
|
-
}
|
|
270
|
-
compareMigrations() {
|
|
271
|
-
return __awaiter(this, void 0, void 0, function* () {
|
|
272
|
-
// MD 순회하여 싱크
|
|
273
|
-
const mdIds = smd_manager_1.SMDManager.getAllIds();
|
|
274
|
-
// 조인테이블 포함하여 MD에서 MigrationSet 추출
|
|
275
|
-
const mdSetsWithJoinTable = mdIds
|
|
276
|
-
.filter((mdId) => {
|
|
277
|
-
const md = smd_manager_1.SMDManager.get(mdId);
|
|
278
|
-
return md.props.length > 0;
|
|
279
|
-
})
|
|
280
|
-
.map((mdId) => {
|
|
281
|
-
const md = smd_manager_1.SMDManager.get(mdId);
|
|
282
|
-
return this.getMigrationSetFromMD(md);
|
|
283
|
-
});
|
|
284
|
-
// 조인테이블만 추출
|
|
285
|
-
const joinTables = (0, lodash_1.uniqBy)(mdSetsWithJoinTable.map((mdSet) => mdSet.joinTables).flat(), (joinTable) => {
|
|
286
|
-
return joinTable.table;
|
|
287
|
-
});
|
|
288
|
-
// 조인테이블 포함하여 MigrationSet 배열
|
|
289
|
-
const mdSets = [...mdSetsWithJoinTable, ...joinTables];
|
|
290
|
-
let codes = (yield Promise.all(mdSets.map((mdSet) => __awaiter(this, void 0, void 0, function* () {
|
|
291
|
-
const dbSet = yield this.getMigrationSetFromDB(mdSet.table);
|
|
292
|
-
if (dbSet === null) {
|
|
293
|
-
// 기존 테이블 없음, 새로 테이블 생성
|
|
294
|
-
return [
|
|
295
|
-
this.generateCreateCode_ColumnAndIndexes(mdSet.table, mdSet.columns, mdSet.indexes),
|
|
296
|
-
...this.generateCreateCode_Foreign(mdSet.table, mdSet.foreigns),
|
|
297
|
-
];
|
|
298
|
-
}
|
|
299
|
-
// 기존 테이블 존재하는 케이스
|
|
300
|
-
const alterCodes = ["columnsAndIndexes", "foreigns"].map((key) => {
|
|
301
|
-
// 배열 원소의 순서가 달라서 불일치가 발생하는걸 방지하기 위해 각 항목별로 정렬 처리 후 비교
|
|
302
|
-
if (key === "columnsAndIndexes") {
|
|
303
|
-
const mdColumns = (0, lodash_1.sortBy)(mdSet.columns, (a) => a.name);
|
|
304
|
-
const dbColumns = (0, lodash_1.sortBy)(dbSet.columns, (a) => a.name);
|
|
305
|
-
/* 디버깅용 코드, 특정 컬럼에서 불일치 발생할 때 확인
|
|
306
|
-
const mdCreatedAt = mdSet.columns.find(
|
|
307
|
-
(col) => col.name === "created_at"
|
|
308
|
-
);
|
|
309
|
-
const dbCreatedAt = dbSet.columns.find(
|
|
310
|
-
(col) => col.name === "created_at"
|
|
311
|
-
);
|
|
312
|
-
console.debug({ mdCreatedAt, dbCreatedAt });
|
|
313
|
-
*/
|
|
314
|
-
const mdIndexes = (0, lodash_1.sortBy)(mdSet.indexes, (a) => a.columns.join("-"));
|
|
315
|
-
const dbIndexes = (0, lodash_1.sortBy)(dbSet.indexes, (a) => a.columns.join("-"));
|
|
316
|
-
const isEqualColumns = (0, fast_deep_equal_1.default)(mdColumns, dbColumns);
|
|
317
|
-
const isEqualIndexes = (0, fast_deep_equal_1.default)(mdIndexes, dbIndexes);
|
|
318
|
-
if (isEqualColumns && isEqualIndexes) {
|
|
319
|
-
return null;
|
|
320
|
-
}
|
|
321
|
-
else {
|
|
322
|
-
// this.showMigrationSet("MD", mdSet);
|
|
323
|
-
// this.showMigrationSet("DB", dbSet);
|
|
324
|
-
return this.generateAlterCode_ColumnAndIndexes(mdSet.table, mdColumns, mdIndexes, dbColumns, dbIndexes);
|
|
325
|
-
}
|
|
326
|
-
}
|
|
327
|
-
else {
|
|
328
|
-
const mdForeigns = (0, lodash_1.sortBy)(mdSet.foreigns, (a) => a.columns.join("-"));
|
|
329
|
-
const dbForeigns = (0, lodash_1.sortBy)(dbSet.foreigns, (a) => a.columns.join("-"));
|
|
330
|
-
if ((0, fast_deep_equal_1.default)(mdForeigns, dbForeigns) === false) {
|
|
331
|
-
// TODO FK alter
|
|
332
|
-
console.log(chalk_1.default.red(`FK 다름! ${mdSet.table}`));
|
|
333
|
-
// console.dir({ mdForeigns, dbForeigns }, { depth: null });
|
|
334
|
-
}
|
|
335
|
-
}
|
|
336
|
-
return null;
|
|
337
|
-
});
|
|
338
|
-
if (alterCodes.every((alterCode) => alterCode === null)) {
|
|
339
|
-
return null;
|
|
340
|
-
}
|
|
341
|
-
else {
|
|
342
|
-
return alterCodes.filter((alterCode) => alterCode !== null).flat();
|
|
343
|
-
}
|
|
344
|
-
}))))
|
|
345
|
-
.flat()
|
|
346
|
-
.filter((code) => code !== null);
|
|
347
|
-
/*
|
|
348
|
-
normal 타입이 앞으로, foreign 이 뒤로
|
|
349
|
-
*/
|
|
350
|
-
codes.sort((codeA, codeB) => {
|
|
351
|
-
if (codeA.type === "foreign" && codeB.type == "normal") {
|
|
352
|
-
return 1;
|
|
353
|
-
}
|
|
354
|
-
else if (codeA.type === "normal" && codeB.type === "foreign") {
|
|
355
|
-
return -1;
|
|
356
|
-
}
|
|
357
|
-
else {
|
|
358
|
-
return 0;
|
|
359
|
-
}
|
|
360
|
-
});
|
|
361
|
-
return codes;
|
|
362
|
-
});
|
|
363
|
-
}
|
|
364
|
-
/*
|
|
365
|
-
기존 테이블 정보 읽어서 MigrationSet 형식으로 리턴
|
|
366
|
-
*/
|
|
367
|
-
getMigrationSetFromDB(table) {
|
|
368
|
-
return __awaiter(this, void 0, void 0, function* () {
|
|
369
|
-
let dbColumns, dbIndexes, dbForeigns;
|
|
370
|
-
try {
|
|
371
|
-
[dbColumns, dbIndexes, dbForeigns] = yield this.readTable(table);
|
|
372
|
-
}
|
|
373
|
-
catch (e) {
|
|
374
|
-
return null;
|
|
375
|
-
}
|
|
376
|
-
const columns = dbColumns.map((dbColumn) => {
|
|
377
|
-
const dbColType = this.resolveDBColType(dbColumn.Type, dbColumn.Field);
|
|
378
|
-
return Object.assign(Object.assign({ name: dbColumn.Field, nullable: dbColumn.Null !== "NO" }, dbColType), (0, lodash_able_1.propIf)(dbColumn.Default !== null, {
|
|
379
|
-
defaultTo: dbColType.type === "float"
|
|
380
|
-
? parseFloat(dbColumn.Default).toString()
|
|
381
|
-
: dbColumn.Default,
|
|
382
|
-
}));
|
|
383
|
-
});
|
|
384
|
-
const dbIndexesGroup = (0, lodash_1.groupBy)(dbIndexes.filter((dbIndex) => dbIndex.Key_name !== "PRIMARY" &&
|
|
385
|
-
!dbForeigns.find((dbForeign) => dbForeign.keyName === dbIndex.Key_name)), (dbIndex) => dbIndex.Key_name);
|
|
386
|
-
// indexes 처리
|
|
387
|
-
const indexes = Object.keys(dbIndexesGroup).map((keyName) => {
|
|
388
|
-
const currentIndexes = dbIndexesGroup[keyName];
|
|
389
|
-
return Object.assign({ type: currentIndexes[0].Non_unique === 1 ? "index" : "unique", columns: currentIndexes.map((currentIndex) => currentIndex.Column_name) }, (0, lodash_able_1.propIf)(currentIndexes.length > 1, {
|
|
390
|
-
name: keyName,
|
|
391
|
-
}));
|
|
392
|
-
});
|
|
393
|
-
// console.log(table);
|
|
394
|
-
// console.table(dbIndexes);
|
|
395
|
-
// console.table(dbForeigns);
|
|
396
|
-
// foreigns 처리
|
|
397
|
-
const foreigns = dbForeigns.map((dbForeign) => {
|
|
398
|
-
return {
|
|
399
|
-
columns: [dbForeign.from],
|
|
400
|
-
to: `${dbForeign.referencesTable}.${dbForeign.referencesField}`,
|
|
401
|
-
onUpdate: dbForeign.onUpdate,
|
|
402
|
-
onDelete: dbForeign.onDelete,
|
|
403
|
-
};
|
|
404
|
-
});
|
|
405
|
-
return {
|
|
406
|
-
table,
|
|
407
|
-
columns,
|
|
408
|
-
indexes,
|
|
409
|
-
foreigns,
|
|
410
|
-
};
|
|
411
|
-
});
|
|
412
|
-
}
|
|
413
|
-
resolveDBColType(colType, colField) {
|
|
414
|
-
let [rawType, unsigned] = colType.split(" ");
|
|
415
|
-
const matched = rawType.match(/\(([0-9]+)\)/);
|
|
416
|
-
let length;
|
|
417
|
-
if (matched !== null && matched[1]) {
|
|
418
|
-
rawType = rawType.replace(/\(([0-9]+)\)/, "");
|
|
419
|
-
length = parseInt(matched[1]);
|
|
420
|
-
}
|
|
421
|
-
if (rawType === "char" && colField === "uuid") {
|
|
422
|
-
return Object.assign({ type: "uuid" }, (0, lodash_able_1.propIf)(length !== undefined, {}));
|
|
423
|
-
}
|
|
424
|
-
switch (rawType) {
|
|
425
|
-
case "int":
|
|
426
|
-
return {
|
|
427
|
-
type: "integer",
|
|
428
|
-
unsigned: unsigned === "unsigned",
|
|
429
|
-
};
|
|
430
|
-
case "float(8,2)":
|
|
431
|
-
return Object.assign({ type: "float" }, (0, lodash_able_1.propIf)(unsigned === "unsigned", {
|
|
432
|
-
unsigned: true,
|
|
433
|
-
}));
|
|
434
|
-
case "decimal(8,2)":
|
|
435
|
-
return Object.assign({ type: "decimal" }, (0, lodash_able_1.propIf)(unsigned === "unsigned", {
|
|
436
|
-
unsigned: true,
|
|
437
|
-
}));
|
|
438
|
-
case "varchar":
|
|
439
|
-
// case "char":
|
|
440
|
-
return Object.assign({ type: "string" }, (0, lodash_able_1.propIf)(length !== undefined, {
|
|
441
|
-
length,
|
|
442
|
-
}));
|
|
443
|
-
case "text":
|
|
444
|
-
case "mediumtext":
|
|
445
|
-
case "longtext":
|
|
446
|
-
case "timestamp":
|
|
447
|
-
case "json":
|
|
448
|
-
case "date":
|
|
449
|
-
case "time":
|
|
450
|
-
return {
|
|
451
|
-
type: rawType,
|
|
452
|
-
};
|
|
453
|
-
case "datetime":
|
|
454
|
-
return {
|
|
455
|
-
type: "dateTime",
|
|
456
|
-
};
|
|
457
|
-
case "tinyint":
|
|
458
|
-
return {
|
|
459
|
-
type: "boolean",
|
|
460
|
-
};
|
|
461
|
-
default:
|
|
462
|
-
throw new Error(`resolve 불가능한 DB컬럼 타입 ${colType} ${rawType}`);
|
|
463
|
-
}
|
|
464
|
-
}
|
|
465
|
-
/*
|
|
466
|
-
기존 테이블 읽어서 cols, indexes 반환
|
|
467
|
-
*/
|
|
468
|
-
readTable(tableName) {
|
|
469
|
-
return __awaiter(this, void 0, void 0, function* () {
|
|
470
|
-
// 테이블 정보
|
|
471
|
-
try {
|
|
472
|
-
const [cols] = yield this.targets.compare.raw(`SHOW FIELDS FROM ${tableName}`);
|
|
473
|
-
const [indexes] = yield this.targets.compare.raw(`SHOW INDEX FROM ${tableName}`);
|
|
474
|
-
const [[row]] = yield this.targets.compare.raw(`SHOW CREATE TABLE ${tableName}`);
|
|
475
|
-
const ddl = row["Create Table"];
|
|
476
|
-
const matched = ddl.match(/CONSTRAINT .+/g);
|
|
477
|
-
const foreignKeys = (matched !== null && matched !== void 0 ? matched : []).map((line) => {
|
|
478
|
-
const matched = line.match(/CONSTRAINT `(.+)` FOREIGN KEY \(`(.+)`\) REFERENCES `(.+)` \(`(.+)`\) ON DELETE ([A-Z ]+) ON UPDATE ([A-Z ]+)/);
|
|
479
|
-
if (!matched) {
|
|
480
|
-
throw new Error(`인식할 수 없는 FOREIGN KEY CONSTRAINT ${line}`);
|
|
481
|
-
}
|
|
482
|
-
const [, keyName, from, referencesTable, referencesField, onDelete, onUpdate,] = matched;
|
|
483
|
-
return {
|
|
484
|
-
keyName,
|
|
485
|
-
from,
|
|
486
|
-
referencesTable,
|
|
487
|
-
referencesField,
|
|
488
|
-
onDelete,
|
|
489
|
-
onUpdate,
|
|
490
|
-
};
|
|
491
|
-
});
|
|
492
|
-
return [cols, indexes, foreignKeys];
|
|
493
|
-
}
|
|
494
|
-
catch (e) {
|
|
495
|
-
throw e;
|
|
496
|
-
}
|
|
497
|
-
});
|
|
498
|
-
}
|
|
499
|
-
/*
|
|
500
|
-
MD 내용 읽어서 MigrationSetAndJoinTable 추출
|
|
501
|
-
*/
|
|
502
|
-
getMigrationSetFromMD(md) {
|
|
503
|
-
const migrationSet = md.props.reduce((r, prop) => {
|
|
504
|
-
var _a;
|
|
505
|
-
// virtual 필드 제외
|
|
506
|
-
if ((0, shared_1.isVirtualProp)(prop)) {
|
|
507
|
-
return r;
|
|
508
|
-
}
|
|
509
|
-
// HasMany 케이스는 아무 처리도 하지 않음
|
|
510
|
-
if ((0, shared_1.isHasManyRelationProp)(prop)) {
|
|
511
|
-
return r;
|
|
512
|
-
}
|
|
513
|
-
// 일반 컬럼
|
|
514
|
-
if (!(0, shared_1.isRelationProp)(prop)) {
|
|
515
|
-
// type resolve
|
|
516
|
-
let type;
|
|
517
|
-
if ((0, shared_1.isTextProp)(prop)) {
|
|
518
|
-
type = prop.textType;
|
|
519
|
-
}
|
|
520
|
-
else if ((0, shared_1.isEnumProp)(prop)) {
|
|
521
|
-
type = "string";
|
|
522
|
-
}
|
|
523
|
-
else {
|
|
524
|
-
type = prop.type;
|
|
525
|
-
}
|
|
526
|
-
const column = Object.assign(Object.assign(Object.assign(Object.assign({ name: prop.name, type }, ((0, shared_1.isIntegerProp)(prop)
|
|
527
|
-
? { unsigned: prop.unsigned === true }
|
|
528
|
-
: {})), ((0, shared_1.isStringProp)(prop) || (0, shared_1.isEnumProp)(prop)
|
|
529
|
-
? { length: prop.length }
|
|
530
|
-
: {})), { nullable: prop.nullable === true }), (0, lodash_able_1.propIf)(prop.dbDefault !== undefined, {
|
|
531
|
-
defaultTo: "" + prop.dbDefault,
|
|
532
|
-
}));
|
|
533
|
-
r.columns.push(column);
|
|
534
|
-
}
|
|
535
|
-
// 일반 컬럼 + ToOne 케이스 컬럼
|
|
536
|
-
if (!(0, shared_1.isRelationProp)(prop) ||
|
|
537
|
-
(0, shared_1.isBelongsToOneRelationProp)(prop) ||
|
|
538
|
-
((0, shared_1.isOneToOneRelationProp)(prop) && prop.hasJoinColumn)) {
|
|
539
|
-
const propName = !(0, shared_1.isRelationProp)(prop)
|
|
540
|
-
? prop.name
|
|
541
|
-
: `${prop.name}_id`;
|
|
542
|
-
// index 처리
|
|
543
|
-
if (prop.index !== undefined) {
|
|
544
|
-
if (prop.index !== true) {
|
|
545
|
-
prop.index.map((indexName) => {
|
|
546
|
-
const namedOne = r.indexes.find((_index) => _index.name === indexName);
|
|
547
|
-
if (namedOne) {
|
|
548
|
-
namedOne.columns.push(propName);
|
|
549
|
-
}
|
|
550
|
-
else {
|
|
551
|
-
r.indexes.push({
|
|
552
|
-
type: "index",
|
|
553
|
-
columns: [propName],
|
|
554
|
-
name: indexName,
|
|
555
|
-
});
|
|
556
|
-
}
|
|
557
|
-
});
|
|
558
|
-
}
|
|
559
|
-
else {
|
|
560
|
-
r.indexes.push({
|
|
561
|
-
type: "index",
|
|
562
|
-
columns: [propName],
|
|
563
|
-
});
|
|
564
|
-
}
|
|
565
|
-
}
|
|
566
|
-
// unique 처리
|
|
567
|
-
if (prop.unique !== undefined) {
|
|
568
|
-
if (prop.unique !== true) {
|
|
569
|
-
prop.unique.map((indexName) => {
|
|
570
|
-
const namedOne = r.indexes.find((_index) => _index.name === indexName);
|
|
571
|
-
if (namedOne) {
|
|
572
|
-
namedOne.columns.push(propName);
|
|
573
|
-
}
|
|
574
|
-
else {
|
|
575
|
-
r.indexes.push({
|
|
576
|
-
type: "unique",
|
|
577
|
-
columns: [propName],
|
|
578
|
-
name: indexName,
|
|
579
|
-
});
|
|
580
|
-
}
|
|
581
|
-
});
|
|
582
|
-
}
|
|
583
|
-
else {
|
|
584
|
-
r.indexes.push({
|
|
585
|
-
type: "unique",
|
|
586
|
-
columns: [propName],
|
|
587
|
-
});
|
|
588
|
-
}
|
|
589
|
-
}
|
|
590
|
-
}
|
|
591
|
-
if ((0, shared_1.isManyToManyRelationProp)(prop)) {
|
|
592
|
-
// ManyToMany 케이스
|
|
593
|
-
const relMd = smd_manager_1.SMDManager.get(prop.with);
|
|
594
|
-
const [table1, table2] = prop.joinTable.split("__");
|
|
595
|
-
const join = {
|
|
596
|
-
from: `${md.table}.id`,
|
|
597
|
-
through: {
|
|
598
|
-
from: `${prop.joinTable}.${(0, inflection_1.singularize)(table1)}_id`,
|
|
599
|
-
to: `${prop.joinTable}.${(0, inflection_1.singularize)(table2)}_id`,
|
|
600
|
-
onUpdate: prop.onUpdate,
|
|
601
|
-
onDelete: prop.onDelete,
|
|
602
|
-
},
|
|
603
|
-
to: `${relMd.table}.id`,
|
|
604
|
-
};
|
|
605
|
-
const through = join.through;
|
|
606
|
-
const fields = [through.from, through.to];
|
|
607
|
-
r.joinTables.push({
|
|
608
|
-
table: through.from.split(".")[0],
|
|
609
|
-
indexes: [
|
|
610
|
-
{
|
|
611
|
-
type: "unique",
|
|
612
|
-
columns: ["uuid"],
|
|
613
|
-
},
|
|
614
|
-
],
|
|
615
|
-
columns: [
|
|
616
|
-
{
|
|
617
|
-
name: "id",
|
|
618
|
-
type: "integer",
|
|
619
|
-
nullable: false,
|
|
620
|
-
unsigned: true,
|
|
621
|
-
},
|
|
622
|
-
...fields.map((field) => {
|
|
623
|
-
return {
|
|
624
|
-
name: field.split(".")[1],
|
|
625
|
-
type: "integer",
|
|
626
|
-
nullable: false,
|
|
627
|
-
unsigned: true,
|
|
628
|
-
};
|
|
629
|
-
}),
|
|
630
|
-
{
|
|
631
|
-
name: "uuid",
|
|
632
|
-
nullable: true,
|
|
633
|
-
type: "uuid",
|
|
634
|
-
},
|
|
635
|
-
],
|
|
636
|
-
foreigns: fields.map((field) => {
|
|
637
|
-
return {
|
|
638
|
-
columns: [field.split(".")[1]],
|
|
639
|
-
to: through.to.includes(field) ? join.to : join.from,
|
|
640
|
-
onUpdate: through.onUpdate,
|
|
641
|
-
onDelete: through.onDelete,
|
|
642
|
-
};
|
|
643
|
-
}),
|
|
644
|
-
});
|
|
645
|
-
return r;
|
|
646
|
-
}
|
|
647
|
-
else if ((0, shared_1.isBelongsToOneRelationProp)(prop) ||
|
|
648
|
-
((0, shared_1.isOneToOneRelationProp)(prop) && prop.hasJoinColumn)) {
|
|
649
|
-
// -OneRelation 케이스
|
|
650
|
-
const idColumnName = prop.name + "_id";
|
|
651
|
-
r.columns.push({
|
|
652
|
-
name: idColumnName,
|
|
653
|
-
type: "integer",
|
|
654
|
-
unsigned: true,
|
|
655
|
-
nullable: (_a = prop.nullable) !== null && _a !== void 0 ? _a : false,
|
|
656
|
-
});
|
|
657
|
-
r.foreigns.push({
|
|
658
|
-
columns: [idColumnName],
|
|
659
|
-
to: `${(0, inflection_1.underscore)((0, inflection_1.pluralize)(prop.with)).toLowerCase()}.id`,
|
|
660
|
-
onUpdate: prop.onUpdate,
|
|
661
|
-
onDelete: prop.onDelete,
|
|
662
|
-
});
|
|
663
|
-
}
|
|
664
|
-
return r;
|
|
665
|
-
}, {
|
|
666
|
-
table: md.table,
|
|
667
|
-
columns: [],
|
|
668
|
-
indexes: [],
|
|
669
|
-
foreigns: [],
|
|
670
|
-
joinTables: [],
|
|
671
|
-
});
|
|
672
|
-
// uuid
|
|
673
|
-
migrationSet.columns = migrationSet.columns.concat({
|
|
674
|
-
name: "uuid",
|
|
675
|
-
nullable: true,
|
|
676
|
-
type: "uuid",
|
|
677
|
-
});
|
|
678
|
-
migrationSet.indexes = migrationSet.indexes.concat({
|
|
679
|
-
type: "unique",
|
|
680
|
-
columns: ["uuid"],
|
|
681
|
-
});
|
|
682
|
-
return migrationSet;
|
|
683
|
-
}
|
|
684
|
-
/*
|
|
685
|
-
MigrationColumn[] 읽어서 컬럼 정의하는 구문 생성
|
|
686
|
-
*/
|
|
687
|
-
genColumnDefinitions(columns) {
|
|
688
|
-
return columns.map((column) => {
|
|
689
|
-
const chains = [];
|
|
690
|
-
if (column.name === "id") {
|
|
691
|
-
return `table.increments().primary();`;
|
|
692
|
-
}
|
|
693
|
-
// type, length
|
|
694
|
-
let columnType = column.type;
|
|
695
|
-
let extraType;
|
|
696
|
-
if (columnType.includes("text") && columnType !== "text") {
|
|
697
|
-
extraType = columnType;
|
|
698
|
-
columnType = "text";
|
|
699
|
-
}
|
|
700
|
-
chains.push(`${column.type}('${column.name}'${column.length ? `, ${column.length}` : ""}${extraType ? `, '${extraType}'` : ""})`);
|
|
701
|
-
if (column.unsigned) {
|
|
702
|
-
chains.push("unsigned()");
|
|
703
|
-
}
|
|
704
|
-
// nullable
|
|
705
|
-
chains.push(column.nullable ? "nullable()" : "notNullable()");
|
|
706
|
-
// defaultTo
|
|
707
|
-
if (column.defaultTo !== undefined) {
|
|
708
|
-
chains.push(`defaultTo(knex.raw('${column.defaultTo}'))`);
|
|
709
|
-
}
|
|
710
|
-
return `table.${chains.join(".")};`;
|
|
711
|
-
});
|
|
712
|
-
}
|
|
713
|
-
/*
|
|
714
|
-
MigrationIndex[] 읽어서 인덱스/유니크 정의하는 구문 생성
|
|
715
|
-
*/
|
|
716
|
-
genIndexDefinitions(indexes) {
|
|
717
|
-
if (indexes.length === 0) {
|
|
718
|
-
return [];
|
|
719
|
-
}
|
|
720
|
-
const lines = (0, lodash_1.uniq)(indexes.reduce((r, index) => {
|
|
721
|
-
if (index.name === undefined) {
|
|
722
|
-
r.push(`table.${index.type}(['${index.columns[0]}'])`);
|
|
723
|
-
}
|
|
724
|
-
else {
|
|
725
|
-
r.push(`table.${index.type}([${index.columns
|
|
726
|
-
.map((col) => `'${col}'`)
|
|
727
|
-
.join(",")}], '${index.name}')`);
|
|
728
|
-
}
|
|
729
|
-
return r;
|
|
730
|
-
}, []));
|
|
731
|
-
return lines;
|
|
732
|
-
}
|
|
733
|
-
/*
|
|
734
|
-
MigrationForeign[] 읽어서 외부키 constraint 정의하는 구문 생성
|
|
735
|
-
*/
|
|
736
|
-
genForeignDefinitions(table, foreigns) {
|
|
737
|
-
return foreigns.reduce((r, foreign) => {
|
|
738
|
-
const columnsStringQuote = foreign.columns
|
|
739
|
-
.map((col) => `'${col.replace(`${table}.`, "")}'`)
|
|
740
|
-
.join(",");
|
|
741
|
-
r.up.push(`table.foreign('${foreign.columns.join(",")}')
|
|
742
|
-
.references('${foreign.to}')
|
|
743
|
-
.onUpdate('${foreign.onUpdate}')
|
|
744
|
-
.onDelete('${foreign.onDelete}')`);
|
|
745
|
-
r.down.push(`table.dropForeign([${columnsStringQuote}])`);
|
|
746
|
-
return r;
|
|
747
|
-
}, {
|
|
748
|
-
up: [],
|
|
749
|
-
down: [],
|
|
750
|
-
});
|
|
751
|
-
}
|
|
752
|
-
/*
|
|
753
|
-
테이블 생성하는 케이스 - 컬럼/인덱스 생성
|
|
754
|
-
*/
|
|
755
|
-
generateCreateCode_ColumnAndIndexes(table, columns, indexes) {
|
|
756
|
-
// 컬럼, 인덱스 처리
|
|
757
|
-
const lines = [
|
|
758
|
-
'import { Knex } from "knex";',
|
|
759
|
-
"",
|
|
760
|
-
"export async function up(knex: Knex): Promise<void> {",
|
|
761
|
-
`return knex.schema.createTable("${table}", (table) => {`,
|
|
762
|
-
"// columns",
|
|
763
|
-
...this.genColumnDefinitions(columns),
|
|
764
|
-
"",
|
|
765
|
-
"// indexes",
|
|
766
|
-
...this.genIndexDefinitions(indexes),
|
|
767
|
-
"});",
|
|
768
|
-
"}",
|
|
769
|
-
"",
|
|
770
|
-
"export async function down(knex: Knex): Promise<void> {",
|
|
771
|
-
` return knex.schema.dropTable("${table}");`,
|
|
772
|
-
"}",
|
|
773
|
-
];
|
|
774
|
-
return {
|
|
775
|
-
table,
|
|
776
|
-
type: "normal",
|
|
777
|
-
title: `create__${table}`,
|
|
778
|
-
formatted: prettier_1.default.format(lines.join("\n"), {
|
|
779
|
-
parser: "typescript",
|
|
780
|
-
}),
|
|
781
|
-
};
|
|
782
|
-
}
|
|
783
|
-
/*
|
|
784
|
-
테이블 생성하는 케이스 - FK 생성
|
|
785
|
-
*/
|
|
786
|
-
generateCreateCode_Foreign(table, foreigns) {
|
|
787
|
-
if (foreigns.length === 0) {
|
|
788
|
-
return [];
|
|
789
|
-
}
|
|
790
|
-
const { up, down } = this.genForeignDefinitions(table, foreigns);
|
|
791
|
-
if (up.length === 0 && down.length === 0) {
|
|
792
|
-
console.log("fk 가 뭔가 다릅니다");
|
|
793
|
-
return [];
|
|
794
|
-
}
|
|
795
|
-
const lines = [
|
|
796
|
-
'import { Knex } from "knex";',
|
|
797
|
-
"",
|
|
798
|
-
"export async function up(knex: Knex): Promise<void> {",
|
|
799
|
-
`return knex.schema.alterTable("${table}", (table) => {`,
|
|
800
|
-
"// create fk",
|
|
801
|
-
...up,
|
|
802
|
-
"});",
|
|
803
|
-
"}",
|
|
804
|
-
"",
|
|
805
|
-
"export async function down(knex: Knex): Promise<void> {",
|
|
806
|
-
`return knex.schema.alterTable("${table}", (table) => {`,
|
|
807
|
-
"// drop fk",
|
|
808
|
-
...down,
|
|
809
|
-
"});",
|
|
810
|
-
"}",
|
|
811
|
-
];
|
|
812
|
-
const foreignKeysString = foreigns
|
|
813
|
-
.map((foreign) => foreign.columns.join("_"))
|
|
814
|
-
.join("_");
|
|
815
|
-
return [
|
|
816
|
-
{
|
|
817
|
-
table,
|
|
818
|
-
type: "foreign",
|
|
819
|
-
title: `foreign__${table}__${foreignKeysString}`,
|
|
820
|
-
formatted: prettier_1.default.format(lines.join("\n"), {
|
|
821
|
-
parser: "typescript",
|
|
822
|
-
}),
|
|
823
|
-
},
|
|
824
|
-
];
|
|
825
|
-
}
|
|
826
|
-
/*
|
|
827
|
-
마이그레이션 컬럼 배열 비교용 코드
|
|
828
|
-
*/
|
|
829
|
-
showMigrationSet(which, migrationSet) {
|
|
830
|
-
const { columns, indexes, foreigns } = migrationSet;
|
|
831
|
-
const styledChalk = which === "MD" ? chalk_1.default.bgGreen.black : chalk_1.default.bgBlue.black;
|
|
832
|
-
console.log(styledChalk(`${which} ${migrationSet.table} Columns\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t`));
|
|
833
|
-
console.table(columns.map((column) => {
|
|
834
|
-
return Object.assign({}, (0, lodash_1.pick)(column, [
|
|
835
|
-
"name",
|
|
836
|
-
"type",
|
|
837
|
-
"nullable",
|
|
838
|
-
"unsigned",
|
|
839
|
-
"length",
|
|
840
|
-
"defaultTo",
|
|
841
|
-
]));
|
|
842
|
-
}), ["name", "type", "nullable", "unsigned", "length", "defaultTo"]);
|
|
843
|
-
if (indexes.length > 0) {
|
|
844
|
-
console.log(styledChalk(`${which} ${migrationSet.table} Indexes\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t`));
|
|
845
|
-
console.table(indexes.map((index) => {
|
|
846
|
-
return Object.assign({}, (0, lodash_1.pick)(index, ["type", "columns", "name"]));
|
|
847
|
-
}));
|
|
848
|
-
}
|
|
849
|
-
if (foreigns.length > 0) {
|
|
850
|
-
console.log(chalk_1.default.bgMagenta.black(`${which} ${migrationSet.table} Foreigns\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t`));
|
|
851
|
-
console.table(foreigns.map((foreign) => {
|
|
852
|
-
return Object.assign({}, (0, lodash_1.pick)(foreign, ["columns", "to", "onUpdate", "onDelete"]));
|
|
853
|
-
}));
|
|
854
|
-
}
|
|
855
|
-
}
|
|
856
|
-
generateAlterCode_ColumnAndIndexes(table, mdColumns, mdIndexes, dbColumns, dbIndexes) {
|
|
857
|
-
// console.log(chalk.cyan("MigrationColumns from DB"));
|
|
858
|
-
// showMigrationSet(dbColumns);
|
|
859
|
-
// console.log(chalk.cyan("MigrationColumns from MD"));
|
|
860
|
-
// showMigrationSet(mdColumns);
|
|
861
|
-
/*
|
|
862
|
-
세부 비교 후 다른점 찾아서 코드 생성
|
|
863
|
-
|
|
864
|
-
1. 컬럼갯수 다름: MD에 있으나, DB에 없다면 추가
|
|
865
|
-
2. 컬럼갯수 다름: MD에 없으나, DB에 있다면 삭제
|
|
866
|
-
3. 그외 컬럼(컬럼 갯수가 동일하거나, 다른 경우 동일한 컬럼끼리) => alter
|
|
867
|
-
4. 다른거 다 동일하고 index만 변경되는 경우
|
|
868
|
-
|
|
869
|
-
** 컬럼명을 변경하는 경우는 따로 핸들링하지 않음
|
|
870
|
-
=> drop/add 형태의 마이그레이션 코드가 생성되는데, 수동으로 rename 코드로 수정하여 처리
|
|
871
|
-
*/
|
|
872
|
-
// 각 컬럼 이름 기준으로 add, drop, alter 여부 확인
|
|
873
|
-
const alterColumnsTo = this.getAlterColumnsTo(mdColumns, dbColumns);
|
|
874
|
-
// 추출된 컬럼들을 기준으로 각각 라인 생성
|
|
875
|
-
const alterColumnLinesTo = this.getAlterColumnLinesTo(alterColumnsTo, mdColumns);
|
|
876
|
-
// 인덱스의 add, drop 여부 확인
|
|
877
|
-
const alterIndexesTo = this.getAlterIndexesTo(mdIndexes, dbIndexes);
|
|
878
|
-
// 추출된 인덱스들을 기준으로 각각 라인 생성
|
|
879
|
-
const alterIndexLinesTo = this.getAlterIndexLinesTo(alterIndexesTo, alterColumnsTo);
|
|
880
|
-
const lines = [
|
|
881
|
-
'import { Knex } from "knex";',
|
|
882
|
-
"",
|
|
883
|
-
"export async function up(knex: Knex): Promise<void> {",
|
|
884
|
-
`return knex.schema.alterTable("${table}", (table) => {`,
|
|
885
|
-
...(alterColumnsTo.add.length > 0 ? alterColumnLinesTo.add.up : []),
|
|
886
|
-
...(alterColumnsTo.drop.length > 0 ? alterColumnLinesTo.drop.up : []),
|
|
887
|
-
...(alterColumnsTo.alter.length > 0 ? alterColumnLinesTo.alter.up : []),
|
|
888
|
-
...(alterIndexesTo.add.length > 0 ? alterIndexLinesTo.add.up : []),
|
|
889
|
-
...(alterIndexesTo.drop.length > 0 ? alterIndexLinesTo.drop.up : []),
|
|
890
|
-
"})",
|
|
891
|
-
"}",
|
|
892
|
-
"",
|
|
893
|
-
"export async function down(knex: Knex): Promise<void> {",
|
|
894
|
-
`return knex.schema.alterTable("${table}", (table) => {`,
|
|
895
|
-
...(alterColumnsTo.add.length > 0 ? alterColumnLinesTo.add.down : []),
|
|
896
|
-
...(alterColumnsTo.drop.length > 0 ? alterColumnLinesTo.drop.down : []),
|
|
897
|
-
...(alterColumnsTo.alter.length > 0 ? alterColumnLinesTo.alter.down : []),
|
|
898
|
-
...(alterIndexLinesTo.add.down.length > 1
|
|
899
|
-
? alterIndexLinesTo.add.down
|
|
900
|
-
: []),
|
|
901
|
-
...(alterIndexLinesTo.drop.down.length > 1
|
|
902
|
-
? alterIndexLinesTo.drop.down
|
|
903
|
-
: []),
|
|
904
|
-
"})",
|
|
905
|
-
"}",
|
|
906
|
-
];
|
|
907
|
-
const formatted = prettier_1.default.format(lines.join("\n"), {
|
|
908
|
-
parser: "typescript",
|
|
909
|
-
});
|
|
910
|
-
const title = [
|
|
911
|
-
"alter",
|
|
912
|
-
table,
|
|
913
|
-
...["add", "drop", "alter"]
|
|
914
|
-
.map((action) => {
|
|
915
|
-
const len = alterColumnsTo[action].length;
|
|
916
|
-
if (len > 0) {
|
|
917
|
-
return action + len;
|
|
918
|
-
}
|
|
919
|
-
return null;
|
|
920
|
-
})
|
|
921
|
-
.filter((part) => part !== null),
|
|
922
|
-
].join("_");
|
|
923
|
-
return [
|
|
924
|
-
{
|
|
925
|
-
table,
|
|
926
|
-
title,
|
|
927
|
-
formatted,
|
|
928
|
-
type: "normal",
|
|
929
|
-
},
|
|
930
|
-
];
|
|
931
|
-
}
|
|
932
|
-
getAlterColumnsTo(mdColumns, dbColumns) {
|
|
933
|
-
const columnsTo = {
|
|
934
|
-
add: [],
|
|
935
|
-
drop: [],
|
|
936
|
-
alter: [],
|
|
937
|
-
};
|
|
938
|
-
// 컬럼명 기준 비교
|
|
939
|
-
const extraColumns = {
|
|
940
|
-
db: (0, lodash_1.differenceBy)(dbColumns, mdColumns, (col) => col.name),
|
|
941
|
-
md: (0, lodash_1.differenceBy)(mdColumns, dbColumns, (col) => col.name),
|
|
942
|
-
};
|
|
943
|
-
if (extraColumns.md.length > 0) {
|
|
944
|
-
columnsTo.add = columnsTo.add.concat(extraColumns.md);
|
|
945
|
-
}
|
|
946
|
-
if (extraColumns.db.length > 0) {
|
|
947
|
-
columnsTo.drop = columnsTo.drop.concat(extraColumns.db);
|
|
948
|
-
}
|
|
949
|
-
// 동일 컬럼명의 세부 필드 비교
|
|
950
|
-
const sameDbColumns = (0, lodash_1.intersectionBy)(dbColumns, mdColumns, (col) => col.name);
|
|
951
|
-
const sameMdColumns = (0, lodash_1.intersectionBy)(mdColumns, dbColumns, (col) => col.name);
|
|
952
|
-
columnsTo.alter = (0, lodash_1.differenceWith)(sameDbColumns, sameMdColumns, (a, b) => (0, fast_deep_equal_1.default)(a, b));
|
|
953
|
-
return columnsTo;
|
|
954
|
-
}
|
|
955
|
-
getAlterColumnLinesTo(columnsTo, mdColumns) {
|
|
956
|
-
let linesTo = {
|
|
957
|
-
add: {
|
|
958
|
-
up: [],
|
|
959
|
-
down: [],
|
|
960
|
-
},
|
|
961
|
-
drop: {
|
|
962
|
-
up: [],
|
|
963
|
-
down: [],
|
|
964
|
-
},
|
|
965
|
-
alter: {
|
|
966
|
-
up: [],
|
|
967
|
-
down: [],
|
|
968
|
-
},
|
|
969
|
-
};
|
|
970
|
-
linesTo.add = {
|
|
971
|
-
up: ["// add", ...this.genColumnDefinitions(columnsTo.add)],
|
|
972
|
-
down: [
|
|
973
|
-
"// rollback - add",
|
|
974
|
-
`table.dropColumns(${columnsTo.add
|
|
975
|
-
.map((col) => `'${col.name}'`)
|
|
976
|
-
.join(", ")})`,
|
|
977
|
-
],
|
|
978
|
-
};
|
|
979
|
-
linesTo.drop = {
|
|
980
|
-
up: [
|
|
981
|
-
"// drop",
|
|
982
|
-
`table.dropColumns(${columnsTo.drop
|
|
983
|
-
.map((col) => `'${col.name}'`)
|
|
984
|
-
.join(", ")})`,
|
|
985
|
-
],
|
|
986
|
-
down: [
|
|
987
|
-
"// rollback - drop",
|
|
988
|
-
...this.genColumnDefinitions(columnsTo.drop),
|
|
989
|
-
],
|
|
990
|
-
};
|
|
991
|
-
linesTo.alter = columnsTo.alter.reduce((r, dbColumn) => {
|
|
992
|
-
const mdColumn = mdColumns.find((col) => col.name == dbColumn.name);
|
|
993
|
-
if (mdColumn === undefined) {
|
|
994
|
-
return r;
|
|
995
|
-
}
|
|
996
|
-
// 컬럼 변경사항
|
|
997
|
-
const columnDiffUp = (0, lodash_1.difference)(this.genColumnDefinitions([mdColumn]), this.genColumnDefinitions([dbColumn]));
|
|
998
|
-
const columnDiffDown = (0, lodash_1.difference)(this.genColumnDefinitions([dbColumn]), this.genColumnDefinitions([mdColumn]));
|
|
999
|
-
if (columnDiffUp.length > 0) {
|
|
1000
|
-
r.up = [
|
|
1001
|
-
...r.up,
|
|
1002
|
-
"// alter column",
|
|
1003
|
-
...columnDiffUp.map((l) => l.replace(";", "") + ".alter();"),
|
|
1004
|
-
];
|
|
1005
|
-
r.down = [
|
|
1006
|
-
...r.down,
|
|
1007
|
-
"// rollback - alter column",
|
|
1008
|
-
...columnDiffDown.map((l) => l.replace(";", "") + ".alter();"),
|
|
1009
|
-
];
|
|
1010
|
-
}
|
|
1011
|
-
return r;
|
|
1012
|
-
}, {
|
|
1013
|
-
up: [],
|
|
1014
|
-
down: [],
|
|
1015
|
-
});
|
|
1016
|
-
return linesTo;
|
|
1017
|
-
}
|
|
1018
|
-
getAlterIndexesTo(mdIndexes, dbIndexes) {
|
|
1019
|
-
// 인덱스 비교
|
|
1020
|
-
let indexesTo = {
|
|
1021
|
-
add: [],
|
|
1022
|
-
drop: [],
|
|
1023
|
-
};
|
|
1024
|
-
const extraIndexes = {
|
|
1025
|
-
db: (0, lodash_1.differenceBy)(dbIndexes, mdIndexes, (col) => { var _a; return [col.type, (_a = col.name) !== null && _a !== void 0 ? _a : col.columns.join("-")].join("//"); }),
|
|
1026
|
-
md: (0, lodash_1.differenceBy)(mdIndexes, dbIndexes, (col) => { var _a; return [col.type, (_a = col.name) !== null && _a !== void 0 ? _a : col.columns.join("-")].join("//"); }),
|
|
1027
|
-
};
|
|
1028
|
-
if (extraIndexes.md.length > 0) {
|
|
1029
|
-
indexesTo.add = indexesTo.add.concat(extraIndexes.md);
|
|
1030
|
-
}
|
|
1031
|
-
if (extraIndexes.db.length > 0) {
|
|
1032
|
-
indexesTo.drop = indexesTo.drop.concat(extraIndexes.db);
|
|
1033
|
-
}
|
|
1034
|
-
return indexesTo;
|
|
1035
|
-
}
|
|
1036
|
-
getAlterIndexLinesTo(indexesTo, columnsTo) {
|
|
1037
|
-
let linesTo = {
|
|
1038
|
-
add: {
|
|
1039
|
-
up: [],
|
|
1040
|
-
down: [],
|
|
1041
|
-
},
|
|
1042
|
-
drop: {
|
|
1043
|
-
up: [],
|
|
1044
|
-
down: [],
|
|
1045
|
-
},
|
|
1046
|
-
};
|
|
1047
|
-
// 인덱스가 추가되는 경우, 컬럼과 같이 추가된 케이스에는 drop에서 제외해야함!
|
|
1048
|
-
linesTo.add = {
|
|
1049
|
-
up: ["// add indexes", ...this.genIndexDefinitions(indexesTo.add)],
|
|
1050
|
-
down: [
|
|
1051
|
-
"// rollback - add indexes",
|
|
1052
|
-
...indexesTo.add
|
|
1053
|
-
.filter((index) => index.columns.every((colName) => columnsTo.add.map((col) => col.name).includes(colName)) === false)
|
|
1054
|
-
.map((index) => `table.drop${(0, inflection_1.capitalize)(index.type)}([${index.columns
|
|
1055
|
-
.map((columnName) => `'${columnName}'`)
|
|
1056
|
-
.join(",")}])`),
|
|
1057
|
-
],
|
|
1058
|
-
};
|
|
1059
|
-
// 인덱스가 삭제되는 경우, 컬럼과 같이 삭제된 케이스에는 drop에서 제외해야함!
|
|
1060
|
-
linesTo.drop = {
|
|
1061
|
-
up: [
|
|
1062
|
-
...indexesTo.drop
|
|
1063
|
-
.filter((index) => index.columns.every((colName) => columnsTo.drop.map((col) => col.name).includes(colName)) === false)
|
|
1064
|
-
.map((index) => `table.drop${(0, inflection_1.capitalize)(index.type)}([${index.columns
|
|
1065
|
-
.map((columnName) => `'${columnName}'`)
|
|
1066
|
-
.join(",")}])`),
|
|
1067
|
-
],
|
|
1068
|
-
down: [
|
|
1069
|
-
"// rollback - drop indexes",
|
|
1070
|
-
...this.genIndexDefinitions(indexesTo.drop),
|
|
1071
|
-
],
|
|
1072
|
-
};
|
|
1073
|
-
return linesTo;
|
|
1074
|
-
}
|
|
1075
|
-
destroy() {
|
|
1076
|
-
return __awaiter(this, void 0, void 0, function* () {
|
|
1077
|
-
yield Promise.all(this.targets.apply.map((db) => {
|
|
1078
|
-
return db.destroy();
|
|
1079
|
-
}));
|
|
1080
|
-
});
|
|
1081
|
-
}
|
|
1082
|
-
}
|
|
1083
|
-
exports.F9Migrator = F9Migrator;
|
|
1084
|
-
//# sourceMappingURL=migrator.js.map
|