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};
pub struct QueryBuilder<'c> {
pub(crate) request_tx: tokio::sync::mpsc::UnboundedSender<RouterCommand>,
pub(crate) sql: String,
pub(crate) bindings: BTreeMap<String, Value>,
pub(crate) query_timeout: std::time::Duration,
pub(crate) bind_error: Option<SurrealError>,
pub(crate) _phantom: PhantomData<&'c ()>,
}
impl<'c> QueryBuilder<'c> {
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
}
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
}
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)
}
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)
}
pub async fn one<T: DeserializeOwned>(self) -> SurrealResult<Option<T>> {
let items: Vec<T> = self.all().await?;
Ok(items.into_iter().next())
}
pub async fn exec(self) -> SurrealResult<()> {
if let Some(e) = self.bind_error {
return Err(e);
}
self.raw().await?;
Ok(())
}
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),
}
}
pub async fn one_typed<T: DeserializeOwned>(self) -> SurrealResult<Option<T>> {
Ok(self.all_typed::<T>().await?.into_iter().next())
}
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())
}
async fn execute_raw(self) -> SurrealResult<Value> {
let params = self.build_params();
send_command(&self.request_tx, "query", params, self.query_timeout).await
}
}
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)?
}
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(())
}