An SQL string can be built in many ways in JavaScript and other languages. Below are the variations I've seen and have used.
My personal favourite at the moment is the Concatenated array items.
Have your own way? Add it below.
var sql = 'SELECT * FROM table WHERE column = value';
- Simple
- Minimal typing
- Can't grow without becoming unreadable
var sql = 'SELECT * ';
sql += 'FROM table ';
sql += 'WHERE column = value ';
Or if you'd like things to line up:
var sql = '' ;
sql = 'SELECT *' ;
sql += 'FROM table ';
sql += 'WHERE column = value ';
- Simple(ish)
- Can grow as needed
- Each line is consistent
- A space is needed on each line (beginning or end)
- A bunch more typing for each line
var sql = [
'SELECT *',
'FROM table',
'WHERE column = value'
];
- Nice to read
- Will grow
- No leading/trailing space needed
- sql.join(' ') is needed when used
var sql = "SELECT * \
FROM table \
WHERE column = value";
- No extra whitespace required
- No need for closing/opening quotes repeatedly
- Will grow
- Having to escape newline looks ugly
- Whitespace after ecaped newline causes a vague error. The trailing space causes the issue
FROM•table•\•
var sql = multiline(function(){/*
SELECT *
FROM table
WHERE column = value
*/});
- Write everything as is
- No newline escape
- Will grow
- No extra whitespace
- Extra package dependency
- Micro performance hit
- JavaScript only (AFAIK)
ES6 natively supports multiline strings.
var sql = `
SELECT *
FROM table
WHERE column = value`;
- Write everything as is
- No newline escape
- Will grow
- Requires using es6-templates to compile JavaScript written using template strings to use ES5-compatible syntax OR you can use io.js instead of NodeJS as it ships with template string support.
knex('table').where({column: value})
- Easy to multiline
- Easy to compose
- Limits SQL injection
- Extra package dependency
- New syntax to learn
https://www.npmjs.org/package/querybox
box.run('query-table', [rowId], function(err, rows) {
console.log(rows[0].name)
})
- SQL in completely separate files
- Easy to multiline
- Easy to compose
- Limits SQL injection
- Easy copy and paste from SQL IDE
- Extra package dependency