Skip to main content

servers/batcher/logical_table/
tables.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
15use std::collections::{HashMap, HashSet};
16use std::sync::Arc;
17
18use api::v1::{ColumnSchema, RowInsertRequests, Rows, SemanticType};
19use arrow::datatypes::Schema as ArrowSchema;
20use async_trait::async_trait;
21use common_time::timestamp::TimeUnit;
22use session::context::QueryContextRef;
23use snafu::OptionExt;
24
25use crate::batcher::logical_table::LogicalTablePendingRowsBatcher;
26use crate::batcher::logical_table::batch_convert::RecordBatchWithTsIdx;
27use crate::error;
28use crate::error::Result;
29use crate::metrics::PENDING_ROWS_BATCH_INGEST_STAGE_ELAPSED;
30use crate::prom_row_builder::{
31    build_prom_create_table_schema_from_proto, identify_missing_columns_from_proto,
32    rows_to_aligned_record_batch,
33};
34
35#[async_trait]
36pub trait PendingRowsSchemaAlterer: Send + Sync {
37    /// Returns whether `ctx` permits creating and altering tables. The batcher
38    /// cannot honor a disabled auto-create policy, so such requests keep the
39    /// ordinary insert path.
40    fn auto_create_enabled(&self, ctx: &QueryContextRef) -> bool;
41
42    /// Batch-create multiple logical tables that are missing.
43    /// Each entry is `(table_name, request_schema)`.
44    async fn create_tables_if_missing_batch(
45        &self,
46        catalog: &str,
47        schema: &str,
48        tables: &[(&str, &[ColumnSchema])],
49        ctx: QueryContextRef,
50    ) -> Result<()>;
51
52    /// Batch-alter multiple logical tables to add missing tag columns.
53    /// Each entry is `(table_name, missing_column_names)`.
54    async fn add_missing_prom_tag_columns_batch(
55        &self,
56        catalog: &str,
57        schema: &str,
58        tables: &[(&str, &[String])],
59        ctx: QueryContextRef,
60    ) -> Result<()>;
61}
62
63pub type PendingRowsSchemaAltererRef = Arc<dyn PendingRowsSchemaAlterer>;
64
65/// Intermediate planning state for resolving and preparing logical tables
66/// before row-to-batch alignment.
67pub(in crate::batcher::logical_table) struct TableResolutionPlan {
68    /// Resolved table schema and table id by logical table name.
69    pub(in crate::batcher::logical_table) region_schemas: HashMap<String, (Arc<ArrowSchema>, u32)>,
70    /// Missing tables that need to be created before alignment.
71    pub(in crate::batcher::logical_table) tables_to_create: Vec<(String, Vec<ColumnSchema>)>,
72    /// Existing tables that need tag-column schema evolution.
73    pub(in crate::batcher::logical_table) tables_to_alter: Vec<(String, Vec<String>)>,
74}
75
76impl LogicalTablePendingRowsBatcher {
77    /// Converts proto `RowInsertRequests` directly into aligned `RecordBatch`es
78    /// in a single pass, handling table creation, schema alteration, column
79    /// renaming, reordering, and null-filling without building intermediate
80    /// RecordBatches.
81    pub(in crate::batcher::logical_table) async fn build_and_align_table_batches(
82        &self,
83        requests: &RowInsertRequests,
84        ctx: &QueryContextRef,
85    ) -> Result<(Vec<(String, u32, RecordBatchWithTsIdx)>, usize)> {
86        let catalog = ctx.current_catalog().to_string();
87        let schema = ctx.current_schema();
88
89        let (table_rows, total_rows) = Self::collect_non_empty_table_rows(requests);
90        if total_rows == 0 {
91            return Ok((Vec::new(), 0));
92        }
93
94        let unique_tables = Self::collect_unique_table_schemas(&table_rows)?;
95        let mut plan = self
96            .plan_table_resolution(&catalog, &schema, ctx, &unique_tables)
97            .await?;
98
99        // New tables are created on the request's selected physical table;
100        // their time index must use the physical table's unit (a missing
101        // physical table is auto-created in the configured auto-create unit
102        // by the schema alterer, matching the fallback here).
103        if !plan.tables_to_create.is_empty() {
104            let physical_unit = self.physical_time_index_unit_or_default(ctx).await;
105            for (_, request_schema) in &mut plan.tables_to_create {
106                align_create_schema_time_index(request_schema, physical_unit);
107            }
108        }
109
110        self.create_missing_tables_and_refresh_schemas(
111            &catalog,
112            &schema,
113            ctx,
114            &table_rows,
115            &mut plan,
116        )
117        .await?;
118
119        self.alter_tables_and_refresh_schemas(&catalog, &schema, ctx, &mut plan)
120            .await?;
121
122        let aligned_batches = Self::build_aligned_batches(&table_rows, &plan.region_schemas)?;
123
124        Ok((aligned_batches, total_rows))
125    }
126}
127
128/// Rewrites the time index column of a create-table schema to `unit`, if the
129/// schema carries a timestamp column in another unit.
130fn align_create_schema_time_index(request_schema: &mut [ColumnSchema], unit: TimeUnit) {
131    for column in request_schema {
132        if column.semantic_type == SemanticType::Timestamp as i32 {
133            column.datatype = api::helper::timestamp_datatype(unit) as i32;
134            column.datatype_extension = None;
135        }
136    }
137}
138
139impl LogicalTablePendingRowsBatcher {
140    /// Extracts non-empty `(table_name, rows)` pairs and computes total row
141    /// count across the retained entries.
142    pub(in crate::batcher::logical_table) fn collect_non_empty_table_rows(
143        requests: &RowInsertRequests,
144    ) -> (Vec<(&str, &Rows)>, usize) {
145        let mut table_rows: Vec<(&str, &Rows)> = Vec::with_capacity(requests.inserts.len());
146        let mut total_rows = 0;
147
148        for request in &requests.inserts {
149            let Some(rows) = &request.rows else {
150                continue;
151            };
152            if rows.rows.is_empty() {
153                continue;
154            }
155
156            total_rows += rows.rows.len();
157            table_rows.push((request.table_name.as_str(), rows));
158        }
159
160        (table_rows, total_rows)
161    }
162}
163
164impl LogicalTablePendingRowsBatcher {
165    /// Returns unique `(table_name, proto_schema)` pairs while keeping the
166    /// first-seen schema for duplicate table names.
167    pub(in crate::batcher::logical_table) fn collect_unique_table_schemas<'a>(
168        table_rows: &[(&'a str, &'a Rows)],
169    ) -> Result<Vec<(&'a str, &'a [ColumnSchema])>> {
170        let mut unique_tables: Vec<(&str, &[ColumnSchema])> = Vec::with_capacity(table_rows.len());
171        let mut seen = HashSet::new();
172
173        for (table_name, rows) in table_rows {
174            if seen.insert(*table_name) {
175                unique_tables.push((*table_name, &rows.schema));
176            } else {
177                // table_rows should group rows by table name.
178                return error::InvalidPromRemoteRequestSnafu {
179                    msg: format!(
180                        "Found duplicated table name in RowInsertRequest: {}",
181                        table_name
182                    ),
183                }
184                .fail();
185            }
186        }
187
188        Ok(unique_tables)
189    }
190}
191
192impl LogicalTablePendingRowsBatcher {
193    /// Resolves table metadata and classifies each table into existing,
194    /// to-create, and to-alter groups used by subsequent DDL steps.
195    pub(in crate::batcher::logical_table) async fn plan_table_resolution(
196        &self,
197        catalog: &str,
198        schema: &str,
199        ctx: &QueryContextRef,
200        unique_tables: &[(&str, &[ColumnSchema])],
201    ) -> Result<TableResolutionPlan> {
202        let mut plan = TableResolutionPlan {
203            region_schemas: HashMap::with_capacity(unique_tables.len()),
204            tables_to_create: Vec::new(),
205            tables_to_alter: Vec::new(),
206        };
207
208        let resolved_tables = {
209            let _timer = PENDING_ROWS_BATCH_INGEST_STAGE_ELAPSED
210                .with_label_values(&["align_resolve_table"])
211                .start_timer();
212            futures::future::join_all(unique_tables.iter().map(|(table_name, _)| {
213                self.catalog_manager
214                    .table(catalog, schema, table_name, Some(ctx.as_ref()))
215            }))
216            .await
217        };
218
219        for ((table_name, rows_schema), table_result) in unique_tables.iter().zip(resolved_tables) {
220            let table = table_result?;
221
222            if let Some(table) = table {
223                let table_info = table.table_info();
224                let table_id = table_info.ident.table_id;
225                let region_schema = table_info.meta.schema.arrow_schema().clone();
226
227                let missing_columns = {
228                    let _timer = PENDING_ROWS_BATCH_INGEST_STAGE_ELAPSED
229                        .with_label_values(&["align_identify_missing_columns"])
230                        .start_timer();
231                    identify_missing_columns_from_proto(rows_schema, region_schema.as_ref())?
232                };
233                if !missing_columns.is_empty() {
234                    plan.tables_to_alter
235                        .push(((*table_name).to_string(), missing_columns));
236                }
237                plan.region_schemas
238                    .insert((*table_name).to_string(), (region_schema, table_id));
239            } else {
240                let request_schema = {
241                    let _timer = PENDING_ROWS_BATCH_INGEST_STAGE_ELAPSED
242                        .with_label_values(&["align_build_create_table_schema"])
243                        .start_timer();
244                    build_prom_create_table_schema_from_proto(rows_schema)?
245                };
246                plan.tables_to_create
247                    .push(((*table_name).to_string(), request_schema));
248            }
249        }
250
251        Ok(plan)
252    }
253}
254
255impl LogicalTablePendingRowsBatcher {
256    /// Batch-creates missing tables, refreshes their schema metadata, and
257    /// enqueues follow-up alters for extra tag columns discovered in later rows.
258    pub(in crate::batcher::logical_table) async fn create_missing_tables_and_refresh_schemas(
259        &self,
260        catalog: &str,
261        schema: &str,
262        ctx: &QueryContextRef,
263        table_rows: &[(&str, &Rows)],
264        plan: &mut TableResolutionPlan,
265    ) -> Result<()> {
266        if plan.tables_to_create.is_empty() {
267            return Ok(());
268        }
269
270        let create_refs: Vec<(&str, &[ColumnSchema])> = plan
271            .tables_to_create
272            .iter()
273            .map(|(name, schema)| (name.as_str(), schema.as_slice()))
274            .collect();
275
276        {
277            let _timer = PENDING_ROWS_BATCH_INGEST_STAGE_ELAPSED
278                .with_label_values(&["align_batch_create_tables"])
279                .start_timer();
280            self.schema_alterer
281                .create_tables_if_missing_batch(catalog, schema, &create_refs, ctx.clone())
282                .await?;
283        }
284
285        let created_table_results = {
286            let _timer = PENDING_ROWS_BATCH_INGEST_STAGE_ELAPSED
287                .with_label_values(&["align_resolve_table_after_create"])
288                .start_timer();
289            futures::future::join_all(plan.tables_to_create.iter().map(|(table_name, _)| {
290                self.catalog_manager
291                    .table(catalog, schema, table_name, Some(ctx.as_ref()))
292            }))
293            .await
294        };
295
296        for ((table_name, _), table_result) in
297            plan.tables_to_create.iter().zip(created_table_results)
298        {
299            let table = table_result?.with_context(|| error::UnexpectedResultSnafu {
300                reason: format!(
301                    "Table not found after pending batch create attempt: {}",
302                    table_name
303                ),
304            })?;
305            let table_info = table.table_info();
306            let table_id = table_info.ident.table_id;
307            let region_schema = table_info.meta.schema.arrow_schema().clone();
308            plan.region_schemas
309                .insert(table_name.clone(), (region_schema, table_id));
310        }
311
312        Self::enqueue_alter_for_new_tables(table_rows, plan)?;
313
314        Ok(())
315    }
316}
317
318impl LogicalTablePendingRowsBatcher {
319    /// For newly created tables, re-checks all row schemas and appends alter
320    /// operations when additional tag columns are still missing.
321    pub(in crate::batcher::logical_table) fn enqueue_alter_for_new_tables(
322        table_rows: &[(&str, &Rows)],
323        plan: &mut TableResolutionPlan,
324    ) -> Result<()> {
325        let created_tables: HashSet<&str> = plan
326            .tables_to_create
327            .iter()
328            .map(|(table_name, _)| table_name.as_str())
329            .collect();
330
331        for (table_name, rows) in table_rows {
332            if !created_tables.contains(table_name) {
333                continue;
334            }
335
336            let Some((region_schema, _)) = plan.region_schemas.get(*table_name) else {
337                continue;
338            };
339
340            let missing_columns = identify_missing_columns_from_proto(&rows.schema, region_schema)?;
341            if missing_columns.is_empty()
342                || plan
343                    .tables_to_alter
344                    .iter()
345                    .any(|(existing_name, _)| existing_name == *table_name)
346            {
347                continue;
348            }
349
350            plan.tables_to_alter
351                .push((table_name.to_string(), missing_columns));
352        }
353
354        Ok(())
355    }
356}
357
358impl LogicalTablePendingRowsBatcher {
359    /// Batch-alters tables that have missing tag columns and refreshes the
360    /// in-memory schema map used for row alignment.
361    pub(in crate::batcher::logical_table) async fn alter_tables_and_refresh_schemas(
362        &self,
363        catalog: &str,
364        schema: &str,
365        ctx: &QueryContextRef,
366        plan: &mut TableResolutionPlan,
367    ) -> Result<()> {
368        if plan.tables_to_alter.is_empty() {
369            return Ok(());
370        }
371
372        let alter_refs: Vec<(&str, &[String])> = plan
373            .tables_to_alter
374            .iter()
375            .map(|(name, cols)| (name.as_str(), cols.as_slice()))
376            .collect();
377        {
378            let _timer = PENDING_ROWS_BATCH_INGEST_STAGE_ELAPSED
379                .with_label_values(&["align_batch_add_missing_columns"])
380                .start_timer();
381            self.schema_alterer
382                .add_missing_prom_tag_columns_batch(catalog, schema, &alter_refs, ctx.clone())
383                .await?;
384        }
385
386        let altered_table_results = {
387            let _timer = PENDING_ROWS_BATCH_INGEST_STAGE_ELAPSED
388                .with_label_values(&["align_resolve_table_after_schema_alter"])
389                .start_timer();
390            futures::future::join_all(plan.tables_to_alter.iter().map(|(table_name, _)| {
391                self.catalog_manager
392                    .table(catalog, schema, table_name, Some(ctx.as_ref()))
393            }))
394            .await
395        };
396
397        for ((table_name, _), table_result) in
398            plan.tables_to_alter.iter().zip(altered_table_results)
399        {
400            let table = table_result?.with_context(|| error::UnexpectedResultSnafu {
401                reason: format!(
402                    "Table not found after pending batch schema alter: {}",
403                    table_name
404                ),
405            })?;
406            let table_info = table.table_info();
407            let table_id = table_info.ident.table_id;
408            let refreshed_region_schema = table_info.meta.schema.arrow_schema().clone();
409            plan.region_schemas
410                .insert(table_name.clone(), (refreshed_region_schema, table_id));
411        }
412
413        Ok(())
414    }
415}
416
417impl LogicalTablePendingRowsBatcher {
418    /// Converts proto rows to `RecordBatch` values aligned to resolved region
419    /// schemas and returns `(table_name, table_id, batch)` tuples.
420    pub(in crate::batcher::logical_table) fn build_aligned_batches(
421        table_rows: &[(&str, &Rows)],
422        region_schemas: &HashMap<String, (Arc<ArrowSchema>, u32)>,
423    ) -> Result<Vec<(String, u32, RecordBatchWithTsIdx)>> {
424        let mut aligned_batches = Vec::with_capacity(table_rows.len());
425        for (table_name, rows) in table_rows {
426            let (region_schema, table_id) =
427                region_schemas.get(*table_name).cloned().with_context(|| {
428                    error::UnexpectedResultSnafu {
429                        reason: format!("Region schema not resolved for table: {}", table_name),
430                    }
431                })?;
432
433            let record_batch = {
434                let _timer = PENDING_ROWS_BATCH_INGEST_STAGE_ELAPSED
435                    .with_label_values(&["align_rows_to_record_batch"])
436                    .start_timer();
437                rows_to_aligned_record_batch(rows, region_schema.as_ref())?
438            };
439            aligned_batches.push((table_name.to_string(), table_id, record_batch));
440        }
441
442        Ok(aligned_batches)
443    }
444}
445
446#[cfg(test)]
447mod tests {
448
449    use api::v1::value::ValueData;
450    use api::v1::{
451        ColumnDataType, ColumnSchema, Row, RowInsertRequest, RowInsertRequests, Rows, SemanticType,
452        Value,
453    };
454    use arrow::datatypes::{DataType as ArrowDataType, Field, Schema as ArrowSchema};
455    use common_query::prelude::greptime_timestamp;
456
457    use crate::batcher::logical_table::LogicalTablePendingRowsBatcher;
458    use crate::batcher::logical_table::batch_convert::TableBatch;
459    use crate::batcher::logical_table::flow_notifier::extract_timestamps;
460    use crate::prom_row_builder::rows_to_aligned_record_batch;
461
462    #[test]
463    fn test_extract_timestamps_uses_aligned_custom_timestamp_index() {
464        let rows = Rows {
465            schema: vec![
466                ColumnSchema {
467                    column_name: greptime_timestamp().to_string(),
468                    datatype: ColumnDataType::TimestampMillisecond as i32,
469                    semantic_type: SemanticType::Timestamp as i32,
470                    ..Default::default()
471                },
472                ColumnSchema {
473                    column_name: "host".to_string(),
474                    datatype: ColumnDataType::String as i32,
475                    semantic_type: SemanticType::Tag as i32,
476                    ..Default::default()
477                },
478                ColumnSchema {
479                    column_name: "greptime_value".to_string(),
480                    datatype: ColumnDataType::Float64 as i32,
481                    semantic_type: SemanticType::Field as i32,
482                    ..Default::default()
483                },
484            ],
485            rows: vec![
486                Row {
487                    values: vec![
488                        Value {
489                            value_data: Some(ValueData::TimestampMillisecondValue(1000)),
490                        },
491                        Value {
492                            value_data: Some(ValueData::StringValue("host-1".to_string())),
493                        },
494                        Value {
495                            value_data: Some(ValueData::F64Value(1.0)),
496                        },
497                    ],
498                },
499                Row {
500                    values: vec![
501                        Value {
502                            value_data: Some(ValueData::TimestampMillisecondValue(2000)),
503                        },
504                        Value {
505                            value_data: Some(ValueData::StringValue("host-2".to_string())),
506                        },
507                        Value {
508                            value_data: Some(ValueData::F64Value(2.0)),
509                        },
510                    ],
511                },
512            ],
513        };
514        let target_schema = ArrowSchema::new(vec![
515            Field::new("host", ArrowDataType::Utf8, true),
516            Field::new(
517                "timestamp",
518                ArrowDataType::Timestamp(arrow::datatypes::TimeUnit::Millisecond, None),
519                false,
520            ),
521            Field::new("greptime_value", ArrowDataType::Float64, true),
522        ]);
523        let batch = rows_to_aligned_record_batch(&rows, &target_schema).unwrap();
524        assert_eq!(1, batch.timestamp_index);
525        let table_batch = TableBatch {
526            table_name: "cpu".to_string(),
527            table_id: 42,
528            row_count: batch.batch.num_rows(),
529            batches: vec![batch],
530        };
531
532        assert_eq!(vec![1000, 2000], extract_timestamps(&table_batch));
533    }
534
535    #[test]
536    fn test_collect_non_empty_table_rows_filters_empty_payloads() {
537        let requests = RowInsertRequests {
538            inserts: vec![
539                RowInsertRequest {
540                    table_name: "cpu".to_string(),
541                    rows: Some(mock_rows(2, "host")),
542                },
543                RowInsertRequest {
544                    table_name: "mem".to_string(),
545                    rows: Some(mock_rows(0, "host")),
546                },
547                RowInsertRequest {
548                    table_name: "disk".to_string(),
549                    rows: None,
550                },
551            ],
552        };
553
554        let (table_rows, total_rows) =
555            LogicalTablePendingRowsBatcher::collect_non_empty_table_rows(&requests);
556
557        assert_eq!(2, total_rows);
558        assert_eq!(1, table_rows.len());
559        assert_eq!("cpu", table_rows[0].0);
560        assert_eq!(2, table_rows[0].1.rows.len());
561    }
562
563    fn mock_rows(row_count: usize, schema_name: &str) -> Rows {
564        Rows {
565            schema: vec![ColumnSchema {
566                column_name: schema_name.to_string(),
567                ..Default::default()
568            }],
569            rows: (0..row_count).map(|_| Row { values: vec![] }).collect(),
570        }
571    }
572}