Skip to main content

connectorx/sources/
mod.rs

1//! This module defines four traits [`Source`], [`SourcePartition`], [`PartitionParser`], and [`Produce`]  to define a source.
2//! This module also contains source implementations for various databases.
3
4#[cfg(feature = "src_bigquery")]
5pub mod bigquery;
6#[cfg(feature = "src_clickhouse")]
7pub mod clickhouse;
8#[cfg(feature = "src_csv")]
9pub mod csv;
10#[cfg(feature = "src_dummy")]
11pub mod dummy;
12#[cfg(feature = "src_mssql_common")]
13pub mod mssql;
14#[cfg(feature = "src_mysql")]
15pub mod mysql;
16/// Oracle source.
17#[cfg(feature = "src_oracle")]
18pub mod oracle;
19#[cfg(feature = "src_postgres")]
20pub mod postgres;
21#[cfg(feature = "src_sqlite")]
22pub mod sqlite;
23/// Trino source.
24#[cfg(feature = "src_trino")]
25pub mod trino;
26
27use crate::data_order::DataOrder;
28use crate::errors::ConnectorXError;
29use crate::sql::CXQuery;
30use crate::typesystem::{TypeAssoc, TypeSystem};
31use std::fmt::Debug;
32
33/// A `Source` connects to a database, fetches the metadata of a query and splits the work into
34/// [`SourcePartition`]s, one per partitioned query.
35///
36/// [`Dispatcher`](crate::dispatcher::Dispatcher) drives a `Source` in this order:
37/// [`set_data_order`](Source::set_data_order), [`set_queries`](Source::set_queries),
38/// [`set_origin_query`](Source::set_origin_query), [`fetch_metadata`](Source::fetch_metadata),
39/// then [`schema`](Source::schema) and [`names`](Source::names), optionally
40/// [`result_rows`](Source::result_rows), and finally [`partition`](Source::partition).
41pub trait Source {
42    /// Supported data orders, ordering by preference.
43    const DATA_ORDERS: &'static [DataOrder];
44    /// The type system this `Source` associated with.
45    type TypeSystem: TypeSystem;
46    /// The partition type produced by [`partition`](Source::partition). It is sent to a worker
47    /// thread, so it must be `Send`.
48    type Partition: SourcePartition<TypeSystem = Self::TypeSystem, Error = Self::Error> + Send;
49    /// The error type returned by this source and its partitions.
50    type Error: From<ConnectorXError> + Send + Debug;
51
52    /// Set the data order negotiated between this source and the destination, one of
53    /// [`DATA_ORDERS`](Source::DATA_ORDERS). Return an error if the order is not supported.
54    fn set_data_order(&mut self, data_order: DataOrder) -> Result<(), Self::Error>;
55
56    /// Set the partitioned queries. Each query becomes one [`SourcePartition`].
57    fn set_queries<Q: ToString>(&mut self, queries: &[CXQuery<Q>]);
58
59    /// Set the original, unpartitioned query, if there is one. Sources can use it to
60    /// count the rows of the whole result in [`result_rows`](Source::result_rows).
61    fn set_origin_query(&mut self, query: Option<String>);
62
63    /// Set queries to run on each connection before the partitioned queries.
64    /// The default implementation panics; sources that support it override it.
65    fn set_pre_execution_queries(&mut self, _pre_execution_queries: Option<&[String]>) {
66        unimplemented!("pre_execution_queries is not implemented in this source type");
67    }
68
69    /// Fetch the result schema (column names and types) of the queries, e.g. by preparing the
70    /// statement or running a `LIMIT 0` query. Called before [`names`](Source::names) and
71    /// [`schema`](Source::schema).
72    fn fetch_metadata(&mut self) -> Result<(), Self::Error>;
73    /// Get total number of rows if available.
74    ///
75    /// Return `Ok(None)` when the total cannot be derived; the dispatcher then counts each
76    /// partition with [`SourcePartition::result_rows`] instead.
77    fn result_rows(&mut self) -> Result<Option<usize>, Self::Error>;
78
79    /// The column names of the result, available after [`fetch_metadata`](Source::fetch_metadata).
80    fn names(&self) -> Vec<String>;
81
82    /// The column types of the result, available after [`fetch_metadata`](Source::fetch_metadata).
83    fn schema(&self) -> Vec<Self::TypeSystem>;
84
85    /// Consume the source and create one partition per query given to
86    /// [`set_queries`](Source::set_queries), in the same order.
87    fn partition(self) -> Result<Vec<Self::Partition>, Self::Error>;
88}
89
90/// In general, a `DataSource` abstracts the data source as a stream, which can produce
91/// a sequence of values of variate types by repetitively calling the function `produce`.
92pub trait SourcePartition {
93    /// The type system of the parent [`Source`].
94    type TypeSystem: TypeSystem;
95    /// The parser that reads the rows of this partition, borrowing from it.
96    type Parser<'a>: PartitionParser<'a, TypeSystem = Self::TypeSystem, Error = Self::Error>
97    where
98        Self: 'a;
99    /// The error type of the parent [`Source`].
100    type Error: From<ConnectorXError> + Send + Debug;
101
102    /// Count total number of rows in each partition.
103    ///
104    /// The count is stored in the partition and reported by [`nrows`](SourcePartition::nrows).
105    /// It is only called when the destination needs a count and
106    /// [`Source::result_rows`] returned `None`.
107    fn result_rows(&mut self) -> Result<(), Self::Error>;
108
109    /// Run the partition's query and return a parser over its result.
110    fn parser(&mut self) -> Result<Self::Parser<'_>, Self::Error>;
111
112    /// Number of rows this `DataSource` got.
113    /// Sometimes it is not possible for the source to know how many rows it gets before reading the whole data.
114    fn nrows(&self) -> usize;
115
116    /// Number of cols this `DataSource` got.
117    fn ncols(&self) -> usize;
118}
119
120/// A `PartitionParser` reads the values of one partition's result, one cell at a time.
121///
122/// The dispatcher calls [`fetch_next`](PartitionParser::fetch_next) to buffer a batch of rows,
123/// then [`parse`](PartitionParser::parse) once per cell in the negotiated
124/// [`DataOrder`]. Each cell's type comes from the source schema.
125pub trait PartitionParser<'a>: Send {
126    /// The type system of the parent [`Source`].
127    type TypeSystem: TypeSystem;
128    /// The error type of the parent [`Source`].
129    type Error: From<ConnectorXError> + Send + Debug;
130
131    /// Read a value `T` by calling `Produce<T>::produce`. Usually this function does not need to be
132    /// implemented.
133    fn parse<'r, T>(&'r mut self) -> Result<T, <Self as PartitionParser<'a>>::Error>
134    where
135        T: TypeAssoc<Self::TypeSystem>,
136        Self: Produce<'r, T, Error = <Self as PartitionParser<'a>>::Error>,
137    {
138        self.produce()
139    }
140
141    /// Fetch next batch of rows from database, return (number of rows fetched to local, whether all rows are fechted from database).
142    /// There might be rows that are not consumed yet when calling the next fetch_next.
143    /// The function might be called even after the last batch is fetched.
144    fn fetch_next(&mut self) -> Result<(usize, bool), Self::Error>;
145}
146
147/// A type implemented `Produce<T>` means that it can produce a value `T` by consuming part of it's raw data buffer.
148pub trait Produce<'r, T> {
149    /// The error returned when the next value cannot be produced as `T`.
150    type Error: From<ConnectorXError> + Send;
151
152    /// Produce the next value from the buffer as `T` and advance past it.
153    fn produce(&'r mut self) -> Result<T, Self::Error>;
154}