common_meta/ddl/test_util/
create_table.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::collections::HashMap;
16use std::sync::Arc;
17
18use api::v1::column_def::try_as_column_schema;
19use api::v1::meta::Partition;
20use api::v1::{ColumnDataType, ColumnDef, CreateTableExpr, SemanticType};
21use chrono::DateTime;
22use common_catalog::consts::{
23    DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME, MITO_ENGINE, MITO2_ENGINE,
24};
25use datatypes::schema::Schema;
26use derive_builder::Builder;
27use store_api::storage::TableId;
28use table::metadata::{TableIdent, TableInfo, TableMeta, TableType};
29use table::requests::TableOptions;
30
31use crate::ddl::test_util::columns::TestColumnDefBuilder;
32use crate::rpc::ddl::CreateTableTask;
33
34#[derive(Default, Builder)]
35#[builder(default)]
36pub struct TestCreateTableExpr {
37    #[builder(setter(into), default = "DEFAULT_CATALOG_NAME.to_string()")]
38    catalog_name: String,
39    #[builder(setter(into), default = "DEFAULT_SCHEMA_NAME.to_string()")]
40    schema_name: String,
41    #[builder(setter(into))]
42    table_name: String,
43    #[builder(setter(into))]
44    desc: String,
45    #[builder(setter(into))]
46    column_defs: Vec<ColumnDef>,
47    #[builder(setter(into))]
48    time_index: String,
49    #[builder(setter(into))]
50    primary_keys: Vec<String>,
51    create_if_not_exists: bool,
52    table_options: HashMap<String, String>,
53    #[builder(setter(into, strip_option))]
54    table_id: Option<TableId>,
55    #[builder(setter(into), default = "MITO2_ENGINE.to_string()")]
56    engine: String,
57}
58
59impl From<TestCreateTableExpr> for CreateTableExpr {
60    fn from(
61        TestCreateTableExpr {
62            catalog_name,
63            schema_name,
64            table_name,
65            desc,
66            column_defs,
67            time_index,
68            primary_keys,
69            create_if_not_exists,
70            table_options,
71            table_id,
72            engine,
73        }: TestCreateTableExpr,
74    ) -> Self {
75        Self {
76            catalog_name,
77            schema_name,
78            table_name,
79            desc,
80            column_defs,
81            time_index,
82            primary_keys,
83            create_if_not_exists,
84            table_options,
85            table_id: table_id.map(|id| api::v1::TableId { id }),
86            engine,
87        }
88    }
89}
90
91/// Builds [TableInfo] from [CreateTableExpr].
92pub fn build_raw_table_info_from_expr(expr: &CreateTableExpr) -> TableInfo {
93    TableInfo {
94        ident: TableIdent {
95            table_id: expr
96                .table_id
97                .as_ref()
98                .map(|table_id| table_id.id)
99                .unwrap_or(0),
100            version: 1,
101        },
102        name: expr.table_name.clone(),
103        desc: Some(expr.desc.clone()),
104        catalog_name: expr.catalog_name.clone(),
105        schema_name: expr.schema_name.clone(),
106        meta: TableMeta {
107            schema: Arc::new(Schema::new(
108                expr.column_defs
109                    .iter()
110                    .map(|column| try_as_column_schema(column).unwrap())
111                    .collect(),
112            )),
113            primary_key_indices: expr
114                .primary_keys
115                .iter()
116                .map(|key| {
117                    expr.column_defs
118                        .iter()
119                        .position(|column| &column.name == key)
120                        .unwrap()
121                })
122                .collect(),
123            value_indices: vec![],
124            engine: expr.engine.clone(),
125            next_column_id: expr.column_defs.len() as u32,
126            options: TableOptions::try_from_iter(&expr.table_options).unwrap(),
127            created_on: DateTime::default(),
128            updated_on: DateTime::default(),
129            partition_key_indices: vec![],
130            column_ids: vec![],
131        },
132        table_type: TableType::Base,
133    }
134}
135
136pub fn test_create_table_task(name: &str, table_id: TableId) -> CreateTableTask {
137    let create_table = TestCreateTableExprBuilder::default()
138        .column_defs([
139            TestColumnDefBuilder::default()
140                .name("ts")
141                .data_type(ColumnDataType::TimestampMillisecond)
142                .semantic_type(SemanticType::Timestamp)
143                .build()
144                .unwrap()
145                .into(),
146            TestColumnDefBuilder::default()
147                .name("host")
148                .data_type(ColumnDataType::String)
149                .semantic_type(SemanticType::Tag)
150                .build()
151                .unwrap()
152                .into(),
153            TestColumnDefBuilder::default()
154                .name("cpu")
155                .data_type(ColumnDataType::Float64)
156                .semantic_type(SemanticType::Field)
157                .build()
158                .unwrap()
159                .into(),
160        ])
161        .table_id(table_id)
162        .time_index("ts")
163        .primary_keys(["host".into()])
164        .table_name(name)
165        .engine(MITO_ENGINE)
166        .build()
167        .unwrap()
168        .into();
169    let table_info = build_raw_table_info_from_expr(&create_table);
170    CreateTableTask {
171        create_table,
172        // Single region
173        partitions: vec![Partition::default()],
174        table_info,
175    }
176}