1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use alloc::vec;
use alloc::vec::Vec;

use crate::{
    expression::{parse_expression, Expression},
    keywords::Keyword,
    lexer::Token,
    parser::{ParseError, Parser},
    Identifier, Span, Spanned,
};

/// Flags for deletion
#[derive(Clone, Debug)]
pub enum DeleteFlag {
    LowPriority(Span),
    Quick(Span),
    Ignore(Span),
}

impl Spanned for DeleteFlag {
    fn span(&self) -> Span {
        match &self {
            DeleteFlag::LowPriority(v) => v.span(),
            DeleteFlag::Quick(v) => v.span(),
            DeleteFlag::Ignore(v) => v.span(),
        }
    }
}

/// Represent a delete statement
/// ```
/// # use sql_parse::{SQLDialect, SQLArguments, ParseOptions, parse_statements, Delete, Statement};
/// # let options = ParseOptions::new().dialect(SQLDialect::MariaDB);
/// # let mut issues = Vec::new();
/// #
/// let sql = "DELETE FROM t1 WHERE c1 IN (SELECT b.c1 FROM t1 b WHERE b.c2=0);";
///
/// let mut stmts = parse_statements(sql, &mut issues, &options);
///
/// # assert!(issues.is_empty());
/// #
/// let delete: Delete = match stmts.pop() {
///     Some(Statement::Delete(d)) => d,
///     _ => panic!("We should get a delete statement")
/// };
///
/// assert!(delete.table.get(0).unwrap().as_str() == "t1");
/// println!("{:#?}", delete.where_)
/// ```
#[derive(Clone, Debug)]
pub struct Delete<'a> {
    /// Span of "DELETE"
    pub delete_span: Span,
    /// Flags following "DELETE"
    pub flags: Vec<DeleteFlag>,
    /// Span of "FROM"
    pub from_span: Span,
    /// Tables to do deletes on
    pub table: Vec<Identifier<'a>>,
    /// Where expression and Span of "WHERE" if specified
    pub where_: Option<(Expression<'a>, Span)>,
}

impl<'a> Spanned for Delete<'a> {
    fn span(&self) -> Span {
        self.delete_span
            .join_span(&self.flags)
            .join_span(&self.from_span)
            .join_span(&self.table)
            .join_span(&self.where_)
    }
}

pub(crate) fn parse_delete<'a, 'b>(parser: &mut Parser<'a, 'b>) -> Result<Delete<'a>, ParseError> {
    let delete_span = parser.consume_keyword(Keyword::DELETE)?;
    let mut flags = Vec::new();

    parser.recovered(
        "FROM",
        &|t| matches!(t, Token::Ident(_, Keyword::FROM)),
        |parser| {
            loop {
                match &parser.token {
                    Token::Ident(_, Keyword::LOW_PRIORITY) => flags.push(DeleteFlag::LowPriority(
                        parser.consume_keyword(Keyword::LOW_PRIORITY)?,
                    )),
                    Token::Ident(_, Keyword::QUICK) => {
                        flags.push(DeleteFlag::Quick(parser.consume_keyword(Keyword::QUICK)?))
                    }
                    Token::Ident(_, Keyword::IGNORE) => {
                        flags.push(DeleteFlag::Ignore(parser.consume_keyword(Keyword::IGNORE)?))
                    }
                    _ => break,
                }
            }
            Ok(())
        },
    )?;

    let from_span = parser.consume_keyword(Keyword::FROM)?;

    let mut table = vec![parser.consume_plain_identifier()?];
    loop {
        if parser.skip_token(Token::Period).is_none() {
            break;
        }
        table.push(parser.consume_plain_identifier()?);
    }

    //TODO [PARTITION (partition_list)]
    //TODO [FOR PORTION OF period FROM expr1 TO expr2]

    let where_ = if let Some(span) = parser.skip_keyword(Keyword::WHERE) {
        Some((parse_expression(parser, false)?, span))
    } else {
        None
    };
    //TODO [ORDER BY ...]
    //TODO LIMIT row_count]
    //TODO [RETURNING select_expr
    //TODO  [, select_expr ...]]

    Ok(Delete {
        flags,
        delete_span,
        table,
        from_span,
        where_,
    })
}