How to Write Compile-Time Checked Queries with sqlx

Use sqlx macros like query! to validate SQL syntax and types at compile time, preventing runtime database errors.

Use the query! or query_as! macros to write SQL queries that are checked at compile time against your database schema. These macros require the sqlx crate with the runtime and macros features enabled, and they validate your SQL syntax and column types before the code compiles.

use sqlx::SqlitePool;

#[sqlx::main]
async fn main() -> Result<(), sqlx::Error> {
    let pool = SqlitePool::connect("sqlite::memory:").await?;

    sqlx::query!("SELECT 1 + 1 as result")
        .fetch_one(&pool)
        .await?;

    Ok(())
}

Add sqlx = { version = "0.8", features = ["runtime-tokio", "sqlite", "macros"] } to your Cargo.toml.