surmux 0.2.0

极简 SurrealDB WebSocket 客户端 — 单连接 JSON-RPC 多路复用, 极简依赖
Documentation
//! `surmux` 基础示例 — 覆盖主要客户端 API.
//!
//! 运行前提: 本地启动 SurrealDB 实例 (示例默认账户 `qianxun_admin`).
//!
//! 必需环境变量:
//! - `SURMUX_PASS` — 认证密码
//!
//! 可选环境变量 (有默认值):
//! - `SURMUX_URL` (默认 `127.0.0.1:8124`)
//! - `SURMUX_USER` (默认 `qianxun_admin`)
//!
//! 运行:
//! ```bash
//! SURMUX_PASS='your_password' cargo run --example basic
//! ```

use serde::{Deserialize, Serialize};
use surmux::{SurrealClient, SurrealConfig};

/// 构建连接配置. `SURMUX_PASS` 必填, 因为默认账户密码包含特殊字符不可外泄.
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 {
    /// SurrealDB 返回的 record id 是 `["table","key"]` 数组, 用 Value 兼容.
    id: serde_json::Value,
    name: String,
    email: String,
    status: String,
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // ============================================================
    // 1. 连接 + 配置
    // ============================================================
    let config = build_config("basic");

    println!("ws_url = {}", config.ws_url()?);

    let client = SurrealClient::connect(config).await?;

    // ============================================================
    // 2. 健康检查 + 版本
    // ============================================================
    client.health().await?;
    println!("SurrealDB version: {}", client.version().await?);

    // 准备 schema
    client.query("REMOVE TABLE IF EXISTS users").exec().await?;

    // ============================================================
    // 3. CRUD 便捷方法
    // ============================================================
    let u = User {
        id: serde_json::json!("u1"),
        name: "Alice".into(),
        email: "alice@example.com".into(),
        status: "active".into(),
    };

    // create
    let created = client.create("users", &u).await?;
    println!("created: {created}");

    // select
    let alice: Option<User> = client.select("users", "u1").await?;
    println!("selected: {alice:#?}");

    // update
    let updated = client
        .update("users", "u1", &serde_json::json!({"status": "inactive"}))
        .await?;
    println!("updated: {updated:#?}");

    // upsert
    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}");

    // delete
    let _deleted = client.delete("users", "u1").await?;
    println!("deleted u1");

    // ============================================================
    // 4. QueryBuilder — 流式查询
    // ============================================================
    // 4a. .all() → Vec<T>
    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);
    }

    // 4b. .one() → Option<T>
    let bob: Option<User> = client
        .query("SELECT * FROM users WHERE id = $id LIMIT 1")
        .bind("id", "u2")
        .one()
        .await?;
    println!("bob: {bob:#?}");

    // 4c. .bind_all() — 批量绑定
    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:#?}");

    // 4d. .timeout() — 覆盖默认超时
    let _: Option<User> = client
        .query("SELECT * FROM users WHERE id = $id")
        .bind("id", "u2")
        .timeout(std::time::Duration::from_secs(5))
        .one()
        .await?;

    // 4e. .raw() — 取原始多语句结果
    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());

    // ============================================================
    // 5. Transaction — 多语句原子事务
    // ============================================================
    // 示例: 原子分配一个 product_alloc token
    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") // 占位绑定, 演示 API (非必需)
        .raw()
        .await?;
    println!("transaction allocated: {allocated:#?}");

    // ============================================================
    // 6. set / unset (key-value)
    // ============================================================
    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(())
}