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
32        let order_by = input
33            .order_by
34            .iter()
35            .map(|c| c.as_str())
36            .collect::<Vec<_>>()
37            .join(", ");
38
39        Ok(format!(
40            "SELECT {} FROM {} ORDER BY {} {};",
41            columns, input.table_name, order_by, input.direction,
42        ))
43    }
44}
45
46#[cfg(test)]
47mod tests {
48    use std::sync::Arc;
49
50    use rand::SeedableRng;
51
52    use super::SelectExprTranslator;
53    use crate::generator::Generator;
54    use crate::generator::select_expr::SelectExprGeneratorBuilder;
55    use crate::test_utils;
56    use crate::translator::DslTranslator;
57
58    #[test]
59    fn test_select_expr_translator() {
60        let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0);
61
62        let test_ctx = test_utils::new_test_ctx();
63        let select_expr_generator = SelectExprGeneratorBuilder::default()
64            .table_ctx(Arc::new(test_ctx))
65            .build()
66            .unwrap();
67
68        let select_expr = select_expr_generator.generate(&mut rng).unwrap();
69        let output = SelectExprTranslator.translate(&select_expr).unwrap();
70        let expected =
71            r#"SELECT ts, memory_util, cpu_util, disk_util FROM test ORDER BY disk_util, ts DESC;"#;
72        assert_eq!(output, expected);
73    }
74}