Skip to main content

connectorx/
source_router.rs

1use crate::constants::CONNECTORX_PROTOCOL;
2use crate::errors::{ConnectorXError, Result};
3use crate::utils::remove_query_params;
4use anyhow::anyhow;
5use fehler::throws;
6#[cfg(feature = "src_redshift")]
7use redshift_iam::redshift_to_postgres;
8use std::convert::TryFrom;
9use url::Url;
10
11/// Database kind, derived from the connection string scheme.
12#[derive(Debug, Clone)]
13pub enum SourceType {
14    /// `postgres://`, `postgresql://` or `redshift-iam://`.
15    Postgres,
16    /// `sqlite://`.
17    SQLite,
18    /// `mysql://`.
19    MySQL,
20    /// `mssql://` (SQL Server).
21    MsSQL,
22    /// `oracle://`.
23    Oracle,
24    /// `bigquery://`.
25    BigQuery,
26    /// `duckdb://`.
27    DuckDB,
28    /// `trino://`.
29    Trino,
30    /// `clickhouse://`.
31    ClickHouse,
32    /// Any other scheme.
33    Unknown,
34}
35
36/// Parsed connection string.
37#[derive(Debug, Clone)]
38pub struct SourceConn {
39    /// Database kind.
40    pub ty: SourceType,
41    /// Connection URL without the `cxprotocol` parameter.
42    pub conn: Url,
43    /// ConnectorX protocol to use, `binary` by default.
44    pub proto: String,
45}
46
47impl TryFrom<&str> for SourceConn {
48    type Error = ConnectorXError;
49
50    fn try_from(conn: &str) -> Result<SourceConn> {
51        let old_url = Url::parse(conn).map_err(|e| anyhow!("parse error: {}", e))?;
52
53        // parse connectorx protocol
54        let proto = match old_url.query_pairs().find(|p| p.0 == CONNECTORX_PROTOCOL) {
55            Some((_, proto)) => proto.to_string(),
56            None => "binary".to_string(),
57        };
58
59        // create url by removing connectorx protocol
60        let url = remove_query_params(&old_url, &[CONNECTORX_PROTOCOL]);
61
62        // users from sqlalchemy may set engine in connection url (e.g. mssql+pymssql://...)
63        // only for compatablility, we don't use the same engine
64        match url.scheme().split('+').collect::<Vec<&str>>()[0] {
65            "postgres" | "postgresql" => Ok(SourceConn::new(SourceType::Postgres, url, proto)),
66            #[cfg(feature = "src_redshift")]
67            "redshift-iam" => Ok(SourceConn::new(
68                SourceType::Postgres,
69                redshift_to_postgres(url),
70                "cursor".to_string(),
71            )),
72            "sqlite" => Ok(SourceConn::new(SourceType::SQLite, url, proto)),
73            "mysql" => Ok(SourceConn::new(SourceType::MySQL, url, proto)),
74            "mssql" => Ok(SourceConn::new(SourceType::MsSQL, url, proto)),
75            "oracle" => Ok(SourceConn::new(SourceType::Oracle, url, proto)),
76            "bigquery" => Ok(SourceConn::new(SourceType::BigQuery, url, proto)),
77            "duckdb" => Ok(SourceConn::new(SourceType::DuckDB, url, proto)),
78            "trino" => Ok(SourceConn::new(SourceType::Trino, url, proto)),
79            "clickhouse" => Ok(SourceConn::new(SourceType::ClickHouse, url, proto)),
80            _ => Ok(SourceConn::new(SourceType::Unknown, url, proto)),
81        }
82    }
83}
84
85impl SourceConn {
86    /// Create a connection from its parts.
87    pub fn new(ty: SourceType, conn: Url, proto: String) -> Self {
88        Self { ty, conn, proto }
89    }
90    /// Override the protocol.
91    pub fn set_protocol(&mut self, protocol: &str) {
92        self.proto = protocol.to_string();
93    }
94}
95
96/// Parse a connection string, overriding the protocol when `protocol` is given.
97#[throws(ConnectorXError)]
98pub fn parse_source(conn: &str, protocol: Option<&str>) -> SourceConn {
99    let mut source_conn = SourceConn::try_from(conn)?;
100    if let Some(p) = protocol {
101        source_conn.set_protocol(p)
102    }
103    source_conn
104}
105
106#[cfg(test)]
107mod tests {
108    use super::SourceConn;
109    use std::convert::TryFrom;
110
111    /// Removing the connectorx protocol must not re-encode the remaining parameters:
112    /// sources that percent-decode the query would otherwise receive a literal `+`
113    /// wherever the caller wrote a space.
114    #[test]
115    fn keeps_remaining_query_params_verbatim() {
116        let source_conn = SourceConn::try_from(
117            "postgresql://u:p@host:5432/db?options=-c%20statement_timeout%3D1s&cxprotocol=cursor",
118        )
119        .unwrap();
120
121        assert_eq!(
122            source_conn.conn.query(),
123            Some("options=-c%20statement_timeout%3D1s")
124        );
125        assert_eq!(source_conn.proto, "cursor");
126    }
127
128    /// The query is left alone even when there is no protocol parameter to remove.
129    #[test]
130    fn leaves_the_query_alone_when_there_is_nothing_to_remove() {
131        let source_conn = SourceConn::try_from("mysql://host:3306/db?a=x%20y&b=%2Fz").unwrap();
132
133        assert_eq!(source_conn.conn.query(), Some("a=x%20y&b=%2Fz"));
134        assert_eq!(source_conn.proto, "binary");
135    }
136
137    /// Without `src_redshift`, `redshift-iam://` is an unknown scheme: `src_postgres` alone does not build the AWS SDK.
138    #[test]
139    #[cfg(not(feature = "src_redshift"))]
140    fn redshift_iam_needs_its_feature() {
141        let conn = SourceConn::try_from("redshift-iam://u:p@h:5439/db").unwrap();
142        assert_eq!(format!("{:?}", conn.ty), "Unknown");
143    }
144
145    /// The scheme picks the source type; a `+driver` suffix (as SQLAlchemy
146    /// writes it) is ignored, and an unknown scheme is kept as `Unknown`.
147    #[test]
148    fn maps_schemes_to_source_types() {
149        use super::SourceType::*;
150        for (url, ty) in [
151            ("postgres://h/db", Postgres),
152            ("postgresql+psycopg2://h/db", Postgres),
153            ("sqlite:///tmp/x.db", SQLite),
154            ("mysql+pymysql://h/db", MySQL),
155            ("mssql+pymssql://h/db", MsSQL),
156            ("oracle://h/db", Oracle),
157            ("bigquery:///tmp/key.json", BigQuery),
158            ("duckdb:///tmp/x.duckdb", DuckDB),
159            ("trino://h/catalog", Trino),
160            ("clickhouse://h/db", ClickHouse),
161            ("nosuchdb://h/db", Unknown),
162        ] {
163            let conn = SourceConn::try_from(url).unwrap();
164            assert_eq!(format!("{:?}", conn.ty), format!("{ty:?}"), "{url}");
165            assert_eq!(conn.proto, "binary", "{url}");
166        }
167    }
168
169    #[test]
170    fn parse_source_overrides_the_protocol_only_when_given() {
171        let conn = super::parse_source("mysql://h/db?cxprotocol=text", None).unwrap();
172        assert_eq!(conn.proto, "text");
173        let conn = super::parse_source("mysql://h/db?cxprotocol=text", Some("binary")).unwrap();
174        assert_eq!(conn.proto, "binary");
175        assert_eq!(conn.conn.as_str(), "mysql://h/db");
176    }
177
178    #[test]
179    fn rejects_strings_that_are_not_urls() {
180        let err = SourceConn::try_from("not a url").unwrap_err();
181        assert!(err.to_string().contains("parse error"), "{err}");
182        assert!(super::parse_source("", None).is_err());
183    }
184}