Skip to main content

common_meta/ddl/alter_logical_tables/
validator.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::collections::HashSet;
16
17use api::v1::AlterTableExpr;
18use api::v1::alter_table_expr::Kind;
19use snafu::{OptionExt, ensure};
20use store_api::storage::TableId;
21use table::table_reference::TableReference;
22
23use crate::ddl::utils::table_id::get_all_table_ids_by_names;
24use crate::ddl::utils::table_info::{
25    all_logical_table_routes_have_same_physical_id, get_all_table_info_values_by_table_ids,
26};
27use crate::error::{
28    AlterLogicalTablesInvalidArgumentsSnafu, Result, TableInfoNotFoundSnafu,
29    TableRouteNotFoundSnafu, UnexpectedSnafu,
30};
31use crate::key::table_info::TableInfoValue;
32use crate::key::table_route::{PhysicalTableRouteValue, TableRouteManager, TableRouteValue};
33use crate::key::{DeserializedValueWithBytes, TableMetadataManagerRef};
34
35/// [AlterLogicalTableValidator] validates the alter logical expressions.
36pub struct AlterLogicalTableValidator<'a> {
37    physical_table_id: TableId,
38    alters: Vec<&'a AlterTableExpr>,
39    expected_table_ids: &'a [TableId],
40}
41
42impl<'a> AlterLogicalTableValidator<'a> {
43    pub fn new(
44        physical_table_id: TableId,
45        alters: Vec<&'a AlterTableExpr>,
46        expected_table_ids: &'a [TableId],
47    ) -> Self {
48        Self {
49            physical_table_id,
50            alters,
51            expected_table_ids,
52        }
53    }
54
55    /// Validates all alter table expressions have the same schema and catalog.
56    fn validate_schema(&self) -> Result<()> {
57        let is_same_schema = self.alters.windows(2).all(|pair| {
58            pair[0].catalog_name == pair[1].catalog_name
59                && pair[0].schema_name == pair[1].schema_name
60        });
61
62        ensure!(
63            is_same_schema,
64            AlterLogicalTablesInvalidArgumentsSnafu {
65                err_msg: "Schemas of the alter table expressions are not the same"
66            }
67        );
68
69        Ok(())
70    }
71
72    /// Validates that all alter table expressions are of the supported kind.
73    /// Currently only supports `AddColumns` operations.
74    fn validate_alter_kind(&self) -> Result<()> {
75        for alter in &self.alters {
76            let kind = alter
77                .kind
78                .as_ref()
79                .context(AlterLogicalTablesInvalidArgumentsSnafu {
80                    err_msg: "Alter kind is missing",
81                })?;
82
83            let Kind::AddColumns(_) = kind else {
84                return AlterLogicalTablesInvalidArgumentsSnafu {
85                    err_msg: "Only support add columns operation",
86                }
87                .fail();
88            };
89        }
90
91        Ok(())
92    }
93
94    fn table_names(&self) -> Vec<TableReference<'_>> {
95        self.alters
96            .iter()
97            .map(|alter| {
98                TableReference::full(&alter.catalog_name, &alter.schema_name, &alter.table_name)
99            })
100            .collect()
101    }
102
103    /// Validates that the physical table info and route exist.
104    ///
105    /// This method performs the following validations:
106    /// 1. Retrieves the full table info and route for the given physical table id
107    /// 2. Ensures the table info and table route exists
108    /// 3. Verifies that the table route is actually a physical table route, not a logical one
109    ///
110    /// Returns a tuple containing the validated table info and physical table route.
111    async fn validate_physical_table(
112        &self,
113        table_metadata_manager: &TableMetadataManagerRef,
114    ) -> Result<(
115        DeserializedValueWithBytes<TableInfoValue>,
116        PhysicalTableRouteValue,
117    )> {
118        let (table_info, table_route) = table_metadata_manager
119            .get_full_table_info(self.physical_table_id)
120            .await?;
121
122        let table_info = table_info.with_context(|| TableInfoNotFoundSnafu {
123            table: format!("table id - {}", self.physical_table_id),
124        })?;
125
126        let physical_table_route = table_route
127            .context(TableRouteNotFoundSnafu {
128                table_id: self.physical_table_id,
129            })?
130            .into_inner();
131
132        let TableRouteValue::Physical(table_route) = physical_table_route else {
133            return AlterLogicalTablesInvalidArgumentsSnafu {
134                err_msg: format!(
135                    "expected a physical table but got a logical table: {:?}",
136                    self.physical_table_id
137                ),
138            }
139            .fail();
140        };
141
142        Ok((table_info, table_route))
143    }
144
145    /// Validates that all logical table routes have the same physical table id.
146    ///
147    /// This method performs the following validations:
148    /// 1. Retrieves table routes for all the given table ids.
149    /// 2. Ensures that all retrieved routes are logical table routes (not physical)
150    /// 3. Verifies that all logical table routes reference the same physical table id.
151    /// 4. Returns an error if any route is not logical or references a different physical table.
152    async fn validate_logical_table_routes(
153        &self,
154        table_route_manager: &TableRouteManager,
155        table_ids: &[TableId],
156    ) -> Result<()> {
157        let all_logical_table_routes_have_same_physical_id =
158            all_logical_table_routes_have_same_physical_id(
159                table_route_manager,
160                table_ids,
161                self.physical_table_id,
162            )
163            .await?;
164
165        ensure!(
166            all_logical_table_routes_have_same_physical_id,
167            AlterLogicalTablesInvalidArgumentsSnafu {
168                err_msg: "All the tasks should have the same physical table id"
169            }
170        );
171
172        Ok(())
173    }
174
175    /// Validates the alter logical expressions.
176    ///
177    /// This method performs the following validations:
178    /// 1. Validates that all alter table expressions have the same schema and catalog.
179    /// 2. Validates that all alter table expressions are of the supported kind.
180    /// 3. Validates that the physical table info and route exist.
181    /// 4. Validates that all logical table routes have the same physical table id.
182    ///
183    /// Returns a [ValidatorResult] containing the validation results.
184    pub async fn validate(
185        &self,
186        table_metadata_manager: &TableMetadataManagerRef,
187    ) -> Result<ValidatorResult> {
188        self.validate_schema()?;
189        self.validate_alter_kind()?;
190        let (physical_table_info, physical_table_route) =
191            self.validate_physical_table(table_metadata_manager).await?;
192        let table_names = self.table_names();
193        let table_ids =
194            get_all_table_ids_by_names(table_metadata_manager.table_name_manager(), &table_names)
195                .await?;
196        // Check before skipping completed ALTERs, while the procedure holds the pinned ID locks.
197        // Old persisted procedures have no pinned IDs and retain their previous behavior.
198        ensure!(
199            self.expected_table_ids.is_empty() || self.expected_table_ids == table_ids,
200            UnexpectedSnafu {
201                err_msg: "logical tables changed and are not covered by the procedure locks; retry the statement",
202            }
203        );
204        let mut table_info_values = get_all_table_info_values_by_table_ids(
205            table_metadata_manager.table_info_manager(),
206            &table_ids,
207            &table_names,
208        )
209        .await?;
210        self.validate_logical_table_routes(
211            table_metadata_manager.table_route_manager(),
212            &table_ids,
213        )
214        .await?;
215        let skip_alter = self
216            .alters
217            .iter()
218            .zip(table_info_values.iter())
219            .map(|(task, table)| skip_alter_logical_region(task, table))
220            .collect::<Vec<_>>();
221        retain_unskipped(&mut table_info_values, &skip_alter);
222        let num_skipped = skip_alter.iter().filter(|&&x| x).count();
223
224        Ok(ValidatorResult {
225            num_skipped,
226            skip_alter,
227            table_info_values,
228            physical_table_info,
229            physical_table_route,
230        })
231    }
232}
233
234/// The result of the validator.
235pub(crate) struct ValidatorResult {
236    pub(crate) num_skipped: usize,
237    pub(crate) skip_alter: Vec<bool>,
238    pub(crate) table_info_values: Vec<DeserializedValueWithBytes<TableInfoValue>>,
239    pub(crate) physical_table_info: DeserializedValueWithBytes<TableInfoValue>,
240    pub(crate) physical_table_route: PhysicalTableRouteValue,
241}
242
243/// Retains the elements that are not skipped.
244pub(crate) fn retain_unskipped<T>(target: &mut Vec<T>, skipped: &[bool]) {
245    debug_assert_eq!(target.len(), skipped.len());
246    let mut iter = skipped.iter();
247    target.retain(|_| !iter.next().unwrap());
248}
249
250/// Returns true if does not required to alter the logical region.
251fn skip_alter_logical_region(alter: &AlterTableExpr, table: &TableInfoValue) -> bool {
252    let existing_columns = table
253        .table_info
254        .meta
255        .schema
256        .column_schemas()
257        .iter()
258        .map(|c| &c.name)
259        .collect::<HashSet<_>>();
260
261    let Some(kind) = alter.kind.as_ref() else {
262        return true; // Never get here since we have checked it in `validate_alter_kind`
263    };
264    let Kind::AddColumns(add_columns) = kind else {
265        return true; // Never get here since we have checked it in `validate_alter_kind`
266    };
267
268    // We only check that all columns have been finished. That is to say,
269    // if one part is finished but another part is not, it will be considered
270    // unfinished.
271    add_columns
272        .add_columns
273        .iter()
274        .map(|add_column| add_column.column_def.as_ref().map(|c| &c.name))
275        .all(|column| {
276            column
277                .map(|c| existing_columns.contains(c))
278                .unwrap_or(false)
279        })
280}
281
282#[cfg(test)]
283mod tests {
284    use super::*;
285
286    #[test]
287    fn test_retain_unskipped() {
288        let mut target = vec![1, 2, 3, 4, 5];
289        let skipped = vec![false, true, false, true, false];
290        retain_unskipped(&mut target, &skipped);
291        assert_eq!(target, vec![1, 3, 5]);
292    }
293}