use common::CAPID_GRAPHDB;
use crate::{FromTable};
use wasccgraph_common::{Statistics, ResultSet};
use wasccgraph_common::protocol::*;
use wascc_actor::{prelude::{deserialize, serialize}, untyped::{self, UntypedHostBinding}};
#[doc(hidden)]
pub struct GraphHostBindingBuilder {
binding: String,
}
impl GraphHostBindingBuilder {
pub fn graph(&self, graph: &str) -> GraphHostBinding {
GraphHostBinding {
hostbinding: untyped::host(&self.binding),
graph_name: graph.to_string(),
}
}
}
pub struct GraphHostBinding {
hostbinding: UntypedHostBinding,
graph_name: String,
}
pub fn host(binding: &str) -> GraphHostBindingBuilder {
GraphHostBindingBuilder {
binding: binding.to_string(),
}
}
pub fn default() -> GraphHostBindingBuilder {
GraphHostBindingBuilder {
binding: "default".to_string(),
}
}
impl GraphHostBinding {
pub fn query<T: FromTable>(&self, query: &str) -> std::result::Result<T, Box<dyn std::error::Error>> {
self.query_with_statistics(query).map(|(value, _)| value)
}
pub fn query_with_statistics<T:FromTable>(&self, query: &str) -> std::result::Result<(T, Statistics), Box<dyn std::error::Error>> {
let result_set = self.get_result_set(query).map_err(|e| format!("{}", e))?;
let value = T::from_table(&result_set).map_err(|e| format!("{}", e))?;
Ok((value, result_set.statistics))
}
pub fn mutate(&mut self, query: &str) -> std::result::Result<(), Box<dyn std::error::Error>> {
self.mutate_with_statistics(query).map(|_| ())
}
pub fn mutate_with_statistics(&mut self, query: &str) -> std::result::Result<Statistics, Box<dyn std::error::Error>> {
let result_set = self.get_result_set(query).map_err(|e| format!("{}", e))?;
Ok(result_set.statistics)
}
pub fn delete(self) -> std::result::Result<(), Box<dyn std::error::Error>> {
let delreq = DeleteRequest {
graph_name: self.graph_name.to_string()
};
self.hostbinding.call(CAPID_GRAPHDB, OP_DELETE, serialize(&delreq)?)?;
Ok(())
}
pub fn name(&self) -> &str {
&self.graph_name
}
fn get_result_set(&self, query: &str) -> std::result::Result<ResultSet, Box<dyn std::error::Error>> {
let query = QueryRequest {
graph_name: self.graph_name.to_string(),
query: query.to_string()
};
let res = self.hostbinding.call(CAPID_GRAPHDB, OP_QUERY, serialize(&query)?)?;
Ok(deserialize(&res)?)
}
}