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, trace_operations_table_name,
33    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_query::Output;
40use common_query::prelude::{greptime_timestamp, greptime_value};
41use common_telemetry::tracing_context::TracingContext;
42use common_telemetry::{error, info, warn};
43use datatypes::schema::SkippingIndexOptions;
44use futures_util::future;
45use meter_macros::write_meter;
46use partition::manager::PartitionRuleManagerRef;
47use session::context::QueryContextRef;
48use snafu::ResultExt;
49use snafu::prelude::*;
50use sql::partition::partition_rule_for_hexstring;
51use sql::statements::create::Partitions;
52use sql::statements::insert::Insert;
53use store_api::metric_engine_consts::{
54    LOGICAL_TABLE_METADATA_KEY, METRIC_ENGINE_NAME, PHYSICAL_TABLE_METADATA_KEY,
55};
56use store_api::mito_engine_options::{
57    APPEND_MODE_KEY, COMPACTION_TYPE, COMPACTION_TYPE_TWCS, MERGE_MODE_KEY, TTL_KEY,
58    TWCS_TIME_WINDOW,
59};
60use store_api::storage::{RegionId, TableId};
61use table::TableRef;
62use table::metadata::TableInfo;
63use table::requests::{
64    AUTO_CREATE_TABLE_KEY, InsertRequest as TableInsertRequest, TABLE_DATA_MODEL,
65    TABLE_DATA_MODEL_TRACE_V1, VALID_TABLE_OPTION_KEYS,
66};
67use table::table_reference::TableReference;
68
69use crate::error::{
70    CatalogSnafu, ColumnOptionsSnafu, CreatePartitionRulesSnafu, FindRegionLeaderSnafu,
71    InvalidInsertRequestSnafu, JoinTaskSnafu, RequestInsertsSnafu, Result, TableNotFoundSnafu,
72};
73use crate::expr_helper;
74use crate::region_req_factory::RegionRequestFactory;
75use crate::req_convert::common::preprocess_row_insert_requests;
76use crate::req_convert::insert::{
77    ColumnToRow, RowToRegion, StatementToRegion, TableToRegion, fill_reqs_with_impure_default,
78};
79use crate::statement::StatementExecutor;
80
81pub struct Inserter {
82    catalog_manager: CatalogManagerRef,
83    pub(crate) partition_manager: PartitionRuleManagerRef,
84    pub(crate) node_manager: NodeManagerRef,
85    pub(crate) table_flownode_set_cache: TableFlownodeSetCacheRef,
86}
87
88pub type InserterRef = Arc<Inserter>;
89
90/// Hint for the table type to create automatically.
91#[derive(Clone)]
92pub enum AutoCreateTableType {
93    /// A logical table with the physical table name.
94    Logical(String),
95    /// A physical table.
96    Physical,
97    /// A log table which is append-only.
98    Log,
99    /// A table that merges rows by `last_non_null` strategy.
100    LastNonNull,
101    /// Create table that build index and default partition rules on trace_id
102    Trace,
103}
104
105impl AutoCreateTableType {
106    pub fn as_str(&self) -> &'static str {
107        match self {
108            AutoCreateTableType::Logical(_) => "logical",
109            AutoCreateTableType::Physical => "physical",
110            AutoCreateTableType::Log => "log",
111            AutoCreateTableType::LastNonNull => "last_non_null",
112            AutoCreateTableType::Trace => "trace",
113        }
114    }
115}
116
117/// Split insert requests into normal and instant requests.
118///
119/// Where instant requests are requests with ttl=instant,
120/// and normal requests are requests with ttl set to other values.
121///
122/// This is used to split requests for different processing.
123#[derive(Clone)]
124pub struct InstantAndNormalInsertRequests {
125    /// Requests with normal ttl.
126    pub normal_requests: RegionInsertRequests,
127    /// Requests with ttl=instant.
128    /// Will be discarded immediately at frontend, wouldn't even insert into memtable, and only sent to flow node if needed.
129    pub instant_requests: RegionInsertRequests,
130}
131
132impl Inserter {
133    pub fn new(
134        catalog_manager: CatalogManagerRef,
135        partition_manager: PartitionRuleManagerRef,
136        node_manager: NodeManagerRef,
137        table_flownode_set_cache: TableFlownodeSetCacheRef,
138    ) -> Self {
139        Self {
140            catalog_manager,
141            partition_manager,
142            node_manager,
143            table_flownode_set_cache,
144        }
145    }
146
147    pub async fn handle_column_inserts(
148        &self,
149        requests: InsertRequests,
150        ctx: QueryContextRef,
151        statement_executor: &StatementExecutor,
152    ) -> Result<Output> {
153        let row_inserts = ColumnToRow::convert(requests)?;
154        self.handle_row_inserts(row_inserts, ctx, statement_executor, false, false)
155            .await
156    }
157
158    /// Handles row inserts request and creates a physical table on demand.
159    pub async fn handle_row_inserts(
160        &self,
161        mut requests: RowInsertRequests,
162        ctx: QueryContextRef,
163        statement_executor: &StatementExecutor,
164        accommodate_existing_schema: bool,
165        is_single_value: bool,
166    ) -> Result<Output> {
167        preprocess_row_insert_requests(&mut requests.inserts)?;
168        self.handle_row_inserts_with_create_type(
169            requests,
170            ctx,
171            statement_executor,
172            AutoCreateTableType::Physical,
173            accommodate_existing_schema,
174            is_single_value,
175        )
176        .await
177    }
178
179    /// Handles row inserts request and creates a log table on demand.
180    pub async fn handle_log_inserts(
181        &self,
182        requests: RowInsertRequests,
183        ctx: QueryContextRef,
184        statement_executor: &StatementExecutor,
185    ) -> Result<Output> {
186        self.handle_row_inserts_with_create_type(
187            requests,
188            ctx,
189            statement_executor,
190            AutoCreateTableType::Log,
191            false,
192            false,
193        )
194        .await
195    }
196
197    pub async fn handle_trace_inserts(
198        &self,
199        requests: RowInsertRequests,
200        ctx: QueryContextRef,
201        statement_executor: &StatementExecutor,
202    ) -> Result<Output> {
203        self.handle_row_inserts_with_create_type(
204            requests,
205            ctx,
206            statement_executor,
207            AutoCreateTableType::Trace,
208            false,
209            false,
210        )
211        .await
212    }
213
214    /// Handles row inserts request and creates a table with `last_non_null` merge mode on demand.
215    pub async fn handle_last_non_null_inserts(
216        &self,
217        requests: RowInsertRequests,
218        ctx: QueryContextRef,
219        statement_executor: &StatementExecutor,
220        accommodate_existing_schema: bool,
221        is_single_value: bool,
222    ) -> Result<Output> {
223        self.handle_row_inserts_with_create_type(
224            requests,
225            ctx,
226            statement_executor,
227            AutoCreateTableType::LastNonNull,
228            accommodate_existing_schema,
229            is_single_value,
230        )
231        .await
232    }
233
234    /// Handles row inserts request with specified [AutoCreateTableType].
235    async fn handle_row_inserts_with_create_type(
236        &self,
237        mut requests: RowInsertRequests,
238        ctx: QueryContextRef,
239        statement_executor: &StatementExecutor,
240        create_type: AutoCreateTableType,
241        accommodate_existing_schema: bool,
242        is_single_value: bool,
243    ) -> Result<Output> {
244        // remove empty requests
245        requests.inserts.retain(|req| {
246            req.rows
247                .as_ref()
248                .map(|r| !r.rows.is_empty())
249                .unwrap_or_default()
250        });
251        validate_column_count_match(&requests)?;
252
253        let CreateAlterTableResult {
254            instant_table_ids,
255            table_infos,
256        } = self
257            .create_or_alter_tables_on_demand(
258                &mut requests,
259                &ctx,
260                create_type,
261                statement_executor,
262                accommodate_existing_schema,
263                is_single_value,
264            )
265            .await?;
266
267        let name_to_info = table_infos
268            .values()
269            .map(|info| (info.name.clone(), info.clone()))
270            .collect::<HashMap<_, _>>();
271        let inserts = RowToRegion::new(
272            name_to_info,
273            instant_table_ids,
274            self.partition_manager.as_ref(),
275        )
276        .convert(requests)
277        .await?;
278
279        self.do_request(inserts, &table_infos, &ctx).await
280    }
281
282    /// Handles row inserts request with metric engine.
283    pub async fn handle_metric_row_inserts(
284        &self,
285        mut requests: RowInsertRequests,
286        ctx: QueryContextRef,
287        statement_executor: &StatementExecutor,
288        physical_table: String,
289    ) -> Result<Output> {
290        // remove empty requests
291        requests.inserts.retain(|req| {
292            req.rows
293                .as_ref()
294                .map(|r| !r.rows.is_empty())
295                .unwrap_or_default()
296        });
297        validate_column_count_match(&requests)?;
298
299        // check and create physical table
300        self.create_physical_table_on_demand(&ctx, physical_table.clone(), statement_executor)
301            .await?;
302
303        // check and create logical tables
304        let CreateAlterTableResult {
305            instant_table_ids,
306            table_infos,
307        } = self
308            .create_or_alter_tables_on_demand(
309                &mut requests,
310                &ctx,
311                AutoCreateTableType::Logical(physical_table.clone()),
312                statement_executor,
313                true,
314                true,
315            )
316            .await?;
317        let name_to_info = table_infos
318            .values()
319            .map(|info| (info.name.clone(), info.clone()))
320            .collect::<HashMap<_, _>>();
321        let inserts = RowToRegion::new(name_to_info, instant_table_ids, &self.partition_manager)
322            .convert(requests)
323            .await?;
324
325        self.do_request(inserts, &table_infos, &ctx).await
326    }
327
328    pub async fn handle_table_insert(
329        &self,
330        request: TableInsertRequest,
331        ctx: QueryContextRef,
332    ) -> Result<Output> {
333        let catalog = request.catalog_name.as_str();
334        let schema = request.schema_name.as_str();
335        let table_name = request.table_name.as_str();
336        let table = self.get_table(catalog, schema, table_name).await?;
337        let table = table.with_context(|| TableNotFoundSnafu {
338            table_name: common_catalog::format_full_table_name(catalog, schema, table_name),
339        })?;
340        let table_info = table.table_info();
341
342        let inserts = TableToRegion::new(&table_info, &self.partition_manager)
343            .convert(request)
344            .await?;
345
346        let table_infos = HashMap::from_iter([(table_info.table_id(), table_info.clone())]);
347
348        self.do_request(inserts, &table_infos, &ctx).await
349    }
350
351    pub async fn handle_statement_insert(
352        &self,
353        insert: &Insert,
354        ctx: &QueryContextRef,
355        statement_executor: &StatementExecutor,
356    ) -> Result<Output> {
357        let (inserts, table_info) =
358            StatementToRegion::new(self.catalog_manager.as_ref(), &self.partition_manager, ctx)
359                .convert(insert, ctx, statement_executor)
360                .await?;
361
362        let table_infos = HashMap::from_iter([(table_info.table_id(), table_info.clone())]);
363
364        self.do_request(inserts, &table_infos, ctx).await
365    }
366}
367
368impl Inserter {
369    async fn do_request(
370        &self,
371        requests: InstantAndNormalInsertRequests,
372        table_infos: &HashMap<TableId, Arc<TableInfo>>,
373        ctx: &QueryContextRef,
374    ) -> Result<Output> {
375        // Fill impure default values in the request
376        let requests = fill_reqs_with_impure_default(table_infos, requests)?;
377
378        let write_cost = write_meter!(
379            ctx.current_catalog(),
380            ctx.current_schema(),
381            requests,
382            ctx.channel() as u8
383        );
384        let request_factory = RegionRequestFactory::new(RegionRequestHeader {
385            tracing_context: TracingContext::from_current_span().to_w3c(),
386            dbname: ctx.get_db_string(),
387            ..Default::default()
388        });
389
390        let InstantAndNormalInsertRequests {
391            normal_requests,
392            instant_requests,
393        } = requests;
394
395        // Mirror requests for source table to flownode asynchronously
396        let flow_mirror_task = FlowMirrorTask::new(
397            &self.table_flownode_set_cache,
398            normal_requests
399                .requests
400                .iter()
401                .chain(instant_requests.requests.iter()),
402        )
403        .await?;
404        flow_mirror_task.detach(self.node_manager.clone())?;
405
406        // Write requests to datanode and wait for response
407        let write_tasks = self
408            .group_requests_by_peer(normal_requests)
409            .await?
410            .into_iter()
411            .map(|(peer, inserts)| {
412                let node_manager = self.node_manager.clone();
413                let request = request_factory.build_insert(inserts);
414                common_runtime::spawn_global(async move {
415                    node_manager
416                        .datanode(&peer)
417                        .await
418                        .handle(request)
419                        .await
420                        .context(RequestInsertsSnafu)
421                })
422            });
423        let results = future::try_join_all(write_tasks)
424            .await
425            .context(JoinTaskSnafu)?;
426        let affected_rows = results
427            .into_iter()
428            .map(|resp| resp.map(|r| r.affected_rows))
429            .sum::<Result<AffectedRows>>()?;
430        crate::metrics::DIST_INGEST_ROW_COUNT
431            .with_label_values(&[ctx.get_db_string().as_str()])
432            .inc_by(affected_rows as u64);
433        Ok(Output::new(
434            OutputData::AffectedRows(affected_rows),
435            OutputMeta::new_with_cost(write_cost as _),
436        ))
437    }
438
439    async fn group_requests_by_peer(
440        &self,
441        requests: RegionInsertRequests,
442    ) -> Result<HashMap<Peer, RegionInsertRequests>> {
443        // group by region ids first to reduce repeatedly call `find_region_leader`
444        // TODO(discord9): determine if a addition clone is worth it
445        let mut requests_per_region: HashMap<RegionId, RegionInsertRequests> = HashMap::new();
446        for req in requests.requests {
447            let region_id = RegionId::from_u64(req.region_id);
448            requests_per_region
449                .entry(region_id)
450                .or_default()
451                .requests
452                .push(req);
453        }
454
455        let mut inserts: HashMap<Peer, RegionInsertRequests> = HashMap::new();
456
457        for (region_id, reqs) in requests_per_region {
458            let peer = self
459                .partition_manager
460                .find_region_leader(region_id)
461                .await
462                .context(FindRegionLeaderSnafu)?;
463            inserts
464                .entry(peer)
465                .or_default()
466                .requests
467                .extend(reqs.requests);
468        }
469
470        Ok(inserts)
471    }
472
473    /// Creates or alter tables on demand:
474    /// - if table does not exist, create table by inferred CreateExpr
475    /// - if table exist, check if schema matches. If any new column found, alter table by inferred `AlterExpr`
476    ///
477    /// Returns a mapping from table name to table id, where table name is the table name involved in the requests.
478    /// This mapping is used in the conversion of RowToRegion.
479    ///
480    /// `accommodate_existing_schema` is used to determine if the existing schema should override the new schema.
481    /// It only works for TIME_INDEX and single VALUE columns. This is for the case where the user creates a table with
482    /// custom schema, and then inserts data with endpoints that have default schema setting, like prometheus
483    /// remote write. This will modify the `RowInsertRequests` in place.
484    /// `is_single_value` indicates whether the default schema only contains single value column so we can accommodate it.
485    async fn create_or_alter_tables_on_demand(
486        &self,
487        requests: &mut RowInsertRequests,
488        ctx: &QueryContextRef,
489        auto_create_table_type: AutoCreateTableType,
490        statement_executor: &StatementExecutor,
491        accommodate_existing_schema: bool,
492        is_single_value: bool,
493    ) -> Result<CreateAlterTableResult> {
494        let _timer = crate::metrics::CREATE_ALTER_ON_DEMAND
495            .with_label_values(&[auto_create_table_type.as_str()])
496            .start_timer();
497
498        let catalog = ctx.current_catalog();
499        let schema = ctx.current_schema();
500
501        let mut table_infos = HashMap::new();
502        // If `auto_create_table` hint is disabled, skip creating/altering tables.
503        let auto_create_table_hint = ctx
504            .extension(AUTO_CREATE_TABLE_KEY)
505            .map(|v| v.parse::<bool>())
506            .transpose()
507            .map_err(|_| {
508                InvalidInsertRequestSnafu {
509                    reason: "`auto_create_table` hint must be a boolean",
510                }
511                .build()
512            })?
513            .unwrap_or(true);
514        if !auto_create_table_hint {
515            let mut instant_table_ids = HashSet::new();
516            for req in &requests.inserts {
517                let table = self
518                    .get_table(catalog, &schema, &req.table_name)
519                    .await?
520                    .context(InvalidInsertRequestSnafu {
521                        reason: format!(
522                            "Table `{}` does not exist, and `auto_create_table` hint is disabled",
523                            req.table_name
524                        ),
525                    })?;
526                let table_info = table.table_info();
527                if table_info.is_ttl_instant_table() {
528                    instant_table_ids.insert(table_info.table_id());
529                }
530                table_infos.insert(table_info.table_id(), table.table_info());
531            }
532            let ret = CreateAlterTableResult {
533                instant_table_ids,
534                table_infos,
535            };
536            return Ok(ret);
537        }
538
539        let mut create_tables = vec![];
540        let mut alter_tables = vec![];
541        let mut need_refresh_table_infos = HashSet::new();
542        let mut instant_table_ids = HashSet::new();
543
544        for req in &mut requests.inserts {
545            match self.get_table(catalog, &schema, &req.table_name).await? {
546                Some(table) => {
547                    let table_info = table.table_info();
548                    if table_info.is_ttl_instant_table() {
549                        instant_table_ids.insert(table_info.table_id());
550                    }
551                    if let Some(alter_expr) = self.get_alter_table_expr_on_demand(
552                        req,
553                        &table,
554                        ctx,
555                        accommodate_existing_schema,
556                        is_single_value,
557                    )? {
558                        alter_tables.push(alter_expr);
559                        need_refresh_table_infos.insert((
560                            catalog.to_string(),
561                            schema.clone(),
562                            req.table_name.clone(),
563                        ));
564                    } else {
565                        table_infos.insert(table_info.table_id(), table.table_info());
566                    }
567                }
568                None => {
569                    let create_expr =
570                        self.get_create_table_expr_on_demand(req, &auto_create_table_type, ctx)?;
571                    create_tables.push(create_expr);
572                }
573            }
574        }
575
576        match auto_create_table_type {
577            AutoCreateTableType::Logical(_) => {
578                if !create_tables.is_empty() {
579                    // Creates logical tables in batch.
580                    let tables = self
581                        .create_logical_tables(create_tables, ctx, statement_executor)
582                        .await?;
583
584                    for table in tables {
585                        let table_info = table.table_info();
586                        if table_info.is_ttl_instant_table() {
587                            instant_table_ids.insert(table_info.table_id());
588                        }
589                        table_infos.insert(table_info.table_id(), table.table_info());
590                    }
591                }
592                if !alter_tables.is_empty() {
593                    // Alter logical tables in batch.
594                    statement_executor
595                        .alter_logical_tables(alter_tables, ctx.clone())
596                        .await?;
597                }
598            }
599            AutoCreateTableType::Physical
600            | AutoCreateTableType::Log
601            | AutoCreateTableType::LastNonNull => {
602                // note that auto create table shouldn't be ttl instant table
603                // for it's a very unexpected behavior and should be set by user explicitly
604                for create_table in create_tables {
605                    let table = self
606                        .create_physical_table(create_table, None, ctx, statement_executor)
607                        .await?;
608                    let table_info = table.table_info();
609                    if table_info.is_ttl_instant_table() {
610                        instant_table_ids.insert(table_info.table_id());
611                    }
612                    table_infos.insert(table_info.table_id(), table.table_info());
613                }
614                for alter_expr in alter_tables.into_iter() {
615                    statement_executor
616                        .alter_table_inner(alter_expr, ctx.clone())
617                        .await?;
618                }
619            }
620
621            AutoCreateTableType::Trace => {
622                let trace_table_name = ctx
623                    .extension(TRACE_TABLE_NAME_SESSION_KEY)
624                    .unwrap_or(TRACE_TABLE_NAME);
625
626                // note that auto create table shouldn't be ttl instant table
627                // for it's a very unexpected behavior and should be set by user explicitly
628                for mut create_table in create_tables {
629                    if create_table.table_name == trace_services_table_name(trace_table_name)
630                        || create_table.table_name == trace_operations_table_name(trace_table_name)
631                    {
632                        // Disable append mode for auxiliary tables (services/operations) since they require upsert behavior.
633                        create_table
634                            .table_options
635                            .insert(APPEND_MODE_KEY.to_string(), "false".to_string());
636                        // Remove `ttl` key from table options if it exists
637                        create_table.table_options.remove(TTL_KEY);
638
639                        let table = self
640                            .create_physical_table(create_table, None, ctx, statement_executor)
641                            .await?;
642                        let table_info = table.table_info();
643                        if table_info.is_ttl_instant_table() {
644                            instant_table_ids.insert(table_info.table_id());
645                        }
646                        table_infos.insert(table_info.table_id(), table.table_info());
647                    } else {
648                        // prebuilt partition rules for uuid data: see the function
649                        // for more information
650                        let partitions = partition_rule_for_hexstring(TRACE_ID_COLUMN)
651                            .context(CreatePartitionRulesSnafu)?;
652                        // add skip index to
653                        // - trace_id: when searching by trace id
654                        // - parent_span_id: when searching root span
655                        // - span_name: when searching certain types of span
656                        let index_columns =
657                            [TRACE_ID_COLUMN, PARENT_SPAN_ID_COLUMN, SERVICE_NAME_COLUMN];
658                        for index_column in index_columns {
659                            if let Some(col) = create_table
660                                .column_defs
661                                .iter_mut()
662                                .find(|c| c.name == index_column)
663                            {
664                                col.options =
665                                    options_from_skipping(&SkippingIndexOptions::default())
666                                        .context(ColumnOptionsSnafu)?;
667                            } else {
668                                warn!(
669                                    "Column {} not found when creating index for trace table: {}.",
670                                    index_column, create_table.table_name
671                                );
672                            }
673                        }
674
675                        // use table_options to mark table model version
676                        create_table.table_options.insert(
677                            TABLE_DATA_MODEL.to_string(),
678                            TABLE_DATA_MODEL_TRACE_V1.to_string(),
679                        );
680
681                        let table = self
682                            .create_physical_table(
683                                create_table,
684                                Some(partitions),
685                                ctx,
686                                statement_executor,
687                            )
688                            .await?;
689                        let table_info = table.table_info();
690                        if table_info.is_ttl_instant_table() {
691                            instant_table_ids.insert(table_info.table_id());
692                        }
693                        table_infos.insert(table_info.table_id(), table.table_info());
694                    }
695                }
696                for alter_expr in alter_tables.into_iter() {
697                    statement_executor
698                        .alter_table_inner(alter_expr, ctx.clone())
699                        .await?;
700                }
701            }
702        }
703
704        // refresh table infos for altered tables
705        for (catalog, schema, table_name) in need_refresh_table_infos {
706            let table = self
707                .get_table(&catalog, &schema, &table_name)
708                .await?
709                .context(TableNotFoundSnafu {
710                    table_name: common_catalog::format_full_table_name(
711                        &catalog,
712                        &schema,
713                        &table_name,
714                    ),
715                })?;
716            let table_info = table.table_info();
717            table_infos.insert(table_info.table_id(), table.table_info());
718        }
719
720        Ok(CreateAlterTableResult {
721            instant_table_ids,
722            table_infos,
723        })
724    }
725
726    async fn create_physical_table_on_demand(
727        &self,
728        ctx: &QueryContextRef,
729        physical_table: String,
730        statement_executor: &StatementExecutor,
731    ) -> Result<()> {
732        let catalog_name = ctx.current_catalog();
733        let schema_name = ctx.current_schema();
734
735        // check if exist
736        if self
737            .get_table(catalog_name, &schema_name, &physical_table)
738            .await?
739            .is_some()
740        {
741            return Ok(());
742        }
743
744        let table_reference = TableReference::full(catalog_name, &schema_name, &physical_table);
745        info!("Physical metric table `{table_reference}` does not exist, try creating table");
746
747        // schema with timestamp and field column
748        let default_schema = vec![
749            ColumnSchema {
750                column_name: greptime_timestamp().to_string(),
751                datatype: ColumnDataType::TimestampMillisecond as _,
752                semantic_type: SemanticType::Timestamp as _,
753                datatype_extension: None,
754                options: None,
755            },
756            ColumnSchema {
757                column_name: greptime_value().to_string(),
758                datatype: ColumnDataType::Float64 as _,
759                semantic_type: SemanticType::Field as _,
760                datatype_extension: None,
761                options: None,
762            },
763        ];
764        let create_table_expr =
765            &mut build_create_table_expr(&table_reference, &default_schema, default_engine())?;
766
767        create_table_expr.engine = METRIC_ENGINE_NAME.to_string();
768        create_table_expr
769            .table_options
770            .insert(PHYSICAL_TABLE_METADATA_KEY.to_string(), "true".to_string());
771
772        // create physical table
773        let res = statement_executor
774            .create_table_inner(create_table_expr, None, ctx.clone())
775            .await;
776
777        match res {
778            Ok(_) => {
779                info!("Successfully created table {table_reference}",);
780                Ok(())
781            }
782            Err(err) => {
783                error!(err; "Failed to create table {table_reference}");
784                Err(err)
785            }
786        }
787    }
788
789    async fn get_table(
790        &self,
791        catalog: &str,
792        schema: &str,
793        table: &str,
794    ) -> Result<Option<TableRef>> {
795        self.catalog_manager
796            .table(catalog, schema, table, None)
797            .await
798            .context(CatalogSnafu)
799    }
800
801    fn get_create_table_expr_on_demand(
802        &self,
803        req: &RowInsertRequest,
804        create_type: &AutoCreateTableType,
805        ctx: &QueryContextRef,
806    ) -> Result<CreateTableExpr> {
807        let mut table_options = std::collections::HashMap::with_capacity(4);
808        fill_table_options_for_create(&mut table_options, create_type, ctx);
809
810        let engine_name = if let AutoCreateTableType::Logical(_) = create_type {
811            // engine should be metric engine when creating logical tables.
812            METRIC_ENGINE_NAME
813        } else {
814            default_engine()
815        };
816
817        let schema = ctx.current_schema();
818        let table_ref = TableReference::full(ctx.current_catalog(), &schema, &req.table_name);
819        // SAFETY: `req.rows` is guaranteed to be `Some` by `handle_row_inserts_with_create_type()`.
820        let request_schema = req.rows.as_ref().unwrap().schema.as_slice();
821        let mut create_table_expr =
822            build_create_table_expr(&table_ref, request_schema, engine_name)?;
823
824        info!("Table `{table_ref}` does not exist, try creating table");
825        create_table_expr.table_options.extend(table_options);
826        Ok(create_table_expr)
827    }
828
829    /// Returns an alter table expression if it finds new columns in the request.
830    /// When `accommodate_existing_schema` is false, it always adds columns if not exist.
831    /// When `accommodate_existing_schema` is true, it may modify the input `req` to
832    /// accommodate it with existing schema. See [`create_or_alter_tables_on_demand`](Self::create_or_alter_tables_on_demand)
833    /// for more details.
834    /// When `accommodate_existing_schema` is true and `is_single_value` is true, it also consider fields when modifying the
835    /// input `req`.
836    fn get_alter_table_expr_on_demand(
837        &self,
838        req: &mut RowInsertRequest,
839        table: &TableRef,
840        ctx: &QueryContextRef,
841        accommodate_existing_schema: bool,
842        is_single_value: bool,
843    ) -> Result<Option<AlterTableExpr>> {
844        let catalog_name = ctx.current_catalog();
845        let schema_name = ctx.current_schema();
846        let table_name = table.table_info().name.clone();
847
848        let request_schema = req.rows.as_ref().unwrap().schema.as_slice();
849        let column_exprs = ColumnExpr::from_column_schemas(request_schema);
850        let add_columns = expr_helper::extract_add_columns_expr(&table.schema(), column_exprs)?;
851        let Some(mut add_columns) = add_columns else {
852            return Ok(None);
853        };
854
855        // If accommodate_existing_schema is true, update request schema for Timestamp/Field columns
856        if accommodate_existing_schema {
857            let table_schema = table.schema();
858            // Find timestamp column name
859            let ts_col_name = table_schema.timestamp_column().map(|c| c.name.clone());
860            // Find field column name if there is only one and `is_single_value` is true.
861            let mut field_col_name = None;
862            if is_single_value {
863                let mut multiple_field_cols = false;
864                table.field_columns().for_each(|col| {
865                    if field_col_name.is_none() {
866                        field_col_name = Some(col.name.clone());
867                    } else {
868                        multiple_field_cols = true;
869                    }
870                });
871                if multiple_field_cols {
872                    field_col_name = None;
873                }
874            }
875
876            // Update column name in request schema for Timestamp/Field columns
877            if let Some(rows) = req.rows.as_mut() {
878                for col in &mut rows.schema {
879                    match col.semantic_type {
880                        x if x == SemanticType::Timestamp as i32 => {
881                            if let Some(ref ts_name) = ts_col_name
882                                && col.column_name != *ts_name
883                            {
884                                col.column_name = ts_name.clone();
885                            }
886                        }
887                        x if x == SemanticType::Field as i32 => {
888                            if let Some(ref field_name) = field_col_name
889                                && col.column_name != *field_name
890                            {
891                                col.column_name = field_name.clone();
892                            }
893                        }
894                        _ => {}
895                    }
896                }
897            }
898
899            // Only keep columns that are tags or non-single field.
900            add_columns.add_columns.retain(|col| {
901                let def = col.column_def.as_ref().unwrap();
902                def.semantic_type == SemanticType::Tag as i32
903                    || (def.semantic_type == SemanticType::Field as i32 && field_col_name.is_none())
904            });
905
906            if add_columns.add_columns.is_empty() {
907                return Ok(None);
908            }
909        }
910
911        Ok(Some(AlterTableExpr {
912            catalog_name: catalog_name.to_string(),
913            schema_name: schema_name.clone(),
914            table_name: table_name.clone(),
915            kind: Some(Kind::AddColumns(add_columns)),
916        }))
917    }
918
919    /// Creates a table with options.
920    async fn create_physical_table(
921        &self,
922        mut create_table_expr: CreateTableExpr,
923        partitions: Option<Partitions>,
924        ctx: &QueryContextRef,
925        statement_executor: &StatementExecutor,
926    ) -> Result<TableRef> {
927        {
928            let table_ref = TableReference::full(
929                &create_table_expr.catalog_name,
930                &create_table_expr.schema_name,
931                &create_table_expr.table_name,
932            );
933
934            info!("Table `{table_ref}` does not exist, try creating table");
935        }
936        let res = statement_executor
937            .create_table_inner(&mut create_table_expr, partitions, ctx.clone())
938            .await;
939
940        let table_ref = TableReference::full(
941            &create_table_expr.catalog_name,
942            &create_table_expr.schema_name,
943            &create_table_expr.table_name,
944        );
945
946        match res {
947            Ok(table) => {
948                info!(
949                    "Successfully created table {} with options: {:?}",
950                    table_ref, create_table_expr.table_options,
951                );
952                Ok(table)
953            }
954            Err(err) => {
955                error!(err; "Failed to create table {}", table_ref);
956                Err(err)
957            }
958        }
959    }
960
961    async fn create_logical_tables(
962        &self,
963        create_table_exprs: Vec<CreateTableExpr>,
964        ctx: &QueryContextRef,
965        statement_executor: &StatementExecutor,
966    ) -> Result<Vec<TableRef>> {
967        let res = statement_executor
968            .create_logical_tables(&create_table_exprs, ctx.clone())
969            .await;
970
971        match res {
972            Ok(res) => {
973                info!("Successfully created logical tables");
974                Ok(res)
975            }
976            Err(err) => {
977                let failed_tables = create_table_exprs
978                    .into_iter()
979                    .map(|expr| {
980                        format!(
981                            "{}.{}.{}",
982                            expr.catalog_name, expr.schema_name, expr.table_name
983                        )
984                    })
985                    .collect::<Vec<_>>();
986                error!(
987                    err;
988                    "Failed to create logical tables {:?}",
989                    failed_tables
990                );
991                Err(err)
992            }
993        }
994    }
995
996    pub fn node_manager(&self) -> &NodeManagerRef {
997        &self.node_manager
998    }
999
1000    pub fn partition_manager(&self) -> &PartitionRuleManagerRef {
1001        &self.partition_manager
1002    }
1003}
1004
1005fn validate_column_count_match(requests: &RowInsertRequests) -> Result<()> {
1006    for request in &requests.inserts {
1007        let rows = request.rows.as_ref().unwrap();
1008        let column_count = rows.schema.len();
1009        rows.rows.iter().try_for_each(|r| {
1010            ensure!(
1011                r.values.len() == column_count,
1012                InvalidInsertRequestSnafu {
1013                    reason: format!(
1014                        "column count mismatch, columns: {}, values: {}",
1015                        column_count,
1016                        r.values.len()
1017                    )
1018                }
1019            );
1020            Ok(())
1021        })?;
1022    }
1023    Ok(())
1024}
1025
1026/// Fill table options for a new table by create type.
1027pub fn fill_table_options_for_create(
1028    table_options: &mut std::collections::HashMap<String, String>,
1029    create_type: &AutoCreateTableType,
1030    ctx: &QueryContextRef,
1031) {
1032    for key in VALID_TABLE_OPTION_KEYS {
1033        if let Some(value) = ctx.extension(key) {
1034            table_options.insert(key.to_string(), value.to_string());
1035        }
1036    }
1037
1038    match create_type {
1039        AutoCreateTableType::Logical(physical_table) => {
1040            table_options.insert(
1041                LOGICAL_TABLE_METADATA_KEY.to_string(),
1042                physical_table.clone(),
1043            );
1044        }
1045        AutoCreateTableType::Physical => {
1046            if let Some(append_mode) = ctx.extension(APPEND_MODE_KEY) {
1047                table_options.insert(APPEND_MODE_KEY.to_string(), append_mode.to_string());
1048            }
1049            if let Some(merge_mode) = ctx.extension(MERGE_MODE_KEY) {
1050                table_options.insert(MERGE_MODE_KEY.to_string(), merge_mode.to_string());
1051            }
1052            if let Some(time_window) = ctx.extension(TWCS_TIME_WINDOW) {
1053                table_options.insert(TWCS_TIME_WINDOW.to_string(), time_window.to_string());
1054                // We need to set the compaction type explicitly.
1055                table_options.insert(
1056                    COMPACTION_TYPE.to_string(),
1057                    COMPACTION_TYPE_TWCS.to_string(),
1058                );
1059            }
1060        }
1061        // Set append_mode to true for log table.
1062        // because log tables should keep rows with the same ts and tags.
1063        AutoCreateTableType::Log => {
1064            table_options.insert(APPEND_MODE_KEY.to_string(), "true".to_string());
1065        }
1066        AutoCreateTableType::LastNonNull => {
1067            table_options.insert(MERGE_MODE_KEY.to_string(), "last_non_null".to_string());
1068        }
1069        AutoCreateTableType::Trace => {
1070            table_options.insert(APPEND_MODE_KEY.to_string(), "true".to_string());
1071        }
1072    }
1073}
1074
1075pub fn build_create_table_expr(
1076    table: &TableReference,
1077    request_schema: &[ColumnSchema],
1078    engine: &str,
1079) -> Result<CreateTableExpr> {
1080    expr_helper::create_table_expr_by_column_schemas(table, request_schema, engine, None)
1081}
1082
1083/// Result of `create_or_alter_tables_on_demand`.
1084struct CreateAlterTableResult {
1085    /// table ids of ttl=instant tables.
1086    instant_table_ids: HashSet<TableId>,
1087    /// Table Info of the created tables.
1088    table_infos: HashMap<TableId, Arc<TableInfo>>,
1089}
1090
1091struct FlowMirrorTask {
1092    requests: HashMap<Peer, RegionInsertRequests>,
1093    num_rows: usize,
1094}
1095
1096impl FlowMirrorTask {
1097    async fn new(
1098        cache: &TableFlownodeSetCacheRef,
1099        requests: impl Iterator<Item = &RegionInsertRequest>,
1100    ) -> Result<Self> {
1101        let mut src_table_reqs: HashMap<TableId, Option<(Vec<Peer>, RegionInsertRequests)>> =
1102            HashMap::new();
1103        let mut num_rows = 0;
1104
1105        for req in requests {
1106            let table_id = RegionId::from_u64(req.region_id).table_id();
1107            match src_table_reqs.get_mut(&table_id) {
1108                Some(Some((_peers, reqs))) => reqs.requests.push(req.clone()),
1109                // already know this is not source table
1110                Some(None) => continue,
1111                _ => {
1112                    // dedup peers
1113                    let peers = cache
1114                        .get(table_id)
1115                        .await
1116                        .context(RequestInsertsSnafu)?
1117                        .unwrap_or_default()
1118                        .values()
1119                        .cloned()
1120                        .collect::<HashSet<_>>()
1121                        .into_iter()
1122                        .collect::<Vec<_>>();
1123
1124                    if !peers.is_empty() {
1125                        let mut reqs = RegionInsertRequests::default();
1126                        reqs.requests.push(req.clone());
1127                        num_rows += reqs
1128                            .requests
1129                            .iter()
1130                            .map(|r| r.rows.as_ref().unwrap().rows.len())
1131                            .sum::<usize>();
1132                        src_table_reqs.insert(table_id, Some((peers, reqs)));
1133                    } else {
1134                        // insert a empty entry to avoid repeat query
1135                        src_table_reqs.insert(table_id, None);
1136                    }
1137                }
1138            }
1139        }
1140
1141        let mut inserts: HashMap<Peer, RegionInsertRequests> = HashMap::new();
1142
1143        for (_table_id, (peers, reqs)) in src_table_reqs
1144            .into_iter()
1145            .filter_map(|(k, v)| v.map(|v| (k, v)))
1146        {
1147            if peers.len() == 1 {
1148                // fast path, zero copy
1149                inserts
1150                    .entry(peers[0].clone())
1151                    .or_default()
1152                    .requests
1153                    .extend(reqs.requests);
1154                continue;
1155            } else {
1156                // TODO(discord9): need to split requests to multiple flownodes
1157                for flownode in peers {
1158                    inserts
1159                        .entry(flownode.clone())
1160                        .or_default()
1161                        .requests
1162                        .extend(reqs.requests.clone());
1163                }
1164            }
1165        }
1166
1167        Ok(Self {
1168            requests: inserts,
1169            num_rows,
1170        })
1171    }
1172
1173    fn detach(self, node_manager: NodeManagerRef) -> Result<()> {
1174        crate::metrics::DIST_MIRROR_PENDING_ROW_COUNT.add(self.num_rows as i64);
1175        for (peer, inserts) in self.requests {
1176            let node_manager = node_manager.clone();
1177            common_runtime::spawn_global(async move {
1178                let result = node_manager
1179                    .flownode(&peer)
1180                    .await
1181                    .handle_inserts(inserts)
1182                    .await
1183                    .context(RequestInsertsSnafu);
1184
1185                match result {
1186                    Ok(resp) => {
1187                        let affected_rows = resp.affected_rows;
1188                        crate::metrics::DIST_MIRROR_ROW_COUNT.inc_by(affected_rows);
1189                        crate::metrics::DIST_MIRROR_PENDING_ROW_COUNT.sub(affected_rows as _);
1190                    }
1191                    Err(err) => {
1192                        error!(err; "Failed to insert data into flownode {}", peer);
1193                    }
1194                }
1195            });
1196        }
1197
1198        Ok(())
1199    }
1200}
1201
1202#[cfg(test)]
1203mod tests {
1204    use std::sync::Arc;
1205
1206    use api::v1::helper::{field_column_schema, time_index_column_schema};
1207    use api::v1::{RowInsertRequest, Rows, Value};
1208    use common_catalog::consts::{DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME};
1209    use common_meta::cache::new_table_flownode_set_cache;
1210    use common_meta::ddl::test_util::datanode_handler::NaiveDatanodeHandler;
1211    use common_meta::test_util::MockDatanodeManager;
1212    use datatypes::data_type::ConcreteDataType;
1213    use datatypes::schema::ColumnSchema;
1214    use moka::future::Cache;
1215    use session::context::QueryContext;
1216    use table::TableRef;
1217    use table::dist_table::DummyDataSource;
1218    use table::metadata::{TableInfoBuilder, TableMetaBuilder, TableType};
1219
1220    use super::*;
1221    use crate::tests::{create_partition_rule_manager, prepare_mocked_backend};
1222
1223    fn make_table_ref_with_schema(ts_name: &str, field_name: &str) -> TableRef {
1224        let schema = datatypes::schema::SchemaBuilder::try_from_columns(vec![
1225            ColumnSchema::new(
1226                ts_name,
1227                ConcreteDataType::timestamp_millisecond_datatype(),
1228                false,
1229            )
1230            .with_time_index(true),
1231            ColumnSchema::new(field_name, ConcreteDataType::float64_datatype(), true),
1232        ])
1233        .unwrap()
1234        .build()
1235        .unwrap();
1236        let meta = TableMetaBuilder::empty()
1237            .schema(Arc::new(schema))
1238            .primary_key_indices(vec![])
1239            .value_indices(vec![1])
1240            .engine("mito")
1241            .next_column_id(0)
1242            .options(Default::default())
1243            .created_on(Default::default())
1244            .build()
1245            .unwrap();
1246        let info = Arc::new(
1247            TableInfoBuilder::default()
1248                .table_id(1)
1249                .table_version(0)
1250                .name("test_table")
1251                .schema_name(DEFAULT_SCHEMA_NAME)
1252                .catalog_name(DEFAULT_CATALOG_NAME)
1253                .desc(None)
1254                .table_type(TableType::Base)
1255                .meta(meta)
1256                .build()
1257                .unwrap(),
1258        );
1259        Arc::new(table::Table::new(
1260            info,
1261            table::metadata::FilterPushDownType::Unsupported,
1262            Arc::new(DummyDataSource),
1263        ))
1264    }
1265
1266    #[tokio::test]
1267    async fn test_accommodate_existing_schema_logic() {
1268        let ts_name = "my_ts";
1269        let field_name = "my_field";
1270        let table = make_table_ref_with_schema(ts_name, field_name);
1271
1272        // The request uses different names for timestamp and field columns
1273        let mut req = RowInsertRequest {
1274            table_name: "test_table".to_string(),
1275            rows: Some(Rows {
1276                schema: vec![
1277                    time_index_column_schema("ts_wrong", ColumnDataType::TimestampMillisecond),
1278                    field_column_schema("field_wrong", ColumnDataType::Float64),
1279                ],
1280                rows: vec![api::v1::Row {
1281                    values: vec![Value::default(), Value::default()],
1282                }],
1283            }),
1284        };
1285        let ctx = Arc::new(QueryContext::with(
1286            DEFAULT_CATALOG_NAME,
1287            DEFAULT_SCHEMA_NAME,
1288        ));
1289
1290        let kv_backend = prepare_mocked_backend().await;
1291        let inserter = Inserter::new(
1292            catalog::memory::MemoryCatalogManager::new(),
1293            create_partition_rule_manager(kv_backend.clone()).await,
1294            Arc::new(MockDatanodeManager::new(NaiveDatanodeHandler)),
1295            Arc::new(new_table_flownode_set_cache(
1296                String::new(),
1297                Cache::new(100),
1298                kv_backend.clone(),
1299            )),
1300        );
1301        let alter_expr = inserter
1302            .get_alter_table_expr_on_demand(&mut req, &table, &ctx, true, true)
1303            .unwrap();
1304        assert!(alter_expr.is_none());
1305
1306        // The request's schema should have updated names for timestamp and field columns
1307        let req_schema = req.rows.as_ref().unwrap().schema.clone();
1308        assert_eq!(req_schema[0].column_name, ts_name);
1309        assert_eq!(req_schema[1].column_name, field_name);
1310    }
1311}