use serde::{Deserialize, Serialize};
use surmux::{SurrealClient, SurrealConfig};
fn build_config(database: &str) -> SurrealConfig {
let url = std::env::var("SURMUX_URL").unwrap_or_else(|_| "127.0.0.1:8124".into());
let user = std::env::var("SURMUX_USER").unwrap_or_else(|_| "qianxun_admin".into());
let pass = match std::env::var("SURMUX_PASS") {
Ok(v) => v,
Err(_) => {
eprintln!("错误: 环境变量 SURMUX_PASS 未设置 (密码必填, 因为默认值不可外泄)");
eprintln!("用法: SURMUX_PASS='your_password' cargo run --example basic");
std::process::exit(2);
}
};
SurrealConfig::new(url)
.user(user)
.password(pass)
.namespace("surmux_test")
.database(database)
}
#[derive(Debug, Serialize, Deserialize)]
struct User {
id: serde_json::Value,
name: String,
email: String,
status: String,
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let config = build_config("basic");
println!("ws_url = {}", config.ws_url()?);
let client = SurrealClient::connect(config).await?;
client.health().await?;
println!("SurrealDB version: {}", client.version().await?);
client.query("REMOVE TABLE IF EXISTS users").exec().await?;
let u = User {
id: serde_json::json!("u1"),
name: "Alice".into(),
email: "alice@example.com".into(),
status: "active".into(),
};
let created = client.create("users", &u).await?;
println!("created: {created}");
let alice: Option<User> = client.select("users", "u1").await?;
println!("selected: {alice:#?}");
let updated = client
.update("users", "u1", &serde_json::json!({"status": "inactive"}))
.await?;
println!("updated: {updated:#?}");
let upserted = client
.upsert(
"users",
"u2",
&User {
id: serde_json::json!("u2"),
name: "Bob".into(),
email: "bob@example.com".into(),
status: "active".into(),
},
)
.await?;
println!("upserted: {upserted}");
let _deleted = client.delete("users", "u1").await?;
println!("deleted u1");
let active: Vec<User> = client
.query("SELECT * FROM users WHERE status = $status")
.bind("status", "active")
.all()
.await?;
println!("active users ({}):", active.len());
for u in &active {
println!(" - {} <{}>", u.name, u.email);
}
let bob: Option<User> = client
.query("SELECT * FROM users WHERE id = $id LIMIT 1")
.bind("id", "u2")
.one()
.await?;
println!("bob: {bob:#?}");
let bindings = std::collections::BTreeMap::from([
("a".to_string(), serde_json::json!("u1")),
("b".to_string(), serde_json::json!("u2")),
]);
let pairs: Vec<User> = client
.query("SELECT * FROM users WHERE id IN [$a, $b] ORDER BY id")
.bind_all(bindings)
.all()
.await?;
println!("pairs: {pairs:#?}");
let _: Option<User> = client
.query("SELECT * FROM users WHERE id = $id")
.bind("id", "u2")
.timeout(std::time::Duration::from_secs(5))
.one()
.await?;
let raw: Vec<surmux::SurrealQueryResult> = client
.query("SELECT count() FROM users GROUP ALL; SELECT count() FROM users WHERE status = 'active' GROUP ALL")
.raw()
.await?;
println!("raw query results: {}", raw.len());
client
.transaction(&[
"DEFINE TABLE IF NOT EXISTS product_alloc SCHEMALESS",
"DEFINE TABLE IF NOT EXISTS product_alloc_log SCHEMALESS",
])
.exec()
.await?;
client
.transaction(&[
"DELETE product_alloc",
"CREATE product_alloc:[1, 2, 3] SET status = 'free'",
])
.exec()
.await?;
let allocated = client
.transaction(&[
"LET $t = (SELECT id FROM product_alloc WHERE status = 'free' LIMIT 1)",
"UPDATE $t.id SET status = 'allocated', allocated_at = time::now() RETURN AFTER",
"CREATE product_alloc_log SET token_id = $t.id, at = time::now()",
])
.bind("dummy", "marker") .raw()
.await?;
println!("transaction allocated: {allocated:#?}");
client.set("api_key", &"sk-demo-12345").await?;
let value: Option<String> = client
.query("SELECT $value FROM $value LIMIT 1")
.bind("value", "通过 RETURN 验证 set() — 此处仅演示 unset")
.one()
.await
.ok()
.flatten();
println!("set ok; presence check skipped: {value:?}");
client.unset("api_key").await?;
println!("完成 — 所有主接口均已演示");
Ok(())
}