forked from lcarli/NodeRed-Azure-SQL
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathazuresql.js
191 lines (171 loc) · 6.33 KB
/
azuresql.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
module.exports = function (RED) {
var Connection = require('tedious').Connection;
var Request = require('tedious').Request;
var TYPES = require('tedious').TYPES;
var client = null;
var dbAddress = "";
var dbName = "";
var username = "";
var pass = "";
var queryString = "";
var messageJSON = "";
var node = null;
var nodeConfig = null;
var statusEnum = {
disconnected: { color: "red", text: "Disconnected" },
sending: { color: "green", text: "Sending" },
sent: { color: "blue", text: "Sent message" },
error: { color: "grey", text: "Error" },
connect: { color: "yellow", text: "Connected"}
};
var setStatus = function (status) {
node.status({ fill: status.color, shape: "dot", text: status.text });
}
//---------------------------------------------------------- DATABASE--------------------------------------------------------------------
function connectToDatabase(callback) {
if (client) {
client.close();
}
// Prepare config
var config = {
userName: username,
password: pass,
server: dbAddress,
options: {encrypt: true, database: dbName, rowCollectionOnDone: true}
};
// Create connection
client = new Connection(config);
client.on('connect', function(err) {
if (err) {
setStatus(statusEnum.error);
node.error('Error: ' +JSON.stringify(err));
node.log('Error: ' +JSON.stringify(err));
} else {
node.log("Connected");
setStatus(statusEnum.connect);
callback();
}
});
}
function executeStatement() {
request = new Request(queryString, function(err, rowCount, rows) {
node.log(rowCount + " rows returned");
if (err) {
setStatus(statusEnum.error);
node.error('Error: ' +JSON.stringify(err));
node.log('Error: ' +JSON.stringify(err));
}
});
var result = [];
var columnDetails= {};
request.on('row', function(columns) {
columns.forEach(function(column) {
if (column.value === null) {
node.log('NULL');
} else {
let columnName = column.metadata.colName;
columnDetails[columnName] = column.value;
}
});
result.push(columnDetails);
node.send(result);
setStatus(statusEnum.sent);
});
request.on('done', function(rowCount, more) {
node.log(rowCount + ' rows returned');
});
client.execSql(request);
}
function executeStatementToInsert() {
request = new Request(queryString+"; select @@identity", function(err, rowCount) {
if (err) {
setStatus(statusEnum.error);
node.error('Error: ' +JSON.stringify(err));
node.log('Error: ' +JSON.stringify(err));
} else {
console.log('Insert complete.');
setStatus(statusEnum.sent);
}
});
request.on('row', function(columns) {
node.log("Insert Complete. ID of inserted item is " + columns[0].value);
node.send("Insert Complete. ID of inserted item is " + columns[0].value);
});
client.execSql(request);
}
//---------------------------------------------------------- GENERAL--------------------------------------------------------------------
var disconnectFrom = function () {
if (client) {
node.log('Disconnecting from Azure SQL');
client.close();
client = null;
setStatus(statusEnum.disconnected);
}
}
// Main function called by Node-RED
function AzureSQL(config) {
// Store node for further use
node = this;
nodeConfig = config;
// Create the Node-RED node
RED.nodes.createNode(this, config);
dbAddress = node.credentials.serverAddress;
dbName = node.credentials.databaseName;
username = node.credentials.login;
pass = node.credentials.password;
this.on('input', function (msg) {
//Connecting to Database and querying
var messageJSON = null;
if (typeof (msg.payload) != "string") {
node.log("JSON");
messageJSON = msg.payload;
} else {
node.log("String");
//Converting string to JSON Object
//Sample string to QUERY : {"action": "Q", "query" : "SELECT * FROM table WHERE firstName = 'Lucas'"}
messageJSON = JSON.parse(msg.payload);
}
var action = messageJSON.action;
queryString = messageJSON.query;
// Sending action to Azure SQL
setStatus(statusEnum.sending);
switch (action) {
case "I":
node.log('Trying to insert data into Database');
connectToDatabase(executeStatementToInsert);
break;
case "Q":
node.log('Trying to query document');
connectToDatabase(executeStatement);
break;
default:
node.log('action was not detected');
node.error('action was not detected');
setStatus(statusEnum.error);
break;
}
});
this.on('close', function () {
disconnectFrom(this);
});
}
// Registration of the node into Node-RED to manage Databases
RED.nodes.registerType("Azure SQL", AzureSQL, {
credentials: {
serverAddress: { type: "text" },
databaseName: { type: "text" },
login: { type: "text" },
password: { type: "password" },
},
defaults: {
name: { value: "Azure SQL" },
}
});
// Helper function to print results in the node
function printResultFor(op) {
return function printResult(err, res) {
if (err) node.error(op + ' error: ' + err.toString());
if (res) node.log(op + ' status: ' + res.constructor.name);
};
}
}