queries is a library that makes it easy to manage SQL queries in Rust.
Its goal is to provide a straight forward way for developers to write SQL
queries and use them in applications (without any risk of SQL injection).
It is heavily inspired by JDBI's SQLobject.
queries builds on top of sqlx.
Usage
The core API is the #[queries::queries] proc-macro. For example, you
might use it like:
You can then use MyQueries with either a connection pool or transaction:
// Using a connection pool
let connection_pool = connect.await?;
let q = from_pool;
let user = q.get_user_by_id.await?;
// Using a transaction
let tx = connection_pool.begin.await?;
let mut q = from_tx;
let user = q.get_user_by_id.await?;
q.commit.await?; // or q.rollback().await?
In short, you can declare the signature for each of your queries in a trait, and then make use of them.
All return values are automatically wrapped in a sqlx::Result<>.
Features
queries should work with any database supported by sqlx.
queries supports connection pools (from_pool()) and transactions
(from_tx()). Transactions provide commit() and rollback() methods.
Query parameters can use any types that sqlx supports (i.e., that
implement the sqlx::Type and sqlx::Encode traits).
Query return values can be:
- Any type that implements
sqlx::FromRow. Option<T>(whereTimplementssqlx::FromRow)Vec<T>(whereTimplementssqlx::FromRow)futures::stream::BoxStream<'_, sqlx::Result<T>>(whereTimplementssqlx::FromRow)
For query return types that expect a single row, if the underlying query
returns multiple rows then a sqlx::Decode error will be returned with an
inner error of queries::MultipleRowsFound.
Limitations
- A given
#[queries::queries]can only work with a single database (e.g., you can't useMyQuerieswith both PostgreSQL and SQLite, you'd need separate declarations). - All query functions are
async.