Rust: tokio-postgres
Connects without TLS for brevity (add postgres-native-tls or tokio-postgres-rustls for TLS, as with PostgreSQL); creates the table, inserts and counts. The code is the same against the original database and against MachSQL; only the address changes.
The only change
Section titled “The only change”DATABASE_URL=postgres://app:${DB_PASSWORD}@old-postgres:5432/appDATABASE_URL=postgres://app:${DB_PASSWORD}@machsql-host:5432/appNothing else changes: not the code, not the driver, not its version, not the SQL.
Versions
Section titled “Versions”- Rust (latest stable, edition 2024)
- tokio-postgres 0.7.18
- tokio 1.54.1
export DATABASE_URL=postgres://app:${DB_PASSWORD}@machsql-host:5432/appcargo runExpected output: inserted todo <id>, <n> open.
Source
Section titled “Source”The program as it is kept and tested in the Mach Database for PostgreSQL repository; highlighted lines read the connection setting.
//! tokio-postgres: the asynchronous PostgreSQL client.
use tokio_postgres::NoTls;
#[tokio::main]async fn main() -> Result<(), tokio_postgres::Error> { let url = std::env::var("DATABASE_URL").expect("set DATABASE_URL"); let (client, connection) = tokio_postgres::connect(&url, NoTls).await?; tokio::spawn(async move { if let Err(e) = connection.await { eprintln!("connection error: {e}"); } }); client .batch_execute("CREATE TABLE IF NOT EXISTS todo (id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, title text NOT NULL, done boolean NOT NULL DEFAULT false)") .await?; let id: i64 = client .query_one("INSERT INTO todo (title) VALUES ($1) RETURNING id", &[&"write the examples"]) .await? .get(0); let open: i64 = client .query_one("SELECT count(*) FROM todo WHERE NOT done", &[]) .await? .get(0); println!("inserted todo {id}, {open} open"); Ok(())}[package]name = "machsql-example-tokio-postgres"version = "0.1.0"edition = "2024"publish = false
# Not a member of the MachSQL workspace.[workspace]
[dependencies]tokio = { version = "1.54.1", features = ["macros", "rt-multi-thread"] }tokio-postgres = "0.7.18"