Expand description
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:
#[derive(sqlx::FromRow)]
struct User {
id: u32,
name: String,
}
#[queries::queries(database = sqlx::Postgres)]
trait MyQueries {
#[query = "SELECT * FROM users WHERE id = $1"]
async fn get_user_by_id(id: u32) -> Option<User>;
}
You can then use MyQueries
with either a connection pool or transaction:
// Using a connection pool
let connection_pool = sqlx::PgPool::connect("...").await?;
let q = MyQueries::from_pool(connection_pool);
let user = q.get_user_by_id(42).await?;
// Using a transaction
let tx = connection_pool.begin().await?;
let mut q = MyQueries::from_tx(tx);
let user = q.get_user_by_id(42).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>
(whereT
implementssqlx::FromRow
)Vec<T>
(whereT
implementssqlx::FromRow
)futures::stream::BoxStream<'_, sqlx::Result<T>>
(whereT
implementssqlx::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 useMyQueries
with both PostgreSQL and SQLite, you’d need separate declarations). - All query functions are
async
.
Structs§
- Multiple
Rows Found - An error indicating that a query which expected 1 (or fewer) rows received multiple rows.