I am fairly new to node and have a problem with dynamic parameterized queries using sqlstring.
The issue with the below code is that filters are optional depending on what a user passes into the function so the order of them can change (making it hard to pass in each filter parameter separately). As far as i know Sqlstring uses the order to determine what parameter matches the proper question mark.
So i am left with passing in all the filters to Sqlstring at once, but If no filters are active then i just get left with an empty string for the filters variable, which will throw a sql syntax error.
let filter = idList !== '' ? ` AND id IN(${idList})` : '';
filter += locationsList !== '' ? ` AND a.locationID IN(${locationsList})` : '';
filter += start !== undefined ? ` AND a.lastEdited >= ${start}` : '';
filter += end !== undefined ? ` AND a.lastEdited <= ${end}` : '';
filter += name !== undefined ? ` AND a.name LIKE '%${name}%'` : '';
const qry = `
SELECT
a.id 'id'
,a.number 'number'
,a.name 'name'
,a.locationID 'locationID'
,a.location 'location'
,a.lastEdited 'lastEdited'
,a.userID 'owner'
FROM tbl_foo_${'?'} a
WHERE a.id > ${'?'} ${'?'} LIMIT ${'?'};`;
let values = [ id, cursor, filter, limit ];
const rows = query(db, qry, values);
//inside of the query function it does this and then runs the query against the database
if (qry.includes('?')) {
sanitizedQry = sqlstring.format(qry, values);
}
The query it produces would look like this:
SELECT
a.id 'id'
,a.number 'number'
,a.name 'name'
,a.locationID 'locationID'
,a.location 'location'
,a.lastEdited 'lastEdited'
,a.userID 'owner'
FROM tbl_foo_36 a
WHERE a.id > 1 '' LIMIT 100;
Is there a better way to do this?