gajus / slonik

A Node.js PostgreSQL client with runtime and build time type safety, and composable SQL.
Other
4.58k stars 139 forks source link

Joining tagged template fragments #78

Closed nodefish closed 5 years ago

nodefish commented 5 years ago

I know you want to discourage dynamic queries, but surely they should have some support in Slonik that is safer than sql.raw and doesn't make me leave Slonik's API completely in favor of a query builder like sqorn.

I find myself doing things like this...

const and_conditions = [];
conditions.forEach(cnd => or_conditions.push(`${cnd.col} LIKE '%${cnd.val}%'`));
const or_fragment = `(${or_conditions.join(' OR ')})`;
if (or_fragment) and_conditions.push(or_fragment);

...and subsequently either using sql.raw for everything at the last stage when I combine the fragments, or fighting against Slonik in an attempt to get some safety, e.g. trying to add Slonik safety like:

const and_conditions = [];
conditions.forEach(cnd => or_conditions.push(sql`${sql.identifier([cnd.col])} LIKE '%${cnd.val}%'`));
const or_fragment = `(${or_conditions.join(' OR ')})`; // <-- no longer valid
if (or_fragment) and_conditions.push(or_fragment);
[...]
const fragment = sql`${base_fragment} WHERE ${and_conditions.join(' AND ')}; // <-- no longer valid

Would it be possible to provide something like a join method on the output object of tagged template literals or something along those lines in order to enhance composability? I'm not actually sure what a good solution would look like, but I feel like composability without totally losing safety is a reasonable goal for this project given that's supposed to be its main strength compared to using node-pg.

gajus commented 5 years ago

https://github.com/gajus/slonik#slonik-query-building-sql-booleanexpression

baerrach commented 4 years ago

sql.booleanExpression was removed in favour of sql.join but the article has not been updated.

See feat: remove multiple methods in favor of sql.join

The doc link is now https://github.com/gajus/slonik#slonik-query-building-sql-join