2

I can't find any note on this topic in the docs, I hope someone has a solution. I'm trying to escape my queryparameters, but I can' add an alias without breaking the query.

What I want to achieve:

SELECT order.name as orderName, customer.name as customerName FROM order LEFT JOIN customer ON order.customerID = customer.id

What I'm doing:

let order = 'order.name as orderName';
let customer = 'customer.name as customerName';
let str = "SELECT ?? FROM order ...."
connection.query(str, [[order,customer]], function(err,res,fields){...}

What I get:

SELECT 'order'.'name as orderName, customer'.'name as customerName' FROM order ...

Obviously this won't work. How can I pass an alias to an escaped param??

edit: If I use only one '?' I get the following query, which won't work as well:

SELECT 'order.name as orderName', 'customer.name as customerName' FROM order

Thanks a lot!

The reason I'm not writing the query at once, are the confusing line breaks in javascript ('xyz, ' + ' abcd, ' + .. if I miss one blank space at the end of a line, js will concat them). I want those long queries to be as readable as possible. splitting the columnnames in single var's seems to be the only way. Or has someone a good approach for this?

CJay87
  • 21
  • 2
  • `?` operator for escaping query values. That will replace value as it is into the query including quotes. For field names, it's better to add it into the query or concat your variable into the query. – Tamilvanan Oct 04 '18 at 10:20
  • @TamilvananN Thanks! Problem: If I use only one '?' I get the following query, which won't work: SELECT 'order.name as orderName', 'customer.name as customerName' FROM order – CJay87 Oct 04 '18 at 10:26
  • It might be the reason of the second param `[[order,customer]]`. I think it should be in single array object like `[order,customer]` – Tamilvanan Oct 04 '18 at 10:29
  • @TamilvananN with a one-level array I need one "?" for each element. But the result is the same ... `SELECT ?,? FROM ...` => `SELECT 'order.name as orderName', 'customer.name as customerName' FROM order` – CJay87 Oct 04 '18 at 10:37
  • Yeah, that's correct. So, we have to declare a string without quotes! – Tamilvanan Oct 04 '18 at 10:45
  • Look into this, https://www.npmjs.com/package/sqlstring#formatting-queries – Tamilvanan Oct 04 '18 at 10:53
  • @Tamilvanan were you able to use alias ? – Mithiridi Prasanth Sep 28 '21 at 16:57

0 Answers0