felixfbecker / node-sql-template-strings

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

Add to Documentation/README that passing in string as Variable not Expression can convert string to SQL object #134

Open aaalexliu opened 4 years ago

aaalexliu commented 4 years ago
const SQL = require("sql-template-strings");
const exampleQuery = "SELECT * FROM example_table";
SQL(exampleQuery);
//returns: SQLStatement { strings: 'SELECT * FROM example_table', values: [] }

I love your package and have been using it extensively in my own project, but was having trouble converting some constants into SQL objects without using append. I figured out that calling SQL as a function and passing in a string variable does the trick. I would be happy to directly edit the README and submit a pull request if that works best.

Also I was wondering if it would be possible to create a new feature that allows the user to pass in an array of strings and get a complete SQL object in return, for example:

const SQL = require("sql-template-strings");
SQL(["SELECT * FROM", " example_table"]).text;
//returns: 'SELECT * FROM example_table'
//right now it's inserting a positional parameter between the strings

I would be happy to work on it and submit a pull request as well if that works best

aaalexliu commented 4 years ago

Sorry, the exampleQuery should actually be wrapped in an array as that is what the SQL object expects for output. So the code example should be:

const SQL = require("sql-template-strings");
const exampleQuery = "SELECT * FROM example_table";
SQL([exampleQuery]);
//returns: SQLStatement { strings: ['SELECT * FROM example_table'], values: [] }
felixfbecker commented 4 years ago

I'm sorry if I overlooked it in the issue, but what was the exact problem with

SQL`SELECT * FROM example_table`;

? My first intuition is that if that is failing in some way, that bug should be fixed (as opposed to documenting workarounds in the README)

aaalexliu commented 4 years ago

My apologies for not being clear, there are no issues with the current command, I was suggesting an extension of functionality in the case where the developer may want to store certain query strings and variables and finds repeated calls to append inconvenient. For example

const command = 'SELECT ';
const formatted_cols = ' to_char(date as 'yyyy-mm-dd') AS date'
const table = ' FROM example_table';

//more convenient:
SQL(command + formatted_cols + table);

//workaround:
SQL``.append(command).append(formatted_cols).append(table);
jose-dataka commented 3 years ago

I have the same problem and it's a great new funcionality.