Skip to content

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.

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)
  • tokio-postgres 0.7.18
  • 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
//! 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(())
}
Cargo.toml
[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"