Skip to content

Better dynamic query building #12

Closed
@okbrown

Description

@okbrown

Hi, First and foremost, I think this is a great start at making something really simple and effective. Thank you!!

However... I have always found template strings a little odd especially in this context.
Let us say we have

const query = `SELECT ${distinct}, ${columns} FROM ${table} ${innerJoins} WHERE ${where}`;
(Where distinct, columns, table etc are their own strings made up of other functions elsehwhere)
which basically outputs...

SELECT DISTINCT(person.uid), person.name, movie.title, movie.year
FROM person 
INNER JOIN movie_ref ON movie_ref.person_id = person.id
INNER JOIN movie ON movie.id = movie_ref.movie_id
WHERE person.name ILIKE '%luke%'

I should then be able to do sql`${query}`.then((data) => console.log(data) or await etc..

But instead I receive a syntax error:
Error: syntax error at or near "$1" at Object.generic (../node_modules/postgres/lib/types.js:200:5)

Gonna take a look at how this tagged template function is actually working as Im aware it takes the values $1, $2 etc.. and so forth to evaluate them and pass them to the statement e.g. select * from table where id = $1 => select * from table where id = somevalue

At the moment, it means I have to directly place all my select statements big or small in this method. Which will start looking very messy especially when queries become more complex and the app grows.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions