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
[dependencies]
rasterizeddb_client = "1.1"
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }The crate's Cargo features:
| feature | default | adds |
|---|---|---|
derive | on | #[derive(Model)], #[derive(FromRow)] and #[derive(SqlEnum)] |
sharding | on | Client-side sharding and the rdb-shard tool; dormant until you build a router. See Client-side sharding |
broker | on | The message broker client. See Message broker client |
chrono | off | chrono::DateTime<Utc>, NaiveDateTime, NaiveDate and NaiveTime as parameters and results |
uuid | off | uuid::Uuid as a parameter and a result |
serde_json | off | serde_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:
[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:
| address | what it reaches | server side |
|---|---|---|
unix:/run/rdb/rdb.sock | a unix socket on the same machine | started with --rdb-socket /run/rdb/rdb.sock |
127.0.0.1:61170 | the native TCP listener, always over TLS | on 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:
rasterizeddb --rdb-socket /run/rdb/rdb.sock --rdb-socket-auth trustConnecting covers passwords, peer logins, TLS certificates and database selection.
Connect and run a first query
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(())
}1: helloResult 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
SELECTlist. 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:
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:
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
| page | for |
|---|---|
| Connecting | every connection setting: logins, TLS, databases, timeouts, reconnects |
| Queries | the query calls, parameters, rows, notices, the simple-query form |
| Types | which Rust type goes with which SQL type |
| Transactions | begin/commit, the retrying closure, savepoints |
| The ORM | #[derive(Model)], every attribute, the query builder |
| Relations | has-many, belongs-to, many-to-many, eager loading |
| Migrations | versioned steps, model sync, migrating on connect |
| Key/value cache | the server's Redis-compatible cache from Rust |
| Administration | typed calls for stores, indexes, roles, backups |
| Errors | the 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:
$nvalues 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_querywhen 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 withLIMIT, keyset pages or a row stream (see The ORM).