sql/statements/
set_variables.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::{Expr, ObjectName};
19use sqlparser_derive::{Visit, VisitMut};
20
21/// SET variables statement.
22#[derive(Debug, Clone, PartialEq, Eq, Visit, VisitMut, Serialize)]
23pub struct SetVariables {
24    pub variable: ObjectName,
25    pub value: Vec<Expr>,
26}
27
28impl Display for SetVariables {
29    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
30        let variable = &self.variable;
31        let value = &self
32            .value
33            .iter()
34            .map(|expr| format!("{}", expr))
35            .collect::<Vec<_>>()
36            .join(", ");
37
38        write!(f, r#"SET {variable} = {value}"#)
39    }
40}
41
42#[cfg(test)]
43mod tests {
44    use std::assert_matches::assert_matches;
45
46    use crate::dialect::GreptimeDbDialect;
47    use crate::parser::{ParseOptions, ParserContext};
48    use crate::statements::statement::Statement;
49
50    #[test]
51    fn test_display_show_variables() {
52        let sql = r"set delayed_insert_timeout=300;";
53        let stmts =
54            ParserContext::create_with_dialect(sql, &GreptimeDbDialect {}, ParseOptions::default())
55                .unwrap();
56        assert_eq!(1, stmts.len());
57        assert_matches!(&stmts[0], Statement::SetVariables { .. });
58
59        match &stmts[0] {
60            Statement::SetVariables(set) => {
61                let new_sql = format!("\n{}", set);
62                assert_eq!(
63                    r#"
64SET delayed_insert_timeout = 300"#,
65                    &new_sql
66                );
67            }
68            _ => {
69                unreachable!();
70            }
71        }
72    }
73}