-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
69 lines (61 loc) · 2.09 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
const fs = require('fs');
const CSV = require('./lib/csv');
const JlSqlApi = require('jl-sql-api');
const parse = require('node-sqlparser').parse;
const api = new JlSqlApi ();
var m_filename = Symbol('filename');
var m_data = Symbol('data');
var m_options = Symbol('options');
class CsvFile {
constructor(filename, options) {
options = Object.assign({
headers: false,
convertNumbers: false,
overwriteOnExecute: false
}, options);
this[m_filename] = filename;
this[m_data] = CSV.parse(fs.readFileSync(this[m_filename], 'utf-8'), options);
this[m_options] = options;
}
query(sql) {
return new Promise((resolve, reject) => {
api.query(sql).fromArrayOfObjects(this[m_data]).toArrayOfObjects((rows) => {
resolve(rows);
});
})
}
execute(sql) {
return new Promise((resolve, reject) => {
api.query(sql).fromArrayOfObjects(this[m_data]).toArrayOfObjects((rows) => {
this[m_data] = rows;
if (this[m_options].overwriteOnExecute) {
fs.writeFile(this[m_filename], CSV.stringify(this[m_data], {
headerRow: this[m_options].headers !== false
}), (err) => {
if (err) {
return reject(err);
}
resolve();
});
} else {
resolve();
}
});
});
}
}
module.exports = {
open: function(connection) {
let options = {};
if (connection.Parameters) {
connection.Parameters.split('&').map(s => {
let [key, val] = s.split('=');
if (val.toLowerCase() === 'true') val = true;
if (val.toLowerCase() === 'false') val = false;
if (CSV.NUMBER_REGEX.test(val)) val = parseFloat(val);
options[key] = val;
});
}
return new CsvFile(connection.Database, options);
}
}