2
\$\begingroup\$

How can I write a better database query wrapper?

//code for connection 
exports.connect = function(callback) {
 client.connect(function(err, conInfo){
 if (err) callback(err);
 conInfo = "Connection at " + client.host + ":" + client.port + "/"
 + client.database + " used by " + client.user;
 callback(null, conInfo);
 });
};
//for queries that do not return realation
exports.runQuery = function(query_str, columns, params, callback) {
 var sqlQuery = query_str + " " + columns;
 client.query(sqlQuery, params, function(err) {
 console.log("NEW QUERY____________________");
 console.log(sqlQuery);
 console.log(params);
 if (err) throw err;
 callback(null);
 });
};
//for select queries
exports.executeQuery = function(query_str, callback) {
 var query = client.query(query_str, function(err){
 console.log("NEW QUERY____________________");
 console.log(query_str);
 if (err) throw err;
 query.on("row", function(row, result) {
 result.addRow(row);
 });
 query.on("end", function (result) {
 callback(null, result.rows);
 });
 });
};
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Nov 13, 2013 at 18:42
\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

I don't do JS, even less node.js, but from the looks of it you seem to be taking in a string for your query, which means client code can do something like "select x, y, sum(z) from mytable where x = " + someValue + " group by x, y" - which is prone to SQL-injection: your client code needs to remember that.

If your executeQuery also took parameters, I think it would be clearer that when you need parameters, they should be passed as arguments to that function, not concatenated into the query string.

answered Nov 19, 2013 at 18:33
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.