tests_fuzz/
generator.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
15pub mod alter_expr;
16pub mod create_expr;
17pub mod insert_expr;
18pub mod repartition_expr;
19pub mod select_expr;
20
21use std::fmt;
22
23use datatypes::data_type::ConcreteDataType;
24use datatypes::types::TimestampType;
25use datatypes::value::Value;
26use rand::Rng;
27
28use crate::error::Error;
29use crate::ir::create_expr::ColumnOption;
30use crate::ir::{AlterTableExpr, CreateTableExpr, Ident};
31
32pub type CreateTableExprGenerator<R> =
33    Box<dyn Generator<CreateTableExpr, R, Error = Error> + Sync + Send>;
34
35pub type AlterTableExprGenerator<R> =
36    Box<dyn Generator<AlterTableExpr, R, Error = Error> + Sync + Send>;
37
38pub type ColumnOptionGenerator<R> = Box<dyn Fn(&mut R, &ConcreteDataType) -> Vec<ColumnOption>>;
39
40pub type ConcreteDataTypeGenerator<R> = Box<dyn Random<ConcreteDataType, R>>;
41
42pub type ValueGenerator<R> =
43    Box<dyn Fn(&mut R, &ConcreteDataType, Option<&dyn Random<Ident, R>>) -> Value>;
44
45pub type TsValueGenerator<R> = Box<dyn Fn(&mut R, TimestampType) -> Value>;
46
47pub trait Generator<T, R: Rng> {
48    type Error: Sync + Send + fmt::Debug;
49
50    fn generate(&self, rng: &mut R) -> Result<T, Self::Error>;
51}
52
53pub trait Random<T, R: Rng> {
54    /// Generates a random element.
55    fn generate(&self, rng: &mut R) -> T {
56        self.choose(rng, 1).remove(0)
57    }
58
59    /// Uniformly sample `amount` distinct elements.
60    fn choose(&self, rng: &mut R, amount: usize) -> Vec<T>;
61}
62
63#[macro_export]
64macro_rules! impl_random {
65    ($type: ident, $value:ident, $values: ident) => {
66        impl<R: Rng> Random<$type, R> for $value {
67            fn choose(&self, rng: &mut R, amount: usize) -> Vec<$type> {
68                // Collects the elements in deterministic order first.
69                let mut result = std::collections::BTreeSet::new();
70                while result.len() != amount {
71                    result.insert($values.choose(rng).unwrap().clone());
72                }
73                let mut result = result.into_iter().map(Into::into).collect::<Vec<_>>();
74                // Shuffles the result slice.
75                result.shuffle(rng);
76                result
77            }
78        }
79    };
80}