Skip to content

Rust: sqlx

Connects, creates a todo table if it does not exist, inserts a row and counts open rows. The code is the same against the original database and against MachSQL; only the address changes.

DATABASE_URL=postgres://app:${DB_PASSWORD}@old-postgres:5432/app
DATABASE_URL=postgres://app:${DB_PASSWORD}@machsql-host:5432/app

Nothing else changes: not the code, not the driver, not its version, not the SQL.

  • Rust (latest stable, edition 2024)
  • sqlx 0.9.0
  • tokio 1.54.1
Terminal window
export DATABASE_URL=postgres://app:${DB_PASSWORD}@machsql-host:5432/app
cargo run

Expected output: inserted todo <id>, <n> open.

The program as it is kept and tested in the Mach Database for PostgreSQL repository; highlighted lines read the connection setting.

src/main.rs
//! sqlx with a PostgreSQL connection pool.
#[tokio::main]
async fn main() -> Result<(), sqlx::Error> {
let url = std::env::var("DATABASE_URL").expect("set DATABASE_URL");
let pool = sqlx::PgPool::connect(&url).await?;
sqlx::query("CREATE TABLE IF NOT EXISTS todo (id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, title text NOT NULL, done boolean NOT NULL DEFAULT false)")
.execute(&pool)
.await?;
let id: i64 = sqlx::query_scalar("INSERT INTO todo (title) VALUES ($1) RETURNING id")
.bind("write the examples")
.fetch_one(&pool)
.await?;
let open: i64 = sqlx::query_scalar("SELECT count(*) FROM todo WHERE NOT done")
.fetch_one(&pool)
.await?;
println!("inserted todo {id}, {open} open");
Ok(())
}
Cargo.toml
[package]
name = "machsql-example-sqlx"
version = "0.1.0"
edition = "2024"
publish = false
# Not a member of the MachSQL workspace.
[workspace]
[dependencies]
sqlx = { version = "0.9.0", default-features = false, features = ["runtime-tokio", "tls-rustls", "postgres", "macros"] }
tokio = { version = "1.54.1", features = ["macros", "rt-multi-thread"] }