-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Description
One of my favorite libraries from the node world is sql-template-strings
. It allows users to take something like this:
pg.query('SELECT author FROM books WHERE name = $1 AND author = $2', [book, author])
And instead write this:
pg.query(SQL`SELECT author FROM books WHERE name = ${book} AND author = ${author}`)
Notice the placement of the book
and author
variables -- they are placed inline inside the query. sql-template-strings
handles creating a prepared statement and ordering the parameters for query execution.
sqlx
reminds me a lot of the first snippet, with the primary additional benefit being that we can get type-safety inferred from the query (which on its own is very cool!). I don't know a lot about Rust macros, but I was wondering if it would be possible to take the sqlx
macro a step further and additionally implement sql-template-strings
-style inline parameters.
Edit:
Here's another example from the sql-template-strings
README showing the benefit when a lot of parameters are used:
db.query(
'INSERT INTO books (name, author, isbn, category, recommended_age, pages, price) VALUES (?, ?, ?, ?, ?, ?, ?)',
[name, author, isbn, category, recommendedAge, pages, price]
)
// is better written as
db.query(SQL`
INSERT
INTO books
(name, author, isbn, category, recommended_age, pages, price)
VALUES (${name}, ${author}, ${isbn}, ${category}, ${recommendedAge}, ${pages}, ${price})
`)