NEW RasterizedDB 1.1.0 is out: sharding and the gateway, the message broker, roles and row-level security, compression, .NET on NuGet, and the enterprise edition. What's new ›
DOCS / RUST CLIENT / GETTING STARTED WITH THE RUST CLIENT

Getting started with the Rust client

rasterizeddb_client is the Rust SDK and ORM for RasterizedDB. It talks to the server's native protocol over a unix socket or TCP, and does not compile the database engine into your program. This page takes you from an empty project to a first query and a first model.

What you need

  • A running RasterizedDB server. See Install and Running the server.
  • Rust 1.88 or newer (the crate uses the 2024 edition).
  • The Tokio runtime. Every call is async.

Add the crate

toml
[dependencies]
rasterizeddb_client = "1.1"
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }

The crate's Cargo features:

featuredefaultadds
deriveon#[derive(Model)], #[derive(FromRow)] and #[derive(SqlEnum)]
shardingonClient-side sharding and the rdb-shard tool; dormant until you build a router. See Client-side sharding
brokeronThe message broker client. See Message broker client
chronooffchrono::DateTime<Utc>, NaiveDateTime, NaiveDate and NaiveTime as parameters and results
uuidoffuuid::Uuid as a parameter and a result
serde_jsonoffserde_json::Value as a result, Json::from_value and Json::parse, #[rdb(json)] model fields, and JSON values in the key/value cache

To turn the optional ones on:

toml
[dependencies]
rasterizeddb_client = { version = "1.1", features = ["chrono", "uuid", "serde_json"] }

To leave out sharding and the broker client, turn the defaults off and keep derive: rasterizeddb_client = { version = "1.1", default-features = false, features = ["derive"] }.

Make the server reachable

The client reaches the server's native listener in one of two ways:

addresswhat it reachesserver side
unix:/run/rdb/rdb.socka unix socket on the same machinestarted with --rdb-socket /run/rdb/rdb.sock
127.0.0.1:61170the native TCP listener, always over TLSon by default, port --rdb-port (61170), address --rdb-addr (127.0.0.1)

A unix socket is the quickest way to start. A server started like this lets a process running as the same operating-system user connect with no password:

sh
rasterizeddb --rdb-socket /run/rdb/rdb.sock --rdb-socket-auth trust

Connecting covers passwords, peer logins, TLS certificates and database selection.

Connect and run a first query

rust
use rasterizeddb_client::prelude::*;

#[tokio::main]
async fn main() -> Result<()> {
    let client = Client::connect("unix:/run/rdb/rdb.sock", Options::default()).await?;

    client
        .run("CREATE TABLE IF NOT EXISTS notes (id BIGSERIAL, body TEXT NOT NULL, PRIMARY KEY (id))")
        .await?;

    let id: i64 = client
        .fetch_scalar("INSERT INTO notes (body) VALUES ($1) RETURNING id", params!["hello"])
        .await?;

    let notes: Vec<(i64, String)> = client
        .fetch_all("SELECT id, body FROM notes WHERE id >= $1 ORDER BY id", params![id])
        .await?;
    for (id, body) in notes {
        println!("{id}: {body}");
    }
    Ok(())
}
text
1: hello

Result is the crate's Result<T, rasterizeddb_client::Error>, which the prelude brings into scope. Three things to know from the start:

  • $1, $2… are filled in by the client. Values are written into the statement as safe literals; a value can never become SQL. See Queries.
  • Columns are read by position. The native protocol sends no column names: column 0 of a row is the first item of your SELECT list. See Reading rows.
  • One statement per call, and each commits on its own. Statements that must commit together go in a transaction.

Client::connect opens and logs in every connection before it returns, so a wrong path or a refused login is an error from connect itself.

A first model

With the default derive feature, a struct can stand for a table:

rust
use rasterizeddb_client::prelude::*;

#[derive(Model, Debug, Clone)]
#[rdb(table = "notes")]
struct Note {
    #[rdb(primary_key, serial)]
    id: i64,
    body: String,
    pinned: bool,
}

#[tokio::main]
async fn main() -> Result<()> {
    let client = Client::connect("unix:/run/rdb/rdb.sock", Options::default()).await?;

    // CREATE TABLE IF NOT EXISTS notes (…), with its keys and indexes.
    client.create_table::<Note>().await?;

    // The row comes back as stored, with the id the server assigned.
    let note = client
        .insert(&Note { id: 0, body: "hello".into(), pinned: true })
        .await?;
    println!("stored as {}", note.id);

    let pinned: Vec<Note> = Note::query()
        .filter(Note::pinned.eq(true))
        .order_by(Note::id.desc())
        .limit(10)
        .all(&client)
        .await?;
    println!("{pinned:?}");
    Ok(())
}

notes already exists from the first example without a pinned column. Either drop it first or use another table name. Migrations shows how to keep a table matching its struct, adding columns as the struct grows.

Share one client

A Client is Send + Sync, and its connections carry many statements at once. Create one at start-up, put it in an Arc, and use it from every task:

rust
use rasterizeddb_client::prelude::*;
use std::sync::Arc;

#[tokio::main]
async fn main() -> Result<()> {
    let client = Arc::new(Client::connect("unix:/run/rdb/rdb.sock", Options::default()).await?);
    client
        .run("CREATE TABLE IF NOT EXISTS hits (id BIGINT NOT NULL, PRIMARY KEY (id))")
        .await?;

    let mut tasks = Vec::new();
    for id in 0..100i64 {
        let client = client.clone();
        tasks.push(tokio::spawn(async move {
            client.exec("INSERT INTO hits (id) VALUES ($1)", params![id]).await
        }));
    }
    for task in tasks {
        task.await.expect("the task panicked")?;
    }
    Ok(())
}

Statements sent at the same time from different tasks run side by side on the server. When their order matters, await one before sending the next.

Where to go next

pagefor
Connectingevery connection setting: logins, TLS, databases, timeouts, reconnects
Queriesthe query calls, parameters, rows, notices, the simple-query form
Typeswhich Rust type goes with which SQL type
Transactionsbegin/commit, the retrying closure, savepoints
The ORM#[derive(Model)], every attribute, the query builder
Relationshas-many, belongs-to, many-to-many, eager loading
Migrationsversioned steps, model sync, migrating on connect
Key/value cachethe server's Redis-compatible cache from Rust
Administrationtyped calls for stores, indexes, roles, backups
Errorsthe error type, SQLSTATEs, what to retry

The crate also ships runnable examples. In a checkout of the repository: RDB_ADDR=unix:/run/rdb/rdb.sock cargo run -p rasterizeddb_client --example quickstart (also orm, migrations and kv).

Limits

  • The client speaks the native protocol only. Tools that need the PostgreSQL protocol (psql, sqlx, tokio-postgres) connect to the server's PostgreSQL listener instead; see Connecting to the server.
  • There are no bound parameters on the wire: $n values are rendered into the statement text by the client (safely). A statement's text is therefore as long as its values.
  • Answers carry no column names. Read rows by position, or use simple_query when you need names (see Queries).
  • A whole answer is held in memory, up to 8 MiB by default (Options::max_message_size). Page large reads with LIMIT, keyset pages or a row stream (see The ORM).
✓ page rendered in 160 µs axum + tera + htmx · no other javascript