Using the embedded engine
Once the engine is running, you use it through rasterizeddb_client, exactly as you would use a server. This page shows the common calls on an embedded engine and covers what is specific to running in-process: client options, several databases, background work, shutdown and drop order, and programs without an async runtime. For the client API in depth, follow the links to the Rust client pages.
The examples assume Linux or another Unix system. On Windows, add .password(user, password) to each Builder before start (see Platforms and CPU).
One client for the whole program
Embedded::connect returns a Client. A Client is Send + Sync, and its connections carry many statements at once, so one client usually serves a whole program. Share it with Arc:
use std::sync::Arc;
use rasterizeddb_client::params;
use rasterizeddb_embedded::Builder;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let db = Builder::in_memory().start().await?;
let client = Arc::new(db.connect().await?);
client.run("CREATE TABLE hits (id BIGINT)").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??;
}
let n: i64 = client.fetch_scalar("SELECT COUNT(*) FROM hits", params![]).await?;
println!("{n} rows");
drop(client);
db.shutdown().await?;
Ok(())
}Statements that different tasks send at the same time run side by side in the engine, so they may take effect in either order. Await one before sending the next when the order matters.
Queries
All the query calls work as documented in Queries: run, query / execute, query_with / exec, and fetch_all, fetch_one, fetch_optional, fetch_scalar for typed rows. Three rules of the native protocol apply here too, because the embedded engine serves only the native protocol:
- One statement per call. Text that holds two statements is refused before it is sent.
- Columns by position. Answers carry no column names. Column
iof a row is itemiof your select list. - Parameters are rendered.
$1…$nbecome safely quoted literals on the client side.
Types lists how Rust and SQL types map, and Errors lists what can go wrong.
Transactions
A statement sent on the client commits on its own. Statements that must commit together run in a transaction, which gets a connection of its own:
use rasterizeddb_client::prelude::*;
use rasterizeddb_embedded::Builder;
#[tokio::main]
async fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
let db = Builder::in_memory().start().await?;
let client = db.connect().await?;
client.run("CREATE TABLE account (id BIGINT PRIMARY KEY, balance BIGINT NOT NULL)").await?;
client.run("INSERT INTO account VALUES (1, 100), (2, 0)").await?;
let tx = client.begin().await?;
tx.exec("UPDATE account SET balance = balance - $1 WHERE id = $2", params![10i64, 1i64]).await?;
tx.exec("UPDATE account SET balance = balance + $1 WHERE id = $2", params![10i64, 2i64]).await?;
tx.commit().await?;
let balances: Vec<(i64, i64)> = client
.fetch_all("SELECT id, balance FROM account ORDER BY id", params![])
.await?;
println!("{balances:?}"); // [(1, 90), (2, 10)]
drop(client);
db.shutdown().await?;
Ok(())
}tx.rollback() undoes it, and dropping tx without committing rolls it back. BEGIN and COMMIT are never written as statements: the client sends them for you. A transaction's statement methods come from the Executor trait, which the prelude brings into scope. The prelude also defines Result with the client's error type, so this main spells out std::result::Result.
Transactions covers isolation levels, read-only transactions, the retrying client.transaction(|tx| …) form and savepoints.
The ORM and migrations
#[derive(Model)] needs rasterizeddb_client as a direct dependency with its default derive feature (see Getting started):
use rasterizeddb_client::prelude::*;
use rasterizeddb_embedded::Builder;
#[derive(Model, Debug)]
struct Note {
#[rdb(primary_key, serial)]
id: i64,
body: String,
pinned: bool,
}
#[tokio::main]
async fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
let db = Builder::open("./notes-data").start().await?;
let client = db.connect().await?;
client.create_table::<Note>().await?; // IF NOT EXISTS: safe on every start
let note = client.insert(&Note { id: 0, body: "hello".into(), pinned: true }).await?;
println!("stored as id {}", note.id);
let pinned = Note::query().filter(Note::pinned.eq(true)).all(&client).await?;
println!("{} pinned", pinned.len());
drop(client);
db.shutdown().await?;
Ok(())
}To run migrations every time the program starts, put a Migrator in Options::migrations and connect with Embedded::connect_with (see Client options). They run before connect_with returns. See The ORM, Relations and Migrations.
Key/value
The engine's key/value store is reached through client.kv(), as on a server. There is no Redis port in embedded mode, so the client is the only way in.
use std::time::Duration;
let kv = client.kv();
kv.set_as("visits", &41i32, None).await?;
let visits: Option<i32> = kv.get_as::<i32>("visits").await?;
kv.set_as("banner", &"Sale!".to_string(), Some(Duration::from_secs(600))).await?;The store is a cache by default and is empty after a restart. To keep it, start with Builder::kv_persist(true) (saved every 300 s and at a clean shutdown; change the interval with kv_save_interval). Cap its memory with kv_max_memory and kv_eviction. See Key/value for typed maps and queries.
Client options
Embedded::options() returns the options connect uses: the client's defaults, the engine's login and, on Windows, trust in the engine's own certificate. Change what you need and pass the result to connect_with. Start from options() rather than Options::default(), so that you keep the login and the certificate pin:
use std::time::Duration;
use rasterizeddb_embedded::{Builder, Options};
let db = Builder::open("./data")
.request_timeout(Duration::from_secs(120)) // statements may run for 2 minutes
.start()
.await?;
let client = db
.connect_with(Options {
connections: 4, // more shared connections
timeout: Some(Duration::from_secs(120)), // wait as long as the engine allows
..db.options()
})
.await?;Keep the two sides in step:
| Engine | Client | Rule |
|---|---|---|
request_timeout (30 s) | timeout (30 s, plus a 2 s grace) | Raise both together, so the client does not give up on a statement the engine is still running. |
request_timeout (30 s), also the idle close | idle_reconnect (20 s) | Keep idle_reconnect below request_timeout, so the client reopens an idle connection before the engine closes it. |
The full list of client options is in Connecting.
Several databases
One engine can hold several databases. The one you get by default is named postgres. Create others with SQL, then connect a client to one with Options::database:
use rasterizeddb_embedded::{Builder, Options};
let db = Builder::open("./data").start().await?;
let admin = db.connect().await?;
admin.run("CREATE DATABASE analytics").await?;
let analytics = db
.connect_with(Options { database: Some("analytics".into()), ..db.options() })
.await?;
analytics.run("CREATE TABLE events (id BIGINT, kind TEXT)").await?;- Every connection a client opens uses its database: the shared ones, reopened ones and each transaction's. A client cannot switch databases later; make one client per database.
- A database that does not exist makes
connect_withfail. It is never quietly replaced by the default database. SHOW DATABASESlists them all.DROP DATABASEdrops one, but not the database the connection itself is using.- With
Builder::password, the login is checked against the roles of the database you name.
This is the way to keep separate data sets in one program, since a process can run only one engine. See Databases for the SQL.
Background work
The engine runs its own maintenance on its own threads, as a server does. The main tasks and their switches:
| Work | Controlled by |
|---|---|
| Returning freed memory to the operating system when idle (glibc only) | Builder::idle_trim |
| Compacting tables whose pointer slots are mostly dead | Builder::auto_compact, auto_compact.* keys |
| Background reclamation of dead rows | vacuum.enabled |
| Writing index snapshots for tables left unwritten for a while | index_snapshot.idle_checkpoint_secs |
| Syncing asynchronous commits | Builder::wal_writer_delay (with synchronous_commit(false)) |
| Saving the key/value store | Builder::kv_persist, kv_save_interval |
The threads are named rasterizeddb-engine (one) and rasterizeddb-worker (the runtime's, worker_threads of them), so you can tell them apart in a profiler or top -H. Each engine thread has a 32 MiB stack.
Signals
Starting an embedded engine turns off the engine's own Ctrl+C and SIGTERM handling for the whole process. That includes a replication listener started later by REPLICATION ENABLE. Your program keeps its signals, and stopping the engine is up to you. For example, with tokio's signal feature:
tokio = { version = "1", features = ["macros", "rt-multi-thread", "signal"] }use rasterizeddb_embedded::Builder;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let db = Builder::open("./data").start().await?;
let client = db.connect().await?;
// … hand `client` to the rest of the program …
tokio::signal::ctrl_c().await?;
drop(client);
db.shutdown().await?;
Ok(())
}Shutdown and drop order
db.shutdown().await stops the engine cleanly: it accepts no new connections, lets statements in flight finish, writes the index snapshots and checkpoints the write-ahead log, so the next start has nothing to replay. Dropping the Embedded does the same, but blocks the dropping thread until it is done. Inside async code, prefer shutdown().await.
Stop things in this order:
- Finish or drop your transactions and clients. A statement sent after the engine has stopped fails with
Error::Transport. - Stop the engine with
shutdown().await,shutdown_blocking(), or by dropping theEmbedded. - Remove anything the database lives in, such as a temporary directory, only after that. In Rust, local variables drop in reverse order of declaration, so declare the directory before the engine.
If the process ends without a shutdown (std::process::exit, a kill, a crash), committed transactions are still in the log. The next start replays it, which takes longer, and the private socket directory under the temporary directory (rdb-embedded-<pid>-<random>) is left behind. The directory lock never outlives the process.
A stopped engine can be started again in the same process, on the same directory or another one.
Programs without an async runtime
The engine runs on its own threads, so a synchronous program can start and stop it with start_blocking and shutdown_blocking. The client is async, so make a small runtime for the statements:
use rasterizeddb_client::params;
use rasterizeddb_embedded::Builder;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let db = Builder::open("./data").start_blocking()?;
let runtime = tokio::runtime::Builder::new_multi_thread()
.worker_threads(1)
.enable_all()
.build()?;
let count = runtime.block_on(async {
let client = db.connect().await?;
client.run("CREATE TABLE IF NOT EXISTS events (id BIGINT, kind TEXT)").await?;
client.exec("INSERT INTO events VALUES ($1, $2)", params![1i64, "boot"]).await?;
client.fetch_scalar::<i64>("SELECT COUNT(*) FROM events", params![]).await
})?;
println!("{count} events");
db.shutdown_blocking()?;
Ok(())
}start_blocking and shutdown_blocking must not be called from inside an async runtime. In async code, use start().await and shutdown().await. start works under any runtime, not only tokio.
Reaching the engine from another process
db.endpoint() returns the address the engine serves, such as unix:/tmp/rdb-embedded-4242-…/native.sock. On Unix, another process running as the same operating-system user can connect to it with rasterizeddb_client, for example a helper tool. The path is new at every start and disappears at shutdown, so pass it to that process each time. For anything long-lived or shared, run the server instead.
Limits
- Only the native protocol is served, so the native protocol's limits apply. See the Rust client.
- One engine per process. Use several databases in it instead of several engines.
Embedded::catalog()and the hiddenrasterizeddb_embedded::enginemodule expose the engine's internals. They are outside the crate's semver promise and can change in any release, so code that uses them may need changes on every upgrade.