-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.js
More file actions
93 lines (78 loc) · 3.31 KB
/
Copy pathindex.js
File metadata and controls
93 lines (78 loc) · 3.31 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
require('dotenv').config();
const getMysqlStructureOld = require('./services/getMysqlStructureOld');
const getMysqlStructureNew = require('./services/getMysqlStructureNew');
const getAlterStatements = require('./services/getAlterStatements');
const mysql = require('mysql2/promise');
const mysqlConfig = {
host: process.env.MYSQL_HOST,
port: process.env.MYSQL_PORT,
user: process.env.MYSQL_USER,
password: process.env.MYSQL_PASSWORD,
database: process.env.MYSQL_DATABASE,
multipleStatements: true
};
const applyChanges = process.argv[2] === 'apply';
const optionalArgsStartIndex = applyChanges ? 3 : 2;
const optionalArgs = [...process.argv].slice(optionalArgsStartIndex);
const applyIndexChanges = optionalArgs.includes('--include-indexes');
(async () => {
const mysqlConnection = await mysql.createConnection(mysqlConfig, mysqlConfig.database);
const oldSchema = await getMysqlStructureOld(mysqlConnection, mysqlConfig.database);
const newSchema = await getMysqlStructureNew();
const { createStatements, alterStatements, modifyStatements, alterKeysStatements } = await getAlterStatements(oldSchema, newSchema);
if (applyChanges) {
if(createStatements.length > 0){
for (const createStatement of createStatements) {
try {
await mysqlConnection.query(createStatement);
} catch (error) {
const sqlMessage = error.sqlMessage || 'Error executing query';
const query = error.sql || createStatement;
console.error(`${sqlMessage}:`, {
query: query,
});
}
}
}
if(alterStatements.length > 0){
for (const alterStatement of alterStatements) {
try {
await mysqlConnection.query(alterStatement);
} catch (error) {
const sqlMessage = error.sqlMessage || 'Error executing query';
const query = error.sql || alterStatement;
console.error(`${sqlMessage}:`, {
query: query,
});
}
}
}
if(modifyStatements.length > 0){
for (const modifyStatement of modifyStatements) {
try {
await mysqlConnection.query(modifyStatement);
} catch (error) {
const sqlMessage = error.sqlMessage || 'Error executing query';
const query = error.sql || modifyStatement;
console.error(`${sqlMessage}:`, {
query: query,
});
}
}
}
if(applyIndexChanges && alterKeysStatements.length > 0){
for (const alterKeysStatement of alterKeysStatements) {
try {
await mysqlConnection.query(alterKeysStatement);
} catch (error) {
const sqlMessage = error.sqlMessage || 'Error executing query';
const query = error.sql || alterKeysStatement;
console.error(`${sqlMessage}:`, {
query: query,
});
}
}
}
}
await mysqlConnection.end();
})();