Skip to main content

connectorx/
dispatcher.rs

1//! This module provides [`dispatcher::Dispatcher`], the core struct in ConnectorX
2//! that drives the data loading from a source to a destination.
3use crate::{
4    data_order::{coordinate, DataOrder},
5    destinations::{Destination, DestinationPartition},
6    errors::{ConnectorXError, Result as CXResult},
7    sources::{PartitionParser, Source, SourcePartition},
8    sql::CXQuery,
9    typesystem::Transport,
10};
11use itertools::Itertools;
12use log::debug;
13use rayon::prelude::*;
14use std::marker::PhantomData;
15
16/// What [`Dispatcher::prepare`] returns: the negotiated data order, the source and
17/// destination partitions, and the source and destination schemas.
18pub type Prepared<'w, S, D> = (
19    DataOrder,
20    Vec<<S as Source>::Partition>,
21    Vec<<D as Destination>::Partition<'w>>,
22    Vec<<S as Source>::TypeSystem>,
23    Vec<<D as Destination>::TypeSystem>,
24);
25
26/// A dispatcher takes a `S: Source`, a `D: Destination`, a `TP: Transport` and a vector of `queries` as input to
27/// load data from `S` to `D` using the queries.
28pub struct Dispatcher<'a, S, D, TP> {
29    src: S,
30    dst: &'a mut D,
31    queries: Vec<CXQuery<String>>,
32    origin_query: Option<String>,
33    _phantom: PhantomData<TP>,
34}
35
36impl<'w, S, D, TP> Dispatcher<'w, S, D, TP>
37where
38    S: Source,
39    D: Destination,
40    TP: Transport<TSS = S::TypeSystem, TSD = D::TypeSystem, S = S, D = D>,
41{
42    /// Create a new dispatcher by providing a source, a destination and the queries.
43    pub fn new<Q>(src: S, dst: &'w mut D, queries: &[Q], origin_query: Option<String>) -> Self
44    where
45        for<'a> &'a Q: Into<CXQuery>,
46    {
47        Self {
48            src,
49            dst,
50            queries: queries.iter().map(Into::into).collect(),
51            origin_query,
52            _phantom: PhantomData,
53        }
54    }
55
56    /// Set queries the source runs on each connection before the actual queries.
57    pub fn set_pre_execution_queries(&mut self, pre_execution_queries: Option<&[String]>) {
58        self.src.set_pre_execution_queries(pre_execution_queries);
59    }
60
61    /// Fetch the metadata, allocate the destination and return the source and destination partitions without running them.
62    pub fn prepare(mut self) -> Result<Prepared<'w, S, D>, TP::Error> {
63        debug!("Prepare");
64        let dorder = coordinate(S::DATA_ORDERS, D::DATA_ORDERS)?;
65        self.src.set_data_order(dorder)?;
66        self.src.set_queries(self.queries.as_slice());
67        self.src.set_origin_query(self.origin_query);
68
69        debug!("Fetching metadata");
70        self.src.fetch_metadata()?;
71        let src_schema = self.src.schema();
72        let dst_schema = src_schema
73            .iter()
74            .map(|&s| TP::convert_typesystem(s))
75            .collect::<CXResult<Vec<_>>>()?;
76        let names = self.src.names();
77
78        let mut total_rows = if self.dst.needs_count() {
79            // return None if cannot derive total count
80            debug!("Try get row rounts for entire result");
81            self.src.result_rows()?
82        } else {
83            debug!("Do not need counts in advance");
84            Some(0)
85        };
86        let mut src_partitions: Vec<S::Partition> = self.src.partition()?;
87        if self.dst.needs_count() && total_rows.is_none() {
88            debug!("Manually count rows of each partitioned query and sum up");
89            // run queries
90            src_partitions
91                .par_iter_mut()
92                .try_for_each(|partition| -> Result<(), S::Error> { partition.result_rows() })?;
93
94            // get number of row of each partition from the source
95            let part_rows: Vec<usize> = src_partitions
96                .iter()
97                .map(|partition| partition.nrows())
98                .collect();
99            total_rows = Some(part_rows.iter().sum());
100        }
101        let total_rows = total_rows.ok_or_else(ConnectorXError::CountError)?;
102
103        debug!(
104            "Allocate destination memory: {}x{}",
105            total_rows,
106            src_schema.len()
107        );
108        self.dst.allocate(total_rows, &names, &dst_schema, dorder)?;
109
110        debug!("Create destination partition");
111        let dst_partitions = self.dst.partition(self.queries.len())?;
112
113        Ok((
114            dorder,
115            src_partitions,
116            dst_partitions,
117            src_schema,
118            dst_schema,
119        ))
120    }
121
122    /// Start the data loading process.
123    pub fn run(self) -> Result<(), TP::Error> {
124        debug!("Run dispatcher");
125        let (dorder, src_partitions, dst_partitions, src_schema, dst_schema) = self.prepare()?;
126
127        #[cfg(all(not(feature = "branch"), not(feature = "fptr")))]
128        compile_error!("branch or fptr, pick one");
129
130        #[cfg(feature = "branch")]
131        let schemas: Vec<_> = src_schema
132            .iter()
133            .zip_eq(&dst_schema)
134            .map(|(&src_ty, &dst_ty)| (src_ty, dst_ty))
135            .collect();
136
137        debug!("Start writing");
138        // parse and write
139        dst_partitions
140            .into_par_iter()
141            .zip_eq(src_partitions)
142            .enumerate()
143            .try_for_each(|(i, (mut dst, mut src))| -> Result<(), TP::Error> {
144                #[cfg(feature = "fptr")]
145                let f: Vec<_> = src_schema
146                    .iter()
147                    .zip_eq(&dst_schema)
148                    .map(|(&src_ty, &dst_ty)| TP::processor(src_ty, dst_ty))
149                    .collect::<CXResult<Vec<_>>>()?;
150
151                let mut parser = src.parser()?;
152
153                match dorder {
154                    DataOrder::RowMajor => loop {
155                        let (n, is_last) = parser.fetch_next()?;
156                        dst.aquire_row(n)?;
157                        for _ in 0..n {
158                            #[allow(clippy::needless_range_loop)]
159                            for col in 0..dst.ncols() {
160                                #[cfg(feature = "fptr")]
161                                f[col](&mut parser, &mut dst)?;
162
163                                #[cfg(feature = "branch")]
164                                {
165                                    let (s1, s2) = schemas[col];
166                                    TP::process(s1, s2, &mut parser, &mut dst)?;
167                                }
168                            }
169                        }
170                        if is_last {
171                            break;
172                        }
173                    },
174                    DataOrder::ColumnMajor => loop {
175                        let (n, is_last) = parser.fetch_next()?;
176                        dst.aquire_row(n)?;
177                        #[allow(clippy::needless_range_loop)]
178                        for col in 0..dst.ncols() {
179                            for _ in 0..n {
180                                #[cfg(feature = "fptr")]
181                                f[col](&mut parser, &mut dst)?;
182                                #[cfg(feature = "branch")]
183                                {
184                                    let (s1, s2) = schemas[col];
185                                    TP::process(s1, s2, &mut parser, &mut dst)?;
186                                }
187                            }
188                        }
189                        if is_last {
190                            break;
191                        }
192                    },
193                }
194
195                debug!("Finalize partition {}", i);
196                dst.finalize()?;
197                debug!("Partition {} finished", i);
198                Ok(())
199            })?;
200
201        debug!("Writing finished");
202
203        Ok(())
204    }
205
206    /// Only fetch the metadata (header) of the destination.
207    pub fn get_meta(&mut self) -> Result<(), TP::Error> {
208        let dorder = coordinate(S::DATA_ORDERS, D::DATA_ORDERS)?;
209        self.src.set_data_order(dorder)?;
210        self.src.set_queries(self.queries.as_slice());
211        self.src.set_origin_query(self.origin_query.clone());
212        self.src.fetch_metadata()?;
213        let src_schema = self.src.schema();
214        let dst_schema = src_schema
215            .iter()
216            .map(|&s| TP::convert_typesystem(s))
217            .collect::<CXResult<Vec<_>>>()?;
218        let names = self.src.names();
219        self.dst.allocate(0, &names, &dst_schema, dorder)?;
220        Ok(())
221    }
222}