Introduction
SQLx is an async SQL toolkit for Rust that lets you write raw SQL queries and have the compiler verify them against a live or cached database schema. Unlike ORMs, SQLx does not generate SQL for you. You write standard SQL and get compile-time type checking, null safety, and connection pooling out of the box.
What SQLx Does
- Checks SQL queries against your actual database schema at compile time
- Maps query results to Rust structs with automatic type conversion
- Provides async connection pools for PostgreSQL, MySQL, MariaDB, and SQLite
- Runs migrations with a built-in CLI tool (
sqlx migrate) - Caches query metadata for offline compilation without a live database
Architecture Overview
SQLx uses Rust procedural macros (sqlx::query! and sqlx::query_as!) that connect to the database during compilation to validate SQL syntax, column types, and nullability. The results are embedded as type information in the compiled binary. At runtime, SQLx provides async drivers built on Tokio or async-std, with connection pooling, TLS, and prepared statement caching.
Self-Hosting & Configuration
- Add
sqlxto Cargo.toml with the desired runtime and database feature flags - Set
DATABASE_URLin.envfor compile-time query checking - Run
cargo sqlx prepareto generate offline query metadata for CI builds - Use
sqlx migrate addandsqlx migrate runfor schema migrations - Configure pool size, timeouts, and TLS via
PgPoolOptionsor connection strings
Key Features
- Compile-time SQL verification that catches typos and type mismatches before runtime
- Zero-cost mapping from SQL rows to Rust structs without runtime reflection
- Offline mode that caches query metadata so CI builds do not need a live database
- Built-in migration system with reversible up/down scripts
- Pure Rust drivers with no dependency on C libraries like libpq
Comparison with Similar Tools
- Diesel — ORM with a Rust DSL for queries; SQLx uses raw SQL with compile-time checks
- SeaORM — async ORM built on top of SQLx; adds an abstraction layer
- tokio-postgres — lower-level async driver without compile-time checking
- sqlc (Go) — similar compile-time SQL approach but for Go; SQLx serves the Rust ecosystem
- Prisma — TypeScript ORM with code generation; SQLx keeps you in raw SQL
FAQ
Q: Do I need a running database to compile?
A: For development, yes. For CI, run cargo sqlx prepare to save query metadata and compile offline.
Q: Does SQLx support transactions?
A: Yes. Use pool.begin() to start a transaction and .commit() or .rollback() to finalize it.
Q: Can I use SQLx with SQLite?
A: Yes. Enable the sqlite feature flag and point DATABASE_URL to a local file.
Q: How does SQLx handle migrations?
A: The sqlx CLI provides migrate add, migrate run, and migrate revert commands for managing schema changes.