tests_fuzz/translator/
common.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 super::DslTranslator;
18use crate::error::{Error, Result};
19use crate::ir::alter_expr::AlterTableOperation;
20use crate::ir::{AlterTableExpr, AlterTableOption};
21
22/// Shared translator for `ALTER TABLE` operations.
23pub(crate) struct CommonAlterTableTranslator;
24
25impl DslTranslator<AlterTableExpr, String> for CommonAlterTableTranslator {
26    type Error = Error;
27
28    fn translate(&self, input: &AlterTableExpr) -> Result<String> {
29        Ok(match &input.alter_kinds {
30            AlterTableOperation::DropColumn { name } => Self::format_drop(&input.table_name, name),
31            AlterTableOperation::SetTableOptions { options } => {
32                Self::format_set_table_options(&input.table_name, options)
33            }
34            AlterTableOperation::UnsetTableOptions { keys } => {
35                Self::format_unset_table_options(&input.table_name, keys)
36            }
37            _ => unimplemented!(),
38        })
39    }
40}
41
42impl CommonAlterTableTranslator {
43    fn format_drop(name: impl Display, column: impl Display) -> String {
44        format!("ALTER TABLE {name} DROP COLUMN {column};")
45    }
46
47    fn format_set_table_options(name: impl Display, options: &[AlterTableOption]) -> String {
48        format!(
49            "ALTER TABLE {name} SET {};",
50            options
51                .iter()
52                .map(|option| option.to_string())
53                .collect::<Vec<_>>()
54                .join(", ")
55        )
56    }
57
58    fn format_unset_table_options(name: impl Display, keys: &[String]) -> String {
59        format!(
60            "ALTER TABLE {name} UNSET {};",
61            keys.iter()
62                .map(|key| format!("'{}'", key))
63                .collect::<Vec<_>>()
64                .join(", ")
65        )
66    }
67}