surmux 0.2.0

极简 SurrealDB WebSocket 客户端 — 单连接 JSON-RPC 多路复用, 极简依赖
Documentation
//! QueryBuilder: 流式构建 SurrealQL 查询.
//!
//! 提供类型安全的参数绑定 + 多种结果提取方式.

use std::collections::BTreeMap;
use std::marker::PhantomData;
use std::time::Duration;

use serde::de::DeserializeOwned;
use serde_json::Value;
use tokio::sync::mpsc::UnboundedSender;
use tokio::sync::oneshot;

use crate::codec;
use crate::config::WireProtocol;
use crate::error::{SurrealError, SurrealResult};
use crate::protocol::SurrealQueryResult;
use crate::router::{RawRpcBytes, RouterCommand};

// ============================================================
// QueryBuilder
// ============================================================

/// 流式构建并执行 SurrealQL 查询.
///
/// # 使用示例
///
/// ```rust,ignore
/// // 单行查询
/// let user: Option<User> = client
///     .query("SELECT * FROM users WHERE email = $email")
///     .bind("email", "test@test.com")
///     .one()
///     .await?;
///
/// // 列表查询
/// let users: Vec<User> = client
///     .query("SELECT * FROM users WHERE status = $status")
///     .bind("status", "active")
///     .all()
///     .await?;
///
/// // 执行 (UPDATE/DELETE/CREATE)
/// client
///     .query("UPDATE users SET status = 'inactive' WHERE id = $id")
///     .bind("id", "user123")
///     .exec()
///     .await?;
/// ```
pub struct QueryBuilder<'c> {
    /// 用于发送 RouterCommand 的通道 (Clone 自 SurrealClient).
    pub(crate) request_tx: tokio::sync::mpsc::UnboundedSender<RouterCommand>,
    /// SurrealQL 语句.
    pub(crate) sql: String,
    /// 绑定的参数 (key → JSON Value).
    pub(crate) bindings: BTreeMap<String, Value>,
    /// 默认查询超时 (来自 SurrealConfig).
    pub(crate) query_timeout: std::time::Duration,
    /// `bind` / `bind_all` 阶段序列化失败的延迟错误 (在执行时检查).
    /// 不在 bind 阶段立刻报错是因为 builder 是同步链, 错误反馈应在 await 边界.
    pub(crate) bind_error: Option<SurrealError>,
    /// 生命周期标记.
    pub(crate) _phantom: PhantomData<&'c ()>,
}

impl<'c> QueryBuilder<'c> {
    /// 绑定单个参数.
    ///
    /// 参数值必须实现 `serde::Serialize`. 若序列化失败, 错误会在执行时
    /// (`.await`) 抛出, 而不是静默丢弃成 `Null`.
    pub fn bind(mut self, key: impl Into<String>, value: impl serde::Serialize) -> Self {
        match serde_json::to_value(&value) {
            Ok(v) => {
                self.bindings.insert(key.into(), v);
            }
            Err(e) if self.bind_error.is_none() => {
                self.bind_error = Some(SurrealError::SerializationFailed(e));
            }
            Err(_) => {} // 保留首个错误
        }
        self
    }

    /// 批量绑定参数 (从 BTreeMap).
    pub fn bind_all(mut self, bindings: impl Into<BTreeMap<String, Value>>) -> Self {
        self.bindings.extend(bindings.into());
        self
    }

    /// 设置查询超时 (覆盖默认值).
    pub fn timeout(mut self, timeout: std::time::Duration) -> Self {
        self.query_timeout = timeout;
        self
    }

    // ============================================================
    // 结果提取方法
    // ============================================================

    /// 执行查询, 返回原始 `Vec<SurrealQueryResult>`.
    ///
    /// 适用于多语句查询 (`SELECT ...; SELECT ...;`).
    pub async fn raw(self) -> SurrealResult<Vec<SurrealQueryResult>> {
        if let Some(e) = self.bind_error {
            return Err(e);
        }
        let raw_value = self.execute_raw().await?;
        serde_json::from_value(raw_value).map_err(SurrealError::SerializationFailed)
    }

    /// 执行查询, 返回第一条语句结果的所有行.
    ///
    /// 适用于 `SELECT * FROM table WHERE ...`.
    pub async fn all<T: DeserializeOwned>(self) -> SurrealResult<Vec<T>> {
        let mut results = self.raw().await?;

        if results.is_empty() {
            return Err(SurrealError::NoResult);
        }

        let first = &mut results[0];

        if !first.is_ok() {
            return Err(SurrealError::QueryFailed {
                code: -1,
                message: format!("查询状态异常: {}", first.status),
            });
        }

        first.take::<T>().map_err(SurrealError::SerializationFailed)
    }

    /// 执行查询, 返回第一条语句结果的第一行.
    ///
    /// 适用于 `SELECT * FROM table WHERE id = $id LIMIT 1`.
    pub async fn one<T: DeserializeOwned>(self) -> SurrealResult<Option<T>> {
        let items: Vec<T> = self.all().await?;
        Ok(items.into_iter().next())
    }

    /// 执行查询 (INSERT/UPDATE/DELETE/CREATE), 忽略结果.
    ///
    /// 仅检查查询是否成功, 不返回数据.
    pub async fn exec(self) -> SurrealResult<()> {
        if let Some(e) = self.bind_error {
            return Err(e);
        }
        self.raw().await?;
        Ok(())
    }

    /// 执行查询, **直接反序列化**到 `Vec<T>`, 跳过 JsonValue 中间树.
    ///
    /// 协议自动适配: 连接是 CBOR 时走 `decode_query_result_typed` (直反序列化),
    /// 是 JSON 时走 `decode_query_result_typed_json`. 两种协议下都跳过
    /// `serde_json::Value` 全树物化, 性能均显著优于 `.all::<T>()`.
    ///
    /// ## CBOR 性能 (推荐)
    /// 对比 `.all::<T>()` decode 阶段提速 50% 以上 (见 `examples/bench_cbor_typed.rs`).
    /// 内存峰值显著降低 (无需构建全量 CborValue → JsonValue 树).
    ///
    /// ## CBOR Tag 兼容性 (仅 CBOR 协议)
    /// SurrealDB CBOR 中 Datetime 用 Tag 12 `[secs, nanos]`, RecordId 用 Tag 8 `[table, key]`,
    /// UUID 用 Tag 37 (16 bytes). 默认 chrono / uuid 类型期望字符串/RFC3339 形式,
    /// 无法直接吃 SurrealDB 的 CBOR Tag (Array/Bytes), 需用 `cbor_datetime` / `cbor_uuid`
    /// wrapper 模块 (见 `serde_compat`).
    pub async fn all_typed<T: DeserializeOwned>(self) -> SurrealResult<Vec<T>> {
        if let Some(e) = self.bind_error {
            return Err(e);
        }
        let params = self.build_params();
        let raw = send_command_raw(&self.request_tx, "query", params, self.query_timeout).await?;
        match raw.protocol {
            WireProtocol::Cbor => codec::decode_query_result_typed::<T>(&raw.bytes),
            WireProtocol::Json => codec::decode_query_result_typed_json::<T>(&raw.bytes),
        }
    }

    /// 单行版本, 与 `.one::<T>()` 对称.
    ///
    /// 协议自适应, 详见 `all_typed`.
    pub async fn one_typed<T: DeserializeOwned>(self) -> SurrealResult<Option<T>> {
        Ok(self.all_typed::<T>().await?.into_iter().next())
    }

    // ============================================================
    // 内部方法
    // ============================================================

    /// 构建 query RPC 的 params (从 self.sql + self.bindings).
    fn build_params(&self) -> Value {
        let bindings_value = if self.bindings.is_empty() {
            None
        } else {
            Some(serde_json::to_value(&self.bindings).unwrap_or(Value::Null))
        };
        crate::protocol::query_params(&self.sql, bindings_value.as_ref())
    }

    /// 发送 query RPC 并返回原始 JSON Value (走通用路径, 经 `serde_json::Value` 中间树).
    async fn execute_raw(self) -> SurrealResult<Value> {
        let params = self.build_params();
        send_command(&self.request_tx, "query", params, self.query_timeout).await
    }
}

// ============================================================
// 辅助: 发送 RouterCommand 并等待响应
// ============================================================

/// 底层: 发送命令到 Router 并等待原始响应字节 (decode 责任下沉).
pub(crate) async fn send_command_raw(
    request_tx: &UnboundedSender<RouterCommand>,
    method: &str,
    params: Value,
    timeout: Duration,
) -> SurrealResult<RawRpcBytes> {
    let (response_tx, response_rx) = oneshot::channel();

    let cmd = RouterCommand {
        method: method.to_string(),
        params,
        response_tx,
    };

    request_tx
        .send(cmd)
        .map_err(|_| SurrealError::ClientClosed)?;

    tokio::time::timeout(timeout, response_rx)
        .await
        .map_err(|_| SurrealError::Timeout("查询超时".into()))?
        .map_err(|_| SurrealError::ConnectionLost)?
}

/// 发送命令到 Router, 解码到 `serde_json::Value` (通用路径).
///
/// 内部: `send_command_raw` → 按 `raw.protocol` 选 CBOR/JSON 解码路径 →
/// 再从 `RpcResponse` 拿 `result` 字段. CBOR 路径走 CborValue → JsonValue 中间树.
pub(crate) async fn send_command(
    request_tx: &UnboundedSender<RouterCommand>,
    method: &str,
    params: Value,
    timeout: Duration,
) -> SurrealResult<Value> {
    let raw = send_command_raw(request_tx, method, params, timeout).await?;
    let resp = match raw.protocol {
        WireProtocol::Cbor => codec::decode_response_cbor(&raw.bytes)?,
        WireProtocol::Json => codec::decode_response_json(&raw.bytes)?,
    };
    resp.into_result()
        .map_err(|(code, message)| SurrealError::QueryFailed { code, message })
}

/// 发送命令并忽略返回值.
pub(crate) async fn send_command_void(
    request_tx: &UnboundedSender<RouterCommand>,
    method: &str,
    params: Value,
    timeout: Duration,
) -> SurrealResult<()> {
    let raw = send_command_raw(request_tx, method, params, timeout).await?;
    let resp = match raw.protocol {
        WireProtocol::Cbor => codec::decode_response_cbor(&raw.bytes)?,
        WireProtocol::Json => codec::decode_response_json(&raw.bytes)?,
    };
    resp.into_result()
        .map_err(|(code, message)| SurrealError::QueryFailed { code, message })?;
    Ok(())
}