tests_fuzz/validator/
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 snafu::{ensure, ResultExt};
16use sqlx::{MySqlPool, Row};
17
18use crate::error::{self, Result, UnexpectedSnafu};
19use crate::ir::alter_expr::AlterTableOption;
20
21/// Parses table options from the result of `SHOW CREATE TABLE`
22/// An example of the result of `SHOW CREATE TABLE`:
23/// +-------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
24/// | Table | Create Table                                                                                                                                                                                           |
25/// +-------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
26/// | json  | CREATE TABLE IF NOT EXISTS `json` (`ts` TIMESTAMP(3) NOT NULL, `j` JSON NULL, TIME INDEX (`ts`)) ENGINE=mito WITH(compaction.twcs.max_output_file_size = '1M', compaction.type = 'twcs', ttl = '1day') |
27/// +-------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
28fn parse_show_create(show_create: &str) -> Result<Vec<AlterTableOption>> {
29    if let Some(option_start) = show_create.find("WITH(") {
30        let option_end = {
31            let remain_str = &show_create[option_start..];
32            if let Some(end) = remain_str.find(')') {
33                end + option_start
34            } else {
35                return UnexpectedSnafu {
36                    violated: format!("Cannot find the end of the options in: {}", show_create),
37                }
38                .fail();
39            }
40        };
41        let options = &show_create[option_start + 5..option_end];
42        Ok(AlterTableOption::parse_kv_pairs(options)?)
43    } else {
44        Ok(vec![])
45    }
46}
47
48/// Fetches table options from the context
49pub async fn fetch_table_options(db: &MySqlPool, sql: &str) -> Result<Vec<AlterTableOption>> {
50    let fetched_rows = sqlx::query(sql)
51        .fetch_all(db)
52        .await
53        .context(error::ExecuteQuerySnafu { sql })?;
54    ensure!(
55        fetched_rows.len() == 1,
56        error::AssertSnafu {
57            reason: format!(
58                "Expected fetched row length: 1, got: {}",
59                fetched_rows.len(),
60            )
61        }
62    );
63
64    let row = fetched_rows.first().unwrap();
65    let show_create = row.try_get::<String, usize>(1).unwrap();
66    parse_show_create(&show_create)
67}
68
69#[cfg(test)]
70mod tests {
71    use std::str::FromStr;
72
73    use common_base::readable_size::ReadableSize;
74    use common_time::Duration;
75
76    use super::*;
77    use crate::ir::alter_expr::Ttl;
78    use crate::ir::AlterTableOption;
79
80    #[test]
81    fn test_parse_show_create() {
82        let show_create = "CREATE TABLE IF NOT EXISTS `json` (`ts` TIMESTAMP(3) NOT NULL, `j` JSON NULL, TIME INDEX (`ts`)) ENGINE=mito WITH(compaction.twcs.max_output_file_size = '1M', compaction.type = 'twcs', ttl = '1day')";
83        let options = parse_show_create(show_create).unwrap();
84        assert_eq!(options.len(), 2);
85        assert_eq!(
86            options[0],
87            AlterTableOption::TwcsMaxOutputFileSize(ReadableSize::from_str("1MB").unwrap())
88        );
89        assert_eq!(
90            options[1],
91            AlterTableOption::Ttl(Ttl::Duration(Duration::new_second(24 * 60 * 60)))
92        );
93    }
94}