-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathindex.js
389 lines (352 loc) · 11.4 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
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
'use strict';
const pg = require('pg');
const pgCopy = require('pg-copy-streams');
const QueryStream = require('pg-query-stream');
const JSONStream = require('JSONStream');
const Excel = require('exceljs');
const csv = require('fast-csv');
const fs = require('fs');
const fsp = require('fs').promises;
const path = require('path');
const Executor = require('@runnerty/module-core').Executor;
class postgresExecutor extends Executor {
constructor(process) {
super(process);
this.ended = false;
this.endOptions = {
end: 'end'
};
}
async exec(params) {
// MAIN:
try {
if (!params.command) {
if (params.command_file) {
// Load SQL file:
try {
await fsp.access(params.command_file, fs.constants.F_OK | fs.constants.W_OK);
params.command = await fsp.readFile(params.command_file, 'utf8');
} catch (err) {
throw new Error(`Load SQLFile: ${err}`);
}
} else {
this.endOptions.end = 'error';
this.endOptions.messageLog = 'execute-postgres dont have command or command_file';
this.endOptions.err_output = 'execute-postgres dont have command or command_file';
this._end(this.endOptions);
}
}
const query = await this.prepareQuery(params);
this.endOptions.command_executed = query;
const connectionOptions = {
user: params.user,
host: params.host,
database: params.database,
password: params.password,
port: params.port,
application_name: params.application_name || 'runnerty',
connectionTimeoutMillis: params.connectionTimeoutMillis || 60000,
query_timeout: params.query_timeout || false,
statement_timeout: params.statement_timeout || false,
idle_in_transaction_session_timeout: params.idle_in_transaction_session_timeout || false,
keepAlive: params.keepAlive || false,
keepAliveInitialDelayMillis: params.keepAliveInitialDelayMillis || 0,
encoding: params.encoding || 'utf8'
};
//SSL
if (params.ssl) {
try {
if (params.ssl.ca) params.ssl.ca = fs.readFileSync(params.ssl.ca);
if (params.ssl.cert) params.ssl.cert = fs.readFileSync(params.ssl.cert);
if (params.ssl.key) params.ssl.key = fs.readFileSync(params.ssl.key);
connectionOptions.ssl = params.ssl;
} catch (error) {
this.endOptions.end = 'error';
this.endOptions.messageLog = `execute-postgres reading ssl file/s: ${error}`;
this.endOptions.err_output = `execute-postgres reading ssl file/s: ${error}`;
this._end(this.endOptions);
}
}
const pool = new pg.Pool(connectionOptions);
pool.on('error', err => {
this.endOptions.end = 'error';
this.endOptions.messageLog = `execute-postgres: ${err}`;
this.endOptions.err_output = `execute-postgres: ${err}`;
this._end(this.endOptions);
});
const client = await pool.connect();
if (params.localInFile) await this.executeCopyFrom(client, query, params);
if (params.fileExport) await this.executeCopyTo(client, query, params);
if (params.jsonFileExport) await this.queryToJSON(client, query, params);
if (params.xlsxFileExport) await this.queryToXLSX(client, query, params);
if (params.csvFileExport) await this.queryToCSV(client, query, params);
if (
!params.localInFile &&
!params.fileExport &&
!params.jsonFileExport &&
!params.xlsxFileExport &&
!params.csvFileExport
)
await this.executeQuery(client, query);
} catch (error) {
this.error(error);
}
}
// Query to DATA_OUTPUT:
async executeQuery(client, query) {
try {
const results = await client.query(query);
var rows = [];
var rowCount = 0;
if (Array.isArray(results)) {
results.forEach(result => {
if (result.rows.length) {
rows.push(...result.rows);
} else {
rows.push(result);
}
rowCount += result.rowCount || 0;
})
} else {
if (results.rows.length) {
rows.push(...results.rows);
} else {
rows.push(results);
}
rowCount = results.rowCount;
}
this.prepareEndOptions(rows[0], rowCount, rows);
this._end(this.endOptions);
client.release();
} catch (err) {
this.error(err, client);
}
}
// COPY to plane file:
async executeCopyTo(client, query, params) {
try {
const resStream = client.query(pgCopy.to(query));
const fileStreamWriter = fs.createWriteStream(params.fileExport);
fileStreamWriter.on('error', error => {
this.error(error, client);
});
fileStreamWriter.on('finish', () => {
this.prepareEndOptions(firstRow, rowCounter);
this._end(this.endOptions);
client.release();
});
resStream.on('error', error => {
this.error(error, client);
});
// STREAMED
let isFirstRow = true;
let firstRow = {};
let rowCounter = 0;
resStream.on('data', row => {
if (isFirstRow) {
firstRow = row;
isFirstRow = false;
}
rowCounter++;
});
resStream.pipe(fileStreamWriter);
} catch (error) {
this.error(error, client);
}
}
// Query to JSON:
async queryToJSON(client, query, params) {
try {
await fsp.access(path.dirname(params.jsonFileExport));
const queryStream = new QueryStream(query);
const resStream = client.query(queryStream);
const fileStreamWriter = fs.createWriteStream(params.jsonFileExport);
fileStreamWriter.on('error', error => {
this.error(error, client);
});
fileStreamWriter.on('finish', () => {
this.prepareEndOptions(firstRow, rowCounter);
this._end(this.endOptions);
client.release();
});
resStream.on('error', error => {
this.error(error, client);
});
// STREAMED
let isFirstRow = true;
let firstRow = {};
let rowCounter = 0;
resStream.on('data', row => {
if (isFirstRow) {
firstRow = row;
isFirstRow = false;
}
rowCounter++;
});
resStream.pipe(JSONStream.stringify()).pipe(fileStreamWriter);
} catch (err) {
this.error(err, client);
}
}
// Query to XLSX:
async queryToXLSX(client, query, params) {
try {
await fsp.access(path.dirname(params.xlsxFileExport));
const queryStream = new QueryStream(query);
const resStream = client.query(queryStream);
const fileStreamWriter = fs.createWriteStream(params.xlsxFileExport);
const options = {
stream: fileStreamWriter,
useStyles: true,
useSharedStrings: true
};
const workbook = new Excel.stream.xlsx.WorkbookWriter(options);
const author = 'Runnerty';
const sheetName = 'Sheet';
const sheet = workbook.addWorksheet(params.xlsxSheetName ? params.xlsxSheetName : sheetName);
workbook.creator = params.xlsxAuthorName ? params.xlsxAuthorName : author;
workbook.lastPrinted = new Date();
fileStreamWriter.on('error', error => {
this.error(error, client);
});
resStream.on('error', error => {
this.error(error, client);
});
// STREAMED
let isFirstRow = true;
let firstRow = {};
let rowCounter = 0;
resStream.on('data', row => {
if (isFirstRow) {
firstRow = row;
sheet.columns = this.generateHeader(row);
isFirstRow = false;
}
sheet.addRow(row).commit();
rowCounter++;
});
resStream.on('end', async () => {
await workbook.commit();
this.prepareEndOptions(firstRow, rowCounter);
this._end(this.endOptions);
client.release();
});
} catch (err) {
this.error(err, client);
}
}
// Query to CSV:
async queryToCSV(client, query, params) {
try {
await fsp.access(path.dirname(params.csvFileExport));
const queryStream = new QueryStream(query);
const resStream = client.query(queryStream);
const fileStreamWriter = fs.createWriteStream(params.csvFileExport);
const paramsCSV = params.csvOptions || {};
if (!paramsCSV.hasOwnProperty('headers')) paramsCSV.headers = true;
const csvStream = csv.format(paramsCSV).on('error', err => {
this.error(err, client);
});
fileStreamWriter.on('error', error => {
this.error(error, client);
});
resStream.on('error', error => {
this.error(error, client);
});
// STREAMED
let isFirstRow = true;
let firstRow = {};
let rowCounter = 0;
resStream.on('data', row => {
if (isFirstRow) {
firstRow = row;
isFirstRow = false;
}
rowCounter++;
});
resStream.on('end', async data => {
this.prepareEndOptions(firstRow, rowCounter);
this._end(this.endOptions);
client.release();
});
resStream.pipe(csvStream).pipe(fileStreamWriter);
} catch (err) {
this.error(err, client);
}
}
// COPY FROM - LOAD DATA:
async executeCopyFrom(client, query, params) {
try {
await fsp.access(params.localInFile);
const resStream = await client.query(pgCopy.from(query));
const fileStreamReader = fs.createReadStream(params.localInFile);
fileStreamReader.on('error', error => {
this.error(error, client);
});
resStream.on('error', error => {
this.error(error, client);
});
resStream.on('finish', () => {
fileStreamReader.close();
this._end(this.endOptions);
client.release();
});
fileStreamReader.pipe(resStream);
} catch (error) {
this.error(error, client);
}
}
error(err, client) {
if (client) client.release();
this.endOptions.end = 'error';
this.endOptions.messageLog = `execute-postgres: ${err}`;
this.endOptions.err_output = `execute-postgres: ${err}`;
this._end(this.endOptions);
}
_end(endOptions) {
if (!this.ended) this.end(endOptions);
this.ended = true;
}
async prepareQuery(values) {
const options = {
useExtraValue: values.args || false,
useProcessValues: true,
useGlobalValues: true,
altValueReplace: 'null'
};
try {
const query = await this.paramsReplace(values.command, options);
return query;
} catch (err) {
throw err;
}
}
generateHeader(row) {
const columns = [];
for (let i = 0; i < Object.keys(row).length; i++) {
columns.push({
header: Object.keys(row)[i],
key: Object.keys(row)[i],
width: 30
});
}
return columns;
}
prepareEndOptions(firstRow, rowCounter, results) {
//STANDARD OUPUT:
this.endOptions.data_output = results || '';
//EXTRA DATA OUTPUT:
this.endOptions.extra_output = {};
this.endOptions.extra_output.db_countrows = rowCounter || '0';
this.endOptions.extra_output.db_firstRow = JSON.stringify(firstRow);
if (firstRow instanceof Object) {
const keys = Object.keys(firstRow);
let keysLength = keys.length;
while (keysLength--) {
const key = keys[keysLength];
this.endOptions.extra_output['db_firstRow_' + key] = firstRow[key];
}
}
}
}
module.exports = postgresExecutor;