1use std::collections::HashMap;
16use std::str::FromStr;
17use std::{fmt, mem};
18
19use arrow::datatypes::Field;
20use arrow_schema::extension::{
21 EXTENSION_TYPE_METADATA_KEY, EXTENSION_TYPE_NAME_KEY, ExtensionType,
22};
23use common_base::readable_size::ReadableSize;
24use serde::{Deserialize, Serialize};
25use snafu::{ResultExt, ensure};
26use sqlparser_derive::{Visit, VisitMut};
27
28use crate::data_type::{ConcreteDataType, DataType};
29use crate::error::{
30 self, ArrowMetadataSnafu, Error, InvalidFulltextOptionSnafu, ParseExtendedTypeSnafu, Result,
31};
32use crate::extension::json::Json2ExtensionType;
33use crate::schema::TYPE_KEY;
34use crate::schema::constraint::ColumnDefaultConstraint;
35#[cfg(feature = "enterprise")]
36use crate::schema::sketch::{HllOptions, KllOptions, MgOptions};
37use crate::value::Value;
38use crate::vectors::json::builder::JsonVectorBuilder;
39use crate::vectors::{MutableVector, VectorRef};
40
41pub type Metadata = HashMap<String, String>;
42
43pub const TIME_INDEX_KEY: &str = "greptime:time_index";
45pub const METRIC_NAME_KEY: &str = "greptime:metric_name";
55pub const COMMENT_KEY: &str = "greptime:storage:comment";
56const DEFAULT_CONSTRAINT_KEY: &str = "greptime:default_constraint";
58pub const FULLTEXT_KEY: &str = "greptime:fulltext";
60pub const INVERTED_INDEX_KEY: &str = "greptime:inverted_index";
62pub const SKIPPING_INDEX_KEY: &str = "greptime:skipping_index";
64pub const COMPRESSION_KEY: &str = "greptime:compression";
66pub const HLL_KEY: &str = "greptime:hll";
68pub const KLL_KEY: &str = "greptime:kll";
70pub const MG_KEY: &str = "greptime:mg";
72
73pub const COLUMN_FULLTEXT_CHANGE_OPT_KEY_ENABLE: &str = "enable";
75pub const COLUMN_FULLTEXT_OPT_KEY_ANALYZER: &str = "analyzer";
76pub const COLUMN_FULLTEXT_OPT_KEY_CASE_SENSITIVE: &str = "case_sensitive";
77pub const COLUMN_FULLTEXT_OPT_KEY_BACKEND: &str = "backend";
78pub const COLUMN_FULLTEXT_OPT_KEY_GRANULARITY: &str = "granularity";
79pub const COLUMN_FULLTEXT_OPT_KEY_FALSE_POSITIVE_RATE: &str = "false_positive_rate";
80
81pub const COLUMN_SKIPPING_INDEX_OPT_KEY_GRANULARITY: &str = "granularity";
83pub const COLUMN_SKIPPING_INDEX_OPT_KEY_FALSE_POSITIVE_RATE: &str = "false_positive_rate";
84pub const COLUMN_SKIPPING_INDEX_OPT_KEY_TYPE: &str = "type";
85
86pub const COLUMN_COMPRESSION_OPT_KEY_TYPE: &str = "type";
88pub const COLUMN_COMPRESSION_OPT_KEY_LEVEL: &str = "level";
89pub const COLUMN_COMPRESSION_OPT_KEY_PAGE_SIZE: &str = "page_size";
90pub const COLUMN_COMPRESSION_OPT_KEY_ENCODING: &str = "encoding";
91
92pub const DEFAULT_GRANULARITY: u32 = 10240;
93
94pub const DEFAULT_FALSE_POSITIVE_RATE: f64 = 0.01;
95
96#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
98pub struct ColumnSchema {
99 pub name: String,
100 pub data_type: ConcreteDataType,
101 is_nullable: bool,
102 is_time_index: bool,
103 default_constraint: Option<ColumnDefaultConstraint>,
104 metadata: Metadata,
105}
106
107impl fmt::Debug for ColumnSchema {
108 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
109 write!(
110 f,
111 "{} {} {}",
112 self.name,
113 self.data_type,
114 if self.is_nullable { "null" } else { "not null" },
115 )?;
116
117 if self.is_time_index {
118 write!(f, " time_index")?;
119 }
120
121 if let Some(default_constraint) = &self.default_constraint {
123 write!(f, " default={:?}", default_constraint)?;
124 }
125
126 if !self.metadata.is_empty() {
128 write!(f, " metadata={:?}", self.metadata)?;
129 }
130
131 Ok(())
132 }
133}
134
135impl ColumnSchema {
136 pub fn new<T: Into<String>>(
137 name: T,
138 data_type: ConcreteDataType,
139 is_nullable: bool,
140 ) -> ColumnSchema {
141 ColumnSchema {
142 name: name.into(),
143 data_type,
144 is_nullable,
145 is_time_index: false,
146 default_constraint: None,
147 metadata: Metadata::new(),
148 }
149 }
150
151 pub fn create_mutable_vector(&self, capacity: usize) -> Box<dyn MutableVector> {
153 if self.data_type.is_json2()
154 && let Some(extension) = self.extension_type::<Json2ExtensionType>().ok().flatten()
155 && extension.metadata().is_version_2()
156 {
157 Box::new(JsonVectorBuilder::with_settings(
158 extension.metadata().json_settings(),
159 capacity,
160 ))
161 } else {
162 self.data_type.create_mutable_vector(capacity)
163 }
164 }
165
166 #[inline]
167 pub fn is_time_index(&self) -> bool {
168 self.is_time_index
169 }
170
171 #[inline]
172 pub fn is_nullable(&self) -> bool {
173 self.is_nullable
174 }
175
176 #[inline]
177 pub fn default_constraint(&self) -> Option<&ColumnDefaultConstraint> {
178 self.default_constraint.as_ref()
179 }
180
181 pub fn is_default_impure(&self) -> bool {
183 self.default_constraint
184 .as_ref()
185 .map(|c| c.is_function())
186 .unwrap_or(false)
187 }
188
189 #[inline]
190 pub fn metadata(&self) -> &Metadata {
191 &self.metadata
192 }
193
194 #[inline]
195 pub fn mut_metadata(&mut self) -> &mut Metadata {
196 &mut self.metadata
197 }
198
199 pub fn column_comment(&self) -> Option<&String> {
201 self.metadata.get(COMMENT_KEY)
202 }
203
204 pub fn with_time_index(mut self, is_time_index: bool) -> Self {
205 self.is_time_index = is_time_index;
206 if is_time_index {
207 let _ = self
208 .metadata
209 .insert(TIME_INDEX_KEY.to_string(), "true".to_string());
210 } else {
211 let _ = self.metadata.remove(TIME_INDEX_KEY);
212 }
213 self
214 }
215
216 pub fn estimated_size(&self) -> usize {
218 mem::size_of_val(self) - mem::size_of_val(&self.data_type)
219 + self.data_type.as_arrow_type().size()
220 + self.name.capacity()
221 + self
222 .default_constraint
223 .as_ref()
224 .map(column_default_constraint_size)
225 .unwrap_or_default()
226 + metadata_size(&self.metadata)
227 }
228
229 pub fn set_inverted_index(&mut self, value: bool) {
234 match value {
235 true => {
236 self.metadata
237 .insert(INVERTED_INDEX_KEY.to_string(), value.to_string());
238 }
239 false => {
240 self.metadata.remove(INVERTED_INDEX_KEY);
241 }
242 }
243 }
244
245 pub fn with_inverted_index(mut self, value: bool) -> Self {
250 self.set_inverted_index(value);
251 self
252 }
253
254 pub fn is_inverted_indexed(&self) -> bool {
255 self.metadata
256 .get(INVERTED_INDEX_KEY)
257 .map(|v| v.eq_ignore_ascii_case("true"))
258 .unwrap_or(false)
259 }
260
261 pub fn is_metric_name(&self) -> bool {
265 self.metadata
266 .get(METRIC_NAME_KEY)
267 .map(|value| value.eq_ignore_ascii_case("true"))
268 .unwrap_or(false)
269 }
270
271 pub fn with_metric_name(mut self, is_metric_name: bool) -> Self {
273 if is_metric_name {
274 let _ = self
275 .metadata
276 .insert(METRIC_NAME_KEY.to_string(), "true".to_string());
277 } else {
278 let _ = self.metadata.remove(METRIC_NAME_KEY);
279 }
280 self
281 }
282
283 pub fn is_fulltext_indexed(&self) -> bool {
284 self.fulltext_options()
285 .unwrap_or_default()
286 .map(|option| option.enable)
287 .unwrap_or_default()
288 }
289
290 pub fn is_skipping_indexed(&self) -> bool {
291 self.skipping_index_options().unwrap_or_default().is_some()
292 }
293
294 pub fn has_inverted_index_key(&self) -> bool {
295 self.metadata.contains_key(INVERTED_INDEX_KEY)
296 }
297
298 pub fn with_default_constraint(
303 mut self,
304 default_constraint: Option<ColumnDefaultConstraint>,
305 ) -> Result<Self> {
306 if let Some(constraint) = &default_constraint {
307 constraint.validate(&self.data_type, self.is_nullable)?;
308 }
309
310 self.default_constraint = default_constraint;
311 Ok(self)
312 }
313
314 pub fn with_nullable_set(mut self) -> Self {
319 self.is_nullable = true;
320 self
321 }
322
323 pub fn set_nullable(&mut self) {
328 self.is_nullable = true;
329 }
330
331 pub fn set_time_index(&mut self) {
336 self.is_time_index = true;
337 }
338
339 pub fn with_metadata(mut self, metadata: Metadata) -> Self {
341 self.metadata = metadata;
342 self
343 }
344
345 pub fn create_default_vector(&self, num_rows: usize) -> Result<Option<VectorRef>> {
349 match &self.default_constraint {
350 Some(c) => c
351 .create_default_vector(&self.data_type, self.is_nullable, num_rows)
352 .map(Some),
353 None => {
354 if self.is_nullable {
355 ColumnDefaultConstraint::null_value()
358 .create_default_vector(&self.data_type, self.is_nullable, num_rows)
359 .map(Some)
360 } else {
361 Ok(None)
362 }
363 }
364 }
365 }
366
367 pub fn create_default_vector_for_padding(&self, num_rows: usize) -> VectorRef {
373 let padding_value = if self.is_nullable {
374 Value::Null
375 } else {
376 self.data_type.default_value()
379 };
380 let value_ref = padding_value.as_value_ref();
381 let mut mutable_vector = self.data_type.create_mutable_vector(num_rows);
382 for _ in 0..num_rows {
383 mutable_vector.push_value_ref(&value_ref);
384 }
385 mutable_vector.to_vector()
386 }
387
388 pub fn create_default(&self) -> Result<Option<Value>> {
392 match &self.default_constraint {
393 Some(c) => c
394 .create_default(&self.data_type, self.is_nullable)
395 .map(Some),
396 None => {
397 if self.is_nullable {
398 ColumnDefaultConstraint::null_value()
400 .create_default(&self.data_type, self.is_nullable)
401 .map(Some)
402 } else {
403 Ok(None)
404 }
405 }
406 }
407 }
408
409 pub fn create_impure_default(&self) -> Result<Option<Value>> {
412 match &self.default_constraint {
413 Some(c) => c.create_impure_default(&self.data_type),
414 None => Ok(None),
415 }
416 }
417
418 pub fn fulltext_options(&self) -> Result<Option<FulltextOptions>> {
420 match self.metadata.get(FULLTEXT_KEY) {
421 None => Ok(None),
422 Some(json) => {
423 let options =
424 serde_json::from_str(json).context(error::DeserializeSnafu { json })?;
425 Ok(Some(options))
426 }
427 }
428 }
429
430 pub fn with_fulltext_options(mut self, options: FulltextOptions) -> Result<Self> {
431 self.metadata.insert(
432 FULLTEXT_KEY.to_string(),
433 serde_json::to_string(&options).context(error::SerializeSnafu)?,
434 );
435 Ok(self)
436 }
437
438 pub fn set_fulltext_options(&mut self, options: &FulltextOptions) -> Result<()> {
439 self.metadata.insert(
440 FULLTEXT_KEY.to_string(),
441 serde_json::to_string(options).context(error::SerializeSnafu)?,
442 );
443 Ok(())
444 }
445
446 pub fn skipping_index_options(&self) -> Result<Option<SkippingIndexOptions>> {
448 match self.metadata.get(SKIPPING_INDEX_KEY) {
449 None => Ok(None),
450 Some(json) => {
451 let options =
452 serde_json::from_str(json).context(error::DeserializeSnafu { json })?;
453 Ok(Some(options))
454 }
455 }
456 }
457
458 pub fn with_skipping_options(mut self, options: SkippingIndexOptions) -> Result<Self> {
459 self.metadata.insert(
460 SKIPPING_INDEX_KEY.to_string(),
461 serde_json::to_string(&options).context(error::SerializeSnafu)?,
462 );
463 Ok(self)
464 }
465
466 pub fn set_skipping_options(&mut self, options: &SkippingIndexOptions) -> Result<()> {
467 self.metadata.insert(
468 SKIPPING_INDEX_KEY.to_string(),
469 serde_json::to_string(options).context(error::SerializeSnafu)?,
470 );
471 Ok(())
472 }
473
474 pub fn unset_skipping_options(&mut self) -> Result<()> {
475 self.metadata.remove(SKIPPING_INDEX_KEY);
476 Ok(())
477 }
478
479 #[cfg(feature = "enterprise")]
481 pub fn hll_options(&self) -> Result<Option<HllOptions>> {
482 self.metadata
483 .get(HLL_KEY)
484 .map(|json| serde_json::from_str(json).context(error::DeserializeSnafu { json }))
485 .transpose()
486 }
487
488 #[cfg(feature = "enterprise")]
490 pub fn with_hll_options(mut self, options: HllOptions) -> Result<Self> {
491 self.set_hll_options(&options)?;
492 Ok(self)
493 }
494
495 #[cfg(feature = "enterprise")]
497 pub fn set_hll_options(&mut self, options: &HllOptions) -> Result<()> {
498 options.validate()?;
499 let json = serde_json::to_string(options).context(error::SerializeSnafu)?;
500 self.metadata.insert(HLL_KEY.to_string(), json);
501 Ok(())
502 }
503
504 #[cfg(feature = "enterprise")]
506 pub fn unset_hll_options(&mut self) {
507 self.metadata.remove(HLL_KEY);
508 }
509
510 #[cfg(feature = "enterprise")]
512 pub fn kll_options(&self) -> Result<Option<KllOptions>> {
513 self.metadata
514 .get(KLL_KEY)
515 .map(|json| serde_json::from_str(json).context(error::DeserializeSnafu { json }))
516 .transpose()
517 }
518
519 #[cfg(feature = "enterprise")]
521 pub fn with_kll_options(mut self, options: KllOptions) -> Result<Self> {
522 self.set_kll_options(&options)?;
523 Ok(self)
524 }
525
526 #[cfg(feature = "enterprise")]
528 pub fn set_kll_options(&mut self, options: &KllOptions) -> Result<()> {
529 options.validate()?;
530 let json = serde_json::to_string(options).context(error::SerializeSnafu)?;
531 self.metadata.insert(KLL_KEY.to_string(), json);
532 Ok(())
533 }
534
535 #[cfg(feature = "enterprise")]
537 pub fn unset_kll_options(&mut self) {
538 self.metadata.remove(KLL_KEY);
539 }
540
541 #[cfg(feature = "enterprise")]
543 pub fn mg_options(&self) -> Result<Option<MgOptions>> {
544 self.metadata
545 .get(MG_KEY)
546 .map(|json| serde_json::from_str(json).context(error::DeserializeSnafu { json }))
547 .transpose()
548 }
549
550 #[cfg(feature = "enterprise")]
552 pub fn with_mg_options(mut self, options: MgOptions) -> Result<Self> {
553 self.set_mg_options(&options)?;
554 Ok(self)
555 }
556
557 #[cfg(feature = "enterprise")]
559 pub fn set_mg_options(&mut self, options: &MgOptions) -> Result<()> {
560 options.validate()?;
561 let json = serde_json::to_string(options).context(error::SerializeSnafu)?;
562 self.metadata.insert(MG_KEY.to_string(), json);
563 Ok(())
564 }
565
566 #[cfg(feature = "enterprise")]
568 pub fn unset_mg_options(&mut self) {
569 self.metadata.remove(MG_KEY);
570 }
571
572 pub fn compression_options(&self) -> Result<Option<CompressionOptions>> {
574 match self.metadata.get(COMPRESSION_KEY) {
575 None => Ok(None),
576 Some(json) => {
577 let options = serde_json::from_str(json).map_err(|e| {
578 error::InvalidCompressionOptionSnafu {
579 msg: format!("invalid compression metadata for column {}: {e}", self.name),
580 }
581 .build()
582 })?;
583 self.validate_compression_options(&options)?;
584 Ok(Some(options))
585 }
586 }
587 }
588
589 pub fn with_compression_options(mut self, options: CompressionOptions) -> Result<Self> {
592 self.validate_compression_options(&options)?;
593 self.metadata.insert(
594 COMPRESSION_KEY.to_string(),
595 serde_json::to_string(&options).context(error::SerializeSnafu)?,
596 );
597 Ok(self)
598 }
599
600 fn validate_compression_options(&self, options: &CompressionOptions) -> Result<()> {
601 options.validate()?;
602 ensure!(
603 !self.data_type.as_arrow_type().is_nested(),
604 error::InvalidCompressionOptionSnafu {
605 msg: format!(
606 "compression options are not supported on column {} of type {}",
607 self.name, self.data_type
608 ),
609 }
610 );
611 if options.encoding == Some(ColumnEncoding::DeltaBinaryPacked) {
612 ensure!(
613 self.data_type.is_timestamp() || self.data_type.as_arrow_type().is_integer(),
614 error::InvalidCompressionOptionSnafu {
615 msg: format!(
616 "encoding delta_binary_packed requires an integer or timestamp column, but column {} is {}",
617 self.name, self.data_type
618 ),
619 }
620 );
621 }
622 Ok(())
623 }
624
625 pub fn extension_type<E>(&self) -> Result<Option<E>>
626 where
627 E: ExtensionType,
628 {
629 let extension_type_name = self.metadata.get(EXTENSION_TYPE_NAME_KEY);
630
631 if extension_type_name.map(|s| s.as_str()) == Some(E::NAME) {
632 let extension_metadata = self.metadata.get(EXTENSION_TYPE_METADATA_KEY);
633 let extension_metadata =
634 E::deserialize_metadata(extension_metadata.map(|s| s.as_str()))
635 .context(ArrowMetadataSnafu)?;
636
637 let extension = E::try_new(&self.data_type.as_arrow_type(), extension_metadata)
638 .context(ArrowMetadataSnafu)?;
639 Ok(Some(extension))
640 } else {
641 Ok(None)
642 }
643 }
644
645 pub fn with_extension_type<E>(&mut self, extension_type: &E)
647 where
648 E: ExtensionType,
649 {
650 self.metadata
651 .insert(EXTENSION_TYPE_NAME_KEY.to_string(), E::NAME.to_string());
652
653 if let Some(extension_metadata) = extension_type.serialize_metadata() {
654 self.metadata
655 .insert(EXTENSION_TYPE_METADATA_KEY.to_string(), extension_metadata);
656 } else {
657 self.metadata.remove(EXTENSION_TYPE_METADATA_KEY);
659 }
660 }
661
662 pub fn is_indexed(&self) -> bool {
663 self.is_inverted_indexed() || self.is_fulltext_indexed() || self.is_skipping_indexed()
664 }
665}
666
667fn metadata_size(metadata: &Metadata) -> usize {
668 mem::size_of::<(String, String)>() * metadata.capacity()
669 + metadata
670 .iter()
671 .map(|(key, value)| key.capacity() + value.capacity())
672 .sum::<usize>()
673}
674
675fn column_default_constraint_size(default_constraint: &ColumnDefaultConstraint) -> usize {
676 match default_constraint {
677 ColumnDefaultConstraint::Function(expr) => expr.capacity(),
678 ColumnDefaultConstraint::Value(value) => value.as_value_ref().data_size(),
679 }
680}
681
682#[derive(Debug, Clone, PartialEq, Eq)]
684pub enum ColumnExtType {
685 Json,
687
688 Vector(u32),
690}
691
692impl fmt::Display for ColumnExtType {
693 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
694 match self {
695 ColumnExtType::Json => write!(f, "Json"),
696 ColumnExtType::Vector(dim) => write!(f, "Vector({})", dim),
697 }
698 }
699}
700
701impl FromStr for ColumnExtType {
702 type Err = String;
703
704 fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
705 match s {
706 "Json" => Ok(ColumnExtType::Json),
707 _ if s.starts_with("Vector(") && s.ends_with(')') => s[7..s.len() - 1]
708 .parse::<u32>()
709 .map(ColumnExtType::Vector)
710 .map_err(|_| "Invalid dimension for Vector".to_string()),
711 _ => Err("Unknown variant".to_string()),
712 }
713 }
714}
715
716impl TryFrom<&Field> for ColumnSchema {
717 type Error = Error;
718
719 fn try_from(field: &Field) -> Result<ColumnSchema> {
720 let mut data_type = ConcreteDataType::try_from(field.data_type())?;
721 if let Some(s) = field.metadata().get(TYPE_KEY) {
723 let extype = ColumnExtType::from_str(s)
724 .map_err(|_| ParseExtendedTypeSnafu { value: s }.build())?;
725 match extype {
726 ColumnExtType::Json => {
727 data_type = ConcreteDataType::json_datatype();
728 }
729 ColumnExtType::Vector(dim) => {
730 data_type = ConcreteDataType::vector_datatype(dim);
731 }
732 }
733 }
734 let mut metadata = field.metadata().clone();
735 let default_constraint = match metadata.remove(DEFAULT_CONSTRAINT_KEY) {
736 Some(json) => {
737 Some(serde_json::from_str(&json).context(error::DeserializeSnafu { json })?)
738 }
739 None => None,
740 };
741 let mut is_time_index = metadata.contains_key(TIME_INDEX_KEY);
742 if is_time_index && !data_type.is_timestamp() {
743 is_time_index = false;
749 metadata.remove(TIME_INDEX_KEY);
750 common_telemetry::debug!(
751 "Column {} is not timestamp ({:?}) but has time index metadata",
752 data_type,
753 field.name(),
754 );
755 }
756
757 Ok(ColumnSchema {
758 name: field.name().clone(),
759 data_type,
760 is_nullable: field.is_nullable(),
761 is_time_index,
762 default_constraint,
763 metadata,
764 })
765 }
766}
767
768impl TryFrom<&ColumnSchema> for Field {
769 type Error = Error;
770
771 fn try_from(column_schema: &ColumnSchema) -> Result<Field> {
772 let mut metadata = column_schema.metadata.clone();
773 if let Some(value) = &column_schema.default_constraint {
774 let old = metadata.insert(
776 DEFAULT_CONSTRAINT_KEY.to_string(),
777 serde_json::to_string(&value).context(error::SerializeSnafu)?,
778 );
779
780 ensure!(
781 old.is_none(),
782 error::DuplicateMetaSnafu {
783 key: DEFAULT_CONSTRAINT_KEY,
784 }
785 );
786 }
787
788 Ok(Field::new(
789 &column_schema.name,
790 column_schema.data_type.as_arrow_type(),
791 column_schema.is_nullable(),
792 )
793 .with_metadata(metadata))
794 }
795}
796
797pub fn metric_name_field_metadata() -> Metadata {
802 let mut metadata = Metadata::new();
803 let _ = metadata.insert(METRIC_NAME_KEY.to_string(), "true".to_string());
804 metadata
805}
806
807pub fn is_metric_name_field(field: &Field) -> bool {
809 field
810 .metadata()
811 .get(METRIC_NAME_KEY)
812 .map(|value| value.eq_ignore_ascii_case("true"))
813 .unwrap_or(false)
814}
815
816#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Visit, VisitMut)]
818#[serde(rename_all = "kebab-case")]
819pub struct FulltextOptions {
820 pub enable: bool,
822 #[serde(default)]
824 pub analyzer: FulltextAnalyzer,
825 #[serde(default)]
827 pub case_sensitive: bool,
828 #[serde(default)]
830 pub backend: FulltextBackend,
831 #[serde(default = "fulltext_options_default_granularity")]
833 pub granularity: u32,
834 #[serde(default = "index_options_default_false_positive_rate_in_10000")]
836 pub false_positive_rate_in_10000: u32,
837}
838
839fn fulltext_options_default_granularity() -> u32 {
840 DEFAULT_GRANULARITY
841}
842
843fn index_options_default_false_positive_rate_in_10000() -> u32 {
844 (DEFAULT_FALSE_POSITIVE_RATE * 10000.0) as u32
845}
846
847impl FulltextOptions {
848 pub fn new(
850 enable: bool,
851 analyzer: FulltextAnalyzer,
852 case_sensitive: bool,
853 backend: FulltextBackend,
854 granularity: u32,
855 false_positive_rate: f64,
856 ) -> Result<Self> {
857 ensure!(
858 0.0 < false_positive_rate && false_positive_rate <= 1.0,
859 error::InvalidFulltextOptionSnafu {
860 msg: format!(
861 "Invalid false positive rate: {false_positive_rate}, expected: 0.0 < rate <= 1.0"
862 ),
863 }
864 );
865 ensure!(
866 granularity > 0,
867 error::InvalidFulltextOptionSnafu {
868 msg: format!("Invalid granularity: {granularity}, expected: positive integer"),
869 }
870 );
871 Ok(Self::new_unchecked(
872 enable,
873 analyzer,
874 case_sensitive,
875 backend,
876 granularity,
877 false_positive_rate,
878 ))
879 }
880
881 pub fn new_unchecked(
883 enable: bool,
884 analyzer: FulltextAnalyzer,
885 case_sensitive: bool,
886 backend: FulltextBackend,
887 granularity: u32,
888 false_positive_rate: f64,
889 ) -> Self {
890 Self {
891 enable,
892 analyzer,
893 case_sensitive,
894 backend,
895 granularity,
896 false_positive_rate_in_10000: (false_positive_rate * 10000.0) as u32,
897 }
898 }
899
900 pub fn false_positive_rate(&self) -> f64 {
902 self.false_positive_rate_in_10000 as f64 / 10000.0
903 }
904}
905
906impl Default for FulltextOptions {
907 fn default() -> Self {
908 Self::new_unchecked(
909 false,
910 FulltextAnalyzer::default(),
911 false,
912 FulltextBackend::default(),
913 DEFAULT_GRANULARITY,
914 DEFAULT_FALSE_POSITIVE_RATE,
915 )
916 }
917}
918
919impl fmt::Display for FulltextOptions {
920 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
921 write!(f, "enable={}", self.enable)?;
922 if self.enable {
923 write!(f, ", analyzer={}", self.analyzer)?;
924 write!(f, ", case_sensitive={}", self.case_sensitive)?;
925 write!(f, ", backend={}", self.backend)?;
926 if self.backend == FulltextBackend::Bloom {
927 write!(f, ", granularity={}", self.granularity)?;
928 write!(f, ", false_positive_rate={}", self.false_positive_rate())?;
929 }
930 }
931 Ok(())
932 }
933}
934
935#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default, Visit, VisitMut)]
937#[serde(rename_all = "kebab-case")]
938pub enum FulltextBackend {
939 #[default]
940 Bloom,
941 Tantivy,
942}
943
944impl fmt::Display for FulltextBackend {
945 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
946 match self {
947 FulltextBackend::Tantivy => write!(f, "tantivy"),
948 FulltextBackend::Bloom => write!(f, "bloom"),
949 }
950 }
951}
952
953impl TryFrom<HashMap<String, String>> for FulltextOptions {
954 type Error = Error;
955
956 fn try_from(options: HashMap<String, String>) -> Result<Self> {
957 let mut fulltext_options = FulltextOptions {
958 enable: true,
959 ..Default::default()
960 };
961
962 if let Some(enable) = options.get(COLUMN_FULLTEXT_CHANGE_OPT_KEY_ENABLE) {
963 match enable.to_ascii_lowercase().as_str() {
964 "true" => fulltext_options.enable = true,
965 "false" => fulltext_options.enable = false,
966 _ => {
967 return InvalidFulltextOptionSnafu {
968 msg: format!("{enable}, expected: 'true' | 'false'"),
969 }
970 .fail();
971 }
972 }
973 };
974
975 if let Some(analyzer) = options.get(COLUMN_FULLTEXT_OPT_KEY_ANALYZER) {
976 match analyzer.to_ascii_lowercase().as_str() {
977 "english" => fulltext_options.analyzer = FulltextAnalyzer::English,
978 "chinese" => fulltext_options.analyzer = FulltextAnalyzer::Chinese,
979 _ => {
980 return InvalidFulltextOptionSnafu {
981 msg: format!("{analyzer}, expected: 'English' | 'Chinese'"),
982 }
983 .fail();
984 }
985 }
986 };
987
988 if let Some(case_sensitive) = options.get(COLUMN_FULLTEXT_OPT_KEY_CASE_SENSITIVE) {
989 match case_sensitive.to_ascii_lowercase().as_str() {
990 "true" => fulltext_options.case_sensitive = true,
991 "false" => fulltext_options.case_sensitive = false,
992 _ => {
993 return InvalidFulltextOptionSnafu {
994 msg: format!("{case_sensitive}, expected: 'true' | 'false'"),
995 }
996 .fail();
997 }
998 }
999 }
1000
1001 if let Some(backend) = options.get(COLUMN_FULLTEXT_OPT_KEY_BACKEND) {
1002 match backend.to_ascii_lowercase().as_str() {
1003 "bloom" => fulltext_options.backend = FulltextBackend::Bloom,
1004 "tantivy" => fulltext_options.backend = FulltextBackend::Tantivy,
1005 _ => {
1006 return InvalidFulltextOptionSnafu {
1007 msg: format!("{backend}, expected: 'bloom' | 'tantivy'"),
1008 }
1009 .fail();
1010 }
1011 }
1012 }
1013
1014 if fulltext_options.backend == FulltextBackend::Bloom {
1015 let granularity = match options.get(COLUMN_FULLTEXT_OPT_KEY_GRANULARITY) {
1017 Some(value) => value
1018 .parse::<u32>()
1019 .ok()
1020 .filter(|&v| v > 0)
1021 .ok_or_else(|| {
1022 error::InvalidFulltextOptionSnafu {
1023 msg: format!(
1024 "Invalid granularity: {value}, expected: positive integer"
1025 ),
1026 }
1027 .build()
1028 })?,
1029 None => DEFAULT_GRANULARITY,
1030 };
1031 fulltext_options.granularity = granularity;
1032
1033 let false_positive_rate = match options.get(COLUMN_FULLTEXT_OPT_KEY_FALSE_POSITIVE_RATE)
1035 {
1036 Some(value) => value
1037 .parse::<f64>()
1038 .ok()
1039 .filter(|&v| v > 0.0 && v <= 1.0)
1040 .ok_or_else(|| {
1041 error::InvalidFulltextOptionSnafu {
1042 msg: format!(
1043 "Invalid false positive rate: {value}, expected: 0.0 < rate <= 1.0"
1044 ),
1045 }
1046 .build()
1047 })?,
1048 None => DEFAULT_FALSE_POSITIVE_RATE,
1049 };
1050 fulltext_options.false_positive_rate_in_10000 = (false_positive_rate * 10000.0) as u32;
1051 }
1052
1053 Ok(fulltext_options)
1054 }
1055}
1056
1057#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default, Visit, VisitMut)]
1059pub enum FulltextAnalyzer {
1060 #[default]
1061 English,
1062 Chinese,
1063}
1064
1065impl fmt::Display for FulltextAnalyzer {
1066 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1067 match self {
1068 FulltextAnalyzer::English => write!(f, "English"),
1069 FulltextAnalyzer::Chinese => write!(f, "Chinese"),
1070 }
1071 }
1072}
1073
1074#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Visit, VisitMut)]
1076#[serde(rename_all = "kebab-case")]
1077pub struct SkippingIndexOptions {
1078 pub granularity: u32,
1080 #[serde(default = "index_options_default_false_positive_rate_in_10000")]
1082 pub false_positive_rate_in_10000: u32,
1083 #[serde(default)]
1085 pub index_type: SkippingIndexType,
1086}
1087
1088impl SkippingIndexOptions {
1089 pub fn new_unchecked(
1091 granularity: u32,
1092 false_positive_rate: f64,
1093 index_type: SkippingIndexType,
1094 ) -> Self {
1095 Self {
1096 granularity,
1097 false_positive_rate_in_10000: (false_positive_rate * 10000.0) as u32,
1098 index_type,
1099 }
1100 }
1101
1102 pub fn new(
1104 granularity: u32,
1105 false_positive_rate: f64,
1106 index_type: SkippingIndexType,
1107 ) -> Result<Self> {
1108 ensure!(
1109 0.0 < false_positive_rate && false_positive_rate <= 1.0,
1110 error::InvalidSkippingIndexOptionSnafu {
1111 msg: format!(
1112 "Invalid false positive rate: {false_positive_rate}, expected: 0.0 < rate <= 1.0"
1113 ),
1114 }
1115 );
1116 ensure!(
1117 granularity > 0,
1118 error::InvalidSkippingIndexOptionSnafu {
1119 msg: format!("Invalid granularity: {granularity}, expected: positive integer"),
1120 }
1121 );
1122 Ok(Self::new_unchecked(
1123 granularity,
1124 false_positive_rate,
1125 index_type,
1126 ))
1127 }
1128
1129 pub fn false_positive_rate(&self) -> f64 {
1131 self.false_positive_rate_in_10000 as f64 / 10000.0
1132 }
1133}
1134
1135impl Default for SkippingIndexOptions {
1136 fn default() -> Self {
1137 Self::new_unchecked(
1138 DEFAULT_GRANULARITY,
1139 DEFAULT_FALSE_POSITIVE_RATE,
1140 SkippingIndexType::default(),
1141 )
1142 }
1143}
1144
1145impl fmt::Display for SkippingIndexOptions {
1146 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1147 write!(f, "granularity={}", self.granularity)?;
1148 write!(f, ", false_positive_rate={}", self.false_positive_rate())?;
1149 write!(f, ", index_type={}", self.index_type)?;
1150 Ok(())
1151 }
1152}
1153
1154#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize, Visit, VisitMut)]
1156pub enum SkippingIndexType {
1157 #[default]
1158 BloomFilter,
1159}
1160
1161impl fmt::Display for SkippingIndexType {
1162 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1163 match self {
1164 SkippingIndexType::BloomFilter => write!(f, "BLOOM"),
1165 }
1166 }
1167}
1168
1169#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1171#[serde(rename_all = "snake_case")]
1172pub enum CompressionType {
1173 #[default]
1174 Zstd,
1175}
1176
1177impl fmt::Display for CompressionType {
1178 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1179 match self {
1180 CompressionType::Zstd => write!(f, "zstd"),
1181 }
1182 }
1183}
1184
1185#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1187#[serde(rename_all = "snake_case")]
1188pub enum ColumnEncoding {
1189 Plain,
1190 DeltaBinaryPacked,
1192}
1193
1194impl fmt::Display for ColumnEncoding {
1195 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1196 match self {
1197 ColumnEncoding::Plain => write!(f, "plain"),
1198 ColumnEncoding::DeltaBinaryPacked => write!(f, "delta_binary_packed"),
1199 }
1200 }
1201}
1202
1203#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1205pub struct CompressionOptions {
1206 #[serde(rename = "type", default)]
1207 pub compression_type: CompressionType,
1208 #[serde(default, skip_serializing_if = "Option::is_none")]
1209 pub level: Option<i32>,
1210 #[serde(default, skip_serializing_if = "Option::is_none")]
1211 pub page_size: Option<ReadableSize>,
1212 #[serde(default, skip_serializing_if = "Option::is_none")]
1213 pub encoding: Option<ColumnEncoding>,
1214}
1215
1216impl CompressionOptions {
1217 fn validate(&self) -> Result<()> {
1218 if let Some(level) = self.level {
1219 ensure!(
1220 ZSTD_LEVELS.contains(&level),
1221 error::InvalidCompressionOptionSnafu {
1222 msg: format!("invalid level: {level}, expected: an integer in 1..=22"),
1223 }
1224 );
1225 }
1226 if let Some(page_size) = self.page_size {
1227 ensure!(
1228 page_size.as_bytes() > 0,
1229 error::InvalidCompressionOptionSnafu {
1230 msg: "page_size must be positive",
1231 }
1232 );
1233 }
1234 Ok(())
1235 }
1236
1237 pub fn to_options_map(&self) -> HashMap<String, String> {
1239 let mut map = HashMap::from([(
1240 COLUMN_COMPRESSION_OPT_KEY_TYPE.to_string(),
1241 self.compression_type.to_string(),
1242 )]);
1243 if let Some(level) = self.level {
1244 map.insert(
1245 COLUMN_COMPRESSION_OPT_KEY_LEVEL.to_string(),
1246 level.to_string(),
1247 );
1248 }
1249 if let Some(page_size) = self.page_size {
1250 let page_size = match serde_json::to_value(page_size) {
1252 Ok(serde_json::Value::String(size)) => size,
1253 _ => page_size.as_bytes().to_string(),
1254 };
1255 map.insert(COLUMN_COMPRESSION_OPT_KEY_PAGE_SIZE.to_string(), page_size);
1256 }
1257 if let Some(encoding) = self.encoding {
1258 map.insert(
1259 COLUMN_COMPRESSION_OPT_KEY_ENCODING.to_string(),
1260 encoding.to_string(),
1261 );
1262 }
1263 map
1264 }
1265}
1266
1267const ZSTD_LEVELS: std::ops::RangeInclusive<i32> = 1..=22;
1269
1270impl TryFrom<HashMap<String, String>> for CompressionOptions {
1271 type Error = Error;
1272
1273 fn try_from(options: HashMap<String, String>) -> Result<Self> {
1274 let compression_type = match options.get(COLUMN_COMPRESSION_OPT_KEY_TYPE) {
1275 Some(value) if value.eq_ignore_ascii_case("zstd") => CompressionType::Zstd,
1276 Some(value) => {
1277 return error::InvalidCompressionOptionSnafu {
1278 msg: format!("invalid type: {value}, expected: 'zstd'"),
1279 }
1280 .fail();
1281 }
1282 None => CompressionType::default(),
1283 };
1284
1285 let level = options
1286 .get(COLUMN_COMPRESSION_OPT_KEY_LEVEL)
1287 .map(|value| {
1288 value
1289 .parse::<i32>()
1290 .ok()
1291 .filter(|level| ZSTD_LEVELS.contains(level))
1292 .ok_or_else(|| {
1293 error::InvalidCompressionOptionSnafu {
1294 msg: format!(
1295 "invalid level: {value}, expected: an integer in {}..={}",
1296 ZSTD_LEVELS.start(),
1297 ZSTD_LEVELS.end()
1298 ),
1299 }
1300 .build()
1301 })
1302 })
1303 .transpose()?;
1304
1305 let page_size = options
1306 .get(COLUMN_COMPRESSION_OPT_KEY_PAGE_SIZE)
1307 .map(|value| {
1308 ReadableSize::from_str(value)
1309 .ok()
1310 .filter(|size| size.as_bytes() > 0)
1311 .ok_or_else(|| {
1312 error::InvalidCompressionOptionSnafu {
1313 msg: format!(
1314 "invalid page_size: {value}, expected: a positive size such as '8MiB'"
1315 ),
1316 }
1317 .build()
1318 })
1319 })
1320 .transpose()?;
1321
1322 let encoding = options
1323 .get(COLUMN_COMPRESSION_OPT_KEY_ENCODING)
1324 .map(|value| match value.to_ascii_lowercase().as_str() {
1325 "plain" => Ok(ColumnEncoding::Plain),
1326 "delta_binary_packed" => Ok(ColumnEncoding::DeltaBinaryPacked),
1327 _ => error::InvalidCompressionOptionSnafu {
1328 msg: format!(
1329 "invalid encoding: {value}, expected: 'plain' or 'delta_binary_packed'"
1330 ),
1331 }
1332 .fail(),
1333 })
1334 .transpose()?;
1335
1336 Ok(CompressionOptions {
1337 compression_type,
1338 level,
1339 page_size,
1340 encoding,
1341 })
1342 }
1343}
1344
1345impl TryFrom<HashMap<String, String>> for SkippingIndexOptions {
1346 type Error = Error;
1347
1348 fn try_from(options: HashMap<String, String>) -> Result<Self> {
1349 let granularity = match options.get(COLUMN_SKIPPING_INDEX_OPT_KEY_GRANULARITY) {
1351 Some(value) => value
1352 .parse::<u32>()
1353 .ok()
1354 .filter(|&v| v > 0)
1355 .ok_or_else(|| {
1356 error::InvalidSkippingIndexOptionSnafu {
1357 msg: format!("Invalid granularity: {value}, expected: positive integer"),
1358 }
1359 .build()
1360 })?,
1361 None => DEFAULT_GRANULARITY,
1362 };
1363
1364 let false_positive_rate =
1366 match options.get(COLUMN_SKIPPING_INDEX_OPT_KEY_FALSE_POSITIVE_RATE) {
1367 Some(value) => value
1368 .parse::<f64>()
1369 .ok()
1370 .filter(|&v| v > 0.0 && v <= 1.0)
1371 .ok_or_else(|| {
1372 error::InvalidSkippingIndexOptionSnafu {
1373 msg: format!(
1374 "Invalid false positive rate: {value}, expected: 0.0 < rate <= 1.0"
1375 ),
1376 }
1377 .build()
1378 })?,
1379 None => DEFAULT_FALSE_POSITIVE_RATE,
1380 };
1381
1382 let index_type = match options.get(COLUMN_SKIPPING_INDEX_OPT_KEY_TYPE) {
1384 Some(typ) => match typ.to_ascii_uppercase().as_str() {
1385 "BLOOM" => SkippingIndexType::BloomFilter,
1386 _ => {
1387 return error::InvalidSkippingIndexOptionSnafu {
1388 msg: format!("Invalid index type: {typ}, expected: 'BLOOM'"),
1389 }
1390 .fail();
1391 }
1392 },
1393 None => SkippingIndexType::default(),
1394 };
1395
1396 Ok(SkippingIndexOptions::new_unchecked(
1397 granularity,
1398 false_positive_rate,
1399 index_type,
1400 ))
1401 }
1402}
1403
1404#[cfg(test)]
1405mod tests {
1406 use std::sync::Arc;
1407
1408 use arrow::datatypes::{DataType as ArrowDataType, TimeUnit};
1409
1410 use super::*;
1411 use crate::extension::json::{Json2ExtensionType, JsonExtensionType};
1412 use crate::types::{StructField, StructType};
1413 use crate::value::Value;
1414 use crate::vectors::Int32Vector;
1415
1416 #[test]
1417 fn test_column_schema() {
1418 let column_schema = ColumnSchema::new("test", ConcreteDataType::int32_datatype(), true);
1419 let field = Field::try_from(&column_schema).unwrap();
1420 assert_eq!("test", field.name());
1421 assert_eq!(ArrowDataType::Int32, *field.data_type());
1422 assert!(field.is_nullable());
1423
1424 let new_column_schema = ColumnSchema::try_from(&field).unwrap();
1425 assert_eq!(column_schema, new_column_schema);
1426 }
1427
1428 #[test]
1429 fn test_with_extension_type_replaces_metadata() {
1430 let mut schema = ColumnSchema::new("j", ConcreteDataType::json_datatype(), true);
1431
1432 schema.with_extension_type(&Json2ExtensionType::default());
1433 assert_eq!(
1434 Some(Json2ExtensionType::NAME),
1435 schema
1436 .metadata()
1437 .get(EXTENSION_TYPE_NAME_KEY)
1438 .map(String::as_str)
1439 );
1440 assert!(schema.metadata().contains_key(EXTENSION_TYPE_METADATA_KEY));
1441
1442 schema.with_extension_type(&JsonExtensionType);
1443 assert_eq!(
1444 Some(JsonExtensionType::NAME),
1445 schema
1446 .metadata()
1447 .get(EXTENSION_TYPE_NAME_KEY)
1448 .map(String::as_str)
1449 );
1450 assert!(!schema.metadata().contains_key(EXTENSION_TYPE_METADATA_KEY));
1451 }
1452
1453 #[test]
1454 fn test_column_schema_with_default_constraint() {
1455 let column_schema = ColumnSchema::new("test", ConcreteDataType::int32_datatype(), true)
1456 .with_default_constraint(Some(ColumnDefaultConstraint::Value(Value::from(99))))
1457 .unwrap();
1458 assert!(
1459 column_schema
1460 .metadata()
1461 .get(DEFAULT_CONSTRAINT_KEY)
1462 .is_none()
1463 );
1464
1465 let field = Field::try_from(&column_schema).unwrap();
1466 assert_eq!("test", field.name());
1467 assert_eq!(ArrowDataType::Int32, *field.data_type());
1468 assert!(field.is_nullable());
1469 assert_eq!(
1470 "{\"Value\":{\"Int32\":99}}",
1471 field.metadata().get(DEFAULT_CONSTRAINT_KEY).unwrap()
1472 );
1473
1474 let new_column_schema = ColumnSchema::try_from(&field).unwrap();
1475 assert_eq!(column_schema, new_column_schema);
1476 }
1477
1478 #[test]
1479 fn test_column_schema_with_metadata() {
1480 let metadata = Metadata::from([
1481 ("k1".to_string(), "v1".to_string()),
1482 (COMMENT_KEY.to_string(), "test comment".to_string()),
1483 ]);
1484 let column_schema = ColumnSchema::new("test", ConcreteDataType::int32_datatype(), true)
1485 .with_metadata(metadata)
1486 .with_default_constraint(Some(ColumnDefaultConstraint::null_value()))
1487 .unwrap();
1488 assert_eq!("v1", column_schema.metadata().get("k1").unwrap());
1489 assert_eq!("test comment", column_schema.column_comment().unwrap());
1490 assert!(
1491 column_schema
1492 .metadata()
1493 .get(DEFAULT_CONSTRAINT_KEY)
1494 .is_none()
1495 );
1496
1497 let field = Field::try_from(&column_schema).unwrap();
1498 assert_eq!("v1", field.metadata().get("k1").unwrap());
1499 let _ = field.metadata().get(DEFAULT_CONSTRAINT_KEY).unwrap();
1500
1501 let new_column_schema = ColumnSchema::try_from(&field).unwrap();
1502 assert_eq!(column_schema, new_column_schema);
1503 }
1504
1505 #[test]
1506 fn test_column_schema_preserves_sketch_metadata() {
1507 let metadata = Metadata::from([
1508 (
1509 "greptime:hll".to_string(),
1510 r#"{"precision":10}"#.to_string(),
1511 ),
1512 ("greptime:kll".to_string(), r#"{"capacity":64}"#.to_string()),
1513 (
1514 "greptime:mg".to_string(),
1515 r#"{"max-counters":64}"#.to_string(),
1516 ),
1517 ]);
1518 let column = ColumnSchema::new("v", ConcreteDataType::int64_datatype(), true)
1519 .with_metadata(metadata.clone());
1520 let field = Field::try_from(&column).unwrap();
1521 assert_eq!(&metadata, field.metadata());
1522 assert_eq!(column, ColumnSchema::try_from(&field).unwrap());
1523 assert_eq!(
1524 column,
1525 serde_json::from_str::<ColumnSchema>(&serde_json::to_string(&column).unwrap()).unwrap()
1526 );
1527 }
1528
1529 #[test]
1530 fn test_column_schema_with_duplicate_metadata() {
1531 let metadata = Metadata::from([(DEFAULT_CONSTRAINT_KEY.to_string(), "v1".to_string())]);
1532 let column_schema = ColumnSchema::new("test", ConcreteDataType::int32_datatype(), true)
1533 .with_metadata(metadata)
1534 .with_default_constraint(Some(ColumnDefaultConstraint::null_value()))
1535 .unwrap();
1536 assert!(Field::try_from(&column_schema).is_err());
1537 }
1538
1539 #[test]
1540 fn test_column_schema_invalid_default_constraint() {
1541 assert!(
1542 ColumnSchema::new("test", ConcreteDataType::int32_datatype(), false)
1543 .with_default_constraint(Some(ColumnDefaultConstraint::null_value()))
1544 .is_err()
1545 );
1546 }
1547
1548 #[test]
1549 fn test_column_default_constraint_try_into_from() {
1550 let default_constraint = ColumnDefaultConstraint::Value(Value::from(42i64));
1551
1552 let bytes: Vec<u8> = default_constraint.clone().try_into().unwrap();
1553 let from_value = ColumnDefaultConstraint::try_from(&bytes[..]).unwrap();
1554
1555 assert_eq!(default_constraint, from_value);
1556 }
1557
1558 #[test]
1559 fn test_column_schema_create_default_null() {
1560 let column_schema = ColumnSchema::new("test", ConcreteDataType::int32_datatype(), true);
1562 let v = column_schema.create_default_vector(5).unwrap().unwrap();
1563 assert_eq!(5, v.len());
1564 assert!(v.only_null());
1565
1566 let column_schema = ColumnSchema::new("test", ConcreteDataType::int32_datatype(), true)
1568 .with_default_constraint(Some(ColumnDefaultConstraint::null_value()))
1569 .unwrap();
1570 let v = column_schema.create_default_vector(5).unwrap().unwrap();
1571 assert_eq!(5, v.len());
1572 assert!(v.only_null());
1573 }
1574
1575 #[test]
1576 fn test_column_schema_create_default_null_struct_with_list() {
1577 let list_type =
1578 ConcreteDataType::list_datatype(Arc::new(ConcreteDataType::int32_datatype()));
1579 let struct_type =
1580 ConcreteDataType::struct_datatype(StructType::new(Arc::new(vec![StructField::new(
1581 "values".to_string(),
1582 list_type,
1583 true,
1584 )])));
1585 let column_schema = ColumnSchema::new("test", struct_type, true);
1586
1587 let v = column_schema.create_default_vector(5).unwrap().unwrap();
1588
1589 assert_eq!(5, v.len());
1590 assert!(v.only_null());
1591 }
1592
1593 #[test]
1594 fn test_column_schema_no_default() {
1595 let column_schema = ColumnSchema::new("test", ConcreteDataType::int32_datatype(), false);
1596 assert!(column_schema.create_default_vector(5).unwrap().is_none());
1597 }
1598
1599 #[test]
1600 fn test_create_default_vector_for_padding() {
1601 let column_schema = ColumnSchema::new("test", ConcreteDataType::int32_datatype(), true);
1602 let vector = column_schema.create_default_vector_for_padding(4);
1603 assert!(vector.only_null());
1604 assert_eq!(4, vector.len());
1605
1606 let column_schema = ColumnSchema::new("test", ConcreteDataType::int32_datatype(), false);
1607 let vector = column_schema.create_default_vector_for_padding(4);
1608 assert_eq!(4, vector.len());
1609 let expect: VectorRef = Arc::new(Int32Vector::from_slice([0, 0, 0, 0]));
1610 assert_eq!(expect, vector);
1611 }
1612
1613 #[test]
1614 fn test_column_schema_single_create_default_null() {
1615 let column_schema = ColumnSchema::new("test", ConcreteDataType::int32_datatype(), true);
1617 let v = column_schema.create_default().unwrap().unwrap();
1618 assert!(v.is_null());
1619
1620 let column_schema = ColumnSchema::new("test", ConcreteDataType::int32_datatype(), true)
1622 .with_default_constraint(Some(ColumnDefaultConstraint::null_value()))
1623 .unwrap();
1624 let v = column_schema.create_default().unwrap().unwrap();
1625 assert!(v.is_null());
1626 }
1627
1628 #[test]
1629 fn test_column_schema_single_create_default_not_null() {
1630 let column_schema = ColumnSchema::new("test", ConcreteDataType::int32_datatype(), true)
1631 .with_default_constraint(Some(ColumnDefaultConstraint::Value(Value::Int32(6))))
1632 .unwrap();
1633 let v = column_schema.create_default().unwrap().unwrap();
1634 assert_eq!(v, Value::Int32(6));
1635 }
1636
1637 #[test]
1638 fn test_column_schema_single_no_default() {
1639 let column_schema = ColumnSchema::new("test", ConcreteDataType::int32_datatype(), false);
1640 assert!(column_schema.create_default().unwrap().is_none());
1641 }
1642
1643 #[test]
1644 fn test_debug_for_column_schema() {
1645 let column_schema_int8 =
1646 ColumnSchema::new("test_column_1", ConcreteDataType::int8_datatype(), true);
1647
1648 let column_schema_int32 =
1649 ColumnSchema::new("test_column_2", ConcreteDataType::int32_datatype(), false);
1650
1651 let formatted_int8 = format!("{:?}", column_schema_int8);
1652 let formatted_int32 = format!("{:?}", column_schema_int32);
1653 assert_eq!(formatted_int8, "test_column_1 Int8 null");
1654 assert_eq!(formatted_int32, "test_column_2 Int32 not null");
1655 }
1656
1657 #[test]
1658 fn test_from_field_to_column_schema() {
1659 let field = Field::new("test", ArrowDataType::Int32, true);
1660 let column_schema = ColumnSchema::try_from(&field).unwrap();
1661 assert_eq!("test", column_schema.name);
1662 assert_eq!(ConcreteDataType::int32_datatype(), column_schema.data_type);
1663 assert!(column_schema.is_nullable);
1664 assert!(!column_schema.is_time_index);
1665 assert!(column_schema.default_constraint.is_none());
1666 assert!(column_schema.metadata.is_empty());
1667
1668 let field = Field::new("test", ArrowDataType::Binary, true);
1669 let field = field.with_metadata(Metadata::from([(
1670 TYPE_KEY.to_string(),
1671 ConcreteDataType::json_datatype().name(),
1672 )]));
1673 let column_schema = ColumnSchema::try_from(&field).unwrap();
1674 assert_eq!("test", column_schema.name);
1675 assert_eq!(ConcreteDataType::json_datatype(), column_schema.data_type);
1676 assert!(column_schema.is_nullable);
1677 assert!(!column_schema.is_time_index);
1678 assert!(column_schema.default_constraint.is_none());
1679 assert_eq!(
1680 column_schema.metadata.get(TYPE_KEY).unwrap(),
1681 &ConcreteDataType::json_datatype().name()
1682 );
1683
1684 let field = Field::new("test", ArrowDataType::Binary, true);
1685 let field = field.with_metadata(Metadata::from([(
1686 TYPE_KEY.to_string(),
1687 ConcreteDataType::vector_datatype(3).name(),
1688 )]));
1689 let column_schema = ColumnSchema::try_from(&field).unwrap();
1690 assert_eq!("test", column_schema.name);
1691 assert_eq!(
1692 ConcreteDataType::vector_datatype(3),
1693 column_schema.data_type
1694 );
1695 assert!(column_schema.is_nullable);
1696 assert!(!column_schema.is_time_index);
1697 assert!(column_schema.default_constraint.is_none());
1698 assert_eq!(
1699 column_schema.metadata.get(TYPE_KEY).unwrap(),
1700 &ConcreteDataType::vector_datatype(3).name()
1701 );
1702 }
1703
1704 #[test]
1705 fn test_column_schema_fix_time_index() {
1706 let field = Field::new(
1707 "test",
1708 ArrowDataType::Timestamp(TimeUnit::Second, None),
1709 false,
1710 );
1711 let field = field.with_metadata(Metadata::from([(
1712 TIME_INDEX_KEY.to_string(),
1713 "true".to_string(),
1714 )]));
1715 let column_schema = ColumnSchema::try_from(&field).unwrap();
1716 assert_eq!("test", column_schema.name);
1717 assert_eq!(
1718 ConcreteDataType::timestamp_second_datatype(),
1719 column_schema.data_type
1720 );
1721 assert!(!column_schema.is_nullable);
1722 assert!(column_schema.is_time_index);
1723 assert!(column_schema.default_constraint.is_none());
1724 assert_eq!(1, column_schema.metadata().len());
1725
1726 let field = Field::new("test", ArrowDataType::Int32, false);
1727 let field = field.with_metadata(Metadata::from([(
1728 TIME_INDEX_KEY.to_string(),
1729 "true".to_string(),
1730 )]));
1731 let column_schema = ColumnSchema::try_from(&field).unwrap();
1732 assert_eq!("test", column_schema.name);
1733 assert_eq!(ConcreteDataType::int32_datatype(), column_schema.data_type);
1734 assert!(!column_schema.is_nullable);
1735 assert!(!column_schema.is_time_index);
1736 assert!(column_schema.default_constraint.is_none());
1737 assert!(column_schema.metadata.is_empty());
1738 }
1739
1740 #[test]
1741 fn test_compression_options_from_map() {
1742 let parse = |pairs: &[(&str, &str)]| {
1743 CompressionOptions::try_from(
1744 pairs
1745 .iter()
1746 .map(|(k, v)| (k.to_string(), v.to_string()))
1747 .collect::<HashMap<_, _>>(),
1748 )
1749 };
1750
1751 let options = parse(&[("type", "ZSTD"), ("level", "3"), ("page_size", "8MiB")]).unwrap();
1752 assert_eq!(
1753 CompressionOptions {
1754 compression_type: CompressionType::Zstd,
1755 level: Some(3),
1756 page_size: Some(ReadableSize::mb(8)),
1757 encoding: None,
1758 },
1759 options
1760 );
1761 assert_eq!(
1763 r#"{"type":"zstd","level":3,"page_size":"8MiB"}"#,
1764 serde_json::to_string(&options).unwrap()
1765 );
1766 assert_eq!(
1767 options,
1768 parse(
1769 &options
1770 .to_options_map()
1771 .iter()
1772 .map(|(k, v)| (k.as_str(), v.as_str()))
1773 .collect::<Vec<_>>()
1774 )
1775 .unwrap()
1776 );
1777
1778 let odd_size = parse(&[("page_size", "1.25MiB")]).unwrap();
1779 assert_eq!(
1780 odd_size,
1781 parse(&[("page_size", odd_size.to_options_map()["page_size"].as_str())]).unwrap()
1782 );
1783
1784 let page_only = parse(&[("page_size", "1MiB")]).unwrap();
1785 assert_eq!(None, page_only.level);
1786 assert_eq!(
1787 r#"{"type":"zstd","page_size":"1MiB"}"#,
1788 serde_json::to_string(&page_only).unwrap()
1789 );
1790
1791 let delta = parse(&[("encoding", "DELTA_BINARY_PACKED")]).unwrap();
1792 assert_eq!(Some(ColumnEncoding::DeltaBinaryPacked), delta.encoding);
1793 assert_eq!(
1794 r#"{"type":"zstd","encoding":"delta_binary_packed"}"#,
1795 serde_json::to_string(&delta).unwrap()
1796 );
1797 assert_eq!(
1798 delta,
1799 parse(&[("encoding", delta.to_options_map()["encoding"].as_str())]).unwrap()
1800 );
1801
1802 for invalid in [
1803 &[("type", "lz4")][..],
1804 &[("level", "0")],
1805 &[("level", "23")],
1806 &[("level", "high")],
1807 &[("page_size", "0")],
1808 &[("page_size", "large")],
1809 &[("encoding", "dictionary")],
1810 ] {
1811 assert!(parse(invalid).is_err(), "{invalid:?}");
1812 }
1813 }
1814
1815 #[test]
1816 fn test_compression_options_reject_nested_types() {
1817 let options = CompressionOptions {
1818 level: Some(3),
1819 ..Default::default()
1820 };
1821 let string_column = ColumnSchema::new("s", ConcreteDataType::string_datatype(), true)
1822 .with_compression_options(options)
1823 .unwrap();
1824 assert_eq!(Some(options), string_column.compression_options().unwrap());
1825
1826 let struct_type =
1827 ConcreteDataType::struct_datatype(StructType::new(Arc::new(vec![StructField::new(
1828 "a".to_string(),
1829 ConcreteDataType::string_datatype(),
1830 true,
1831 )])));
1832 let list_type =
1833 ConcreteDataType::list_datatype(Arc::new(ConcreteDataType::string_datatype()));
1834 for data_type in [struct_type, list_type] {
1835 assert!(
1836 ColumnSchema::new("n", data_type, true)
1837 .with_compression_options(options)
1838 .is_err()
1839 );
1840 }
1841 }
1842
1843 #[test]
1844 fn test_delta_encoding_requires_integer_or_timestamp() {
1845 let options = CompressionOptions {
1846 encoding: Some(ColumnEncoding::DeltaBinaryPacked),
1847 ..Default::default()
1848 };
1849 for data_type in [
1850 ConcreteDataType::int32_datatype(),
1851 ConcreteDataType::uint64_datatype(),
1852 ConcreteDataType::timestamp_nanosecond_datatype(),
1853 ] {
1854 assert!(
1855 ColumnSchema::new("c", data_type, true)
1856 .with_compression_options(options)
1857 .is_ok()
1858 );
1859 }
1860 for data_type in [
1861 ConcreteDataType::string_datatype(),
1862 ConcreteDataType::float64_datatype(),
1863 ] {
1864 assert!(
1865 ColumnSchema::new("c", data_type, true)
1866 .with_compression_options(options)
1867 .is_err()
1868 );
1869 }
1870 }
1871
1872 #[test]
1873 fn test_skipping_index_options_deserialization() {
1874 let original_options = "{\"granularity\":1024,\"false-positive-rate-in-10000\":10,\"index-type\":\"BloomFilter\"}";
1875 let options = serde_json::from_str::<SkippingIndexOptions>(original_options).unwrap();
1876 assert_eq!(1024, options.granularity);
1877 assert_eq!(SkippingIndexType::BloomFilter, options.index_type);
1878 assert_eq!(0.001, options.false_positive_rate());
1879
1880 let options_str = serde_json::to_string(&options).unwrap();
1881 assert_eq!(options_str, original_options);
1882 }
1883
1884 #[test]
1885 fn test_skipping_index_options_deserialization_v0_14_to_v0_15() {
1886 let options = "{\"granularity\":10240,\"index-type\":\"BloomFilter\"}";
1887 let options = serde_json::from_str::<SkippingIndexOptions>(options).unwrap();
1888 assert_eq!(10240, options.granularity);
1889 assert_eq!(SkippingIndexType::BloomFilter, options.index_type);
1890 assert_eq!(DEFAULT_FALSE_POSITIVE_RATE, options.false_positive_rate());
1891
1892 let options_str = serde_json::to_string(&options).unwrap();
1893 assert_eq!(
1894 options_str,
1895 "{\"granularity\":10240,\"false-positive-rate-in-10000\":100,\"index-type\":\"BloomFilter\"}"
1896 );
1897 }
1898
1899 #[test]
1900 fn test_fulltext_options_deserialization() {
1901 let original_options = "{\"enable\":true,\"analyzer\":\"English\",\"case-sensitive\":false,\"backend\":\"bloom\",\"granularity\":1024,\"false-positive-rate-in-10000\":10}";
1902 let options = serde_json::from_str::<FulltextOptions>(original_options).unwrap();
1903 assert!(!options.case_sensitive);
1904 assert!(options.enable);
1905 assert_eq!(FulltextBackend::Bloom, options.backend);
1906 assert_eq!(FulltextAnalyzer::default(), options.analyzer);
1907 assert_eq!(1024, options.granularity);
1908 assert_eq!(0.001, options.false_positive_rate());
1909
1910 let options_str = serde_json::to_string(&options).unwrap();
1911 assert_eq!(options_str, original_options);
1912 }
1913
1914 #[test]
1915 fn test_fulltext_options_deserialization_v0_14_to_v0_15() {
1916 let options = "{\"enable\":true,\"analyzer\":\"English\",\"case-sensitive\":false,\"backend\":\"bloom\"}";
1918 let options = serde_json::from_str::<FulltextOptions>(options).unwrap();
1919 assert!(!options.case_sensitive);
1920 assert!(options.enable);
1921 assert_eq!(FulltextBackend::Bloom, options.backend);
1922 assert_eq!(FulltextAnalyzer::default(), options.analyzer);
1923 assert_eq!(DEFAULT_GRANULARITY, options.granularity);
1924 assert_eq!(DEFAULT_FALSE_POSITIVE_RATE, options.false_positive_rate());
1925
1926 let options_str = serde_json::to_string(&options).unwrap();
1927 assert_eq!(
1928 options_str,
1929 "{\"enable\":true,\"analyzer\":\"English\",\"case-sensitive\":false,\"backend\":\"bloom\",\"granularity\":10240,\"false-positive-rate-in-10000\":100}"
1930 );
1931 }
1932}