use std::collections::hash_map::RandomState;
use std::collections::HashMap;
use std::fmt::Debug;
use std::hash::Hash;
use anyhow::Result;
use async_trait::async_trait;
use crate::client::ILazyClient;
use crate::errors::DgraphError;
use crate::txn::default::Base;
use crate::txn::{IState, Query, TxnState, TxnType, TxnVariant};
#[cfg(feature = "dgraph-1-0")]
use crate::Assigned;
use crate::IDgraphClient;
#[cfg(any(feature = "dgraph-1-1", feature = "dgraph-21-03"))]
use crate::Response;
use crate::{Mutation, Request};
#[cfg(feature = "dgraph-1-0")]
pub type MutationResponse = Assigned;
#[cfg(any(feature = "dgraph-1-1", feature = "dgraph-21-03"))]
pub type MutationResponse = Response;
#[derive(Clone, Debug)]
pub struct Mutated<C: ILazyClient> {
base: Base<C>,
mutated: bool,
}
#[cfg(any(feature = "dgraph-1-1", feature = "dgraph-21-03"))]
pub struct UpsertMutation {
mu: Vec<Mutation>,
}
#[cfg(any(feature = "dgraph-1-1", feature = "dgraph-21-03"))]
impl From<Vec<Mutation>> for UpsertMutation {
fn from(mu: Vec<Mutation>) -> Self {
Self { mu }
}
}
#[cfg(any(feature = "dgraph-1-1", feature = "dgraph-21-03"))]
impl From<Mutation> for UpsertMutation {
fn from(mu: Mutation) -> Self {
Self { mu: vec![mu] }
}
}
#[async_trait]
impl<C: ILazyClient> IState for Mutated<C> {
fn query_request<S: ILazyClient>(
&self,
state: &TxnState<S>,
query: String,
vars: HashMap<String, String, RandomState>,
) -> Request {
self.base.query_request(state, query, vars)
}
}
pub type TxnMutatedType<C> = TxnVariant<Mutated<C>, C>;
impl<C: ILazyClient> TxnType<C> {
pub fn mutated(self) -> TxnMutatedType<C> {
TxnVariant {
state: self.state,
extra: Mutated {
base: self.extra,
mutated: false,
},
}
}
}
#[async_trait]
pub trait Mutate: Query {
async fn discard(mut self) -> Result<()>;
async fn commit(self) -> Result<()>;
async fn mutate(&mut self, mu: Mutation) -> Result<MutationResponse>;
async fn mutate_and_commit_now(mut self, mu: Mutation) -> Result<MutationResponse>;
#[cfg(any(feature = "dgraph-1-1", feature = "dgraph-21-03"))]
async fn upsert<Q, M>(&mut self, query: Q, mu: M) -> Result<MutationResponse>
where
Q: Into<String> + Send + Sync,
M: Into<UpsertMutation> + Send + Sync;
#[cfg(any(feature = "dgraph-1-1", feature = "dgraph-21-03"))]
async fn upsert_and_commit_now<Q, M>(mut self, query: Q, mu: M) -> Result<MutationResponse>
where
Q: Into<String> + Send + Sync,
M: Into<UpsertMutation> + Send + Sync;
#[cfg(any(feature = "dgraph-1-1", feature = "dgraph-21-03"))]
async fn upsert_with_vars<Q, K, V, M>(
&mut self,
query: Q,
vars: HashMap<K, V>,
mu: M,
) -> Result<MutationResponse>
where
Q: Into<String> + Send + Sync,
K: Into<String> + Send + Sync + Eq + Hash,
V: Into<String> + Send + Sync,
M: Into<UpsertMutation> + Send + Sync;
#[cfg(any(feature = "dgraph-1-1", feature = "dgraph-21-03"))]
async fn upsert_with_vars_and_commit_now<Q, K, V, M>(
mut self,
query: Q,
vars: HashMap<K, V>,
mu: M,
) -> Result<MutationResponse>
where
Q: Into<String> + Send + Sync,
K: Into<String> + Send + Sync + Eq + Hash,
V: Into<String> + Send + Sync,
M: Into<UpsertMutation> + Send + Sync;
}
#[async_trait]
impl<C: ILazyClient> Mutate for TxnMutatedType<C> {
async fn discard(mut self) -> Result<()> {
self.context.aborted = true;
self.commit_or_abort().await
}
async fn commit(self) -> Result<()> {
self.commit_or_abort().await
}
async fn mutate(&mut self, mu: Mutation) -> Result<MutationResponse> {
self.do_mutation("", HashMap::<String, String>::with_capacity(0), mu, false)
.await
}
async fn mutate_and_commit_now(mut self, mu: Mutation) -> Result<MutationResponse> {
self.do_mutation("", HashMap::<String, String>::with_capacity(0), mu, true)
.await
}
#[cfg(any(feature = "dgraph-1-1", feature = "dgraph-21-03"))]
async fn upsert<Q, M>(&mut self, query: Q, mu: M) -> Result<MutationResponse>
where
Q: Into<String> + Send + Sync,
M: Into<UpsertMutation> + Send + Sync,
{
self.do_mutation(
query,
HashMap::<String, String>::with_capacity(0),
mu,
false,
)
.await
}
#[cfg(any(feature = "dgraph-1-1", feature = "dgraph-21-03"))]
async fn upsert_and_commit_now<Q, M>(mut self, query: Q, mu: M) -> Result<MutationResponse>
where
Q: Into<String> + Send + Sync,
M: Into<UpsertMutation> + Send + Sync,
{
self.do_mutation(query, HashMap::<String, String>::with_capacity(0), mu, true)
.await
}
#[cfg(any(feature = "dgraph-1-1", feature = "dgraph-21-03"))]
async fn upsert_with_vars<Q, K, V, M>(
&mut self,
query: Q,
vars: HashMap<K, V>,
mu: M,
) -> Result<MutationResponse>
where
Q: Into<String> + Send + Sync,
K: Into<String> + Send + Sync + Eq + Hash,
V: Into<String> + Send + Sync,
M: Into<UpsertMutation> + Send + Sync,
{
self.do_mutation(query, vars, mu, false).await
}
#[cfg(any(feature = "dgraph-1-1", feature = "dgraph-21-03"))]
async fn upsert_with_vars_and_commit_now<Q, K, V, M>(
mut self,
query: Q,
vars: HashMap<K, V>,
mu: M,
) -> Result<MutationResponse>
where
Q: Into<String> + Send + Sync,
K: Into<String> + Send + Sync + Eq + Hash,
V: Into<String> + Send + Sync,
M: Into<UpsertMutation> + Send + Sync,
{
self.do_mutation(query, vars, mu, true).await
}
}
impl<C: ILazyClient> TxnMutatedType<C> {
#[cfg(feature = "dgraph-1-0")]
async fn do_mutation<Q, K, V>(
&mut self,
_query: Q,
_vars: HashMap<K, V>,
mut mu: Mutation,
commit_now: bool,
) -> Result<MutationResponse>
where
Q: Into<String> + Send + Sync,
K: Into<String> + Send + Sync + Eq + Hash,
V: Into<String> + Send + Sync,
{
self.extra.mutated = true;
mu.commit_now = commit_now;
mu.start_ts = self.context.start_ts;
let assigned = match self.stub.mutate(mu).await {
Ok(assigned) => assigned,
Err(err) => {
anyhow::bail!(DgraphError::GrpcError(err));
}
};
match assigned.context.as_ref() {
Some(src) => self.context.merge_context(src)?,
None => anyhow::bail!(DgraphError::MissingTxnContext),
}
Ok(assigned)
}
#[cfg(any(feature = "dgraph-1-1", feature = "dgraph-21-03"))]
async fn do_mutation<Q, K, V, M>(
&mut self,
query: Q,
vars: HashMap<K, V>,
mu: M,
commit_now: bool,
) -> Result<MutationResponse>
where
Q: Into<String> + Send + Sync,
K: Into<String> + Send + Sync + Eq + Hash,
V: Into<String> + Send + Sync,
M: Into<UpsertMutation>,
{
self.extra.mutated = true;
let vars = vars.into_iter().fold(HashMap::new(), |mut tmp, (k, v)| {
tmp.insert(k.into(), v.into());
tmp
});
let mu: UpsertMutation = mu.into();
let request = Request {
query: query.into(),
vars,
start_ts: self.context.start_ts,
commit_now,
mutations: mu.mu,
..Default::default()
};
let response = match self.stub.do_request(request).await {
Ok(response) => response,
Err(err) => {
anyhow::bail!(DgraphError::GrpcError(err));
}
};
match response.txn.as_ref() {
Some(txn) => self.context.merge_context(txn)?,
None => anyhow::bail!(DgraphError::MissingTxnContext),
}
Ok(response)
}
async fn commit_or_abort(self) -> Result<()> {
let extra = self.extra;
let state = *self.state;
if !extra.mutated {
return Ok(());
};
let mut client = state.stub;
let txn = state.context;
match client.commit_or_abort(txn).await {
Ok(_txn_context) => Ok(()),
Err(err) => anyhow::bail!(DgraphError::GrpcError(err)),
}
}
}