Skip to main content

datatypes/
schema.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
15mod column_schema;
16pub mod constraint;
17pub mod ext;
18#[cfg(feature = "enterprise")]
19mod sketch;
20
21use std::collections::HashMap;
22use std::sync::Arc;
23use std::{fmt, mem};
24
25use arrow::datatypes::{Field, Schema as ArrowSchema};
26use datafusion_common::DFSchemaRef;
27use serde::{Deserialize, Deserializer, Serialize};
28use snafu::{ResultExt, ensure};
29
30use crate::error::{self, DuplicateColumnSnafu, Error, ProjectArrowSchemaSnafu, Result};
31use crate::prelude::ConcreteDataType;
32pub use crate::schema::column_schema::{
33    COLUMN_COMPRESSION_OPT_KEY_ENCODING, COLUMN_COMPRESSION_OPT_KEY_LEVEL,
34    COLUMN_COMPRESSION_OPT_KEY_PAGE_SIZE, COLUMN_COMPRESSION_OPT_KEY_TYPE,
35    COLUMN_FULLTEXT_CHANGE_OPT_KEY_ENABLE, COLUMN_FULLTEXT_OPT_KEY_ANALYZER,
36    COLUMN_FULLTEXT_OPT_KEY_BACKEND, COLUMN_FULLTEXT_OPT_KEY_CASE_SENSITIVE,
37    COLUMN_FULLTEXT_OPT_KEY_FALSE_POSITIVE_RATE, COLUMN_FULLTEXT_OPT_KEY_GRANULARITY,
38    COLUMN_SKIPPING_INDEX_OPT_KEY_FALSE_POSITIVE_RATE, COLUMN_SKIPPING_INDEX_OPT_KEY_GRANULARITY,
39    COLUMN_SKIPPING_INDEX_OPT_KEY_TYPE, COMMENT_KEY, COMPRESSION_KEY, ColumnEncoding,
40    ColumnExtType, ColumnSchema, CompressionOptions, CompressionType, FULLTEXT_KEY,
41    FulltextAnalyzer, FulltextBackend, FulltextOptions, HLL_KEY, INVERTED_INDEX_KEY, KLL_KEY,
42    METRIC_NAME_KEY, MG_KEY, Metadata, SKIPPING_INDEX_KEY, SkippingIndexOptions, SkippingIndexType,
43    TIME_INDEX_KEY, is_metric_name_field, metric_name_field_metadata,
44};
45pub use crate::schema::constraint::ColumnDefaultConstraint;
46#[cfg(feature = "enterprise")]
47pub use crate::schema::sketch::{HllOptions, KllOptions, MgOptions};
48
49/// Key used to store version number of the schema in metadata.
50pub const VERSION_KEY: &str = "greptime:version";
51/// Key used to store actual column type in field metadata.
52pub const TYPE_KEY: &str = "greptime:type";
53
54/// A common schema, should be immutable.
55#[derive(Clone, PartialEq, Eq, Serialize)]
56pub struct Schema {
57    column_schemas: Vec<ColumnSchema>,
58    #[serde(skip_serializing)]
59    name_to_index: HashMap<String, usize>,
60    #[serde(skip_serializing)]
61    arrow_schema: Arc<ArrowSchema>,
62    /// Index of the timestamp key column.
63    ///
64    /// Timestamp key column is the column holds the timestamp and forms part of
65    /// the primary key. None means there is no timestamp key column.
66    #[serde(skip_serializing)]
67    timestamp_index: Option<usize>,
68    /// Version of the schema.
69    ///
70    /// Initial value is zero. The version should bump after altering schema.
71    version: u32,
72}
73
74impl<'de> Deserialize<'de> for Schema {
75    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
76    where
77        D: Deserializer<'de>,
78    {
79        use serde::de::Error;
80
81        #[derive(Deserialize)]
82        struct RawSchema {
83            column_schemas: Vec<ColumnSchema>,
84            version: u32,
85        }
86        let raw = RawSchema::deserialize(deserializer)?;
87
88        SchemaBuilder::try_from(raw.column_schemas)
89            .and_then(|x| x.version(raw.version).build())
90            .map_err(D::Error::custom)
91    }
92}
93
94impl fmt::Debug for Schema {
95    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
96        f.debug_struct("Schema")
97            .field("column_schemas", &self.column_schemas)
98            .field("name_to_index", &self.name_to_index)
99            .field("timestamp_index", &self.timestamp_index)
100            .field("version", &self.version)
101            .finish()
102    }
103}
104
105impl Schema {
106    /// Initial version of the schema.
107    pub const INITIAL_VERSION: u32 = 0;
108
109    /// Create a schema from a vector of [ColumnSchema].
110    ///
111    /// # Panics
112    /// Panics when ColumnSchema's `default_constraint` can't be serialized into json.
113    pub fn new(column_schemas: Vec<ColumnSchema>) -> Schema {
114        // Builder won't fail in this case
115        Self::new_with_version(column_schemas, Self::INITIAL_VERSION)
116    }
117
118    pub fn new_with_version(column_schemas: Vec<ColumnSchema>, version: u32) -> Schema {
119        SchemaBuilder::try_from(column_schemas)
120            .unwrap()
121            .version(version)
122            .build()
123            .unwrap()
124    }
125
126    /// Try to Create a schema from a vector of [ColumnSchema].
127    pub fn try_new(column_schemas: Vec<ColumnSchema>) -> Result<Schema> {
128        SchemaBuilder::try_from(column_schemas)?.build()
129    }
130
131    pub fn arrow_schema(&self) -> &Arc<ArrowSchema> {
132        &self.arrow_schema
133    }
134
135    pub fn column_schemas(&self) -> &[ColumnSchema] {
136        &self.column_schemas
137    }
138
139    pub fn column_schema_by_name(&self, name: &str) -> Option<&ColumnSchema> {
140        self.name_to_index
141            .get(name)
142            .map(|index| &self.column_schemas[*index])
143    }
144
145    /// Retrieve the column's name by index
146    /// # Panics
147    /// This method **may** panic if the index is out of range of column schemas.
148    pub fn column_name_by_index(&self, idx: usize) -> &str {
149        &self.column_schemas[idx].name
150    }
151
152    pub fn column_index_by_name(&self, name: &str) -> Option<usize> {
153        self.name_to_index.get(name).copied()
154    }
155
156    pub fn contains_column(&self, name: &str) -> bool {
157        self.name_to_index.contains_key(name)
158    }
159
160    pub fn num_columns(&self) -> usize {
161        self.column_schemas.len()
162    }
163
164    pub fn is_empty(&self) -> bool {
165        self.column_schemas.is_empty()
166    }
167
168    /// Returns index of the timestamp key column.
169    pub fn timestamp_index(&self) -> Option<usize> {
170        self.timestamp_index
171    }
172
173    pub fn timestamp_column(&self) -> Option<&ColumnSchema> {
174        self.timestamp_index.map(|idx| &self.column_schemas[idx])
175    }
176
177    pub fn version(&self) -> u32 {
178        self.version
179    }
180
181    pub fn metadata(&self) -> &HashMap<String, String> {
182        &self.arrow_schema.metadata
183    }
184
185    /// Returns the estimated memory footprint of this schema.
186    pub fn estimated_size(&self) -> usize {
187        mem::size_of_val(self)
188            + mem::size_of::<ColumnSchema>() * self.column_schemas.capacity()
189            + self
190                .column_schemas
191                .iter()
192                .map(|column_schema| {
193                    column_schema.estimated_size() - mem::size_of::<ColumnSchema>()
194                })
195                .sum::<usize>()
196            + mem::size_of::<(String, usize)>() * self.name_to_index.capacity()
197            + self
198                .name_to_index
199                .keys()
200                .map(|name| name.capacity())
201                .sum::<usize>()
202            + arrow_schema_size(self.arrow_schema.as_ref())
203    }
204
205    /// Generate a new projected schema
206    ///
207    /// # Panic
208    ///
209    /// If the index out ouf bound
210    pub fn try_project(&self, indices: &[usize]) -> Result<Self> {
211        let mut column_schemas = Vec::with_capacity(indices.len());
212        let mut timestamp_index = None;
213        for index in indices {
214            if let Some(ts_index) = self.timestamp_index
215                && ts_index == *index
216            {
217                timestamp_index = Some(column_schemas.len());
218            }
219            column_schemas.push(self.column_schemas[*index].clone());
220        }
221        let arrow_schema = self
222            .arrow_schema
223            .project(indices)
224            .context(ProjectArrowSchemaSnafu)?;
225        let name_to_index = column_schemas
226            .iter()
227            .enumerate()
228            .map(|(pos, column_schema)| (column_schema.name.clone(), pos))
229            .collect();
230
231        Ok(Self {
232            column_schemas,
233            name_to_index,
234            arrow_schema: Arc::new(arrow_schema),
235            timestamp_index,
236            version: self.version,
237        })
238    }
239}
240
241fn arrow_schema_size(schema: &ArrowSchema) -> usize {
242    mem::size_of_val(schema)
243        + schema.fields.size()
244        + mem::size_of::<(String, String)>() * schema.metadata.capacity()
245        + schema
246            .metadata
247            .iter()
248            .map(|(key, value)| key.capacity() + value.capacity())
249            .sum::<usize>()
250}
251
252#[derive(Default)]
253pub struct SchemaBuilder {
254    column_schemas: Vec<ColumnSchema>,
255    name_to_index: HashMap<String, usize>,
256    fields: Vec<Field>,
257    timestamp_index: Option<usize>,
258    version: u32,
259    metadata: HashMap<String, String>,
260}
261
262impl TryFrom<Vec<ColumnSchema>> for SchemaBuilder {
263    type Error = Error;
264
265    fn try_from(column_schemas: Vec<ColumnSchema>) -> Result<SchemaBuilder> {
266        SchemaBuilder::try_from_columns(column_schemas)
267    }
268}
269
270impl SchemaBuilder {
271    pub fn try_from_columns(column_schemas: Vec<ColumnSchema>) -> Result<Self> {
272        let FieldsAndIndices {
273            fields,
274            name_to_index,
275            timestamp_index,
276        } = collect_fields(&column_schemas)?;
277
278        Ok(Self {
279            column_schemas,
280            name_to_index,
281            fields,
282            timestamp_index,
283            ..Default::default()
284        })
285    }
286
287    pub fn version(mut self, version: u32) -> Self {
288        self.version = version;
289        self
290    }
291
292    /// Add key value pair to metadata.
293    ///
294    /// Old metadata with same key would be overwritten.
295    pub fn add_metadata(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
296        let _ = self.metadata.insert(key.into(), value.into());
297        self
298    }
299
300    pub fn build(mut self) -> Result<Schema> {
301        if let Some(timestamp_index) = self.timestamp_index {
302            validate_timestamp_index(&self.column_schemas, timestamp_index)?;
303        }
304
305        self.metadata
306            .insert(VERSION_KEY.to_string(), self.version.to_string());
307
308        let arrow_schema = ArrowSchema::new(self.fields).with_metadata(self.metadata);
309
310        Ok(Schema {
311            column_schemas: self.column_schemas,
312            name_to_index: self.name_to_index,
313            arrow_schema: Arc::new(arrow_schema),
314            timestamp_index: self.timestamp_index,
315            version: self.version,
316        })
317    }
318}
319
320struct FieldsAndIndices {
321    fields: Vec<Field>,
322    name_to_index: HashMap<String, usize>,
323    timestamp_index: Option<usize>,
324}
325
326fn collect_fields(column_schemas: &[ColumnSchema]) -> Result<FieldsAndIndices> {
327    let mut fields = Vec::with_capacity(column_schemas.len());
328    let mut name_to_index = HashMap::with_capacity(column_schemas.len());
329    let mut timestamp_index = None;
330    for (index, column_schema) in column_schemas.iter().enumerate() {
331        if column_schema.is_time_index() && timestamp_index.is_none() {
332            timestamp_index = Some(index);
333        }
334        let mut field = Field::try_from(column_schema)?;
335
336        // Column with type Json or Vector performs the same as binary column in Arrow, so we need to mark it
337        let extype = match column_schema.data_type {
338            ConcreteDataType::Json(_) => Some(ColumnExtType::Json),
339            ConcreteDataType::Vector(d) => Some(ColumnExtType::Vector(d.dim)),
340            _ => None,
341        };
342        if let Some(extype) = extype {
343            field
344                .metadata_mut()
345                .insert(TYPE_KEY.to_string(), extype.to_string());
346        }
347        fields.push(field);
348        ensure!(
349            name_to_index
350                .insert(column_schema.name.clone(), index)
351                .is_none(),
352            DuplicateColumnSnafu {
353                column: &column_schema.name,
354            }
355        );
356    }
357
358    Ok(FieldsAndIndices {
359        fields,
360        name_to_index,
361        timestamp_index,
362    })
363}
364
365fn validate_timestamp_index(column_schemas: &[ColumnSchema], timestamp_index: usize) -> Result<()> {
366    ensure!(
367        timestamp_index < column_schemas.len(),
368        error::InvalidTimestampIndexSnafu {
369            index: timestamp_index,
370        }
371    );
372
373    let column_schema = &column_schemas[timestamp_index];
374    ensure!(
375        column_schema.data_type.is_timestamp(),
376        error::InvalidTimestampIndexSnafu {
377            index: timestamp_index,
378        }
379    );
380    ensure!(
381        column_schema.is_time_index(),
382        error::InvalidTimestampIndexSnafu {
383            index: timestamp_index,
384        }
385    );
386
387    Ok(())
388}
389
390pub type SchemaRef = Arc<Schema>;
391
392impl TryFrom<Arc<ArrowSchema>> for Schema {
393    type Error = Error;
394
395    fn try_from(arrow_schema: Arc<ArrowSchema>) -> Result<Schema> {
396        let mut column_schemas = Vec::with_capacity(arrow_schema.fields.len());
397        let mut name_to_index = HashMap::with_capacity(arrow_schema.fields.len());
398        for field in &arrow_schema.fields {
399            let column_schema = ColumnSchema::try_from(field.as_ref())?;
400            let _ = name_to_index.insert(field.name().clone(), column_schemas.len());
401            column_schemas.push(column_schema);
402        }
403
404        let mut timestamp_index = None;
405        for (index, column_schema) in column_schemas.iter().enumerate() {
406            if column_schema.is_time_index() {
407                validate_timestamp_index(&column_schemas, index)?;
408                timestamp_index = Some(index);
409                break;
410            }
411        }
412
413        let version = try_parse_version(&arrow_schema.metadata, VERSION_KEY)?;
414
415        Ok(Self {
416            column_schemas,
417            name_to_index,
418            arrow_schema,
419            timestamp_index,
420            version,
421        })
422    }
423}
424
425impl TryFrom<ArrowSchema> for Schema {
426    type Error = Error;
427
428    fn try_from(arrow_schema: ArrowSchema) -> Result<Schema> {
429        let arrow_schema = Arc::new(arrow_schema);
430
431        Schema::try_from(arrow_schema)
432    }
433}
434
435impl TryFrom<DFSchemaRef> for Schema {
436    type Error = Error;
437
438    fn try_from(value: DFSchemaRef) -> Result<Self> {
439        value.inner().clone().try_into()
440    }
441}
442
443fn try_parse_version(metadata: &HashMap<String, String>, key: &str) -> Result<u32> {
444    if let Some(value) = metadata.get(key) {
445        let version = value
446            .parse()
447            .context(error::ParseSchemaVersionSnafu { value })?;
448
449        Ok(version)
450    } else {
451        Ok(Schema::INITIAL_VERSION)
452    }
453}
454
455#[cfg(test)]
456mod tests {
457    use super::*;
458    use crate::data_type::ConcreteDataType;
459
460    #[test]
461    fn test_build_empty_schema() {
462        let schema = SchemaBuilder::default().build().unwrap();
463        assert_eq!(0, schema.num_columns());
464        assert!(schema.is_empty());
465    }
466
467    #[test]
468    fn test_schema_no_timestamp() {
469        let column_schemas = vec![
470            ColumnSchema::new("col1", ConcreteDataType::int32_datatype(), false),
471            ColumnSchema::new("col2", ConcreteDataType::float64_datatype(), true),
472        ];
473        let schema = Schema::new(column_schemas.clone());
474
475        assert_eq!(2, schema.num_columns());
476        assert!(!schema.is_empty());
477        assert!(schema.timestamp_index().is_none());
478        assert!(schema.timestamp_column().is_none());
479        assert_eq!(Schema::INITIAL_VERSION, schema.version());
480
481        for column_schema in &column_schemas {
482            let found = schema.column_schema_by_name(&column_schema.name).unwrap();
483            assert_eq!(column_schema, found);
484        }
485        assert!(schema.column_schema_by_name("col3").is_none());
486
487        let new_schema = Schema::try_from(schema.arrow_schema().clone()).unwrap();
488
489        assert_eq!(schema, new_schema);
490        assert_eq!(column_schemas, schema.column_schemas());
491    }
492
493    #[test]
494    fn test_schema_duplicate_column() {
495        let column_schemas = vec![
496            ColumnSchema::new("col1", ConcreteDataType::int32_datatype(), false),
497            ColumnSchema::new("col1", ConcreteDataType::float64_datatype(), true),
498        ];
499        let err = Schema::try_new(column_schemas).unwrap_err();
500
501        assert!(
502            matches!(err, Error::DuplicateColumn { .. }),
503            "expect DuplicateColumn, found {}",
504            err
505        );
506    }
507
508    #[test]
509    fn test_metadata() {
510        let column_schemas = vec![ColumnSchema::new(
511            "col1",
512            ConcreteDataType::int32_datatype(),
513            false,
514        )];
515        let schema = SchemaBuilder::try_from(column_schemas)
516            .unwrap()
517            .add_metadata("k1", "v1")
518            .build()
519            .unwrap();
520
521        assert_eq!("v1", schema.metadata().get("k1").unwrap());
522    }
523
524    #[test]
525    fn test_schema_with_timestamp() {
526        let column_schemas = vec![
527            ColumnSchema::new("col1", ConcreteDataType::int32_datatype(), true),
528            ColumnSchema::new(
529                "ts",
530                ConcreteDataType::timestamp_millisecond_datatype(),
531                false,
532            )
533            .with_time_index(true),
534        ];
535        let schema = SchemaBuilder::try_from(column_schemas.clone())
536            .unwrap()
537            .version(123)
538            .build()
539            .unwrap();
540
541        assert_eq!(1, schema.timestamp_index().unwrap());
542        assert_eq!(&column_schemas[1], schema.timestamp_column().unwrap());
543        assert_eq!(123, schema.version());
544
545        let new_schema = Schema::try_from(schema.arrow_schema().clone()).unwrap();
546        assert_eq!(1, schema.timestamp_index().unwrap());
547        assert_eq!(schema, new_schema);
548    }
549
550    #[test]
551    fn test_schema_wrong_timestamp() {
552        let column_schemas = vec![
553            ColumnSchema::new("col1", ConcreteDataType::int32_datatype(), true)
554                .with_time_index(true),
555            ColumnSchema::new("col2", ConcreteDataType::float64_datatype(), false),
556        ];
557        assert!(
558            SchemaBuilder::try_from(column_schemas)
559                .unwrap()
560                .build()
561                .is_err()
562        );
563
564        let column_schemas = vec![
565            ColumnSchema::new("col1", ConcreteDataType::int32_datatype(), true),
566            ColumnSchema::new("col2", ConcreteDataType::float64_datatype(), false)
567                .with_time_index(true),
568        ];
569
570        assert!(
571            SchemaBuilder::try_from(column_schemas)
572                .unwrap()
573                .build()
574                .is_err()
575        );
576    }
577}