sql/statements/
truncate.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::fmt::Display;
16
17use serde::Serialize;
18use sqlparser::ast::ObjectName;
19use sqlparser_derive::{Visit, VisitMut};
20
21/// TRUNCATE TABLE statement.
22#[derive(Debug, Clone, PartialEq, Eq, Visit, VisitMut, Serialize)]
23pub struct TruncateTable {
24    table_name: ObjectName,
25}
26
27impl TruncateTable {
28    /// Creates a statement for `TRUNCATE TABLE`
29    pub fn new(table_name: ObjectName) -> Self {
30        Self { table_name }
31    }
32
33    pub fn table_name(&self) -> &ObjectName {
34        &self.table_name
35    }
36}
37
38impl Display for TruncateTable {
39    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
40        let table_name = self.table_name();
41        write!(f, r#"TRUNCATE TABLE {table_name}"#)
42    }
43}
44
45#[cfg(test)]
46mod tests {
47    use std::assert_matches::assert_matches;
48
49    use crate::dialect::GreptimeDbDialect;
50    use crate::parser::{ParseOptions, ParserContext};
51    use crate::statements::statement::Statement;
52
53    #[test]
54    fn test_display_for_tuncate_table() {
55        let sql = r"truncate table t1;";
56        let stmts: Vec<Statement> =
57            ParserContext::create_with_dialect(sql, &GreptimeDbDialect {}, ParseOptions::default())
58                .unwrap();
59        assert_eq!(1, stmts.len());
60        assert_matches!(&stmts[0], Statement::TruncateTable { .. });
61        match &stmts[0] {
62            Statement::TruncateTable(trunc) => {
63                let new_sql = format!("\n{}", trunc);
64                assert_eq!(
65                    r#"
66TRUNCATE TABLE t1"#,
67                    &new_sql
68                );
69            }
70            _ => {
71                unreachable!();
72            }
73        }
74    }
75}