tests_fuzz/translator/mysql/
select_expr.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 crate::error::{Error, Result};
16use crate::ir::select_expr::SelectExpr;
17use crate::translator::DslTranslator;
18
19pub struct SelectExprTranslator;
20
21impl DslTranslator<SelectExpr, String> for SelectExprTranslator {
22    type Error = Error;
23
24    fn translate(&self, input: &SelectExpr) -> Result<String> {
25        let columns = input
26            .columns
27            .iter()
28            .map(|c| c.name.to_string())
29            .collect::<Vec<_>>()
30            .join(", ")
31            .to_string();
32
33        let order_by = input
34            .order_by
35            .iter()
36            .map(|c| c.as_str())
37            .collect::<Vec<_>>()
38            .join(", ")
39            .to_string();
40
41        Ok(format!(
42            "SELECT {} FROM {} ORDER BY {} {};",
43            columns, input.table_name, order_by, input.direction,
44        ))
45    }
46}
47
48#[cfg(test)]
49mod tests {
50    use std::sync::Arc;
51
52    use rand::SeedableRng;
53
54    use super::SelectExprTranslator;
55    use crate::generator::select_expr::SelectExprGeneratorBuilder;
56    use crate::generator::Generator;
57    use crate::test_utils;
58    use crate::translator::DslTranslator;
59
60    #[test]
61    fn test_select_expr_translator() {
62        let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0);
63
64        let test_ctx = test_utils::new_test_ctx();
65        let select_expr_generator = SelectExprGeneratorBuilder::default()
66            .table_ctx(Arc::new(test_ctx))
67            .build()
68            .unwrap();
69
70        let select_expr = select_expr_generator.generate(&mut rng).unwrap();
71        let output = SelectExprTranslator.translate(&select_expr).unwrap();
72        let expected =
73            r#"SELECT ts, memory_util, cpu_util, disk_util FROM test ORDER BY disk_util, ts DESC;"#;
74        assert_eq!(output, expected);
75    }
76}