Skip to main content

operator/insert/
otlp.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//! Side-effect-free destination validation for prepared OTLP batches. Catalog
16//! failures propagate; row errors let the converter reject complete source-point fan-outs.
17
18use std::collections::HashSet;
19
20use ahash::{HashMap as AHashMap, HashMapExt};
21use api::helper::{ColumnDataTypeWrapper, to_grpc_value};
22use api::v1::alter_table_expr::Kind;
23use api::v1::column_def::try_as_column_schema;
24use api::v1::{
25    ColumnDataType, ColumnDef, ColumnSchema, Row, RowInsertRequest, Rows, SemanticType, Value,
26};
27use common_query::native_histogram::native_histogram_value_type;
28use common_query::prelude::{greptime_timestamp, greptime_value};
29use common_time::timestamp::TimeUnit;
30use datatypes::schema::ColumnSchema as DataColumn;
31use session::context::QueryContextRef;
32use snafu::prelude::*;
33use store_api::metric_engine_consts::{
34    LOGICAL_TABLE_METADATA_KEY, METRIC_ENGINE_NAME, PHYSICAL_TABLE_METADATA_KEY,
35};
36use table::TableRef;
37
38use crate::error::{self, InvalidInsertRequestSnafu, Result};
39use crate::insert::{
40    AutoCreateTableType, Inserter, convert_rows_time_unit, convert_timestamp_value_data,
41    request_is_native_histogram, table_is_native_histogram, table_time_index_unit,
42};
43use crate::req_convert::insert::{ImpureDefaultFiller, value_matches_type};
44
45pub struct MetricInsertPreflight {
46    /// Rejections in batch order, then row order.
47    pub rejections: Vec<Vec<Option<String>>>,
48    /// Backing tables for existing or newly created logical metric-engine destinations.
49    pub physical_tables: std::collections::HashMap<String, String>,
50}
51
52struct PhysicalColumns {
53    by_name: AHashMap<String, (DataColumn, SemanticType)>,
54    fields: Vec<String>,
55}
56
57impl PhysicalColumns {
58    fn new(columns: Vec<(DataColumn, SemanticType)>) -> Self {
59        let fields = columns
60            .iter()
61            .filter(|(_, semantic)| *semantic == SemanticType::Field)
62            .map(|(column, _)| column.name.clone())
63            .collect();
64        let by_name = columns
65            .into_iter()
66            .map(|(column, semantic)| (column.name.clone(), (column, semantic)))
67            .collect();
68        Self { by_name, fields }
69    }
70}
71
72impl Inserter {
73    /// Validate each row independently, sharing schema planning within each batch.
74    /// Fresh cross-point conflicts are resolved by the converter after this pass.
75    pub async fn validate_and_normalize_otlp_metrics(
76        &self,
77        batches: &mut [RowInsertRequest],
78        ctx: &QueryContextRef,
79        metric_engine: bool,
80        physical_table: &str,
81    ) -> Result<MetricInsertPreflight> {
82        let disabled = self.auto_create_disabled_reason(ctx)?;
83        let mut tables = AHashMap::new();
84        let mut physical_tables = std::collections::HashMap::new();
85        for request in batches.iter() {
86            if !tables.contains_key(&request.table_name) {
87                let table = self
88                    .get_table(
89                        ctx.current_catalog(),
90                        &ctx.current_schema(),
91                        &request.table_name,
92                    )
93                    .await?;
94                tables.insert(request.table_name.clone(), table);
95            }
96            let backing = match tables[&request.table_name].as_ref() {
97                Some(table) if table.table_info().meta.engine == METRIC_ENGINE_NAME => table
98                    .table_info()
99                    .meta
100                    .options
101                    .extra_options
102                    .get(LOGICAL_TABLE_METADATA_KEY)
103                    .cloned(),
104                None if metric_engine => Some(physical_table.to_string()),
105                _ => None,
106            };
107            if let Some(backing) = backing {
108                physical_tables.insert(request.table_name.clone(), backing);
109            }
110        }
111        // Shared schemas accumulate tags across logical tables; index them once per request.
112        let mut physical_columns = AHashMap::new();
113        for backing in physical_tables.values() {
114            if !tables.contains_key(backing) {
115                let table = self
116                    .get_table(ctx.current_catalog(), &ctx.current_schema(), backing)
117                    .await?;
118                tables.insert(backing.clone(), table);
119            }
120            physical_columns.entry(backing.as_str()).or_insert_with(|| {
121                PhysicalColumns::new(tables[backing].as_ref().map(table_columns).unwrap_or_else(
122                    || default_physical_columns(self.auto_create_physical_table_timestamp_unit),
123                ))
124            });
125        }
126        // Match ordinary insertion: impure defaults are evaluated once per table
127        // and request, while supplied nulls remain supplied nulls.
128        let mut fillers = AHashMap::new();
129        let mut build_plan = |source: &mut RowInsertRequest| {
130            let rows = source.rows.as_mut().context(InvalidInsertRequestSnafu {
131                reason: "missing metric rows",
132            })?;
133            let input_columns = rows.schema.len();
134            let source_timestamp = timestamp_column(&rows.schema);
135            let request = &mut RowInsertRequest {
136                table_name: source.table_name.clone(),
137                rows: Some(Rows {
138                    schema: std::mem::take(&mut rows.schema),
139                    rows: Vec::new(),
140                }),
141            };
142            let auto_create = disabled.is_none()
143                || Self::is_auto_create_exempt_private_table(
144                    &ctx.current_schema(),
145                    &request.table_name,
146                );
147            let target = tables[&request.table_name].as_ref();
148            let backing = physical_tables.get(&request.table_name);
149            let physical = backing.and_then(|name| tables[name].as_ref());
150            if let Some(physical) = physical {
151                ensure!(
152                    physical
153                        .table_info()
154                        .meta
155                        .options
156                        .extra_options
157                        .contains_key(PHYSICAL_TABLE_METADATA_KEY),
158                    InvalidInsertRequestSnafu {
159                        reason: "selected backing table is not a physical metric table"
160                    }
161                );
162            }
163            if metric_engine {
164                ensure!(
165                    backing.is_none() || physical.is_some() || auto_create,
166                    InvalidInsertRequestSnafu {
167                        reason: format!(
168                            "missing physical table and {}",
169                            disabled.unwrap_or_default()
170                        ),
171                    }
172                );
173                let unit = target
174                    .and_then(table_time_index_unit)
175                    .or_else(|| physical.and_then(table_time_index_unit))
176                    // The physical table will be auto-created in the configured
177                    // unit, so validate its rows in that unit as well.
178                    .unwrap_or(self.auto_create_physical_table_timestamp_unit);
179                if let Some(rows) = &mut request.rows {
180                    convert_rows_time_unit(rows, unit)?;
181                }
182            }
183            let mut columns = if let Some(table) = target {
184                ensure!(
185                    !table
186                        .table_info()
187                        .meta
188                        .options
189                        .extra_options
190                        .contains_key(PHYSICAL_TABLE_METADATA_KEY),
191                    InvalidInsertRequestSnafu {
192                        reason: "direct writes to a physical metric table are forbidden",
193                    }
194                );
195                ensure!(
196                    request_is_native_histogram(&request.rows.as_ref().unwrap().schema)
197                        == table_is_native_histogram(table),
198                    InvalidInsertRequestSnafu {
199                        reason: format!(
200                            "Table `{}` cannot mix native histogram and float sample fields",
201                            request.table_name
202                        ),
203                    }
204                );
205                let mut columns = table_columns(table);
206                if auto_create {
207                    // Ordinary OTLP insertion does not rename columns.
208                    if let Some(alter) = self.get_alter_table_expr_on_demand(
209                        request,
210                        table,
211                        ctx,
212                        metric_engine,
213                        true,
214                        true,
215                    )? && let Some(Kind::AddColumns(add)) = alter.kind
216                    {
217                        for column in add.add_columns {
218                            let def =
219                                column
220                                    .column_def
221                                    .with_context(|| InvalidInsertRequestSnafu {
222                                        reason: "missing column definition",
223                                    })?;
224                            columns.push(column_definition(&def)?);
225                        }
226                    }
227                }
228                columns
229            } else {
230                ensure!(
231                    auto_create,
232                    InvalidInsertRequestSnafu {
233                        reason: format!(
234                            "missing table `{}` and {}",
235                            request.table_name,
236                            disabled.unwrap_or_default()
237                        ),
238                    }
239                );
240                let create_type = if metric_engine {
241                    AutoCreateTableType::Logical(physical_table.to_string())
242                } else {
243                    AutoCreateTableType::Physical
244                };
245                let create =
246                    self.get_create_table_expr_on_demand(request, &create_type, ctx, None)?;
247                if metric_engine {
248                    ensure!(
249                        create
250                            .column_defs
251                            .iter()
252                            .filter(|c| c.semantic_type == SemanticType::Field as i32)
253                            .count()
254                            == 1,
255                        InvalidInsertRequestSnafu {
256                            reason: "logical metrics require exactly one sample field"
257                        }
258                    );
259                }
260                create
261                    .column_defs
262                    .iter()
263                    .map(column_definition)
264                    .collect::<Result<Vec<_>>>()?
265            };
266            let rows = request.rows.as_mut().context(InvalidInsertRequestSnafu {
267                reason: "missing metric rows",
268            })?;
269            if let Some(backing) = backing {
270                // Logical tag nullability follows the shared physical schema.
271                for (column, semantic) in &mut columns {
272                    if *semantic == SemanticType::Tag {
273                        column.set_nullable();
274                    }
275                }
276                validate_physical_columns(rows, &physical_columns[backing.as_str()], auto_create)?;
277            }
278            // Only defaults need values in the planning template.
279            rows.rows.push(Row::default());
280            if let Some(table) = target {
281                if !fillers.contains_key(&request.table_name) {
282                    fillers.insert(
283                        request.table_name.clone(),
284                        ImpureDefaultFiller::new(table.table_info())?,
285                    );
286                }
287                fillers[&request.table_name].fill_rows(rows);
288            }
289            RowValidationPlan::new(
290                input_columns,
291                source_timestamp,
292                std::mem::take(rows),
293                &columns,
294            )
295        };
296        let mut rejections = Vec::with_capacity(batches.len());
297        for request in batches {
298            let num_rows = request
299                .rows
300                .as_ref()
301                .context(InvalidInsertRequestSnafu {
302                    reason: "missing metric rows",
303                })?
304                .rows
305                .len();
306            let plan = match build_plan(request) {
307                Ok(plan) => plan,
308                Err(err) if attributable(&err) => {
309                    rejections.push(vec![Some(err.to_string()); num_rows]);
310                    continue;
311                }
312                Err(err) => return Err(err),
313            };
314            let rows = request.rows.as_mut().context(InvalidInsertRequestSnafu {
315                reason: "missing metric rows",
316            })?;
317            let mut errors = Vec::with_capacity(num_rows);
318            for row in &mut rows.rows {
319                match plan.apply_row(row) {
320                    Ok(()) => errors.push(None),
321                    Err(err) if attributable(&err) => errors.push(Some(err.to_string())),
322                    Err(err) => return Err(err),
323                }
324            }
325            rows.schema = plan.schema;
326            rejections.push(errors);
327        }
328        Ok(MetricInsertPreflight {
329            rejections,
330            physical_tables,
331        })
332    }
333}
334
335fn attributable(err: &error::Error) -> bool {
336    matches!(
337        err,
338        error::Error::InvalidInsertRequest { .. }
339            | error::Error::BuildCreateExprOnInsertion { .. }
340            | error::Error::FindNewColumnsOnInsertion { .. }
341            | error::Error::InvalidColumnDef { .. }
342    )
343}
344
345fn invalid(reason: impl Into<String>) -> error::Error {
346    InvalidInsertRequestSnafu {
347        reason: reason.into(),
348    }
349    .build()
350}
351
352fn column_definition(def: &ColumnDef) -> Result<(DataColumn, SemanticType)> {
353    let column = try_as_column_schema(def).map_err(|err| invalid(err.to_string()))?;
354    let semantic =
355        SemanticType::try_from(def.semantic_type).map_err(|err| invalid(err.to_string()))?;
356    Ok((column, semantic))
357}
358
359fn table_columns(table: &TableRef) -> Vec<(DataColumn, SemanticType)> {
360    let info = table.table_info();
361    let primary_keys: HashSet<_> = info.meta.primary_key_indices.iter().copied().collect();
362    info.meta
363        .schema
364        .column_schemas()
365        .iter()
366        .enumerate()
367        .map(|(index, column)| {
368            let semantic = if column.is_time_index() {
369                SemanticType::Timestamp
370            } else if primary_keys.contains(&index) {
371                SemanticType::Tag
372            } else {
373                SemanticType::Field
374            };
375            (column.clone(), semantic)
376        })
377        .collect()
378}
379
380fn default_physical_columns(unit: TimeUnit) -> Vec<(DataColumn, SemanticType)> {
381    use datatypes::prelude::ConcreteDataType;
382    vec![
383        (
384            DataColumn::new(
385                greptime_timestamp(),
386                ConcreteDataType::timestamp_datatype(unit),
387                false,
388            )
389            .with_time_index(true),
390            SemanticType::Timestamp,
391        ),
392        (
393            DataColumn::new(greptime_value(), ConcreteDataType::float64_datatype(), true),
394            SemanticType::Field,
395        ),
396    ]
397}
398
399fn check_definition(
400    source: &ColumnSchema,
401    target: &DataColumn,
402    semantic: SemanticType,
403) -> Result<()> {
404    ensure!(
405        api::helper::is_column_type_value_eq(
406            source.datatype,
407            source.datatype_extension.clone(),
408            &target.data_type
409        ) && source.semantic_type == semantic as i32,
410        InvalidInsertRequestSnafu {
411            reason: format!(
412                "incompatible datatype or semantic type for column `{}`",
413                source.column_name
414            ),
415        }
416    );
417    Ok(())
418}
419
420fn validate_physical_columns(
421    rows: &Rows,
422    columns: &PhysicalColumns,
423    auto_create: bool,
424) -> Result<()> {
425    for source in &rows.schema {
426        if let Some((target, semantic)) = columns.by_name.get(&source.column_name) {
427            check_definition(source, target, *semantic)?;
428        } else {
429            ensure!(
430                auto_create,
431                InvalidInsertRequestSnafu {
432                    reason: format!(
433                        "missing physical column `{}` while auto-DDL is disabled",
434                        source.column_name
435                    )
436                }
437            );
438            ensure!(
439                source.semantic_type == SemanticType::Tag as i32
440                    || (source.semantic_type == SemanticType::Field as i32
441                        && api::helper::is_column_type_value_eq(
442                            source.datatype,
443                            source.datatype_extension.clone(),
444                            native_histogram_value_type()
445                        )),
446                InvalidInsertRequestSnafu {
447                    reason: format!("cannot add physical column `{}`", source.column_name)
448                }
449            );
450        }
451    }
452    for name in &columns.fields {
453        if !rows.schema.iter().any(|c| c.column_name == *name) {
454            let (column, _) = &columns.by_name[name];
455            ensure!(
456                !column.is_default_impure(),
457                InvalidInsertRequestSnafu {
458                    reason: format!("impure default for physical field `{}`", column.name)
459                }
460            );
461            ensure!(
462                column
463                    .create_default()
464                    .map_err(|e| invalid(e.to_string()))?
465                    .is_some(),
466                InvalidInsertRequestSnafu {
467                    reason: format!("missing required physical field `{}`", column.name)
468                }
469            );
470        }
471    }
472    Ok(())
473}
474
475/// Schema decisions are shared; row values are always checked independently.
476struct RowValidationPlan {
477    input_columns: usize,
478    schema: Vec<ColumnSchema>,
479    nullable: Vec<bool>,
480    defaults: Vec<Value>,
481    timestamp: Option<(usize, TimeUnit, TimeUnit)>,
482}
483
484impl RowValidationPlan {
485    fn new(
486        input_columns: usize,
487        source_timestamp: Option<(usize, TimeUnit)>,
488        mut template: Rows,
489        columns: &[(DataColumn, SemanticType)],
490    ) -> Result<Self> {
491        let by_name: AHashMap<_, _> = columns
492            .iter()
493            .map(|(column, semantic)| (column.name.as_str(), (column, *semantic)))
494            .collect();
495        let mut names = HashSet::new();
496        let mut nullable = Vec::with_capacity(columns.len());
497        for source in &template.schema {
498            ensure!(
499                names.insert(source.column_name.as_str()),
500                InvalidInsertRequestSnafu {
501                    reason: format!("duplicate column `{}`", source.column_name),
502                }
503            );
504            let (target, semantic) = by_name
505                .get(source.column_name.as_str())
506                .ok_or_else(|| invalid(format!("unknown column `{}`", source.column_name)))?;
507            check_definition(source, target, *semantic)?;
508            nullable.push(target.is_nullable());
509        }
510        let missing = columns
511            .iter()
512            .filter(|(column, _)| !names.contains(column.name.as_str()))
513            .collect::<Vec<_>>();
514        let mut row = template.rows.pop().context(InvalidInsertRequestSnafu {
515            reason: "missing normalization template",
516        })?;
517        // Resolve omissions before schemas are merged; an explicit null never uses a default.
518        for (column, semantic) in missing {
519            let value = column
520                .create_default()
521                .map_err(|err| invalid(err.to_string()))?
522                .ok_or_else(|| invalid(format!("missing required column `{}`", column.name)))?;
523            let (datatype, datatype_extension) =
524                ColumnDataTypeWrapper::try_from(column.data_type.clone())
525                    .map_err(|err| invalid(err.to_string()))?
526                    .into_parts();
527            template.schema.push(ColumnSchema {
528                column_name: column.name.clone(),
529                datatype: datatype as i32,
530                semantic_type: *semantic as i32,
531                datatype_extension,
532                options: None,
533            });
534            row.values.push(to_grpc_value(value));
535            nullable.push(column.is_nullable());
536        }
537        ensure!(
538            row.values.len() + input_columns == template.schema.len(),
539            InvalidInsertRequestSnafu {
540                reason: "invalid normalization template"
541            }
542        );
543        let defaults = row.values;
544        for ((source, nullable), value) in template.schema[input_columns..]
545            .iter()
546            .zip(&nullable[input_columns..])
547            .zip(&defaults)
548        {
549            validate_value(value, source, *nullable)?;
550        }
551        let timestamp = source_timestamp.and_then(|(index, source)| {
552            let target = ColumnDataType::try_from(template.schema[index].datatype)
553                .ok()
554                .and_then(api::helper::timestamp_unit)?;
555            (source != target).then_some((index, source, target))
556        });
557        Ok(Self {
558            input_columns,
559            schema: template.schema,
560            nullable,
561            defaults,
562            timestamp,
563        })
564    }
565
566    fn apply_row(&self, row: &mut Row) -> Result<()> {
567        ensure!(
568            row.values.len() == self.input_columns,
569            InvalidInsertRequestSnafu {
570                reason: "column count mismatch",
571            }
572        );
573        if let Some((index, source, target)) = self.timestamp
574            && let Some(value) = row.values[index].value_data.take()
575        {
576            row.values[index].value_data =
577                convert_timestamp_value_data(value, source, target, index)?;
578        }
579        for ((source, nullable), value) in self.schema.iter().zip(&self.nullable).zip(&row.values) {
580            validate_value(value, source, *nullable)?;
581        }
582        row.values.extend_from_slice(&self.defaults);
583        Ok(())
584    }
585}
586
587fn timestamp_column(schema: &[ColumnSchema]) -> Option<(usize, TimeUnit)> {
588    let index = schema
589        .iter()
590        .position(|column| column.semantic_type == SemanticType::Timestamp as i32)?;
591    let unit = ColumnDataType::try_from(schema[index].datatype)
592        .ok()
593        .and_then(api::helper::timestamp_unit)?;
594    Some((index, unit))
595}
596
597fn validate_value(value: &Value, source: &ColumnSchema, nullable: bool) -> Result<()> {
598    ensure!(
599        value_matches_type(value, source.datatype, source.datatype_extension.as_ref()),
600        InvalidInsertRequestSnafu {
601            reason: format!("value datatype differs for `{}`", source.column_name)
602        }
603    );
604    ensure!(
605        value.value_data.is_some() || nullable,
606        InvalidInsertRequestSnafu {
607            reason: format!(
608                "null supplied for non-nullable column `{}`",
609                source.column_name
610            ),
611        }
612    );
613    Ok(())
614}
615
616#[cfg(test)]
617fn validate_and_fill_rows(rows: &mut Rows, columns: &[(DataColumn, SemanticType)]) -> Result<()> {
618    let template = Rows {
619        schema: rows.schema.clone(),
620        rows: vec![Row::default()],
621    };
622    let plan = RowValidationPlan::new(
623        rows.schema.len(),
624        timestamp_column(&rows.schema),
625        template,
626        columns,
627    )?;
628    for row in &mut rows.rows {
629        plan.apply_row(row)?;
630    }
631    rows.schema = plan.schema;
632    Ok(())
633}
634
635#[cfg(test)]
636mod tests {
637    use api::v1::value::ValueData;
638    use api::v1::{ColumnDataType, Row};
639    use datatypes::prelude::ConcreteDataType;
640    use datatypes::schema::ColumnDefaultConstraint;
641    use datatypes::value::Value as DataValue;
642
643    use super::*;
644
645    #[test]
646    fn test_reused_plan_checks_each_value_and_timestamp() {
647        let schema = vec![api::v1::helper::time_index_column_schema(
648            greptime_timestamp(),
649            ColumnDataType::TimestampSecond,
650        )];
651        let mut template = Rows {
652            schema: schema.clone(),
653            rows: Vec::new(),
654        };
655        convert_rows_time_unit(&mut template, TimeUnit::Nanosecond).unwrap();
656        let columns = vec![(
657            DataColumn::new(
658                greptime_timestamp(),
659                ConcreteDataType::timestamp_nanosecond_datatype(),
660                false,
661            )
662            .with_time_index(true),
663            SemanticType::Timestamp,
664        )];
665        template.rows.push(Row::default());
666        let plan =
667            RowValidationPlan::new(schema.len(), timestamp_column(&schema), template, &columns)
668                .unwrap();
669        for (value, valid) in [
670            (Some(ValueData::TimestampSecondValue(1)), true),
671            (Some(ValueData::StringValue("invalid".into())), false),
672            (None, false),
673            (Some(ValueData::TimestampSecondValue(i64::MAX)), false),
674            (Some(ValueData::TimestampSecondValue(2)), true),
675        ] {
676            let mut rows = Rows {
677                schema: schema.clone(),
678                rows: vec![Row {
679                    values: vec![Value { value_data: value }],
680                }],
681            };
682            assert_eq!(plan.apply_row(&mut rows.rows[0]).is_ok(), valid);
683            if valid {
684                assert_eq!(
685                    plan.schema[0].datatype,
686                    ColumnDataType::TimestampNanosecond as i32
687                );
688                assert!(matches!(
689                    rows.rows[0].values[0].value_data,
690                    Some(ValueData::TimestampNanosecondValue(
691                        1_000_000_000 | 2_000_000_000
692                    ))
693                ));
694            }
695        }
696    }
697
698    #[test]
699    fn test_preflight_omissions_defaults_and_explicit_nulls() {
700        let mut columns = default_physical_columns(TimeUnit::Millisecond);
701        columns.push((
702            DataColumn::new("host", ConcreteDataType::string_datatype(), false)
703                .with_default_constraint(Some(ColumnDefaultConstraint::Value(DataValue::String(
704                    "unknown".into(),
705                ))))
706                .unwrap(),
707            SemanticType::Tag,
708        ));
709        let row = || Rows {
710            schema: vec![ColumnSchema {
711                column_name: greptime_timestamp().into(),
712                datatype: ColumnDataType::TimestampMillisecond as i32,
713                semantic_type: SemanticType::Timestamp as i32,
714                ..Default::default()
715            }],
716            rows: vec![Row {
717                values: vec![Value {
718                    value_data: Some(ValueData::TimestampMillisecondValue(1)),
719                }],
720            }],
721        };
722        let mut omitted = row();
723        validate_and_fill_rows(&mut omitted, &columns).unwrap();
724        assert_eq!(omitted.schema[2].column_name, "host");
725        assert_eq!(
726            omitted.rows[0].values[2].value_data,
727            Some(ValueData::StringValue("unknown".into()))
728        );
729        omitted.rows[0].values[2] = Value::default();
730        assert!(validate_and_fill_rows(&mut omitted, &columns).is_err());
731        columns[2].0 = DataColumn::new("host", ConcreteDataType::string_datatype(), false);
732        assert!(validate_and_fill_rows(&mut row(), &columns).is_err());
733        columns[2].0.set_nullable();
734        let mut nullable = row();
735        validate_and_fill_rows(&mut nullable, &columns).unwrap();
736        assert_eq!(nullable.rows[0].values[2].value_data, None);
737    }
738
739    #[test]
740    fn test_preflight_existing_columns_and_physical_definitions() {
741        let columns = default_physical_columns(TimeUnit::Millisecond);
742        let mut rows = Rows {
743            schema: vec![ColumnSchema {
744                column_name: greptime_timestamp().into(),
745                datatype: ColumnDataType::TimestampMillisecond as i32,
746                semantic_type: SemanticType::Timestamp as i32,
747                ..Default::default()
748            }],
749            rows: vec![Row {
750                values: vec![Value {
751                    value_data: Some(ValueData::TimestampMillisecondValue(1)),
752                }],
753            }],
754        };
755        validate_and_fill_rows(&mut rows, &columns).unwrap();
756        for case in 0..3 {
757            let mut invalid = rows.clone();
758            match case {
759                0 => invalid.schema[0].semantic_type = SemanticType::Tag as i32,
760                1 => invalid.schema[0].datatype = ColumnDataType::TimestampNanosecond as i32,
761                _ => {
762                    invalid.rows[0].values[0].value_data =
763                        Some(ValueData::StringValue("bad".into()))
764                }
765            }
766            assert!(validate_and_fill_rows(&mut invalid, &columns).is_err());
767        }
768        let columns = PhysicalColumns::new(columns);
769        rows.schema[1].column_name = "new_field".into();
770        assert!(validate_physical_columns(&rows, &columns, true).is_err());
771        rows.schema[1].semantic_type = SemanticType::Tag as i32;
772        rows.schema[1].datatype = ColumnDataType::String as i32;
773        assert!(validate_physical_columns(&rows, &columns, false).is_err());
774        assert!(validate_physical_columns(&rows, &columns, true).is_ok());
775    }
776
777    #[test]
778    fn test_preflight_shared_physical_field_defaults() {
779        let rows = Rows {
780            schema: vec![api::v1::helper::time_index_column_schema(
781                greptime_timestamp(),
782                ColumnDataType::TimestampMillisecond,
783            )],
784            ..Default::default()
785        };
786        let required = DataColumn::new("required", ConcreteDataType::float64_datatype(), false);
787        let defaulted = required
788            .clone()
789            .with_default_constraint(Some(ColumnDefaultConstraint::Value(DataValue::Float64(
790                1.0.into(),
791            ))))
792            .unwrap();
793        let impure = DataColumn::new(
794            "impure",
795            ConcreteDataType::timestamp_millisecond_datatype(),
796            false,
797        )
798        .with_default_constraint(Some(ColumnDefaultConstraint::Function(
799            "current_timestamp()".into(),
800        )))
801        .unwrap();
802        for (field, error) in [
803            (required, Some("missing required physical field `required`")),
804            (defaulted, None),
805            (impure, Some("impure default for physical field `impure`")),
806        ] {
807            let mut columns = default_physical_columns(TimeUnit::Millisecond);
808            columns.extend((0..1024).map(|index| {
809                (
810                    DataColumn::new(
811                        format!("unrelated_tag_{index}"),
812                        ConcreteDataType::string_datatype(),
813                        true,
814                    ),
815                    SemanticType::Tag,
816                )
817            }));
818            columns.push((field, SemanticType::Field));
819            let columns = PhysicalColumns::new(columns);
820            for auto_create in [false, true] {
821                let result = validate_physical_columns(&rows, &columns, auto_create);
822                if let Some(error) = error {
823                    assert!(result.unwrap_err().to_string().contains(error));
824                } else {
825                    result.unwrap();
826                }
827            }
828        }
829    }
830}