-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
233 lines (209 loc) · 5.7 KB
/
index.js
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
require("dotenv").config();
const {
RDSDataClient,
ExecuteStatementCommand,
BeginTransactionCommand,
RollbackTransactionCommand,
CommitTransactionCommand,
} = require("@aws-sdk/client-rds-data");
const fs = require("fs");
const chalk = require("chalk");
const engine = process.env.RDS_RDBMS || "postgres";
const clientParams = {
apiVersion: "2018-08-01",
region: process.env.RDS_REGION,
database: process.env.RDS_DATABASE || engine,
};
const [migrationPath, debug] = process.argv.slice(2);
const rdsDataClient = new RDSDataClient(clientParams);
const params = {
resourceArn: process.env.RDS_RESOURCE_ARN,
secretArn: process.env.RDS_SECRET_ARN,
};
const checkMigrationsSchema = async () => {
debug &&
console.log(
chalk(
chalk.bgYellow("Debug:"),
`Starting check migrations schema for ${JSON.stringify({
...clientParams,
...params,
})}`,
"\n\n"
)
);
try {
await rdsDataClient.send(
new ExecuteStatementCommand({
...params,
sql:
engine === "postgres"
? `CREATE SCHEMA IF NOT EXISTS MIGRATIONS`
: `CREATE SCHEMA IF NOT EXISTS MIGRATIONS DEFAULT CHARACTER SET utf8`,
})
);
await rdsDataClient.send(
new ExecuteStatementCommand({
...params,
sql:
engine === "postgres"
? `CREATE TABLE IF NOT EXISTS MIGRATIONS.version (
id SERIAL,
version varchar NULL DEFAULT NULL,
PRIMARY KEY (id))`
: `CREATE TABLE IF NOT EXISTS MIGRATIONS.version (
id INT NOT NULL AUTO_INCREMENT,
version varchar NULL DEFAULT NULL,
PRIMARY KEY (id))
ENGINE = InnoDB`,
})
);
} catch (error) {
throw new Error(`check migrations schema failed. Error: ${error}`, {
cause: error,
});
}
};
const checkMigrationTable = async () => {
try {
// get the current version
const { records } = await rdsDataClient.send(
new ExecuteStatementCommand({
...params,
sql: `SELECT version FROM MIGRATIONS.version WHERE id = 1`,
})
);
return records.length ? records[0][0]["stringValue"] : 0;
} catch (error) {
throw new Error("check migration table failed", { cause: error });
}
};
const updateSchemaMigrationVersion = async (fileName, transactionId) => {
await rdsDataClient.send(
new ExecuteStatementCommand({
...params,
sql:
engine === "postgres"
? `INSERT INTO MIGRATIONS.version (id, version)
VALUES (1, '${fileName}') ON CONFLICT (id) DO UPDATE SET version = excluded.version;`
: `INSERT INTO MIGRATIONS.version (id, version)
VALUES (1, '${fileName}') ON DUPLICATE KEY UPDATE version=VALUES(version);`,
transactionId,
})
);
};
const executeFileStatements = async (fileName) => {
const filePath = `${process.env.PWD}/${migrationPath}/${fileName}`;
if (!fs.existsSync(filePath)) {
throw new Error(`File does not exist ${filePath}`);
}
console.log(
chalk(
chalk.blue("Info:"),
`Running Migration`,
chalk.magenta(fileName),
"\n\n"
)
);
const contents = fs.readFileSync(filePath, "utf8");
const statements = contents.split(";");
const { transactionId } = await rdsDataClient.send(
new BeginTransactionCommand(params)
);
try {
for (let i = 0; i < statements.length; i++) {
let sql = statements[i]?.trim();
if (!sql || sql == "\n") {
continue;
}
console.log(
chalk(
chalk.blue("Info:"),
`Running Migration Statement`,
chalk.magenta(i + 1),
"\n",
sql
)
);
await rdsDataClient.send(
new ExecuteStatementCommand({
...params,
sql,
transactionId,
})
);
console.log(
chalk(
chalk.green("Success:"),
`Migration Statement`,
chalk.magenta(i + 1),
"\n\n"
)
);
}
await updateSchemaMigrationVersion(fileName, transactionId);
await rdsDataClient.send(
new CommitTransactionCommand({
...params,
transactionId,
})
);
console.log(
chalk(
chalk.green("Success:"),
`Migration Complete`,
chalk.magenta(fileName)
)
);
} catch (error) {
await rdsDataClient.send(
new RollbackTransactionCommand({
...params,
transactionId,
})
);
throw new Error(`Statement in ${fileName} failed. Error: ${error}`, {
cause: error,
});
}
};
const getFileNameTime = (fileName) =>
BigInt(`${fileName}`.split("_")[0].replace(".sql", ""));
const migrate = async (currentMigrationVersion) => {
const files = fs.readdirSync(`${process.env.PWD}/${migrationPath}`);
const currentMigrationFileTime = getFileNameTime(currentMigrationVersion);
const filteredFiles = files
.filter(
(file) =>
!currentMigrationVersion ||
getFileNameTime(file) > currentMigrationFileTime
)
.sort((a, b) =>
getFileNameTime(a) < getFileNameTime(b)
? -1
: getFileNameTime(a) > getFileNameTime(b)
? 1
: 0
);
if (!filteredFiles.length) {
console.log(
`${chalk.yellow("Warn:")} Current migration ${chalk.magenta(
currentMigrationVersion
)} is up to date`
);
return;
}
for (const file of filteredFiles) {
await executeFileStatements(file);
}
};
const run = async () => {
try {
await checkMigrationsSchema();
const currentMigrationVersion = await checkMigrationTable();
await migrate(currentMigrationVersion);
} catch (error) {
console.log(chalk.red(error));
}
};
run();