Skip to main content

table/
metadata.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::{HashMap, HashSet};
16use std::sync::Arc;
17
18use chrono::{DateTime, Utc};
19use common_catalog::consts::{
20    DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME, MITO_ENGINE, MITO2_ENGINE,
21};
22use common_macro::ToMetaBuilder;
23use common_query::AddColumnLocation;
24use datafusion_expr::TableProviderFilterPushDown;
25use datatypes::error::time_index_not_widening_error;
26pub use datatypes::error::{Error as ConvertError, Result as ConvertResult};
27use datatypes::extension::json::json2_metadata_with_updated_settings;
28use datatypes::schema::{
29    ColumnSchema, FulltextOptions, Schema, SchemaBuilder, SchemaRef, SkippingIndexOptions,
30};
31use derive_builder::Builder;
32use serde::{Deserialize, Deserializer, Serialize};
33use snafu::{OptionExt, ResultExt, ensure};
34use store_api::metric_engine_consts::{PHYSICAL_TABLE_METADATA_KEY, PRIMARY_KEY_ENCODING};
35use store_api::mito_engine_options::{
36    APPEND_MODE_KEY, AUTO_FLUSH_INTERVAL_KEY, COMPACTION_EXPERIMENTAL_OUTPUT_PARALLELISM,
37    COMPACTION_TYPE, COMPACTION_TYPE_TWCS, MAX_ROW_GROUP_ROW_COUNT, MERGE_MODE_KEY,
38    PRESERVE_ROW_SEQUENCE, SKIP_WAL_KEY, SST_FORMAT_KEY, TWCS_ACTIVE_WINDOW_TRIGGER_FILE_NUM,
39    TWCS_TRIGGER_FILE_NUM,
40};
41use store_api::region_request::{SetRegionOption, UnsetRegionOption};
42use store_api::storage::{ColumnDescriptor, ColumnDescriptorBuilder, ColumnId};
43
44use crate::error::{self, Result};
45use crate::requests::{
46    AddColumnRequest, AlterKind, AnnotationContext, AnnotationFamily, AnnotationValidationError,
47    ModifyColumnTypeRequest, REPARTITION_COLUMN_HINT_KEY, REPARTITION_PARTITION_NUM_HINT_KEY,
48    SetDefaultRequest, SetIndexOption, SetJsonSettingsRequest, TableOptions, UnsetIndexOption,
49    has_stable_string_form, parse_entity_columns, parse_entity_option_key,
50    validate_and_normalize_annotation, validate_annotation_keys,
51};
52use crate::table_reference::TableReference;
53
54pub type TableId = u32;
55pub type TableVersion = u64;
56
57/// Indicates whether and how a filter expression can be handled by a
58/// Table for table scans.
59#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
60pub enum FilterPushDownType {
61    /// The expression cannot be used by the provider.
62    Unsupported,
63    /// The expression can be used to help minimise the data retrieved,
64    /// but the provider cannot guarantee that all returned tuples
65    /// satisfy the filter. The Filter plan node containing this expression
66    /// will be preserved.
67    Inexact,
68    /// The provider guarantees that all returned data satisfies this
69    /// filter expression. The Filter plan node containing this expression
70    /// will be removed.
71    Exact,
72}
73
74impl From<TableProviderFilterPushDown> for FilterPushDownType {
75    fn from(value: TableProviderFilterPushDown) -> Self {
76        match value {
77            TableProviderFilterPushDown::Unsupported => FilterPushDownType::Unsupported,
78            TableProviderFilterPushDown::Inexact => FilterPushDownType::Inexact,
79            TableProviderFilterPushDown::Exact => FilterPushDownType::Exact,
80        }
81    }
82}
83
84impl From<FilterPushDownType> for TableProviderFilterPushDown {
85    fn from(value: FilterPushDownType) -> Self {
86        match value {
87            FilterPushDownType::Unsupported => TableProviderFilterPushDown::Unsupported,
88            FilterPushDownType::Inexact => TableProviderFilterPushDown::Inexact,
89            FilterPushDownType::Exact => TableProviderFilterPushDown::Exact,
90        }
91    }
92}
93
94/// Indicates the type of this table for metadata/catalog purposes.
95#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
96pub enum TableType {
97    /// An ordinary physical table.
98    Base,
99    /// A non-materialised table that itself uses a query internally to provide data.
100    View,
101    /// A transient table.
102    Temporary,
103}
104
105impl std::fmt::Display for TableType {
106    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
107        match self {
108            TableType::Base => f.write_str("BASE TABLE"),
109            TableType::Temporary => f.write_str("TEMPORARY"),
110            TableType::View => f.write_str("VIEW"),
111        }
112    }
113}
114
115impl From<TableType> for datafusion::datasource::TableType {
116    fn from(t: TableType) -> datafusion::datasource::TableType {
117        match t {
118            TableType::Base => datafusion::datasource::TableType::Base,
119            TableType::View => datafusion::datasource::TableType::View,
120            TableType::Temporary => datafusion::datasource::TableType::Temporary,
121        }
122    }
123}
124
125/// Identifier of the table.
126#[derive(Serialize, Deserialize, Clone, Debug, Eq, PartialEq, Default)]
127pub struct TableIdent {
128    /// Unique id of this table.
129    pub table_id: TableId,
130    /// Version of the table, bumped when metadata (such as schema) of the table
131    /// being changed.
132    pub version: TableVersion,
133}
134
135/// The table metadata.
136///
137/// Note: if you add new fields to this struct, please ensure 'new_meta_builder' function works.
138#[derive(Clone, Debug, Builder, PartialEq, Eq, ToMetaBuilder, Serialize)]
139#[builder(pattern = "mutable", custom_constructor)]
140pub struct TableMeta {
141    pub schema: SchemaRef,
142    /// The indices of columns in primary key. Note that the index of timestamp column
143    /// is not included in these indices.
144    pub primary_key_indices: Vec<usize>,
145    #[builder(default = "self.default_value_indices()?")]
146    pub value_indices: Vec<usize>,
147    #[builder(default, setter(into))]
148    pub engine: String,
149    pub next_column_id: ColumnId,
150    /// Table options.
151    #[builder(default)]
152    pub options: TableOptions,
153    #[builder(default = "Utc::now()")]
154    pub created_on: DateTime<Utc>,
155    #[builder(default = "self.default_updated_on()")]
156    pub updated_on: DateTime<Utc>,
157    #[builder(default = "Vec::new()")]
158    pub partition_key_indices: Vec<usize>,
159    #[builder(default = "Vec::new()")]
160    pub column_ids: Vec<ColumnId>,
161}
162
163impl TableMeta {
164    pub fn empty() -> Self {
165        Self {
166            schema: Arc::new(Schema::new(vec![])),
167            primary_key_indices: vec![],
168            value_indices: vec![],
169            engine: "".to_string(),
170            next_column_id: 0,
171            options: TableOptions::default(),
172            created_on: Utc::now(),
173            updated_on: Utc::now(),
174            partition_key_indices: vec![],
175            column_ids: vec![],
176        }
177    }
178}
179
180impl<'de> Deserialize<'de> for TableMeta {
181    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
182    where
183        D: Deserializer<'de>,
184    {
185        #[derive(Deserialize)]
186        struct RawTableMeta {
187            schema: SchemaRef,
188            primary_key_indices: Vec<usize>,
189            value_indices: Vec<usize>,
190            engine: String,
191            next_column_id: ColumnId,
192            options: TableOptions,
193            created_on: DateTime<Utc>,
194            updated_on: Option<DateTime<Utc>>,
195            #[serde(default)]
196            partition_key_indices: Vec<usize>,
197            #[serde(default)]
198            column_ids: Vec<ColumnId>,
199        }
200
201        let RawTableMeta {
202            schema,
203            primary_key_indices,
204            value_indices,
205            engine,
206            next_column_id,
207            options,
208            created_on,
209            updated_on,
210            partition_key_indices,
211            column_ids,
212        } = RawTableMeta::deserialize(deserializer)?;
213
214        Ok(Self {
215            schema,
216            primary_key_indices,
217            value_indices,
218            engine,
219            next_column_id,
220            options,
221            created_on,
222            updated_on: updated_on.unwrap_or(created_on),
223            partition_key_indices,
224            column_ids,
225        })
226    }
227}
228
229impl TableMetaBuilder {
230    /// Note: Please always use [new_meta_builder] to create new [TableMetaBuilder].
231    #[cfg(any(test, feature = "testing"))]
232    pub fn empty() -> Self {
233        Self {
234            schema: None,
235            primary_key_indices: None,
236            value_indices: None,
237            engine: None,
238            next_column_id: None,
239            options: None,
240            created_on: None,
241            updated_on: None,
242            partition_key_indices: None,
243            column_ids: None,
244        }
245    }
246}
247
248impl TableMetaBuilder {
249    fn default_value_indices(&self) -> std::result::Result<Vec<usize>, String> {
250        match (&self.primary_key_indices, &self.schema) {
251            (Some(v), Some(schema)) => {
252                let column_schemas = schema.column_schemas();
253                Ok((0..column_schemas.len())
254                    .filter(|idx| !v.contains(idx))
255                    .collect())
256            }
257            _ => Err("Missing primary_key_indices or schema to create value_indices".to_string()),
258        }
259    }
260
261    fn default_updated_on(&self) -> DateTime<Utc> {
262        self.created_on.unwrap_or_default()
263    }
264
265    pub fn new_external_table() -> Self {
266        Self {
267            schema: None,
268            primary_key_indices: Some(Vec::new()),
269            value_indices: Some(Vec::new()),
270            engine: None,
271            next_column_id: Some(0),
272            options: None,
273            created_on: None,
274            updated_on: None,
275            partition_key_indices: None,
276            column_ids: None,
277        }
278    }
279}
280
281/// The result after splitting requests by column location info.
282struct SplitResult<'a> {
283    /// column requests should be added at first place.
284    columns_at_first: Vec<&'a AddColumnRequest>,
285    /// column requests should be added after already exist columns.
286    columns_at_after: HashMap<String, Vec<&'a AddColumnRequest>>,
287    /// column requests should be added at last place.
288    columns_at_last: Vec<&'a AddColumnRequest>,
289    /// all column names should be added.
290    column_names: Vec<String>,
291}
292
293impl TableMeta {
294    pub fn row_key_column_names(&self) -> impl Iterator<Item = &String> {
295        let columns_schemas = &self.schema.column_schemas();
296        self.primary_key_indices
297            .iter()
298            .map(|idx| &columns_schemas[*idx].name)
299    }
300
301    pub fn field_column_names(&self) -> impl Iterator<Item = &String> {
302        // `value_indices` is wrong under distributed mode. Use the logic copied from DESC TABLE
303        let columns_schemas = self.schema.column_schemas();
304        let primary_key_indices = &self.primary_key_indices;
305        columns_schemas
306            .iter()
307            .enumerate()
308            .filter(|(i, cs)| !primary_key_indices.contains(i) && !cs.is_time_index())
309            .map(|(_, cs)| &cs.name)
310    }
311
312    pub fn partition_column_names(&self) -> impl Iterator<Item = &String> {
313        let columns_schemas = &self.schema.column_schemas();
314        self.partition_key_indices
315            .iter()
316            .map(|idx| &columns_schemas[*idx].name)
317    }
318
319    pub fn partition_columns(&self) -> impl Iterator<Item = &ColumnSchema> {
320        self.partition_key_indices
321            .iter()
322            .map(|idx| &self.schema.column_schemas()[*idx])
323    }
324
325    /// Returns the new [TableMetaBuilder] after applying given `alter_kind`.
326    ///
327    /// The returned builder would derive the next column id of this meta.
328    pub fn builder_with_alter_kind(
329        &self,
330        table_name: &str,
331        alter_kind: &AlterKind,
332    ) -> Result<TableMetaBuilder> {
333        let mut builder = match alter_kind {
334            AlterKind::AddColumns { columns } => self.add_columns(table_name, columns),
335            AlterKind::DropColumns { names } => self.remove_columns(table_name, names),
336            AlterKind::ModifyColumnTypes { columns } => {
337                self.modify_column_types(table_name, columns)
338            }
339            AlterKind::SetJsonSettings { request } => self.set_json_settings(table_name, request),
340            // No need to rebuild table meta when renaming tables.
341            AlterKind::RenameTable { .. } => Ok(self.new_meta_builder()),
342            AlterKind::SetTableOptions { options } => self.set_table_options(options),
343            AlterKind::UnsetTableOptions { keys } => self.unset_table_options(keys),
344            AlterKind::SetAnnotations { family, options } => {
345                self.set_annotations(table_name, *family, options)
346            }
347            AlterKind::UnsetAnnotations { family, keys } => {
348                self.unset_annotations(table_name, *family, keys)
349            }
350            AlterKind::SetIndexes { options } => self.set_indexes(table_name, options),
351            AlterKind::UnsetIndexes { options } => self.unset_indexes(table_name, options),
352            AlterKind::DropDefaults { names } => self.drop_defaults(table_name, names),
353            AlterKind::SetDefaults { defaults } => self.set_defaults(table_name, defaults),
354        }?;
355        let _ = builder.updated_on(Utc::now());
356        Ok(builder)
357    }
358
359    /// Creates a [TableMetaBuilder] with modified table options.
360    fn set_table_options(&self, requests: &[SetRegionOption]) -> Result<TableMetaBuilder> {
361        let mut new_options = self.options.clone();
362
363        for request in requests {
364            match request {
365                SetRegionOption::WriteBufferSize(new_write_buffer_size) => {
366                    new_options.write_buffer_size = *new_write_buffer_size;
367                }
368                SetRegionOption::Ttl(new_ttl) => {
369                    new_options.ttl = *new_ttl;
370                }
371                SetRegionOption::Twsc(key, value) => {
372                    let persisted_key = if matches!(
373                        key.as_str(),
374                        TWCS_TRIGGER_FILE_NUM | TWCS_ACTIVE_WINDOW_TRIGGER_FILE_NUM
375                    ) {
376                        new_options.extra_options.remove(TWCS_TRIGGER_FILE_NUM);
377                        new_options
378                            .extra_options
379                            .remove(TWCS_ACTIVE_WINDOW_TRIGGER_FILE_NUM);
380                        TWCS_TRIGGER_FILE_NUM
381                    } else {
382                        key
383                    };
384                    if !value.is_empty() {
385                        new_options
386                            .extra_options
387                            .insert(persisted_key.to_string(), value.clone());
388                        // Ensure node restart correctly.
389                        new_options.extra_options.insert(
390                            COMPACTION_TYPE.to_string(),
391                            COMPACTION_TYPE_TWCS.to_string(),
392                        );
393                    } else {
394                        // Invalidate the previous change option if an empty value has been set.
395                        new_options.extra_options.remove(persisted_key);
396                    }
397                }
398                SetRegionOption::Format(value) => {
399                    new_options
400                        .extra_options
401                        .insert(SST_FORMAT_KEY.to_string(), value.clone());
402                }
403                SetRegionOption::AppendMode(value) => {
404                    new_options
405                        .extra_options
406                        .insert(APPEND_MODE_KEY.to_string(), value.to_string());
407                    if *value {
408                        new_options.extra_options.remove(MERGE_MODE_KEY);
409                    }
410                }
411                SetRegionOption::AutoFlushInterval(new_interval) => {
412                    if let Some(interval) = new_interval {
413                        new_options.extra_options.insert(
414                            AUTO_FLUSH_INTERVAL_KEY.to_string(),
415                            humantime::format_duration(*interval).to_string(),
416                        );
417                    } else {
418                        new_options.extra_options.remove(AUTO_FLUSH_INTERVAL_KEY);
419                    }
420                }
421                SetRegionOption::CompactionOutputParallelism(parallelism) => {
422                    if let Some(parallelism) = parallelism {
423                        new_options.extra_options.insert(
424                            COMPACTION_EXPERIMENTAL_OUTPUT_PARALLELISM.to_string(),
425                            parallelism.to_string(),
426                        );
427                    } else {
428                        new_options
429                            .extra_options
430                            .remove(COMPACTION_EXPERIMENTAL_OUTPUT_PARALLELISM);
431                    }
432                }
433                SetRegionOption::MaxRowGroupRowCount(row_count) => {
434                    if let Some(row_count) = row_count {
435                        new_options
436                            .extra_options
437                            .insert(MAX_ROW_GROUP_ROW_COUNT.to_string(), row_count.to_string());
438                    } else {
439                        new_options.extra_options.remove(MAX_ROW_GROUP_ROW_COUNT);
440                    }
441                }
442                SetRegionOption::PreserveRowSequence(preserve) => {
443                    if *preserve {
444                        new_options
445                            .extra_options
446                            .insert(PRESERVE_ROW_SEQUENCE.to_string(), preserve.to_string());
447                    } else {
448                        new_options.extra_options.remove(PRESERVE_ROW_SEQUENCE);
449                    }
450                }
451                SetRegionOption::SkipWal(skip_wal) => {
452                    new_options.skip_wal = *skip_wal;
453                    // Keep the explicit table option so it remains distinguishable
454                    // from a value inherited from the schema.
455                    new_options
456                        .extra_options
457                        .insert(SKIP_WAL_KEY.to_string(), skip_wal.to_string());
458                }
459            }
460        }
461        let mut builder = self.new_meta_builder();
462        builder.options(new_options);
463
464        Ok(builder)
465    }
466
467    fn unset_table_options(&self, requests: &[UnsetRegionOption]) -> Result<TableMetaBuilder> {
468        let requests = requests.iter().map(Into::into).collect::<Vec<_>>();
469        self.set_table_options(&requests)
470    }
471
472    /// Applies an annotation SET. Validation lives here, on the mutation
473    /// path, so it runs both at frontend verification and again inside the
474    /// alter procedure's prepare step — under the table lock, against fresh
475    /// metadata.
476    fn set_annotations(
477        &self,
478        table_name: &str,
479        family: AnnotationFamily,
480        options: &[(String, String)],
481    ) -> Result<TableMetaBuilder> {
482        validate_annotation_keys(options.iter().map(|(key, _)| key.as_str())).map_err(|err| {
483            error::InvalidAlterRequestSnafu {
484                table: table_name,
485                err: err.to_string(),
486            }
487            .build()
488        })?;
489        let cx = AnnotationContext {
490            data_model: self.options.data_model(),
491            schema: &self.schema,
492            partition_key_indices: &self.partition_key_indices,
493        };
494        let mut new_options = self.options.clone();
495        for (key, value) in options {
496            ensure!(
497                AnnotationFamily::of_key(key) == Some(family),
498                error::InvalidAlterRequestSnafu {
499                    table: table_name,
500                    err: format!(
501                        "`{key}` is outside the `{}` annotation namespace",
502                        family.namespace()
503                    ),
504                }
505            );
506            let checked = validate_and_normalize_annotation(family, &cx, key, value).map_err(
507                |e| match e {
508                    AnnotationValidationError::ColumnNotFound { column } => {
509                        error::ColumnNotExistsSnafu {
510                            column_name: column,
511                            table_name,
512                        }
513                        .build()
514                    }
515                    other => error::InvalidAlterRequestSnafu {
516                        table: table_name,
517                        err: other.to_string(),
518                    }
519                    .build(),
520                },
521            )?;
522            new_options.extra_options.insert(key.clone(), checked);
523        }
524        let mut builder = self.new_meta_builder();
525        builder.options(new_options);
526        Ok(builder)
527    }
528
529    /// Applies an annotation UNSET. Deliberately lenient inside the family's
530    /// namespace: keys this version does not recognise may still be removed,
531    /// so options left behind by other versions can be cleaned up.
532    fn unset_annotations(
533        &self,
534        table_name: &str,
535        family: AnnotationFamily,
536        keys: &[String],
537    ) -> Result<TableMetaBuilder> {
538        validate_annotation_keys(keys.iter().map(String::as_str)).map_err(|err| {
539            error::InvalidAlterRequestSnafu {
540                table: table_name,
541                err: err.to_string(),
542            }
543            .build()
544        })?;
545        let mut new_options = self.options.clone();
546        for key in keys {
547            ensure!(
548                AnnotationFamily::of_key(key) == Some(family),
549                error::InvalidAlterRequestSnafu {
550                    table: table_name,
551                    err: format!(
552                        "`{key}` is outside the `{}` annotation namespace",
553                        family.namespace()
554                    ),
555                }
556            );
557            new_options.extra_options.remove(key);
558        }
559        let mut builder = self.new_meta_builder();
560        builder.options(new_options);
561        Ok(builder)
562    }
563
564    fn set_indexes(
565        &self,
566        table_name: &str,
567        requests: &[SetIndexOption],
568    ) -> Result<TableMetaBuilder> {
569        let table_schema = &self.schema;
570        let mut set_index_options: HashMap<&str, Vec<_>> = HashMap::new();
571        for request in requests {
572            let column_name = request.column_name();
573            table_schema
574                .column_index_by_name(column_name)
575                .with_context(|| error::ColumnNotExistsSnafu {
576                    column_name,
577                    table_name,
578                })?;
579            set_index_options
580                .entry(column_name)
581                .or_default()
582                .push(request);
583        }
584
585        let mut meta_builder = self.new_meta_builder();
586        let mut columns: Vec<_> = Vec::with_capacity(table_schema.column_schemas().len());
587        for mut column in table_schema.column_schemas().iter().cloned() {
588            if let Some(request) = set_index_options.get(column.name.as_str()) {
589                for request in request {
590                    self.set_index(&mut column, request)?;
591                }
592            }
593            columns.push(column);
594        }
595
596        let mut builder = SchemaBuilder::try_from_columns(columns)
597            .with_context(|_| error::SchemaBuildSnafu {
598                msg: format!("Failed to convert column schemas into schema for table {table_name}"),
599            })?
600            .version(table_schema.version() + 1);
601
602        for (k, v) in table_schema.metadata().iter() {
603            builder = builder.add_metadata(k, v);
604        }
605
606        let new_schema = builder.build().with_context(|_| {
607            let column_names = requests
608                .iter()
609                .map(|request| request.column_name())
610                .collect::<Vec<_>>();
611            error::SchemaBuildSnafu {
612                msg: format!(
613                    "Table {table_name} cannot set index options with columns {column_names:?}",
614                ),
615            }
616        })?;
617        let _ = meta_builder
618            .schema(Arc::new(new_schema))
619            .primary_key_indices(self.primary_key_indices.clone());
620
621        Ok(meta_builder)
622    }
623
624    fn unset_indexes(
625        &self,
626        table_name: &str,
627        requests: &[UnsetIndexOption],
628    ) -> Result<TableMetaBuilder> {
629        let table_schema = &self.schema;
630        let mut set_index_options: HashMap<&str, Vec<_>> = HashMap::new();
631        for request in requests {
632            let column_name = request.column_name();
633            table_schema
634                .column_index_by_name(column_name)
635                .with_context(|| error::ColumnNotExistsSnafu {
636                    column_name,
637                    table_name,
638                })?;
639            set_index_options
640                .entry(column_name)
641                .or_default()
642                .push(request);
643        }
644
645        let mut meta_builder = self.new_meta_builder();
646        let mut columns: Vec<_> = Vec::with_capacity(table_schema.column_schemas().len());
647        for mut column in table_schema.column_schemas().iter().cloned() {
648            if let Some(request) = set_index_options.get(column.name.as_str()) {
649                for request in request {
650                    self.unset_index(&mut column, request)?;
651                }
652            }
653            columns.push(column);
654        }
655
656        let mut builder = SchemaBuilder::try_from_columns(columns)
657            .with_context(|_| error::SchemaBuildSnafu {
658                msg: format!("Failed to convert column schemas into schema for table {table_name}"),
659            })?
660            .version(table_schema.version() + 1);
661
662        for (k, v) in table_schema.metadata().iter() {
663            builder = builder.add_metadata(k, v);
664        }
665
666        let new_schema = builder.build().with_context(|_| {
667            let column_names = requests
668                .iter()
669                .map(|request| request.column_name())
670                .collect::<Vec<_>>();
671            error::SchemaBuildSnafu {
672                msg: format!(
673                    "Table {table_name} cannot set index options with columns {column_names:?}",
674                ),
675            }
676        })?;
677        let _ = meta_builder
678            .schema(Arc::new(new_schema))
679            .primary_key_indices(self.primary_key_indices.clone());
680
681        Ok(meta_builder)
682    }
683
684    fn set_index(&self, column_schema: &mut ColumnSchema, request: &SetIndexOption) -> Result<()> {
685        match request {
686            SetIndexOption::Fulltext {
687                column_name,
688                options,
689            } => {
690                ensure!(
691                    column_schema.data_type.is_string(),
692                    error::InvalidColumnOptionSnafu {
693                        column_name,
694                        msg: "FULLTEXT index only supports string type",
695                    }
696                );
697
698                let current_fulltext_options = column_schema
699                    .fulltext_options()
700                    .context(error::SetFulltextOptionsSnafu { column_name })?;
701                set_column_fulltext_options(
702                    column_schema,
703                    column_name,
704                    options,
705                    current_fulltext_options,
706                )?;
707            }
708            SetIndexOption::Inverted { column_name } => {
709                debug_assert_eq!(column_schema.name, *column_name);
710                column_schema.set_inverted_index(true);
711            }
712            SetIndexOption::Skipping {
713                column_name,
714                options,
715            } => {
716                set_column_skipping_index_options(column_schema, column_name, options)?;
717            }
718        }
719
720        Ok(())
721    }
722
723    fn unset_index(
724        &self,
725        column_schema: &mut ColumnSchema,
726        request: &UnsetIndexOption,
727    ) -> Result<()> {
728        match request {
729            UnsetIndexOption::Fulltext { column_name } => {
730                let current_fulltext_options = column_schema
731                    .fulltext_options()
732                    .context(error::SetFulltextOptionsSnafu { column_name })?;
733                unset_column_fulltext_options(
734                    column_schema,
735                    column_name,
736                    current_fulltext_options.clone(),
737                )?
738            }
739            UnsetIndexOption::Inverted { .. } => {
740                column_schema.set_inverted_index(false);
741            }
742            UnsetIndexOption::Skipping { column_name } => {
743                unset_column_skipping_index_options(column_schema, column_name)?;
744            }
745        }
746
747        Ok(())
748    }
749
750    // TODO(yingwen): Remove this.
751    /// Allocate a new column for the table.
752    ///
753    /// This method would bump the `next_column_id` of the meta.
754    pub fn alloc_new_column(
755        &mut self,
756        table_name: &str,
757        new_column: &ColumnSchema,
758    ) -> Result<ColumnDescriptor> {
759        let desc = ColumnDescriptorBuilder::new(
760            self.next_column_id as ColumnId,
761            &new_column.name,
762            new_column.data_type.clone(),
763        )
764        .is_nullable(new_column.is_nullable())
765        .default_constraint(new_column.default_constraint().cloned())
766        .build()
767        .context(error::BuildColumnDescriptorSnafu {
768            table_name,
769            column_name: &new_column.name,
770        })?;
771
772        // Bump next column id.
773        self.next_column_id += 1;
774
775        Ok(desc)
776    }
777
778    /// Create a [`TableMetaBuilder`] from the current TableMeta.
779    fn new_meta_builder(&self) -> TableMetaBuilder {
780        let mut builder = TableMetaBuilder::from(self);
781        // Manually remove value_indices.
782        builder.value_indices = None;
783        builder
784    }
785
786    // TODO(yingwen): Tests add if not exists.
787    fn add_columns(
788        &self,
789        table_name: &str,
790        requests: &[AddColumnRequest],
791    ) -> Result<TableMetaBuilder> {
792        let table_schema = &self.schema;
793        let mut meta_builder = self.new_meta_builder();
794
795        let mut names = HashSet::with_capacity(requests.len());
796        let mut new_columns = Vec::with_capacity(requests.len());
797        for col_to_add in requests {
798            if let Some(column_schema) =
799                table_schema.column_schema_by_name(&col_to_add.column_schema.name)
800            {
801                // If the column already exists.
802                ensure!(
803                    col_to_add.add_if_not_exists,
804                    error::ColumnExistsSnafu {
805                        table_name,
806                        column_name: &col_to_add.column_schema.name
807                    },
808                );
809
810                // Checks if the type is the same
811                ensure!(
812                    column_schema.data_type == col_to_add.column_schema.data_type,
813                    error::InvalidAlterRequestSnafu {
814                        table: table_name,
815                        err: format!(
816                            "column {} already exists with different type {:?}",
817                            col_to_add.column_schema.name, column_schema.data_type,
818                        ),
819                    }
820                );
821            } else {
822                // A new column.
823                // Ensures we only add a column once.
824                ensure!(
825                    names.insert(&col_to_add.column_schema.name),
826                    error::InvalidAlterRequestSnafu {
827                        table: table_name,
828                        err: format!(
829                            "add column {} more than once",
830                            col_to_add.column_schema.name
831                        ),
832                    }
833                );
834
835                ensure!(
836                    col_to_add.column_schema.is_nullable()
837                        || col_to_add.column_schema.default_constraint().is_some(),
838                    error::InvalidAlterRequestSnafu {
839                        table: table_name,
840                        err: format!(
841                            "no default value for column {}",
842                            col_to_add.column_schema.name
843                        ),
844                    },
845                );
846
847                // A dropped column may leave a stale entity declaration behind;
848                // re-adding it must not hand the declaration a type without a
849                // stable string form.
850                if !has_stable_string_form(&col_to_add.column_schema.data_type)
851                    && let Some(key) =
852                        entity_option_referencing(&self.options, &col_to_add.column_schema.name)
853                {
854                    return error::InvalidAlterRequestSnafu {
855                        table: table_name,
856                        err: format!(
857                            "column `{}` is referenced by entity option `{key}` and must \
858                             keep a type that renders as a string, got `{}`",
859                            col_to_add.column_schema.name, col_to_add.column_schema.data_type
860                        ),
861                    }
862                    .fail();
863                }
864
865                new_columns.push(col_to_add.clone());
866            }
867        }
868        let requests = &new_columns[..];
869
870        let SplitResult {
871            columns_at_first,
872            columns_at_after,
873            columns_at_last,
874            column_names,
875        } = self.split_requests_by_column_location(table_name, requests)?;
876        let mut columns = Vec::with_capacity(table_schema.num_columns() + requests.len());
877        // add new columns with FIRST, and in reverse order of requests.
878        columns_at_first.iter().rev().for_each(|request| {
879            columns.push(request.column_schema.clone());
880        });
881        // add existed columns in original order and handle new columns with AFTER.
882        for column_schema in table_schema.column_schemas() {
883            columns.push(column_schema.clone());
884            if let Some(requests) = columns_at_after.get(&column_schema.name) {
885                requests.iter().rev().for_each(|request| {
886                    columns.push(request.column_schema.clone());
887                });
888            }
889        }
890        // add new columns without location info to last.
891        columns_at_last.iter().for_each(|request| {
892            columns.push(request.column_schema.clone());
893        });
894
895        let mut builder = SchemaBuilder::try_from(columns)
896            .with_context(|_| error::SchemaBuildSnafu {
897                msg: format!("Failed to convert column schemas into schema for table {table_name}"),
898            })?
899            // Also bump the schema version.
900            .version(table_schema.version() + 1);
901        for (k, v) in table_schema.metadata().iter() {
902            builder = builder.add_metadata(k, v);
903        }
904        let new_schema = builder.build().with_context(|_| error::SchemaBuildSnafu {
905            msg: format!("Table {table_name} cannot add new columns {column_names:?}"),
906        })?;
907
908        // Regions append new tags to the end of their primary key regardless of the column
909        // location (see `RegionMetadataBuilder::add_columns`), so the table key keeps its order
910        // and appends new key columns in request order.
911        let primary_key_indices = self
912            .primary_key_indices
913            .iter()
914            .map(|idx| table_schema.column_name_by_index(*idx))
915            .chain(
916                requests
917                    .iter()
918                    .filter(|request| request.is_key)
919                    .map(|request| request.column_schema.name.as_str()),
920            )
921            // This unwrap is safe since all these columns are in the new schema.
922            .map(|name| new_schema.column_index_by_name(name).unwrap())
923            .collect();
924
925        let partition_key_indices = self
926            .partition_key_indices
927            .iter()
928            .map(|idx| table_schema.column_name_by_index(*idx))
929            // This unwrap is safe since we only add new columns.
930            .map(|name| new_schema.column_index_by_name(name).unwrap())
931            .collect();
932
933        // value_indices would be generated automatically.
934        let _ = meta_builder
935            .schema(Arc::new(new_schema))
936            .primary_key_indices(primary_key_indices)
937            .partition_key_indices(partition_key_indices);
938
939        Ok(meta_builder)
940    }
941
942    fn remove_columns(
943        &self,
944        table_name: &str,
945        column_names: &[String],
946    ) -> Result<TableMetaBuilder> {
947        let table_schema = &self.schema;
948        let column_names: HashSet<_> = column_names.iter().collect();
949        let mut meta_builder = self.new_meta_builder();
950
951        let timestamp_index = table_schema.timestamp_index();
952        // Check whether columns are existing and not in primary key index.
953        for column_name in &column_names {
954            if let Some(index) = table_schema.column_index_by_name(column_name) {
955                // This is a linear search, but since there won't be too much columns, the performance should
956                // be acceptable.
957                ensure!(
958                    !self.primary_key_indices.contains(&index),
959                    error::RemoveColumnInIndexSnafu {
960                        column_name: *column_name,
961                        table_name,
962                    }
963                );
964
965                ensure!(
966                    !self.partition_key_indices.contains(&index),
967                    error::RemovePartitionColumnSnafu {
968                        column_name: *column_name,
969                        table_name,
970                    }
971                );
972
973                if let Some(ts_index) = timestamp_index {
974                    // Not allowed to remove column in timestamp index.
975                    ensure!(
976                        index != ts_index,
977                        error::RemoveColumnInIndexSnafu {
978                            column_name: table_schema.column_name_by_index(ts_index),
979                            table_name,
980                        }
981                    );
982                }
983            } else {
984                return error::ColumnNotExistsSnafu {
985                    column_name: *column_name,
986                    table_name,
987                }
988                .fail()?;
989            }
990        }
991
992        // Collect columns after removal.
993        let columns: Vec<_> = table_schema
994            .column_schemas()
995            .iter()
996            .filter(|column_schema| !column_names.contains(&column_schema.name))
997            .cloned()
998            .collect();
999
1000        let mut builder = SchemaBuilder::try_from_columns(columns)
1001            .with_context(|_| error::SchemaBuildSnafu {
1002                msg: format!("Failed to convert column schemas into schema for table {table_name}"),
1003            })?
1004            // Also bump the schema version.
1005            .version(table_schema.version() + 1);
1006        for (k, v) in table_schema.metadata().iter() {
1007            builder = builder.add_metadata(k, v);
1008        }
1009        let new_schema = builder.build().with_context(|_| error::SchemaBuildSnafu {
1010            msg: format!("Table {table_name} cannot add remove columns {column_names:?}"),
1011        })?;
1012
1013        // Rebuild the indices of primary key columns.
1014        let primary_key_indices = self
1015            .primary_key_indices
1016            .iter()
1017            .map(|idx| table_schema.column_name_by_index(*idx))
1018            // This unwrap is safe since we don't allow removing a primary key column.
1019            .map(|name| new_schema.column_index_by_name(name).unwrap())
1020            .collect();
1021
1022        let partition_key_indices = self
1023            .partition_key_indices
1024            .iter()
1025            .map(|idx| table_schema.column_name_by_index(*idx))
1026            // This unwrap is safe since we don't allow removing a partition key column.
1027            .map(|name| new_schema.column_index_by_name(name).unwrap())
1028            .collect();
1029
1030        let _ = meta_builder
1031            .schema(Arc::new(new_schema))
1032            .primary_key_indices(primary_key_indices)
1033            .partition_key_indices(partition_key_indices);
1034
1035        Ok(meta_builder)
1036    }
1037
1038    fn modify_column_types(
1039        &self,
1040        table_name: &str,
1041        requests: &[ModifyColumnTypeRequest],
1042    ) -> Result<TableMetaBuilder> {
1043        let table_schema = &self.schema;
1044        let mut meta_builder = self.new_meta_builder();
1045
1046        let mut modify_column_types = HashMap::with_capacity(requests.len());
1047        let timestamp_index = table_schema.timestamp_index();
1048
1049        for col_to_change in requests {
1050            let change_column_name = &col_to_change.column_name;
1051
1052            let index = table_schema
1053                .column_index_by_name(change_column_name)
1054                .with_context(|| error::ColumnNotExistsSnafu {
1055                    column_name: change_column_name,
1056                    table_name,
1057                })?;
1058
1059            // A column referenced by an entity declaration may be dropped (the
1060            // read-time derivation skips the stale declaration), but must not
1061            // change to a type without a stable string form. Checked after the
1062            // existence lookup so a missing column keeps reporting
1063            // `ColumnNotExists` regardless of stale declarations.
1064            if !has_stable_string_form(&col_to_change.target_type)
1065                && let Some(key) = entity_option_referencing(&self.options, change_column_name)
1066            {
1067                return error::InvalidAlterRequestSnafu {
1068                    table: table_name,
1069                    err: format!(
1070                        "column `{change_column_name}` is referenced by entity option \
1071                         `{key}` and must keep a type that renders as a string, got `{}`",
1072                        col_to_change.target_type
1073                    ),
1074                }
1075                .fail();
1076            }
1077
1078            let column = &table_schema.column_schemas()[index];
1079
1080            ensure!(
1081                !self.primary_key_indices.contains(&index),
1082                error::InvalidAlterRequestSnafu {
1083                    table: table_name,
1084                    err: format!(
1085                        "Not allowed to change primary key index column '{}'",
1086                        column.name
1087                    )
1088                }
1089            );
1090
1091            let is_time_index = timestamp_index == Some(index);
1092            if is_time_index {
1093                // The time index column is NOT NULL by construction and only
1094                // supports widening its unit; historical data in SSTs is cast
1095                // to the new unit on read, so no backfill is needed.
1096                ensure!(
1097                    column
1098                        .data_type
1099                        .is_timestamp_unit_widening_to(&col_to_change.target_type),
1100                    error::InvalidAlterRequestSnafu {
1101                        table: table_name,
1102                        err: time_index_not_widening_error(
1103                            &column.name,
1104                            &column.data_type,
1105                            &col_to_change.target_type,
1106                        ),
1107                    }
1108                );
1109            } else {
1110                // Partition rules keep bounds typed as the column, and functions such as
1111                // `iceberg_hash` route by the typed value, so a new type would reroute or
1112                // break routing. Time index widening above keeps timestamps comparable.
1113                ensure!(
1114                    !self.partition_key_indices.contains(&index),
1115                    error::InvalidAlterRequestSnafu {
1116                        table: table_name,
1117                        err: format!("Not allowed to change partition column '{}'", column.name)
1118                    }
1119                );
1120                ensure!(
1121                    column
1122                        .data_type
1123                        .can_arrow_type_cast_to(&col_to_change.target_type),
1124                    error::InvalidAlterRequestSnafu {
1125                        table: table_name,
1126                        err: format!(
1127                            "column '{}' cannot be cast automatically to type '{}'",
1128                            col_to_change.column_name, col_to_change.target_type,
1129                        ),
1130                    }
1131                );
1132
1133                ensure!(
1134                    column.is_nullable(),
1135                    error::InvalidAlterRequestSnafu {
1136                        table: table_name,
1137                        err: format!(
1138                            "column '{}' must be nullable to ensure safe conversion.",
1139                            col_to_change.column_name,
1140                        ),
1141                    }
1142                );
1143            }
1144            ensure!(
1145                modify_column_types
1146                    .insert(&col_to_change.column_name, col_to_change)
1147                    .is_none(),
1148                error::InvalidAlterRequestSnafu {
1149                    table: table_name,
1150                    err: format!(
1151                        "change column datatype {} more than once",
1152                        col_to_change.column_name
1153                    ),
1154                }
1155            );
1156        }
1157        // Collect columns after changed.
1158
1159        let mut columns: Vec<_> = Vec::with_capacity(table_schema.column_schemas().len());
1160        for mut column in table_schema.column_schemas().iter().cloned() {
1161            if let Some(change_column) = modify_column_types.get(&column.name) {
1162                column.data_type = change_column.target_type.clone();
1163                let new_default = if let Some(default_value) = column.default_constraint() {
1164                    Some(
1165                        default_value
1166                            .cast_to_datatype(&change_column.target_type)
1167                            .with_context(|_| error::CastDefaultValueSnafu {
1168                                reason: format!(
1169                                    "Failed to cast default value from {:?} to type {:?}",
1170                                    default_value, change_column.target_type
1171                                ),
1172                            })?,
1173                    )
1174                } else {
1175                    None
1176                };
1177                column = column
1178                    .clone()
1179                    .with_default_constraint(new_default.clone())
1180                    .with_context(|_| error::CastDefaultValueSnafu {
1181                        reason: format!("Failed to set new default: {:?}", new_default),
1182                    })?;
1183            }
1184            columns.push(column)
1185        }
1186
1187        let mut builder = SchemaBuilder::try_from_columns(columns)
1188            .with_context(|_| error::SchemaBuildSnafu {
1189                msg: format!("Failed to convert column schemas into schema for table {table_name}"),
1190            })?
1191            // Also bump the schema version.
1192            .version(table_schema.version() + 1);
1193        for (k, v) in table_schema.metadata().iter() {
1194            builder = builder.add_metadata(k, v);
1195        }
1196        let new_schema = builder.build().with_context(|_| {
1197            let column_names: Vec<_> = requests
1198                .iter()
1199                .map(|request| &request.column_name)
1200                .collect();
1201
1202            error::SchemaBuildSnafu {
1203                msg: format!(
1204                    "Table {table_name} cannot change datatype with columns {column_names:?}"
1205                ),
1206            }
1207        })?;
1208
1209        let _ = meta_builder
1210            .schema(Arc::new(new_schema))
1211            .primary_key_indices(self.primary_key_indices.clone());
1212
1213        Ok(meta_builder)
1214    }
1215
1216    fn set_json_settings(
1217        &self,
1218        table_name: &str,
1219        req: &SetJsonSettingsRequest,
1220    ) -> Result<TableMetaBuilder> {
1221        let table_schema = &self.schema;
1222        let idx = table_schema
1223            .column_index_by_name(&req.column_name)
1224            .with_context(|| error::ColumnNotExistsSnafu {
1225                column_name: &req.column_name,
1226                table_name,
1227            })?;
1228        let col = &table_schema.column_schemas()[idx];
1229
1230        ensure!(
1231            !self.primary_key_indices.contains(&idx) && table_schema.timestamp_index() != Some(idx),
1232            error::InvalidAlterRequestSnafu {
1233                table: table_name,
1234                err: format!(
1235                    "Not allowed to change JSON settings for key or timestamp column '{}'",
1236                    col.name
1237                ),
1238            }
1239        );
1240        ensure!(
1241            col.data_type.is_json2(),
1242            error::InvalidAlterRequestSnafu {
1243                table: table_name,
1244                err: format!("column '{}' is not a JSON2 column", col.name),
1245            }
1246        );
1247
1248        let target_metadata =
1249            json2_metadata_with_updated_settings(col.metadata(), req.settings.clone()).map_err(
1250                |err| {
1251                    error::InvalidAlterRequestSnafu {
1252                        table: table_name,
1253                        err: err.to_string(),
1254                    }
1255                    .build()
1256                },
1257            )?;
1258
1259        let mut cols = table_schema.column_schemas().to_vec();
1260        *cols[idx].mut_metadata() = target_metadata;
1261
1262        let mut builder = SchemaBuilder::try_from_columns(cols)
1263            .with_context(|_| error::SchemaBuildSnafu {
1264                msg: format!("Failed to convert column schemas into schema for table {table_name}"),
1265            })?
1266            .version(table_schema.version() + 1);
1267
1268        for (k, v) in table_schema.metadata().iter() {
1269            builder = builder.add_metadata(k, v);
1270        }
1271
1272        let new_schema = builder.build().with_context(|_| error::SchemaBuildSnafu {
1273            msg: format!(
1274                "Table {table_name} cannot change JSON settings for column {}",
1275                req.column_name
1276            ),
1277        })?;
1278
1279        let mut meta_builder = self.new_meta_builder();
1280        let _ = meta_builder
1281            .schema(Arc::new(new_schema))
1282            .primary_key_indices(self.primary_key_indices.clone());
1283
1284        Ok(meta_builder)
1285    }
1286
1287    /// Split requests into different groups using column location info.
1288    fn split_requests_by_column_location<'a>(
1289        &self,
1290        table_name: &str,
1291        requests: &'a [AddColumnRequest],
1292    ) -> Result<SplitResult<'a>> {
1293        let table_schema = &self.schema;
1294        let mut columns_at_first = Vec::new();
1295        let mut columns_at_after = HashMap::new();
1296        let mut columns_at_last = Vec::new();
1297        let mut column_names = Vec::with_capacity(requests.len());
1298        for request in requests {
1299            // Check whether columns to add are already existing.
1300            let column_name = &request.column_schema.name;
1301            column_names.push(column_name.clone());
1302            ensure!(
1303                table_schema.column_schema_by_name(column_name).is_none(),
1304                error::ColumnExistsSnafu {
1305                    column_name,
1306                    table_name,
1307                }
1308            );
1309            match request.location.as_ref() {
1310                Some(AddColumnLocation::First) => {
1311                    columns_at_first.push(request);
1312                }
1313                Some(AddColumnLocation::After { column_name }) => {
1314                    ensure!(
1315                        table_schema.column_schema_by_name(column_name).is_some(),
1316                        error::ColumnNotExistsSnafu {
1317                            column_name,
1318                            table_name,
1319                        }
1320                    );
1321                    columns_at_after
1322                        .entry(column_name.clone())
1323                        .or_insert(Vec::new())
1324                        .push(request);
1325                }
1326                None => {
1327                    columns_at_last.push(request);
1328                }
1329            }
1330        }
1331        Ok(SplitResult {
1332            columns_at_first,
1333            columns_at_after,
1334            columns_at_last,
1335            column_names,
1336        })
1337    }
1338
1339    fn drop_defaults(&self, table_name: &str, column_names: &[String]) -> Result<TableMetaBuilder> {
1340        let table_schema = &self.schema;
1341        let mut meta_builder = self.new_meta_builder();
1342        let mut columns = Vec::with_capacity(table_schema.num_columns());
1343        for column_schema in table_schema.column_schemas() {
1344            if let Some(name) = column_names.iter().find(|s| **s == column_schema.name) {
1345                // Drop default constraint.
1346                ensure!(
1347                    column_schema.default_constraint().is_some(),
1348                    error::InvalidAlterRequestSnafu {
1349                        table: table_name,
1350                        err: format!("column {name} does not have a default value"),
1351                    }
1352                );
1353                if !column_schema.is_nullable() {
1354                    return error::InvalidAlterRequestSnafu {
1355                        table: table_name,
1356                        err: format!(
1357                            "column {name} is not nullable and `default` cannot be dropped",
1358                        ),
1359                    }
1360                    .fail();
1361                }
1362                let new_column_schema = column_schema.clone();
1363                let new_column_schema = new_column_schema
1364                    .with_default_constraint(None)
1365                    .with_context(|_| error::SchemaBuildSnafu {
1366                        msg: format!("Table {table_name} cannot drop default values"),
1367                    })?;
1368                columns.push(new_column_schema);
1369            } else {
1370                columns.push(column_schema.clone());
1371            }
1372        }
1373
1374        let mut builder = SchemaBuilder::try_from_columns(columns)
1375            .with_context(|_| error::SchemaBuildSnafu {
1376                msg: format!("Failed to convert column schemas into schema for table {table_name}"),
1377            })?
1378            // Also bump the schema version.
1379            .version(table_schema.version() + 1);
1380        for (k, v) in table_schema.metadata().iter() {
1381            builder = builder.add_metadata(k, v);
1382        }
1383        let new_schema = builder.build().with_context(|_| error::SchemaBuildSnafu {
1384            msg: format!("Table {table_name} cannot drop default values"),
1385        })?;
1386
1387        let _ = meta_builder.schema(Arc::new(new_schema));
1388
1389        Ok(meta_builder)
1390    }
1391
1392    fn set_defaults(
1393        &self,
1394        table_name: &str,
1395        set_defaults: &[SetDefaultRequest],
1396    ) -> Result<TableMetaBuilder> {
1397        let table_schema = &self.schema;
1398        let mut meta_builder = self.new_meta_builder();
1399        let mut columns = Vec::with_capacity(table_schema.num_columns());
1400        for column_schema in table_schema.column_schemas() {
1401            if let Some(set_default) = set_defaults
1402                .iter()
1403                .find(|s| s.column_name == column_schema.name)
1404            {
1405                let new_column_schema = column_schema.clone();
1406                let new_column_schema = new_column_schema
1407                    .with_default_constraint(set_default.default_constraint.clone())
1408                    .with_context(|_| error::SchemaBuildSnafu {
1409                        msg: format!("Table {table_name} cannot set default values"),
1410                    })?;
1411                columns.push(new_column_schema);
1412            } else {
1413                columns.push(column_schema.clone());
1414            }
1415        }
1416
1417        let mut builder = SchemaBuilder::try_from_columns(columns)
1418            .with_context(|_| error::SchemaBuildSnafu {
1419                msg: format!("Failed to convert column schemas into schema for table {table_name}"),
1420            })?
1421            // Also bump the schema version.
1422            .version(table_schema.version() + 1);
1423        for (k, v) in table_schema.metadata().iter() {
1424            builder = builder.add_metadata(k, v);
1425        }
1426        let new_schema = builder.build().with_context(|_| error::SchemaBuildSnafu {
1427            msg: format!("Table {table_name} cannot set default values"),
1428        })?;
1429
1430        let _ = meta_builder.schema(Arc::new(new_schema));
1431
1432        Ok(meta_builder)
1433    }
1434}
1435
1436#[derive(Clone, Debug, PartialEq, Eq, Builder, Serialize, Deserialize)]
1437#[builder(pattern = "owned")]
1438pub struct TableInfo {
1439    /// Id and version of the table.
1440    #[builder(default, setter(into))]
1441    pub ident: TableIdent,
1442    /// Name of the table.
1443    #[builder(setter(into))]
1444    pub name: String,
1445    /// Comment of the table.
1446    #[builder(default, setter(into))]
1447    pub desc: Option<String>,
1448    #[builder(default = "DEFAULT_CATALOG_NAME.to_string()", setter(into))]
1449    pub catalog_name: String,
1450    #[builder(default = "DEFAULT_SCHEMA_NAME.to_string()", setter(into))]
1451    pub schema_name: String,
1452    pub meta: TableMeta,
1453    #[builder(default = "TableType::Base")]
1454    pub table_type: TableType,
1455}
1456
1457pub type TableInfoRef = Arc<TableInfo>;
1458
1459impl TableInfo {
1460    pub fn table_id(&self) -> TableId {
1461        self.ident.table_id
1462    }
1463
1464    /// Returns the full table name in the form of `{catalog}.{schema}.{table}`.
1465    pub fn full_table_name(&self) -> String {
1466        common_catalog::format_full_table_name(&self.catalog_name, &self.schema_name, &self.name)
1467    }
1468
1469    pub fn get_db_string(&self) -> String {
1470        common_catalog::build_db_string(&self.catalog_name, &self.schema_name)
1471    }
1472
1473    /// Returns true when the table is the metric engine's physical table.
1474    pub fn is_physical_table(&self) -> bool {
1475        self.meta
1476            .options
1477            .extra_options
1478            .contains_key(PHYSICAL_TABLE_METADATA_KEY)
1479    }
1480
1481    /// Ordinary Mito tables accept sparse keys directly. The metric engine encodes its own keys.
1482    pub fn is_sparse_mito_table(&self) -> bool {
1483        matches!(self.meta.engine.as_str(), MITO_ENGINE | MITO2_ENGINE)
1484            && self.has_sparse_primary_key_option()
1485    }
1486
1487    /// Whether the table explicitly selects sparse primary-key encoding.
1488    pub fn has_sparse_primary_key_option(&self) -> bool {
1489        self.meta
1490            .options
1491            .extra_options
1492            .get(PRIMARY_KEY_ENCODING)
1493            .is_some_and(|encoding| encoding.eq_ignore_ascii_case("sparse"))
1494    }
1495
1496    /// Return true if the table's TTL is `instant`.
1497    pub fn is_ttl_instant_table(&self) -> bool {
1498        self.meta
1499            .options
1500            .ttl
1501            .map(|t| t.is_instant())
1502            .unwrap_or(false)
1503    }
1504}
1505
1506impl TableInfoBuilder {
1507    pub fn new<S: Into<String>>(name: S, meta: TableMeta) -> Self {
1508        Self {
1509            name: Some(name.into()),
1510            meta: Some(meta),
1511            ..Default::default()
1512        }
1513    }
1514
1515    pub fn table_id(mut self, id: TableId) -> Self {
1516        let ident = self.ident.get_or_insert_with(TableIdent::default);
1517        ident.table_id = id;
1518        self
1519    }
1520
1521    pub fn table_version(mut self, version: TableVersion) -> Self {
1522        let ident = self.ident.get_or_insert_with(TableIdent::default);
1523        ident.version = version;
1524        self
1525    }
1526}
1527
1528impl TableIdent {
1529    pub fn new(table_id: TableId) -> Self {
1530        Self {
1531            table_id,
1532            version: 0,
1533        }
1534    }
1535}
1536
1537impl From<TableId> for TableIdent {
1538    fn from(table_id: TableId) -> Self {
1539        Self::new(table_id)
1540    }
1541}
1542
1543impl TableInfo {
1544    /// Returns the map of column name to column id.
1545    ///
1546    /// Note: This method may return an empty map for older versions that did not include this field.
1547    pub fn name_to_ids(&self) -> Option<HashMap<String, ColumnId>> {
1548        let column_schemas = self.meta.schema.column_schemas();
1549        if self.meta.column_ids.len() != column_schemas.len() {
1550            None
1551        } else {
1552            Some(
1553                self.meta
1554                    .column_ids
1555                    .iter()
1556                    .enumerate()
1557                    .map(|(index, id)| (column_schemas[index].name.clone(), *id))
1558                    .collect(),
1559            )
1560        }
1561    }
1562
1563    /// Sort the columns in [TableInfo], logical tables require it.
1564    pub fn sort_columns(&mut self) {
1565        let column_schemas = self.meta.schema.column_schemas();
1566        let primary_keys = self
1567            .meta
1568            .primary_key_indices
1569            .iter()
1570            .map(|index| column_schemas[*index].name.clone())
1571            .collect::<HashSet<_>>();
1572
1573        let name_to_ids = self.name_to_ids().unwrap_or_default();
1574        let mut column_schemas = column_schemas.to_vec();
1575        column_schemas.sort_unstable_by(|a, b| a.name.cmp(&b.name));
1576
1577        // Compute new indices of sorted columns
1578        let mut primary_key_indices = Vec::with_capacity(primary_keys.len());
1579        let mut value_indices = Vec::with_capacity(column_schemas.len() - primary_keys.len());
1580        let mut column_ids = Vec::with_capacity(column_schemas.len());
1581        for (index, column_schema) in column_schemas.iter().enumerate() {
1582            if primary_keys.contains(&column_schema.name) {
1583                primary_key_indices.push(index);
1584            } else {
1585                value_indices.push(index);
1586            }
1587            if let Some(id) = name_to_ids.get(&column_schema.name) {
1588                column_ids.push(*id);
1589            }
1590        }
1591
1592        // Overwrite table meta
1593        self.meta.schema = Arc::new(Schema::new_with_version(
1594            column_schemas,
1595            self.meta.schema.version(),
1596        ));
1597        self.meta.primary_key_indices = primary_key_indices;
1598        self.meta.value_indices = value_indices;
1599        self.meta.column_ids = column_ids;
1600    }
1601
1602    /// Extracts region options from table info.
1603    ///
1604    /// All "region options" are actually a copy of table options for redundancy.
1605    pub fn to_region_options(&self) -> HashMap<String, String> {
1606        let mut options = HashMap::from(&self.meta.options);
1607        options.remove(REPARTITION_COLUMN_HINT_KEY);
1608        options.remove(REPARTITION_PARTITION_NUM_HINT_KEY);
1609        options
1610    }
1611
1612    /// Returns the table reference.
1613    pub fn table_ref(&self) -> TableReference<'_> {
1614        TableReference::full(
1615            self.catalog_name.as_str(),
1616            self.schema_name.as_str(),
1617            self.name.as_str(),
1618        )
1619    }
1620}
1621
1622fn entity_option_referencing<'a>(options: &'a TableOptions, column: &str) -> Option<&'a str> {
1623    options.extra_options.iter().find_map(|(key, value)| {
1624        (parse_entity_option_key(key).is_some()
1625            && parse_entity_columns(value).iter().any(|c| c == column))
1626        .then_some(key.as_str())
1627    })
1628}
1629
1630/// Set column fulltext options if it passed the validation.
1631///
1632/// Options allowed to modify:
1633/// * backend
1634///
1635/// Options not allowed to modify:
1636/// * analyzer
1637/// * case_sensitive
1638fn set_column_fulltext_options(
1639    column_schema: &mut ColumnSchema,
1640    column_name: &str,
1641    options: &FulltextOptions,
1642    current_options: Option<FulltextOptions>,
1643) -> Result<()> {
1644    if let Some(current_options) = current_options {
1645        ensure!(
1646            current_options.analyzer == options.analyzer
1647                && current_options.case_sensitive == options.case_sensitive,
1648            error::InvalidColumnOptionSnafu {
1649                column_name,
1650                msg: format!(
1651                    "Cannot change analyzer or case_sensitive if FULLTEXT index is set before. Previous analyzer: {}, previous case_sensitive: {}",
1652                    current_options.analyzer, current_options.case_sensitive
1653                ),
1654            }
1655        );
1656    }
1657
1658    column_schema
1659        .set_fulltext_options(options)
1660        .context(error::SetFulltextOptionsSnafu { column_name })?;
1661
1662    Ok(())
1663}
1664
1665fn unset_column_fulltext_options(
1666    column_schema: &mut ColumnSchema,
1667    column_name: &str,
1668    current_options: Option<FulltextOptions>,
1669) -> Result<()> {
1670    ensure!(
1671        current_options
1672            .as_ref()
1673            .is_some_and(|options| options.enable),
1674        error::InvalidColumnOptionSnafu {
1675            column_name,
1676            msg: "FULLTEXT index already disabled".to_string(),
1677        }
1678    );
1679
1680    let mut options = current_options.unwrap();
1681    options.enable = false;
1682    column_schema
1683        .set_fulltext_options(&options)
1684        .context(error::SetFulltextOptionsSnafu { column_name })?;
1685
1686    Ok(())
1687}
1688
1689fn set_column_skipping_index_options(
1690    column_schema: &mut ColumnSchema,
1691    column_name: &str,
1692    options: &SkippingIndexOptions,
1693) -> Result<()> {
1694    column_schema
1695        .set_skipping_options(options)
1696        .context(error::SetSkippingOptionsSnafu { column_name })?;
1697
1698    Ok(())
1699}
1700
1701fn unset_column_skipping_index_options(
1702    column_schema: &mut ColumnSchema,
1703    column_name: &str,
1704) -> Result<()> {
1705    column_schema
1706        .unset_skipping_options()
1707        .context(error::UnsetSkippingOptionsSnafu { column_name })?;
1708    Ok(())
1709}
1710
1711#[cfg(test)]
1712mod tests {
1713    use std::assert_matches;
1714
1715    use common_error::ext::ErrorExt;
1716    use common_error::status_code::StatusCode;
1717    use datatypes::data_type::ConcreteDataType;
1718    use datatypes::extension::json::{Json2ExtensionType, JsonMetadata};
1719    use datatypes::json::JsonSettings;
1720    use datatypes::schema::{
1721        ColumnSchema, FulltextAnalyzer, FulltextBackend, Schema, SchemaBuilder,
1722    };
1723    use datatypes::types::JsonType;
1724
1725    use super::*;
1726    use crate::Error;
1727
1728    /// Create a test schema with 3 columns: `[col1 int32, ts timestampmills, col2 int32]`.
1729    fn new_test_schema() -> Schema {
1730        let column_schemas = vec![
1731            ColumnSchema::new("col1", ConcreteDataType::int32_datatype(), true),
1732            ColumnSchema::new(
1733                "ts",
1734                ConcreteDataType::timestamp_millisecond_datatype(),
1735                false,
1736            )
1737            .with_time_index(true),
1738            ColumnSchema::new("col2", ConcreteDataType::int32_datatype(), true),
1739        ];
1740        SchemaBuilder::try_from(column_schemas)
1741            .unwrap()
1742            .version(123)
1743            .build()
1744            .unwrap()
1745    }
1746
1747    fn add_columns_to_meta(meta: &TableMeta) -> TableMeta {
1748        let new_tag = ColumnSchema::new("my_tag", ConcreteDataType::string_datatype(), true);
1749        let new_field = ColumnSchema::new("my_field", ConcreteDataType::string_datatype(), true);
1750        let alter_kind = AlterKind::AddColumns {
1751            columns: vec![
1752                AddColumnRequest {
1753                    column_schema: new_tag,
1754                    is_key: true,
1755                    location: None,
1756                    add_if_not_exists: false,
1757                },
1758                AddColumnRequest {
1759                    column_schema: new_field,
1760                    is_key: false,
1761                    location: None,
1762                    add_if_not_exists: false,
1763                },
1764            ],
1765        };
1766
1767        let builder = meta
1768            .builder_with_alter_kind("my_table", &alter_kind)
1769            .unwrap();
1770        builder.build().unwrap()
1771    }
1772
1773    fn add_columns_to_meta_with_location(meta: &TableMeta) -> TableMeta {
1774        let new_tag = ColumnSchema::new("my_tag_first", ConcreteDataType::string_datatype(), true);
1775        let new_field = ColumnSchema::new(
1776            "my_field_after_ts",
1777            ConcreteDataType::string_datatype(),
1778            true,
1779        );
1780        let yet_another_field = ColumnSchema::new(
1781            "yet_another_field_after_ts",
1782            ConcreteDataType::int64_datatype(),
1783            true,
1784        );
1785        let alter_kind = AlterKind::AddColumns {
1786            columns: vec![
1787                AddColumnRequest {
1788                    column_schema: new_tag,
1789                    is_key: true,
1790                    location: Some(AddColumnLocation::First),
1791                    add_if_not_exists: false,
1792                },
1793                AddColumnRequest {
1794                    column_schema: new_field,
1795                    is_key: false,
1796                    location: Some(AddColumnLocation::After {
1797                        column_name: "ts".to_string(),
1798                    }),
1799                    add_if_not_exists: false,
1800                },
1801                AddColumnRequest {
1802                    column_schema: yet_another_field,
1803                    is_key: true,
1804                    location: Some(AddColumnLocation::After {
1805                        column_name: "ts".to_string(),
1806                    }),
1807                    add_if_not_exists: false,
1808                },
1809            ],
1810        };
1811
1812        let builder = meta
1813            .builder_with_alter_kind("my_table", &alter_kind)
1814            .unwrap();
1815        builder.build().unwrap()
1816    }
1817
1818    #[test]
1819    fn test_set_json_settings() {
1820        let schema = Arc::new(
1821            SchemaBuilder::try_from_columns(vec![
1822                ColumnSchema::new("col1", ConcreteDataType::int32_datatype(), true),
1823                ColumnSchema::new(
1824                    "ts",
1825                    ConcreteDataType::timestamp_millisecond_datatype(),
1826                    false,
1827                )
1828                .with_time_index(true),
1829                json2_column_schema_v1("payload", JsonSettings::new_v2()),
1830            ])
1831            .unwrap()
1832            .version(123)
1833            .build()
1834            .unwrap(),
1835        );
1836        let meta = TableMetaBuilder::empty()
1837            .schema(schema)
1838            .primary_key_indices(vec![0])
1839            .engine("engine")
1840            .next_column_id(3)
1841            .build()
1842            .unwrap();
1843
1844        let alter_kind = AlterKind::SetJsonSettings {
1845            request: SetJsonSettingsRequest {
1846                column_name: "payload".to_string(),
1847                settings: JsonSettings::try_new(vec![], Some(10)).unwrap(),
1848            },
1849        };
1850        let new_meta = meta
1851            .builder_with_alter_kind("my_table", &alter_kind)
1852            .unwrap()
1853            .build()
1854            .unwrap();
1855
1856        let payload = new_meta.schema.column_schema_by_name("payload").unwrap();
1857        let json_metadata: JsonMetadata =
1858            serde_json::from_str(payload.metadata().get("ARROW:extension:metadata").unwrap())
1859                .unwrap();
1860        assert!(json_metadata.is_version_2());
1861        assert_eq!(
1862            Some(10),
1863            json_metadata.json_settings().max_auto_expanded_paths()
1864        );
1865        assert_eq!(124, new_meta.schema.version());
1866        assert_eq!(meta.primary_key_indices, new_meta.primary_key_indices);
1867    }
1868
1869    fn json2_column_schema_v1(name: &str, settings: JsonSettings) -> ColumnSchema {
1870        let mut column_schema =
1871            ColumnSchema::new(name, ConcreteDataType::Json(JsonType::null()), true);
1872        column_schema.with_extension_type(&Json2ExtensionType::new(Arc::new(
1873            JsonMetadata::new_v1(settings),
1874        )));
1875        column_schema
1876    }
1877
1878    #[test]
1879    fn test_set_json_settings_rejects_non_json2_column() {
1880        let schema = Arc::new(new_test_schema());
1881        let meta = TableMetaBuilder::empty()
1882            .schema(schema)
1883            .primary_key_indices(vec![0])
1884            .engine("engine")
1885            .next_column_id(3)
1886            .build()
1887            .unwrap();
1888        let alter_kind = AlterKind::SetJsonSettings {
1889            request: SetJsonSettingsRequest {
1890                column_name: "col2".to_string(),
1891                settings: JsonSettings::new_v2(),
1892            },
1893        };
1894
1895        let err = match meta.builder_with_alter_kind("my_table", &alter_kind) {
1896            Ok(_) => panic!("expected modifying JSON settings on a non-JSON2 column to fail"),
1897            Err(err) => err,
1898        };
1899        assert!(err.to_string().contains("is not a JSON2 column"));
1900    }
1901
1902    #[test]
1903    fn test_modify_time_index_column_type() {
1904        let schema = Arc::new(new_test_schema());
1905        let meta = TableMetaBuilder::empty()
1906            .schema(schema)
1907            .primary_key_indices(vec![0])
1908            .engine("engine")
1909            .next_column_id(3)
1910            .build()
1911            .unwrap();
1912
1913        // Widening the time index unit is allowed.
1914        let alter_kind = AlterKind::ModifyColumnTypes {
1915            columns: vec![ModifyColumnTypeRequest {
1916                column_name: "ts".to_string(),
1917                target_type: ConcreteDataType::timestamp_microsecond_datatype(),
1918            }],
1919        };
1920        let new_meta = meta
1921            .builder_with_alter_kind("my_table", &alter_kind)
1922            .unwrap()
1923            .build()
1924            .unwrap();
1925        let ts_column = new_meta.schema.column_schema_by_name("ts").unwrap();
1926        assert_eq!(
1927            ConcreteDataType::timestamp_microsecond_datatype(),
1928            ts_column.data_type
1929        );
1930        assert!(ts_column.is_time_index());
1931        assert!(!ts_column.is_nullable());
1932        assert_eq!(new_meta.schema.version(), 124);
1933        assert_eq!(&[0], &new_meta.primary_key_indices[..]);
1934
1935        // Any non-widening change (narrowing, same type, non-timestamp) is
1936        // rejected.
1937        for target in [
1938            ConcreteDataType::timestamp_second_datatype(),
1939            ConcreteDataType::timestamp_millisecond_datatype(),
1940            ConcreteDataType::string_datatype(),
1941        ] {
1942            let alter_kind = AlterKind::ModifyColumnTypes {
1943                columns: vec![ModifyColumnTypeRequest {
1944                    column_name: "ts".to_string(),
1945                    target_type: target.clone(),
1946                }],
1947            };
1948            let res = meta.builder_with_alter_kind("my_table", &alter_kind);
1949            assert!(res.is_err(), "expected rejection for {target}");
1950        }
1951    }
1952
1953    #[test]
1954    fn test_modify_partition_column_type() {
1955        // `col2` is nullable and not in the primary key, so only its partition role
1956        // decides whether the change is allowed.
1957        let alter_kind = AlterKind::ModifyColumnTypes {
1958            columns: vec![ModifyColumnTypeRequest {
1959                column_name: "col2".to_string(),
1960                target_type: ConcreteDataType::float64_datatype(),
1961            }],
1962        };
1963        for (partition_key_indices, allowed) in [(vec![], true), (vec![2], false)] {
1964            let meta = TableMetaBuilder::empty()
1965                .schema(Arc::new(new_test_schema()))
1966                .primary_key_indices(vec![0])
1967                .partition_key_indices(partition_key_indices)
1968                .engine("engine")
1969                .next_column_id(3)
1970                .build()
1971                .unwrap();
1972            let result = meta.builder_with_alter_kind("my_table", &alter_kind);
1973            assert_eq!(result.is_ok(), allowed);
1974        }
1975
1976        // Widening the unit of a time index that is also a partition column is allowed.
1977        let meta = TableMetaBuilder::empty()
1978            .schema(Arc::new(new_test_schema()))
1979            .primary_key_indices(vec![0])
1980            .partition_key_indices(vec![1])
1981            .engine("engine")
1982            .next_column_id(3)
1983            .build()
1984            .unwrap();
1985        let alter_kind = AlterKind::ModifyColumnTypes {
1986            columns: vec![ModifyColumnTypeRequest {
1987                column_name: "ts".to_string(),
1988                target_type: ConcreteDataType::timestamp_microsecond_datatype(),
1989            }],
1990        };
1991        assert!(
1992            meta.builder_with_alter_kind("my_table", &alter_kind)
1993                .is_ok()
1994        );
1995    }
1996
1997    #[test]
1998    fn test_add_columns() {
1999        let schema = Arc::new(new_test_schema());
2000        let meta = TableMetaBuilder::empty()
2001            .schema(schema)
2002            .primary_key_indices(vec![0])
2003            .engine("engine")
2004            .next_column_id(3)
2005            .build()
2006            .unwrap();
2007
2008        let new_meta = add_columns_to_meta(&meta);
2009        let names: Vec<String> = new_meta
2010            .schema
2011            .column_schemas()
2012            .iter()
2013            .map(|column_schema| column_schema.name.clone())
2014            .collect();
2015        assert_eq!(&["col1", "ts", "col2", "my_tag", "my_field"], &names[..]);
2016        assert_eq!(&[0, 3], &new_meta.primary_key_indices[..]);
2017        assert_eq!(&[1, 2, 4], &new_meta.value_indices[..]);
2018    }
2019
2020    #[test]
2021    fn test_add_columns_keeps_primary_key_order() {
2022        let schema = Arc::new(new_test_schema());
2023        // The key order differs from the column order, like `PRIMARY KEY(col2, col1)`.
2024        let meta = TableMetaBuilder::empty()
2025            .schema(schema)
2026            .primary_key_indices(vec![2, 0])
2027            .engine("engine")
2028            .next_column_id(3)
2029            .build()
2030            .unwrap();
2031
2032        let key_after_col1 = |name: &str| AddColumnRequest {
2033            column_schema: ColumnSchema::new(name, ConcreteDataType::string_datatype(), true),
2034            is_key: true,
2035            location: Some(AddColumnLocation::After {
2036                column_name: "col1".to_string(),
2037            }),
2038            add_if_not_exists: false,
2039        };
2040        let alter_kind = AlterKind::AddColumns {
2041            columns: vec![key_after_col1("k1"), key_after_col1("k2")],
2042        };
2043        let new_meta = meta
2044            .builder_with_alter_kind("my_table", &alter_kind)
2045            .unwrap()
2046            .build()
2047            .unwrap();
2048
2049        let names: Vec<_> = new_meta
2050            .schema
2051            .column_schemas()
2052            .iter()
2053            .map(|column_schema| column_schema.name.as_str())
2054            .collect();
2055        assert_eq!(&["col1", "k2", "k1", "ts", "col2"], &names[..]);
2056        // Regions append new tags in request order, not in column order: `col2, col1, k1, k2`.
2057        assert_eq!(&[4, 0, 2, 1], &new_meta.primary_key_indices[..]);
2058    }
2059
2060    #[test]
2061    fn test_set_append_mode_true_clears_merge_mode_option() {
2062        let schema = Arc::new(new_test_schema());
2063        let mut table_options = TableOptions::default();
2064        table_options
2065            .extra_options
2066            .insert(MERGE_MODE_KEY.to_string(), "last_non_null".to_string());
2067        let meta = TableMetaBuilder::empty()
2068            .schema(schema)
2069            .primary_key_indices(vec![0])
2070            .engine("engine")
2071            .next_column_id(3)
2072            .options(table_options)
2073            .build()
2074            .unwrap();
2075
2076        let alter_kind = AlterKind::SetTableOptions {
2077            options: vec![SetRegionOption::AppendMode(true)],
2078        };
2079        let new_meta = meta
2080            .builder_with_alter_kind("my_table", &alter_kind)
2081            .unwrap()
2082            .build()
2083            .unwrap();
2084
2085        assert_eq!(
2086            Some("true"),
2087            new_meta
2088                .options
2089                .extra_options
2090                .get(APPEND_MODE_KEY)
2091                .map(String::as_str)
2092        );
2093        assert!(!new_meta.options.extra_options.contains_key(MERGE_MODE_KEY));
2094    }
2095
2096    #[test]
2097    fn test_set_append_mode_false_keeps_merge_mode_option() {
2098        let schema = Arc::new(new_test_schema());
2099        let mut table_options = TableOptions::default();
2100        table_options
2101            .extra_options
2102            .insert(MERGE_MODE_KEY.to_string(), "last_non_null".to_string());
2103        let meta = TableMetaBuilder::empty()
2104            .schema(schema)
2105            .primary_key_indices(vec![0])
2106            .engine("engine")
2107            .next_column_id(3)
2108            .options(table_options)
2109            .build()
2110            .unwrap();
2111
2112        let alter_kind = AlterKind::SetTableOptions {
2113            options: vec![SetRegionOption::AppendMode(false)],
2114        };
2115        let new_meta = meta
2116            .builder_with_alter_kind("my_table", &alter_kind)
2117            .unwrap()
2118            .build()
2119            .unwrap();
2120
2121        assert_eq!(
2122            Some("false"),
2123            new_meta
2124                .options
2125                .extra_options
2126                .get(APPEND_MODE_KEY)
2127                .map(String::as_str)
2128        );
2129        assert_eq!(
2130            Some("last_non_null"),
2131            new_meta
2132                .options
2133                .extra_options
2134                .get(MERGE_MODE_KEY)
2135                .map(String::as_str)
2136        );
2137    }
2138
2139    #[test]
2140    fn test_set_preserve_row_sequence_option() {
2141        let schema = Arc::new(new_test_schema());
2142        let meta = TableMetaBuilder::empty()
2143            .schema(schema)
2144            .primary_key_indices(vec![0])
2145            .engine("engine")
2146            .next_column_id(3)
2147            .build()
2148            .unwrap();
2149
2150        let apply = |meta: &TableMeta, kind: &AlterKind| {
2151            meta.builder_with_alter_kind("my_table", kind)
2152                .unwrap()
2153                .build()
2154                .unwrap()
2155        };
2156
2157        let with_true = apply(
2158            &meta,
2159            &AlterKind::SetTableOptions {
2160                options: vec![SetRegionOption::PreserveRowSequence(true)],
2161            },
2162        );
2163        assert_eq!(
2164            Some("true"),
2165            with_true
2166                .options
2167                .extra_options
2168                .get(PRESERVE_ROW_SEQUENCE)
2169                .map(String::as_str)
2170        );
2171
2172        let set_false = apply(
2173            &with_true,
2174            &AlterKind::SetTableOptions {
2175                options: vec![SetRegionOption::PreserveRowSequence(false)],
2176            },
2177        );
2178        assert!(
2179            !set_false
2180                .options
2181                .extra_options
2182                .contains_key(PRESERVE_ROW_SEQUENCE)
2183        );
2184
2185        let unset = apply(
2186            &with_true,
2187            &AlterKind::UnsetTableOptions {
2188                keys: vec![UnsetRegionOption::PreserveRowSequence],
2189            },
2190        );
2191        assert!(
2192            !unset
2193                .options
2194                .extra_options
2195                .contains_key(PRESERVE_ROW_SEQUENCE)
2196        );
2197    }
2198
2199    #[test]
2200    fn test_set_skip_wal_updates_typed_and_extra_options() {
2201        let mut meta = TableMetaBuilder::empty()
2202            .schema(Arc::new(new_test_schema()))
2203            .primary_key_indices(vec![0])
2204            .engine("engine")
2205            .next_column_id(3)
2206            .build()
2207            .unwrap();
2208        meta.options
2209            .extra_options
2210            .insert(SKIP_WAL_KEY.to_string(), false.to_string());
2211
2212        let alter_kind = AlterKind::SetTableOptions {
2213            options: vec![SetRegionOption::SkipWal(true)],
2214        };
2215        let new_meta = meta
2216            .builder_with_alter_kind("my_table", &alter_kind)
2217            .unwrap()
2218            .build()
2219            .unwrap();
2220
2221        assert!(new_meta.options.skip_wal);
2222        assert_eq!(
2223            Some("true"),
2224            new_meta
2225                .options
2226                .extra_options
2227                .get(SKIP_WAL_KEY)
2228                .map(String::as_str)
2229        );
2230
2231        let alter_kind = AlterKind::SetTableOptions {
2232            options: vec![SetRegionOption::SkipWal(false)],
2233        };
2234        let new_meta = new_meta
2235            .builder_with_alter_kind("my_table", &alter_kind)
2236            .unwrap()
2237            .build()
2238            .unwrap();
2239
2240        assert!(!new_meta.options.skip_wal);
2241        assert_eq!(
2242            Some("false"),
2243            new_meta
2244                .options
2245                .extra_options
2246                .get(SKIP_WAL_KEY)
2247                .map(String::as_str)
2248        );
2249    }
2250
2251    #[test]
2252    fn test_set_unset_repartition_hints_together() {
2253        let meta = TableMetaBuilder::empty()
2254            .schema(Arc::new(new_test_schema()))
2255            .primary_key_indices(vec![0])
2256            .engine("engine")
2257            .next_column_id(3)
2258            .build()
2259            .unwrap();
2260        let options = vec![
2261            (REPARTITION_COLUMN_HINT_KEY.to_string(), "col1".to_string()),
2262            (
2263                REPARTITION_PARTITION_NUM_HINT_KEY.to_string(),
2264                "10".to_string(),
2265            ),
2266        ];
2267        for reverse in [false, true] {
2268            let mut options = options.clone();
2269            if reverse {
2270                options.reverse();
2271            }
2272            let updated = meta
2273                .builder_with_alter_kind(
2274                    "t",
2275                    &AlterKind::SetAnnotations {
2276                        family: AnnotationFamily::RepartitionHint,
2277                        options: options.clone(),
2278                    },
2279                )
2280                .unwrap()
2281                .build()
2282                .unwrap();
2283            assert_eq!(
2284                updated.options.extra_options,
2285                options.iter().cloned().collect()
2286            );
2287            for (key, value) in [
2288                (REPARTITION_COLUMN_HINT_KEY, "missing"),
2289                (REPARTITION_PARTITION_NUM_HINT_KEY, "0"),
2290            ] {
2291                let invalid = options
2292                    .iter()
2293                    .map(|(k, v)| {
2294                        (
2295                            k.clone(),
2296                            if k == key {
2297                                value.to_string()
2298                            } else {
2299                                v.clone()
2300                            },
2301                        )
2302                    })
2303                    .collect();
2304                assert!(
2305                    updated
2306                        .builder_with_alter_kind(
2307                            "t",
2308                            &AlterKind::SetAnnotations {
2309                                family: AnnotationFamily::RepartitionHint,
2310                                options: invalid,
2311                            }
2312                        )
2313                        .is_err()
2314                );
2315                assert_eq!(
2316                    updated.options.extra_options,
2317                    options.iter().cloned().collect()
2318                );
2319            }
2320            let cleared = updated
2321                .builder_with_alter_kind(
2322                    "t",
2323                    &AlterKind::UnsetAnnotations {
2324                        family: AnnotationFamily::RepartitionHint,
2325                        keys: options.into_iter().map(|(key, _)| key).collect(),
2326                    },
2327                )
2328                .unwrap()
2329                .build()
2330                .unwrap();
2331            assert!(cleared.options.extra_options.is_empty());
2332        }
2333    }
2334
2335    #[test]
2336    fn test_repartition_partition_num_hint() {
2337        for partition_key_indices in [vec![], vec![0]] {
2338            let mut meta = TableMetaBuilder::empty()
2339                .schema(Arc::new(new_test_schema()))
2340                .primary_key_indices(vec![0])
2341                .partition_key_indices(partition_key_indices)
2342                .engine("engine")
2343                .next_column_id(3)
2344                .build()
2345                .unwrap();
2346            for value in ["", " ", "0", "-1", "1.5", "abc", "4294967296"] {
2347                let err = meta
2348                    .builder_with_alter_kind(
2349                        "t",
2350                        &AlterKind::SetAnnotations {
2351                            family: AnnotationFamily::RepartitionHint,
2352                            options: vec![(
2353                                REPARTITION_PARTITION_NUM_HINT_KEY.to_string(),
2354                                value.to_string(),
2355                            )],
2356                        },
2357                    )
2358                    .err()
2359                    .unwrap();
2360                assert!(
2361                    err.to_string().contains("expects a positive integer"),
2362                    "{err}"
2363                );
2364            }
2365            for (value, expected) in [(" 8 ", "8"), ("1", "1"), ("4294967295", "4294967295")] {
2366                meta = meta
2367                    .builder_with_alter_kind(
2368                        "t",
2369                        &AlterKind::SetAnnotations {
2370                            family: AnnotationFamily::RepartitionHint,
2371                            options: vec![(
2372                                REPARTITION_PARTITION_NUM_HINT_KEY.to_string(),
2373                                value.to_string(),
2374                            )],
2375                        },
2376                    )
2377                    .unwrap()
2378                    .build()
2379                    .unwrap();
2380                assert_eq!(
2381                    meta.options.extra_options,
2382                    HashMap::from([(
2383                        REPARTITION_PARTITION_NUM_HINT_KEY.to_string(),
2384                        expected.to_string()
2385                    )])
2386                );
2387            }
2388            for _ in 0..2 {
2389                meta = meta
2390                    .builder_with_alter_kind(
2391                        "t",
2392                        &AlterKind::UnsetAnnotations {
2393                            family: AnnotationFamily::RepartitionHint,
2394                            keys: vec![REPARTITION_PARTITION_NUM_HINT_KEY.to_string()],
2395                        },
2396                    )
2397                    .unwrap()
2398                    .build()
2399                    .unwrap();
2400                assert!(meta.options.extra_options.is_empty());
2401            }
2402        }
2403    }
2404
2405    #[test]
2406    fn test_set_repartition_column_hint() {
2407        let meta = TableMetaBuilder::empty()
2408            .schema(Arc::new(new_test_schema()))
2409            .primary_key_indices(vec![0])
2410            .engine("engine")
2411            .next_column_id(3)
2412            .build()
2413            .unwrap();
2414
2415        let alter_kind = AlterKind::SetAnnotations {
2416            family: AnnotationFamily::RepartitionHint,
2417            options: vec![(
2418                REPARTITION_COLUMN_HINT_KEY.to_string(),
2419                " col1 ".to_string(),
2420            )],
2421        };
2422        let new_meta = meta
2423            .builder_with_alter_kind("my_table", &alter_kind)
2424            .unwrap()
2425            .build()
2426            .unwrap();
2427
2428        assert_eq!(
2429            Some("col1"),
2430            new_meta
2431                .options
2432                .extra_options
2433                .get(REPARTITION_COLUMN_HINT_KEY)
2434                .map(String::as_str)
2435        );
2436    }
2437
2438    #[test]
2439    fn test_set_repartition_column_hint_rejects_empty_column() {
2440        let meta = TableMetaBuilder::empty()
2441            .schema(Arc::new(new_test_schema()))
2442            .primary_key_indices(vec![0])
2443            .engine("engine")
2444            .next_column_id(3)
2445            .build()
2446            .unwrap();
2447
2448        let alter_kind = AlterKind::SetAnnotations {
2449            family: AnnotationFamily::RepartitionHint,
2450            options: vec![(REPARTITION_COLUMN_HINT_KEY.to_string(), " ".to_string())],
2451        };
2452        let err = meta
2453            .builder_with_alter_kind("my_table", &alter_kind)
2454            .err()
2455            .unwrap();
2456
2457        assert!(
2458            err.to_string()
2459                .contains("repartition.column.hint expects exactly one column name")
2460        );
2461    }
2462
2463    #[test]
2464    fn test_set_repartition_column_hint_rejects_multiple_columns() {
2465        let meta = TableMetaBuilder::empty()
2466            .schema(Arc::new(new_test_schema()))
2467            .primary_key_indices(vec![0])
2468            .engine("engine")
2469            .next_column_id(3)
2470            .build()
2471            .unwrap();
2472
2473        let alter_kind = AlterKind::SetAnnotations {
2474            family: AnnotationFamily::RepartitionHint,
2475            options: vec![(
2476                REPARTITION_COLUMN_HINT_KEY.to_string(),
2477                "col1,col2".to_string(),
2478            )],
2479        };
2480        let err = meta
2481            .builder_with_alter_kind("my_table", &alter_kind)
2482            .err()
2483            .unwrap();
2484
2485        assert!(
2486            err.to_string()
2487                .contains("repartition.column.hint expects exactly one column name")
2488        );
2489    }
2490
2491    #[test]
2492    fn test_set_repartition_column_hint_rejects_missing_column() {
2493        let meta = TableMetaBuilder::empty()
2494            .schema(Arc::new(new_test_schema()))
2495            .primary_key_indices(vec![0])
2496            .engine("engine")
2497            .next_column_id(3)
2498            .build()
2499            .unwrap();
2500
2501        let alter_kind = AlterKind::SetAnnotations {
2502            family: AnnotationFamily::RepartitionHint,
2503            options: vec![(
2504                REPARTITION_COLUMN_HINT_KEY.to_string(),
2505                "missing".to_string(),
2506            )],
2507        };
2508        let err = meta
2509            .builder_with_alter_kind("my_table", &alter_kind)
2510            .err()
2511            .unwrap();
2512
2513        assert!(err.to_string().contains("Column missing not exists"));
2514    }
2515
2516    #[test]
2517    fn test_set_repartition_column_hint_rejects_time_index_column() {
2518        let meta = TableMetaBuilder::empty()
2519            .schema(Arc::new(new_test_schema()))
2520            .primary_key_indices(vec![0])
2521            .engine("engine")
2522            .next_column_id(3)
2523            .build()
2524            .unwrap();
2525
2526        let alter_kind = AlterKind::SetAnnotations {
2527            family: AnnotationFamily::RepartitionHint,
2528            options: vec![(REPARTITION_COLUMN_HINT_KEY.to_string(), "ts".to_string())],
2529        };
2530        let err = meta
2531            .builder_with_alter_kind("my_table", &alter_kind)
2532            .err()
2533            .unwrap();
2534
2535        assert!(
2536            err.to_string()
2537                .contains("cannot set repartition.column.hint to the time index column")
2538        );
2539    }
2540
2541    #[test]
2542    fn test_set_repartition_column_hint_rejects_partitioned_table() {
2543        let meta = TableMetaBuilder::empty()
2544            .schema(Arc::new(new_test_schema()))
2545            .primary_key_indices(vec![0])
2546            .engine("engine")
2547            .next_column_id(3)
2548            .partition_key_indices(vec![0])
2549            .build()
2550            .unwrap();
2551
2552        let alter_kind = AlterKind::SetAnnotations {
2553            family: AnnotationFamily::RepartitionHint,
2554            options: vec![(REPARTITION_COLUMN_HINT_KEY.to_string(), "col1".to_string())],
2555        };
2556        let err = meta
2557            .builder_with_alter_kind("my_table", &alter_kind)
2558            .err()
2559            .unwrap();
2560
2561        assert!(
2562            err.to_string()
2563                .contains("cannot set repartition.column.hint on a table with partition metadata")
2564        );
2565    }
2566
2567    #[test]
2568    fn test_unset_repartition_column_hint() {
2569        let mut table_options = TableOptions::default();
2570        table_options
2571            .extra_options
2572            .insert(REPARTITION_COLUMN_HINT_KEY.to_string(), "col1".to_string());
2573        let meta = TableMetaBuilder::empty()
2574            .schema(Arc::new(new_test_schema()))
2575            .primary_key_indices(vec![0])
2576            .engine("engine")
2577            .next_column_id(3)
2578            .options(table_options)
2579            .build()
2580            .unwrap();
2581
2582        let new_meta = meta
2583            .builder_with_alter_kind(
2584                "my_table",
2585                &AlterKind::UnsetAnnotations {
2586                    family: AnnotationFamily::RepartitionHint,
2587                    keys: vec![REPARTITION_COLUMN_HINT_KEY.to_string()],
2588                },
2589            )
2590            .unwrap()
2591            .build()
2592            .unwrap();
2593
2594        assert!(
2595            !new_meta
2596                .options
2597                .extra_options
2598                .contains_key(REPARTITION_COLUMN_HINT_KEY)
2599        );
2600    }
2601
2602    #[test]
2603    fn test_repartition_hints_are_not_region_options() {
2604        let mut table_options = TableOptions::default();
2605        table_options
2606            .extra_options
2607            .insert(REPARTITION_COLUMN_HINT_KEY.to_string(), "col1".to_string());
2608        table_options.extra_options.insert(
2609            REPARTITION_PARTITION_NUM_HINT_KEY.to_string(),
2610            "8".to_string(),
2611        );
2612        let table_info = TableInfoBuilder::default()
2613            .table_id(1)
2614            .table_version(0)
2615            .name("my_table")
2616            .catalog_name(DEFAULT_CATALOG_NAME)
2617            .schema_name(DEFAULT_SCHEMA_NAME)
2618            .meta(
2619                TableMetaBuilder::empty()
2620                    .schema(Arc::new(new_test_schema()))
2621                    .primary_key_indices(vec![0])
2622                    .engine("engine")
2623                    .next_column_id(3)
2624                    .options(table_options)
2625                    .build()
2626                    .unwrap(),
2627            )
2628            .build()
2629            .unwrap();
2630
2631        assert!(
2632            !table_info
2633                .to_region_options()
2634                .contains_key(REPARTITION_PARTITION_NUM_HINT_KEY)
2635        );
2636        assert!(
2637            !table_info
2638                .to_region_options()
2639                .contains_key(REPARTITION_COLUMN_HINT_KEY)
2640        );
2641    }
2642
2643    #[test]
2644    fn test_compaction_output_parallelism_persistence_and_unset() {
2645        let mut meta = TableMetaBuilder::empty()
2646            .schema(Arc::new(new_test_schema()))
2647            .primary_key_indices(vec![0])
2648            .engine("mito")
2649            .next_column_id(3)
2650            .options(TableOptions::default())
2651            .build()
2652            .unwrap();
2653        for (kind, expected) in [
2654            (
2655                AlterKind::SetTableOptions {
2656                    options: vec![SetRegionOption::CompactionOutputParallelism(Some(4))],
2657                },
2658                Some("4"),
2659            ),
2660            (
2661                AlterKind::SetTableOptions {
2662                    options: vec![SetRegionOption::CompactionOutputParallelism(Some(1))],
2663                },
2664                Some("1"),
2665            ),
2666            (
2667                AlterKind::UnsetTableOptions {
2668                    keys: vec![UnsetRegionOption::CompactionOutputParallelism],
2669                },
2670                None,
2671            ),
2672        ] {
2673            meta = meta
2674                .builder_with_alter_kind("my_table", &kind)
2675                .unwrap()
2676                .build()
2677                .unwrap();
2678            // Restart uses the persisted table options to reopen regions.
2679            let json = serde_json::to_string(&meta.options).unwrap();
2680            let restored: TableOptions = serde_json::from_str(&json).unwrap();
2681            assert_eq!(
2682                expected,
2683                restored
2684                    .extra_options
2685                    .get(COMPACTION_EXPERIMENTAL_OUTPUT_PARALLELISM)
2686                    .map(String::as_str)
2687            );
2688            assert!(!restored.extra_options.contains_key(COMPACTION_TYPE));
2689        }
2690    }
2691
2692    #[test]
2693    fn test_set_auto_flush_interval() {
2694        let schema = Arc::new(new_test_schema());
2695        let table_options = TableOptions::default();
2696        let meta = TableMetaBuilder::empty()
2697            .schema(schema)
2698            .primary_key_indices(vec![0])
2699            .engine("engine")
2700            .next_column_id(3)
2701            .options(table_options)
2702            .build()
2703            .unwrap();
2704
2705        let alter_kind = AlterKind::SetTableOptions {
2706            options: vec![SetRegionOption::AutoFlushInterval(Some(
2707                std::time::Duration::from_secs(300),
2708            ))],
2709        };
2710        let new_meta = meta
2711            .builder_with_alter_kind("my_table", &alter_kind)
2712            .unwrap()
2713            .build()
2714            .unwrap();
2715
2716        assert_eq!(
2717            Some("5m"),
2718            new_meta
2719                .options
2720                .extra_options
2721                .get(AUTO_FLUSH_INTERVAL_KEY)
2722                .map(String::as_str)
2723        );
2724    }
2725
2726    #[test]
2727    fn test_set_auto_flush_interval_none_removes_existing() {
2728        let schema = Arc::new(new_test_schema());
2729        let mut table_options = TableOptions::default();
2730        table_options
2731            .extra_options
2732            .insert(AUTO_FLUSH_INTERVAL_KEY.to_string(), "5m".to_string());
2733        let meta = TableMetaBuilder::empty()
2734            .schema(schema)
2735            .primary_key_indices(vec![0])
2736            .engine("engine")
2737            .next_column_id(3)
2738            .options(table_options)
2739            .build()
2740            .unwrap();
2741
2742        let alter_kind = AlterKind::SetTableOptions {
2743            options: vec![SetRegionOption::AutoFlushInterval(None)],
2744        };
2745        let new_meta = meta
2746            .builder_with_alter_kind("my_table", &alter_kind)
2747            .unwrap()
2748            .build()
2749            .unwrap();
2750
2751        assert!(
2752            !new_meta
2753                .options
2754                .extra_options
2755                .contains_key(AUTO_FLUSH_INTERVAL_KEY)
2756        );
2757    }
2758
2759    #[test]
2760    fn test_set_twcs_trigger_persists_legacy_key() {
2761        for key in [TWCS_TRIGGER_FILE_NUM, TWCS_ACTIVE_WINDOW_TRIGGER_FILE_NUM] {
2762            let mut table_options = TableOptions::default();
2763            table_options.extra_options.insert(
2764                TWCS_ACTIVE_WINDOW_TRIGGER_FILE_NUM.to_string(),
2765                "4".to_string(),
2766            );
2767            let meta = TableMetaBuilder::empty()
2768                .schema(Arc::new(new_test_schema()))
2769                .primary_key_indices(vec![0])
2770                .engine("engine")
2771                .next_column_id(3)
2772                .options(table_options)
2773                .build()
2774                .unwrap();
2775            let alter_kind = AlterKind::SetTableOptions {
2776                options: vec![SetRegionOption::Twsc(key.to_string(), "8".to_string())],
2777            };
2778
2779            let new_meta = meta
2780                .builder_with_alter_kind("my_table", &alter_kind)
2781                .unwrap()
2782                .build()
2783                .unwrap();
2784
2785            assert_eq!(
2786                Some("8"),
2787                new_meta
2788                    .options
2789                    .extra_options
2790                    .get(TWCS_TRIGGER_FILE_NUM)
2791                    .map(String::as_str)
2792            );
2793            assert!(
2794                !new_meta
2795                    .options
2796                    .extra_options
2797                    .contains_key(TWCS_ACTIVE_WINDOW_TRIGGER_FILE_NUM)
2798            );
2799        }
2800    }
2801
2802    #[test]
2803    fn test_set_and_unset_max_row_group_row_count() {
2804        let meta = TableMetaBuilder::empty()
2805            .schema(Arc::new(new_test_schema()))
2806            .primary_key_indices(vec![0])
2807            .engine("engine")
2808            .next_column_id(3)
2809            .options(TableOptions::default())
2810            .build()
2811            .unwrap();
2812
2813        let alter_kind = AlterKind::SetTableOptions {
2814            options: vec![SetRegionOption::MaxRowGroupRowCount(Some(512))],
2815        };
2816        let new_meta = meta
2817            .builder_with_alter_kind("my_table", &alter_kind)
2818            .unwrap()
2819            .build()
2820            .unwrap();
2821        assert_eq!(
2822            Some("512"),
2823            new_meta
2824                .options
2825                .extra_options
2826                .get(MAX_ROW_GROUP_ROW_COUNT)
2827                .map(String::as_str)
2828        );
2829
2830        let alter_kind = AlterKind::UnsetTableOptions {
2831            keys: vec![UnsetRegionOption::MaxRowGroupRowCount],
2832        };
2833        let new_meta = new_meta
2834            .builder_with_alter_kind("my_table", &alter_kind)
2835            .unwrap()
2836            .build()
2837            .unwrap();
2838        assert!(
2839            !new_meta
2840                .options
2841                .extra_options
2842                .contains_key(MAX_ROW_GROUP_ROW_COUNT)
2843        );
2844    }
2845
2846    #[test]
2847    fn test_add_columns_multiple_times() {
2848        let schema = Arc::new(new_test_schema());
2849        let meta = TableMetaBuilder::empty()
2850            .schema(schema)
2851            .primary_key_indices(vec![0])
2852            .engine("engine")
2853            .next_column_id(3)
2854            .build()
2855            .unwrap();
2856
2857        let alter_kind = AlterKind::AddColumns {
2858            columns: vec![
2859                AddColumnRequest {
2860                    column_schema: ColumnSchema::new(
2861                        "col3",
2862                        ConcreteDataType::int32_datatype(),
2863                        true,
2864                    ),
2865                    is_key: true,
2866                    location: None,
2867                    add_if_not_exists: true,
2868                },
2869                AddColumnRequest {
2870                    column_schema: ColumnSchema::new(
2871                        "col3",
2872                        ConcreteDataType::int32_datatype(),
2873                        true,
2874                    ),
2875                    is_key: true,
2876                    location: None,
2877                    add_if_not_exists: true,
2878                },
2879            ],
2880        };
2881        let err = meta
2882            .builder_with_alter_kind("my_table", &alter_kind)
2883            .err()
2884            .unwrap();
2885        assert_eq!(StatusCode::InvalidArguments, err.status_code());
2886    }
2887
2888    #[test]
2889    fn test_remove_columns() {
2890        let schema = Arc::new(new_test_schema());
2891        let meta = TableMetaBuilder::empty()
2892            .schema(schema.clone())
2893            .primary_key_indices(vec![0])
2894            .engine("engine")
2895            .next_column_id(3)
2896            .build()
2897            .unwrap();
2898        // Add more columns so we have enough candidate columns to remove.
2899        let meta = add_columns_to_meta(&meta);
2900
2901        let alter_kind = AlterKind::DropColumns {
2902            names: vec![String::from("col2"), String::from("my_field")],
2903        };
2904        let new_meta = meta
2905            .builder_with_alter_kind("my_table", &alter_kind)
2906            .unwrap()
2907            .build()
2908            .unwrap();
2909
2910        let names: Vec<String> = new_meta
2911            .schema
2912            .column_schemas()
2913            .iter()
2914            .map(|column_schema| column_schema.name.clone())
2915            .collect();
2916        assert_eq!(&["col1", "ts", "my_tag"], &names[..]);
2917        assert_eq!(&[0, 2], &new_meta.primary_key_indices[..]);
2918        assert_eq!(&[1], &new_meta.value_indices[..]);
2919        assert_eq!(
2920            schema.timestamp_column(),
2921            new_meta.schema.timestamp_column()
2922        );
2923    }
2924
2925    #[test]
2926    fn test_remove_multiple_columns_before_timestamp() {
2927        let column_schemas = vec![
2928            ColumnSchema::new("col1", ConcreteDataType::int32_datatype(), true),
2929            ColumnSchema::new("col2", ConcreteDataType::int32_datatype(), true),
2930            ColumnSchema::new("col3", ConcreteDataType::int32_datatype(), true),
2931            ColumnSchema::new(
2932                "ts",
2933                ConcreteDataType::timestamp_millisecond_datatype(),
2934                false,
2935            )
2936            .with_time_index(true),
2937        ];
2938        let schema = Arc::new(
2939            SchemaBuilder::try_from(column_schemas)
2940                .unwrap()
2941                .version(123)
2942                .build()
2943                .unwrap(),
2944        );
2945        let meta = TableMetaBuilder::empty()
2946            .schema(schema.clone())
2947            .primary_key_indices(vec![1])
2948            .engine("engine")
2949            .next_column_id(4)
2950            .build()
2951            .unwrap();
2952
2953        // Remove columns in reverse order to test whether timestamp index is valid.
2954        let alter_kind = AlterKind::DropColumns {
2955            names: vec![String::from("col3"), String::from("col1")],
2956        };
2957        let new_meta = meta
2958            .builder_with_alter_kind("my_table", &alter_kind)
2959            .unwrap()
2960            .build()
2961            .unwrap();
2962
2963        let names: Vec<String> = new_meta
2964            .schema
2965            .column_schemas()
2966            .iter()
2967            .map(|column_schema| column_schema.name.clone())
2968            .collect();
2969        assert_eq!(&["col2", "ts"], &names[..]);
2970        assert_eq!(&[0], &new_meta.primary_key_indices[..]);
2971        assert_eq!(&[1], &new_meta.value_indices[..]);
2972        assert_eq!(
2973            schema.timestamp_column(),
2974            new_meta.schema.timestamp_column()
2975        );
2976    }
2977
2978    #[test]
2979    fn test_add_existing_column() {
2980        let schema = Arc::new(new_test_schema());
2981        let meta = TableMetaBuilder::empty()
2982            .schema(schema)
2983            .primary_key_indices(vec![0])
2984            .engine("engine")
2985            .next_column_id(3)
2986            .build()
2987            .unwrap();
2988
2989        let alter_kind = AlterKind::AddColumns {
2990            columns: vec![AddColumnRequest {
2991                column_schema: ColumnSchema::new("col1", ConcreteDataType::string_datatype(), true),
2992                is_key: false,
2993                location: None,
2994                add_if_not_exists: false,
2995            }],
2996        };
2997
2998        let err = meta
2999            .builder_with_alter_kind("my_table", &alter_kind)
3000            .err()
3001            .unwrap();
3002        assert_eq!(StatusCode::TableColumnExists, err.status_code());
3003
3004        // Add if not exists
3005        let alter_kind = AlterKind::AddColumns {
3006            columns: vec![AddColumnRequest {
3007                column_schema: ColumnSchema::new("col1", ConcreteDataType::int32_datatype(), true),
3008                is_key: true,
3009                location: None,
3010                add_if_not_exists: true,
3011            }],
3012        };
3013        let new_meta = meta
3014            .builder_with_alter_kind("my_table", &alter_kind)
3015            .unwrap()
3016            .build()
3017            .unwrap();
3018        assert_eq!(
3019            meta.schema.column_schemas(),
3020            new_meta.schema.column_schemas()
3021        );
3022        assert_eq!(meta.schema.version() + 1, new_meta.schema.version());
3023    }
3024
3025    #[test]
3026    fn test_add_different_type_column() {
3027        let schema = Arc::new(new_test_schema());
3028        let meta = TableMetaBuilder::empty()
3029            .schema(schema)
3030            .primary_key_indices(vec![0])
3031            .engine("engine")
3032            .next_column_id(3)
3033            .build()
3034            .unwrap();
3035
3036        // Add if not exists, but different type.
3037        let alter_kind = AlterKind::AddColumns {
3038            columns: vec![AddColumnRequest {
3039                column_schema: ColumnSchema::new("col1", ConcreteDataType::string_datatype(), true),
3040                is_key: false,
3041                location: None,
3042                add_if_not_exists: true,
3043            }],
3044        };
3045        let err = meta
3046            .builder_with_alter_kind("my_table", &alter_kind)
3047            .err()
3048            .unwrap();
3049        assert_eq!(StatusCode::InvalidArguments, err.status_code());
3050    }
3051
3052    #[test]
3053    fn test_add_invalid_column() {
3054        let schema = Arc::new(new_test_schema());
3055        let meta = TableMetaBuilder::empty()
3056            .schema(schema)
3057            .primary_key_indices(vec![0])
3058            .engine("engine")
3059            .next_column_id(3)
3060            .build()
3061            .unwrap();
3062
3063        // Not nullable and no default value.
3064        let alter_kind = AlterKind::AddColumns {
3065            columns: vec![AddColumnRequest {
3066                column_schema: ColumnSchema::new(
3067                    "weny",
3068                    ConcreteDataType::string_datatype(),
3069                    false,
3070                ),
3071                is_key: false,
3072                location: None,
3073                add_if_not_exists: false,
3074            }],
3075        };
3076
3077        let err = meta
3078            .builder_with_alter_kind("my_table", &alter_kind)
3079            .err()
3080            .unwrap();
3081        assert_eq!(StatusCode::InvalidArguments, err.status_code());
3082    }
3083
3084    #[test]
3085    fn test_remove_unknown_column() {
3086        let schema = Arc::new(new_test_schema());
3087        let meta = TableMetaBuilder::empty()
3088            .schema(schema)
3089            .primary_key_indices(vec![0])
3090            .engine("engine")
3091            .next_column_id(3)
3092            .build()
3093            .unwrap();
3094
3095        let alter_kind = AlterKind::DropColumns {
3096            names: vec![String::from("unknown")],
3097        };
3098
3099        let err = meta
3100            .builder_with_alter_kind("my_table", &alter_kind)
3101            .err()
3102            .unwrap();
3103        assert_eq!(StatusCode::TableColumnNotFound, err.status_code());
3104    }
3105
3106    #[test]
3107    fn test_change_unknown_column_data_type() {
3108        let schema = Arc::new(new_test_schema());
3109        let meta = TableMetaBuilder::empty()
3110            .schema(schema)
3111            .primary_key_indices(vec![0])
3112            .engine("engine")
3113            .next_column_id(3)
3114            .build()
3115            .unwrap();
3116
3117        let alter_kind = AlterKind::ModifyColumnTypes {
3118            columns: vec![ModifyColumnTypeRequest {
3119                column_name: "unknown".to_string(),
3120                target_type: ConcreteDataType::string_datatype(),
3121            }],
3122        };
3123
3124        let err = meta
3125            .builder_with_alter_kind("my_table", &alter_kind)
3126            .err()
3127            .unwrap();
3128        assert_eq!(StatusCode::TableColumnNotFound, err.status_code());
3129    }
3130
3131    #[test]
3132    fn test_remove_key_column() {
3133        let schema = Arc::new(new_test_schema());
3134        let meta = TableMetaBuilder::empty()
3135            .schema(schema)
3136            .primary_key_indices(vec![0])
3137            .engine("engine")
3138            .next_column_id(3)
3139            .build()
3140            .unwrap();
3141
3142        // Remove column in primary key.
3143        let alter_kind = AlterKind::DropColumns {
3144            names: vec![String::from("col1")],
3145        };
3146
3147        let err = meta
3148            .builder_with_alter_kind("my_table", &alter_kind)
3149            .err()
3150            .unwrap();
3151        assert_eq!(StatusCode::InvalidArguments, err.status_code());
3152
3153        // Remove timestamp column.
3154        let alter_kind = AlterKind::DropColumns {
3155            names: vec![String::from("ts")],
3156        };
3157
3158        let err = meta
3159            .builder_with_alter_kind("my_table", &alter_kind)
3160            .err()
3161            .unwrap();
3162        assert_eq!(StatusCode::InvalidArguments, err.status_code());
3163    }
3164
3165    #[test]
3166    fn test_remove_partition_column() {
3167        let schema = Arc::new(new_test_schema());
3168        let meta = TableMetaBuilder::empty()
3169            .schema(schema)
3170            .primary_key_indices(vec![])
3171            .partition_key_indices(vec![0])
3172            .engine("engine")
3173            .next_column_id(3)
3174            .build()
3175            .unwrap();
3176        // Remove column in primary key.
3177        let alter_kind = AlterKind::DropColumns {
3178            names: vec![String::from("col1")],
3179        };
3180
3181        let err = meta
3182            .builder_with_alter_kind("my_table", &alter_kind)
3183            .err()
3184            .unwrap();
3185        assert_matches!(err, Error::RemovePartitionColumn { .. });
3186    }
3187
3188    #[test]
3189    fn test_change_key_column_data_type() {
3190        let schema = Arc::new(new_test_schema());
3191        let meta = TableMetaBuilder::empty()
3192            .schema(schema)
3193            .primary_key_indices(vec![0])
3194            .engine("engine")
3195            .next_column_id(3)
3196            .build()
3197            .unwrap();
3198
3199        // Remove column in primary key.
3200        let alter_kind = AlterKind::ModifyColumnTypes {
3201            columns: vec![ModifyColumnTypeRequest {
3202                column_name: "col1".to_string(),
3203                target_type: ConcreteDataType::string_datatype(),
3204            }],
3205        };
3206
3207        let err = meta
3208            .builder_with_alter_kind("my_table", &alter_kind)
3209            .err()
3210            .unwrap();
3211        assert_eq!(StatusCode::InvalidArguments, err.status_code());
3212
3213        // Remove timestamp column.
3214        let alter_kind = AlterKind::ModifyColumnTypes {
3215            columns: vec![ModifyColumnTypeRequest {
3216                column_name: "ts".to_string(),
3217                target_type: ConcreteDataType::string_datatype(),
3218            }],
3219        };
3220
3221        let err = meta
3222            .builder_with_alter_kind("my_table", &alter_kind)
3223            .err()
3224            .unwrap();
3225        assert_eq!(StatusCode::InvalidArguments, err.status_code());
3226    }
3227
3228    #[test]
3229    fn test_alloc_new_column() {
3230        let schema = Arc::new(new_test_schema());
3231        let mut meta = TableMetaBuilder::empty()
3232            .schema(schema)
3233            .primary_key_indices(vec![0])
3234            .engine("engine")
3235            .next_column_id(3)
3236            .build()
3237            .unwrap();
3238        assert_eq!(3, meta.next_column_id);
3239
3240        let column_schema = ColumnSchema::new("col1", ConcreteDataType::int32_datatype(), true);
3241        let desc = meta.alloc_new_column("test_table", &column_schema).unwrap();
3242
3243        assert_eq!(4, meta.next_column_id);
3244        assert_eq!(column_schema.name, desc.name);
3245    }
3246
3247    #[test]
3248    fn test_add_columns_with_location() {
3249        let schema = Arc::new(new_test_schema());
3250        let meta = TableMetaBuilder::empty()
3251            .schema(schema)
3252            .primary_key_indices(vec![0])
3253            // partition col: col1, col2
3254            .partition_key_indices(vec![0, 2])
3255            .engine("engine")
3256            .next_column_id(3)
3257            .build()
3258            .unwrap();
3259
3260        let new_meta = add_columns_to_meta_with_location(&meta);
3261        let names: Vec<String> = new_meta
3262            .schema
3263            .column_schemas()
3264            .iter()
3265            .map(|column_schema| column_schema.name.clone())
3266            .collect();
3267        assert_eq!(
3268            &[
3269                "my_tag_first",               // primary key column
3270                "col1",                       // partition column
3271                "ts",                         // timestamp column
3272                "yet_another_field_after_ts", // primary key column
3273                "my_field_after_ts",          // value column
3274                "col2",                       // partition column
3275            ],
3276            &names[..]
3277        );
3278        // New key columns follow the existing key `col1` in request order, whatever their location.
3279        assert_eq!(&[1, 0, 3], &new_meta.primary_key_indices[..]);
3280        assert_eq!(&[2, 4, 5], &new_meta.value_indices[..]);
3281        assert_eq!(&[1, 5], &new_meta.partition_key_indices[..]);
3282    }
3283
3284    #[test]
3285    fn test_modify_column_fulltext_options() {
3286        let schema = Arc::new(new_test_schema());
3287        let meta = TableMetaBuilder::empty()
3288            .schema(schema)
3289            .primary_key_indices(vec![0])
3290            .engine("engine")
3291            .next_column_id(3)
3292            .build()
3293            .unwrap();
3294
3295        let alter_kind = AlterKind::SetIndexes {
3296            options: vec![SetIndexOption::Fulltext {
3297                column_name: "col1".to_string(),
3298                options: FulltextOptions::default(),
3299            }],
3300        };
3301        let err = meta
3302            .builder_with_alter_kind("my_table", &alter_kind)
3303            .err()
3304            .unwrap();
3305        assert_eq!(
3306            "Invalid column option, column name: col1, error: FULLTEXT index only supports string type",
3307            err.to_string()
3308        );
3309
3310        // Add a string column and make it fulltext indexed
3311        let new_meta = add_columns_to_meta_with_location(&meta);
3312        let alter_kind = AlterKind::SetIndexes {
3313            options: vec![SetIndexOption::Fulltext {
3314                column_name: "my_tag_first".to_string(),
3315                options: FulltextOptions::new_unchecked(
3316                    true,
3317                    FulltextAnalyzer::Chinese,
3318                    true,
3319                    FulltextBackend::Bloom,
3320                    1000,
3321                    0.01,
3322                ),
3323            }],
3324        };
3325        let new_meta = new_meta
3326            .builder_with_alter_kind("my_table", &alter_kind)
3327            .unwrap()
3328            .build()
3329            .unwrap();
3330        let column_schema = new_meta
3331            .schema
3332            .column_schema_by_name("my_tag_first")
3333            .unwrap();
3334        let fulltext_options = column_schema.fulltext_options().unwrap().unwrap();
3335        assert!(fulltext_options.enable);
3336        assert_eq!(
3337            datatypes::schema::FulltextAnalyzer::Chinese,
3338            fulltext_options.analyzer
3339        );
3340        assert!(fulltext_options.case_sensitive);
3341
3342        let alter_kind = AlterKind::UnsetIndexes {
3343            options: vec![UnsetIndexOption::Fulltext {
3344                column_name: "my_tag_first".to_string(),
3345            }],
3346        };
3347        let new_meta = new_meta
3348            .builder_with_alter_kind("my_table", &alter_kind)
3349            .unwrap()
3350            .build()
3351            .unwrap();
3352        let column_schema = new_meta
3353            .schema
3354            .column_schema_by_name("my_tag_first")
3355            .unwrap();
3356        let fulltext_options = column_schema.fulltext_options().unwrap().unwrap();
3357        assert!(!fulltext_options.enable);
3358    }
3359
3360    #[test]
3361    fn test_table_info_serde_compatibility() {
3362        // "serialized" is generated by the following codes before this refactor (PR 7626):
3363        //
3364        // ```Rust
3365        // serde_json::to_string(&RawTableInfo::from(TableInfo {
3366        //     ident: TableIdent {
3367        //         table_id: 1024,
3368        //         version: 1,
3369        //     },
3370        //     name: "foo".to_string(),
3371        //     desc: Some("my table".to_string()),
3372        //     catalog_name: "greptime".to_string(),
3373        //     schema_name: "public".to_string(),
3374        //     meta: TableMeta {
3375        //         schema: Arc::new(new_test_schema()),
3376        //         primary_key_indices: vec![0],
3377        //         value_indices: vec![1, 2],
3378        //         engine: "mito".to_string(),
3379        //         next_column_id: 3,
3380        //         options: TableOptions {
3381        //             ttl: Some(common_time::TimeToLive::Duration(
3382        //                 std::time::Duration::from_secs(3600),
3383        //             )),
3384        //             ..Default::default()
3385        //         },
3386        //         created_on: DateTime::<Utc>::MIN_UTC,
3387        //         updated_on: DateTime::<Utc>::MAX_UTC,
3388        //         partition_key_indices: vec![2],
3389        //         column_ids: vec![0, 1, 2],
3390        //     },
3391        //     table_type: TableType::Base,
3392        // }))
3393        // ```
3394        let serialized = r#"{"ident":{"table_id":1024,"version":1},"name":"foo","desc":"my table","catalog_name":"greptime","schema_name":"public","meta":{"schema":{"column_schemas":[{"name":"col1","data_type":{"Int32":{}},"is_nullable":true,"is_time_index":false,"default_constraint":null,"metadata":{}},{"name":"ts","data_type":{"Timestamp":{"Millisecond":null}},"is_nullable":false,"is_time_index":true,"default_constraint":null,"metadata":{"greptime:time_index":"true"}},{"name":"col2","data_type":{"Int32":{}},"is_nullable":true,"is_time_index":false,"default_constraint":null,"metadata":{}}],"timestamp_index":1,"version":123},"primary_key_indices":[0],"value_indices":[1,2],"engine":"mito","next_column_id":3,"options":{"write_buffer_size":null,"ttl":"1h","skip_wal":false,"extra_options":{}},"created_on":"-262143-01-01T00:00:00Z","updated_on":"+262142-12-31T23:59:59.999999999Z","partition_key_indices":[2],"column_ids":[0,1,2]},"table_type":"Base"}"#;
3395
3396        let actual: TableInfo = serde_json::from_str(serialized).unwrap();
3397        let expected = TableInfo {
3398            ident: TableIdent {
3399                table_id: 1024,
3400                version: 1,
3401            },
3402            name: "foo".to_string(),
3403            desc: Some("my table".to_string()),
3404            catalog_name: "greptime".to_string(),
3405            schema_name: "public".to_string(),
3406            meta: TableMeta {
3407                schema: Arc::new(new_test_schema()),
3408                primary_key_indices: vec![0],
3409                value_indices: vec![1, 2],
3410                engine: "mito".to_string(),
3411                next_column_id: 3,
3412                options: TableOptions {
3413                    ttl: Some(common_time::TimeToLive::Duration(
3414                        std::time::Duration::from_secs(3600),
3415                    )),
3416                    ..Default::default()
3417                },
3418                created_on: DateTime::<Utc>::MIN_UTC,
3419                updated_on: DateTime::<Utc>::MAX_UTC,
3420                partition_key_indices: vec![2],
3421                column_ids: vec![0, 1, 2],
3422            },
3423            table_type: TableType::Base,
3424        };
3425        assert_eq!(actual, expected);
3426    }
3427
3428    use crate::requests::{SEMANTIC_METRIC_UNIT, SEMANTIC_SIGNAL_TYPE};
3429
3430    /// `host` is a tag, `service` and `note` are string fields, `payload` is a
3431    /// binary field.
3432    fn semantic_test_meta() -> TableMeta {
3433        let column_schemas = vec![
3434            ColumnSchema::new("host", ConcreteDataType::string_datatype(), true),
3435            ColumnSchema::new(
3436                "ts",
3437                ConcreteDataType::timestamp_millisecond_datatype(),
3438                false,
3439            )
3440            .with_time_index(true),
3441            ColumnSchema::new("payload", ConcreteDataType::binary_datatype(), true),
3442            ColumnSchema::new("service", ConcreteDataType::string_datatype(), true),
3443            ColumnSchema::new("note", ConcreteDataType::string_datatype(), true),
3444        ];
3445        let schema = Arc::new(
3446            SchemaBuilder::try_from(column_schemas)
3447                .unwrap()
3448                .build()
3449                .unwrap(),
3450        );
3451        TableMetaBuilder::empty()
3452            .schema(schema)
3453            .primary_key_indices(vec![0])
3454            .engine("engine")
3455            .next_column_id(5)
3456            .build()
3457            .unwrap()
3458    }
3459
3460    #[test]
3461    fn test_set_semantic_annotations() {
3462        let meta = semantic_test_meta();
3463        // `service` is a plain field: entity columns may be tags or fields.
3464        let alter_kind = AlterKind::SetAnnotations {
3465            family: AnnotationFamily::Semantic,
3466            options: vec![
3467                (SEMANTIC_SIGNAL_TYPE.to_string(), "trace".to_string()),
3468                (
3469                    "greptime.semantic.entity.service.id".to_string(),
3470                    "service".to_string(),
3471                ),
3472            ],
3473        };
3474        let new_meta = meta
3475            .builder_with_alter_kind("my_table", &alter_kind)
3476            .unwrap()
3477            .build()
3478            .unwrap();
3479        assert_eq!(
3480            new_meta.options.extra_options.get(SEMANTIC_SIGNAL_TYPE),
3481            Some(&"trace".to_string())
3482        );
3483        assert_eq!(
3484            new_meta
3485                .options
3486                .extra_options
3487                .get("greptime.semantic.entity.service.id"),
3488            Some(&"service".to_string())
3489        );
3490    }
3491
3492    #[test]
3493    fn test_repartition_hint_batch_rejects_duplicate_keys() {
3494        let meta = TableMetaBuilder::empty()
3495            .schema(Arc::new(new_test_schema()))
3496            .primary_key_indices(vec![0])
3497            .engine("engine")
3498            .next_column_id(3)
3499            .build()
3500            .unwrap();
3501
3502        // Direct gRPC can hand the mutation layer a duplicated batch the
3503        // converter never saw; last-write-wins must not silently apply.
3504        let dup_set = AlterKind::SetAnnotations {
3505            family: AnnotationFamily::RepartitionHint,
3506            options: vec![
3507                (REPARTITION_COLUMN_HINT_KEY.to_string(), "col1".to_string()),
3508                (REPARTITION_COLUMN_HINT_KEY.to_string(), "col2".to_string()),
3509            ],
3510        };
3511        let err = meta
3512            .builder_with_alter_kind("my_table", &dup_set)
3513            .err()
3514            .unwrap();
3515        assert!(
3516            err.to_string().contains("duplicate repartition hint keys"),
3517            "{err}"
3518        );
3519
3520        let dup_unset = AlterKind::UnsetAnnotations {
3521            family: AnnotationFamily::RepartitionHint,
3522            keys: vec![
3523                REPARTITION_COLUMN_HINT_KEY.to_string(),
3524                REPARTITION_COLUMN_HINT_KEY.to_string(),
3525            ],
3526        };
3527        let err = meta
3528            .builder_with_alter_kind("my_table", &dup_unset)
3529            .err()
3530            .unwrap();
3531        assert!(
3532            err.to_string().contains("duplicate repartition hint keys"),
3533            "{err}"
3534        );
3535    }
3536
3537    #[test]
3538    fn test_set_semantic_annotations_rejects_invalid() {
3539        let meta = semantic_test_meta();
3540        let cases = [
3541            (
3542                "greptime.semantic.unknown_key",
3543                "x",
3544                "unknown semantic option",
3545            ),
3546            (SEMANTIC_SIGNAL_TYPE, "garbage", "invalid value"),
3547            (
3548                "greptime.semantic.entity.host.id",
3549                "no_such_column",
3550                "no_such_column",
3551            ),
3552            (
3553                "greptime.semantic.entity.host.id",
3554                "payload",
3555                "cannot render as a string",
3556            ),
3557        ];
3558        for (key, value, needle) in cases {
3559            let alter_kind = AlterKind::SetAnnotations {
3560                family: AnnotationFamily::Semantic,
3561                options: vec![(key.to_string(), value.to_string())],
3562            };
3563            let err = meta
3564                .builder_with_alter_kind("my_table", &alter_kind)
3565                .err()
3566                .unwrap();
3567            assert!(
3568                err.to_string().contains(needle),
3569                "key `{key}`: unexpected error `{err}`"
3570            );
3571        }
3572
3573        // ALTER keeps missing columns on the 4002 contract (pinned by sqlness);
3574        // the shared validator must not collapse it into InvalidArguments.
3575        let missing = meta
3576            .builder_with_alter_kind(
3577                "my_table",
3578                &AlterKind::SetAnnotations {
3579                    family: AnnotationFamily::Semantic,
3580                    options: vec![(
3581                        "greptime.semantic.entity.host.id".to_string(),
3582                        "no_such_column".to_string(),
3583                    )],
3584                },
3585            )
3586            .err()
3587            .unwrap();
3588        assert_eq!(
3589            common_error::status_code::StatusCode::TableColumnNotFound,
3590            common_error::ext::ErrorExt::status_code(&missing)
3591        );
3592    }
3593
3594    #[test]
3595    fn test_unset_semantic_annotations() {
3596        let mut meta = semantic_test_meta();
3597        meta.options
3598            .extra_options
3599            .insert(SEMANTIC_SIGNAL_TYPE.to_string(), "trace".to_string());
3600        // A key this version does not recognise, still inside the namespace.
3601        meta.options
3602            .extra_options
3603            .insert("greptime.semantic.future_key".to_string(), "x".to_string());
3604
3605        let alter_kind = AlterKind::UnsetAnnotations {
3606            family: AnnotationFamily::Semantic,
3607            keys: vec![
3608                SEMANTIC_SIGNAL_TYPE.to_string(),
3609                "greptime.semantic.future_key".to_string(),
3610                // Absent key: removal is a no-op, not an error.
3611                SEMANTIC_METRIC_UNIT.to_string(),
3612            ],
3613        };
3614        let new_meta = meta
3615            .builder_with_alter_kind("my_table", &alter_kind)
3616            .unwrap()
3617            .build()
3618            .unwrap();
3619        assert!(
3620            !new_meta
3621                .options
3622                .extra_options
3623                .contains_key(SEMANTIC_SIGNAL_TYPE)
3624        );
3625        assert!(
3626            !new_meta
3627                .options
3628                .extra_options
3629                .contains_key("greptime.semantic.future_key")
3630        );
3631
3632        let outside = AlterKind::UnsetAnnotations {
3633            family: AnnotationFamily::Semantic,
3634            keys: vec!["ttl".to_string()],
3635        };
3636        let err = meta
3637            .builder_with_alter_kind("my_table", &outside)
3638            .err()
3639            .unwrap();
3640        assert!(err.to_string().contains("annotation namespace"), "{err}");
3641    }
3642
3643    #[test]
3644    fn test_modify_entity_column_type_keeps_string_form() {
3645        let mut meta = semantic_test_meta();
3646        meta.options.extra_options.insert(
3647            "greptime.semantic.entity.service.id".to_string(),
3648            "service".to_string(),
3649        );
3650
3651        let alter_kind = AlterKind::ModifyColumnTypes {
3652            columns: vec![ModifyColumnTypeRequest {
3653                column_name: "service".to_string(),
3654                target_type: ConcreteDataType::binary_datatype(),
3655            }],
3656        };
3657        let err = meta
3658            .builder_with_alter_kind("my_table", &alter_kind)
3659            .err()
3660            .unwrap();
3661        assert!(
3662            err.to_string()
3663                .contains("must keep a type that renders as a string"),
3664            "{err}"
3665        );
3666
3667        // An unreferenced column may still change to a non-string form.
3668        let alter_kind = AlterKind::ModifyColumnTypes {
3669            columns: vec![ModifyColumnTypeRequest {
3670                column_name: "note".to_string(),
3671                target_type: ConcreteDataType::binary_datatype(),
3672            }],
3673        };
3674        meta.builder_with_alter_kind("my_table", &alter_kind)
3675            .unwrap();
3676    }
3677
3678    #[test]
3679    fn test_stale_entity_declaration_guards_readd_and_reports_missing_column() {
3680        // A stale declaration: `gone` was dropped after being declared.
3681        let mut meta = semantic_test_meta();
3682        meta.options.extra_options.insert(
3683            "greptime.semantic.entity.service.id".to_string(),
3684            "gone".to_string(),
3685        );
3686
3687        // MODIFY on the missing column keeps the ColumnNotExists contract
3688        // (4002), stale declaration or not.
3689        let modify = AlterKind::ModifyColumnTypes {
3690            columns: vec![ModifyColumnTypeRequest {
3691                column_name: "gone".to_string(),
3692                target_type: ConcreteDataType::binary_datatype(),
3693            }],
3694        };
3695        let err = meta
3696            .builder_with_alter_kind("my_table", &modify)
3697            .err()
3698            .unwrap();
3699        assert_eq!(
3700            common_error::status_code::StatusCode::TableColumnNotFound,
3701            common_error::ext::ErrorExt::status_code(&err)
3702        );
3703
3704        // Re-adding the declared column must not hand the declaration a
3705        // non-string type...
3706        let add = |ty: ConcreteDataType| AlterKind::AddColumns {
3707            columns: vec![AddColumnRequest {
3708                column_schema: ColumnSchema::new("gone", ty, true),
3709                is_key: false,
3710                location: None,
3711                add_if_not_exists: false,
3712            }],
3713        };
3714        let err = meta
3715            .builder_with_alter_kind("my_table", &add(ConcreteDataType::binary_datatype()))
3716            .err()
3717            .unwrap();
3718        assert!(
3719            err.to_string()
3720                .contains("must keep a type that renders as a string"),
3721            "{err}"
3722        );
3723
3724        // ...while a string re-add re-satisfies it.
3725        meta.builder_with_alter_kind("my_table", &add(ConcreteDataType::string_datatype()))
3726            .unwrap();
3727    }
3728}