-
Notifications
You must be signed in to change notification settings - Fork 4
/
table_insert.js
136 lines (98 loc) · 3.01 KB
/
table_insert.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
module.exports = function(RED) {
"use strict";
var hanaClient = require('@sap/hana-client');
var async = require('async');
function isInt(n){
return Number(n) === n && n % 1 === 0;
}
function isFloat(n){
return Number(n) === n && n % 1 !== 0;
}
function insertNode(n){
//console.dir(n);
RED.nodes.createNode(this, n);
this.mydbConf = n.mydb;
this.table = n.table;
this.columns = n.columns.split(',');
var columns = [];
for(var c = 0; c < this.columns.length; c++){
columns.push('"' + this.columns[c] + '"');
}
var columnsForSql = columns.join(',');
this.hanaConfig = RED.nodes.getNode(this.mydbConf);
var node = this;
node.on("input", function(msg, send, done) {
node.warn("Payload : " + JSON.stringify(msg.payload));
if(typeof msg.payload[0] !== 'object'){
msg.payload = [ msg.payload ];
}
var conn = hanaClient.createConnection();
node.conn_params = {
host : node.hanaConfig.host,
port : node.hanaConfig.port,
user : node.hanaConfig.user,
password : node.hanaConfig.password
};
conn.connect(node.conn_params, function(err, result) {
if(err) {
node.warn("Connection Params : " + JSON.stringify(node.conn_params));
node.warn(err);
var errMess = "Connection failed for host " + node.hanaConfig.host + " with user " + node.hanaConfig.user;
node.warn(errMess);
msg.statusCode = 500;
msg.payload = err;
send(msg);
done();
}
else
{
var fnExec = [];
for(var i = 0; i < msg.payload.length; i++){
let values = [];
for(var c = 0; c < node.columns.length; c++){
let col = node.columns[c];
let val = msg.payload[i][col];
if(isInt(val) || isFloat(val)){
values.push(val);
}
else{
values.push("'" + val + "'");
}
}
let valuesForSql = values.join(',');
let sql = 'INSERT INTO "' + node.table + '" (' + columnsForSql + ') VALUES (' + valuesForSql + ');';
node.warn("SQL loop : " + sql);
var fn = function(callback){
conn.exec(sql, [], function (err2, result2) {
if (err2) {
node.warn(err2);
callback(null, err2);
}
else{
callback(null, result2);
}
});
};
fnExec.push(fn);
}
async.series(
fnExec,
function(err, results) {
node.warn("Async insert results : " + JSON.stringify(results) );
var total = 0;
for(var r = 0; r < results.length; r++){
total += results[r];
}
msg.statusCode = 200;
msg.payload = total;
send(msg);
done();
conn.disconnect();
}
);
}
});
});
}
RED.nodes.registerType("table_insert", insertNode);
}