Rust SDK & ORM
spyd-rust-driver sync Client/Pool, Tokio async client, spyd_model! macro ORM, and migrations.
The official Rust driver provides both zero-runtime synchronous I/O and opt-in Tokio asynchronous I/O (features = ["async"]) over SpydWire v2 (SPD2) binary TLS framing, alongside a compile-time macro ORM (spyd_model!), type-checked query builder, RAII transactions, connection pools, and SHA-256 migrations.
1. Installation (Cargo.toml)#
# Synchronous (zero async runtime dependencies)
[dependencies]
spyd-rust-driver = "1.0.0"
# Async with Tokio + tokio-rustls
[dependencies]
spyd-rust-driver = { version = "1.0.0", features = ["async"] }
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }2. Raw Synchronous Driver (Client & Pool)#
use spyd_rust_driver::orm::Value;
use spyd_rust_driver::{Client, Pool};
fn main() -> Result<(), spyd_rust_driver::Error> {
let mut client = Client::connect(
"spydwire://app:YOUR_TOKEN@127.0.0.1:5433/default?tls=1&ca=docker/tls/ca.crt&server_name=localhost",
)?;
client.ping()?;
client.use_database("default")?;
// Parameterized insert & returning
client.execute(
"users | insert [{ email: $1, name: $2, active: $3 }]",
&[Value::from("ada@example.test"), Value::from("Ada"), Value::Bool(true)],
)?;
// Prepared statements (server-cached plan + automatic reprepare)
let stmt = client.prepare("users | where active == $1 | pick id, email | sort id")?;
let rows = client.query_prepared(stmt.id, &[Value::Bool(true)])?;
for row in &rows {
println!("{:?} -> {:?}", row[0], row[1]);
}
client.close_prepared(stmt.id)?;
// Interactive transaction
client.begin()?;
client.execute("accounts | where id == $1 | set { balance: balance_delta(balance, 0, 100000, -50) }", &[Value::U64(1)])?;
client.commit()?;
// Thread-safe connection pool
let pool = Pool::new("spydwire://app:YOUR_TOKEN@127.0.0.1:5433?tls=1&ca=docker/tls/ca.crt", 16, 4)?;
let count_rows = pool.query("users | agg count() as n", &[])?;
println!("User count: {:?}", count_rows);
Ok(())
}3. Declarative Sync ORM (spyd_model! & Database)#
Define strongly typed collections with compile-time field accessors, indexes, decimal precision, and schema evolution:
use spyd_rust_driver::orm::{Database, Decimal, Migration, Model, SyncOptions};
use spyd_rust_driver::spyd_model;
spyd_model! {
#[collection = "users"]
pub struct User {
#[primary]
#[auto_increment]
pub id: Option<u64>,
#[not_null]
#[unique]
#[spyd_type = String(160)]
pub email: String,
#[not_null]
#[spyd_type = String(80)]
pub name: String,
#[spyd_type = Decimal(12, 2)]
pub balance: Decimal,
#[not_null]
#[default = Bool(true)]
pub active: bool,
}
}
fn main() -> Result<(), spyd_rust_driver::Error> {
let mut db = Database::connect(
"spydwire://app:YOUR_TOKEN@127.0.0.1:5433?tls=1&ca=docker/tls/ca.crt&server_name=localhost",
)?;
// Idempotent schema provisioning & additive drift sync
db.create_all(&[User::schema()])?;
db.sync(&[User::schema()], SyncOptions::default())?;
let created = db.create(&User {
id: None,
email: "grace@example.test".to_owned(),
name: "Grace Hopper".to_owned(),
balance: "250.00".parse().expect("decimal"),
active: true,
})?;
// Type-safe query builder
let active_users = db
.query::<User>()
.filter(User::active().eq(true)?)
.order_by(User::id().asc()?)
.limit(20)
.all()?;
// RAII transaction: auto-rolls back if closure returns Err or panics
db.transaction(|tx| {
let mut updated = created.clone();
updated.balance = "300.00".parse().expect("decimal");
tx.save(&updated)
})?;
// Checksummed migrations
db.migrate(&[
Migration::new(
"0001_user_region",
["alter collection users add field region string(32)"],
["alter collection users drop field region"],
),
])?;
println!("Active count: {}", active_users.len());
Ok(())
}4. Non-Blocking Async Driver & ORM (features = ["async"])#
use spyd_rust_driver::AsyncPool;
use spyd_rust_driver::orm::{AsyncDatabase, Decimal, Model, Value};
#[tokio::main]
async fn main() -> Result<(), spyd_rust_driver::Error> {
let dsn = "spydwire://app:YOUR_TOKEN@127.0.0.1:5433?tls=1&ca=docker/tls/ca.crt&server_name=localhost";
// Async ORM backed by tokio + tokio-rustls
let db = AsyncDatabase::connect(dsn).await?;
db.create_all(&[User::schema()]).await?;
let user = db.create(&User {
id: None,
email: "alan@example.test".to_owned(),
name: "Alan Turing".to_owned(),
balance: "100.00".parse().expect("decimal"),
active: true,
}).await?;
let found = db
.query::<User>()
.filter(User::active().eq(true)?)
.order_by(User::id().desc()?)
.limit(10)
.all()
.await?;
db.transaction(|tx| Box::pin(async move {
let mut u = user.clone();
u.balance = "150.00".parse().expect("decimal");
tx.save(&u).await
})).await?;
// Raw async pool with semaphore-bounded concurrency
let pool = AsyncPool::new(dsn, 16, 8)?;
let rows = pool.query("users | where active == $1 | take 5", &[Value::Bool(true)]).await?;
println!("ORM: {}, raw: {}", found.len(), rows.len());
Ok(())
}5. Multi-Model Values (Vector, GeoPoint, Json, Bytes)#
Use spyd_rust_driver::orm::{GeoPoint, Vector, Date, Timestamp, UuidBytes} or raw Value variants directly:
use spyd_rust_driver::orm::{GeoPoint, Value, Vector};
let vec_param = Value::Vector(vec![0.12_f32, -0.44, 0.89].into());
let nearby = client.query(
"catalog_items | where nearest(embedding, $1, 10) and geo_within(coords, 37.7, -122.5, 37.8, -122.3) | pick id, title",
&[vec_param],
)?;6. Query Cancellation & Error Matching#
// Send cancel(id) from another connection sharing user + tenant
let query_id = client.next_id();
cancel_client.cancel(query_id)?;Pattern-match spyd_rust_driver::Error: Error::Connect, Error::Io, Error::Authentication, Error::Query, Error::Protocol, Error::Value, Error::Schema, Error::NoResult, Error::MultipleResults.