-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathsqlapply.js
72 lines (63 loc) · 2.46 KB
/
sqlapply.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
// Setup the database from SQL files that hopefully are fully replayable
const { Pool } = require('pg')
const EventEmitter = require("events");
const fs = require("./fsasync.js");
const path = require("path");
Array.prototype.forEachAsync = async function (fn) {
for (let t of this) { await fn(t) }
};
exports.events = new EventEmitter();
async function sqlApply (directory, client) {
const dirExists = await fs.promises.exists(directory);
if (dirExists) {
let entries = await fs.promises.readdir(directory);
let filtered = entries.filter(entry => !entry.endsWith("~") && !entry.startsWith("."));
await filtered.forEachAsync(async entry => {
let sqlFile = path.join(directory, entry);
exports.events.emit("sqlFile", sqlFile);
let file = await fs.promises.readFile(sqlFile);
let statements = file.split("\n\n");
let sqlToRun = statements.filter(statement => !statement.startsWith("--"));
await sqlToRun.forEachAsync(async sql => {
try {
// console.log("sqlapply", sqlFile, sql.substring(0, 40) + "...");
let res = await client.query(sql);
}
catch (e) {
console.log(
"keepie sqlapply - error doing",
sqlFile, sql, e
);
}
});
});
}
return "hello";
}
exports.initDb = async function (directoryOrListOfDirectory, dbConfig) {
const pool = new Pool(dbConfig);
const client = await pool.connect();
if (directoryOrListOfDirectory !== undefined) {
try {
if (typeof(directoryOrListOfDirectory) == "string") {
await sqlApply(directoryOrListOfDirectory, client);
}
else if (typeof(directoryOrListOfDirectory) == "object"
&& directoryOrListOfDirectory.filter !== undefined
&& typeof(directoryOrListOfDirectory.filter) == "function") {
await directoryOrListOfDirectory.forEachAsync(async singleDirectory => {
await sqlApply(singleDirectory, client)
});
}
}
finally {
await client.release();
}
}
return pool;
};
async function init(config, sqlScriptDir) {
let client = await exports.initDb(sqlScriptDir, config);
await client.end()
};
// end here