Skip to main content

operator/
insert.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::sync::Arc;
16
17use ahash::{HashMap, HashMapExt, HashSet, HashSetExt};
18use api::v1::alter_table_expr::Kind;
19use api::v1::column_def::options_from_skipping;
20use api::v1::region::{
21    InsertRequest as RegionInsertRequest, InsertRequests as RegionInsertRequests,
22    RegionRequestHeader,
23};
24use api::v1::{
25    AlterTableExpr, ColumnDataType, ColumnSchema, CreateTableExpr, InsertRequests,
26    RowInsertRequest, RowInsertRequests, SemanticType,
27};
28use catalog::CatalogManagerRef;
29use client::{OutputData, OutputMeta};
30use common_catalog::consts::{
31    PARENT_SPAN_ID_COLUMN, SERVICE_NAME_COLUMN, TRACE_ID_COLUMN, TRACE_TABLE_NAME,
32    TRACE_TABLE_NAME_SESSION_KEY, default_engine, is_ddl_reserved_table,
33    trace_operations_table_name, trace_services_table_name,
34};
35use common_grpc_expr::util::ColumnExpr;
36use common_meta::cache::TableFlownodeSetCacheRef;
37use common_meta::node_manager::{AffectedRows, NodeManagerRef};
38use common_meta::peer::Peer;
39use common_meta::rpc::ddl::TriggerReason;
40use common_query::Output;
41use common_query::native_histogram::{is_native_histogram_value_type, native_histogram_value_type};
42use common_query::prelude::{greptime_timestamp, greptime_value};
43use common_telemetry::tracing_context::TracingContext;
44use common_telemetry::{error, info, warn};
45use datatypes::schema::SkippingIndexOptions;
46use futures_util::future;
47use meter_macros::write_meter;
48use partition::manager::PartitionRuleManagerRef;
49use session::context::QueryContextRef;
50use snafu::ResultExt;
51use snafu::prelude::*;
52use sql::partition::partition_rule_for_hexstring;
53use sql::statements::create::Partitions;
54use sql::statements::insert::Insert;
55use store_api::metric_engine_consts::{
56    LOGICAL_TABLE_METADATA_KEY, METRIC_ENGINE_NAME, PHYSICAL_TABLE_METADATA_KEY,
57};
58use store_api::mito_engine_options::{
59    APPEND_MODE_KEY, COMPACTION_TYPE, COMPACTION_TYPE_TWCS, MERGE_MODE_KEY, TTL_KEY,
60    TWCS_TIME_WINDOW,
61};
62use store_api::storage::{RegionId, TableId};
63use table::TableRef;
64use table::metadata::TableInfo;
65use table::requests::{
66    AUTO_CREATE_TABLE_KEY, InsertRequest as TableInsertRequest, SEMANTIC_PER_TABLE_INDEX_KEY,
67    TABLE_DATA_MODEL, TABLE_DATA_MODEL_TRACE_V1, TRACE_TABLE_PARTITIONS_HINT_KEY,
68    VALID_TABLE_OPTION_KEYS, is_semantic_option_key, validate_semantic_option,
69};
70use table::table_reference::TableReference;
71
72use crate::error::{
73    CatalogSnafu, ColumnOptionsSnafu, CreatePartitionRulesSnafu, FindRegionLeaderSnafu,
74    InvalidInsertRequestSnafu, JoinTaskSnafu, RequestInsertsSnafu, Result, TableNotFoundSnafu,
75};
76use crate::expr_helper;
77use crate::region_req_factory::RegionRequestFactory;
78use crate::req_convert::common::preprocess_row_insert_requests;
79use crate::req_convert::insert::{
80    ColumnToRow, RowToRegion, StatementToRegion, TableToRegion, fill_reqs_with_impure_default,
81};
82use crate::statement::StatementExecutor;
83
84pub struct Inserter {
85    catalog_manager: CatalogManagerRef,
86    pub(crate) partition_manager: PartitionRuleManagerRef,
87    pub(crate) node_manager: NodeManagerRef,
88    pub(crate) table_flownode_set_cache: TableFlownodeSetCacheRef,
89    /// Server-side upper bound for auto table creation on write.
90    /// When `false`, missing tables are never auto-created regardless of the
91    /// per-request `auto_create_table` hint. When `true`, the hint still applies.
92    auto_create_table: bool,
93}
94
95pub type InserterRef = Arc<Inserter>;
96
97/// Hint for the table type to create automatically.
98#[derive(Clone)]
99pub enum AutoCreateTableType {
100    /// A logical table with the physical table name.
101    Logical(String),
102    /// A physical table.
103    Physical,
104    /// A log table which is append-only.
105    Log,
106    /// A table that merges rows by `last_non_null` strategy.
107    LastNonNull,
108    /// Create table that build index and default partition rules on trace_id
109    Trace { alter_existing: bool },
110}
111
112impl AutoCreateTableType {
113    pub fn as_str(&self) -> &'static str {
114        match self {
115            AutoCreateTableType::Logical(_) => "logical",
116            AutoCreateTableType::Physical => "physical",
117            AutoCreateTableType::Log => "log",
118            AutoCreateTableType::LastNonNull => "last_non_null",
119            AutoCreateTableType::Trace { .. } => "trace",
120        }
121    }
122
123    fn alter_existing(&self) -> bool {
124        !matches!(
125            self,
126            Self::Trace {
127                alter_existing: false
128            }
129        )
130    }
131}
132
133/// Split insert requests into normal and instant requests.
134///
135/// Where instant requests are requests with ttl=instant,
136/// and normal requests are requests with ttl set to other values.
137///
138/// This is used to split requests for different processing.
139#[derive(Clone)]
140pub struct InstantAndNormalInsertRequests {
141    /// Requests with normal ttl.
142    pub normal_requests: RegionInsertRequests,
143    /// Requests with ttl=instant.
144    /// Will be discarded immediately at frontend, wouldn't even insert into memtable, and only sent to flow node if needed.
145    pub instant_requests: RegionInsertRequests,
146}
147
148impl Inserter {
149    pub fn new(
150        catalog_manager: CatalogManagerRef,
151        partition_manager: PartitionRuleManagerRef,
152        node_manager: NodeManagerRef,
153        table_flownode_set_cache: TableFlownodeSetCacheRef,
154        auto_create_table: bool,
155    ) -> Self {
156        Self {
157            catalog_manager,
158            partition_manager,
159            node_manager,
160            table_flownode_set_cache,
161            auto_create_table,
162        }
163    }
164
165    pub async fn handle_column_inserts(
166        &self,
167        requests: InsertRequests,
168        ctx: QueryContextRef,
169        statement_executor: &StatementExecutor,
170    ) -> Result<Output> {
171        let row_inserts = ColumnToRow::convert(requests)?;
172        self.handle_row_inserts(row_inserts, ctx, statement_executor, false, false)
173            .await
174    }
175
176    /// Handles row inserts request and creates a physical table on demand.
177    pub async fn handle_row_inserts(
178        &self,
179        mut requests: RowInsertRequests,
180        ctx: QueryContextRef,
181        statement_executor: &StatementExecutor,
182        accommodate_existing_schema: bool,
183        is_single_value: bool,
184    ) -> Result<Output> {
185        preprocess_row_insert_requests(&mut requests.inserts)?;
186        self.handle_row_inserts_with_create_type(
187            requests,
188            ctx,
189            statement_executor,
190            AutoCreateTableType::Physical,
191            accommodate_existing_schema,
192            is_single_value,
193        )
194        .await
195    }
196
197    /// Handles row inserts request and creates a log table on demand.
198    pub async fn handle_log_inserts(
199        &self,
200        requests: RowInsertRequests,
201        ctx: QueryContextRef,
202        statement_executor: &StatementExecutor,
203    ) -> Result<Output> {
204        self.handle_row_inserts_with_create_type(
205            requests,
206            ctx,
207            statement_executor,
208            AutoCreateTableType::Log,
209            false,
210            false,
211        )
212        .await
213    }
214
215    pub async fn handle_trace_inserts(
216        &self,
217        requests: RowInsertRequests,
218        ctx: QueryContextRef,
219        statement_executor: &StatementExecutor,
220    ) -> Result<Output> {
221        self.handle_row_inserts_with_create_type(
222            requests,
223            ctx,
224            statement_executor,
225            AutoCreateTableType::Trace {
226                alter_existing: true,
227            },
228            false,
229            false,
230        )
231        .await
232    }
233
234    /// Handles row inserts request and creates a table with `last_non_null` merge mode on demand.
235    pub async fn handle_last_non_null_inserts(
236        &self,
237        requests: RowInsertRequests,
238        ctx: QueryContextRef,
239        statement_executor: &StatementExecutor,
240        accommodate_existing_schema: bool,
241        is_single_value: bool,
242    ) -> Result<Output> {
243        self.handle_row_inserts_with_create_type(
244            requests,
245            ctx,
246            statement_executor,
247            AutoCreateTableType::LastNonNull,
248            accommodate_existing_schema,
249            is_single_value,
250        )
251        .await
252    }
253
254    /// Handles row inserts request with specified [AutoCreateTableType].
255    async fn handle_row_inserts_with_create_type(
256        &self,
257        mut requests: RowInsertRequests,
258        ctx: QueryContextRef,
259        statement_executor: &StatementExecutor,
260        create_type: AutoCreateTableType,
261        accommodate_existing_schema: bool,
262        is_single_value: bool,
263    ) -> Result<Output> {
264        // remove empty requests
265        requests.inserts.retain(|req| {
266            req.rows
267                .as_ref()
268                .map(|r| !r.rows.is_empty())
269                .unwrap_or_default()
270        });
271        validate_column_count_match(&requests)?;
272
273        let CreateAlterTableResult {
274            instant_table_ids,
275            table_infos,
276        } = self
277            .create_or_alter_tables_on_demand(
278                &mut requests,
279                &ctx,
280                create_type,
281                statement_executor,
282                accommodate_existing_schema,
283                is_single_value,
284            )
285            .await?;
286
287        let name_to_info = table_infos
288            .values()
289            .map(|info| (info.name.clone(), info.clone()))
290            .collect::<HashMap<_, _>>();
291        let inserts = RowToRegion::new(
292            name_to_info,
293            instant_table_ids,
294            self.partition_manager.as_ref(),
295        )
296        .convert(requests)
297        .await?;
298
299        self.do_request(inserts, &table_infos, &ctx).await
300    }
301
302    /// Handles row inserts request with metric engine.
303    pub async fn handle_metric_row_inserts(
304        &self,
305        mut requests: RowInsertRequests,
306        ctx: QueryContextRef,
307        statement_executor: &StatementExecutor,
308        physical_table: String,
309    ) -> Result<Output> {
310        // remove empty requests
311        requests.inserts.retain(|req| {
312            req.rows
313                .as_ref()
314                .map(|r| !r.rows.is_empty())
315                .unwrap_or_default()
316        });
317        validate_column_count_match(&requests)?;
318
319        // check and create physical table
320        self.create_physical_table_on_demand(&ctx, physical_table.clone(), statement_executor)
321            .await?;
322
323        // check and create logical tables
324        let CreateAlterTableResult {
325            instant_table_ids,
326            table_infos,
327        } = self
328            .create_or_alter_tables_on_demand(
329                &mut requests,
330                &ctx,
331                AutoCreateTableType::Logical(physical_table.clone()),
332                statement_executor,
333                true,
334                true,
335            )
336            .await?;
337        let name_to_info = table_infos
338            .values()
339            .map(|info| (info.name.clone(), info.clone()))
340            .collect::<HashMap<_, _>>();
341        let inserts = RowToRegion::new(name_to_info, instant_table_ids, &self.partition_manager)
342            .convert(requests)
343            .await?;
344
345        self.do_request(inserts, &table_infos, &ctx).await
346    }
347
348    pub async fn handle_table_insert(
349        &self,
350        request: TableInsertRequest,
351        ctx: QueryContextRef,
352    ) -> Result<Output> {
353        let catalog = request.catalog_name.as_str();
354        let schema = request.schema_name.as_str();
355        let table_name = request.table_name.as_str();
356        let table = self.get_table(catalog, schema, table_name).await?;
357        let table = table.with_context(|| TableNotFoundSnafu {
358            table_name: common_catalog::format_full_table_name(catalog, schema, table_name),
359        })?;
360        let table_info = table.table_info();
361
362        let inserts = TableToRegion::new(&table_info, &self.partition_manager)
363            .convert(request)
364            .await?;
365
366        let table_infos = HashMap::from_iter([(table_info.table_id(), table_info.clone())]);
367
368        self.do_request(inserts, &table_infos, &ctx).await
369    }
370
371    pub async fn handle_statement_insert(
372        &self,
373        insert: &Insert,
374        ctx: &QueryContextRef,
375    ) -> Result<Output> {
376        let (inserts, table_info) =
377            StatementToRegion::new(self.catalog_manager.as_ref(), &self.partition_manager, ctx)
378                .convert(insert, ctx)
379                .await?;
380
381        let table_infos = HashMap::from_iter([(table_info.table_id(), table_info.clone())]);
382
383        self.do_request(inserts, &table_infos, ctx).await
384    }
385}
386
387impl Inserter {
388    async fn do_request(
389        &self,
390        requests: InstantAndNormalInsertRequests,
391        table_infos: &HashMap<TableId, Arc<TableInfo>>,
392        ctx: &QueryContextRef,
393    ) -> Result<Output> {
394        // Fill impure default values in the request
395        let requests = fill_reqs_with_impure_default(table_infos, requests)?;
396
397        let write_cost = write_meter!(
398            ctx.current_catalog(),
399            ctx.current_schema(),
400            requests,
401            ctx.channel() as u8
402        );
403        let request_factory = RegionRequestFactory::new(RegionRequestHeader {
404            tracing_context: TracingContext::from_current_span().to_w3c(),
405            dbname: ctx.get_db_string(),
406            ..Default::default()
407        });
408
409        let InstantAndNormalInsertRequests {
410            normal_requests,
411            instant_requests,
412        } = requests;
413
414        // Mirror requests for source table to flownode asynchronously
415        let flow_mirror_task = FlowMirrorTask::new(
416            &self.table_flownode_set_cache,
417            normal_requests
418                .requests
419                .iter()
420                .chain(instant_requests.requests.iter()),
421        )
422        .await?;
423        flow_mirror_task.detach(self.node_manager.clone())?;
424
425        // Write requests to datanode and wait for response
426        let write_tasks = self
427            .group_requests_by_peer(normal_requests)
428            .await?
429            .into_iter()
430            .map(|(peer, inserts)| {
431                let node_manager = self.node_manager.clone();
432                let request = request_factory.build_insert(inserts);
433                common_runtime::spawn_global(async move {
434                    node_manager
435                        .datanode(&peer)
436                        .await
437                        .handle(request)
438                        .await
439                        .context(RequestInsertsSnafu)
440                })
441            });
442        let results = future::try_join_all(write_tasks)
443            .await
444            .context(JoinTaskSnafu)?;
445        let affected_rows = results
446            .into_iter()
447            .map(|resp| resp.map(|r| r.affected_rows))
448            .sum::<Result<AffectedRows>>()?;
449        crate::metrics::DIST_INGEST_ROW_COUNT
450            .with_label_values(&[ctx.get_db_string().as_str()])
451            .inc_by(affected_rows as u64);
452        Ok(Output::new(
453            OutputData::AffectedRows(affected_rows),
454            OutputMeta::new_with_cost(write_cost as _),
455        ))
456    }
457
458    async fn group_requests_by_peer(
459        &self,
460        requests: RegionInsertRequests,
461    ) -> Result<HashMap<Peer, RegionInsertRequests>> {
462        // group by region ids first to reduce repeatedly call `find_region_leader`
463        // TODO(discord9): determine if a addition clone is worth it
464        let mut requests_per_region: HashMap<RegionId, RegionInsertRequests> = HashMap::new();
465        for req in requests.requests {
466            let region_id = RegionId::from_u64(req.region_id);
467            requests_per_region
468                .entry(region_id)
469                .or_default()
470                .requests
471                .push(req);
472        }
473
474        let mut inserts: HashMap<Peer, RegionInsertRequests> = HashMap::new();
475
476        for (region_id, reqs) in requests_per_region {
477            let peer = self
478                .partition_manager
479                .find_region_leader(region_id)
480                .await
481                .context(FindRegionLeaderSnafu)?;
482            inserts
483                .entry(peer)
484                .or_default()
485                .requests
486                .extend(reqs.requests);
487        }
488
489        Ok(inserts)
490    }
491
492    /// Returns `None` if auto table creation is allowed, or `Some(reason)` if
493    /// disabled by either the global config or the request hint. The reason tells
494    /// which one, for a clearer error.
495    fn auto_create_disabled_reason(&self, ctx: &QueryContextRef) -> Result<Option<&'static str>> {
496        let auto_create_table_hint = ctx
497            .extension(AUTO_CREATE_TABLE_KEY)
498            .map(|v| v.parse::<bool>())
499            .transpose()
500            .map_err(|_| {
501                InvalidInsertRequestSnafu {
502                    reason: "`auto_create_table` hint must be a boolean",
503                }
504                .build()
505            })?
506            .unwrap_or(true);
507        Ok(if !self.auto_create_table {
508            Some("auto-create table is disabled by frontend config")
509        } else if !auto_create_table_hint {
510            Some("`auto_create_table` hint is disabled")
511        } else {
512            None
513        })
514    }
515
516    /// Ensures a trace table has the request-global schema without requiring a
517    /// padded data row to drive on-demand creation or alteration. When
518    /// `alter_existing` is false, a table created after planning is left for the
519    /// caller to re-plan.
520    pub async fn ensure_trace_table_on_demand(
521        &self,
522        table_name: &str,
523        request_schema: Vec<ColumnSchema>,
524        alter_existing: bool,
525        ctx: &QueryContextRef,
526        statement_executor: &StatementExecutor,
527    ) -> Result<()> {
528        let mut requests = RowInsertRequests {
529            inserts: vec![RowInsertRequest {
530                table_name: table_name.to_string(),
531                rows: Some(api::v1::Rows {
532                    schema: request_schema,
533                    rows: Vec::new(),
534                }),
535            }],
536        };
537        self.create_or_alter_tables_on_demand(
538            &mut requests,
539            ctx,
540            AutoCreateTableType::Trace { alter_existing },
541            statement_executor,
542            false,
543            false,
544        )
545        .await?;
546        Ok(())
547    }
548
549    /// Creates or alter tables on demand:
550    /// - if table does not exist, create table by inferred CreateExpr
551    /// - if table exist, check if schema matches. If any new column found, alter table by inferred `AlterExpr`
552    ///
553    /// Returns a mapping from table name to table id, where table name is the table name involved in the requests.
554    /// This mapping is used in the conversion of RowToRegion.
555    ///
556    /// `accommodate_existing_schema` is used to determine if the existing schema should override the new schema.
557    /// It only works for TIME_INDEX and single VALUE columns. This is for the case where the user creates a table with
558    /// custom schema, and then inserts data with endpoints that have default schema setting, like prometheus
559    /// remote write. This will modify the `RowInsertRequests` in place.
560    /// `is_single_value` indicates whether the default schema only contains single value column so we can accommodate it.
561    async fn create_or_alter_tables_on_demand(
562        &self,
563        requests: &mut RowInsertRequests,
564        ctx: &QueryContextRef,
565        auto_create_table_type: AutoCreateTableType,
566        statement_executor: &StatementExecutor,
567        accommodate_existing_schema: bool,
568        is_single_value: bool,
569    ) -> Result<CreateAlterTableResult> {
570        let _timer = crate::metrics::CREATE_ALTER_ON_DEMAND
571            .with_label_values(&[auto_create_table_type.as_str()])
572            .start_timer();
573
574        let catalog = ctx.current_catalog();
575        let schema = ctx.current_schema();
576
577        let mut table_infos = HashMap::new();
578        if let Some(disabled_reason) = self.auto_create_disabled_reason(ctx)? {
579            let mut instant_table_ids = HashSet::new();
580            for req in &requests.inserts {
581                let table = match self.get_table(catalog, &schema, &req.table_name).await? {
582                    Some(table) => table,
583                    // System-defined table: created canonically by the system,
584                    // so the auto-create config/hint does not apply.
585                    None if is_ddl_reserved_table(&schema, &req.table_name) => {
586                        statement_executor
587                            .create_declared_relationships_table(catalog, ctx.clone())
588                            .await?
589                    }
590                    None => {
591                        return InvalidInsertRequestSnafu {
592                            reason: format!(
593                                "Table `{}` does not exist, and {}",
594                                req.table_name, disabled_reason
595                            ),
596                        }
597                        .fail();
598                    }
599                };
600                let table_info = table.table_info();
601                if table_info.is_ttl_instant_table() {
602                    instant_table_ids.insert(table_info.table_id());
603                }
604                table_infos.insert(table_info.table_id(), table.table_info());
605            }
606            let ret = CreateAlterTableResult {
607                instant_table_ids,
608                table_infos,
609            };
610            return Ok(ret);
611        }
612
613        let mut create_tables = vec![];
614        let mut alter_tables = vec![];
615        let mut need_refresh_table_infos = HashSet::new();
616        let mut instant_table_ids = HashSet::new();
617
618        for req in &mut requests.inserts {
619            match self.get_table(catalog, &schema, &req.table_name).await? {
620                Some(table) => {
621                    let table_info = table.table_info();
622                    if table_info.is_ttl_instant_table() {
623                        instant_table_ids.insert(table_info.table_id());
624                    }
625                    if let Some(alter_expr) = self.get_alter_table_expr_on_demand(
626                        req,
627                        &table,
628                        ctx,
629                        accommodate_existing_schema,
630                        is_single_value,
631                        auto_create_table_type.alter_existing(),
632                    )? {
633                        alter_tables.push(alter_expr);
634                        need_refresh_table_infos.insert((
635                            catalog.to_string(),
636                            schema.clone(),
637                            req.table_name.clone(),
638                        ));
639                    } else {
640                        table_infos.insert(table_info.table_id(), table.table_info());
641                    }
642                }
643                // A DDL-reserved table's definition never derives from the
644                // write request; the system creates it canonically, below the
645                // user-DDL guard that rejects the generic create path.
646                None if is_ddl_reserved_table(&schema, &req.table_name) => {
647                    let table = statement_executor
648                        .create_declared_relationships_table(catalog, ctx.clone())
649                        .await?;
650                    let table_info = table.table_info();
651                    if table_info.is_ttl_instant_table() {
652                        instant_table_ids.insert(table_info.table_id());
653                    }
654                    table_infos.insert(table_info.table_id(), table_info);
655                }
656                None => {
657                    let create_expr =
658                        self.get_create_table_expr_on_demand(req, &auto_create_table_type, ctx)?;
659                    create_tables.push(create_expr);
660                }
661            }
662        }
663
664        match auto_create_table_type {
665            AutoCreateTableType::Logical(_) => {
666                if !create_tables.is_empty() {
667                    // Creates logical tables in batch.
668                    let tables = self
669                        .create_logical_tables(create_tables, ctx, statement_executor)
670                        .await?;
671
672                    for table in tables {
673                        let table_info = table.table_info();
674                        if table_info.is_ttl_instant_table() {
675                            instant_table_ids.insert(table_info.table_id());
676                        }
677                        table_infos.insert(table_info.table_id(), table.table_info());
678                    }
679                }
680                if !alter_tables.is_empty() {
681                    // Alter logical tables in batch.
682                    statement_executor
683                        .alter_logical_tables(alter_tables, ctx.clone(), TriggerReason::AutoAlter)
684                        .await?;
685                }
686            }
687            AutoCreateTableType::Physical
688            | AutoCreateTableType::Log
689            | AutoCreateTableType::LastNonNull => {
690                // note that auto create table shouldn't be ttl instant table
691                // for it's a very unexpected behavior and should be set by user explicitly
692                for create_table in create_tables {
693                    let table = self
694                        .create_physical_table(create_table, None, ctx, statement_executor)
695                        .await?;
696                    let table_info = table.table_info();
697                    if table_info.is_ttl_instant_table() {
698                        instant_table_ids.insert(table_info.table_id());
699                    }
700                    table_infos.insert(table_info.table_id(), table.table_info());
701                }
702                for alter_expr in alter_tables.into_iter() {
703                    statement_executor
704                        .alter_table_inner(alter_expr, ctx.clone(), TriggerReason::AutoAlter)
705                        .await?;
706                }
707            }
708
709            AutoCreateTableType::Trace { .. } => {
710                let trace_table_name = ctx
711                    .extension(TRACE_TABLE_NAME_SESSION_KEY)
712                    .unwrap_or(TRACE_TABLE_NAME);
713
714                let trace_table_partitions = if let Some(trace_table_partitions) =
715                    ctx.extension(TRACE_TABLE_PARTITIONS_HINT_KEY)
716                {
717                    let p = trace_table_partitions.parse::<u32>().map_err(|_| {
718                        InvalidInsertRequestSnafu {
719                            reason: format!(
720                                "Failed to parse trace_table_partitions: {}",
721                                trace_table_partitions
722                            ),
723                        }
724                        .build()
725                    })?;
726                    Some(p)
727                } else {
728                    None
729                };
730
731                // note that auto create table shouldn't be ttl instant table
732                // for it's a very unexpected behavior and should be set by user explicitly
733                for mut create_table in create_tables {
734                    if create_table.table_name == trace_services_table_name(trace_table_name)
735                        || create_table.table_name == trace_operations_table_name(trace_table_name)
736                    {
737                        // Disable append mode for auxiliary tables (services/operations) since they require upsert behavior.
738                        create_table
739                            .table_options
740                            .insert(APPEND_MODE_KEY.to_string(), "false".to_string());
741                        // Remove `ttl` key from table options if it exists
742                        create_table.table_options.remove(TTL_KEY);
743
744                        let table = self
745                            .create_physical_table(create_table, None, ctx, statement_executor)
746                            .await?;
747                        let table_info = table.table_info();
748                        if table_info.is_ttl_instant_table() {
749                            instant_table_ids.insert(table_info.table_id());
750                        }
751                        table_infos.insert(table_info.table_id(), table.table_info());
752                    } else {
753                        // prebuilt partition rules for uuid data: see the function
754                        // for more information
755                        let partitions = if matches!(trace_table_partitions, Some(0) | Some(1)) {
756                            // disable partitions
757                            None
758                        } else {
759                            let p = partition_rule_for_hexstring(
760                                TRACE_ID_COLUMN,
761                                trace_table_partitions,
762                            )
763                            .context(CreatePartitionRulesSnafu)?;
764                            Some(p)
765                        };
766
767                        // add skip index to
768                        // - trace_id: when searching by trace id
769                        // - parent_span_id: when searching root span
770                        // - span_name: when searching certain types of span
771                        let index_columns =
772                            [TRACE_ID_COLUMN, PARENT_SPAN_ID_COLUMN, SERVICE_NAME_COLUMN];
773                        for index_column in index_columns {
774                            if let Some(col) = create_table
775                                .column_defs
776                                .iter_mut()
777                                .find(|c| c.name == index_column)
778                            {
779                                col.options =
780                                    options_from_skipping(&SkippingIndexOptions::default())
781                                        .context(ColumnOptionsSnafu)?;
782                            } else {
783                                warn!(
784                                    "Column {} not found when creating index for trace table: {}.",
785                                    index_column, create_table.table_name
786                                );
787                            }
788                        }
789
790                        // use table_options to mark table model version
791                        create_table.table_options.insert(
792                            TABLE_DATA_MODEL.to_string(),
793                            TABLE_DATA_MODEL_TRACE_V1.to_string(),
794                        );
795
796                        let table = self
797                            .create_physical_table(
798                                create_table,
799                                partitions,
800                                ctx,
801                                statement_executor,
802                            )
803                            .await?;
804                        let table_info = table.table_info();
805                        if table_info.is_ttl_instant_table() {
806                            instant_table_ids.insert(table_info.table_id());
807                        }
808                        table_infos.insert(table_info.table_id(), table.table_info());
809                    }
810                }
811                for alter_expr in alter_tables.into_iter() {
812                    statement_executor
813                        .alter_table_inner(alter_expr, ctx.clone(), TriggerReason::AutoAlter)
814                        .await?;
815                }
816            }
817        }
818
819        // refresh table infos for altered tables
820        for (catalog, schema, table_name) in need_refresh_table_infos {
821            let table = self
822                .get_table(&catalog, &schema, &table_name)
823                .await?
824                .context(TableNotFoundSnafu {
825                    table_name: common_catalog::format_full_table_name(
826                        &catalog,
827                        &schema,
828                        &table_name,
829                    ),
830                })?;
831            let table_info = table.table_info();
832            table_infos.insert(table_info.table_id(), table.table_info());
833        }
834
835        Ok(CreateAlterTableResult {
836            instant_table_ids,
837            table_infos,
838        })
839    }
840
841    async fn create_physical_table_on_demand(
842        &self,
843        ctx: &QueryContextRef,
844        physical_table: String,
845        statement_executor: &StatementExecutor,
846    ) -> Result<()> {
847        let catalog_name = ctx.current_catalog();
848        let schema_name = ctx.current_schema();
849
850        // check if exist
851        if self
852            .get_table(catalog_name, &schema_name, &physical_table)
853            .await?
854            .is_some()
855        {
856            return Ok(());
857        }
858
859        // Gate here too, otherwise a disabled switch would still leak the physical table.
860        if let Some(disabled_reason) = self.auto_create_disabled_reason(ctx)? {
861            return InvalidInsertRequestSnafu {
862                reason: format!(
863                    "Physical table `{physical_table}` does not exist, and {disabled_reason}"
864                ),
865            }
866            .fail();
867        }
868
869        let table_reference = TableReference::full(catalog_name, &schema_name, &physical_table);
870        info!("Physical metric table `{table_reference}` does not exist, try creating table");
871
872        // schema with timestamp and field column
873        let default_schema = vec![
874            ColumnSchema {
875                column_name: greptime_timestamp().to_string(),
876                datatype: ColumnDataType::TimestampMillisecond as _,
877                semantic_type: SemanticType::Timestamp as _,
878                datatype_extension: None,
879                options: None,
880            },
881            ColumnSchema {
882                column_name: greptime_value().to_string(),
883                datatype: ColumnDataType::Float64 as _,
884                semantic_type: SemanticType::Field as _,
885                datatype_extension: None,
886                options: None,
887            },
888        ];
889        let create_table_expr =
890            &mut build_create_table_expr(&table_reference, &default_schema, default_engine())?;
891
892        create_table_expr.engine = METRIC_ENGINE_NAME.to_string();
893        create_table_expr
894            .table_options
895            .insert(PHYSICAL_TABLE_METADATA_KEY.to_string(), "true".to_string());
896
897        // create physical table
898        let res = statement_executor
899            .create_table_inner(
900                create_table_expr,
901                None,
902                ctx.clone(),
903                TriggerReason::AutoCreate,
904            )
905            .await;
906
907        match res {
908            Ok(_) => {
909                info!("Successfully created table {table_reference}",);
910                Ok(())
911            }
912            Err(err) => {
913                error!(err; "Failed to create table {table_reference}");
914                Err(err)
915            }
916        }
917    }
918
919    async fn get_table(
920        &self,
921        catalog: &str,
922        schema: &str,
923        table: &str,
924    ) -> Result<Option<TableRef>> {
925        self.catalog_manager
926            .table(catalog, schema, table, None)
927            .await
928            .context(CatalogSnafu)
929    }
930
931    fn get_create_table_expr_on_demand(
932        &self,
933        req: &RowInsertRequest,
934        create_type: &AutoCreateTableType,
935        ctx: &QueryContextRef,
936    ) -> Result<CreateTableExpr> {
937        let schema = ctx.current_schema();
938        let mut table_options = std::collections::HashMap::with_capacity(4);
939        fill_table_options_for_create(&mut table_options, create_type, ctx);
940        apply_per_table_semantic_options(&mut table_options, ctx, &req.table_name);
941
942        let engine_name = if let AutoCreateTableType::Logical(_) = create_type {
943            // engine should be metric engine when creating logical tables.
944            METRIC_ENGINE_NAME
945        } else {
946            default_engine()
947        };
948
949        let table_ref = TableReference::full(ctx.current_catalog(), &schema, &req.table_name);
950        // SAFETY: `req.rows` is guaranteed to be `Some` by `handle_row_inserts_with_create_type()`.
951        let request_schema = req.rows.as_ref().unwrap().schema.as_slice();
952        let mut create_table_expr =
953            build_create_table_expr(&table_ref, request_schema, engine_name)?;
954
955        // extension set by the Splunk HEC handler for identity path
956        if ctx.extension(SPLUNK_PK_METADATA_ORDER_KEY).is_some() {
957            reorder_splunk_primary_keys(&mut create_table_expr.primary_keys);
958        }
959
960        info!("Table `{table_ref}` does not exist, try creating table");
961        create_table_expr.table_options.extend(table_options);
962        Ok(create_table_expr)
963    }
964
965    /// Returns an alter table expression if it finds new columns in the request.
966    /// When `accommodate_existing_schema` is false, it always adds columns if not exist.
967    /// When `accommodate_existing_schema` is true, it may modify the input `req` to
968    /// accommodate it with existing schema. See [`create_or_alter_tables_on_demand`](Self::create_or_alter_tables_on_demand)
969    /// for more details.
970    /// When `accommodate_existing_schema` is true and `is_single_value` is true, it also consider fields when modifying the
971    /// input `req`.
972    fn get_alter_table_expr_on_demand(
973        &self,
974        req: &mut RowInsertRequest,
975        table: &TableRef,
976        ctx: &QueryContextRef,
977        accommodate_existing_schema: bool,
978        is_single_value: bool,
979        alter_existing: bool,
980    ) -> Result<Option<AlterTableExpr>> {
981        if !alter_existing {
982            return Ok(None);
983        }
984
985        let catalog_name = ctx.current_catalog();
986        let schema_name = ctx.current_schema();
987        let table_name = table.table_info().name.clone();
988
989        // Never auto-alter a system-defined table to fit a write; a request
990        // with unknown columns fails instead.
991        if is_ddl_reserved_table(&schema_name, &table_name) {
992            return Ok(None);
993        }
994
995        let request_schema = req.rows.as_ref().unwrap().schema.as_slice();
996        let request_field_count = request_schema
997            .iter()
998            .filter(|col| col.semantic_type == SemanticType::Field as i32)
999            .count();
1000        let column_exprs = ColumnExpr::from_column_schemas(request_schema);
1001        let add_columns = expr_helper::extract_add_columns_expr(&table.schema(), column_exprs)?;
1002        let Some(mut add_columns) = add_columns else {
1003            return Ok(None);
1004        };
1005
1006        // If accommodate_existing_schema is true, update request schema for Timestamp/Field columns
1007        if accommodate_existing_schema {
1008            let request_is_native_histogram = request_is_native_histogram(request_schema);
1009            let table_is_native_histogram = table_is_native_histogram(table);
1010            ensure!(
1011                request_is_native_histogram == table_is_native_histogram,
1012                InvalidInsertRequestSnafu {
1013                    reason: format!(
1014                        "Table `{table_name}` cannot mix native histogram and float sample fields"
1015                    ),
1016                }
1017            );
1018            let table_schema = table.schema();
1019            // Find timestamp column name
1020            let ts_col_name = table_schema.timestamp_column().map(|c| c.name.clone());
1021            // Find field column name if there is only one and `is_single_value` is true.
1022            let mut field_col_name = None;
1023            if is_single_value && request_field_count <= 1 {
1024                let mut multiple_field_cols = false;
1025                table.field_columns().for_each(|col| {
1026                    if field_col_name.is_none() {
1027                        field_col_name = Some(col.name.clone());
1028                    } else {
1029                        multiple_field_cols = true;
1030                    }
1031                });
1032                if multiple_field_cols {
1033                    field_col_name = None;
1034                }
1035            }
1036
1037            // Update column name in request schema for Timestamp/Field columns
1038            if let Some(rows) = req.rows.as_mut() {
1039                for col in &mut rows.schema {
1040                    match col.semantic_type {
1041                        x if x == SemanticType::Timestamp as i32 => {
1042                            if let Some(ref ts_name) = ts_col_name
1043                                && col.column_name != *ts_name
1044                            {
1045                                col.column_name = ts_name.clone();
1046                            }
1047                        }
1048                        x if x == SemanticType::Field as i32 => {
1049                            if let Some(ref field_name) = field_col_name
1050                                && col.column_name != *field_name
1051                            {
1052                                col.column_name = field_name.clone();
1053                            }
1054                        }
1055                        _ => {}
1056                    }
1057                }
1058            }
1059
1060            // Only keep columns that are tags or non-single field.
1061            add_columns.add_columns.retain(|col| {
1062                let def = col.column_def.as_ref().unwrap();
1063                def.semantic_type == SemanticType::Tag as i32
1064                    || (def.semantic_type == SemanticType::Field as i32 && field_col_name.is_none())
1065            });
1066
1067            if add_columns.add_columns.is_empty() {
1068                return Ok(None);
1069            }
1070        }
1071
1072        Ok(Some(AlterTableExpr {
1073            catalog_name: catalog_name.to_string(),
1074            schema_name: schema_name.clone(),
1075            table_name: table_name.clone(),
1076            kind: Some(Kind::AddColumns(add_columns)),
1077        }))
1078    }
1079
1080    /// Creates a table with options.
1081    async fn create_physical_table(
1082        &self,
1083        mut create_table_expr: CreateTableExpr,
1084        partitions: Option<Partitions>,
1085        ctx: &QueryContextRef,
1086        statement_executor: &StatementExecutor,
1087    ) -> Result<TableRef> {
1088        {
1089            let table_ref = TableReference::full(
1090                &create_table_expr.catalog_name,
1091                &create_table_expr.schema_name,
1092                &create_table_expr.table_name,
1093            );
1094
1095            info!("Table `{table_ref}` does not exist, try creating table");
1096        }
1097        let res = statement_executor
1098            .create_table_inner(
1099                &mut create_table_expr,
1100                partitions,
1101                ctx.clone(),
1102                TriggerReason::AutoCreate,
1103            )
1104            .await;
1105
1106        let table_ref = TableReference::full(
1107            &create_table_expr.catalog_name,
1108            &create_table_expr.schema_name,
1109            &create_table_expr.table_name,
1110        );
1111
1112        match res {
1113            Ok(table) => {
1114                info!(
1115                    "Successfully created table {} with options: {:?}",
1116                    table_ref, create_table_expr.table_options,
1117                );
1118                Ok(table)
1119            }
1120            Err(err) => {
1121                error!(err; "Failed to create table {}", table_ref);
1122                Err(err)
1123            }
1124        }
1125    }
1126
1127    async fn create_logical_tables(
1128        &self,
1129        create_table_exprs: Vec<CreateTableExpr>,
1130        ctx: &QueryContextRef,
1131        statement_executor: &StatementExecutor,
1132    ) -> Result<Vec<TableRef>> {
1133        let res = statement_executor
1134            .create_logical_tables(&create_table_exprs, ctx.clone(), TriggerReason::AutoCreate)
1135            .await;
1136
1137        match res {
1138            Ok(res) => {
1139                info!("Successfully created logical tables");
1140                Ok(res)
1141            }
1142            Err(err) => {
1143                let failed_tables = create_table_exprs
1144                    .into_iter()
1145                    .map(|expr| {
1146                        format!(
1147                            "{}.{}.{}",
1148                            expr.catalog_name, expr.schema_name, expr.table_name
1149                        )
1150                    })
1151                    .collect::<Vec<_>>();
1152                error!(
1153                    err;
1154                    "Failed to create logical tables {:?}",
1155                    failed_tables
1156                );
1157                Err(err)
1158            }
1159        }
1160    }
1161
1162    pub fn node_manager(&self) -> &NodeManagerRef {
1163        &self.node_manager
1164    }
1165
1166    pub fn partition_manager(&self) -> &PartitionRuleManagerRef {
1167        &self.partition_manager
1168    }
1169
1170    pub fn table_flownode_set_cache(&self) -> &TableFlownodeSetCacheRef {
1171        &self.table_flownode_set_cache
1172    }
1173}
1174
1175fn request_is_native_histogram(request_schema: &[ColumnSchema]) -> bool {
1176    let mut fields = request_schema
1177        .iter()
1178        .filter(|col| col.semantic_type == SemanticType::Field as i32);
1179    let Some(col) = fields.next() else {
1180        return false;
1181    };
1182
1183    fields.next().is_none()
1184        && api::helper::is_column_type_value_eq(
1185            col.datatype,
1186            col.datatype_extension.clone(),
1187            native_histogram_value_type(),
1188        )
1189}
1190
1191fn table_is_native_histogram(table: &TableRef) -> bool {
1192    let mut fields = table.field_columns();
1193    let Some(col) = fields.next() else {
1194        return false;
1195    };
1196
1197    fields.next().is_none() && is_native_histogram_value_type(&col.data_type)
1198}
1199
1200fn validate_column_count_match(requests: &RowInsertRequests) -> Result<()> {
1201    for request in &requests.inserts {
1202        let rows = request.rows.as_ref().unwrap();
1203        let column_count = rows.schema.len();
1204        rows.rows.iter().try_for_each(|r| {
1205            ensure!(
1206                r.values.len() == column_count,
1207                InvalidInsertRequestSnafu {
1208                    reason: format!(
1209                        "column count mismatch, columns: {}, values: {}",
1210                        column_count,
1211                        r.values.len()
1212                    )
1213                }
1214            );
1215            Ok(())
1216        })?;
1217    }
1218    Ok(())
1219}
1220
1221/// Fill table options for a new table by create type.
1222pub fn fill_table_options_for_create(
1223    table_options: &mut std::collections::HashMap<String, String>,
1224    create_type: &AutoCreateTableType,
1225    ctx: &QueryContextRef,
1226) {
1227    for key in VALID_TABLE_OPTION_KEYS {
1228        if let Some(value) = ctx.extension(key) {
1229            table_options.insert(key.to_string(), value.to_string());
1230        }
1231    }
1232
1233    // Semantic keys use their own vocabulary instead of the fixed option list.
1234    for (key, value) in ctx.extensions() {
1235        if is_semantic_option_key(&key) && validate_semantic_option(&key, &value) {
1236            table_options.insert(key, value);
1237        }
1238    }
1239
1240    match create_type {
1241        AutoCreateTableType::Logical(physical_table) => {
1242            table_options.insert(
1243                LOGICAL_TABLE_METADATA_KEY.to_string(),
1244                physical_table.clone(),
1245            );
1246        }
1247        AutoCreateTableType::Physical => {
1248            if let Some(append_mode) = ctx.extension(APPEND_MODE_KEY) {
1249                table_options.insert(APPEND_MODE_KEY.to_string(), append_mode.to_string());
1250            }
1251            if let Some(merge_mode) = ctx.extension(MERGE_MODE_KEY) {
1252                table_options.insert(MERGE_MODE_KEY.to_string(), merge_mode.to_string());
1253            }
1254            if let Some(time_window) = ctx.extension(TWCS_TIME_WINDOW) {
1255                table_options.insert(TWCS_TIME_WINDOW.to_string(), time_window.to_string());
1256                // We need to set the compaction type explicitly.
1257                table_options.insert(
1258                    COMPACTION_TYPE.to_string(),
1259                    COMPACTION_TYPE_TWCS.to_string(),
1260                );
1261            }
1262        }
1263        // Set append_mode to true for log table.
1264        // because log tables should keep rows with the same ts and tags.
1265        AutoCreateTableType::Log => {
1266            table_options.insert(APPEND_MODE_KEY.to_string(), "true".to_string());
1267        }
1268        AutoCreateTableType::LastNonNull => {
1269            if ctx
1270                .extension(APPEND_MODE_KEY)
1271                .is_some_and(|value| value.eq_ignore_ascii_case("true"))
1272            {
1273                table_options.insert(APPEND_MODE_KEY.to_string(), "true".to_string());
1274                table_options.insert(MERGE_MODE_KEY.to_string(), "last_row".to_string());
1275            } else if let Some(merge_mode) = ctx.extension(MERGE_MODE_KEY) {
1276                table_options.insert(MERGE_MODE_KEY.to_string(), merge_mode.to_string());
1277            } else {
1278                table_options.insert(MERGE_MODE_KEY.to_string(), "last_non_null".to_string());
1279            }
1280        }
1281        AutoCreateTableType::Trace { .. } => {
1282            table_options.insert(APPEND_MODE_KEY.to_string(), "true".to_string());
1283        }
1284    }
1285}
1286
1287/// Folds the semantic keys for `table_name` carried on the internal per-table
1288/// index extension into `table_options`.
1289///
1290/// The index is a `{table_name -> {semantic_key: value}}` JSON blob produced by
1291/// the OTLP metrics encode path (where one metric can fan out into several
1292/// tables with distinct keys). Common keys shared by every table in a request
1293/// travel as plain semantic extensions and are handled by
1294/// [`fill_table_options_for_create`]; this carries only the per-table tail.
1295/// Keys are re-checked against the vocabulary defensively. Ingestion paths
1296/// without a per-table index (logs, traces, Prom RW) carry no extension, so this
1297/// is a no-op for them.
1298fn apply_per_table_semantic_options(
1299    table_options: &mut std::collections::HashMap<String, String>,
1300    ctx: &QueryContextRef,
1301    table_name: &str,
1302) {
1303    let Some(raw) = ctx.extension(SEMANTIC_PER_TABLE_INDEX_KEY) else {
1304        return;
1305    };
1306    let Ok(index) = serde_json::from_str::<
1307        std::collections::BTreeMap<String, std::collections::BTreeMap<String, String>>,
1308    >(raw) else {
1309        warn!("failed to parse semantic per-table index, skipping per-table options");
1310        return;
1311    };
1312    let Some(entry) = index.get(table_name) else {
1313        return;
1314    };
1315    for (key, value) in entry {
1316        if is_semantic_option_key(key) && validate_semantic_option(key, value) {
1317            table_options.insert(key.clone(), value.clone());
1318        }
1319    }
1320}
1321
1322pub fn build_create_table_expr(
1323    table: &TableReference,
1324    request_schema: &[ColumnSchema],
1325    engine: &str,
1326) -> Result<CreateTableExpr> {
1327    expr_helper::create_table_expr_by_column_schemas(table, request_schema, engine, None)
1328}
1329
1330/// `QueryContext` extension key the Splunk HEC handler sets (to `"true"`) on its identity
1331/// path to request metadata-first primary-key ordering at table creation. It is absent for
1332/// user-supplied pipelines, so their primary-key order is left untouched.
1333pub const SPLUNK_PK_METADATA_ORDER_KEY: &str = "splunk_pk_metadata_order";
1334
1335/// Moves Splunk's metadata tags (`host`, `source`, `sourcetype`) to the front of the
1336/// primary key, keeping the relative order of the remaining tags.
1337fn reorder_splunk_primary_keys(primary_keys: &mut [String]) {
1338    const LEAD: [&str; 3] = ["host", "source", "sourcetype"];
1339    // Stable sort: `LEAD` columns move to the front in `host`/`source`/`sourcetype` order;
1340    // every other column keeps its existing relative position.
1341    primary_keys.sort_by_key(|name| {
1342        LEAD.iter()
1343            .position(|&lead| lead == name.as_str())
1344            .unwrap_or(LEAD.len())
1345    });
1346}
1347
1348/// Result of `create_or_alter_tables_on_demand`.
1349struct CreateAlterTableResult {
1350    /// table ids of ttl=instant tables.
1351    instant_table_ids: HashSet<TableId>,
1352    /// Table Info of the created tables.
1353    table_infos: HashMap<TableId, Arc<TableInfo>>,
1354}
1355
1356struct FlowMirrorTask {
1357    requests: HashMap<Peer, RegionInsertRequests>,
1358    num_rows: usize,
1359}
1360
1361impl FlowMirrorTask {
1362    async fn new(
1363        cache: &TableFlownodeSetCacheRef,
1364        requests: impl Iterator<Item = &RegionInsertRequest>,
1365    ) -> Result<Self> {
1366        let mut src_table_reqs: HashMap<TableId, Option<(Vec<Peer>, RegionInsertRequests)>> =
1367            HashMap::new();
1368        let mut num_rows = 0;
1369
1370        for req in requests {
1371            let table_id = RegionId::from_u64(req.region_id).table_id();
1372            match src_table_reqs.get_mut(&table_id) {
1373                Some(Some((_peers, reqs))) => reqs.requests.push(req.clone()),
1374                // already know this is not source table
1375                Some(None) => continue,
1376                _ => {
1377                    // dedup peers
1378                    let peers = cache
1379                        .get(table_id)
1380                        .await
1381                        .context(RequestInsertsSnafu)?
1382                        .unwrap_or_default()
1383                        .values()
1384                        .cloned()
1385                        .collect::<HashSet<_>>()
1386                        .into_iter()
1387                        .collect::<Vec<_>>();
1388
1389                    if !peers.is_empty() {
1390                        let mut reqs = RegionInsertRequests::default();
1391                        reqs.requests.push(req.clone());
1392                        num_rows += reqs
1393                            .requests
1394                            .iter()
1395                            .map(|r| r.rows.as_ref().unwrap().rows.len())
1396                            .sum::<usize>();
1397                        src_table_reqs.insert(table_id, Some((peers, reqs)));
1398                    } else {
1399                        // insert a empty entry to avoid repeat query
1400                        src_table_reqs.insert(table_id, None);
1401                    }
1402                }
1403            }
1404        }
1405
1406        let mut inserts: HashMap<Peer, RegionInsertRequests> = HashMap::new();
1407
1408        for (_table_id, (peers, reqs)) in src_table_reqs
1409            .into_iter()
1410            .filter_map(|(k, v)| v.map(|v| (k, v)))
1411        {
1412            if peers.len() == 1 {
1413                // fast path, zero copy
1414                inserts
1415                    .entry(peers[0].clone())
1416                    .or_default()
1417                    .requests
1418                    .extend(reqs.requests);
1419                continue;
1420            } else {
1421                // TODO(discord9): need to split requests to multiple flownodes
1422                for flownode in peers {
1423                    inserts
1424                        .entry(flownode.clone())
1425                        .or_default()
1426                        .requests
1427                        .extend(reqs.requests.clone());
1428                }
1429            }
1430        }
1431
1432        Ok(Self {
1433            requests: inserts,
1434            num_rows,
1435        })
1436    }
1437
1438    fn detach(self, node_manager: NodeManagerRef) -> Result<()> {
1439        crate::metrics::DIST_MIRROR_PENDING_ROW_COUNT.add(self.num_rows as i64);
1440        for (peer, inserts) in self.requests {
1441            let node_manager = node_manager.clone();
1442            common_runtime::spawn_global(async move {
1443                let result = node_manager
1444                    .flownode(&peer)
1445                    .await
1446                    .handle_inserts(inserts)
1447                    .await
1448                    .context(RequestInsertsSnafu);
1449
1450                match result {
1451                    Ok(resp) => {
1452                        let affected_rows = resp.affected_rows;
1453                        crate::metrics::DIST_MIRROR_ROW_COUNT.inc_by(affected_rows);
1454                        crate::metrics::DIST_MIRROR_PENDING_ROW_COUNT.sub(affected_rows as _);
1455                    }
1456                    Err(err) => {
1457                        error!(err; "Failed to insert data into flownode {}", peer);
1458                    }
1459                }
1460            });
1461        }
1462
1463        Ok(())
1464    }
1465}
1466
1467#[cfg(test)]
1468mod tests {
1469    use std::sync::Arc;
1470
1471    use api::helper::ColumnDataTypeWrapper;
1472    use api::v1::helper::{field_column_schema, time_index_column_schema};
1473    use api::v1::{RowInsertRequest, Rows, Value};
1474    use common_catalog::consts::{DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME};
1475    use common_meta::cache::new_table_flownode_set_cache;
1476    use common_meta::ddl::test_util::datanode_handler::NaiveDatanodeHandler;
1477    use common_meta::test_util::MockDatanodeManager;
1478    use common_query::native_histogram::NATIVE_HISTOGRAM_FIELD;
1479    use common_query::prelude::{greptime_native_histogram, set_default_prefix};
1480    use datatypes::data_type::ConcreteDataType;
1481    use datatypes::schema::ColumnSchema;
1482    use moka::future::Cache;
1483    use session::context::QueryContext;
1484    use table::TableRef;
1485    use table::dist_table::DummyDataSource;
1486    use table::metadata::{TableInfoBuilder, TableMetaBuilder, TableType};
1487
1488    use super::*;
1489    use crate::tests::{create_partition_rule_manager, prepare_mocked_backend};
1490
1491    fn make_table_ref_with_schema(
1492        ts_name: &str,
1493        field_name: &str,
1494        field_type: ConcreteDataType,
1495    ) -> TableRef {
1496        let schema = datatypes::schema::SchemaBuilder::try_from_columns(vec![
1497            ColumnSchema::new(
1498                ts_name,
1499                ConcreteDataType::timestamp_millisecond_datatype(),
1500                false,
1501            )
1502            .with_time_index(true),
1503            ColumnSchema::new(field_name, field_type, true),
1504        ])
1505        .unwrap()
1506        .build()
1507        .unwrap();
1508        let meta = TableMetaBuilder::empty()
1509            .schema(Arc::new(schema))
1510            .primary_key_indices(vec![])
1511            .value_indices(vec![1])
1512            .engine("mito")
1513            .next_column_id(0)
1514            .options(Default::default())
1515            .created_on(Default::default())
1516            .build()
1517            .unwrap();
1518        let info = Arc::new(
1519            TableInfoBuilder::default()
1520                .table_id(1)
1521                .table_version(0)
1522                .name("test_table")
1523                .schema_name(DEFAULT_SCHEMA_NAME)
1524                .catalog_name(DEFAULT_CATALOG_NAME)
1525                .desc(None)
1526                .table_type(TableType::Base)
1527                .meta(meta)
1528                .build()
1529                .unwrap(),
1530        );
1531        Arc::new(table::Table::new(
1532            info,
1533            table::metadata::FilterPushDownType::Unsupported,
1534            Arc::new(DummyDataSource),
1535        ))
1536    }
1537
1538    #[tokio::test]
1539    async fn test_accommodate_existing_schema_and_reject_kind_changes() {
1540        let ts_name = "my_ts";
1541        let field_name = "my_field";
1542        let table =
1543            make_table_ref_with_schema(ts_name, field_name, ConcreteDataType::float64_datatype());
1544
1545        // The request uses different names for timestamp and field columns
1546        let mut req = RowInsertRequest {
1547            table_name: "test_table".to_string(),
1548            rows: Some(Rows {
1549                schema: vec![
1550                    time_index_column_schema("ts_wrong", ColumnDataType::TimestampMillisecond),
1551                    field_column_schema("field_wrong", ColumnDataType::Float64),
1552                ],
1553                rows: vec![api::v1::Row {
1554                    values: vec![Value::default(), Value::default()],
1555                }],
1556            }),
1557        };
1558        let ctx = Arc::new(QueryContext::with(
1559            DEFAULT_CATALOG_NAME,
1560            DEFAULT_SCHEMA_NAME,
1561        ));
1562
1563        let kv_backend = prepare_mocked_backend().await;
1564        let inserter = Inserter::new(
1565            catalog::memory::MemoryCatalogManager::new(),
1566            create_partition_rule_manager(kv_backend.clone()).await,
1567            Arc::new(MockDatanodeManager::new(NaiveDatanodeHandler)),
1568            Arc::new(new_table_flownode_set_cache(
1569                String::new(),
1570                Cache::new(100),
1571                kv_backend.clone(),
1572            )),
1573            true,
1574        );
1575        // Do not apply an absent-table plan to a table that appeared concurrently.
1576        assert!(
1577            inserter
1578                .get_alter_table_expr_on_demand(&mut req, &table, &ctx, false, false, false)
1579                .unwrap()
1580                .is_none()
1581        );
1582        let alter_expr = inserter
1583            .get_alter_table_expr_on_demand(&mut req, &table, &ctx, true, true, true)
1584            .unwrap();
1585        assert!(alter_expr.is_none());
1586
1587        // The request's schema should have updated names for timestamp and field columns
1588        let req_schema = req.rows.as_ref().unwrap().schema.clone();
1589        assert_eq!(req_schema[0].column_name, ts_name);
1590        assert_eq!(req_schema[1].column_name, field_name);
1591
1592        let (datatype, datatype_extension) =
1593            ColumnDataTypeWrapper::try_from(native_histogram_value_type().clone())
1594                .unwrap()
1595                .into_parts();
1596        let mut histogram_req = RowInsertRequest {
1597            table_name: "test_table".to_string(),
1598            rows: Some(Rows {
1599                schema: vec![
1600                    time_index_column_schema("ts", ColumnDataType::TimestampMillisecond),
1601                    api::v1::ColumnSchema {
1602                        column_name: greptime_native_histogram().to_string(),
1603                        datatype: datatype as i32,
1604                        semantic_type: SemanticType::Field as i32,
1605                        datatype_extension,
1606                        options: None,
1607                    },
1608                ],
1609                rows: vec![],
1610            }),
1611        };
1612        let error = inserter
1613            .get_alter_table_expr_on_demand(&mut histogram_req, &table, &ctx, true, true, true)
1614            .unwrap_err();
1615        assert!(
1616            error
1617                .to_string()
1618                .contains("cannot mix native histogram and float sample fields")
1619        );
1620
1621        let histogram_table = make_table_ref_with_schema(
1622            "ts",
1623            greptime_native_histogram(),
1624            native_histogram_value_type().clone(),
1625        );
1626        let mut sample_req = RowInsertRequest {
1627            table_name: "test_table".to_string(),
1628            rows: Some(Rows {
1629                schema: vec![
1630                    time_index_column_schema("ts", ColumnDataType::TimestampMillisecond),
1631                    field_column_schema(greptime_value(), ColumnDataType::Float64),
1632                ],
1633                rows: vec![],
1634            }),
1635        };
1636        let error = inserter
1637            .get_alter_table_expr_on_demand(
1638                &mut sample_req,
1639                &histogram_table,
1640                &ctx,
1641                true,
1642                true,
1643                true,
1644            )
1645            .unwrap_err();
1646        assert!(
1647            error
1648                .to_string()
1649                .contains("cannot mix native histogram and float sample fields")
1650        );
1651    }
1652
1653    #[test]
1654    fn test_native_histogram_detection_survives_prefix_change() {
1655        set_default_prefix(Some("custom")).unwrap();
1656        let table = make_table_ref_with_schema(
1657            "custom_timestamp",
1658            NATIVE_HISTOGRAM_FIELD,
1659            native_histogram_value_type().clone(),
1660        );
1661        let (datatype, datatype_extension) =
1662            ColumnDataTypeWrapper::try_from(native_histogram_value_type().clone())
1663                .unwrap()
1664                .into_parts();
1665        let request_schema = [api::v1::ColumnSchema {
1666            column_name: greptime_native_histogram().to_string(),
1667            datatype: datatype as i32,
1668            semantic_type: SemanticType::Field as i32,
1669            datatype_extension,
1670            options: None,
1671        }];
1672
1673        assert!(request_is_native_histogram(&request_schema));
1674        assert!(table_is_native_histogram(&table));
1675    }
1676
1677    #[test]
1678    fn test_last_non_null_create_options_preserve_default_without_append_mode() {
1679        let ctx = Arc::new(QueryContext::with(
1680            DEFAULT_CATALOG_NAME,
1681            DEFAULT_SCHEMA_NAME,
1682        ));
1683        let mut table_options = Default::default();
1684
1685        fill_table_options_for_create(&mut table_options, &AutoCreateTableType::LastNonNull, &ctx);
1686
1687        assert_eq!(
1688            Some("last_non_null"),
1689            table_options.get(MERGE_MODE_KEY).map(String::as_str)
1690        );
1691        assert!(!table_options.contains_key(APPEND_MODE_KEY));
1692    }
1693
1694    #[test]
1695    fn test_fill_table_options_copies_semantic_extensions() {
1696        use table::requests::{
1697            SEMANTIC_METRIC_TYPE, SEMANTIC_PER_TABLE_INDEX_KEY, SEMANTIC_SIGNAL_TYPE,
1698            SEMANTIC_SOURCE, SEMANTIC_SOURCE_VERSION, SIGNAL_TYPE_METRIC, SOURCE_OPENTELEMETRY,
1699        };
1700
1701        let mut ctx = QueryContext::with(DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME);
1702        ctx.set_extension(SEMANTIC_SIGNAL_TYPE, SIGNAL_TYPE_METRIC);
1703        ctx.set_extension(SEMANTIC_SOURCE, SOURCE_OPENTELEMETRY);
1704        ctx.set_extension(SEMANTIC_SOURCE_VERSION, "2.0");
1705        ctx.set_extension(SEMANTIC_METRIC_TYPE, "bogus");
1706        // The internal transport key must NOT be copied into table options.
1707        ctx.set_extension(SEMANTIC_PER_TABLE_INDEX_KEY, "{}");
1708        let ctx = Arc::new(ctx);
1709        let mut table_options = Default::default();
1710
1711        fill_table_options_for_create(&mut table_options, &AutoCreateTableType::Physical, &ctx);
1712
1713        assert_eq!(
1714            Some(SIGNAL_TYPE_METRIC),
1715            table_options.get(SEMANTIC_SIGNAL_TYPE).map(String::as_str)
1716        );
1717        assert_eq!(
1718            Some(SOURCE_OPENTELEMETRY),
1719            table_options.get(SEMANTIC_SOURCE).map(String::as_str)
1720        );
1721        assert_eq!(
1722            Some("2.0"),
1723            table_options
1724                .get(SEMANTIC_SOURCE_VERSION)
1725                .map(String::as_str)
1726        );
1727        assert!(!table_options.contains_key(SEMANTIC_METRIC_TYPE));
1728        assert!(!table_options.contains_key(SEMANTIC_PER_TABLE_INDEX_KEY));
1729    }
1730
1731    #[test]
1732    fn test_apply_per_table_semantic_options() {
1733        use table::requests::{
1734            SEMANTIC_METRIC_TYPE, SEMANTIC_METRIC_UNIT, SEMANTIC_PER_TABLE_INDEX_KEY,
1735        };
1736
1737        let index = r#"{
1738            "http_requests_total": {
1739                "greptime.semantic.metric.type": "counter",
1740                "greptime.semantic.metric.unit": "By",
1741                "greptime.semantic.metric.type_BOGUS": "x"
1742            },
1743            "other_table": {
1744                "greptime.semantic.metric.type": "gauge"
1745            }
1746        }"#;
1747        let mut ctx = QueryContext::with(DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME);
1748        ctx.set_extension(SEMANTIC_PER_TABLE_INDEX_KEY, index);
1749        let ctx = Arc::new(ctx);
1750
1751        let mut table_options = std::collections::HashMap::new();
1752        apply_per_table_semantic_options(&mut table_options, &ctx, "http_requests_total");
1753        assert_eq!(
1754            table_options.get(SEMANTIC_METRIC_TYPE).map(String::as_str),
1755            Some("counter")
1756        );
1757        assert_eq!(
1758            table_options.get(SEMANTIC_METRIC_UNIT).map(String::as_str),
1759            Some("By")
1760        );
1761        // The unknown key is rejected by the vocabulary check; other tables' keys
1762        // never appear.
1763        assert!(!table_options.contains_key("greptime.semantic.metric.type_BOGUS"));
1764        assert_eq!(table_options.len(), 2);
1765
1766        let mut empty = std::collections::HashMap::new();
1767        apply_per_table_semantic_options(&mut empty, &ctx, "not_in_index");
1768        assert!(empty.is_empty());
1769
1770        // No extension at all is a no-op (e.g. logs / Prom RW).
1771        let bare = Arc::new(QueryContext::with(
1772            DEFAULT_CATALOG_NAME,
1773            DEFAULT_SCHEMA_NAME,
1774        ));
1775        let mut opts = std::collections::HashMap::new();
1776        apply_per_table_semantic_options(&mut opts, &bare, "http_requests_total");
1777        assert!(opts.is_empty());
1778    }
1779
1780    #[test]
1781    fn test_last_non_null_create_options_preserve_default_with_append_mode_false() {
1782        let mut ctx = QueryContext::with(DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME);
1783        ctx.set_extension(APPEND_MODE_KEY, "false");
1784        let ctx = Arc::new(ctx);
1785        let mut table_options = Default::default();
1786
1787        fill_table_options_for_create(&mut table_options, &AutoCreateTableType::LastNonNull, &ctx);
1788
1789        assert!(!table_options.contains_key(APPEND_MODE_KEY));
1790        assert_eq!(
1791            Some("last_non_null"),
1792            table_options.get(MERGE_MODE_KEY).map(String::as_str)
1793        );
1794    }
1795
1796    #[test]
1797    fn test_last_non_null_create_options_use_configured_merge_mode() {
1798        let mut ctx = QueryContext::with(DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME);
1799        ctx.set_extension(MERGE_MODE_KEY, "last_row");
1800        let ctx = Arc::new(ctx);
1801        let mut table_options = Default::default();
1802
1803        fill_table_options_for_create(&mut table_options, &AutoCreateTableType::LastNonNull, &ctx);
1804
1805        assert_eq!(
1806            Some("last_row"),
1807            table_options.get(MERGE_MODE_KEY).map(String::as_str)
1808        );
1809        assert!(!table_options.contains_key(APPEND_MODE_KEY));
1810    }
1811
1812    #[test]
1813    fn test_last_non_null_create_options_use_last_row_with_append_mode_true() {
1814        let mut ctx = QueryContext::with(DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME);
1815        ctx.set_extension(APPEND_MODE_KEY, "true");
1816        let ctx = Arc::new(ctx);
1817        let mut table_options = Default::default();
1818
1819        fill_table_options_for_create(&mut table_options, &AutoCreateTableType::LastNonNull, &ctx);
1820
1821        assert_eq!(
1822            Some("true"),
1823            table_options.get(APPEND_MODE_KEY).map(String::as_str)
1824        );
1825        assert_eq!(
1826            Some("last_row"),
1827            table_options.get(MERGE_MODE_KEY).map(String::as_str)
1828        );
1829    }
1830}