1use std::collections::{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::prelude::VectorRef;
29use datatypes::schema::{
30 ColumnDefaultConstraint, ColumnSchema, FulltextOptions, SkippingIndexOptions,
31};
32use greptime_proto::v1::region::compact_request;
33use once_cell::sync::Lazy;
34use serde::{Deserialize, Serialize};
35use store_api::metric_engine_consts::{
36 LOGICAL_TABLE_METADATA_KEY, PHYSICAL_TABLE_METADATA_KEY, is_metric_engine_option_key,
37};
38use store_api::mito_engine_options::{
39 APPEND_MODE_KEY, COMPACTION_TYPE, MEMTABLE_TYPE, MERGE_MODE_KEY, SST_FORMAT_KEY,
40 TWCS_FALLBACK_TO_LOCAL, TWCS_MAX_OUTPUT_FILE_SIZE, TWCS_TIME_WINDOW, TWCS_TRIGGER_FILE_NUM,
41 is_mito_engine_option_key,
42};
43use store_api::region_request::{SetRegionOption, UnsetRegionOption};
44
45use crate::error::{ParseTableOptionSnafu, Result};
46use crate::metadata::{TableId, TableVersion};
47use crate::table_reference::TableReference;
48
49pub const FILE_TABLE_META_KEY: &str = "__private.file_table_meta";
50pub const FILE_TABLE_LOCATION_KEY: &str = "location";
51pub const FILE_TABLE_PATTERN_KEY: &str = "pattern";
52pub const FILE_TABLE_FORMAT_KEY: &str = "format";
53
54pub const TABLE_DATA_MODEL: &str = "table_data_model";
55pub const TABLE_DATA_MODEL_TRACE_V1: &str = "greptime_trace_v1";
56
57pub const OTLP_METRIC_COMPAT_KEY: &str = "otlp_metric_compat";
58pub const OTLP_METRIC_COMPAT_PROM: &str = "prom";
59
60pub const VALID_TABLE_OPTION_KEYS: [&str; 13] = [
61 WRITE_BUFFER_SIZE_KEY,
63 TTL_KEY,
64 STORAGE_KEY,
65 COMMENT_KEY,
66 SKIP_WAL_KEY,
67 SST_FORMAT_KEY,
68 FILE_TABLE_LOCATION_KEY,
70 FILE_TABLE_FORMAT_KEY,
71 FILE_TABLE_PATTERN_KEY,
72 PHYSICAL_TABLE_METADATA_KEY,
74 LOGICAL_TABLE_METADATA_KEY,
75 TABLE_DATA_MODEL,
77 OTLP_METRIC_COMPAT_KEY,
78];
79
80pub const DDL_TIMEOUT: &str = "timeout";
81pub const DDL_WAIT: &str = "wait";
82
83pub const VALID_DDL_OPTION_KEYS: [&str; 2] = [DDL_TIMEOUT, DDL_WAIT];
84
85static VALID_DB_OPT_KEYS: Lazy<HashSet<&str>> = Lazy::new(|| {
87 let mut set = HashSet::new();
88 set.insert(TTL_KEY);
89 set.insert(STORAGE_KEY);
90 set.insert(MEMTABLE_TYPE);
91 set.insert(APPEND_MODE_KEY);
92 set.insert(MERGE_MODE_KEY);
93 set.insert(SKIP_WAL_KEY);
94 set.insert(COMPACTION_TYPE);
95 set.insert(TWCS_FALLBACK_TO_LOCAL);
96 set.insert(TWCS_TIME_WINDOW);
97 set.insert(TWCS_TRIGGER_FILE_NUM);
98 set.insert(TWCS_MAX_OUTPUT_FILE_SIZE);
99 set.insert(SST_FORMAT_KEY);
100 set
101});
102
103pub fn validate_database_option(key: &str) -> bool {
105 VALID_DB_OPT_KEYS.contains(&key)
106}
107
108pub fn validate_table_option(key: &str) -> bool {
110 if is_supported_in_s3(key) {
111 return true;
112 }
113
114 if is_supported_in_oss(key) {
115 return true;
116 }
117
118 if is_mito_engine_option_key(key) {
119 return true;
120 }
121
122 if is_metric_engine_option_key(key) {
123 return true;
124 }
125
126 VALID_TABLE_OPTION_KEYS.contains(&key) || VALID_DDL_OPTION_KEYS.contains(&key)
127}
128
129#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
130#[serde(default)]
131pub struct TableOptions {
132 pub write_buffer_size: Option<ReadableSize>,
134 pub ttl: Option<TimeToLive>,
136 pub skip_wal: bool,
138 pub extra_options: HashMap<String, String>,
140}
141
142pub const WRITE_BUFFER_SIZE_KEY: &str = "write_buffer_size";
143pub const TTL_KEY: &str = store_api::mito_engine_options::TTL_KEY;
144pub const STORAGE_KEY: &str = "storage";
145pub const COMMENT_KEY: &str = "comment";
146pub const AUTO_CREATE_TABLE_KEY: &str = "auto_create_table";
147pub const SKIP_WAL_KEY: &str = store_api::mito_engine_options::SKIP_WAL_KEY;
148
149impl TableOptions {
150 pub fn try_from_iter<T: ToString, U: IntoIterator<Item = (T, T)>>(
151 iter: U,
152 ) -> Result<TableOptions> {
153 let mut options = TableOptions::default();
154
155 let kvs: HashMap<String, String> = iter
156 .into_iter()
157 .map(|(k, v)| (k.to_string(), v.to_string()))
158 .collect();
159
160 if let Some(write_buffer_size) = kvs.get(WRITE_BUFFER_SIZE_KEY) {
161 let size = ReadableSize::from_str(write_buffer_size).map_err(|_| {
162 ParseTableOptionSnafu {
163 key: WRITE_BUFFER_SIZE_KEY,
164 value: write_buffer_size,
165 }
166 .build()
167 })?;
168 options.write_buffer_size = Some(size)
169 }
170
171 if let Some(ttl) = kvs.get(TTL_KEY) {
172 let ttl_value = TimeToLive::from_humantime_or_str(ttl).map_err(|_| {
173 ParseTableOptionSnafu {
174 key: TTL_KEY,
175 value: ttl,
176 }
177 .build()
178 })?;
179 options.ttl = Some(ttl_value);
180 }
181
182 if let Some(skip_wal) = kvs.get(SKIP_WAL_KEY) {
183 options.skip_wal = skip_wal.parse().map_err(|_| {
184 ParseTableOptionSnafu {
185 key: SKIP_WAL_KEY,
186 value: skip_wal,
187 }
188 .build()
189 })?;
190 }
191
192 options.extra_options = HashMap::from_iter(
193 kvs.into_iter()
194 .filter(|(k, _)| k != WRITE_BUFFER_SIZE_KEY && k != TTL_KEY),
195 );
196
197 Ok(options)
198 }
199}
200
201impl fmt::Display for TableOptions {
202 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
203 let mut key_vals = vec![];
204 if let Some(size) = self.write_buffer_size {
205 key_vals.push(format!("{}={}", WRITE_BUFFER_SIZE_KEY, size));
206 }
207
208 if let Some(ttl) = self.ttl.map(|ttl| ttl.to_string()) {
209 key_vals.push(format!("{}={}", TTL_KEY, ttl));
210 }
211
212 if self.skip_wal {
213 key_vals.push(format!("{}={}", SKIP_WAL_KEY, self.skip_wal));
214 }
215
216 for (k, v) in &self.extra_options {
217 key_vals.push(format!("{}={}", k, v));
218 }
219
220 write!(f, "{}", key_vals.join(" "))
221 }
222}
223
224impl From<&TableOptions> for HashMap<String, String> {
225 fn from(opts: &TableOptions) -> Self {
226 let mut res = HashMap::with_capacity(2 + opts.extra_options.len());
227 if let Some(write_buffer_size) = opts.write_buffer_size {
228 let _ = res.insert(
229 WRITE_BUFFER_SIZE_KEY.to_string(),
230 write_buffer_size.to_string(),
231 );
232 }
233 if let Some(ttl_str) = opts.ttl.map(|ttl| ttl.to_string()) {
234 let _ = res.insert(TTL_KEY.to_string(), ttl_str);
235 }
236 res.extend(
237 opts.extra_options
238 .iter()
239 .map(|(k, v)| (k.clone(), v.clone())),
240 );
241 res
242 }
243}
244
245#[derive(Debug, Clone, Serialize, Deserialize)]
247pub struct AlterTableRequest {
248 pub catalog_name: String,
249 pub schema_name: String,
250 pub table_name: String,
251 pub table_id: TableId,
252 pub alter_kind: AlterKind,
253 pub table_version: Option<TableVersion>,
255}
256
257#[derive(Debug, Clone, Serialize, Deserialize)]
259pub struct AddColumnRequest {
260 pub column_schema: ColumnSchema,
261 pub is_key: bool,
262 pub location: Option<AddColumnLocation>,
263 pub add_if_not_exists: bool,
265}
266
267#[derive(Debug, Clone, Serialize, Deserialize)]
269pub struct ModifyColumnTypeRequest {
270 pub column_name: String,
271 pub target_type: ConcreteDataType,
272}
273
274#[derive(Debug, Clone, Serialize, Deserialize)]
275pub enum AlterKind {
276 AddColumns {
277 columns: Vec<AddColumnRequest>,
278 },
279 DropColumns {
280 names: Vec<String>,
281 },
282 ModifyColumnTypes {
283 columns: Vec<ModifyColumnTypeRequest>,
284 },
285 RenameTable {
286 new_table_name: String,
287 },
288 SetTableOptions {
289 options: Vec<SetRegionOption>,
290 },
291 UnsetTableOptions {
292 keys: Vec<UnsetRegionOption>,
293 },
294 SetIndexes {
295 options: Vec<SetIndexOption>,
296 },
297 UnsetIndexes {
298 options: Vec<UnsetIndexOption>,
299 },
300 DropDefaults {
301 names: Vec<String>,
302 },
303 SetDefaults {
304 defaults: Vec<SetDefaultRequest>,
305 },
306}
307
308#[derive(Debug, Clone, Serialize, Deserialize)]
309pub struct SetDefaultRequest {
310 pub column_name: String,
311 pub default_constraint: Option<ColumnDefaultConstraint>,
312}
313
314#[derive(Debug, Clone, Serialize, Deserialize)]
315pub enum SetIndexOption {
316 Fulltext {
317 column_name: String,
318 options: FulltextOptions,
319 },
320 Inverted {
321 column_name: String,
322 },
323 Skipping {
324 column_name: String,
325 options: SkippingIndexOptions,
326 },
327}
328
329impl SetIndexOption {
330 pub fn column_name(&self) -> &str {
332 match self {
333 SetIndexOption::Fulltext { column_name, .. } => column_name,
334 SetIndexOption::Inverted { column_name, .. } => column_name,
335 SetIndexOption::Skipping { column_name, .. } => column_name,
336 }
337 }
338}
339
340#[derive(Debug, Clone, Serialize, Deserialize)]
341pub enum UnsetIndexOption {
342 Fulltext { column_name: String },
343 Inverted { column_name: String },
344 Skipping { column_name: String },
345}
346
347impl UnsetIndexOption {
348 pub fn column_name(&self) -> &str {
350 match self {
351 UnsetIndexOption::Fulltext { column_name, .. } => column_name,
352 UnsetIndexOption::Inverted { column_name, .. } => column_name,
353 UnsetIndexOption::Skipping { column_name, .. } => column_name,
354 }
355 }
356}
357
358#[derive(Debug)]
359pub struct InsertRequest {
360 pub catalog_name: String,
361 pub schema_name: String,
362 pub table_name: String,
363 pub columns_values: HashMap<String, VectorRef>,
364}
365
366#[derive(Debug)]
368pub struct DeleteRequest {
369 pub catalog_name: String,
370 pub schema_name: String,
371 pub table_name: String,
372 pub key_column_values: HashMap<String, VectorRef>,
376}
377
378#[derive(Debug)]
379pub enum CopyDirection {
380 Export,
381 Import,
382}
383
384#[derive(Debug)]
386pub struct CopyTableRequest {
387 pub catalog_name: String,
388 pub schema_name: String,
389 pub table_name: String,
390 pub location: String,
391 pub with: HashMap<String, String>,
392 pub connection: HashMap<String, String>,
393 pub pattern: Option<String>,
394 pub direction: CopyDirection,
395 pub timestamp_range: Option<TimestampRange>,
396 pub limit: Option<u64>,
397}
398
399#[derive(Debug, Clone, Default)]
400pub struct FlushTableRequest {
401 pub catalog_name: String,
402 pub schema_name: String,
403 pub table_name: String,
404}
405
406#[derive(Debug, Clone, Default)]
407pub struct BuildIndexTableRequest {
408 pub catalog_name: String,
409 pub schema_name: String,
410 pub table_name: String,
411}
412
413#[derive(Debug, Clone, PartialEq)]
414pub struct CompactTableRequest {
415 pub catalog_name: String,
416 pub schema_name: String,
417 pub table_name: String,
418 pub compact_options: compact_request::Options,
419 pub parallelism: u32,
420}
421
422impl Default for CompactTableRequest {
423 fn default() -> Self {
424 Self {
425 catalog_name: Default::default(),
426 schema_name: Default::default(),
427 table_name: Default::default(),
428 compact_options: compact_request::Options::Regular(Default::default()),
429 parallelism: 1,
430 }
431 }
432}
433
434#[derive(Debug, Clone, Serialize, Deserialize)]
436pub struct TruncateTableRequest {
437 pub catalog_name: String,
438 pub schema_name: String,
439 pub table_name: String,
440 pub table_id: TableId,
441}
442
443impl TruncateTableRequest {
444 pub fn table_ref(&self) -> TableReference<'_> {
445 TableReference {
446 catalog: &self.catalog_name,
447 schema: &self.schema_name,
448 table: &self.table_name,
449 }
450 }
451}
452
453#[derive(Debug, Clone, Default, Deserialize, Serialize)]
454pub struct CopyDatabaseRequest {
455 pub catalog_name: String,
456 pub schema_name: String,
457 pub location: String,
458 pub with: HashMap<String, String>,
459 pub connection: HashMap<String, String>,
460 pub time_range: Option<TimestampRange>,
461}
462
463#[derive(Debug, Clone, Default, Deserialize, Serialize)]
464pub struct CopyQueryToRequest {
465 pub location: String,
466 pub with: HashMap<String, String>,
467 pub connection: HashMap<String, String>,
468}
469
470#[cfg(test)]
471mod tests {
472 use std::time::Duration;
473
474 use super::*;
475
476 #[test]
477 fn test_validate_table_option() {
478 assert!(validate_table_option(FILE_TABLE_LOCATION_KEY));
479 assert!(validate_table_option(FILE_TABLE_FORMAT_KEY));
480 assert!(validate_table_option(FILE_TABLE_PATTERN_KEY));
481 assert!(validate_table_option(TTL_KEY));
482 assert!(validate_table_option(WRITE_BUFFER_SIZE_KEY));
483 assert!(validate_table_option(STORAGE_KEY));
484 assert!(!validate_table_option("foo"));
485 }
486
487 #[test]
488 fn test_serialize_table_options() {
489 let options = TableOptions {
490 write_buffer_size: None,
491 ttl: Some(Duration::from_secs(1000).into()),
492 extra_options: HashMap::new(),
493 skip_wal: false,
494 };
495 let serialized = serde_json::to_string(&options).unwrap();
496 let deserialized: TableOptions = serde_json::from_str(&serialized).unwrap();
497 assert_eq!(options, deserialized);
498 }
499
500 #[test]
501 fn test_convert_hashmap_between_table_options() {
502 let options = TableOptions {
503 write_buffer_size: Some(ReadableSize::mb(128)),
504 ttl: Some(Duration::from_secs(1000).into()),
505 extra_options: HashMap::new(),
506 skip_wal: false,
507 };
508 let serialized_map = HashMap::from(&options);
509 let serialized = TableOptions::try_from_iter(&serialized_map).unwrap();
510 assert_eq!(options, serialized);
511
512 let options = TableOptions {
513 write_buffer_size: None,
514 ttl: Default::default(),
515 extra_options: HashMap::new(),
516 skip_wal: false,
517 };
518 let serialized_map = HashMap::from(&options);
519 let serialized = TableOptions::try_from_iter(&serialized_map).unwrap();
520 assert_eq!(options, serialized);
521
522 let options = TableOptions {
523 write_buffer_size: Some(ReadableSize::mb(128)),
524 ttl: Some(Duration::from_secs(1000).into()),
525 extra_options: HashMap::from([("a".to_string(), "A".to_string())]),
526 skip_wal: false,
527 };
528 let serialized_map = HashMap::from(&options);
529 let serialized = TableOptions::try_from_iter(&serialized_map).unwrap();
530 assert_eq!(options, serialized);
531 }
532
533 #[test]
534 fn test_table_options_to_string() {
535 let options = TableOptions {
536 write_buffer_size: Some(ReadableSize::mb(128)),
537 ttl: Some(Duration::from_secs(1000).into()),
538 extra_options: HashMap::new(),
539 skip_wal: false,
540 };
541
542 assert_eq!(
543 "write_buffer_size=128.0MiB ttl=16m 40s",
544 options.to_string()
545 );
546
547 let options = TableOptions {
548 write_buffer_size: Some(ReadableSize::mb(128)),
549 ttl: Some(Duration::from_secs(1000).into()),
550 extra_options: HashMap::from([("a".to_string(), "A".to_string())]),
551 skip_wal: false,
552 };
553
554 assert_eq!(
555 "write_buffer_size=128.0MiB ttl=16m 40s a=A",
556 options.to_string()
557 );
558
559 let options = TableOptions {
560 write_buffer_size: Some(ReadableSize::mb(128)),
561 ttl: Some(Duration::from_secs(1000).into()),
562 extra_options: HashMap::new(),
563 skip_wal: true,
564 };
565 assert_eq!(
566 "write_buffer_size=128.0MiB ttl=16m 40s skip_wal=true",
567 options.to_string()
568 );
569 }
570}