I've written a microservice that is doing external calls to a SQL database. I have a js file that is solely dedicated to these awful looking queries that are formed as a string..
let data_example = 'SELECT * \
WHERE BLAH = BLAH AND \
....';
It's barely human readable and looks awful. What's the best way to store/organize or approach a long SQL query string that needs to be stored and called in Node?
I've written a microservice that is doing external calls to a SQL database. I have a js file that is solely dedicated to these awful looking queries that are formed as a string..
let data_example = 'SELECT * \
WHERE BLAH = BLAH AND \
....';
It's barely human readable and looks awful. What's the best way to store/organize or approach a long SQL query string that needs to be stored and called in Node?
Share Improve this question asked Jun 21, 2016 at 13:21 Ryan ShockerRyan Shocker 7131 gold badge10 silver badges25 bronze badges1 Answer
Reset to default 6You have a couple of options.
You could store them in a file you read at program startup, so you're authoring them in a tool that understands SQL, perhaps can even connect to your DB to auto-plete things for you, can help you format, do syntax highlighting, etc.
You can use ES2015 ("ES6") template strings (also called "template literals"):
let data_example = ` SELECT * WHERE BLAH = BLAH AND ... `;
Template strings can span lines (note that newlines, and whitespace at the beginning of subsequent lines, are part of the string).
Just be sure you don't use the features of template strings to fill in parameters through (hidden) string concatenation, because That Would Be Wrong™. :-) That is, just like you wouldn't do this:
// We know NOT to do this example = "WHERE SomeColumn = '" + userInputValue + "'";
don't do the same thing using the hidden string concatenation of template strings:
// We also know NOT to do this example = `WHERE SomeColumn = ${userInputValue};`
....which is how you would do that string concatenation using a template string. If you're in the habit of using template strings, it would be really easy to do that by mistake, and have an SQL Injection vector.
There are probably use cases for both options.