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::{ResultExt, ensure};
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 // Safety: the SQL is built by fuzz validators from generated identifiers only.
51 let fetched_rows = sqlx::query(sqlx::AssertSqlSafe(sql))
52 .fetch_all(db)
53 .await
54 .context(error::ExecuteQuerySnafu { sql })?;
55 ensure!(
56 fetched_rows.len() == 1,
57 error::AssertSnafu {
58 reason: format!(
59 "Expected fetched row length: 1, got: {}",
60 fetched_rows.len(),
61 )
62 }
63 );
64
65 let row = fetched_rows.first().unwrap();
66 let show_create = row.try_get::<String, usize>(1).unwrap();
67 parse_show_create(&show_create)
68}
69
70#[cfg(test)]
71mod tests {
72 use std::str::FromStr;
73
74 use common_base::readable_size::ReadableSize;
75 use common_time::Duration;
76
77 use super::*;
78 use crate::ir::AlterTableOption;
79 use crate::ir::alter_expr::Ttl;
80
81 #[test]
82 fn test_parse_show_create() {
83 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')";
84 let options = parse_show_create(show_create).unwrap();
85 assert_eq!(options.len(), 2);
86 assert_eq!(
87 options[0],
88 AlterTableOption::TwcsMaxOutputFileSize(ReadableSize::from_str("1MB").unwrap())
89 );
90 assert_eq!(
91 options[1],
92 AlterTableOption::Ttl(Ttl::Duration(Duration::new_second(24 * 60 * 60)))
93 );
94 }
95}