🧰 The Rust SQL Toolkit. An async, pure Rust SQL crate featuring compile-time checked queries without a DSL. Supports PostgreSQL, MySQL, and SQLite.
🧰 The Rust SQL Toolkit. An async, pure Rust SQL crate featuring compile-time checked queries without a DSL. Supports PostgreSQL, MySQL, and SQLite.
SQLx is an async, pure Rust† SQL crate featuring compile-time checked queries without a DSL.
Truly Asynchronous. Built from the ground-up using async/await for maximum concurrency.
Compile-time checked queries (if you want). See SQLx is not an ORM.
Database Agnostic. Support for PostgreSQL, MySQL, MariaDB, SQLite.
Pure Rust. The Postgres and MySQL/MariaDB drivers are written in pure Rust using zero unsafe†† code.
Runtime Agnostic. Works on different runtimes (async-std / tokio / actix) and TLS backends (native-tls, rustls).
† The SQLite driver uses the libsqlite3 C library as SQLite is an embedded database (the only way we could be pure Rust for SQLite is by porting all of SQLite to Rust).
†† SQLx uses #![forbid(unsafe_code)] unless the sqlite feature is enabled.
The SQLite driver directly invokes the SQLite3 API via libsqlite3-sys, which requires unsafe.
Cross-platform. Being native Rust, SQLx will compile anywhere Rust is supported.
Built-in connection pooling with sqlx::Pool.
Row streaming. Data is read asynchronously from the database and decoded on demand.
Automatic statement preparation and caching. When using the high-level query API (sqlx::query), statements are
prepared and cached per connection.
Simple (unprepared) query execution including fetching results into the same Row types used by
the high-level API. Supports batch execution and returns results from all statements.
Transport Layer Security (TLS) where supported (MySQL, MariaDB and PostgreSQL).
Asynchronous notifications using LISTEN and NOTIFY for PostgreSQL.
Nested transactions with support for save points.
Any database driver for changing the database driver at runtime. An AnyPool connects to the driver indicated by the URL scheme.
SQLx is compatible with the async-std, tokio, and actix runtimes; and, the native-tls and rustls TLS backends. When adding the dependency, you must choose a runtime feature that is runtime + tls.
…For backward-compatibility reasons, the runtime and TLS features can either be chosen together as a single feature, or separately.
For forward compatibility, you should use the separate runtime and TLS features as the combination features may be removed in the future.
runtime-async-std: Use the async-std runtime without enabling a TLS backend.
runtime-tokio: Use the tokio runtime without enabling a TLS backend.
tls-native-tls: Use the native-tls TLS backend (OpenSSL on *nix, SChannel on Windows, Secure Transport on macOS).
tls-rustls: Use the rustls TLS backend (cross-platform backend, only supports TLS 1.2 and 1.3).
tls-rustls-aws-lc-rs: Use the rustls TLS backend with aws-lc-rs.
postgres: Add support for the Postgres database server.
mysql: Add support for the MySQL/MariaDB database server.
Note: RSA auth without TLS requires mysql-rsa (not enabled by mysql).
mysql-rsa: Enable RSA password encryption for caching_sha2_password/sha256_password when TLS is off. Only enable it if you must connect without TLS to servers that require RSA auth. Prefer using TLS.
mssql: Add support for the MSSQL database server.
sqlite: Add support for the self-contained SQLite database engine with SQLite bundled and statically-linked.
sqlite-unbundled: The same as above (sqlite), but link SQLite from the system instead of the bundled version.
rusqlite README for details.3.20.0 or newer is recommended.sqlite-preupdate-hook: enables SQLite's preupdate hook API.
sqlite-unbundled may cause linker failures if the system SQLite version does not support it.any: Add support for the Any database driver, which can proxy to a database driver at runtime.
derive: Add support for the derive family macros, those are FromRow, Type, Encode, Decode.
macros: Add support for the query*! macros, which allows compile-time checked queries.
migrate: Add support for the migration management and migrate! macro, which allow compile-time embedded migrations.
uuid: Add support for UUID.
chrono: Add support for date and time types from chrono.
time: Add support for date and time types from time crate (alternative to chrono, which is preferred by query! macro, if both enabled)
bstr: Add support for bstr::BString.
bigdecimal: Add support for NUMERIC using the bigdecimal crate.
rust_decimal: Add support for NUMERIC using the rust_decimal crate.
ipnet: Add support for INET and CIDR (in postgres) using the ipnet crate.
ipnetwork: Add support for INET and CIDR (in postgres) using the ipnetwork crate.
json: Add support for JSON and JSONB (in postgres) using the serde_json crate.
Offline mode is now always enabled. See sqlx-cli/README.md.
SQLx supports compile-time checked queries. It does not, however, do this by providing a Rust API or DSL (domain-specific language) for building queries. Instead, it provides macros that take regular SQL as input and ensure that it is valid for your database. The way this works is that SQLx connects to your development DB at compile time to have the database itself verify (and return some info on) your SQL queries. This has some potentially surprising implications:
If you are looking for an (asynchronous) ORM, you can check out our new Ecosystem wiki page!
See the examples/ folder for more in-depth usage.
…A single connection can be established using any of the database connection types and calling connect().
use sqlx::Connection;
let conn = SqliteConnection::connect("sqlite::memory:").await?;Generally, you will want to instead create a connection pool (sqlx::Pool) for the application to
regulate how many server-side connections it's using.
let pool = MySqlPool::connect("mysql://user:pass@host/database").await?;In SQL, queries can be separated into prepared (parameterized) or unprepared (simple). Prepared queries have their
query plan cached, use a binary mode of communication (lower bandwidth and faster decoding), and utilize parameters
to avoid SQL injection. Unprepared queries are simple and intended only for use where a prepared statement
will not work, such as various database commands (e.g., PRAGMA or SET or BEGIN).
SQLx supports all operations with both types of queries. In SQLx, a &str is treated as an unprepared query,
and a Query or QueryAs struct is treated as a prepared query.
// low-level, Executor trait
conn.execute("BEGIN").await?; // unprepared, simple query
conn.execute(sqlx::query("DELETE FROM table")).await?; // prepared, cached queryWe should prefer to use the high-level query interface whenever possible. To make this easier, there are finalizers
on the type to avoid the need to wrap with an executor.
sqlx::query("DELETE FROM table").execute(&mut conn).await?;
sqlx::query("DELETE FROM table").execute(&pool).await?;The execute query finalizer returns the number of affected rows, if any, and drops all received results.
In addition, there are fetch, fetch_one, fetch_optional, and fetch_all to receive results.
The Query type returned from sqlx::query will return Row<'conn> from the database. Column values can be accessed
by ordinal or by name with row.get(). As the Row retains an immutable borrow on the connection, only one
Row may exist at a time.
The fetch query finalizer returns a stream-like type that iterates through the rows in the result sets.
// provides `try_next`
use futures_util::TryStreamExt;
// provides `try_get`
use sqlx::Row;
let mut rows = sqlx::query("SELECT * FROM users WHERE email = ?")
.bind("[email protected]")
.fetch(&mut conn);
while let Some(row) = rows.try_next().await? {
// map the row into a user-defined domain type
let email: &str = row.try_get("email")?;
}To assist with mapping the row into a domain type, one of two idioms may be used:
let mut stream = sqlx::query("SELECT * FROM users")
.map(|row: PgRow| {
// map the row into a user-defined domain type
})
.fetch(&mut conn);#[derive(sqlx::FromRow)]
struct User { name: String, id: i64 }
let mut stream = sqlx::query_as::<_, User>("SELECT * FROM users WHERE email = ? OR name = ?")
.bind("[email protected]")
.bind("example_username")
.fetch(&mut conn);Instead of a stream of results, we can use fetch_one or fetch_optional to request one required or optional result
from the database.
We can use the macro, sqlx::query! to achieve compile-time syntactic and semantic verification of the SQL, with
an output to an anonymous record type where each SQL column is a Rust field (using raw identifiers where needed).
let countries = sqlx::query!(
"
SELECT country, COUNT(*) as count
FROM users
GROUP BY country
WHERE organization = ?
",
organization
)
.fetch_all(&pool) // -> Vec<{ country: String, count: i64 }>
.await?;
// countries[0].country
// countries[0].countDifferences from query():
The input (or bind) parameters must be given all at once (and they are compile-time validated to be the right number and the right type).
The output type is an anonymous record. In the above example the type would be similar to:
{ country: String, count: i64 }The DATABASE_URL environment variable must be set at build time to a database which it can prepare
querie
Postgres: connect over a caller-provided socket, and a wasm-safe `Instant`, for hosts like Cloudflare Workers
Support for specifying database URLs per test via an environment variable option in sqlx::test macro
SQLite: SQLITE_FULL leaves stale transaction depth and breaks subsequent begin_with calls
SQLCipher crashes on a segfault
MySQL: a cancelled prepare leaves its response on the stream
Mysql failure while dropping a future in the middle of reading or writing to the stream.
Mariadb connection from pool fails
sqlx-cli `prepare --check` command requires a database URL in offline mode
PostgreSQL: cancelling Pool::begin_with can return an open transaction to the pool (0.9.0)
Make PostgreSQL advisory-lock string hashing optional