Skip to main content

mito2/read/
flat_projection.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//! Utilities for projection on flat format.
16
17use std::sync::Arc;
18
19use api::v1::SemanticType;
20use common_recordbatch::error::{ArrowComputeSnafu, NewDfRecordBatchSnafu};
21use common_recordbatch::{DfRecordBatch, RecordBatch};
22use datatypes::arrow::array::{Array, AsArray};
23use datatypes::arrow::datatypes::{DataType as ArrowDataType, Field};
24use datatypes::extension::json::is_json2_extension_type;
25use datatypes::prelude::{ConcreteDataType, DataType};
26use datatypes::schema::{Schema, SchemaRef};
27use datatypes::value::Value;
28use datatypes::vectors::json::json2_physical_data_type;
29use snafu::{OptionExt, ResultExt};
30use store_api::metadata::{RegionMetadata, RegionMetadataRef};
31use store_api::storage::ColumnId;
32
33use crate::cache::CacheStrategy;
34use crate::error::{InvalidRequestSnafu, Result};
35use crate::read::projection::{read_column_ids_from_projection, repeated_vector_with_cache};
36use crate::read::read_columns::{JsonTargetTypes, ReadColumns};
37use crate::sst::parquet::Json2RewriteTargets;
38use crate::sst::parquet::flat_format::sst_column_id_indices;
39use crate::sst::parquet::format::FormatProjection;
40use crate::sst::{
41    FlatSchemaOptions, internal_fields, tag_maybe_to_dictionary_field, to_flat_sst_arrow_schema,
42    with_field_id,
43};
44
45/// Handles projection and converts batches in flat format with correct schema.
46///
47/// This mapper support duplicate and unsorted projection indices.
48/// The output schema is determined by the projection indices.
49/// Input indices address the compatible merge schema, not physical Parquet
50/// columns or temporary predicate projections. Sparse compaction uses
51/// `input_arrow_schema(true)` without expanded tags and bypasses query output
52/// conversion. Sparse compaction retains encoded keys through filtering and
53/// passes batches directly to compatibility; predicate tags stay temporary.
54pub struct FlatProjectionMapper {
55    /// Metadata of the region.
56    metadata: RegionMetadataRef,
57    /// Schema for converted [RecordBatch] to return.
58    output_schema: SchemaRef,
59    /// The columns to read from memtables and SSTs.
60    /// The mapper won't deduplicate the column ids.
61    ///
62    /// Note that this doesn't contain the `__table_id` and `__tsid`.
63    read_cols: ReadColumns,
64    /// Ids and DataTypes of columns of the expected batch.
65    /// We can use this to check if the batch is compatible with the expected schema.
66    ///
67    /// It doesn't contain internal columns but always contains the time index column.
68    batch_schema: Vec<(ColumnId, ConcreteDataType)>,
69    /// `true` If the original projection is empty.
70    is_empty_projection: bool,
71    /// The index in flat format [RecordBatch] for each column in the output [RecordBatch].
72    batch_indices: Vec<usize>,
73    /// Precomputed Arrow schema for input batches.
74    input_arrow_schema: datatypes::arrow::datatypes::SchemaRef,
75}
76
77impl FlatProjectionMapper {
78    /// Returns a new mapper with projection.
79    /// If `projection` is empty, it outputs [RecordBatch] without any column but only a row count.
80    /// `SELECT COUNT(*) FROM table` is an example that uses an empty projection. DataFusion accepts
81    /// empty `RecordBatch` and only use its row count in this query.
82    pub fn new(
83        metadata: &RegionMetadataRef,
84        projection: impl IntoIterator<Item = usize>,
85    ) -> Result<Self> {
86        let projection: Vec<_> = projection.into_iter().collect();
87        let read_column_ids = read_column_ids_from_projection(metadata, &projection)?;
88        let read_cols = ReadColumns::new(read_column_ids);
89        Self::new_with_read_columns(metadata, projection, read_cols)
90    }
91
92    /// Returns a new mapper with output projection and explicit read columns.
93    pub fn new_with_read_columns(
94        metadata: &RegionMetadataRef,
95        projection: Vec<usize>,
96        read_cols: ReadColumns,
97    ) -> Result<Self> {
98        Self::new_with_json2_rewrite_targets(
99            metadata,
100            projection,
101            read_cols,
102            &Json2RewriteTargets::default(),
103        )
104    }
105
106    /// Returns a mapper for a compaction read with fixed JSON2 output layouts.
107    pub(crate) fn new_with_json2_rewrite_targets(
108        metadata: &RegionMetadataRef,
109        projection: Vec<usize>,
110        read_cols: ReadColumns,
111        json2_rewrite_targets: &Json2RewriteTargets,
112    ) -> Result<Self> {
113        // If the original projection is empty.
114        let is_empty_projection = projection.is_empty();
115
116        // Output column schemas for the projection.
117        let mut col_schemas = Vec::with_capacity(projection.len());
118        // Column ids of the output projection without deduplication.
119        let mut output_col_ids = Vec::with_capacity(projection.len());
120        for idx in &projection {
121            let col = metadata
122                .column_metadatas
123                .get(*idx)
124                .with_context(|| InvalidRequestSnafu {
125                    region_id: metadata.region_id,
126                    reason: format!("projection index {} is out of bound", idx),
127                })?;
128            output_col_ids.push(col.column_id);
129
130            let mut schema = col.column_schema.clone();
131            if let Some(data_type) = read_cols.json_target_type(col.column_id) {
132                schema.data_type = ConcreteDataType::json2(data_type.clone());
133            }
134            col_schemas.push(schema);
135        }
136
137        // Creates a map to lookup index.
138        let id_to_index = sst_column_id_indices(metadata);
139
140        // TODO(yingwen): Support different flat schema options.
141        let format_projection = FormatProjection::compute_format_projection(
142            metadata,
143            &id_to_index,
144            // All columns with internal columns.
145            metadata.column_metadatas.len() + 3,
146            read_cols.clone(),
147        );
148
149        let batch_schema =
150            flat_projected_columns(metadata, &format_projection, read_cols.json_target_types());
151
152        let input_arrow_schema =
153            compute_input_arrow_schema(metadata, &batch_schema, json2_rewrite_targets);
154
155        // If projection is empty, we don't output any column.
156        let output_schema = if is_empty_projection {
157            Arc::new(Schema::new(vec![]))
158        } else {
159            // Safety: Columns come from existing schema.
160            Arc::new(Schema::new(col_schemas))
161        };
162
163        let batch_indices = if is_empty_projection {
164            vec![]
165        } else {
166            output_col_ids
167                .iter()
168                .map(|id| {
169                    // Safety: The map is computed from the read projection.
170                    format_projection
171                        .column_id_to_projected_index
172                        .get(id)
173                        .copied()
174                        .with_context(|| {
175                            let name = metadata
176                                .column_by_id(*id)
177                                .map(|column| column.column_schema.name.clone())
178                                .unwrap_or_else(|| id.to_string());
179                            InvalidRequestSnafu {
180                                region_id: metadata.region_id,
181                                reason: format!(
182                                    "output column {} is missing in read projection",
183                                    name
184                                ),
185                            }
186                        })
187                })
188                .collect::<Result<Vec<_>>>()?
189        };
190
191        Ok(FlatProjectionMapper {
192            metadata: metadata.clone(),
193            output_schema,
194            read_cols,
195            batch_schema,
196            is_empty_projection,
197            batch_indices,
198            input_arrow_schema,
199        })
200    }
201
202    /// Returns a new mapper without projection.
203    pub fn all(metadata: &RegionMetadataRef) -> Result<Self> {
204        FlatProjectionMapper::new(metadata, 0..metadata.column_metadatas.len())
205    }
206
207    /// Keeps projected string primary-key columns in their flat-format dictionary encoding.
208    pub(crate) fn with_pk_dictionary_encoding(mut self) -> Self {
209        let mut changed = false;
210        let columns = self
211            .output_schema
212            .column_schemas()
213            .iter()
214            .map(|column| {
215                let mut column = column.clone();
216                if column.data_type == ConcreteDataType::string_datatype()
217                    && self
218                        .metadata
219                        .column_by_name(&column.name)
220                        .is_some_and(|metadata| metadata.semantic_type == SemanticType::Tag)
221                {
222                    changed = true;
223                    column.data_type = ConcreteDataType::dictionary_datatype(
224                        ConcreteDataType::uint32_datatype(),
225                        column.data_type.clone(),
226                    );
227                }
228                column
229            })
230            .collect();
231        if changed {
232            self.output_schema = Arc::new(Schema::new_with_version(
233                columns,
234                self.output_schema.version(),
235            ));
236        }
237        self
238    }
239
240    /// Returns the metadata that created the mapper.
241    pub(crate) fn metadata(&self) -> &RegionMetadataRef {
242        &self.metadata
243    }
244    /// Returns projected columns that we need to read from memtables and SSTs.
245    pub(crate) fn read_columns(&self) -> &ReadColumns {
246        &self.read_cols
247    }
248
249    /// Returns the field column start index in output batch.
250    pub(crate) fn field_column_start(&self) -> usize {
251        for (idx, column_id) in self
252            .batch_schema
253            .iter()
254            .map(|(column_id, _)| column_id)
255            .enumerate()
256        {
257            // Safety: We get the column id from the metadata in new().
258            if self
259                .metadata
260                .column_by_id(*column_id)
261                .unwrap()
262                .semantic_type
263                == SemanticType::Field
264            {
265                return idx;
266            }
267        }
268
269        self.batch_schema.len()
270    }
271
272    /// Returns ids of columns of the batch that the mapper expects to convert.
273    pub(crate) fn batch_schema(&self) -> &[(ColumnId, ConcreteDataType)] {
274        &self.batch_schema
275    }
276
277    /// Returns the input arrow schema from sources.
278    ///
279    /// The merge reader can use this schema.
280    pub(crate) fn input_arrow_schema(
281        &self,
282        compaction: bool,
283    ) -> datatypes::arrow::datatypes::SchemaRef {
284        if !compaction {
285            self.input_arrow_schema.clone()
286        } else {
287            // For compaction, we need to build a different schema from encoding.
288            let mut options = FlatSchemaOptions::from_encoding(self.metadata.primary_key_encoding);
289            options.concretized_json_types = self
290                .input_arrow_schema
291                .fields()
292                .iter()
293                .filter(|&field| is_json2_extension_type(field))
294                .map(|field| (field.name().clone(), field.data_type().clone()))
295                .collect();
296            to_flat_sst_arrow_schema(&self.metadata, &options)
297        }
298    }
299
300    /// Returns the schema of converted [RecordBatch].
301    /// This is the schema that the stream will output. This schema may contain
302    /// less columns than [FlatProjectionMapper::column_ids()].
303    pub(crate) fn output_schema(&self) -> SchemaRef {
304        self.output_schema.clone()
305    }
306
307    /// Converts a flat format [RecordBatch] to a normal [RecordBatch].
308    ///
309    /// The batch must match the `projection` using to build the mapper.
310    /// JSON2 columns must already match query types before merge and deduplication.
311    pub(crate) fn convert(
312        &self,
313        batch: &datatypes::arrow::record_batch::RecordBatch,
314        cache_strategy: &CacheStrategy,
315    ) -> common_recordbatch::error::Result<RecordBatch> {
316        if self.is_empty_projection {
317            return RecordBatch::new_with_count(self.output_schema.clone(), batch.num_rows());
318        }
319        // Construct output record batch directly from Arrow arrays to avoid
320        // Arrow -> Vector -> Arrow roundtrips in the hot path.
321        let mut arrays = Vec::with_capacity(self.output_schema.num_columns());
322        for (output_idx, index) in self.batch_indices.iter().enumerate() {
323            let mut array = batch.column(*index).clone();
324            if matches!(
325                self.output_schema.arrow_schema().fields()[output_idx].data_type(),
326                ArrowDataType::Dictionary(_, _)
327            ) && let Some(dictionary) = array.as_any_dictionary_opt()
328                && dictionary.values().len() > dictionary.len()
329            {
330                // Small scan slices must not retain an entire SST's tag dictionary in merges.
331                array = arrow_select::dictionary::garbage_collect_any_dictionary(dictionary)
332                    .context(ArrowComputeSnafu)?;
333            }
334            // Cast dictionary values to the target type.
335            if let ArrowDataType::Dictionary(_key_type, value_type) = array.data_type()
336                && !matches!(
337                    self.output_schema.arrow_schema().fields()[output_idx].data_type(),
338                    ArrowDataType::Dictionary(_, _)
339                )
340            {
341                // When a string dictionary column contains only a single value, reuse a cached
342                // repeated vector to avoid repeatedly expanding the dictionary.
343                if let Some(dict_array) = single_value_string_dictionary(
344                    &array,
345                    &self.output_schema.column_schemas()[output_idx].data_type,
346                    value_type.as_ref(),
347                ) {
348                    let dict_values = dict_array.values();
349                    let value = if dict_values.is_null(0) {
350                        Value::Null
351                    } else {
352                        Value::from(datatypes::arrow_array::string_array_value(dict_values, 0))
353                    };
354
355                    let repeated = repeated_vector_with_cache(
356                        &self.output_schema.column_schemas()[output_idx].data_type,
357                        &value,
358                        batch.num_rows(),
359                        cache_strategy,
360                    )?;
361                    array = repeated.to_arrow_array();
362                } else {
363                    let casted = datatypes::arrow::compute::cast(&array, value_type)
364                        .context(ArrowComputeSnafu)?;
365                    array = casted;
366                }
367            }
368
369            arrays.push(array);
370        }
371
372        let df_record_batch =
373            DfRecordBatch::try_new(self.output_schema.arrow_schema().clone(), arrays)
374                .context(NewDfRecordBatchSnafu)?;
375        Ok(RecordBatch::from_df_record_batch(
376            self.output_schema.clone(),
377            df_record_batch,
378        ))
379    }
380}
381
382fn single_value_string_dictionary<'a>(
383    array: &'a Arc<dyn Array>,
384    output_type: &ConcreteDataType,
385    value_type: &ArrowDataType,
386) -> Option<&'a datatypes::arrow::array::DictionaryArray<datatypes::arrow::datatypes::UInt32Type>> {
387    if !matches!(
388        value_type,
389        ArrowDataType::Utf8 | ArrowDataType::LargeUtf8 | ArrowDataType::Utf8View
390    ) || !output_type.is_string()
391    {
392        return None;
393    }
394
395    let dict_array = array
396        .as_any()
397        .downcast_ref::<datatypes::arrow::array::DictionaryArray<
398            datatypes::arrow::datatypes::UInt32Type,
399        >>()?;
400
401    (dict_array.values().len() == 1 && dict_array.null_count() == 0).then_some(dict_array)
402}
403
404/// Returns ids and datatypes of columns after applying the projection and JSON2 target types.
405///
406/// It adds the time index column if it doesn't present in the projection.
407pub(crate) fn flat_projected_columns(
408    metadata: &RegionMetadata,
409    format_projection: &FormatProjection,
410    json_target_types: &JsonTargetTypes,
411) -> Vec<(ColumnId, ConcreteDataType)> {
412    let time_index = metadata.time_index_column();
413    let num_columns = if format_projection
414        .column_id_to_projected_index
415        .contains_key(&time_index.column_id)
416    {
417        format_projection.column_id_to_projected_index.len()
418    } else {
419        format_projection.column_id_to_projected_index.len() + 1
420    };
421    let mut schema = vec![None; num_columns];
422    for (column_id, index) in &format_projection.column_id_to_projected_index {
423        let data_type = if let Some(json_type) = json_target_types.get(column_id) {
424            ConcreteDataType::json2(json_type.clone())
425        } else {
426            // Safety: FormatProjection ensures the id is valid.
427            metadata
428                .column_by_id(*column_id)
429                .unwrap()
430                .column_schema
431                .data_type
432                .clone()
433        };
434        schema[*index] = Some((*column_id, data_type));
435    }
436    if num_columns != format_projection.column_id_to_projected_index.len() {
437        schema[num_columns - 1] = Some((
438            time_index.column_id,
439            time_index.column_schema.data_type.clone(),
440        ));
441    }
442
443    // Safety: FormatProjection ensures all indices can be unwrapped.
444    schema.into_iter().map(|id_type| id_type.unwrap()).collect()
445}
446
447/// Computes the Arrow schema for input batches.
448///
449/// # Panics
450/// Panics if it can't find the column by the column id in the batch_schema.
451pub(crate) fn compute_input_arrow_schema(
452    metadata: &RegionMetadata,
453    batch_schema: &[(ColumnId, ConcreteDataType)],
454    json2_rewrite_targets: &Json2RewriteTargets,
455) -> datatypes::arrow::datatypes::SchemaRef {
456    let mut new_fields = Vec::with_capacity(batch_schema.len() + 3);
457    for (column_id, data_type) in batch_schema {
458        let data_type = json2_rewrite_targets
459            .get(column_id)
460            .map(|x| json2_physical_data_type(&x.target_layout))
461            .unwrap_or_else(|| data_type.as_arrow_type());
462
463        let column_metadata = metadata.column_by_id(*column_id).unwrap();
464        let field = Field::new(
465            &column_metadata.column_schema.name,
466            data_type,
467            column_metadata.column_schema.is_nullable(),
468        )
469        .with_metadata(column_metadata.column_schema.metadata().clone());
470        let field = with_field_id(field, *column_id);
471        if column_metadata.semantic_type == SemanticType::Tag {
472            new_fields.push(tag_maybe_to_dictionary_field(
473                &column_metadata.column_schema.data_type,
474                &Arc::new(field),
475            ));
476        } else {
477            new_fields.push(Arc::new(field));
478        }
479    }
480    new_fields.extend_from_slice(&internal_fields());
481
482    Arc::new(datatypes::arrow::datatypes::Schema::new(new_fields))
483}
484
485#[cfg(test)]
486mod tests {
487    use datatypes::schema::ColumnSchema;
488    use datatypes::vectors::Helper;
489    use store_api::metadata::{ColumnMetadata, RegionMetadataBuilder};
490    use store_api::storage::RegionId;
491
492    use super::*;
493    use datatypes::types::json_type::JsonNativeType;
494
495    #[test]
496    fn test_json2_root_hint_uses_output_type_before_merge()
497    -> std::result::Result<(), Box<dyn std::error::Error>> {
498        let mut builder = RegionMetadataBuilder::new(RegionId::new(1024, 0));
499        builder
500            .push_column_metadata(ColumnMetadata {
501                column_schema: ColumnSchema::new(
502                    "j",
503                    ConcreteDataType::json2(JsonNativeType::object()),
504                    true,
505                ),
506                semantic_type: SemanticType::Field,
507                column_id: 0,
508            })
509            .push_column_metadata(ColumnMetadata {
510                column_schema: ColumnSchema::new(
511                    "ts",
512                    ConcreteDataType::timestamp_millisecond_datatype(),
513                    false,
514                ),
515                semantic_type: SemanticType::Timestamp,
516                column_id: 1,
517            });
518        let metadata = Arc::new(builder.build()?);
519        let read_cols = ReadColumns::new([0, 1])
520            .with_json_target_types([(0, JsonNativeType::String)].into_iter().collect());
521        let mapper = FlatProjectionMapper::new_with_read_columns(&metadata, vec![0, 1], read_cols)?;
522        let input = mapper.input_arrow_schema(false);
523        assert_eq!(
524            &ArrowDataType::Binary,
525            input.field_with_name("j")?.data_type()
526        );
527        assert_eq!(
528            mapper
529                .output_schema()
530                .arrow_schema()
531                .field_with_name("j")?
532                .data_type(),
533            input.field_with_name("j")?.data_type(),
534        );
535        Ok(())
536    }
537
538    fn metadata_with_legacy_json() -> RegionMetadataRef {
539        let mut builder = RegionMetadataBuilder::new(RegionId::new(1024, 0));
540        builder
541            .push_column_metadata(ColumnMetadata {
542                column_schema: datatypes::schema::ColumnSchema::new(
543                    "j",
544                    ConcreteDataType::json_datatype(),
545                    true,
546                ),
547                semantic_type: SemanticType::Field,
548                column_id: 0,
549            })
550            .push_column_metadata(ColumnMetadata {
551                column_schema: datatypes::schema::ColumnSchema::new(
552                    "ts",
553                    ConcreteDataType::timestamp_millisecond_datatype(),
554                    false,
555                ),
556                semantic_type: SemanticType::Timestamp,
557                column_id: 1,
558            });
559        Arc::new(builder.build().unwrap())
560    }
561
562    #[test]
563    fn test_tag_projection_preserves_dictionary() {
564        let mut builder = RegionMetadataBuilder::new(RegionId::new(1024, 0));
565        builder
566            .push_column_metadata(ColumnMetadata {
567                column_schema: ColumnSchema::new("tag", ConcreteDataType::string_datatype(), true),
568                semantic_type: SemanticType::Tag,
569                column_id: 0,
570            })
571            .push_column_metadata(ColumnMetadata {
572                column_schema: ColumnSchema::new(
573                    "ts",
574                    ConcreteDataType::timestamp_millisecond_datatype(),
575                    false,
576                ),
577                semantic_type: SemanticType::Timestamp,
578                column_id: 1,
579            })
580            .primary_key(vec![0]);
581        let metadata = Arc::new(builder.build().unwrap());
582
583        let mapper = FlatProjectionMapper::new(&metadata, [0, 1]).unwrap();
584        assert_eq!(
585            &ArrowDataType::Utf8,
586            mapper.output_schema().arrow_schema().field(0).data_type()
587        );
588
589        let mapper = mapper.with_pk_dictionary_encoding();
590        assert_eq!(
591            &ArrowDataType::Dictionary(
592                Box::new(ArrowDataType::UInt32),
593                Box::new(ArrowDataType::Utf8),
594            ),
595            mapper.output_schema().arrow_schema().field(0).data_type()
596        );
597    }
598
599    #[test]
600    fn test_tag_projection_compacts_dictionary_slices() {
601        use datatypes::arrow::array::{
602            DictionaryArray, StringArray, TimestampMillisecondArray, UInt32Array,
603        };
604        use datatypes::arrow::datatypes::UInt32Type;
605
606        let mut builder = RegionMetadataBuilder::new(RegionId::new(1024, 0));
607        builder
608            .push_column_metadata(ColumnMetadata {
609                column_schema: ColumnSchema::new("tag", ConcreteDataType::string_datatype(), true),
610                semantic_type: SemanticType::Tag,
611                column_id: 0,
612            })
613            .push_column_metadata(ColumnMetadata {
614                column_schema: ColumnSchema::new(
615                    "ts",
616                    ConcreteDataType::timestamp_millisecond_datatype(),
617                    false,
618                ),
619                semantic_type: SemanticType::Timestamp,
620                column_id: 1,
621            })
622            .primary_key(vec![0]);
623        let metadata = Arc::new(builder.build().unwrap());
624        let mapper = FlatProjectionMapper::new(&metadata, [0, 1])
625            .unwrap()
626            .with_pk_dictionary_encoding();
627        let values = StringArray::from_iter(
628            (0..1024).map(|i| (i != 1).then(|| format!("{i}{}", "x".repeat(4096)))),
629        );
630        let dictionary = DictionaryArray::<UInt32Type>::try_new(
631            UInt32Array::from(vec![Some(1023), None, Some(1), Some(1023)]),
632            Arc::new(values),
633        )
634        .unwrap();
635        let expected = datatypes::arrow::compute::cast(&dictionary, &ArrowDataType::Utf8).unwrap();
636        let batch = DfRecordBatch::try_from_iter([
637            ("tag", Arc::new(dictionary) as Arc<dyn Array>),
638            (
639                "ts",
640                Arc::new(TimestampMillisecondArray::from(vec![1, 2, 3, 4])),
641            ),
642        ])
643        .unwrap();
644        let output = mapper.convert(&batch, &CacheStrategy::Disabled).unwrap();
645        let actual = output.column(0);
646        assert!(actual.get_array_memory_size() < 64 * 1024);
647        assert_eq!(actual.data_type(), batch.column(0).data_type());
648        assert_eq!(
649            datatypes::arrow::compute::cast(actual.as_ref(), &ArrowDataType::Utf8)
650                .unwrap()
651                .as_ref(),
652            expected.as_ref(),
653        );
654    }
655
656    #[test]
657    fn test_single_value_dictionary_preserves_string_type() {
658        use datatypes::arrow::array::{DictionaryArray, TimestampMillisecondArray, UInt32Array};
659        use datatypes::arrow::datatypes::UInt32Type;
660
661        for data_type in [
662            ConcreteDataType::large_string_datatype(),
663            ConcreteDataType::utf8_view_datatype(),
664        ] {
665            let mut builder = RegionMetadataBuilder::new(RegionId::new(1024, 0));
666            builder
667                .push_column_metadata(ColumnMetadata {
668                    column_schema: ColumnSchema::new("tag", data_type.clone(), true),
669                    semantic_type: SemanticType::Tag,
670                    column_id: 0,
671                })
672                .push_column_metadata(ColumnMetadata {
673                    column_schema: ColumnSchema::new(
674                        "ts",
675                        ConcreteDataType::timestamp_millisecond_datatype(),
676                        false,
677                    ),
678                    semantic_type: SemanticType::Timestamp,
679                    column_id: 1,
680                })
681                .primary_key(vec![0]);
682            let metadata = Arc::new(builder.build().unwrap());
683            let mapper = FlatProjectionMapper::new(&metadata, [0, 1]).unwrap();
684
685            for value in [Value::from("greptime"), Value::Null] {
686                let mut values = data_type.create_mutable_vector(1);
687                values.try_push_value_ref(&value.as_value_ref()).unwrap();
688                let dictionary = Arc::new(
689                    DictionaryArray::<UInt32Type>::try_new(
690                        UInt32Array::from(vec![0, 0, 0]),
691                        values.to_vector().to_arrow_array(),
692                    )
693                    .unwrap(),
694                );
695                let arrays: Vec<Arc<dyn Array>> = mapper
696                    .batch_schema()
697                    .iter()
698                    .map(|(id, _)| match id {
699                        0 => dictionary.clone() as Arc<dyn Array>,
700                        1 => Arc::new(TimestampMillisecondArray::from(vec![1, 2, 3])),
701                        _ => unreachable!(),
702                    })
703                    .collect();
704                let fields = mapper
705                    .batch_schema()
706                    .iter()
707                    .zip(&arrays)
708                    .map(|((id, _), array)| {
709                        Field::new(id.to_string(), array.data_type().clone(), true)
710                    })
711                    .collect::<Vec<_>>();
712                let batch = DfRecordBatch::try_new(
713                    Arc::new(datatypes::arrow::datatypes::Schema::new(fields)),
714                    arrays,
715                )
716                .unwrap();
717                let output = mapper.convert(&batch, &CacheStrategy::Disabled).unwrap();
718                let vector = Helper::try_into_vector(output.column(0)).unwrap();
719                assert_eq!(data_type, vector.data_type());
720                for row in 0..3 {
721                    assert_eq!(value, vector.get(row));
722                }
723            }
724        }
725    }
726
727    #[test]
728    fn test_json_type_hint_does_not_concretize_legacy_json() {
729        let metadata = metadata_with_legacy_json();
730        let mapper = FlatProjectionMapper::new_with_read_columns(
731            &metadata,
732            vec![0, 1],
733            ReadColumns::new([0, 1]),
734        )
735        .unwrap();
736
737        assert_eq!(
738            mapper.batch_schema()[0],
739            (0, ConcreteDataType::json_datatype())
740        );
741    }
742}