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_clientdeclares Rust 1.88 as its minimum; see Limits forrasterizeddb_embedded1.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
[dependencies]
rasterizeddb_embedded = "1.1"
rasterizeddb_client = "1.1"
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }| Crate | Why |
|---|---|
rasterizeddb_embedded | The engine and the Builder that starts it. It depends on rasterizeddb_core 1.1.0 (the engine) and rasterizeddb_client 1.1.0. |
rasterizeddb_client | The 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. |
tokio | The 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:
| Feature | Default | Adds |
|---|---|---|
derive | yes | #[derive(Model)], #[derive(FromRow)], #[derive(SqlEnum)] |
sharding | yes | Client-side sharding; dormant until a router is built. See Client-side sharding |
broker | yes | The message broker client. See Message broker client |
chrono | no | chrono date and time types as parameters and results |
uuid | no | uuid::Uuid as a parameter and a result |
serde_json | no | serde_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
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:
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:
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.
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:
2: review
3: release
3 tasks, 2 openSome 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.
shutdowndrains the statements in flight, writes the index snapshots and checkpoints the log, so the next start has nothing to replay. If you forget, dropping theEmbedded(here, at the end ofmain) 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:
[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:
RUSTFLAGS="-C target-cpu=x86-64-v3" cargo build --releaseA 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:
[dependencies]
env_logger = "0.11"env_logger::init(); // first thing in main; then RUST_LOG=warn ./your-programNext 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_embedded1.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"inCargo.tomlpicks it up), or a current stable compiler.