Skip to main content

connectorx/sources/mysql/
mod.rs

1//! Source implementation for MySQL database.
2
3mod connection;
4mod errors;
5mod typesystem;
6
7pub use self::connection::build_opts;
8pub use self::errors::MySQLSourceError;
9use crate::constants::DB_BUFFER_SIZE;
10use crate::{
11    data_order::DataOrder,
12    errors::ConnectorXError,
13    sources::{PartitionParser, Produce, Source, SourcePartition},
14    sql::{count_query, limit0_query, CXQuery},
15};
16use anyhow::anyhow;
17use chrono::{NaiveDate, NaiveDateTime, NaiveTime};
18use fehler::{throw, throws};
19use log::{debug, warn};
20use r2d2::{Pool, PooledConnection};
21use r2d2_mysql::{
22    mysql::{
23        prelude::{FromValue, Queryable},
24        Binary, Column, QueryResult, Row, Text,
25    },
26    MySqlConnectionManager,
27};
28use rust_decimal::Decimal;
29use serde_json::Value;
30use sqlparser::dialect::MySqlDialect;
31use std::marker::PhantomData;
32pub use typesystem::MySQLTypeSystem;
33
34type MysqlConn = PooledConnection<MySqlConnectionManager>;
35
36/// Marker type: fetch with the MySQL binary (prepared statement) protocol.
37pub enum BinaryProtocol {}
38/// Marker type: fetch with the MySQL text protocol.
39pub enum TextProtocol {}
40
41#[throws(MySQLSourceError)]
42fn get_total_rows(conn: &mut MysqlConn, query: &CXQuery<String>) -> usize {
43    conn.query_first(&count_query(query, &MySqlDialect {})?)?
44        .ok_or_else(|| anyhow!("mysql failed to get the count of query: {}", query))?
45}
46
47/// Takes a connection from the pool and runs the pre-execution queries on it.
48#[throws(MySQLSourceError)]
49fn pooled_conn(
50    pool: &Pool<MySqlConnectionManager>,
51    pre_execution_queries: &Option<Vec<String>>,
52) -> MysqlConn {
53    let mut conn = pool.get()?;
54    if let Some(pre_queries) = pre_execution_queries {
55        for pre_query in pre_queries {
56            conn.query_drop(pre_query)?;
57        }
58    }
59    conn
60}
61
62/// Source that reads from MySQL. `P` selects the protocol.
63pub struct MySQLSource<P> {
64    pool: Pool<MySqlConnectionManager>,
65    origin_query: Option<String>,
66    queries: Vec<CXQuery<String>>,
67    names: Vec<String>,
68    schema: Vec<MySQLTypeSystem>,
69    pre_execution_queries: Option<Vec<String>>,
70    _protocol: PhantomData<P>,
71}
72
73fn column_metadata(columns: &[Column]) -> (Vec<String>, Vec<MySQLTypeSystem>) {
74    columns
75        .iter()
76        .map(|col| {
77            (
78                col.name_str().to_string(),
79                MySQLTypeSystem::from((&col.column_type(), &col.flags(), col.character_set())),
80            )
81        })
82        .unzip()
83}
84
85/// Derive the schema by running each query with `LIMIT 0`. MySQL sends the
86/// column definitions even when the result set is empty, so no row is read.
87fn limit0_metadata(
88    conn: &mut MysqlConn,
89    queries: &[CXQuery<String>],
90) -> Result<(Vec<String>, Vec<MySQLTypeSystem>), MySQLSourceError> {
91    for (i, query) in queries.iter().enumerate() {
92        // assuming all the partition queries yield same schema
93        match conn.query_iter(limit0_query(query, &MySqlDialect {})?.as_str()) {
94            Ok(iter) => {
95                let (names, types) = column_metadata(iter.columns().as_ref());
96                if !names.is_empty() {
97                    return Ok((names, types));
98                }
99                debug!("no result columns for '{}', try next query", query);
100            }
101            Err(e) if i == queries.len() - 1 => {
102                // tried the last query but still get an error
103                debug!("cannot get metadata for '{}': {}", query, e);
104                return Err(e.into());
105            }
106            Err(e) => {
107                debug!("cannot get metadata for '{}', try next query: {}", query, e);
108            }
109        }
110    }
111    Err(anyhow!("cannot get metadata: no query returned a result set with columns").into())
112}
113
114impl<P> MySQLSource<P> {
115    /// Create a source with a pool of up to `nconn` connections.
116    #[throws(MySQLSourceError)]
117    pub fn new(conn: &str, nconn: usize) -> Self {
118        let manager = MySqlConnectionManager::new(build_opts(conn)?);
119        let pool = r2d2::Pool::builder()
120            .max_size(nconn as u32)
121            .build(manager)?;
122
123        Self {
124            pool,
125            origin_query: None,
126            queries: vec![],
127            names: vec![],
128            schema: vec![],
129            pre_execution_queries: None,
130            _protocol: PhantomData,
131        }
132    }
133}
134
135impl<P> Source for MySQLSource<P>
136where
137    MySQLSourcePartition<P>:
138        SourcePartition<TypeSystem = MySQLTypeSystem, Error = MySQLSourceError>,
139    P: Send,
140{
141    const DATA_ORDERS: &'static [DataOrder] = &[DataOrder::RowMajor];
142    type Partition = MySQLSourcePartition<P>;
143    type TypeSystem = MySQLTypeSystem;
144    type Error = MySQLSourceError;
145
146    #[throws(MySQLSourceError)]
147    fn set_data_order(&mut self, data_order: DataOrder) {
148        if !matches!(data_order, DataOrder::RowMajor) {
149            throw!(ConnectorXError::UnsupportedDataOrder(data_order));
150        }
151    }
152
153    fn set_queries<Q: ToString>(&mut self, queries: &[CXQuery<Q>]) {
154        self.queries = queries.iter().map(|q| q.map(Q::to_string)).collect();
155    }
156
157    fn set_origin_query(&mut self, query: Option<String>) {
158        self.origin_query = query;
159    }
160
161    fn set_pre_execution_queries(&mut self, pre_execution_queries: Option<&[String]>) {
162        self.pre_execution_queries = pre_execution_queries.map(|s| s.to_vec());
163    }
164
165    #[throws(MySQLSourceError)]
166    fn fetch_metadata(&mut self) {
167        assert!(!self.queries.is_empty());
168
169        let mut conn = pooled_conn(&self.pool, &self.pre_execution_queries)?;
170        let first_query = &self.queries[0];
171
172        let (names, types) = match conn.prep(first_query) {
173            Ok(stmt) => column_metadata(stmt.columns()),
174            Err(e) => {
175                warn!(
176                    "mysql prepared statement error: {:?}, switch to limit 0 method",
177                    e
178                );
179                limit0_metadata(&mut conn, &self.queries)?
180            }
181        };
182        self.names = names;
183        self.schema = types;
184    }
185
186    #[throws(MySQLSourceError)]
187    fn result_rows(&mut self) -> Option<usize> {
188        match &self.origin_query {
189            Some(q) => {
190                let cxq = CXQuery::Naked(q.clone());
191                let mut conn = pooled_conn(&self.pool, &self.pre_execution_queries)?;
192                let nrows = get_total_rows(&mut conn, &cxq)?;
193                Some(nrows)
194            }
195            None => None,
196        }
197    }
198
199    fn names(&self) -> Vec<String> {
200        self.names.clone()
201    }
202
203    fn schema(&self) -> Vec<Self::TypeSystem> {
204        self.schema.clone()
205    }
206
207    #[throws(MySQLSourceError)]
208    fn partition(self) -> Vec<Self::Partition> {
209        let mut ret = vec![];
210        for query in self.queries {
211            let conn = pooled_conn(&self.pool, &self.pre_execution_queries)?;
212
213            ret.push(MySQLSourcePartition::new(conn, &query, &self.schema));
214        }
215        ret
216    }
217}
218
219/// One partition of a [`MySQLSource`].
220pub struct MySQLSourcePartition<P> {
221    conn: MysqlConn,
222    query: CXQuery<String>,
223    schema: Vec<MySQLTypeSystem>,
224    nrows: usize,
225    ncols: usize,
226    _protocol: PhantomData<P>,
227}
228
229impl<P> MySQLSourcePartition<P> {
230    /// Create a partition that runs `query` on `conn`.
231    pub fn new(conn: MysqlConn, query: &CXQuery<String>, schema: &[MySQLTypeSystem]) -> Self {
232        Self {
233            conn,
234            query: query.clone(),
235            schema: schema.to_vec(),
236            nrows: 0,
237            ncols: schema.len(),
238            _protocol: PhantomData,
239        }
240    }
241}
242
243impl SourcePartition for MySQLSourcePartition<BinaryProtocol> {
244    type TypeSystem = MySQLTypeSystem;
245    type Parser<'a> = MySQLBinarySourceParser<'a>;
246    type Error = MySQLSourceError;
247
248    #[throws(MySQLSourceError)]
249    fn result_rows(&mut self) {
250        self.nrows = get_total_rows(&mut self.conn, &self.query)?;
251    }
252
253    #[throws(MySQLSourceError)]
254    fn parser(&mut self) -> Self::Parser<'_> {
255        let stmt = self.conn.prep(self.query.as_str())?;
256        let iter = self.conn.exec_iter(stmt, ())?;
257        MySQLBinarySourceParser::new(iter, &self.schema)
258    }
259
260    fn nrows(&self) -> usize {
261        self.nrows
262    }
263
264    fn ncols(&self) -> usize {
265        self.ncols
266    }
267}
268
269impl SourcePartition for MySQLSourcePartition<TextProtocol> {
270    type TypeSystem = MySQLTypeSystem;
271    type Parser<'a> = MySQLTextSourceParser<'a>;
272    type Error = MySQLSourceError;
273
274    #[throws(MySQLSourceError)]
275    fn result_rows(&mut self) {
276        self.nrows = get_total_rows(&mut self.conn, &self.query)?;
277    }
278
279    #[throws(MySQLSourceError)]
280    fn parser(&mut self) -> Self::Parser<'_> {
281        let query = self.query.clone();
282        let iter = self.conn.query_iter(query)?;
283        MySQLTextSourceParser::new(iter, &self.schema)
284    }
285
286    fn nrows(&self) -> usize {
287        self.nrows
288    }
289
290    fn ncols(&self) -> usize {
291        self.ncols
292    }
293}
294
295/// Takes the cell at `cidx` out of `row` and converts it to `T`.
296///
297/// `Row::take` panics inside mysql_common when the value has no representation
298/// in `T` (zero dates, TIME values outside a chrono `NaiveTime`, DECIMALs wider
299/// than rust_decimal, ...). Use `take_opt` instead and report the failure as an
300/// error naming the column (#476, #268).
301///
302/// `Produced` is the type named in that error: the column's Rust type, without
303/// the `Option` of nullable columns, as in the other sources.
304fn take_cell<T: FromValue, Produced>(
305    row: &mut Row,
306    ridx: usize,
307    cidx: usize,
308) -> Result<T, MySQLSourceError> {
309    match row.take_opt::<T, _>(cidx) {
310        Some(Ok(value)) => Ok(value),
311        Some(Err(e)) => Err(ConnectorXError::cannot_produce::<Produced>(Some(format!(
312            "column `{}` (index {}): {}",
313            row.columns_ref()[cidx].name_str(),
314            cidx,
315            e
316        )))
317        .into()),
318        None => Err(anyhow!("mysql cannot parse at position: ({}, {})", ridx, cidx).into()),
319    }
320}
321
322/// Row parser for the binary protocol.
323pub struct MySQLBinarySourceParser<'a> {
324    iter: QueryResult<'a, 'a, 'a, Binary>,
325    rowbuf: Vec<Row>,
326    ncols: usize,
327    current_col: usize,
328    current_row: usize,
329    is_finished: bool,
330}
331
332impl<'a> MySQLBinarySourceParser<'a> {
333    /// Wrap a binary protocol result set.
334    pub fn new(iter: QueryResult<'a, 'a, 'a, Binary>, schema: &[MySQLTypeSystem]) -> Self {
335        Self {
336            iter,
337            rowbuf: Vec::with_capacity(DB_BUFFER_SIZE),
338            ncols: schema.len(),
339            current_row: 0,
340            current_col: 0,
341            is_finished: false,
342        }
343    }
344
345    #[throws(MySQLSourceError)]
346    fn next_loc(&mut self) -> (usize, usize) {
347        let ret = (self.current_row, self.current_col);
348        self.current_row += (self.current_col + 1) / self.ncols;
349        self.current_col = (self.current_col + 1) % self.ncols;
350        ret
351    }
352}
353
354impl<'a> PartitionParser<'a> for MySQLBinarySourceParser<'a> {
355    type TypeSystem = MySQLTypeSystem;
356    type Error = MySQLSourceError;
357
358    #[throws(MySQLSourceError)]
359    fn fetch_next(&mut self) -> (usize, bool) {
360        assert!(self.current_col == 0);
361        let remaining_rows = self.rowbuf.len() - self.current_row;
362        if remaining_rows > 0 {
363            return (remaining_rows, self.is_finished);
364        } else if self.is_finished {
365            return (0, self.is_finished);
366        }
367
368        if !self.rowbuf.is_empty() {
369            self.rowbuf.drain(..);
370        }
371
372        for _ in 0..DB_BUFFER_SIZE {
373            if let Some(item) = self.iter.next() {
374                self.rowbuf.push(item?);
375            } else {
376                self.is_finished = true;
377                break;
378            }
379        }
380        self.current_row = 0;
381        self.current_col = 0;
382
383        (self.rowbuf.len(), self.is_finished)
384    }
385}
386
387macro_rules! impl_produce_binary {
388    ($($t: ty,)+) => {
389        $(
390            impl<'r, 'a> Produce<'r, $t> for MySQLBinarySourceParser<'a> {
391                type Error = MySQLSourceError;
392
393                #[throws(MySQLSourceError)]
394                fn produce(&'r mut self) -> $t {
395                    let (ridx, cidx) = self.next_loc()?;
396                    take_cell::<$t, $t>(&mut self.rowbuf[ridx], ridx, cidx)?
397                }
398            }
399
400            impl<'r, 'a> Produce<'r, Option<$t>> for MySQLBinarySourceParser<'a> {
401                type Error = MySQLSourceError;
402
403                #[throws(MySQLSourceError)]
404                fn produce(&'r mut self) -> Option<$t> {
405                    let (ridx, cidx) = self.next_loc()?;
406                    take_cell::<Option<$t>, $t>(&mut self.rowbuf[ridx], ridx, cidx)?
407                }
408            }
409        )+
410    };
411}
412
413impl_produce_binary!(
414    i8,
415    i16,
416    i32,
417    i64,
418    u8,
419    u16,
420    u32,
421    u64,
422    f32,
423    f64,
424    NaiveDate,
425    NaiveTime,
426    NaiveDateTime,
427    Decimal,
428    String,
429    Vec<u8>,
430    Value,
431);
432
433/// Row parser for the text protocol.
434pub struct MySQLTextSourceParser<'a> {
435    iter: QueryResult<'a, 'a, 'a, Text>,
436    rowbuf: Vec<Row>,
437    ncols: usize,
438    current_col: usize,
439    current_row: usize,
440    is_finished: bool,
441}
442
443impl<'a> MySQLTextSourceParser<'a> {
444    /// Wrap a text protocol result set.
445    pub fn new(iter: QueryResult<'a, 'a, 'a, Text>, schema: &[MySQLTypeSystem]) -> Self {
446        Self {
447            iter,
448            rowbuf: Vec::with_capacity(DB_BUFFER_SIZE),
449            ncols: schema.len(),
450            current_row: 0,
451            current_col: 0,
452            is_finished: false,
453        }
454    }
455
456    #[throws(MySQLSourceError)]
457    fn next_loc(&mut self) -> (usize, usize) {
458        let ret = (self.current_row, self.current_col);
459        self.current_row += (self.current_col + 1) / self.ncols;
460        self.current_col = (self.current_col + 1) % self.ncols;
461        ret
462    }
463}
464
465impl<'a> PartitionParser<'a> for MySQLTextSourceParser<'a> {
466    type TypeSystem = MySQLTypeSystem;
467    type Error = MySQLSourceError;
468
469    #[throws(MySQLSourceError)]
470    fn fetch_next(&mut self) -> (usize, bool) {
471        assert!(self.current_col == 0);
472        let remaining_rows = self.rowbuf.len() - self.current_row;
473        if remaining_rows > 0 {
474            return (remaining_rows, self.is_finished);
475        } else if self.is_finished {
476            return (0, self.is_finished);
477        }
478
479        if !self.rowbuf.is_empty() {
480            self.rowbuf.drain(..);
481        }
482        for _ in 0..DB_BUFFER_SIZE {
483            if let Some(item) = self.iter.next() {
484                self.rowbuf.push(item?);
485            } else {
486                self.is_finished = true;
487                break;
488            }
489        }
490        self.current_row = 0;
491        self.current_col = 0;
492        (self.rowbuf.len(), self.is_finished)
493    }
494}
495
496macro_rules! impl_produce_text {
497    ($($t: ty,)+) => {
498        $(
499            impl<'r, 'a> Produce<'r, $t> for MySQLTextSourceParser<'a> {
500                type Error = MySQLSourceError;
501
502                #[throws(MySQLSourceError)]
503                fn produce(&'r mut self) -> $t {
504                    let (ridx, cidx) = self.next_loc()?;
505                    take_cell::<$t, $t>(&mut self.rowbuf[ridx], ridx, cidx)?
506                }
507            }
508
509            impl<'r, 'a> Produce<'r, Option<$t>> for MySQLTextSourceParser<'a> {
510                type Error = MySQLSourceError;
511
512                #[throws(MySQLSourceError)]
513                fn produce(&'r mut self) -> Option<$t> {
514                    let (ridx, cidx) = self.next_loc()?;
515                    take_cell::<Option<$t>, $t>(&mut self.rowbuf[ridx], ridx, cidx)?
516                }
517            }
518        )+
519    };
520}
521
522impl_produce_text!(
523    i8,
524    i16,
525    i32,
526    i64,
527    u8,
528    u16,
529    u32,
530    u64,
531    f32,
532    f64,
533    NaiveDate,
534    NaiveTime,
535    NaiveDateTime,
536    Decimal,
537    String,
538    Vec<u8>,
539    Value,
540);