databend_common_ast/ast/statements/
settings.rs

1// Copyright 2021 Datafuse Labs
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;
16use std::fmt::Formatter;
17
18use derive_visitor::Drive;
19use derive_visitor::DriveMut;
20
21use crate::ast::Identifier;
22use crate::ast::SetType;
23use crate::ast::SetValues;
24
25#[derive(Debug, Clone, PartialEq, Drive, DriveMut)]
26pub struct Settings {
27    pub set_type: SetType,
28    pub identifiers: Vec<Identifier>,
29    pub values: SetValues,
30}
31
32impl Display for Settings {
33    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
34        match self.set_type {
35            SetType::SettingsGlobal => write!(f, "GLOBAL ")?,
36            SetType::SettingsSession => write!(f, "SESSION ")?,
37            SetType::Variable => write!(f, "VARIABLE ")?,
38            SetType::SettingsQuery => write!(f, "")?,
39        }
40
41        if self.identifiers.len() > 1 {
42            write!(f, "(")?;
43        }
44        for (idx, variable) in self.identifiers.iter().enumerate() {
45            if idx > 0 {
46                write!(f, ", ")?;
47            }
48            write!(f, "{variable}")?;
49        }
50        if self.identifiers.len() > 1 {
51            write!(f, ")")?;
52        }
53
54        match &self.values {
55            SetValues::Expr(exprs) => {
56                write!(f, " = ")?;
57                if exprs.len() > 1 {
58                    write!(f, "(")?;
59                }
60
61                for (idx, value) in exprs.iter().enumerate() {
62                    if idx > 0 {
63                        write!(f, ", ")?;
64                    }
65                    write!(f, "{value}")?;
66                }
67                if exprs.len() > 1 {
68                    write!(f, ")")?;
69                }
70            }
71            SetValues::Query(query) => {
72                write!(f, " = {query}")?;
73            }
74            SetValues::None => {}
75        }
76        Ok(())
77    }
78}