-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathschemaTool.js
More file actions
466 lines (420 loc) · 12.9 KB
/
schemaTool.js
File metadata and controls
466 lines (420 loc) · 12.9 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
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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
const parseArgs = require("minimist");
const fs = require("fs");
const pathUtils = require("path");
const mysql = require("mysql");
const confirm = require("confirm-cli");
let connection = null;
const reportSqlError = (error) => {
console.log("Could not connect to MySQL.");
console.log(error.code);
console.log(error.sqlMessage);
};
const exitCleanly = (exitValue) => {
if (typeof exitValue === "undefined") {
exitValue = 0;
}
if (connection !== null) {
connection.end();
}
process.exit(exitValue);
};
const printUsageAndExit = () => {
console.log("Usage:");
console.log("node schemaTool.js setUp");
console.log("node schemaTool.js verify");
console.log("node schemaTool.js destroy (-f)");
exitCleanly(1);
};
const databaseExists = (done) => {
connection.query(
"SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = ?",
[databaseName],
(error, results) => {
if (error) {
reportSqlError(error);
exitCleanly();
return;
}
done(results.length > 0);
},
);
};
const tableExists = (table, done) => {
connection.query(
"SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ?",
[databaseName, table.name],
(error, results) => {
if (error) {
reportSqlError(error);
exitCleanly();
return;
}
done(results.length > 0);
},
);
};
const getTableFieldAttributes = (table, field, done) => {
connection.query(
"SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ? AND COLUMN_NAME = ?",
[databaseName, table.name, field.name],
(error, results) => {
if (error) {
reportSqlError(error);
exitCleanly();
return;
}
if (results.length > 0) {
done(results[0]);
} else {
done(null);
}
},
);
};
const compareTableFieldAttributes = (table, field, fieldAttributes) => {
let outputMessageList = [];
const tempDescription = "Field \"" + field.name + "\" of table \"" + table.name + "\"";
let tempAttributesAreCorrect = true;
let tempType = fieldAttributes.COLUMN_TYPE.toLowerCase();
if (tempType.match(/^int\([0-9]+\)$/)) {
tempType = "int";
} else if (tempType.match(/^bigint\([0-9]+\)$/)) {
tempType = "bigint";
}
if (tempType !== field.type.toLowerCase()) {
outputMessageList.push(tempDescription + " has the wrong data type \"" + fieldAttributes.COLUMN_TYPE + "\". It should be \"" + field.type + "\".");
tempAttributesAreCorrect = false;
}
let tempColumnKey = fieldAttributes.COLUMN_KEY.toUpperCase();
let tempExpectedColumnKey;
if ("primaryKey" in field && field.primaryKey) {
tempExpectedColumnKey = "PRI";
} else if ("indexed" in field && field.indexed) {
tempExpectedColumnKey = "MUL";
} else {
tempExpectedColumnKey = "";
}
if (tempColumnKey !== tempExpectedColumnKey) {
outputMessageList.push(tempDescription + " has the wrong COLUMN_KEY value.");
tempAttributesAreCorrect = false;
}
const tempIsAutoIncrement = (fieldAttributes.EXTRA.toLowerCase() === "auto_increment");
let tempShouldBeAutoIncrement;
if ("autoIncrement" in field) {
tempShouldBeAutoIncrement = field.autoIncrement;
} else {
tempShouldBeAutoIncrement = false;
}
if (tempIsAutoIncrement !== tempShouldBeAutoIncrement) {
outputMessageList.push(tempDescription + " has the wrong EXTRA value.");
tempAttributesAreCorrect = false;
}
if (tempAttributesAreCorrect) {
outputMessageList = [tempDescription + " exists and has the correct attributes."];
}
return {
isCorrect: tempAttributesAreCorrect,
message: outputMessageList.join("\n"),
};
};
const createDatabase = (done) => {
connection.query(
"CREATE DATABASE " + databaseName,
[],
(error) => {
if (error) {
reportSqlError(error);
exitCleanly();
return;
}
done();
},
);
};
const getFieldDefinition = (field) => {
let output = field.name + " " + field.type;
if ("autoIncrement" in field) {
if (field.autoIncrement) {
output += " AUTO_INCREMENT";
}
}
return output;
};
const createTable = (table, done) => {
const fieldDefinitionList = [];
for (const field of table.fields) {
const tempDefinition = getFieldDefinition(field);
fieldDefinitionList.push(tempDefinition);
}
for (const field of table.fields) {
if ("primaryKey" in field && field.primaryKey) {
fieldDefinitionList.push(`PRIMARY KEY (${field.name})`);
}
if ("indexed" in field && field.indexed) {
fieldDefinitionList.push(`INDEX (${field.name})`);
}
}
connection.query(
"CREATE TABLE " + databaseName + "." + table.name + " (" + fieldDefinitionList.join(", ") + ")",
[],
(error) => {
if (error) {
reportSqlError(error);
exitCleanly();
return;
}
done();
},
);
};
const addTableField = (table, field, done) => {
const tempDefinition = getFieldDefinition(field);
let tempStatement = `ALTER TABLE ${databaseName}.${table.name} ADD COLUMN ${tempDefinition}`;
if ("indexed" in field && field.indexed) {
tempStatement += `, ADD INDEX (${field.name})`;
}
connection.query(
tempStatement,
[],
(error) => {
if (error) {
reportSqlError(error);
exitCleanly();
return;
}
done();
},
);
};
const deleteDatabase = (done) => {
connection.query(
"DROP DATABASE " + databaseName,
[],
(error) => {
if (error) {
reportSqlError(error);
exitCleanly();
return;
}
done();
},
);
};
const setUpTableField = (table, field, done) => {
getTableFieldAttributes(table, field, (fieldAttributes) => {
if (fieldAttributes !== null) {
const tempResult = compareTableFieldAttributes(table, field, fieldAttributes);
console.log(tempResult.message);
if (!tempResult.isCorrect) {
console.log("Aborting.");
exitCleanly();
}
done();
return;
}
console.log("Adding field \"" + field.name + "\" to table \"" + table.name + "\"...");
addTableField(table, field, () => {
console.log("Added field \"" + field.name + "\" to table \"" + table.name + "\".");
done();
});
});
};
const setUpTableFields = (table, done) => {
let index = 0;
const setUpNextTableField = () => {
if (index >= table.fields.length) {
done();
return;
}
const tempField = table.fields[index];
index += 1;
setUpTableField(table, tempField, setUpNextTableField);
};
setUpNextTableField();
};
const setUpTable = (table, done) => {
tableExists(table, (exists) => {
if (exists) {
console.log("Table \"" + table.name + "\" already exists.");
setUpTableFields(table, done);
return;
}
console.log("Creating table \"" + table.name + "\"...");
createTable(table, () => {
console.log("Created table \"" + table.name + "\".");
done();
});
});
};
const setUpTables = (done) => {
let index = 0;
const setUpNextTable = () => {
if (index >= schemaConfig.tables.length) {
done();
return;
}
const tempTable = schemaConfig.tables[index];
index += 1;
setUpTable(tempTable, setUpNextTable);
};
setUpNextTable();
};
const setUpDatabase = (done) => {
databaseExists((exists) => {
if (exists) {
console.log("Database \"" + databaseName + "\" already exists.");
setUpTables(done);
return;
}
console.log("Creating database \"" + databaseName + "\"...");
createDatabase(() => {
console.log("Created database \"" + databaseName + "\".");
setUpTables(done);
});
});
};
const setUpSchemaCommand = () => {
console.log("Setting up database...");
setUpDatabase(() => {
console.log("Finished setting up database \"" + databaseName + "\".");
exitCleanly();
});
};
const verifyTableField = (table, field, done) => {
getTableFieldAttributes(table, field, (fieldAttributes) => {
if (fieldAttributes === null) {
console.log("Field \"" + field.name + "\" of table \"" + table.name + "\" is missing.");
done();
return;
}
const tempResult = compareTableFieldAttributes(table, field, fieldAttributes);
console.log(tempResult.message);
done();
});
};
const verifyTableFields = (table, done) => {
let index = 0;
const verifyNextTableField = () => {
if (index >= table.fields.length) {
done();
return;
}
const tempField = table.fields[index];
index += 1;
verifyTableField(table, tempField, verifyNextTableField);
};
verifyNextTableField();
};
const verifyTable = (table, done) => {
tableExists(table, (exists) => {
if (!exists) {
console.log("Table \"" + table.name + "\" is missing.");
done();
return;
}
console.log("Table \"" + table.name + "\" exists.");
verifyTableFields(table, done);
});
};
const verifyTables = (done) => {
let index = 0;
const verifyNextTable = () => {
if (index >= schemaConfig.tables.length) {
done();
return;
}
const tempTable = schemaConfig.tables[index];
index += 1;
verifyTable(tempTable, verifyNextTable);
};
verifyNextTable();
};
const verifyDatabase = (done) => {
databaseExists((exists) => {
if (!exists) {
console.log("Database \"" + databaseName + "\" is missing.");
done();
return;
}
console.log("Database \"" + databaseName + "\" exists.");
verifyTables(done);
});
};
const verifySchemaCommand = () => {
console.log("Verifying database...");
verifyDatabase(() => {
console.log("Finished verifying database.");
exitCleanly();
});
};
const destroyDatabase = () => {
console.log("Destroying database...");
databaseExists((exists) => {
if (!exists) {
console.log("Database is already missing.");
exitCleanly();
return;
}
deleteDatabase(() => {
console.log("Destroyed database.");
exitCleanly();
});
});
};
const destroySchemaCommand = () => {
if ("f" in args && args.f) {
destroyDatabase();
} else {
confirm(
"Are you sure you want to destroy the database \"" + databaseName + "\"?",
destroyDatabase,
() => {
console.log("Database NOT destroyed.");
exitCleanly();
},
{ text: ["Destroy", "Cancel"] },
);
}
};
const processCli = () => {
const command = args["_"][0].toLowerCase();
if (command === "setup") {
setUpSchemaCommand();
} else if (command === "destroy") {
destroySchemaCommand();
} else if (command === "verify") {
verifySchemaCommand();
} else {
printUsageAndExit();
}
};
const baseDirectory = "./ostracodMultiplayerConfig";
if (!fs.existsSync(baseDirectory)) {
console.log("Could not find " + baseDirectory + ".");
console.log("Make sure your current working directory is correct!");
exitCleanly(1);
}
const databaseConfigPath = pathUtils.join(baseDirectory, "databaseConfig.json");
const schemaConfigPath = pathUtils.join(baseDirectory, "schemaConfig.json");
const databaseConfig = JSON.parse(fs.readFileSync(databaseConfigPath, "utf8"));
const schemaConfig = JSON.parse(fs.readFileSync(schemaConfigPath, "utf8"));
const { databaseName } = databaseConfig;
const args = parseArgs(process.argv.slice(2));
if (args["_"].length !== 1) {
printUsageAndExit();
}
console.log("Connecting to MySQL...");
connection = mysql.createConnection({
host: databaseConfig.host,
user: databaseConfig.username,
password: databaseConfig.password,
});
connection.connect((error) => {
if (error) {
reportSqlError(error);
exitCleanly();
return;
}
console.log("Connected.");
processCli();
});