From 03514410755ef26b06c6331d592a6d27609bfea7 Mon Sep 17 00:00:00 2001 From: Marco <53404825+gre000@users.noreply.github.com> Date: Fri, 10 Apr 2020 23:53:17 +0200 Subject: [PATCH] MySQL allows to pass named parameters as object (#565) * add check isobj * added example to readme.md * edit if Syntax * add Documentation link to readme.md * fixed Syntax and edit readme.md --- storage/mysql/68-mysql.js | 18 +++++++++++++++++- storage/mysql/README.md | 23 +++++++++++++++++++++++ 2 files changed, 40 insertions(+), 1 deletion(-) diff --git a/storage/mysql/68-mysql.js b/storage/mysql/68-mysql.js index 95444e7f..c14ecccc 100644 --- a/storage/mysql/68-mysql.js +++ b/storage/mysql/68-mysql.js @@ -123,7 +123,23 @@ module.exports = function(RED) { node.on("input", function(msg) { if (node.mydbConfig.connected) { if (typeof msg.topic === 'string') { - var bind = Array.isArray(msg.payload) ? msg.payload : []; + //console.log("query:",msg.topic); + var bind = []; + if (Array.isArray(msg.payload)) { bind = msg.payload; } + else if (typeof msg.payload === 'object' && msg.payload !== null) { + bind=msg.payload; + node.mydbConfig.connection.config.queryFormat = function (query, values) { + if (!values){ + return query; + } + return query.replace(/\:(\w+)/g, function (txt, key) { + if (values.hasOwnProperty(key)) { + return this.escape(values[key]); + } + return txt; + }.bind(this)); + }; + } node.mydbConfig.connection.query(msg.topic, bind, function(err, rows) { if (err) { status = {fill:"red",shape:"ring",text:"Error: "+err.code}; diff --git a/storage/mysql/README.md b/storage/mysql/README.md index 0af76eba..015adf0c 100644 --- a/storage/mysql/README.md +++ b/storage/mysql/README.md @@ -27,3 +27,26 @@ If nothing is found for the key then null is returned. The reconnect retry timeout in milliseconds can be changed by adding a line to settings.js
mysqlReconnectTime: 30000,

+ + +Preparing Queries +----- +```javascript +msg.payload=[24, 'example-user']; +msg.topic="INSERT INTO users (`userid`, `username`) VALUES (?, ?);" +return msg; +``` + +with named parameters: + +```javascript +msg.payload={} +msg.payload.userToChange=42; +msg.payload.newUsername="example-user"; +msg.topic="INSERT INTO users (`userid`, `username`) VALUES (:userToChange, :newUsername) ON DUPLICATE KEY UPDATE `username`=:newUsername;" +return msg; +``` +Documentation +----- + +Documentation of the used Node.js package