Skip to main content

connectorx/sources/oracle/
mod.rs

1mod errors;
2mod typesystem;
3
4use std::collections::HashMap;
5
6pub use self::errors::OracleSourceError;
7pub use self::typesystem::OracleTypeSystem;
8use crate::constants::{DB_BUFFER_SIZE, ORACLE_ARRAY_SIZE};
9use crate::utils::OwningHandle;
10use crate::{
11    data_order::DataOrder,
12    errors::ConnectorXError,
13    sources::{PartitionParser, Produce, Source, SourcePartition},
14    sql::{count_query, limit0_query_oracle, CXQuery},
15    utils::DummyBox,
16};
17use chrono::{DateTime, FixedOffset, NaiveDate, NaiveDateTime, Utc};
18use fehler::{throw, throws};
19use log::debug;
20use r2d2::{Pool, PooledConnection};
21use r2d2_oracle::oracle::ResultSet;
22use r2d2_oracle::{
23    oracle::{Connector, Row, Statement, Version},
24    OracleConnectionManager,
25};
26use rust_decimal::Decimal;
27use sqlparser::dialect::Dialect;
28use url::Url;
29use urlencoding::decode;
30
31type OracleManager = OracleConnectionManager;
32type OracleConn = PooledConnection<OracleManager>;
33
34/// SQL dialect for Oracle.
35#[derive(Debug)]
36pub struct OracleDialect {}
37
38// implementation copy from AnsiDialect
39impl Dialect for OracleDialect {
40    fn is_identifier_start(&self, ch: char) -> bool {
41        ch.is_ascii_lowercase() || ch.is_ascii_uppercase()
42    }
43
44    fn is_identifier_part(&self, ch: char) -> bool {
45        ch.is_ascii_lowercase() || ch.is_ascii_uppercase() || ch.is_ascii_digit() || ch == '_'
46    }
47}
48
49/// Source that reads from Oracle.
50pub struct OracleSource {
51    pool: Pool<OracleManager>,
52    origin_query: Option<String>,
53    queries: Vec<CXQuery<String>>,
54    names: Vec<String>,
55    schema: Vec<OracleTypeSystem>,
56    current_schema: Option<String>,
57}
58
59/// Build an Oracle connector from an `oracle://` URL. Uses external authentication when no user and password are given.
60#[throws(OracleSourceError)]
61pub fn connect_oracle(conn: &Url) -> Connector {
62    let user = decode(conn.username())?.into_owned();
63    let password = decode(conn.password().unwrap_or(""))?.into_owned();
64    let host = decode(conn.host_str().unwrap_or("localhost"))?.into_owned();
65
66    let params: HashMap<String, String> = conn.query_pairs().into_owned().collect();
67
68    let conn_str = if params.get("alias").is_some_and(|v| v == "true") {
69        host.clone()
70    } else {
71        let port = conn.port().unwrap_or(1521);
72        let path = decode(conn.path())?.into_owned();
73        format!("//{}:{}{}", host, port, path)
74    };
75
76    let mut connector = oracle::Connector::new(user.as_str(), password.as_str(), conn_str.as_str());
77    if user.is_empty() && password.is_empty() {
78        debug!("No username or password provided, assuming system auth.");
79        connector.external_auth(true);
80    }
81    connector
82}
83
84impl OracleSource {
85    /// Create a source with a pool of up to `nconn` connections.
86    #[throws(OracleSourceError)]
87    pub fn new(conn: &str, nconn: usize) -> Self {
88        let conn = Url::parse(conn)?;
89        let connector = connect_oracle(&conn)?;
90        let manager = OracleConnectionManager::from_connector(connector);
91        let pool = r2d2::Pool::builder()
92            .max_size(nconn as u32)
93            .build(manager)?;
94
95        let params: HashMap<String, String> = conn.query_pairs().into_owned().collect();
96        let current_schema = params.get("schema").cloned();
97
98        Self {
99            pool,
100            origin_query: None,
101            queries: vec![],
102            names: vec![],
103            schema: vec![],
104            current_schema,
105        }
106    }
107    /// Get a pooled connection, switched to the `schema` from the connection string if one was given.
108    pub fn get_conn(&self) -> Result<OracleConn, OracleSourceError> {
109        let conn = self.pool.get()?;
110        if let Some(schema) = &self.current_schema {
111            conn.set_current_schema(schema)?;
112        }
113        Ok(conn)
114    }
115}
116
117/// Oldest Instant Client known to read native `BOOLEAN` columns correctly. On the first execution
118/// of a statement on a connection, Instant Client 23.4 can return `TRUE` for a `FALSE` value that
119/// directly follows another `FALSE`, without raising an error. Clients older than 23 report
120/// `BOOLEAN` columns as `NUMBER`, so they never reach this check.
121const MIN_BOOLEAN_CLIENT_VERSION: Version = Version::new(23, 5, 0, 0, 0);
122
123fn client_reads_boolean_correctly(client: &Version) -> bool {
124    *client >= MIN_BOOLEAN_CLIENT_VERSION
125}
126
127/// Refuses to read a native `BOOLEAN` column through an Instant Client that may return wrong
128/// values for it.
129#[throws(OracleSourceError)]
130fn check_boolean_client(names: &[String], schema: &[OracleTypeSystem]) {
131    if let Some(i) = schema
132        .iter()
133        .position(|ty| matches!(ty, OracleTypeSystem::Boolean(_)))
134    {
135        let client = Version::client()?;
136        if !client_reads_boolean_correctly(&client) {
137            throw!(OracleSourceError::UnreliableBooleanClient {
138                column: names[i].clone(),
139                client: client.to_string(),
140            });
141        }
142    }
143}
144
145impl Source for OracleSource
146where
147    OracleSourcePartition:
148        SourcePartition<TypeSystem = OracleTypeSystem, Error = OracleSourceError>,
149{
150    const DATA_ORDERS: &'static [DataOrder] = &[DataOrder::RowMajor];
151    type Partition = OracleSourcePartition;
152    type TypeSystem = OracleTypeSystem;
153    type Error = OracleSourceError;
154
155    #[throws(OracleSourceError)]
156    fn set_data_order(&mut self, data_order: DataOrder) {
157        if !matches!(data_order, DataOrder::RowMajor) {
158            throw!(ConnectorXError::UnsupportedDataOrder(data_order));
159        }
160    }
161
162    fn set_queries<Q: ToString>(&mut self, queries: &[CXQuery<Q>]) {
163        self.queries = queries.iter().map(|q| q.map(Q::to_string)).collect();
164    }
165
166    fn set_origin_query(&mut self, query: Option<String>) {
167        self.origin_query = query;
168    }
169
170    #[throws(OracleSourceError)]
171    fn fetch_metadata(&mut self) {
172        assert!(!self.queries.is_empty());
173
174        let conn = self.get_conn()?;
175        for (i, query) in self.queries.iter().enumerate() {
176            // assuming all the partition queries yield same schema
177            // without rownum = 1, derived type might be wrong
178            // example: select avg(test_int), test_char from test_table group by test_char
179            // -> (NumInt, Char) instead of (NumtFloat, Char)
180            match conn.query(limit0_query_oracle(query)?.as_str(), &[]) {
181                Ok(rows) => {
182                    let (names, types): (Vec<String>, Vec<OracleTypeSystem>) = rows
183                        .column_info()
184                        .iter()
185                        .map(|col| {
186                            (
187                                col.name().to_string(),
188                                OracleTypeSystem::from(col.oracle_type()),
189                            )
190                        })
191                        .unzip();
192                    check_boolean_client(&names, &types)?;
193                    self.names = names;
194                    self.schema = types;
195                    return;
196                }
197                Err(e) if i == self.queries.len() - 1 => {
198                    // tried the last query but still get an error
199                    debug!("cannot get metadata for '{}': {}", query, e);
200                    throw!(e);
201                }
202                Err(_) => {}
203            }
204        }
205        // tried all queries but all get empty result set
206        let iter = conn.query(self.queries[0].as_str(), &[])?;
207        let (names, types) = iter
208            .column_info()
209            .iter()
210            .map(|col| (col.name().to_string(), OracleTypeSystem::VarChar(false)))
211            .unzip();
212        self.names = names;
213        self.schema = types;
214    }
215
216    #[throws(OracleSourceError)]
217    fn result_rows(&mut self) -> Option<usize> {
218        match &self.origin_query {
219            Some(q) => {
220                let cxq = CXQuery::Naked(q.clone());
221                let conn = self.get_conn()?;
222
223                let nrows = conn
224                    .query_row_as::<usize>(count_query(&cxq, &OracleDialect {})?.as_str(), &[])?;
225                Some(nrows)
226            }
227            None => None,
228        }
229    }
230
231    fn names(&self) -> Vec<String> {
232        self.names.clone()
233    }
234
235    fn schema(&self) -> Vec<Self::TypeSystem> {
236        self.schema.clone()
237    }
238
239    #[throws(OracleSourceError)]
240    fn partition(self) -> Vec<Self::Partition> {
241        let mut ret = vec![];
242        for query in &self.queries {
243            let conn = self.get_conn()?;
244            ret.push(OracleSourcePartition::new(conn, query, &self.schema));
245        }
246        ret
247    }
248}
249
250/// One partition of an [`OracleSource`].
251pub struct OracleSourcePartition {
252    conn: OracleConn,
253    query: CXQuery<String>,
254    schema: Vec<OracleTypeSystem>,
255    nrows: usize,
256    ncols: usize,
257}
258
259impl OracleSourcePartition {
260    /// Create a partition that runs `query` on `conn`.
261    pub fn new(conn: OracleConn, query: &CXQuery<String>, schema: &[OracleTypeSystem]) -> Self {
262        Self {
263            conn,
264            query: query.clone(),
265            schema: schema.to_vec(),
266            nrows: 0,
267            ncols: schema.len(),
268        }
269    }
270}
271
272impl SourcePartition for OracleSourcePartition {
273    type TypeSystem = OracleTypeSystem;
274    type Parser<'a> = OracleTextSourceParser<'a>;
275    type Error = OracleSourceError;
276
277    #[throws(OracleSourceError)]
278    fn result_rows(&mut self) {
279        self.nrows = self
280            .conn
281            .query_row_as::<usize>(count_query(&self.query, &OracleDialect {})?.as_str(), &[])?;
282    }
283
284    #[throws(OracleSourceError)]
285    fn parser(&mut self) -> Self::Parser<'_> {
286        let query = self.query.clone();
287
288        // let iter = self.conn.query(query.as_str(), &[])?;
289        OracleTextSourceParser::new(&self.conn, query.as_str(), &self.schema)?
290    }
291
292    fn nrows(&self) -> usize {
293        self.nrows
294    }
295
296    fn ncols(&self) -> usize {
297        self.ncols
298    }
299}
300
301unsafe impl<'a> Send for OracleTextSourceParser<'a> {}
302
303/// Row parser for an Oracle partition.
304pub struct OracleTextSourceParser<'a> {
305    rows: OwningHandle<Statement, DummyBox<ResultSet<'a, Row>>>,
306    rowbuf: Vec<Row>,
307    ncols: usize,
308    current_col: usize,
309    current_row: usize,
310    is_finished: bool,
311}
312
313impl<'a> OracleTextSourceParser<'a> {
314    /// Run `query` on `conn` and prepare to parse its rows.
315    #[throws(OracleSourceError)]
316    pub fn new(conn: &'a OracleConn, query: &str, schema: &[OracleTypeSystem]) -> Self {
317        let stmt = conn
318            .statement(query)
319            .prefetch_rows(ORACLE_ARRAY_SIZE)
320            .fetch_array_size(ORACLE_ARRAY_SIZE)
321            .build()?;
322        let rows: OwningHandle<Statement, DummyBox<ResultSet<'a, Row>>> =
323            OwningHandle::new_with_fn(Box::new(stmt), |stmt: *const Statement| unsafe {
324                DummyBox((*(stmt as *mut Statement)).query(&[]).unwrap())
325            });
326
327        Self {
328            rows,
329            rowbuf: Vec::with_capacity(DB_BUFFER_SIZE),
330            ncols: schema.len(),
331            current_row: 0,
332            current_col: 0,
333            is_finished: false,
334        }
335    }
336
337    #[throws(OracleSourceError)]
338    fn next_loc(&mut self) -> (usize, usize) {
339        let ret = (self.current_row, self.current_col);
340        self.current_row += (self.current_col + 1) / self.ncols;
341        self.current_col = (self.current_col + 1) % self.ncols;
342        ret
343    }
344}
345
346impl<'a> PartitionParser<'a> for OracleTextSourceParser<'a> {
347    type TypeSystem = OracleTypeSystem;
348    type Error = OracleSourceError;
349
350    #[throws(OracleSourceError)]
351    fn fetch_next(&mut self) -> (usize, bool) {
352        assert!(self.current_col == 0);
353        let remaining_rows = self.rowbuf.len() - self.current_row;
354        if remaining_rows > 0 {
355            return (remaining_rows, self.is_finished);
356        } else if self.is_finished {
357            return (0, self.is_finished);
358        }
359
360        if !self.rowbuf.is_empty() {
361            self.rowbuf.drain(..);
362        }
363        for _ in 0..DB_BUFFER_SIZE {
364            if let Some(item) = (*self.rows).next() {
365                self.rowbuf.push(item?);
366            } else {
367                self.is_finished = true;
368                break;
369            }
370        }
371        self.current_row = 0;
372        self.current_col = 0;
373        (self.rowbuf.len(), self.is_finished)
374    }
375}
376
377macro_rules! impl_produce_text {
378    ($($t: ty,)+) => {
379        $(
380            impl<'r, 'a> Produce<'r, $t> for OracleTextSourceParser<'a> {
381                type Error = OracleSourceError;
382
383                #[throws(OracleSourceError)]
384                fn produce(&'r mut self) -> $t {
385                    let (ridx, cidx) = self.next_loc()?;
386                    let res = self.rowbuf[ridx].get(cidx)?;
387                    res
388                }
389            }
390
391            impl<'r, 'a> Produce<'r, Option<$t>> for OracleTextSourceParser<'a> {
392                type Error = OracleSourceError;
393
394                #[throws(OracleSourceError)]
395                fn produce(&'r mut self) -> Option<$t> {
396                    let (ridx, cidx) = self.next_loc()?;
397                    let res = self.rowbuf[ridx].get(cidx)?;
398                    res
399                }
400            }
401        )+
402    };
403}
404
405impl_produce_text!(i64, bool, f64, String, NaiveDate, NaiveDateTime, Vec<u8>,);
406
407// `TIMESTAMP WITH TIME ZONE`: rust-oracle's `FromSql for DateTime<Utc>` reads the wall-clock time as if it were UTC
408// and drops the offset (`11:00:00 -08:00` would become `11:00:00 UTC`). Read it with its offset, then convert.
409fn timestamp_tz_to_utc(value: DateTime<FixedOffset>) -> DateTime<Utc> {
410    value.with_timezone(&Utc)
411}
412
413impl<'r, 'a> Produce<'r, DateTime<Utc>> for OracleTextSourceParser<'a> {
414    type Error = OracleSourceError;
415
416    #[throws(OracleSourceError)]
417    fn produce(&'r mut self) -> DateTime<Utc> {
418        let (ridx, cidx) = self.next_loc()?;
419        let value: DateTime<FixedOffset> = self.rowbuf[ridx].get(cidx)?;
420        timestamp_tz_to_utc(value)
421    }
422}
423
424impl<'r, 'a> Produce<'r, Option<DateTime<Utc>>> for OracleTextSourceParser<'a> {
425    type Error = OracleSourceError;
426
427    #[throws(OracleSourceError)]
428    fn produce(&'r mut self) -> Option<DateTime<Utc>> {
429        let (ridx, cidx) = self.next_loc()?;
430        let value: Option<DateTime<FixedOffset>> = self.rowbuf[ridx].get(cidx)?;
431        value.map(timestamp_tz_to_utc)
432    }
433}
434
435// Manual implementation for Decimal since Oracle doesn't support it directly via FromSql
436impl<'r, 'a> Produce<'r, Decimal> for OracleTextSourceParser<'a> {
437    type Error = OracleSourceError;
438
439    #[throws(OracleSourceError)]
440    fn produce(&'r mut self) -> Decimal {
441        let (ridx, cidx) = self.next_loc()?;
442        let s: String = self.rowbuf[ridx].get(cidx)?;
443        let res = s.parse::<Decimal>()?;
444        res
445    }
446}
447
448impl<'r, 'a> Produce<'r, Option<Decimal>> for OracleTextSourceParser<'a> {
449    type Error = OracleSourceError;
450
451    #[throws(OracleSourceError)]
452    fn produce(&'r mut self) -> Option<Decimal> {
453        let (ridx, cidx) = self.next_loc()?;
454        let s: Option<String> = self.rowbuf[ridx].get(cidx)?;
455        match s {
456            Some(val) => Some(val.parse::<Decimal>()?),
457            None => None,
458        }
459    }
460}
461
462#[cfg(test)]
463mod tests {
464    use super::*;
465
466    #[test]
467    fn timestamp_with_time_zone_keeps_the_instant() {
468        let west = FixedOffset::west_opt(8 * 3600).unwrap();
469        let value = chrono::TimeZone::with_ymd_and_hms(&west, 1999, 12, 1, 11, 0, 0).unwrap();
470        assert_eq!(
471            timestamp_tz_to_utc(value).to_rfc3339(),
472            "1999-12-01T19:00:00+00:00"
473        );
474    }
475
476    #[test]
477    fn boolean_client_threshold() {
478        // versions as reported by `Version::client()` for the Instant Client zips
479        assert!(!client_reads_boolean_correctly(&Version::new(
480            23, 4, 0, 24, 5
481        )));
482        assert!(client_reads_boolean_correctly(&Version::new(
483            23, 5, 0, 24, 7
484        )));
485        assert!(client_reads_boolean_correctly(&Version::new(
486            23, 26, 3, 0, 0
487        )));
488    }
489
490    #[test]
491    fn check_boolean_client_skips_queries_without_boolean() {
492        // no Boolean column -> the client version is never looked up
493        let names = vec!["A".to_string()];
494        let schema = vec![OracleTypeSystem::NumInt(true)];
495        assert!(check_boolean_client(&names, &schema).is_ok());
496    }
497}