SQLx
SQLx is an async SQL crate that talks to Postgres, MySQL, and SQLite without an ORM. Queries are strings (or macros that check them against a live database at compile time).
Detailed Explanation
SQLx gives you a pool, a transaction, and query / query_as. You write SQL. You map rows to structs with FromRow or with the query_as! macro. There is no identity map, no lazy-loaded relation graph, no Users.save(). If you want those, SeaORM or Diesel sit closer to an ORM. If you want SQL you can read, SQLx is the default in Tokio services.
query! and query_as! connect to a database at compile time (or use an offline cache of query metadata) and check that the SQL is valid and that the Rust types match the columns. A renamed column is a compile error. That is the headline feature. The cost is a database in CI or a committed .sqlx cache. query without the macro is a runtime string; you get errors when you run the query.
The API is async. Use it with Tokio. A Pool is what you put in Axum State. pool.begin().await? starts a transaction; tx.commit().await? commits; drop without commit rolls back. query_as::<_, User>("select ...").fetch_one(&mut *tx) runs inside the transaction. Do not take a connection from the pool for each line of a multi-step write without a transaction if they must be atomic.
SQLx does not invent a query builder you must use. The QueryBuilder exists for dynamic SQL (filters you may or may not add). Prefer static SQL plus AND fragments you control. Never concatenate a user string into the query; use bind parameters $1, ? depending on the engine.
When you reach for SQLx: a Tokio API with SQL you want to see. When you reach for Diesel: sync, heavy compile-time schema, a query DSL. When you reach for SeaORM: entities and relations with async.
Code Examples
struct User {
id: i64,
name: String,
}
fn bind_user_id(id: i64) -> i64 {
id // stands in for $1 in a real `query_as!`
}
fn main() {
let u = User { id: bind_user_id(17), name: "ada".into() };
println!("{} {}", u.id, u.name); // prints: 17 ada
}Common Gotchas
`query!` needs a database or offline metadata
A clean CI without `DATABASE_URL` or `.sqlx` will fail the compile. Commit the cache or provide the URL.
String-concatenated SQL is injection
Bind parameters. The macro will not save a format string you built by hand.
Async only
Calling SQLx from a sync function means `block_on` or a redesign. Do not block a Tokio worker on a sync wrapper either.
Forgetting `commit` rolls back
Drop of a `Transaction` is rollback. That is correct and surprising if you thought destructors commit.