common_meta/ddl/alter_table/
check.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 api::v1::alter_table_expr::Kind;
16use api::v1::RenameTable;
17use common_catalog::format_full_table_name;
18use snafu::ensure;
19
20use crate::ddl::alter_table::AlterTableProcedure;
21use crate::error::{self, Result};
22use crate::key::table_name::TableNameKey;
23
24impl AlterTableProcedure {
25    /// Checks:
26    /// - The new table name doesn't exist (rename).
27    /// - Table exists.
28    pub(crate) async fn check_alter(&self) -> Result<()> {
29        let alter_expr = &self.data.task.alter_table;
30        let catalog = &alter_expr.catalog_name;
31        let schema = &alter_expr.schema_name;
32        let table_name = &alter_expr.table_name;
33        // Safety: Checked in `AlterTableProcedure::new`.
34        let alter_kind = self.data.task.alter_table.kind.as_ref().unwrap();
35
36        let manager = &self.context.table_metadata_manager;
37        if let Kind::RenameTable(RenameTable { new_table_name }) = alter_kind {
38            let new_table_name_key = TableNameKey::new(catalog, schema, new_table_name);
39            let exists = manager
40                .table_name_manager()
41                .exists(new_table_name_key)
42                .await?;
43            ensure!(
44                !exists,
45                error::TableAlreadyExistsSnafu {
46                    table_name: format_full_table_name(catalog, schema, new_table_name),
47                }
48            )
49        }
50
51        let table_name_key = TableNameKey::new(catalog, schema, table_name);
52        let exists = manager.table_name_manager().exists(table_name_key).await?;
53        ensure!(
54            exists,
55            error::TableNotFoundSnafu {
56                table_name: format_full_table_name(catalog, schema, &alter_expr.table_name),
57            }
58        );
59
60        Ok(())
61    }
62}