Skip to main content

connectorx/sources/dummy/
mod.rs

1//! A dummy source that generates different values based on an internal counter.
2//! This source is for test purpose.
3
4mod typesystem;
5
6pub use self::typesystem::DummyTypeSystem;
7use super::{PartitionParser, Produce, Source, SourcePartition};
8use crate::data_order::DataOrder;
9use crate::errors::{ConnectorXError, Result};
10use crate::sql::CXQuery;
11use chrono::{offset, DateTime, Utc};
12use fehler::{throw, throws};
13use num_traits::cast::FromPrimitive;
14
15/// Source that generates values without a database, for tests and benchmarks.
16pub struct DummySource {
17    names: Vec<String>,
18    schema: Vec<DummyTypeSystem>,
19    queries: Vec<CXQuery<String>>,
20}
21
22impl DummySource {
23    /// Create a source with the given column names and types.
24    pub fn new<S: AsRef<str>>(names: &[S], schema: &[DummyTypeSystem]) -> Self {
25        assert_eq!(names.len(), schema.len());
26        DummySource {
27            names: names.iter().map(|s| s.as_ref().to_string()).collect(),
28            schema: schema.to_vec(),
29            queries: vec![],
30        }
31    }
32}
33
34impl Source for DummySource {
35    const DATA_ORDERS: &'static [DataOrder] = &[DataOrder::RowMajor];
36    type TypeSystem = DummyTypeSystem;
37    type Partition = DummySourcePartition;
38    type Error = ConnectorXError;
39
40    #[throws(ConnectorXError)]
41    fn set_data_order(&mut self, data_order: DataOrder) {
42        if !matches!(data_order, DataOrder::RowMajor) {
43            throw!(ConnectorXError::UnsupportedDataOrder(data_order))
44        }
45    }
46
47    // query: nrows,ncols
48    fn set_queries<Q: ToString>(&mut self, queries: &[CXQuery<Q>]) {
49        self.queries = queries.iter().map(|q| q.map(Q::to_string)).collect();
50    }
51
52    fn set_origin_query(&mut self, _query: Option<String>) {}
53
54    fn fetch_metadata(&mut self) -> Result<()> {
55        Ok(())
56    }
57
58    fn result_rows(&mut self) -> Result<Option<usize>> {
59        Ok(None)
60    }
61
62    fn names(&self) -> Vec<String> {
63        self.names.clone()
64    }
65
66    fn schema(&self) -> Vec<Self::TypeSystem> {
67        self.schema.clone()
68    }
69
70    fn partition(self) -> Result<Vec<Self::Partition>> {
71        assert!(!self.queries.is_empty());
72        let queries = self.queries;
73        let schema = self.schema;
74
75        Ok(queries
76            .into_iter()
77            .map(|q| DummySourcePartition::new(&schema, &q))
78            .collect())
79    }
80}
81
82/// One partition of a [`DummySource`].
83pub struct DummySourcePartition {
84    nrows: usize,
85    ncols: usize,
86    counter: usize,
87}
88
89impl DummySourcePartition {
90    /// Create a partition from a query of the form `"nrows,ncols"`.
91    pub fn new(_schema: &[DummyTypeSystem], q: &CXQuery<String>) -> Self {
92        let v: Vec<usize> = q.as_str().split(',').map(|s| s.parse().unwrap()).collect();
93
94        DummySourcePartition {
95            nrows: v[0],
96            ncols: v[1],
97            counter: 0,
98        }
99    }
100}
101
102impl SourcePartition for DummySourcePartition {
103    type TypeSystem = DummyTypeSystem;
104    type Parser<'a> = DummySourcePartitionParser<'a>;
105    type Error = ConnectorXError;
106
107    fn result_rows(&mut self) -> Result<()> {
108        Ok(())
109    }
110
111    fn parser(&mut self) -> Result<Self::Parser<'_>> {
112        Ok(DummySourcePartitionParser::new(
113            &mut self.counter,
114            self.nrows,
115            self.ncols,
116        ))
117    }
118
119    fn nrows(&self) -> usize {
120        self.nrows
121    }
122
123    fn ncols(&self) -> usize {
124        self.ncols
125    }
126}
127
128/// Value parser for a dummy partition.
129pub struct DummySourcePartitionParser<'a> {
130    counter: &'a mut usize,
131    #[allow(unused)]
132    nrows: usize,
133    ncols: usize,
134}
135
136impl<'a> DummySourcePartitionParser<'a> {
137    fn new(counter: &'a mut usize, nrows: usize, ncols: usize) -> Self {
138        DummySourcePartitionParser {
139            counter,
140            ncols,
141            nrows,
142        }
143    }
144
145    fn next_val(&mut self) -> usize {
146        let ret = *self.counter / self.ncols;
147        *self.counter += 1;
148        ret
149    }
150}
151
152impl<'a> PartitionParser<'a> for DummySourcePartitionParser<'a> {
153    type TypeSystem = DummyTypeSystem;
154    type Error = ConnectorXError;
155
156    fn fetch_next(&mut self) -> Result<(usize, bool)> {
157        Ok((self.nrows, true))
158    }
159}
160
161macro_rules! numeric_impl {
162    ($($t: ty),+) => {
163        $(
164            impl<'r, 'a> Produce<'r, $t> for DummySourcePartitionParser<'a> {
165                type Error = ConnectorXError;
166
167                fn produce(&mut self) -> Result<$t> {
168                    let ret = self.next_val();
169                    Ok(FromPrimitive::from_usize(ret).unwrap_or_default())
170                }
171            }
172
173            impl<'r, 'a> Produce<'r, Option<$t>> for DummySourcePartitionParser<'a> {
174                type Error = ConnectorXError;
175
176                fn produce(&mut self) -> Result<Option<$t>> {
177                    let ret = self.next_val();
178                    Ok(Some(FromPrimitive::from_usize(ret).unwrap_or_default()))
179                }
180            }
181        )+
182    };
183}
184
185numeric_impl!(u64, i32, i64, f64);
186
187impl<'r, 'a> Produce<'r, String> for DummySourcePartitionParser<'a> {
188    type Error = ConnectorXError;
189
190    fn produce(&mut self) -> Result<String> {
191        let ret = self.next_val().to_string();
192        Ok(ret)
193    }
194}
195
196impl<'r, 'a> Produce<'r, Option<String>> for DummySourcePartitionParser<'a> {
197    type Error = ConnectorXError;
198
199    fn produce(&mut self) -> Result<Option<String>> {
200        let ret = self.next_val().to_string();
201        Ok(Some(ret))
202    }
203}
204
205impl<'r, 'a> Produce<'r, bool> for DummySourcePartitionParser<'a> {
206    type Error = ConnectorXError;
207
208    fn produce(&mut self) -> Result<bool> {
209        let ret = self.next_val().is_multiple_of(2);
210        Ok(ret)
211    }
212}
213
214impl<'r, 'a> Produce<'r, Option<bool>> for DummySourcePartitionParser<'a> {
215    type Error = ConnectorXError;
216
217    fn produce(&mut self) -> Result<Option<bool>> {
218        let ret = match self.next_val() % 3 {
219            0 => Some(true),
220            1 => Some(false),
221            2 => None,
222            _ => unreachable!(),
223        };
224
225        Ok(ret)
226    }
227}
228
229impl<'r, 'a> Produce<'r, DateTime<Utc>> for DummySourcePartitionParser<'a> {
230    type Error = ConnectorXError;
231
232    fn produce(&mut self) -> Result<DateTime<Utc>> {
233        self.next_val();
234        let ret = offset::Utc::now();
235
236        Ok(ret)
237    }
238}
239
240impl<'r, 'a> Produce<'r, Option<DateTime<Utc>>> for DummySourcePartitionParser<'a> {
241    type Error = ConnectorXError;
242
243    fn produce(&mut self) -> Result<Option<DateTime<Utc>>> {
244        self.next_val();
245        let ret = match self.next_val() % 2 {
246            0 => Some(offset::Utc::now()),
247            1 => None,
248            _ => unreachable!(),
249        };
250        Ok(ret)
251    }
252}