Skip to main content

table/
requests.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
15//! Table and TableEngine requests
16
17use std::collections::{BTreeMap, HashMap, HashSet};
18use std::fmt;
19use std::str::FromStr;
20
21use common_base::readable_size::ReadableSize;
22use common_datasource::object_store::oss::is_supported_in_oss;
23use common_datasource::object_store::s3::is_supported_in_s3;
24use common_query::AddColumnLocation;
25use common_time::TimeToLive;
26use common_time::range::TimestampRange;
27use datatypes::data_type::ConcreteDataType;
28use datatypes::json::JsonSettings;
29use datatypes::prelude::VectorRef;
30use datatypes::schema::{
31    ColumnDefaultConstraint, ColumnSchema, FulltextOptions, Schema, SkippingIndexOptions,
32};
33use greptime_proto::v1::region::{build_index_request, compact_request};
34use once_cell::sync::Lazy;
35use serde::{Deserialize, Serialize};
36use store_api::metric_engine_consts::{
37    LOGICAL_TABLE_METADATA_KEY, MEMTABLE_PARTITION_TREE_PRIMARY_KEY_ENCODING,
38    PHYSICAL_TABLE_METADATA_KEY, PRIMARY_KEY_ENCODING, is_metric_engine_option_key,
39};
40use store_api::mito_engine_options::{
41    APPEND_MODE_KEY, COMPACTION_TYPE, EXPERIMENTAL_SST_FLOAT_FIELD_ENCODING, FloatFieldEncoding,
42    MEMTABLE_BULK_ENCODE_BYTES_THRESHOLD, MEMTABLE_BULK_ENCODE_ROW_THRESHOLD,
43    MEMTABLE_BULK_MAX_MERGE_GROUPS, MEMTABLE_BULK_MERGE_THRESHOLD, MEMTABLE_TYPE, MERGE_MODE_KEY,
44    SST_FORMAT_KEY, TWCS_ACTIVE_WINDOW_L1_MERGE_TRIGGER, TWCS_ACTIVE_WINDOW_TRIGGER_FILE_NUM,
45    TWCS_FALLBACK_TO_LOCAL, TWCS_INACTIVE_WINDOW_L1_MERGE_TRIGGER,
46    TWCS_INACTIVE_WINDOW_TRIGGER_FILE_NUM, TWCS_MAX_OUTPUT_FILE_SIZE, TWCS_TIME_WINDOW,
47    TWCS_TRIGGER_FILE_NUM, is_mito_engine_option_key, normalize_twcs_trigger_options,
48};
49use store_api::region_request::{SetRegionOption, UnsetRegionOption};
50
51use crate::error::{
52    ConflictingTableOptionsSnafu, ParseTableOptionSnafu, PhysicalTableOptionSnafu, Result,
53};
54use crate::metadata::{TableId, TableVersion};
55
56mod semantic;
57pub use semantic::*;
58
59pub const FILE_TABLE_META_KEY: &str = "__private.file_table_meta";
60pub const RELATIONAL_META_KEY: &str = "__private.relational_meta";
61pub const FILE_TABLE_LOCATION_KEY: &str = "location";
62pub const FILE_TABLE_PATTERN_KEY: &str = "pattern";
63pub const FILE_TABLE_FORMAT_KEY: &str = "format";
64pub const RELATIONAL_CONNECTION_KEY: &str = "connection";
65pub const RELATIONAL_REMOTE_TABLE_KEY: &str = "remote_table";
66
67/// Options captured at `CREATE EXTERNAL TABLE ... ENGINE=relational WITH (...)` time
68/// and persisted in the region manifest.
69///
70/// `connection` is persisted in **plaintext** so the datanode can reconnect to the
71/// remote database when serving queries on the region.
72#[derive(Clone, Serialize, Deserialize, PartialEq, Eq)]
73pub struct RelationalOptions {
74    /// Full DSN, e.g. `mysql://user:password@host:3306/db`.
75    pub connection: String,
76    pub remote_table: String,
77}
78
79impl RelationalOptions {
80    /// Returns a copy with the password in `connection` replaced by
81    /// `REDACTED_OPTION_VALUE`, safe to surface in error messages and logs. The persisted
82    /// manifest keeps the plaintext `connection` so the datanode can reconnect
83    /// to the remote database when serving queries.
84    pub fn redacted(&self) -> Self {
85        Self {
86            connection: redact_connection(&self.connection),
87            remote_table: self.remote_table.clone(),
88        }
89    }
90}
91
92/// Redacts the password of a connection DSN, preserving the other fields
93/// (scheme, host, port, user, database). On a parse failure the whole string is
94/// replaced with `REDACTED_OPTION_VALUE` (best-effort).
95pub fn redact_connection(connection: &str) -> String {
96    match url::Url::parse(connection) {
97        Ok(mut url) => {
98            if url.password().is_some() {
99                let _ = url.set_password(Some(REDACTED_OPTION_VALUE));
100            }
101            url.to_string()
102        }
103        Err(_) => REDACTED_OPTION_VALUE.to_string(),
104    }
105}
106
107pub fn redact_relational_options(encoded: &str) -> String {
108    serde_json::from_str::<RelationalOptions>(encoded)
109        .ok()
110        .and_then(|opts| serde_json::to_string(&opts.redacted()).ok())
111        .unwrap_or_else(|| REDACTED_OPTION_VALUE.to_string())
112}
113
114pub fn redact_option_value(key: &str, value: &str) -> Option<String> {
115    if is_credential_option(key) {
116        Some(REDACTED_OPTION_VALUE.to_string())
117    } else if key == RELATIONAL_META_KEY {
118        Some(redact_relational_options(value))
119    } else {
120        None
121    }
122}
123
124impl std::fmt::Debug for RelationalOptions {
125    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
126        f.debug_struct("RelationalOptions")
127            .field("connection", &redact_connection(&self.connection))
128            .field("remote_table", &self.remote_table)
129            .finish()
130    }
131}
132
133pub const TABLE_DATA_MODEL: &str = "table_data_model";
134pub const TABLE_DATA_MODEL_TRACE_V1: &str = "greptime_trace_v1";
135/// Table data model used by the JSON2-based OTLP trace pipeline.
136pub const TABLE_DATA_MODEL_TRACE_V2: &str = "greptime_trace_v2";
137/// Table data model of OTLP log tables auto-created with the v1 built-in schema.
138/// Log tables without this marker keep the legacy built-in schema.
139pub const TABLE_DATA_MODEL_LOG_V1: &str = "greptime_log_v1";
140
141/// Returns true for the Trace V1 and V2 data models supported
142/// by semantic graph derivation.
143pub fn is_trace_table(table_info: &crate::metadata::TableInfo) -> bool {
144    let table_data_model = table_info.meta.options.data_model();
145    matches!(
146        table_data_model,
147        Some(TABLE_DATA_MODEL_TRACE_V1 | TABLE_DATA_MODEL_TRACE_V2)
148    )
149}
150
151/// Retained table metadata; OTLP metrics always use Prometheus-compatible conversion.
152pub const OTLP_METRIC_COMPAT_KEY: &str = "otlp_metric_compat";
153pub const OTLP_METRIC_COMPAT_PROM: &str = "prom";
154
155pub const VALID_TABLE_OPTION_KEYS: [&str; 17] = [
156    // common keys:
157    WRITE_BUFFER_SIZE_KEY,
158    TTL_KEY,
159    STORAGE_KEY,
160    COMMENT_KEY,
161    SKIP_WAL_KEY,
162    SST_FORMAT_KEY,
163    // file engine keys:
164    FILE_TABLE_LOCATION_KEY,
165    FILE_TABLE_FORMAT_KEY,
166    FILE_TABLE_PATTERN_KEY,
167    // relational engine keys:
168    RELATIONAL_CONNECTION_KEY,
169    RELATIONAL_REMOTE_TABLE_KEY,
170    // metric engine keys:
171    PHYSICAL_TABLE_METADATA_KEY,
172    LOGICAL_TABLE_METADATA_KEY,
173    // table model info
174    TABLE_DATA_MODEL,
175    OTLP_METRIC_COMPAT_KEY,
176    REPARTITION_COLUMN_HINT_KEY,
177    REPARTITION_PARTITION_NUM_HINT_KEY,
178];
179
180pub const DDL_TIMEOUT: &str = "timeout";
181pub const DDL_WAIT: &str = "wait";
182
183pub const VALID_DDL_OPTION_KEYS: [&str; 2] = [DDL_TIMEOUT, DDL_WAIT];
184
185/// The key of ingest rows rate limit option (rows per second, cluster-wide) in database options.
186pub const INGEST_ROWS_RATE_LIMIT_KEY: &str = "ingest_rows_rate_limit";
187
188// Valid option keys when creating a db.
189static VALID_DB_OPT_KEYS: Lazy<HashSet<&str>> = Lazy::new(|| {
190    let mut set = HashSet::new();
191    set.insert(TTL_KEY);
192    set.insert(STORAGE_KEY);
193    set.insert(MEMTABLE_TYPE);
194    set.insert(MEMTABLE_BULK_MERGE_THRESHOLD);
195    set.insert(MEMTABLE_BULK_ENCODE_ROW_THRESHOLD);
196    set.insert(MEMTABLE_BULK_ENCODE_BYTES_THRESHOLD);
197    set.insert(MEMTABLE_BULK_MAX_MERGE_GROUPS);
198    set.insert(APPEND_MODE_KEY);
199    set.insert(MERGE_MODE_KEY);
200    set.insert(SKIP_WAL_KEY);
201    set.insert(COMPACTION_TYPE);
202    set.insert(TWCS_FALLBACK_TO_LOCAL);
203    set.insert(TWCS_TIME_WINDOW);
204    set.insert(TWCS_TRIGGER_FILE_NUM);
205    set.insert(TWCS_ACTIVE_WINDOW_TRIGGER_FILE_NUM);
206    set.insert(TWCS_ACTIVE_WINDOW_L1_MERGE_TRIGGER);
207    set.insert(TWCS_INACTIVE_WINDOW_TRIGGER_FILE_NUM);
208    set.insert(TWCS_INACTIVE_WINDOW_L1_MERGE_TRIGGER);
209    set.insert(TWCS_MAX_OUTPUT_FILE_SIZE);
210    set.insert(SST_FORMAT_KEY);
211    set.insert(INGEST_ROWS_RATE_LIMIT_KEY);
212    set
213});
214
215/// Returns true if the `key` is a valid key for database.
216pub fn validate_database_option(key: &str) -> bool {
217    VALID_DB_OPT_KEYS.contains(&key)
218}
219
220/// Validates a database option value, returning the violated constraint on error.
221pub fn validate_database_option_value(
222    key: &str,
223    value: Option<&str>,
224) -> std::result::Result<(), &'static str> {
225    if key == INGEST_ROWS_RATE_LIMIT_KEY {
226        return value
227            .and_then(|value| value.parse::<u64>().ok())
228            .map(|_| ())
229            .ok_or("expected a non-negative integer fitting in u64");
230    }
231    let (minimum, constraint) = match key {
232        TWCS_TRIGGER_FILE_NUM
233        | TWCS_ACTIVE_WINDOW_TRIGGER_FILE_NUM
234        | TWCS_INACTIVE_WINDOW_TRIGGER_FILE_NUM => {
235            (0, "expected a non-negative integer fitting in usize")
236        }
237        TWCS_ACTIVE_WINDOW_L1_MERGE_TRIGGER | TWCS_INACTIVE_WINDOW_L1_MERGE_TRIGGER => {
238            (2, "expected an integer greater than or equal to 2")
239        }
240        _ => return Ok(()),
241    };
242    if value
243        .and_then(|value| value.parse::<usize>().ok())
244        .is_some_and(|files| files >= minimum)
245    {
246        Ok(())
247    } else {
248        Err(constraint)
249    }
250}
251
252/// Returns true if the `key` is a valid key for any engine or storage.
253pub fn validate_table_option(key: &str) -> bool {
254    if is_supported_in_s3(key) {
255        return true;
256    }
257
258    if is_supported_in_oss(key) {
259        return true;
260    }
261
262    if is_mito_engine_option_key(key) {
263        return true;
264    }
265
266    if is_metric_engine_option_key(key) {
267        return true;
268    }
269
270    // Semantic-layer keys share a reserved prefix instead of a fixed allowlist so
271    // the vocabulary can grow without touching this gate. See `semantic` module.
272    if is_semantic_option_key(key) {
273        return true;
274    }
275
276    VALID_TABLE_OPTION_KEYS.contains(&key) || VALID_DDL_OPTION_KEYS.contains(&key)
277}
278
279#[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
280#[serde(default)]
281pub struct TableOptions {
282    /// Per-region write buffer stall threshold. Writes are rejected at twice this size.
283    pub write_buffer_size: Option<ReadableSize>,
284    /// Time-to-live of table. Expired data will be automatically purged.
285    pub ttl: Option<TimeToLive>,
286    /// Skip wal write for this table.
287    pub skip_wal: bool,
288    /// Extra options that may not applicable to all table engines.
289    pub extra_options: HashMap<String, String>,
290}
291
292pub const WRITE_BUFFER_SIZE_KEY: &str = store_api::mito_engine_options::WRITE_BUFFER_SIZE_KEY;
293pub const TTL_KEY: &str = store_api::mito_engine_options::TTL_KEY;
294pub const STORAGE_KEY: &str = "storage";
295pub const COMMENT_KEY: &str = "comment";
296pub const AUTO_CREATE_TABLE_KEY: &str = "auto_create_table";
297pub const SKIP_WAL_KEY: &str = store_api::mito_engine_options::SKIP_WAL_KEY;
298pub const TRACE_TABLE_PARTITIONS_HINT_KEY: &str = "trace_table_partitions";
299pub const REPARTITION_COLUMN_HINT_KEY: &str = "repartition.column.hint";
300
301/// Table-level partition count hint consumed by the auto-repartition planner.
302pub const REPARTITION_PARTITION_NUM_HINT_KEY: &str = "repartition.partition.num.hint";
303
304impl TableOptions {
305    /// Returns the table data model, if specified.
306    pub fn data_model(&self) -> Option<&str> {
307        self.extra_options.get(TABLE_DATA_MODEL).map(String::as_str)
308    }
309
310    pub fn try_from_iter<T: ToString, U: IntoIterator<Item = (T, T)>>(
311        iter: U,
312    ) -> Result<TableOptions> {
313        let mut options = TableOptions::default();
314
315        let mut kvs: HashMap<String, String> = iter
316            .into_iter()
317            .map(|(k, v)| (k.to_string(), v.to_string()))
318            .collect();
319
320        if kvs.contains_key(LOGICAL_TABLE_METADATA_KEY) {
321            for key in [
322                PRIMARY_KEY_ENCODING,
323                MEMTABLE_PARTITION_TREE_PRIMARY_KEY_ENCODING,
324            ] {
325                if kvs.contains_key(key) {
326                    return PhysicalTableOptionSnafu { key }.fail();
327                }
328            }
329        }
330
331        normalize_twcs_trigger_options(&mut kvs).map_err(|conflict| {
332            ConflictingTableOptionsSnafu {
333                first_key: TWCS_TRIGGER_FILE_NUM,
334                first_value: conflict.legacy_value,
335                second_key: TWCS_ACTIVE_WINDOW_TRIGGER_FILE_NUM,
336                second_value: conflict.canonical_value,
337            }
338            .build()
339        })?;
340
341        if let Some(write_buffer_size) = kvs.get(WRITE_BUFFER_SIZE_KEY) {
342            let size = ReadableSize::from_str(write_buffer_size).map_err(|_| {
343                ParseTableOptionSnafu {
344                    key: WRITE_BUFFER_SIZE_KEY,
345                    value: write_buffer_size,
346                }
347                .build()
348            })?;
349            options.write_buffer_size = Some(size)
350        }
351
352        if let Some(ttl) = kvs.get(TTL_KEY) {
353            let ttl_value = TimeToLive::from_humantime_or_str(ttl).map_err(|_| {
354                ParseTableOptionSnafu {
355                    key: TTL_KEY,
356                    value: ttl,
357                }
358                .build()
359            })?;
360            options.ttl = Some(ttl_value);
361        }
362
363        if let Some(encoding) = kvs.get(EXPERIMENTAL_SST_FLOAT_FIELD_ENCODING) {
364            encoding.parse::<FloatFieldEncoding>().map_err(|_| {
365                ParseTableOptionSnafu {
366                    key: EXPERIMENTAL_SST_FLOAT_FIELD_ENCODING,
367                    value: encoding,
368                }
369                .build()
370            })?;
371        }
372
373        if let Some(skip_wal) = kvs.get(SKIP_WAL_KEY) {
374            options.skip_wal = skip_wal.parse().map_err(|_| {
375                ParseTableOptionSnafu {
376                    key: SKIP_WAL_KEY,
377                    value: skip_wal,
378                }
379                .build()
380            })?;
381        }
382
383        options.extra_options = HashMap::from_iter(
384            kvs.into_iter()
385                .filter(|(k, _)| k != WRITE_BUFFER_SIZE_KEY && k != TTL_KEY),
386        );
387
388        Ok(options)
389    }
390}
391
392/// Option keys whose values contain credentials and must be masked when rendered.
393const CREDENTIAL_OPTION_KEYS: [&str; 5] = [
394    "access_key_id",
395    "connection",
396    "secret_access_key",
397    "session_token",
398    "access_key_secret",
399];
400
401/// Placeholder rendered instead of a credential value.
402pub const REDACTED_OPTION_VALUE: &str = "******";
403
404pub fn is_credential_option(key: &str) -> bool {
405    CREDENTIAL_OPTION_KEYS.contains(&key)
406}
407
408/// Renders the options for users, e.g. `information_schema.tables.create_options`,
409/// so credential values are masked.
410impl fmt::Display for TableOptions {
411    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
412        let mut key_vals = vec![];
413        if let Some(size) = self.write_buffer_size {
414            key_vals.push(format!("{}={}", WRITE_BUFFER_SIZE_KEY, size));
415        }
416
417        if let Some(ttl) = self.ttl.map(|ttl| ttl.to_string()) {
418            key_vals.push(format!("{}={}", TTL_KEY, ttl));
419        }
420
421        if self.skip_wal && !self.extra_options.contains_key(SKIP_WAL_KEY) {
422            key_vals.push(format!("{}={}", SKIP_WAL_KEY, self.skip_wal));
423        }
424
425        // Sort by key so `create_options` is stable across queries; `HashMap` order is not.
426        let extra_options: BTreeMap<_, _> = self.extra_options.iter().collect();
427        for (k, v) in extra_options {
428            let value = redact_option_value(k, v).unwrap_or_else(|| v.clone());
429            key_vals.push(format!("{}={}", k, value));
430        }
431
432        write!(f, "{}", key_vals.join(" "))
433    }
434}
435
436impl fmt::Debug for TableOptions {
437    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
438        let extra_options = self
439            .extra_options
440            .iter()
441            .map(|(key, value)| {
442                let redacted = redact_option_value(key, value).unwrap_or_else(|| value.clone());
443                (key.clone(), redacted)
444            })
445            .collect::<HashMap<_, _>>();
446        f.debug_struct("TableOptions")
447            .field("write_buffer_size", &self.write_buffer_size)
448            .field("ttl", &self.ttl)
449            .field("skip_wal", &self.skip_wal)
450            .field("extra_options", &extra_options)
451            .finish()
452    }
453}
454
455impl From<&TableOptions> for HashMap<String, String> {
456    fn from(opts: &TableOptions) -> Self {
457        let mut res = HashMap::with_capacity(3 + opts.extra_options.len());
458        if let Some(write_buffer_size) = opts.write_buffer_size {
459            let _ = res.insert(
460                WRITE_BUFFER_SIZE_KEY.to_string(),
461                write_buffer_size.to_string(),
462            );
463        }
464        if let Some(ttl_str) = opts.ttl.map(|ttl| ttl.to_string()) {
465            let _ = res.insert(TTL_KEY.to_string(), ttl_str);
466        }
467        if opts.skip_wal {
468            let _ = res.insert(SKIP_WAL_KEY.to_string(), true.to_string());
469        }
470        res.extend(opts.extra_options.clone());
471        res
472    }
473}
474
475/// Alter table request
476#[derive(Debug, Clone, Serialize, Deserialize)]
477pub struct AlterTableRequest {
478    pub catalog_name: String,
479    pub schema_name: String,
480    pub table_name: String,
481    pub table_id: TableId,
482    pub alter_kind: AlterKind,
483    // None in standalone.
484    pub table_version: Option<TableVersion>,
485}
486
487/// Add column request
488#[derive(Debug, Clone, Serialize, Deserialize)]
489pub struct AddColumnRequest {
490    pub column_schema: ColumnSchema,
491    pub is_key: bool,
492    pub location: Option<AddColumnLocation>,
493    /// Add column if not exists.
494    pub add_if_not_exists: bool,
495}
496
497/// Change column datatype request
498#[derive(Debug, Clone, Serialize, Deserialize)]
499pub struct ModifyColumnTypeRequest {
500    pub column_name: String,
501    pub target_type: ConcreteDataType,
502}
503
504/// Set JSON2 settings request.
505#[derive(Debug, Clone, Serialize, Deserialize)]
506pub struct SetJsonSettingsRequest {
507    pub column_name: String,
508    pub settings: JsonSettings,
509}
510
511/// A family of annotation table options: pure metadata markers that no region
512/// consumes. Setting or unsetting them only rewrites the table's
513/// `extra_options`, so the alter skips region dispatch entirely.
514#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
515pub enum AnnotationFamily {
516    /// `greptime.semantic.*` options (see the [`semantic`] module).
517    Semantic,
518    /// Column and partition count hints consumed by the auto-repartition planner.
519    RepartitionHint,
520}
521
522impl AnnotationFamily {
523    /// The key namespace used in diagnostics; accepted keys are classified by [`Self::of_key`].
524    pub fn namespace(self) -> &'static str {
525        match self {
526            Self::Semantic => SEMANTIC_PREFIX,
527            Self::RepartitionHint => "repartition.",
528        }
529    }
530
531    pub fn of_key(key: &str) -> Option<Self> {
532        if key.starts_with(SEMANTIC_PREFIX) {
533            Some(Self::Semantic)
534        } else if matches!(
535            key,
536            REPARTITION_COLUMN_HINT_KEY | REPARTITION_PARTITION_NUM_HINT_KEY
537        ) {
538            Some(Self::RepartitionHint)
539        } else {
540            None
541        }
542    }
543
544    /// Whether this family may be altered on logical metric tables. Only
545    /// families whose values nothing on the physical side consumes qualify;
546    /// the repartition hint drives physical region repartitioning.
547    pub fn allows_logical_tables(self) -> bool {
548        match self {
549            Self::Semantic => true,
550            Self::RepartitionHint => false,
551        }
552    }
553
554    /// Whether duplicate keys are rejected in this family's SET/UNSET batch.
555    pub fn requires_unique_keys(self) -> bool {
556        matches!(self, Self::RepartitionHint)
557    }
558
559    /// The error for a SET/UNSET batch mixing this family with other options.
560    pub fn mixed_batch_error(self) -> String {
561        match self {
562            Self::Semantic => format!(
563                "`{SEMANTIC_PREFIX}*` options must be altered separately from other table options"
564            ),
565            Self::RepartitionHint => {
566                "repartition hints must be altered separately from other table options".to_string()
567            }
568        }
569    }
570}
571
572/// Why an annotation SET/UNSET key batch was rejected.
573#[derive(Debug, Clone, PartialEq, Eq)]
574pub enum AnnotationKeyError {
575    MixedFamilies { family: AnnotationFamily },
576    DuplicateKey,
577}
578
579impl fmt::Display for AnnotationKeyError {
580    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
581        match self {
582            Self::MixedFamilies { family } => f.write_str(&family.mixed_batch_error()),
583            Self::DuplicateKey => f.write_str("duplicate repartition hint keys"),
584        }
585    }
586}
587
588/// Validates a SET/UNSET batch and returns its annotation family.
589///
590/// Empty batches and batches containing only non-annotation keys return `None`.
591/// Annotation keys cannot share a batch with another family or region options.
592/// Duplicate keys are rejected only for families that require unique keys.
593pub fn validate_annotation_keys<'a>(
594    keys: impl IntoIterator<Item = &'a str>,
595) -> std::result::Result<Option<AnnotationFamily>, AnnotationKeyError> {
596    let mut keys = keys.into_iter();
597    let Some(first) = keys.next() else {
598        return Ok(None);
599    };
600    let family = AnnotationFamily::of_key(first);
601    let reject_duplicates = family.is_some_and(|family| family.requires_unique_keys());
602    let mut seen = HashSet::new();
603    if reject_duplicates {
604        seen.insert(first);
605    }
606    for key in keys {
607        let this = AnnotationFamily::of_key(key);
608        if this != family
609            && let Some(family) = family.or(this)
610        {
611            return Err(AnnotationKeyError::MixedFamilies { family });
612        }
613        if reject_duplicates && !seen.insert(key) {
614            return Err(AnnotationKeyError::DuplicateKey);
615        }
616    }
617    Ok(family)
618}
619
620/// Table shape an annotation option is validated against.
621pub struct AnnotationContext<'a> {
622    pub data_model: Option<&'a str>,
623    pub schema: &'a Schema,
624    pub partition_key_indices: &'a [usize],
625}
626
627/// Why an annotation option was rejected. Typed so each DDL entry point maps
628/// rules onto its existing error variants and status codes: ALTER keeps
629/// missing columns as `TableColumnNotFound` (4002), CREATE keeps its
630/// `InvalidArguments` family — the rules converge, the contracts do not.
631#[derive(Debug, Clone, PartialEq, Eq)]
632pub enum AnnotationValidationError {
633    UnknownKey {
634        key: String,
635    },
636    InvalidValue {
637        key: String,
638        value: String,
639    },
640    ColumnNotFound {
641        column: String,
642    },
643    ColumnNotStringForm {
644        key: String,
645        column: String,
646        ty: ConcreteDataType,
647    },
648    InvalidPartitionNumHint {
649        value: String,
650    },
651    NotSingleColumn,
652    PartitionMetadataConflict,
653    TimeIndexConflict,
654}
655
656impl fmt::Display for AnnotationValidationError {
657    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
658        match self {
659            Self::UnknownKey { key } => write!(f, "unknown semantic option `{key}`"),
660            Self::InvalidValue { key, value } => {
661                write!(f, "invalid value `{value}` for semantic option `{key}`")
662            }
663            Self::ColumnNotFound { column } => write!(f, "column `{column}` not found"),
664            Self::ColumnNotStringForm { key, column, ty } => write!(
665                f,
666                "entity column `{column}` (option `{key}`) has type `{ty}`, \
667                 which cannot render as a string"
668            ),
669            Self::InvalidPartitionNumHint { value } => write!(
670                f,
671                "{REPARTITION_PARTITION_NUM_HINT_KEY} expects a positive integer within u32 range, got `{value}`"
672            ),
673            Self::NotSingleColumn => write!(
674                f,
675                "{REPARTITION_COLUMN_HINT_KEY} expects exactly one column name"
676            ),
677            Self::PartitionMetadataConflict => write!(
678                f,
679                "cannot set {REPARTITION_COLUMN_HINT_KEY} on a table with partition metadata"
680            ),
681            Self::TimeIndexConflict => write!(
682                f,
683                "cannot set {REPARTITION_COLUMN_HINT_KEY} to the time index column"
684            ),
685        }
686    }
687}
688
689/// Validates one annotation option and returns the value to store — the
690/// repartition hints are trimmed, semantic values pass
691/// through unchanged.
692pub(crate) fn validate_and_normalize_annotation(
693    family: AnnotationFamily,
694    cx: &AnnotationContext<'_>,
695    key: &str,
696    value: &str,
697) -> std::result::Result<String, AnnotationValidationError> {
698    match family {
699        AnnotationFamily::Semantic => {
700            if !is_semantic_option_key(key) {
701                return Err(AnnotationValidationError::UnknownKey {
702                    key: key.to_string(),
703                });
704            }
705            if !validate_semantic_option(key, value) {
706                return Err(AnnotationValidationError::InvalidValue {
707                    key: key.to_string(),
708                    value: value.to_string(),
709                });
710            }
711            if parse_entity_option_key(key).is_some() {
712                for column in parse_entity_columns(value) {
713                    if trace_v2_attribute(cx.schema, cx.data_model, &column).is_some() {
714                        continue;
715                    }
716                    let schema = cx.schema.column_schema_by_name(&column).ok_or_else(|| {
717                        AnnotationValidationError::ColumnNotFound {
718                            column: column.clone(),
719                        }
720                    })?;
721                    if !has_stable_string_form(&schema.data_type) {
722                        return Err(AnnotationValidationError::ColumnNotStringForm {
723                            key: key.to_string(),
724                            column,
725                            ty: schema.data_type.clone(),
726                        });
727                    }
728                }
729            }
730            Ok(value.to_string())
731        }
732        AnnotationFamily::RepartitionHint if key == REPARTITION_PARTITION_NUM_HINT_KEY => {
733            let value = value.trim();
734            if !matches!(value.parse::<u32>(), Ok(1..)) {
735                return Err(AnnotationValidationError::InvalidPartitionNumHint {
736                    value: value.to_string(),
737                });
738            }
739            Ok(value.to_string())
740        }
741        AnnotationFamily::RepartitionHint => {
742            let column_name = value.trim();
743            if column_name.is_empty() || column_name.contains(',') {
744                return Err(AnnotationValidationError::NotSingleColumn);
745            }
746            if !cx.partition_key_indices.is_empty() {
747                return Err(AnnotationValidationError::PartitionMetadataConflict);
748            }
749            let column_index = cx.schema.column_index_by_name(column_name).ok_or_else(|| {
750                AnnotationValidationError::ColumnNotFound {
751                    column: column_name.to_string(),
752                }
753            })?;
754            if cx.schema.timestamp_index() == Some(column_index) {
755                return Err(AnnotationValidationError::TimeIndexConflict);
756            }
757            Ok(column_name.to_string())
758        }
759    }
760}
761
762/// CREATE-side entry: validates every annotation option present in `options`
763/// and writes normalized values back in place.
764pub fn validate_and_normalize_annotation_options(
765    options: &mut TableOptions,
766    schema: &Schema,
767    partition_key_indices: &[usize],
768) -> std::result::Result<(), AnnotationValidationError> {
769    let cx = AnnotationContext {
770        data_model: options.data_model(),
771        schema,
772        partition_key_indices,
773    };
774    let mut normalized = Vec::new();
775    for (key, value) in &options.extra_options {
776        let Some(family) = AnnotationFamily::of_key(key) else {
777            continue;
778        };
779        let checked = validate_and_normalize_annotation(family, &cx, key, value)?;
780        if checked != *value {
781            normalized.push((key.clone(), checked));
782        }
783    }
784    for (key, value) in normalized {
785        options.extra_options.insert(key, value);
786    }
787    Ok(())
788}
789
790#[derive(Debug, Clone, Serialize, Deserialize)]
791pub enum AlterKind {
792    AddColumns {
793        columns: Vec<AddColumnRequest>,
794    },
795    DropColumns {
796        names: Vec<String>,
797    },
798    ModifyColumnTypes {
799        columns: Vec<ModifyColumnTypeRequest>,
800    },
801    SetJsonSettings {
802        request: SetJsonSettingsRequest,
803    },
804    RenameTable {
805        new_table_name: String,
806    },
807    SetTableOptions {
808        options: Vec<SetRegionOption>,
809    },
810    UnsetTableOptions {
811        keys: Vec<UnsetRegionOption>,
812    },
813    SetAnnotations {
814        family: AnnotationFamily,
815        options: Vec<(String, String)>,
816    },
817    UnsetAnnotations {
818        family: AnnotationFamily,
819        keys: Vec<String>,
820    },
821    SetIndexes {
822        options: Vec<SetIndexOption>,
823    },
824    UnsetIndexes {
825        options: Vec<UnsetIndexOption>,
826    },
827    DropDefaults {
828        names: Vec<String>,
829    },
830    SetDefaults {
831        defaults: Vec<SetDefaultRequest>,
832    },
833}
834
835#[derive(Debug, Clone, Serialize, Deserialize)]
836pub struct SetDefaultRequest {
837    pub column_name: String,
838    pub default_constraint: Option<ColumnDefaultConstraint>,
839}
840
841#[derive(Debug, Clone, Serialize, Deserialize)]
842pub enum SetIndexOption {
843    Fulltext {
844        column_name: String,
845        options: FulltextOptions,
846    },
847    Inverted {
848        column_name: String,
849    },
850    Skipping {
851        column_name: String,
852        options: SkippingIndexOptions,
853    },
854}
855
856impl SetIndexOption {
857    /// Returns the column name of the index option.
858    pub fn column_name(&self) -> &str {
859        match self {
860            SetIndexOption::Fulltext { column_name, .. } => column_name,
861            SetIndexOption::Inverted { column_name, .. } => column_name,
862            SetIndexOption::Skipping { column_name, .. } => column_name,
863        }
864    }
865}
866
867#[derive(Debug, Clone, Serialize, Deserialize)]
868pub enum UnsetIndexOption {
869    Fulltext { column_name: String },
870    Inverted { column_name: String },
871    Skipping { column_name: String },
872}
873
874impl UnsetIndexOption {
875    /// Returns the column name of the index option.
876    pub fn column_name(&self) -> &str {
877        match self {
878            UnsetIndexOption::Fulltext { column_name, .. } => column_name,
879            UnsetIndexOption::Inverted { column_name, .. } => column_name,
880            UnsetIndexOption::Skipping { column_name, .. } => column_name,
881        }
882    }
883}
884
885#[derive(Debug)]
886pub struct InsertRequest {
887    pub catalog_name: String,
888    pub schema_name: String,
889    pub table_name: String,
890    pub columns_values: HashMap<String, VectorRef>,
891    /// Whether this insert should skip WAL.
892    pub skip_wal: bool,
893}
894
895/// Delete (by primary key) request
896#[derive(Debug)]
897pub struct DeleteRequest {
898    pub catalog_name: String,
899    pub schema_name: String,
900    pub table_name: String,
901    /// Values of each column in this table's primary key and time index.
902    ///
903    /// The key is the column name, and the value is the column value.
904    pub key_column_values: HashMap<String, VectorRef>,
905}
906
907#[derive(Debug)]
908pub enum CopyDirection {
909    Export,
910    Import,
911}
912
913/// Copy table request
914#[derive(Debug)]
915pub struct CopyTableRequest {
916    pub catalog_name: String,
917    pub schema_name: String,
918    pub table_name: String,
919    pub location: String,
920    pub with: HashMap<String, String>,
921    pub connection: HashMap<String, String>,
922    pub pattern: Option<String>,
923    pub direction: CopyDirection,
924    pub timestamp_range: Option<TimestampRange>,
925    pub limit: Option<u64>,
926}
927
928#[derive(Debug, Clone, Default)]
929pub struct FlushTableRequest {
930    pub catalog_name: String,
931    pub schema_name: String,
932    pub table_name: String,
933}
934
935#[derive(Debug, Clone, Default)]
936pub struct BuildIndexTableRequest {
937    /// The index build mode. Absent options select SST indexes.
938    pub options: Option<build_index_request::Options>,
939    pub catalog_name: String,
940    pub schema_name: String,
941    pub table_name: String,
942}
943
944#[derive(Debug, Clone, PartialEq)]
945pub struct CompactTableRequest {
946    pub catalog_name: String,
947    pub schema_name: String,
948    pub table_name: String,
949    pub compact_options: compact_request::Options,
950    pub parallelism: u32,
951    pub time_range: Option<TimestampRange>,
952}
953
954impl Default for CompactTableRequest {
955    fn default() -> Self {
956        Self {
957            catalog_name: Default::default(),
958            schema_name: Default::default(),
959            table_name: Default::default(),
960            compact_options: compact_request::Options::Regular(Default::default()),
961            parallelism: 1,
962            time_range: None,
963        }
964    }
965}
966
967#[derive(Debug, Clone, Default, Deserialize, Serialize)]
968pub struct CopyDatabaseRequest {
969    pub catalog_name: String,
970    pub schema_name: String,
971    pub location: String,
972    pub with: HashMap<String, String>,
973    pub connection: HashMap<String, String>,
974    pub time_range: Option<TimestampRange>,
975}
976
977#[derive(Debug, Clone, Default, Deserialize, Serialize)]
978pub struct CopyQueryToRequest {
979    pub location: String,
980    pub with: HashMap<String, String>,
981    pub connection: HashMap<String, String>,
982}
983
984#[cfg(test)]
985mod tests {
986    use std::time::Duration;
987
988    use common_error::ext::ErrorExt;
989    use common_error::status_code::StatusCode;
990
991    use super::*;
992
993    #[test]
994    fn test_redact_connection() {
995        assert_eq!(
996            redact_connection("mysql://user:secret@127.0.0.1:3306/db"),
997            "mysql://user:******@127.0.0.1:3306/db"
998        );
999        // A DSN without a password is left unchanged.
1000        assert_eq!(
1001            redact_connection("mysql://user@127.0.0.1:3306/db"),
1002            "mysql://user@127.0.0.1:3306/db"
1003        );
1004        // Unparsable input is fully redacted.
1005        assert_eq!(redact_connection("not-a-url"), "******");
1006    }
1007
1008    #[test]
1009    fn test_relational_options_redacted() {
1010        let options = RelationalOptions {
1011            connection: "mysql://user:secret@127.0.0.1:3306/db".to_string(),
1012            remote_table: "sample".to_string(),
1013        };
1014        let redacted = options.redacted();
1015        assert_eq!(redacted.connection, "mysql://user:******@127.0.0.1:3306/db");
1016        assert_eq!(redacted.remote_table, "sample");
1017    }
1018
1019    #[test]
1020    fn test_relational_options_debug_redacts_connection() {
1021        let options = RelationalOptions {
1022            connection: "mysql://user:secret@127.0.0.1:3306/db".to_string(),
1023            remote_table: "sample".to_string(),
1024        };
1025        let debug = format!("{options:?}");
1026        assert!(!debug.contains("secret"));
1027        assert!(debug.contains("******"));
1028        assert!(debug.contains("sample"));
1029    }
1030
1031    #[test]
1032    fn test_table_options_display_redacts_relational_meta() {
1033        let options = TableOptions {
1034            extra_options: HashMap::from([(
1035                RELATIONAL_META_KEY.to_string(),
1036                r#"{"connection":"mysql://user:secret@127.0.0.1:3306/db","remote_table":"sample"}"#
1037                    .to_string(),
1038            )]),
1039            ..Default::default()
1040        };
1041        let rendered = options.to_string();
1042        assert!(!rendered.contains("secret"));
1043        assert!(rendered.contains("******"));
1044    }
1045
1046    #[test]
1047    fn test_table_options_debug_redacts_relational_meta() {
1048        let options = TableOptions {
1049            extra_options: HashMap::from([(
1050                RELATIONAL_META_KEY.to_string(),
1051                r#"{"connection":"mysql://user:secret@127.0.0.1:3306/db","remote_table":"sample"}"#
1052                    .to_string(),
1053            )]),
1054            ..Default::default()
1055        };
1056        let rendered = format!("{options:?}");
1057        assert!(!rendered.contains("secret"));
1058        assert!(rendered.contains("******"));
1059    }
1060
1061    #[test]
1062    fn test_table_options_debug_redacts_credential() {
1063        let options = TableOptions {
1064            extra_options: HashMap::from([
1065                ("secret_access_key".to_string(), "my-secret".to_string()),
1066                ("session_token".to_string(), "my-token".to_string()),
1067                ("location".to_string(), "s3://bucket/file.csv".to_string()),
1068            ]),
1069            ..Default::default()
1070        };
1071        let rendered = format!("{options:?}");
1072        assert!(!rendered.contains("my-secret"));
1073        assert!(!rendered.contains("my-token"));
1074        assert!(rendered.contains("******"));
1075        assert!(rendered.contains("s3://bucket/file.csv"));
1076    }
1077
1078    #[test]
1079    fn test_validate_annotation_keys() {
1080        let column = REPARTITION_COLUMN_HINT_KEY;
1081        let count = REPARTITION_PARTITION_NUM_HINT_KEY;
1082        for (keys, expected) in [
1083            (vec![], None),
1084            (vec![TTL_KEY, TTL_KEY], None),
1085            (vec!["repartition.unknown.hint"], None),
1086            (vec![column], Some(AnnotationFamily::RepartitionHint)),
1087            (vec![count], Some(AnnotationFamily::RepartitionHint)),
1088            (vec![column, count], Some(AnnotationFamily::RepartitionHint)),
1089            (vec![count, column], Some(AnnotationFamily::RepartitionHint)),
1090            (
1091                vec!["greptime.semantic.source", "greptime.semantic.source"],
1092                Some(AnnotationFamily::Semantic),
1093            ),
1094        ] {
1095            assert_eq!(validate_annotation_keys(keys), Ok(expected));
1096        }
1097        for keys in [
1098            vec![column, column],
1099            vec![count, count],
1100            vec![column, count, column],
1101        ] {
1102            assert_eq!(
1103                validate_annotation_keys(keys),
1104                Err(AnnotationKeyError::DuplicateKey)
1105            );
1106        }
1107        for keys in [
1108            vec![column, TTL_KEY],
1109            vec![TTL_KEY, count],
1110            vec![column, "greptime.semantic.source"],
1111        ] {
1112            assert_eq!(
1113                validate_annotation_keys(keys),
1114                Err(AnnotationKeyError::MixedFamilies {
1115                    family: AnnotationFamily::RepartitionHint,
1116                })
1117            );
1118        }
1119    }
1120
1121    #[test]
1122    fn test_validate_table_option() {
1123        assert!(validate_table_option(FILE_TABLE_LOCATION_KEY));
1124        assert!(validate_table_option(FILE_TABLE_FORMAT_KEY));
1125        assert!(validate_table_option(FILE_TABLE_PATTERN_KEY));
1126        assert!(validate_table_option(RELATIONAL_CONNECTION_KEY));
1127        assert!(validate_table_option(RELATIONAL_REMOTE_TABLE_KEY));
1128        assert!(validate_table_option(TTL_KEY));
1129        assert!(validate_table_option(WRITE_BUFFER_SIZE_KEY));
1130        assert!(validate_table_option(STORAGE_KEY));
1131        assert!(validate_table_option(MEMTABLE_BULK_MERGE_THRESHOLD));
1132        assert!(validate_table_option(EXPERIMENTAL_SST_FLOAT_FIELD_ENCODING));
1133        assert!(validate_table_option(REPARTITION_COLUMN_HINT_KEY));
1134        assert!(validate_table_option(REPARTITION_PARTITION_NUM_HINT_KEY));
1135        assert_eq!(AnnotationFamily::of_key("repartition.unknown.hint"), None);
1136        assert!(!validate_table_option("foo"));
1137
1138        // Only whitelisted semantic keys are accepted.
1139        assert!(validate_table_option(SEMANTIC_SIGNAL_TYPE));
1140        assert!(validate_table_option(SEMANTIC_METRIC_TYPE));
1141        // Unknown semantic key, near-miss, and the internal transport key are rejected.
1142        assert!(!validate_table_option("greptime.semantic.future.key"));
1143        assert!(!validate_table_option("greptime.semanticx"));
1144        assert!(!validate_table_option(SEMANTIC_PER_TABLE_INDEX_KEY));
1145    }
1146
1147    #[test]
1148    fn test_validate_database_option() {
1149        assert!(validate_database_option(MEMTABLE_TYPE));
1150        assert!(validate_database_option(MEMTABLE_BULK_MERGE_THRESHOLD));
1151        assert!(validate_database_option(MEMTABLE_BULK_ENCODE_ROW_THRESHOLD));
1152        assert!(validate_database_option(
1153            MEMTABLE_BULK_ENCODE_BYTES_THRESHOLD
1154        ));
1155        assert!(validate_database_option(MEMTABLE_BULK_MAX_MERGE_GROUPS));
1156        assert!(validate_database_option(
1157            "compaction.twcs.active_window.trigger_file_num"
1158        ));
1159        assert!(validate_database_option(
1160            "compaction.twcs.active_window.l1_merge_trigger"
1161        ));
1162        assert!(validate_database_option(
1163            "compaction.twcs.inactive_window.trigger_file_num"
1164        ));
1165        assert!(validate_database_option(
1166            "compaction.twcs.inactive_window.l1_merge_trigger"
1167        ));
1168        assert!(validate_database_option(INGEST_ROWS_RATE_LIMIT_KEY));
1169        assert!(validate_database_option("ingest_rows_rate_limit"));
1170        assert!(!validate_database_option("foo"));
1171    }
1172
1173    #[test]
1174    fn test_primary_key_encoding_on_metric_tables() {
1175        for key in [
1176            PRIMARY_KEY_ENCODING,
1177            MEMTABLE_PARTITION_TREE_PRIMARY_KEY_ENCODING,
1178        ] {
1179            let error = TableOptions::try_from_iter([
1180                (LOGICAL_TABLE_METADATA_KEY, "metrics"),
1181                (key, "sparse"),
1182            ])
1183            .unwrap_err();
1184            assert_eq!(StatusCode::InvalidArguments, error.status_code());
1185            assert!(error.to_string().contains(key));
1186            TableOptions::try_from_iter([(PHYSICAL_TABLE_METADATA_KEY, ""), (key, "sparse")])
1187                .unwrap();
1188        }
1189    }
1190
1191    #[test]
1192    fn test_parse_float_field_encoding_option() {
1193        let options = TableOptions::try_from_iter([(
1194            EXPERIMENTAL_SST_FLOAT_FIELD_ENCODING,
1195            "byte_stream_split",
1196        )])
1197        .unwrap();
1198        assert_eq!(
1199            options
1200                .extra_options
1201                .get(EXPERIMENTAL_SST_FLOAT_FIELD_ENCODING),
1202            Some(&"byte_stream_split".to_string())
1203        );
1204        assert!(
1205            TableOptions::try_from_iter([(EXPERIMENTAL_SST_FLOAT_FIELD_ENCODING, "invalid",)])
1206                .is_err()
1207        );
1208    }
1209
1210    #[test]
1211    fn test_database_trigger_value_boundaries() {
1212        let maximum = usize::MAX.to_string();
1213        let overflow = format!("{maximum}0");
1214        for (key, minimum) in [
1215            (TWCS_TRIGGER_FILE_NUM, 0),
1216            (TWCS_ACTIVE_WINDOW_TRIGGER_FILE_NUM, 0),
1217            (TWCS_INACTIVE_WINDOW_TRIGGER_FILE_NUM, 0),
1218            (TWCS_ACTIVE_WINDOW_L1_MERGE_TRIGGER, 2),
1219            (TWCS_INACTIVE_WINDOW_L1_MERGE_TRIGGER, 2),
1220        ] {
1221            for invalid in [
1222                None,
1223                Some(""),
1224                Some("invalid"),
1225                Some("-1"),
1226                Some(overflow.as_str()),
1227            ] {
1228                assert!(
1229                    validate_database_option_value(key, invalid).is_err(),
1230                    "{key}: {invalid:?}"
1231                );
1232            }
1233            for valid in ["2", maximum.as_str()] {
1234                assert!(
1235                    validate_database_option_value(key, Some(valid)).is_ok(),
1236                    "{key}: {valid}"
1237                );
1238            }
1239            for boundary in ["0", "1"] {
1240                assert_eq!(
1241                    validate_database_option_value(key, Some(boundary)).is_ok(),
1242                    minimum == 0,
1243                    "{key}: {boundary}"
1244                );
1245            }
1246        }
1247    }
1248
1249    #[test]
1250    fn test_database_ingest_rate_limit_value_boundaries() {
1251        for invalid in [
1252            None,
1253            Some(""),
1254            Some("abc"),
1255            Some("1000/s"),
1256            Some("-1"),
1257            Some("1.5"),
1258            Some("18446744073709551616"),
1259        ] {
1260            assert!(validate_database_option_value(INGEST_ROWS_RATE_LIMIT_KEY, invalid).is_err());
1261        }
1262        let maximum = u64::MAX.to_string();
1263        for valid in ["0", "1", maximum.as_str()] {
1264            assert!(
1265                validate_database_option_value(INGEST_ROWS_RATE_LIMIT_KEY, Some(valid)).is_ok()
1266            );
1267        }
1268    }
1269
1270    #[test]
1271    fn test_serialize_table_options() {
1272        let options = TableOptions {
1273            write_buffer_size: None,
1274            ttl: Some(Duration::from_secs(1000).into()),
1275            extra_options: HashMap::new(),
1276            skip_wal: false,
1277        };
1278        let serialized = serde_json::to_string(&options).unwrap();
1279        let deserialized: TableOptions = serde_json::from_str(&serialized).unwrap();
1280        assert_eq!(options, deserialized);
1281    }
1282
1283    #[test]
1284    fn test_convert_hashmap_between_table_options() {
1285        let options = TableOptions {
1286            write_buffer_size: Some(ReadableSize::mb(128)),
1287            ttl: Some(Duration::from_secs(1000).into()),
1288            extra_options: HashMap::new(),
1289            skip_wal: false,
1290        };
1291        let serialized_map = HashMap::from(&options);
1292        let serialized = TableOptions::try_from_iter(&serialized_map).unwrap();
1293        assert_eq!(options, serialized);
1294
1295        let options = TableOptions {
1296            write_buffer_size: None,
1297            ttl: None,
1298            extra_options: HashMap::from([(SKIP_WAL_KEY.to_string(), true.to_string())]),
1299            skip_wal: true,
1300        };
1301        let serialized_map = HashMap::from(&options);
1302        assert_eq!(
1303            Some("true"),
1304            serialized_map.get(SKIP_WAL_KEY).map(String::as_str)
1305        );
1306        let serialized = TableOptions::try_from_iter(&serialized_map).unwrap();
1307        assert_eq!(options, serialized);
1308
1309        let options = TableOptions {
1310            write_buffer_size: None,
1311            ttl: Default::default(),
1312            extra_options: HashMap::new(),
1313            skip_wal: false,
1314        };
1315        let serialized_map = HashMap::from(&options);
1316        let serialized = TableOptions::try_from_iter(&serialized_map).unwrap();
1317        assert_eq!(options, serialized);
1318
1319        let options = TableOptions {
1320            write_buffer_size: Some(ReadableSize::mb(128)),
1321            ttl: Some(Duration::from_secs(1000).into()),
1322            extra_options: HashMap::from([("a".to_string(), "A".to_string())]),
1323            skip_wal: false,
1324        };
1325        let serialized_map = HashMap::from(&options);
1326        let serialized = TableOptions::try_from_iter(&serialized_map).unwrap();
1327        assert_eq!(options, serialized);
1328
1329        let options = TableOptions {
1330            extra_options: HashMap::from([(SKIP_WAL_KEY.to_string(), false.to_string())]),
1331            skip_wal: false,
1332            ..Default::default()
1333        };
1334        let serialized_map = HashMap::from(&options);
1335        let serialized = TableOptions::try_from_iter(&serialized_map).unwrap();
1336        assert_eq!(options, serialized);
1337    }
1338
1339    #[test]
1340    fn test_table_options_normalizes_twcs_trigger_aliases() {
1341        for options in [
1342            vec![(TWCS_ACTIVE_WINDOW_TRIGGER_FILE_NUM, "4")],
1343            vec![
1344                (TWCS_TRIGGER_FILE_NUM, "4"),
1345                (TWCS_ACTIVE_WINDOW_TRIGGER_FILE_NUM, "4"),
1346            ],
1347        ] {
1348            let table_options = TableOptions::try_from_iter(options).unwrap();
1349            assert_eq!(
1350                HashMap::from([(TWCS_TRIGGER_FILE_NUM.to_string(), "4".to_string())]),
1351                table_options.extra_options
1352            );
1353        }
1354    }
1355
1356    #[test]
1357    fn test_table_options_rejects_conflicting_twcs_trigger_aliases() {
1358        let error = TableOptions::try_from_iter([
1359            (TWCS_TRIGGER_FILE_NUM, "4"),
1360            (TWCS_ACTIVE_WINDOW_TRIGGER_FILE_NUM, "8"),
1361        ])
1362        .unwrap_err();
1363        assert_eq!(StatusCode::InvalidArguments, error.status_code());
1364        assert_eq!(
1365            "Conflicting table options: compaction.twcs.trigger_file_num=4 and compaction.twcs.active_window.trigger_file_num=8",
1366            error.to_string()
1367        );
1368    }
1369
1370    #[test]
1371    fn test_table_options_to_string() {
1372        let options = TableOptions {
1373            write_buffer_size: Some(ReadableSize::mb(128)),
1374            ttl: Some(Duration::from_secs(1000).into()),
1375            extra_options: HashMap::new(),
1376            skip_wal: false,
1377        };
1378
1379        assert_eq!(
1380            "write_buffer_size=128.0MiB ttl=16m 40s",
1381            options.to_string()
1382        );
1383
1384        let options = TableOptions {
1385            write_buffer_size: Some(ReadableSize::mb(128)),
1386            ttl: Some(Duration::from_secs(1000).into()),
1387            extra_options: HashMap::from([("a".to_string(), "A".to_string())]),
1388            skip_wal: false,
1389        };
1390
1391        assert_eq!(
1392            "write_buffer_size=128.0MiB ttl=16m 40s a=A",
1393            options.to_string()
1394        );
1395
1396        let options = TableOptions {
1397            write_buffer_size: Some(ReadableSize::mb(128)),
1398            ttl: Some(Duration::from_secs(1000).into()),
1399            extra_options: HashMap::new(),
1400            skip_wal: true,
1401        };
1402        assert_eq!(
1403            "write_buffer_size=128.0MiB ttl=16m 40s skip_wal=true",
1404            options.to_string()
1405        );
1406
1407        let options = TableOptions {
1408            write_buffer_size: None,
1409            ttl: None,
1410            extra_options: HashMap::from([(SKIP_WAL_KEY.to_string(), "false".to_string())]),
1411            skip_wal: false,
1412        };
1413        assert_eq!("skip_wal=false", options.to_string());
1414    }
1415}