patternjavascriptMinor
Building SQL from multiple combinations of query parameters
Viewed 0 times
combinationssqlquerybuildingmultiplefromparameters
Problem
I have a node.js/express.js based REST application. In one GET service I am querying data based on different set of request parameters. I am looking for a better way to implement it.
Data can be queried by passing difference combination request parameters. Can anyone please suggest any better (reusable, abstract, robust) way of doing it? I was wondering if I can create a module for building query. Something like setting all param values in the module and let the module validate and construct the query.
function handleGet(connection,req,res) {
var sql = 'SELECT id, name, age, rent, marks FROM student WHERE class = 10';
if (req.param('minAge') && req.param('maxAge')) {
sql = sql + ' AND age BETWEEN ' + connection.escape(req.param('minAge')) + ' AND ' + connection.escape(req.param('maxAge'));
}
if (req.param('minRent') && req.param('maxRent')) {
sql =sql + ' AND rent BETWEEN ' + connection.escape(req.param('minRent'))
+ ' AND ' + connection.escape(req.param('maxRent'));
};
if (req.param('marks')) {
sql = sql + ' AND marks >= ' + connection.escape(req.param('marks'));
};
};
var limit = ('undefined' === typeof req.params.limit) ? 20: req.params.limit;
connection.query(sql + ' ORDER BY id DESC LIMIT ' + limit, function handleSql(err, rows){
if (err){ logAndRespond(err,res); return; }
if (rows.length === 0){ res.send(204); return; }
res.json(200, {'students':rows});
connection.release();
});
}Data can be queried by passing difference combination request parameters. Can anyone please suggest any better (reusable, abstract, robust) way of doing it? I was wondering if I can create a module for building query. Something like setting all param values in the module and let the module validate and construct the query.
Solution
Instead of dynamic string concatenation, you can do a logic trick. I'm going to use named sql placeholders for clarity. You'll obviously need to implement the code, I'm just giving you the idea.
You may need to check for an empty string instead of checking for null to detect when a param was omitted depending on you implementation, but you get the point - let each criteria be satisfied if the param is missing.
select a
, b
, c
from someTbl
where (:PMaxAge is null or maxAge = :PMinRent)
and (:PMaxRent is null or rent <= :PMaxRent)
-- etc ...You may need to check for an empty string instead of checking for null to detect when a param was omitted depending on you implementation, but you get the point - let each criteria be satisfied if the param is missing.
Code Snippets
select a
, b
, c
from someTbl
where (:PMaxAge is null or maxAge <= :PMaxAge)
and (:PMinRent is null or rent >= :PMinRent)
and (:PMaxRent is null or rent <= :PMaxRent)
-- etc ...Context
StackExchange Code Review Q#56202, answer score: 2
Revisions (0)
No revisions yet.