forked from StellarSplit/StellarSplit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstream.helper.ts
More file actions
64 lines (58 loc) · 1.69 KB
/
Copy pathstream.helper.ts
File metadata and controls
64 lines (58 loc) · 1.69 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
import * as fs from "fs";
export async function streamQueryToCsv(
sql: string,
params: any[],
filePath: string,
headers: string[],
sectionLabel?: string,
) {
const { Pool } = require("pg");
const QueryStream = require("pg-query-stream");
const pool = new Pool({
host: process.env.DB_HOST || "localhost",
port: parseInt(process.env.DB_PORT || "5432", 10),
user: process.env.DB_USERNAME || "postgres",
password: process.env.DB_PASSWORD || "postgres",
database: process.env.DB_NAME || "stellarsplit_dev",
});
const client = await pool.connect();
try {
const qs = new QueryStream(sql, params);
const dbStream = client.query(qs);
if (sectionLabel) {
await fs.promises.appendFile(filePath, `${sectionLabel}\n`);
}
const writeStream = fs.createWriteStream(filePath, {
flags: "a",
encoding: "utf8",
});
writeStream.write(headers.join(",") + "\n");
await new Promise<void>((resolve, reject) => {
dbStream.on("data", (row: any) => {
try {
const line = headers
.map((h) => {
const v = String(row[h] ?? "");
if (v.includes(",") || v.includes("\n") || v.includes('"')) {
return '"' + v.replace(/"/g, '""') + '"';
}
return v;
})
.join(",");
writeStream.write(line + "\n");
} catch (err) {
reject(err);
}
});
dbStream.on("end", () => {
writeStream.end();
resolve();
});
dbStream.on("error", (err: any) => reject(err));
writeStream.on("error", (err) => reject(err));
});
} finally {
client.release();
await pool.end();
}
}