Skip to main content

flow/batching_mode/
table_creator.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 api::v1::CreateTableExpr;
16use common_recordbatch::map_dictionary_to_values_data_type;
17use datafusion_common::tree_node::TreeNode;
18use datafusion_expr::LogicalPlan;
19use datatypes::prelude::ConcreteDataType;
20use datatypes::schema::ColumnSchema;
21use operator::expr_helper::column_schemas_to_defs;
22use snafu::ResultExt;
23
24use crate::Error;
25use crate::adapter::{AUTO_CREATED_PLACEHOLDER_TS_COL, AUTO_CREATED_UPDATE_AT_TS_COL};
26use crate::batching_mode::utils::FindGroupByFinalName;
27use crate::error::{ConvertColumnSchemaSnafu, DatafusionSnafu};
28
29#[derive(Debug, Clone, PartialEq, Eq)]
30pub enum QueryType {
31    /// query is a tql query
32    Tql,
33    /// query is a sql query
34    Sql,
35}
36
37// auto created table have a auto added column `update_at`, and optional have a `AUTO_CREATED_PLACEHOLDER_TS_COL` column for time index placeholder if no timestamp column is specified
38// TODO(discord9): for now no default value is set for auto added column for compatibility reason with streaming mode, but this might change in favor of simpler code?
39pub(super) fn create_table_with_expr(
40    plan: &LogicalPlan,
41    sink_table_name: &[String; 3],
42    query_type: &QueryType,
43) -> Result<CreateTableExpr, Error> {
44    let table_def = match query_type {
45        &QueryType::Sql => {
46            if let Some(def) = build_pk_from_aggr(plan)? {
47                def
48            } else {
49                build_by_sql_schema(plan)?
50            }
51        }
52        // Every string column of a PromQL answer is a label of its output series. An aggregate
53        // inside the plan does not tell which: in `m / scalar(sum(m))` it groups by time alone
54        // while the answer keeps every label of `m`.
55        QueryType::Tql => build_by_tql_schema(plan)?,
56    };
57    let first_time_stamp = table_def.ts_col;
58    let primary_keys = table_def.pks;
59
60    let mut column_schemas = Vec::new();
61    for field in plan.schema().fields() {
62        let name = field.name();
63        let ty = map_dictionary_to_values_data_type(&ConcreteDataType::from_arrow_type(
64            field.data_type(),
65        ));
66        let col_schema = if first_time_stamp == Some(name.clone()) {
67            ColumnSchema::new(name, ty, false).with_time_index(true)
68        } else {
69            ColumnSchema::new(name, ty, true)
70        };
71
72        match query_type {
73            QueryType::Sql => {
74                column_schemas.push(col_schema);
75            }
76            QueryType::Tql => {
77                // if is val column, need to rename as val DOUBLE NULL
78                // if is tag column, need to cast type as STRING NULL
79                let is_tag_column = primary_keys.contains(name);
80                let is_val_column = !is_tag_column && first_time_stamp.as_ref() != Some(name);
81                if is_val_column {
82                    let col_schema =
83                        ColumnSchema::new(name, ConcreteDataType::float64_datatype(), true);
84                    column_schemas.push(col_schema);
85                } else if is_tag_column {
86                    let col_schema =
87                        ColumnSchema::new(name, ConcreteDataType::string_datatype(), true);
88                    column_schemas.push(col_schema);
89                } else {
90                    // time index column
91                    column_schemas.push(col_schema);
92                }
93            }
94        }
95    }
96
97    if query_type == &QueryType::Sql {
98        let update_at_schema = ColumnSchema::new(
99            AUTO_CREATED_UPDATE_AT_TS_COL,
100            ConcreteDataType::timestamp_millisecond_datatype(),
101            true,
102        );
103        column_schemas.push(update_at_schema);
104    }
105
106    let time_index = if let Some(time_index) = first_time_stamp {
107        time_index
108    } else {
109        column_schemas.push(
110            ColumnSchema::new(
111                AUTO_CREATED_PLACEHOLDER_TS_COL,
112                ConcreteDataType::timestamp_millisecond_datatype(),
113                false,
114            )
115            .with_time_index(true),
116        );
117        AUTO_CREATED_PLACEHOLDER_TS_COL.to_string()
118    };
119
120    let column_defs =
121        column_schemas_to_defs(column_schemas, &primary_keys).context(ConvertColumnSchemaSnafu)?;
122    Ok(CreateTableExpr {
123        catalog_name: sink_table_name[0].clone(),
124        schema_name: sink_table_name[1].clone(),
125        table_name: sink_table_name[2].clone(),
126        desc: "Auto created table by flow engine".to_string(),
127        column_defs,
128        time_index,
129        primary_keys,
130        create_if_not_exists: true,
131        table_options: Default::default(),
132        table_id: None,
133        engine: "mito".to_string(),
134    })
135}
136
137/// simply build by schema, return first timestamp column and no primary key
138fn build_by_sql_schema(plan: &LogicalPlan) -> Result<TableDef, Error> {
139    let first_time_stamp = plan.schema().fields().iter().find_map(|f| {
140        if ConcreteDataType::from_arrow_type(f.data_type()).is_timestamp() {
141            Some(f.name().clone())
142        } else {
143            None
144        }
145    });
146    Ok(TableDef {
147        ts_col: first_time_stamp,
148        pks: vec![],
149    })
150}
151
152/// Return first timestamp column found in output schema and all string columns
153fn build_by_tql_schema(plan: &LogicalPlan) -> Result<TableDef, Error> {
154    let first_time_stamp = plan.schema().fields().iter().find_map(|f| {
155        if ConcreteDataType::from_arrow_type(f.data_type()).is_timestamp() {
156            Some(f.name().clone())
157        } else {
158            None
159        }
160    });
161    let string_columns = plan
162        .schema()
163        .fields()
164        .iter()
165        .filter_map(|f| {
166            if map_dictionary_to_values_data_type(&ConcreteDataType::from_arrow_type(f.data_type()))
167                .is_string()
168            {
169                Some(f.name().clone())
170            } else {
171                None
172            }
173        })
174        .collect::<Vec<_>>();
175
176    Ok(TableDef {
177        ts_col: first_time_stamp,
178        pks: string_columns,
179    })
180}
181
182struct TableDef {
183    ts_col: Option<String>,
184    pks: Vec<String>,
185}
186
187/// Return first timestamp column which is in group by clause and other columns which are also in group by clause
188///
189/// # Returns
190///
191/// * `Option<String>` - first timestamp column which is in group by clause
192/// * `Vec<String>` - other columns which are also in group by clause
193///
194/// if no aggregation found, return None
195fn build_pk_from_aggr(plan: &LogicalPlan) -> Result<Option<TableDef>, Error> {
196    let fields = plan.schema().fields();
197    let mut pk_names = FindGroupByFinalName::default();
198
199    plan.visit(&mut pk_names)
200        .with_context(|_| DatafusionSnafu {
201            context: format!("Can't find aggr expr in plan {plan:?}"),
202        })?;
203
204    // if no group by clause, return empty with first timestamp column found in output schema
205    let Some(pk_final_names) = pk_names.get_group_expr_names() else {
206        return Ok(None);
207    };
208    if pk_final_names.is_empty() {
209        let first_ts_col = fields
210            .iter()
211            .find(|f| ConcreteDataType::from_arrow_type(f.data_type()).is_timestamp())
212            .map(|f| f.name().clone());
213        return Ok(Some(TableDef {
214            ts_col: first_ts_col,
215            pks: vec![],
216        }));
217    }
218
219    let all_pk_cols: Vec<_> = fields
220        .iter()
221        .filter(|f| pk_final_names.contains(f.name()))
222        .map(|f| f.name().clone())
223        .collect();
224    // Auto-created tables use the first timestamp column in the group-by keys
225    // as the time index. It is possible that timestamp columns appear only as
226    // aggregate outputs (for example `max(ts)`) and are not group-by keys; in
227    // that case `first_time_stamp` stays `None` and the caller falls back to a
228    // placeholder time index column.
229    let first_time_stamp = fields
230        .iter()
231        .find(|f| {
232            all_pk_cols.contains(&f.name().clone())
233                && ConcreteDataType::from_arrow_type(f.data_type()).is_timestamp()
234        })
235        .map(|f| f.name().clone());
236
237    let all_pk_cols: Vec<_> = all_pk_cols
238        .into_iter()
239        .filter(|col| first_time_stamp.as_ref() != Some(col))
240        .collect();
241
242    Ok(Some(TableDef {
243        ts_col: first_time_stamp,
244        pks: all_pk_cols,
245    }))
246}
247
248#[cfg(test)]
249mod test {
250    use std::sync::Arc;
251
252    use api::v1::column_def::try_as_column_schema;
253    use catalog::RegisterTableRequest;
254    use catalog::memory::new_memory_catalog_manager;
255    use common_catalog::consts::{DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME};
256    use datafusion::arrow::datatypes::{
257        DataType as ArrowDataType, Field, Schema as ArrowSchema, TimeUnit,
258    };
259    use datafusion_common::DFSchema;
260    use datafusion_expr::logical_plan::EmptyRelation;
261    use datatypes::prelude::ConcreteDataType;
262    use datatypes::schema::{ColumnSchema, Schema};
263    use pretty_assertions::assert_eq;
264    use query::options::QueryOptions;
265    use query::{QueryEngineFactory, QueryEngineRef};
266    use session::context::QueryContext;
267    use table::metadata::{TableInfoBuilder, TableMetaBuilder};
268    use table::test_util::EmptyTable;
269
270    use super::*;
271    use crate::adapter::{AUTO_CREATED_PLACEHOLDER_TS_COL, AUTO_CREATED_UPDATE_AT_TS_COL};
272    use crate::batching_mode::utils::sql_to_df_plan;
273    use crate::test_utils::create_test_query_engine;
274
275    #[test]
276    fn test_tql_dictionary_string_is_label() {
277        let arrow_schema = Arc::new(ArrowSchema::new(vec![
278            Field::new_dictionary("host", ArrowDataType::UInt32, ArrowDataType::Utf8, true),
279            Field::new("value", ArrowDataType::Float64, true),
280            Field::new(
281                "ts",
282                ArrowDataType::Timestamp(TimeUnit::Millisecond, None),
283                false,
284            ),
285        ]));
286        let plan = LogicalPlan::EmptyRelation(EmptyRelation {
287            produce_one_row: false,
288            schema: Arc::new(DFSchema::try_from(arrow_schema).unwrap()),
289        });
290
291        let expr = create_table_with_expr(
292            &plan,
293            &[
294                "greptime".to_string(),
295                "public".to_string(),
296                "sink".to_string(),
297            ],
298            &QueryType::Tql,
299        )
300        .unwrap();
301        let columns = expr
302            .column_defs
303            .iter()
304            .map(|column| try_as_column_schema(column).unwrap())
305            .collect::<Vec<_>>();
306
307        assert_eq!(vec!["host".to_string()], expr.primary_keys);
308        assert_eq!("ts", expr.time_index);
309        assert_eq!(ConcreteDataType::string_datatype(), columns[0].data_type);
310        assert_eq!(ConcreteDataType::float64_datatype(), columns[1].data_type);
311        assert!(columns[2].is_time_index());
312    }
313
314    /// Creates a query engine holding a Prometheus shaped table `http_requests`: tags
315    /// (`host`, `idc`), a single f64 value column (`val`) and a time index (`ts`), so that
316    /// TQL queries can be planned against it.
317    fn create_tql_test_query_engine() -> QueryEngineRef {
318        let catalog_list = new_memory_catalog_manager().unwrap();
319        let table_meta = TableMetaBuilder::empty()
320            .schema(Arc::new(Schema::new(vec![
321                ColumnSchema::new(
322                    "ts",
323                    ConcreteDataType::timestamp_millisecond_datatype(),
324                    false,
325                )
326                .with_time_index(true),
327                ColumnSchema::new("host", ConcreteDataType::string_datatype(), true),
328                ColumnSchema::new("idc", ConcreteDataType::string_datatype(), true),
329                ColumnSchema::new("val", ConcreteDataType::float64_datatype(), true),
330            ])))
331            // `host` and `idc` are tags, `val` is the value column
332            .primary_key_indices(vec![1, 2])
333            .value_indices(vec![3])
334            .engine("mito".to_string())
335            .next_column_id(1026)
336            .build()
337            .unwrap();
338        let table_info = TableInfoBuilder::default()
339            .name("http_requests".to_string())
340            .meta(table_meta)
341            .build()
342            .unwrap();
343        assert!(
344            catalog_list
345                .register_table_sync(RegisterTableRequest {
346                    catalog: DEFAULT_CATALOG_NAME.to_string(),
347                    schema: DEFAULT_SCHEMA_NAME.to_string(),
348                    table_name: "http_requests".to_string(),
349                    table_id: 1026,
350                    table: EmptyTable::from_table_info(&table_info),
351                })
352                .is_ok()
353        );
354
355        QueryEngineFactory::new(
356            catalog_list,
357            None,
358            None,
359            None,
360            None,
361            false,
362            QueryOptions::default(),
363        )
364        .query_engine()
365    }
366
367    /// A TQL `count_values` flow must keep the generated label as a primary key of the auto
368    /// created sink table. `count_values("status_code", http_requests)` groups by the sample
369    /// value column and projects the label as a unary scalar expression of that column
370    /// (`prom_float_to_string(val) AS status_code`), so the label only derives from a group by
371    /// column instead of referencing it directly.
372    ///
373    /// The plan is built with the same path a flow task uses (including the DataFusion
374    /// optimizers, which may rewrite the shape of the alias), and the assertion covers both.
375    #[tokio::test]
376    async fn test_tql_count_values_generated_label_is_primary_key() {
377        let query_engine = create_tql_test_query_engine();
378        let ctx = QueryContext::arc();
379
380        for optimize in [false, true] {
381            let plan = sql_to_df_plan(
382                ctx.clone(),
383                query_engine.clone(),
384                r#"TQL EVAL (0, 15, '5s') count_values("status_code", http_requests)"#,
385                optimize,
386            )
387            .await
388            .unwrap();
389            let plan_display = plan.display_indent_schema().to_string();
390            let expr = create_table_with_expr(
391                &plan,
392                &[
393                    "greptime".to_string(),
394                    "public".to_string(),
395                    "sink".to_string(),
396                ],
397                &QueryType::Tql,
398            )
399            .unwrap();
400            let columns = expr
401                .column_defs
402                .iter()
403                .map(|column| try_as_column_schema(column).unwrap())
404                .collect::<Vec<_>>();
405
406            assert_eq!(
407                vec!["status_code".to_string()],
408                expr.primary_keys,
409                "optimize={optimize}, plan:\n{plan_display}"
410            );
411            assert_eq!(
412                "ts", expr.time_index,
413                "optimize={optimize}, plan:\n{plan_display}"
414            );
415            // the aggregation output is a value column, the generated label is a tag column
416            assert_eq!(
417                "count(http_requests.val)", columns[0].name,
418                "optimize={optimize}, plan:\n{plan_display}"
419            );
420            assert_eq!(ConcreteDataType::float64_datatype(), columns[0].data_type);
421            assert_eq!("ts", columns[1].name);
422            assert!(columns[1].is_time_index());
423            assert_eq!("status_code", columns[2].name);
424            assert_eq!(ConcreteDataType::string_datatype(), columns[2].data_type);
425        }
426    }
427
428    #[tokio::test]
429    async fn test_gen_create_table_sql() {
430        let query_engine = create_test_query_engine();
431        let ctx = QueryContext::arc();
432        struct TestCase {
433            sql: String,
434            sink_table_name: String,
435            column_schemas: Vec<ColumnSchema>,
436            primary_keys: Vec<String>,
437            time_index: String,
438        }
439
440        let update_at_schema = ColumnSchema::new(
441            AUTO_CREATED_UPDATE_AT_TS_COL,
442            ConcreteDataType::timestamp_millisecond_datatype(),
443            true,
444        );
445
446        let ts_placeholder_schema = ColumnSchema::new(
447            AUTO_CREATED_PLACEHOLDER_TS_COL,
448            ConcreteDataType::timestamp_millisecond_datatype(),
449            false,
450        )
451        .with_time_index(true);
452
453        let testcases = vec![
454            TestCase {
455                sql: "SELECT number, ts FROM numbers_with_ts".to_string(),
456                sink_table_name: "new_table".to_string(),
457                column_schemas: vec![
458                    ColumnSchema::new("number", ConcreteDataType::uint32_datatype(), true),
459                    ColumnSchema::new(
460                        "ts",
461                        ConcreteDataType::timestamp_millisecond_datatype(),
462                        false,
463                    )
464                    .with_time_index(true),
465                    update_at_schema.clone(),
466                ],
467                primary_keys: vec![],
468                time_index: "ts".to_string(),
469            },
470            TestCase {
471                sql: "SELECT number, max(ts) FROM numbers_with_ts GROUP BY number".to_string(),
472                sink_table_name: "new_table".to_string(),
473                column_schemas: vec![
474                    ColumnSchema::new("number", ConcreteDataType::uint32_datatype(), true),
475                    ColumnSchema::new(
476                        "max(numbers_with_ts.ts)",
477                        ConcreteDataType::timestamp_millisecond_datatype(),
478                        true,
479                    ),
480                    update_at_schema.clone(),
481                    ts_placeholder_schema.clone(),
482                ],
483                primary_keys: vec!["number".to_string()],
484                time_index: AUTO_CREATED_PLACEHOLDER_TS_COL.to_string(),
485            },
486            TestCase {
487                sql: "SELECT max(number), ts FROM numbers_with_ts GROUP BY ts".to_string(),
488                sink_table_name: "new_table".to_string(),
489                column_schemas: vec![
490                    ColumnSchema::new(
491                        "max(numbers_with_ts.number)",
492                        ConcreteDataType::uint32_datatype(),
493                        true,
494                    ),
495                    ColumnSchema::new(
496                        "ts",
497                        ConcreteDataType::timestamp_millisecond_datatype(),
498                        false,
499                    )
500                    .with_time_index(true),
501                    update_at_schema.clone(),
502                ],
503                primary_keys: vec![],
504                time_index: "ts".to_string(),
505            },
506            TestCase {
507                sql: "SELECT number, ts FROM numbers_with_ts GROUP BY ts, number".to_string(),
508                sink_table_name: "new_table".to_string(),
509                column_schemas: vec![
510                    ColumnSchema::new("number", ConcreteDataType::uint32_datatype(), true),
511                    ColumnSchema::new(
512                        "ts",
513                        ConcreteDataType::timestamp_millisecond_datatype(),
514                        false,
515                    )
516                    .with_time_index(true),
517                    update_at_schema.clone(),
518                ],
519                primary_keys: vec!["number".to_string()],
520                time_index: "ts".to_string(),
521            },
522        ];
523
524        for tc in testcases {
525            let plan = sql_to_df_plan(ctx.clone(), query_engine.clone(), &tc.sql, true)
526                .await
527                .unwrap();
528            let expr = create_table_with_expr(
529                &plan,
530                &[
531                    "greptime".to_string(),
532                    "public".to_string(),
533                    tc.sink_table_name.clone(),
534                ],
535                &QueryType::Sql,
536            )
537            .unwrap();
538            // TODO(discord9): assert expr
539            let column_schemas = expr
540                .column_defs
541                .iter()
542                .map(|c| try_as_column_schema(c).unwrap())
543                .collect::<Vec<_>>();
544            assert_eq!(tc.column_schemas, column_schemas, "{:?}", tc.sql);
545            assert_eq!(tc.primary_keys, expr.primary_keys, "{:?}", tc.sql);
546            assert_eq!(tc.time_index, expr.time_index, "{:?}", tc.sql);
547        }
548    }
549}