@bkmj/node-red-contrib-odbcmj 1.3.1 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/README.md +29 -19
  2. package/odbc.html +14 -36
  3. package/odbc.js +43 -32
  4. package/package.json +1 -1
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # node-red-contrib-odbcmj
2
2
 
3
- A Node-RED implementation of odbc.js (https://www.npmjs.com/package/odbc). This node allows you to make queries to a database through an ODBC connection. Additionally, parameters can be passed to the SQL query using Mustache syntax, prepared statements, or directly in the query string.
3
+ A Node-RED implementation of odbc.js (https://www.npmjs.com/package/odbc). This node allows you to make queries to a database through an ODBC connection. Parameters can be passed to the SQL query using Mustache syntax, prepared statements, or directly in the query string.
4
4
 
5
5
  ---
6
6
  ## Acknowledgment
@@ -17,6 +17,7 @@ This node is an unofficial fork of node-red-contrib-odbc by Mark Irish (https://
17
17
  * Connection nodes can have individually defined names.
18
18
  * Selectable SQL syntax checker.
19
19
  * Allows parameters to be passed as an object, mapping values to named parameters in the query.
20
+ * Automatically handles prepared statements based on the query and parameters.
20
21
 
21
22
  ## Installation
22
23
 
@@ -31,18 +32,21 @@ For the `odbc` connector requirements, please see [the documentation for that pa
31
32
 
32
33
  `node-red-contrib-odbcmj` provides two nodes:
33
34
 
34
- * **`odbc config`**: A configuration node for defining your connection string and managing your connection parameters.
35
- * **`odbc`**: A node for running queries with or without parameters passed using Mustache syntax, a parameter array, or a parameter object.
35
+ * **`odbc config`**: A configuration node for defining your connection string and managing your connection  
36
+ parameters.
37
+ * **`odbc`**: A node for running queries with or without parameters.
36
38
 
37
39
  ### `odbc config`
38
40
 
39
- A configuration node that manages connections in an `odbc.pool` object. [Can take any configuration property recognized by `odbc.pool()`](https://www.npmjs.com/package/odbc#constructor-odbcpoolconnectionstring). The connection pool will initialize the first time an `odbc` node receives an input message.
41
+ A configuration node that manages connections in an `odbc.pool` object. [Can take any configuration property recognized by `odbc.pool()`](https://www.npmjs.com/package/odbc#constructor-odbcpoolconnectionstring). The connection pool will initialize the first time  
42
+ an `odbc` node receives an input message.
40
43
 
41
44
  #### Properties
42
45
 
43
46
  * (**required**) **`connectionString`**: <`string`>
44
47
 
45
- An ODBC connection string that defines your DSN and/or connection string options. Check your ODBC driver documentation for more information about valid connection strings.
48
+ An ODBC connection string that defines your DSN and/or connection string options.  
49
+ Check your ODBC driver documentation for more information about valid connection strings.
46
50
 
47
51
  Example:
48
52
  ```
@@ -71,7 +75,8 @@ A configuration node that manages connections in an `odbc.pool` object. [Can tak
71
75
 
72
76
  * (optional) **`loginTimeout`**: <`number`>
73
77
 
74
- The number of seconds for an attempt to create a connection before returning to the application. Default: 3.
78
+ The number of seconds for an attempt to create a connection before returning to the application.  
79
+ Default: 3.
75
80
 
76
81
  * (optional) **`syntaxChecker`**: <`boolean`>
77
82
 
@@ -92,21 +97,18 @@ A node that runs a query when input is received. Each instance of the node can d
92
97
 
93
98
  The ODBC pool node that defines the connection settings and manages the connection pool used by this node.
94
99
 
95
- * (optional) **`queryType`**: <`string`>
96
-
97
- Selects the type of query to execute. Options are:
98
- * `query`: A regular SQL query. Parameters can be passed using Mustache templating or an array in `msg.parameters`.
99
- * `statement`: A prepared statement. Requires `msg.parameters`.
100
-
101
100
  * (optional) **`query`**: <`string`>
102
101
 
103
- A valid SQL query string.
104
- * For `queryType: "query"`, it can contain parameters inserted using Mustache syntax (e.g., `{{{payload}}}`). You can also use placeholders (`?`) and provide an array of values in `msg.parameters`.
105
- * For `queryType: "statement"`, it should use placeholders (`?`) for parameters.
102
+ A valid SQL query string.  
103
+
104
+ * Can contain parameters inserted using Mustache syntax (e.g., `{{{payload}}}`).
105
+ * Can use placeholders (`?`) for parameters.
106
+ * Can embed parameters directly in the query string.
106
107
 
107
108
  * (**required**) **`result to`**: <`dot-notation string`>
108
109
 
109
- The JSON nested element structure that will contain the result output. The string must be a valid JSON object structure using dot-notation, minus the `msg.` (e.g., `payload.results`) and must not start or end with a period. Square bracket notation is not allowed. The node input object is carried out to the output, as long as the output object name does not conflict with it. If the targeted output JSON object was already present in the input, the result from the query will be appended to it if it was itself an object (but not an array); otherwise, the original key/value pair will be overwritten.
110
+ The JSON nested element structure that will contain the result output. The string must be a valid JSON object structure using dot-notation, minus the `msg.` (e.g., `payload.results`) and must not start or end with a period. Square bracket notation is not allowed. The node input object is carried out to the output, as long as the output object name does not conflict with it. If the targeted output JSON object was already present in the input, the result from the query will be appended to it  
111
+ if it was itself an object (but not an array); otherwise, the original key/value pair will be overwritten.
110
112
 
111
113
  Example:
112
114
 
@@ -124,9 +126,8 @@ The `odbc` node accepts a message input that can contain:
124
126
  * A JSON string containing a `query` property with the SQL string.
125
127
  * An object with a `query` property containing the SQL string.
126
128
  * **`parameters`**: <`array` or `object`>
127
- * Required for prepared statements (`queryType: "statement"`).
128
129
  * Can be an array of values or an object mapping parameter names to values.
129
- * For regular queries (`queryType: "query"`) with placeholders (`?`), provide an array of values.
130
+ * If the query contains placeholders (`?`) and `msg.parameters` is an object, the values will be automatically mapped to the placeholders based on the order of the parameters in the query.
130
131
 
131
132
  #### Outputs
132
133
 
@@ -134,4 +135,13 @@ Returns a message containing:
134
135
 
135
136
  * **`output object`**: <`array`> The `odbc` result array returned from the query.
136
137
  * **`odbc`**: <`object`> Contains additional information returned by the `odbc` module.
137
- * **`parsedQuery`**: <`object`> (Optional) The parsed SQL query if the syntax checker is enabled.
138
+ * **`parsedQuery`**: <`object`> (Optional) The parsed SQL query if the syntax checker is enabled.
139
+
140
+ **Automatic Prepared Statement Handling**
141
+
142
+ The node automatically determines whether to use a prepared statement or a regular query based on the following:
143
+
144
+ * **Presence of Placeholders:** If the query string contains placeholders (`?`), the node will use a prepared statement.
145
+ * **`msg.parameters` Object:** If the `msg.parameters` object is provided (either as an array or an object), the node will use a prepared statement.
146
+
147
+ This automatic handling ensures that your queries are executed in the most secure way possible, minimizing the risk of SQL injection vulnerabilities.
package/odbc.html CHANGED
@@ -99,9 +99,7 @@
99
99
  defaults: {
100
100
  name: {value:""},
101
101
  connection: {type:"odbc config", required:true},
102
- queryType: { value: "query" },
103
102
  query: {value: ""},
104
- parameters: {value: ""},
105
103
  outputObj: {value:"payload"}
106
104
  },
107
105
  inputs:1,
@@ -116,16 +114,6 @@
116
114
  mode: 'ace/mode/sql',
117
115
  value: this.query
118
116
  });
119
- $("#node-input-queryType").on("change", function() {
120
- if ($(this).val() === "statement") {
121
- $("#node-input-parameters").show();
122
- } else {
123
- $("#node-input-parameters").hide();
124
- }
125
- });
126
-
127
- // Trigger the change event initially to set the visibility
128
- $("#node-input-queryType").trigger("change");
129
117
  },
130
118
  oneditsave: function() {
131
119
  this.query = this.editor.getValue();
@@ -151,24 +139,11 @@
151
139
  <input type="text" id="node-input-connection">
152
140
  </div>
153
141
 
154
- <div class="form-row">
155
- <label for="node-input-queryType"><i class="fa fa-code"></i> Query Type</label>
156
- <select id="node-input-queryType">
157
- <option value="query">Query</option>
158
- <option value="statement">Prepared Statement</option>
159
- </select>
160
- </div>
161
-
162
142
  <div class="form-row node-text-editor-row">
163
143
  <label for="node-input-query" style="width: 100% !important;"><i class="fa fa-search"></i> Query</label>
164
144
  <div style="height: 250px;" class="node-text-editor" id="node-input-query-editor" ></div>
165
145
  </div>
166
146
 
167
- <div class="form-row" id="node-input-parameters">
168
- <label for="node-input-parameters-editor"><i class="fa fa-list"></i> Parameters</label>
169
- <input type="text" id="node-input-parameters-editor">
170
- </div>
171
-
172
147
  <div class="form-row">
173
148
  <label for="node-input-outputObj"><i class="fa fa-edit"></i> Result to</label>
174
149
  <span>msg.</span><input type="text" id="node-input-outputObj" placeholder="payload" style="width: 64%;">
@@ -238,17 +213,12 @@ defined in the node properties.
238
213
 
239
214
  The ODBC pool node that defines the connection settings and manages the connection pool used by this node.
240
215
 
241
- * (optional) **`queryType`**: <`string`>
242
-
243
- Selects the type of query to execute. Options are:
244
- * `query`: A regular SQL query. Parameters can be passed using Mustache templating, a parameter array in `msg.parameters`, or directly in the query string.
245
- * `statement`: A prepared statement (requires `msg.parameters`).
246
-
247
216
  * (optional) **`query`**: <`string`>
248
217
 
249
218
  A valid SQL query string.
250
- * For `queryType: "query"`, it can contain parameters inserted using Mustache syntax (e.g., `{{{payload}}}`). You can also use placeholders (`?`) and provide an array of values in `msg.parameters`, or embed the parameters directly in the query string.
251
- * For `queryType: "statement"`, it should use placeholders (`?`) for parameters.
219
+ * Can contain parameters inserted using Mustache syntax (e.g., `{{{payload}}}`).
220
+ * Can use placeholders (`?`) for parameters.
221
+ * Can embed parameters directly in the query string.
252
222
 
253
223
  * (**required**) **`result to`**: <`dot-notation string`>
254
224
 
@@ -276,9 +246,8 @@ The `odbc` node accepts a message input that can contain:
276
246
  * A JSON string containing a `query` property with the SQL string.
277
247
  * An object with a `query` property containing the SQL string.
278
248
  * **`parameters`**: <`array` or `object`>
279
- * Required for prepared statements (`queryType: "statement"`).
280
- * Can be an array of values or an object mapping parameter names to values.
281
- * For regular queries (`queryType: "query"`) with placeholders (`?`), provide an array of values.
249
+ * Can be an array of values corresponding to the placeholders (`?`) in the query.
250
+ * Can be an object mapping parameter names to values. If the query contains placeholders (`?`) and `msg.parameters` is an object, the values will be automatically mapped to the placeholders based on the order of the parameters in the query.
282
251
 
283
252
  ## Outputs
284
253
 
@@ -287,4 +256,13 @@ Returns a message containing:
287
256
  * **`output object`**: <`array`> The `odbc` result array returned from the query.
288
257
  * **`odbc`**: <`object`> Contains additional information returned by the `odbc` module.
289
258
  * **`parsedQuery`**: <`object`> (Optional) The parsed SQL query if the syntax checker is enabled.
259
+
260
+ ## Automatic Prepared Statement Handling
261
+
262
+ The node automatically determines whether to use a prepared statement or a regular query based on the following:
263
+
264
+ * **Presence of Placeholders:** If the query string contains placeholders (`?`), the node will use a prepared statement.
265
+ * **`msg.parameters` Object/Array:** If the `msg.parameters` object/array is provided, the node will use a prepared statement.
266
+
267
+ This automatic handling ensures that your queries are executed in the most secure way possible, minimizing the risk of SQL injection vulnerabilities.
290
268
  </script>
package/odbc.js CHANGED
@@ -1,14 +1,14 @@
1
1
  module.exports = function(RED) {
2
- const odbcModule = require('odbc');
3
- const mustache = require('mustache');
4
- const objPath = require('object-path');
2
+ const odbcModule = require('odbc'); // Import the odbc module for database connectivity
3
+ const mustache = require('mustache'); // Import the mustache module for templating
4
+ const objPath = require('object-path'); // Import the object-path module for object manipulation
5
5
 
6
6
  // --- ODBC Configuration Node ---
7
7
  function poolConfig(config) {
8
- RED.nodes.createNode(this, config);
9
- this.config = config;
10
- this.pool = null;
11
- this.connecting = false;
8
+ RED.nodes.createNode(this, config); // Create a Node-RED node
9
+ this.config = config; // Store the node configuration
10
+ this.pool = null; // Initialize the connection pool
11
+ this.connecting = false; // Flag to indicate if the node is connecting
12
12
 
13
13
  const enableSyntaxChecker = this.config.syntaxtick; // Renamed for clarity
14
14
  const syntax = this.config.syntax;
@@ -71,8 +71,13 @@ module.exports = function(RED) {
71
71
  this.status({ fill: "blue", shape: "dot", text: "querying..." });
72
72
  this.config.outputObj = msg?.output || this.config?.outputObj;
73
73
 
74
- const isPreparedStatement = this.config.queryType === "statement";
74
+ // Automatically determine if it's a prepared statement based on the presence of
75
+ // placeholders (?) in the query or if msg.parameters is an object/array.
76
+ const isPreparedStatement = msg?.parameters || (this?.queryString ? this.queryString.includes('?') : false);
75
77
  this.queryString = this.config.query;
78
+ if (!this.queryString.length) {
79
+ this.queryString = null;
80
+ }
76
81
 
77
82
  // --- Construct the query string ---
78
83
  if (!isPreparedStatement && this.queryString) {
@@ -89,6 +94,9 @@ module.exports = function(RED) {
89
94
 
90
95
  // Handle cases where the query is provided in the message
91
96
  if (msg?.query) {
97
+ if (this.queryString) {
98
+ node.log('Warning. The query defined in the node configuration was overwritten by msg.config.');
99
+ }
92
100
  this.queryString = msg.query;
93
101
  } else if (msg?.payload) {
94
102
  if (typeof msg.payload === 'string') {
@@ -107,18 +115,26 @@ module.exports = function(RED) {
107
115
  throw new Error("No query to execute");
108
116
  }
109
117
 
110
- // --- Parameter validation for prepared statements ---
118
+ // --- Parameter handling for prepared statements ---
111
119
  if (isPreparedStatement) {
112
- if (this.queryString.includes('?')) {
113
- if (!msg?.parameters) {
114
- throw new Error("Prepared statement requires msg.parameters");
115
- } else if (!Array.isArray(msg.parameters)) {
116
- throw new Error("msg.parameters must be an array");
117
- } else if ((this.queryString.match(/\?/g) || []).length !== msg.parameters.length) {
118
- throw new Error("Incorrect number of parameters");
119
- }
120
+ if (!msg?.parameters) {
121
+ throw new Error("Prepared statement requires msg.parameters");
120
122
  } else {
121
- this.warn("Prepared statement without parameters. Consider using a regular query.");
123
+ // If parameters are provided as an object, extract parameter names from the query
124
+ // and create an ordered array of values for the prepared statement.
125
+ if (typeof msg.parameters === 'object' && !Array.isArray(msg.parameters)) {
126
+ const paramNames = this.queryString.match(/\(([^)]*)\)/)[1].split(',').map(el => el.trim());
127
+
128
+ // Create an ordered array of values
129
+ msg.parameters = paramNames.map(name => msg.parameters[name]);
130
+ }
131
+ }
132
+
133
+ // Validate the parameters array
134
+ if (!Array.isArray(msg.parameters)) {
135
+ throw new Error("msg.parameters must be an object or an array");
136
+ } else if ((this.queryString.match(/\?/g) || []).length !== msg.parameters.length) {
137
+ throw new Error("Incorrect number of parameters");
122
138
  }
123
139
  }
124
140
 
@@ -159,20 +175,16 @@ module.exports = function(RED) {
159
175
  try {
160
176
  let result;
161
177
  if (isPreparedStatement) {
162
- const stmt = await this.connection.prepare(this.queryString);
163
- let values = msg.parameters;
164
-
165
- if (typeof values === 'object' && !Array.isArray(values)) {
166
- // Assuming your parameters are like this: (param1, param2, param3)
167
- const paramNames = this.queryString.match(/\(([^)]*)\)/)[1].split(',').map(el => el.trim());
168
-
169
- // Create an ordered array of values
170
- values = paramNames.map(name => msg.parameters[name]);
171
- }
172
-
178
+ // --- Execute prepared statement ---
179
+ const stmt = await this.connection.createStatement();
180
+ await stmt.prepare(this.queryString);
181
+
182
+ // Bind the values to the prepared statement
183
+ await stmt.bind(msg.parameters);
184
+
173
185
  // Execute the prepared statement
174
- const result = await stmt.execute(values);
175
- stmt.finalize();
186
+ result = await stmt.execute();
187
+ stmt.close();
176
188
  } else {
177
189
  // --- Execute regular query ---
178
190
  result = await this.connection.query(this.queryString, msg?.parameters);
@@ -201,7 +213,6 @@ module.exports = function(RED) {
201
213
  }
202
214
  } catch (error) {
203
215
  // Handle query errors (e.g., log the error, set node status)
204
- this.error(`Error executing query: ${error}`);
205
216
  this.status({ fill: "red", shape: "ring", text: "Query error" });
206
217
  throw error; // Re-throw to trigger the outer catch block
207
218
  } finally {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bkmj/node-red-contrib-odbcmj",
3
- "version": "1.3.1",
3
+ "version": "1.5.0",
4
4
  "description": "Node Red implementation of odbc.js",
5
5
  "keywords": [
6
6
  "node-red",