surrealdb_core/sql/statements/
delete.rs1use crate::ctx::Context;
2use crate::dbs::{Iterator, Options, Statement};
3use crate::doc::CursorDoc;
4use crate::err::Error;
5use crate::idx::planner::{QueryPlanner, RecordStrategy, StatementContext};
6use crate::sql::{Cond, Explain, Output, Timeout, Value, Values, With};
7
8use reblessive::tree::Stk;
9use revision::revisioned;
10use serde::{Deserialize, Serialize};
11use std::fmt;
12
13#[revisioned(revision = 3)]
14#[derive(Clone, Debug, Default, Eq, PartialEq, PartialOrd, Serialize, Deserialize, Hash)]
15#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
16#[non_exhaustive]
17pub struct DeleteStatement {
18 #[revision(start = 2)]
19 pub only: bool,
20 pub what: Values,
21 #[revision(start = 3)]
22 pub with: Option<With>,
23 pub cond: Option<Cond>,
24 pub output: Option<Output>,
25 pub timeout: Option<Timeout>,
26 pub parallel: bool,
27 #[revision(start = 3)]
28 pub explain: Option<Explain>,
29}
30
31impl DeleteStatement {
32 pub(crate) fn writeable(&self) -> bool {
34 true
35 }
36 pub(crate) async fn compute(
38 &self,
39 stk: &mut Stk,
40 ctx: &Context,
41 opt: &Options,
42 doc: Option<&CursorDoc>,
43 ) -> Result<Value, Error> {
44 opt.valid_for_db()?;
46 let mut i = Iterator::new();
48 let stm = Statement::from(self);
50 let opt = &opt.new_with_futures(false);
52 let ctx = stm.setup_timeout(ctx)?;
54 let mut planner = QueryPlanner::new();
56 let stm_ctx = StatementContext::new(&ctx, opt, &stm)?;
57 for w in self.what.0.iter() {
59 let v = w.compute(stk, &ctx, opt, doc).await?;
60 i.prepare(stk, &mut planner, &stm_ctx, v).await.map_err(|e| match e {
61 Error::InvalidStatementTarget {
62 value: v,
63 } => Error::DeleteStatement {
64 value: v,
65 },
66 e => e,
67 })?;
68 }
69 let ctx = stm.setup_query_planner(planner, ctx);
71 let res = i.output(stk, &ctx, opt, &stm, RecordStrategy::KeysAndValues).await?;
73 if ctx.is_timedout() {
75 return Err(Error::QueryTimedout);
76 }
77 match res {
79 Value::Array(mut a) if self.only => match a.len() {
81 1 => Ok(a.remove(0)),
83 _ => Err(Error::SingleOnlyOutput),
85 },
86 v => Ok(v),
88 }
89 }
90}
91
92impl fmt::Display for DeleteStatement {
93 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
94 write!(f, "DELETE")?;
95 if self.only {
96 f.write_str(" ONLY")?
97 }
98 write!(f, " {}", self.what)?;
99 if let Some(ref v) = self.with {
100 write!(f, " {v}")?
101 }
102 if let Some(ref v) = self.cond {
103 write!(f, " {v}")?
104 }
105 if let Some(ref v) = self.output {
106 write!(f, " {v}")?
107 }
108 if let Some(ref v) = self.timeout {
109 write!(f, " {v}")?
110 }
111 if self.parallel {
112 f.write_str(" PARALLEL")?
113 }
114 if let Some(ref v) = self.explain {
115 write!(f, " {v}")?
116 }
117 Ok(())
118 }
119}