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