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 / EMBEDDED ENGINE / GETTING STARTED WITH THE EMBEDDED ENGINE

Getting started with the embedded engine

This page takes you from an empty Cargo project to a program with a database inside it. First a minimal program, then a realistic one that creates a table, writes rows and reads them back through rasterizeddb_client.

Requirements

  • Stable Rust. rasterizeddb_client declares Rust 1.88 as its minimum; see Limits for rasterizeddb_embedded 1.1.0 on compilers older than 1.100.
  • Linux, another Unix system, or Windows; x86-64 or ARM64.
  • On x86-64, a CPU with AVX2 (x86-64-v3). The engine refuses to start without it.

Add the dependencies

toml
[dependencies]
rasterizeddb_embedded = "1.1"
rasterizeddb_client = "1.1"
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
CrateWhy
rasterizeddb_embeddedThe engine and the Builder that starts it. It depends on rasterizeddb_core 1.1.0 (the engine) and rasterizeddb_client 1.1.0.
rasterizeddb_clientThe API you use the database through. rasterizeddb_embedded re-exports it as rasterizeddb_embedded::client, but the derive macros (#[derive(Model)], #[derive(FromRow)], #[derive(SqlEnum)]) generate code that names rasterizeddb_client directly, so add it as a dependency of your own. Cargo resolves both to the same copy.
tokioThe client is async. Your program needs a runtime for its own code; the engine brings its own.

rasterizeddb_embedded has no Cargo features of its own. It builds the engine with the engine's default features, and the engine does not build with them off.

The client's optional features go on your rasterizeddb_client line:

FeatureDefaultAdds
deriveyes#[derive(Model)], #[derive(FromRow)], #[derive(SqlEnum)]
shardingyesClient-side sharding; dormant until a router is built. See Client-side sharding
brokeryesThe message broker client. See Message broker client
chrononochrono date and time types as parameters and results
uuidnouuid::Uuid as a parameter and a result
serde_jsonnoserde_json::Value results, #[rdb(json)] model fields, JSON key/value values

For example, rasterizeddb_client = { version = "1.1", features = ["chrono", "uuid"] }.

The first build compiles the whole engine, so expect it to take a while longer than a typical crate.

A minimal program

rust
use rasterizeddb_embedded::Builder;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // A database in ./data, created if it does not exist.
    let db = Builder::open("./data").start().await?;
    let client = db.connect().await?;

    client.execute("CREATE TABLE IF NOT EXISTS notes (id BIGINT, body TEXT)", &[]).await?;
    client.execute("INSERT INTO notes VALUES (1, 'hello')", &[]).await?;
    let rows = client.query("SELECT body FROM notes WHERE id = 1", &[]).await?;
    println!("{}", rows.iter().next().unwrap().get::<String>(0)?);

    drop(client);
    db.shutdown().await?; // drains, writes the index snapshots, checkpoints the log
    Ok(())
}

Use Builder::in_memory() in place of Builder::open(...) for a database that lives only as long as the engine.

On Windows, add a password before start. The embedded endpoint there is a loopback TCP port, and start refuses to serve it without authentication:

rust
let db = Builder::open("./data")
    .password("app", "change-me")
    .start()
    .await?;

Embedded::connect logs in with that password for you. To write one program for every platform:

rust
let mut builder = Builder::open("./data");
if cfg!(not(unix)) {
    builder = builder.password("app", "change-me");
}
let db = builder.start().await?;

A realistic program

A to-do list kept in ./tasks-data. Run it twice and the second run finds the first run's tasks.

rust
use rasterizeddb_client::params;
use rasterizeddb_embedded::Builder;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut builder = Builder::open("./tasks-data");
    if cfg!(not(unix)) {
        builder = builder.password("tasks", "change-me");
    }
    let db = builder.start().await?;
    let client = db.connect().await?;

    client
        .run(
            "CREATE TABLE IF NOT EXISTS tasks (\
                id BIGSERIAL, \
                title TEXT NOT NULL, \
                done BOOLEAN NOT NULL DEFAULT false, \
                PRIMARY KEY (id))",
        )
        .await?;

    // $1, $2 … are filled in from params![…].
    let id: i64 = client
        .fetch_scalar("INSERT INTO tasks (title) VALUES ($1) RETURNING id", params!["write the docs"])
        .await?;
    client
        .exec("INSERT INTO tasks (title) VALUES ($1), ($2)", params!["review", "release"])
        .await?;
    client.exec("UPDATE tasks SET done = true WHERE id = $1", params![id]).await?;

    // Columns are read by position, in the order of the select list.
    let open: Vec<(i64, String)> = client
        .fetch_all("SELECT id, title FROM tasks WHERE done = false ORDER BY id", params![])
        .await?;
    for (id, title) in &open {
        println!("{id}: {title}");
    }

    let total: i64 = client.fetch_scalar("SELECT COUNT(*) FROM tasks", params![]).await?;
    println!("{total} tasks, {} open", open.len());

    drop(client);
    db.shutdown().await?;
    Ok(())
}

The first run prints:

text
2: review
3: release
3 tasks, 2 open

Some things to know about this program:

  • Each statement commits on its own. To commit several together, use a transaction. See Transactions.
  • Parameters are rendered, not bound. The client writes each value into the statement as a safely quoted literal, so a value can never become SQL syntax. One call sends one statement, and text that holds two statements is refused.
  • Stop the engine before the program ends. shutdown drains the statements in flight, writes the index snapshots and checkpoints the log, so the next start has nothing to replay. If you forget, dropping the Embedded (here, at the end of main) does the same work, blocking the thread until it is done.

The Rust client pages cover the query calls, types and errors in full.

Build for full speed

On x86-64, the engine's vector code runs fastest when the compiler may use AVX2 directly, as the server binary is built. Add this to .cargo/config.toml in your project:

toml
[target.x86_64-unknown-linux-gnu]
rustflags = ["-C", "target-cpu=x86-64-v3"]

[target.x86_64-pc-windows-msvc]
rustflags = ["-C", "target-cpu=x86-64-v3"]

Or set it for one build:

sh
RUSTFLAGS="-C target-cpu=x86-64-v3" cargo build --release

A binary built this way does not run on a CPU without AVX2. That costs nothing, because the engine refuses such a CPU anyway. ARM64 needs no flags.

See the engine's log

The engine logs through the log crate. Install any logger in your program to see its messages, such as warnings about a setting it ignored:

toml
[dependencies]
env_logger = "0.11"
rust
env_logger::init(); // first thing in main; then RUST_LOG=warn ./your-program

Next steps

  • The Builder: every setting, its default and when to change it.
  • Using the engine: the ORM, transactions, key/value, several databases, shutdown and sync programs.
  • Testing with the engine: one engine per process, temporary directories, parallel tests.

Limits

  • A program can run one engine at a time. Serve more databases from that engine with CREATE DATABASE.
  • rasterizeddb_embedded 1.1.0 can fail to compile on Rust compilers older than 1.100, with error E0275 while the compiler evaluates the engine's statement futures. 1.1.1 fixes this; use 1.1.1 or later ("1.1" in Cargo.toml picks it up), or a current stable compiler.
✓ page rendered in 413 µs axum + tera + htmx · no other javascript