cql3_parser/
delete.rs

1use crate::begin_batch::BeginBatch;
2use crate::common::{FQName, Identifier, RelationElement};
3use itertools::Itertools;
4use std::fmt::{Display, Formatter};
5
6/// the data for a delete statement.
7#[derive(PartialEq, Debug, Clone)]
8pub struct Delete {
9    /// if set the statement starts with `BEGIN BATCH`
10    pub begin_batch: Option<BeginBatch>,
11    /// an optional list of columns to delete
12    pub columns: Vec<IndexedColumn>,
13    /// the table to delete from
14    pub table_name: FQName,
15    /// an optional timestamp to use for the deletion.
16    pub timestamp: Option<u64>,
17    /// the were clause for the delete.
18    pub where_clause: Vec<RelationElement>,
19    /// if present a list of key,values for the `IF` clause
20    pub if_clause: Vec<RelationElement>,
21    /// if true and if_clause is NONE then `IF EXISTS` is added
22    pub if_exists: bool,
23}
24
25impl Display for Delete {
26    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
27        write!(
28            f,
29            "{}DELETE {}FROM {}{} WHERE {}{}",
30            self.begin_batch
31                .as_ref()
32                .map_or("".to_string(), |x| x.to_string()),
33            {
34                let mut str = "".to_string();
35                if !self.columns.is_empty() {
36                    str = self.columns.iter().join(", ");
37                    str.push(' ');
38                }
39                str
40            },
41            self.table_name,
42            self.timestamp
43                .as_ref()
44                .map_or("".to_string(), |x| format!(" USING TIMESTAMP {}", x)),
45            self.where_clause.iter().join(" AND "),
46            if !self.if_clause.is_empty() {
47                format!(" IF {}", self.if_clause.iter().join(" AND "))
48            } else if self.if_exists {
49                " IF EXISTS".to_string()
50            } else {
51                "".to_string()
52            }
53        )
54    }
55}
56
57/// Defines an indexed column.  Indexed columns comprise a column name and an optional index into
58/// the column.  This is expressed as `column[idx]`
59#[derive(PartialEq, Debug, Clone)]
60pub struct IndexedColumn {
61    /// the column name
62    pub column: Identifier,
63    /// the optional index in to the column
64    pub idx: Option<String>,
65}
66
67impl Display for IndexedColumn {
68    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
69        match &self.idx {
70            Some(x) => write!(f, "{}[{}]", self.column, x),
71            None => write!(f, "{}", self.column),
72        }
73    }
74}