Skip to main content

connectorx/
lib.rs

1#![allow(clippy::upper_case_acronyms)]
2#![warn(missing_docs)]
3// The crate docs link to items behind source and destination features. They
4// resolve with `--features all`, which is what CI and docs.rs build, so only
5// check them there.
6#![cfg_attr(not(feature = "all"), allow(rustdoc::broken_intra_doc_links))]
7// The Trino and BigQuery client errors (232 and 176 bytes) are held by value in
8// the source error enums and propagate into `ConnectorXOutError`. Boxing them
9// would change public error types; the error path is cold, so the larger
10// `Result` is not worth an API break.
11#![allow(clippy::result_large_err)]
12
13//! # ConnectorX
14//!
15//! ConnectorX enables you to load data from databases into dataframes in the fastest and most memory efficient way by leveraging
16//! zero-copy and partition-based parallelism.
17//!
18//! Currently, ConnectorX consists of a Rust core library and a python library. This is the documentation for the Rust crate.
19//! For the documentation of the Python library, please refer to our [Github Readme](https://github.com/sfu-db/connector-x).
20//!
21//! # Design
22//!
23//! A data loading problem consists of three sub-problems:
24//! 1. How to connect to the data source and read data.
25//! 2. How to connect to the data destination and write data.
26//! 3. How to map the types between the source and destination.
27//!
28//! Additionally, since ConnectorX will partition a query into partitions and execute them in parallel, we also have
29//! 4. How to partition the query and run them in parallel.
30//!
31//! ConnectorX approaches these problems by defining abstractions on sources, destinations, and mapping rules.
32//! For the partition-based parallelism, ConnectorX will partition the query as well as the source and the destination
33//! together and put them into threads.
34//! Each thread will own exactly 1 query, 1 partitioned source, and 1 partitioned destination.
35//!
36//! The following graph depicts the internal mechanism when ConnectorX is downloading the data.
37//!
38//! ```text
39//!                     +------------------------------------------------------------+
40//!                     |                           Thread 1                         |
41//!                     |                                                            |
42//!     +---+           | +-----------------+   +-------------+  +-----------------+ |          +---+
43//!     |   +-----------+>| Partitioned Src +-->| Type Mapper +->| Partitioned Dst +-+--------->|   |
44//!     |   |           | +-----------------+   +-------------+  +-----------------+ |          |   |
45//!     | D |           |                                                            |          | D |
46//!     | a |           +------------------------------------------------------------+          | a |
47//!     | t |                                          .                                        | t |
48//!     | a |                                          .                                        | a |
49//!     | b |                                          .                                        | f |
50//!     | a |           +------------------------------------------------------------+          | r |
51//!     | s |           |                           Thread n                         |          | a |
52//!     | e |           |                                                            |          | m |
53//!     |   |           | +-----------------+   +-------------+  +-----------------+ |          | e |
54//!     |   +-----------+>| Partitioned Src +-->| Type Mapper +->| Partitioned Dst +-+--------->|   |
55//!     +---+           | +-----------------+   +-------------+  +-----------------+ |          +---+
56//!                     |                                                            |
57//!                     +------------------------------------------------------------+
58//!
59//! ```
60//! ## How does ConnectorX download the data?
61//!
62//! Upon receiving the query, e.g. SELECT * FROM lineitem, ConnectorX will first issue a LIMIT 0 query SELECT * FROM lineitem LIMIT 0 to get the schema of the result set.
63//!
64//! Then, if partition_on is specified, ConnectorX will issue `SELECT MIN($partition_on), MAX($partition_on) FROM (SELECT * FROM lineitem)` to know the range of the partition column.
65//! After that, the original query is split into partitions based on the min/max information, e.g. `SELECT * FROM (SELECT * FROM lineitem) WHERE $partition_on > 0 AND $partition_on < 10000`.
66//! ConnectorX will then run a count query to get the partition size (e.g. `SELECT COUNT(*) FROM (SELECT * FROM lineitem) WHERE $partition_on > 0 AND $partition_on < 10000`).
67//! If the partition is not specified, the count query will be `SELECT COUNT(*) FROM (SELECT * FROM lineitem)`.
68//!
69//! Finally, ConnectorX will use the schema info as well as the count info to allocate memory and download data by executing the queries normally.
70//! Once the downloading begins, there will be one thread for each partition so that the data are downloaded in parallel at the partition level.
71//! The thread will issue the query of the corresponding partition to the database and then write the returned data to the destination row-wise or column-wise (depends on the database) in a streaming fashion.
72//! This mechanism implies that having an index on the partition column is recommended to make full use of the parallel downloading power provided by ConnectorX.
73//!
74//! # Extending ConnectorX
75//! ## Adding a new source
76//!
77//! To add a new data source, you need to implement [`sources::Source`], [`sources::SourcePartition`], [`sources::PartitionParser`], and [`sources::Produce`] for the source.
78//! In detail, [`sources::Source`] describes how to connect to the database from a connection string, as well as how to do partitioning on the source to produce a list of [`sources::SourcePartition`].
79//! [`sources::SourcePartition`] describes how to get the row count for the specific partition so that the destination can preallocate the memory.
80//! Finally, [`sources::PartitionParser`] and [`sources::Produce`] abstracts away the detail about how does each partition parse different types.
81//!
82//! ## Adding a new destination
83//!
84//! To add a new data destination, you need to implement [`destinations::Destination`], [`destinations::DestinationPartition`], and [`destinations::Consume`]. Similar to the sources,
85//! [`destinations::Destination`] describes how to allocate the memory of the data destination, as well as how to do partitioning on the destination to produce a list of [`destinations::DestinationPartition`].
86//! [`destinations::DestinationPartition`] and [`destinations::Consume`] abstract away the detail about how does each partition writes different types.
87//!
88//! ## Adding a new transport (type mapping)
89//!
90//! After having a source and a destination that describes how to read and write the data,
91//! ConnectorX also needs to know how to convert the values with different types from the source to the destination.
92//! For example, Postgres can produce a `uuid` type but there's no uuid in Arrow. It is the transport's duty to convert
93//! the `uuid` into an Arrow compatible type, e.g. string. You can use the [`impl_transport!`] macro to define a transport.
94//!
95//! ## Putting things together
96//!
97//! Say, you decide to load data from SQL Server to Arrow. In ConnectorX we already provided the source for SQL Server as [`sources::sqlite::SQLiteSource`], and the
98//! Arrow destination [`destinations::arrow::ArrowDestination`], as well as the transport [`transports::SQLiteArrowTransport`].
99//! Given the source, destination and transport already implemented, you can use [`dispatcher::Dispatcher`] to load the data:
100//!
101//! ```no_run
102//! use connectorx::prelude::*;
103//!
104//! let mut destination = ArrowDestination::new();
105//! let source = SQLiteSource::new("/path/to/db", 10).expect("cannot create the source");
106//! let queries = &["SELECT * FROM db WHERE id < 100", "SELECT * FROM db WHERE id >= 100"];
107//! let dispatcher = Dispatcher::<SQLiteSource, ArrowDestination, SQLiteArrowTransport>::new(source, &mut destination, queries, None);
108//! dispatcher.run().expect("run failed");
109//!
110//! let data = destination.arrow();
111//! ```
112//!
113//! Or simply you can directly use the [`get_arrow::get_arrow`] in which we wrapped the above procedures:
114//!
115//! ```no_run
116//! use connectorx::prelude::*;
117//! use std::convert::TryFrom;
118//!
119//! let mut source_conn = SourceConn::try_from("postgresql://username:password@host:port/db?cxprotocol=binary").expect("parse conn str failed");
120//! let queries = &[CXQuery::from("SELECT * FROM table WHERE id < 100"), CXQuery::from("SELECT * FROM table WHERE id >= 100")];
121//! let destination = get_arrow(&source_conn, None, queries, None).expect("run failed");
122//!
123//! let data = destination.arrow();
124//! ```
125//!
126//! NOTE: the pool size parameter `nconn` used in initializing the source should be larger than or equal to the number of partitioned queries input later.
127//!
128//! ## Need more examples?
129//! You can use the existing implementation as the example.
130//! [MySQL source](https://github.com/sfu-db/connector-x/tree/main/connectorx/src/sources/mysql),
131//! [Arrow destination](https://github.com/sfu-db/connector-x/tree/main/connectorx/src/destinations/arrow),
132//! [MySQL to Arrow transport](https://github.com/sfu-db/connector-x/blob/main/connectorx/src/transports/mysql_arrow.rs).
133//!
134//! # Sources protocols & Destinations that is implemented in the Rust core.
135//!
136//! ## Sources
137//! - [x] Postgres
138//! - [x] Mysql
139//! - [x] Sqlite
140//! - [x] SQL Server
141//! - [x] Oracle
142//! - [x] BigQuery
143//!
144//! ## Destinations
145//! - [x] Arrow
146//! - [x] Polars
147//!
148//! # Feature gates
149//! By default, ConnectorX does not enable any sources / destinations to keep the dependencies minimal.
150//! Instead, we provide following features for you to opt-in: `src_sqlite`, `src_postgres`, `src_mysql`, `src_mssql`, `src_oracle`, `dst_arrow`, `dst_polars`.
151//! For example, if you'd like to load data from Postgres to Arrow, you can enable `src_postgres` and `dst_arrow` in `Cargo.toml`.
152//! This will enable [`sources::postgres`], [`destinations::arrow`] and [`transports::PostgresArrowTransport`].
153
154pub mod typesystem;
155#[macro_use]
156mod macros;
157/// Streaming iterator over Arrow record batches.
158#[cfg(feature = "dst_arrow")]
159pub mod arrow_batch_iter;
160/// Crate-wide constants and defaults.
161pub mod constants;
162pub mod data_order;
163pub mod destinations;
164mod dispatcher;
165/// Error types.
166pub mod errors;
167/// Execution of federated queries across several databases.
168#[cfg(feature = "fed_exec")]
169pub mod fed_dispatcher;
170/// Rewriting of federated queries into per-database plans.
171#[cfg(feature = "federation")]
172pub mod fed_rewriter;
173/// Load query results into Arrow in one call.
174#[cfg(feature = "dst_arrow")]
175pub mod get_arrow;
176/// Splitting a query into range partitions on a numeric column.
177pub mod partition;
178/// Parsing of connection strings into a source type and URL.
179pub mod source_router;
180pub mod sources;
181#[doc(hidden)]
182pub mod sql;
183pub mod transports;
184#[doc(hidden)]
185pub mod utils;
186
187/// Common imports for using ConnectorX.
188pub mod prelude {
189    #[cfg(feature = "dst_arrow")]
190    pub use crate::arrow_batch_iter::{set_global_num_thread, RecordBatchIterator};
191    pub use crate::data_order::{coordinate, DataOrder};
192    #[cfg(feature = "dst_arrow")]
193    pub use crate::destinations::arrow::{ArrowDestination, ArrowPartitionWriter, ArrowTypeSystem};
194    #[cfg(feature = "dst_arrow")]
195    pub use crate::destinations::arrowstream::{
196        ArrowDestination as ArrowStreamDestination,
197        ArrowPartitionWriter as ArrowStreamPartitionWriter,
198        ArrowTypeSystem as ArrowStreamTypeSystem,
199    };
200    pub use crate::destinations::{Consume, Destination, DestinationPartition};
201    pub use crate::dispatcher::Dispatcher;
202    pub use crate::errors::{ConnectorXError, ConnectorXOutError};
203    #[cfg(feature = "federation")]
204    pub use crate::fed_rewriter::{rewrite_sql, FederatedDataSourceInfo, Plan};
205    #[cfg(feature = "dst_arrow")]
206    pub use crate::get_arrow::{get_arrow, new_record_batch_iter};
207    pub use crate::source_router::*;
208    #[cfg(feature = "src_bigquery")]
209    pub use crate::sources::bigquery::BigQuerySource;
210    #[cfg(feature = "src_clickhouse")]
211    pub use crate::sources::clickhouse::ClickHouseSource;
212    #[cfg(feature = "src_csv")]
213    pub use crate::sources::csv::CSVSource;
214    #[cfg(feature = "src_dummy")]
215    pub use crate::sources::dummy::DummySource;
216    #[cfg(feature = "src_mssql_common")]
217    pub use crate::sources::mssql::MsSQLSource;
218    #[cfg(feature = "src_mysql")]
219    pub use crate::sources::mysql::MySQLSource;
220    #[cfg(feature = "src_oracle")]
221    pub use crate::sources::oracle::OracleSource;
222    #[cfg(feature = "src_postgres")]
223    pub use crate::sources::postgres::PostgresSource;
224    #[cfg(feature = "src_sqlite")]
225    pub use crate::sources::sqlite::SQLiteSource;
226    #[cfg(feature = "src_trino")]
227    pub use crate::sources::trino::TrinoSource;
228    pub use crate::sources::{PartitionParser, Produce, Source, SourcePartition};
229    pub use crate::sql::CXQuery;
230    // Every transport needs a source feature and `dst_arrow`, so with only one
231    // of the two enabled there is nothing to re-export.
232    #[allow(unused_imports)]
233    pub use crate::transports::*;
234    pub use crate::typesystem::{
235        ParameterizedFunc, ParameterizedOn, Realize, Transport, TypeAssoc, TypeConversion,
236        TypeSystem,
237    };
238}