node-sql-template-strings icon indicating copy to clipboard operation
node-sql-template-strings copied to clipboard

feat: Support for nested sql statements

Open skyjur opened this issue 6 years ago β€’ 4 comments

I think nested query statements gives much better readability compared to appends:

Let' say I have helpers

function authorFilter(author) {
  return SQL`author=${author}`;
}
function nameFilter(name) {
  return SQL`name=${name}`;
}

With append it would be:

SQL`SELECT author FROM books WHERE `
   .append(authorFilter(author))
   .append(' AND ')
   .append(nameFilter(book))`

With nested queries:

SQL`SELECT author FROM books WHERE
     ${authorFilter(author)} AND
     ${nameFilter(book)}`;

This also enables easy support for raw values:

const tableName = "books";

SQL`SELECT * FROM ${SQL([tableName])}`.sql;
// => SELECT * FROM books

However SQL( [ value ] ) syntax is slightly cryptic. I'd vote to bring back raw() as

SQL.raw = function(value) {
  return SQL([value]);
};

Or this:

function SQL(strings) {
   if(typeof strings === 'string') {
       return SQL([strings])
   else
  return new SQLStatement(strings.slice(0), Array.from(arguments).slice(1))
}

SQL`SELECT * FROM ${SQL(tableName)}`

This also solves use case described in https://github.com/felixfbecker/node-sql-template-strings/pull/72

skyjur avatar Apr 29 '18 17:04 skyjur

Codecov Report

Merging #79 into master will not change coverage. The diff coverage is 100%.

@@          Coverage Diff          @@
##           master    #79   +/-   ##
=====================================
  Coverage     100%   100%           
=====================================
  Files           1      1           
  Lines          35     45   +10     
  Branches        6      7    +1     
=====================================
+ Hits           35     45   +10
Impacted Files Coverage Ξ”
index.js 100% <100%> (ΓΈ) :arrow_up:

codecov[bot] avatar Apr 29 '18 17:04 codecov[bot]

@skyjur Is this PR still in development? If you are busy I am more than happy to help out. Really looking forward to that feature :)

KeKs0r avatar May 29 '18 07:05 KeKs0r

@KeKs0r it's kind of ready and I've used it in a few simple cases, but haven't done very extensive testing.

skyjur avatar May 29 '18 07:05 skyjur

@skyjur I love the idea of nested sql statements for so I implemented it in @sequencework/sql (which is shamelessly inspired by sql-template-strings). I'd love if you could try it and let me know what you think 😬

lucleray avatar Sep 20 '18 17:09 lucleray