felixfbecker / node-sql-template-strings

ES6 tagged template strings for prepared SQL statements 📋
ISC License
610 stars 40 forks source link

Allow to build complex queries by bypass SqlStatement instance as parameter #30

Open Strate opened 7 years ago

Strate commented 7 years ago

Seems that it is not possible right now to do something like this:

import {SQL} from "sql-template-strings"

function prepareSet(values) { /* implementation skipped */}

pg.query(SQL`UPDATE ${SQL("table")} SET ${SQL(prepareSet({key: value})} WHERE id = ${id}`)

I mean that if parameter is already instance of SQLStatement, it could be inserted to query as-is (with possible merging nested parameters).

What do you think about it?

felixfbecker commented 7 years ago

This functionality is provided with .append(). I think passing template strings into template strings is confusing tbh.

Strate commented 7 years ago

As for me, this one:

pg.query(SQL`UPDATE ${SQL("table")} SET ${SQL(prepareSet({key: value})} WHERE id = ${id}`)

is less confusing than

pg.query(SQL`UPDATE `.append("table SET").append(prepareSet({key: value})).append(SQL` WHERE id = ${id}`)

btw, you can choose the way as you want, I suggest just to allow passing SQLStatement as template variable.

Would you accept PR?

felixfbecker commented 7 years ago

I guess why not, as long as it has test cases covering all the cases where both statements have values and not

felixfbecker commented 7 years ago

Btw, SQL("table") doesn't actually work. The first parameter to a template string tag is an array.

Janpot commented 6 years ago

Maybe you could draw inspiration from pg-template-tag? This one allows nesting. Also the immutable nature makes it feel more like working with a string, which comes more natural to me.

WebReflection commented 5 years ago

My pull request would allow the following:

// example (no idea what prepareSet would do)
const prepareSet = obj => SQL`preparedName = ${obj.key}`;

// auto back-tick escaping of single/double quoted parts + auto merge of values
SQL`UPDATE '${`table_${name}`}' SET ${prepareSet({
  key: value
})} WHERE id = ${id}`;

Hope that works better for this case too 👋