1mod connection;
4mod errors;
5mod typesystem;
6
7pub use self::errors::PostgresSourceError;
8pub use cidr_02::IpInet;
9pub use connection::rewrite_tls_args;
10pub use pgvector::{Bit, HalfVector, SparseVector, Vector};
11pub use typesystem::{PostgresTypePairs, PostgresTypeSystem};
12
13use crate::constants::DB_BUFFER_SIZE;
14use crate::{
15 data_order::DataOrder,
16 errors::ConnectorXError,
17 sources::{PartitionParser, Produce, Source, SourcePartition},
18 sql::{count_query, CXQuery},
19};
20use anyhow::anyhow;
21use chrono::{DateTime, FixedOffset, NaiveDate, NaiveDateTime, NaiveTime, Utc};
22use csv::{ReaderBuilder, StringRecord, StringRecordsIntoIter};
23use fehler::{throw, throws};
24use hex::decode;
25use postgres::{
26 binary_copy::{BinaryCopyOutIter, BinaryCopyOutRow},
27 fallible_iterator::FallibleIterator,
28 tls::{MakeTlsConnect, TlsConnect},
29 Config, CopyOutReader, Row, RowIter, SimpleQueryMessage, Socket,
30};
31use r2d2::{Pool, PooledConnection};
32use r2d2_postgres::PostgresConnectionManager;
33use rust_decimal::Decimal;
34use serde_json::{from_str, Value};
35use sqlparser::dialect::PostgreSqlDialect;
36use std::collections::HashMap;
37use std::convert::TryFrom;
38use std::marker::PhantomData;
39use uuid::Uuid;
40
41pub enum BinaryProtocol {}
43
44pub enum CSVProtocol {}
46
47pub enum CursorProtocol {}
49
50pub enum SimpleProtocol {}
52
53type PgManager<C> = PostgresConnectionManager<C>;
54type PgConn<C> = PooledConnection<PgManager<C>>;
55
56macro_rules! impl_produce_unimplemented {
57 ($(($protocol: ty, $t: ty, $msg: expr),)+) => {
58 $(
59 impl<'r> Produce<'r, $t> for $protocol {
60 type Error = PostgresSourceError;
61
62 #[throws(PostgresSourceError)]
63 fn produce(&'r mut self) -> $t {
64 unimplemented!($msg);
65 }
66 }
67
68 impl<'r> Produce<'r, Option<$t>> for $protocol {
69 type Error = PostgresSourceError;
70
71 #[throws(PostgresSourceError)]
72 fn produce(&'r mut self) -> Option<$t> {
73 unimplemented!($msg);
74 }
75 }
76 )+
77 };
78}
79
80impl_produce_unimplemented!(
81 (PostgresCSVSourceParser<'_>, HashMap<String, Option<String>>, "Please use `cursor` protocol for hstore type"),
82 (PostgresCSVSourceParser<'_>, Vector, "Please use `binary` protocol for vector type"),
83 (PostgresCSVSourceParser<'_>, HalfVector, "Please use `binary` protocol for halfvector type"),
84 (PostgresCSVSourceParser<'_>, Bit, "Please use `binary` protocol for bit type"),
85 (PostgresCSVSourceParser<'_>, SparseVector, "Please use `binary` protocol for sparsevector type"),
86
87
88 (PostgresSimpleSourceParser,HashMap<String, Option<String>>, "unimplemented"),
89 (PostgresSimpleSourceParser,Value, "unimplemented"),
90 (PostgresSimpleSourceParser, Vector, "Please use `binary` protocol for vector type"),
91 (PostgresSimpleSourceParser, HalfVector, "Please use `binary` protocol for halfvector type"),
92 (PostgresSimpleSourceParser, Bit, "Please use `binary` protocol for bit type"),
93 (PostgresSimpleSourceParser, SparseVector, "Please use `binary` protocol for sparsevector type"),
94
95);
96
97fn maybe_rewrite_text_query(
106 query: &CXQuery<String>,
107 names: &[String],
108 schema: &[PostgresTypeSystem],
109) -> CXQuery<String> {
110 let text_mask: Vec<bool> = schema
111 .iter()
112 .map(|ts| {
113 matches!(
114 ts,
115 PostgresTypeSystem::Range(_) | PostgresTypeSystem::TsVector(_)
116 )
117 })
118 .collect();
119
120 if !text_mask.iter().any(|&cast| cast) {
121 return query.clone();
122 }
123
124 let cols: String = names
125 .iter()
126 .zip(text_mask.iter())
127 .map(|(name, cast_to_text)| {
128 let quoted = quote_ident(name);
129 if *cast_to_text {
130 format!("{}::text", quoted)
131 } else {
132 quoted
133 }
134 })
135 .collect::<Vec<_>>()
136 .join(", ");
137
138 let rewritten = format!("SELECT {} FROM ({}) AS _cx_sub", cols, query.as_str());
139 CXQuery::Wrapped(rewritten)
140}
141
142fn quote_ident(ident: &str) -> String {
143 format!("\"{}\"", ident.replace('\"', "\"\""))
144}
145
146#[cfg(test)]
147mod text_rewrite_tests {
148 use super::{maybe_rewrite_text_query, quote_ident, PostgresTypeSystem};
149 use crate::sql::CXQuery;
150
151 #[test]
152 fn quote_ident_escapes_embedded_quotes() {
153 assert_eq!(quote_ident("a\"b"), "\"a\"\"b\"");
154 }
155
156 #[test]
157 fn rewrite_escapes_column_names_and_casts_only_ranges() {
158 let q = CXQuery::Naked("SELECT 1".to_string());
159 let names = vec!["plain".to_string(), "a\"b".to_string()];
160 let schema = vec![
161 PostgresTypeSystem::Int4(true),
162 PostgresTypeSystem::Range(true),
163 ];
164 let rewritten = maybe_rewrite_text_query(&q, &names, &schema);
165 assert_eq!(
166 rewritten.as_str(),
167 "SELECT \"plain\", \"a\"\"b\"::text FROM (SELECT 1) AS _cx_sub"
168 );
169 }
170
171 #[test]
172 fn rewrite_casts_tsvector_and_ranges() {
173 let q = CXQuery::Wrapped("SELECT * FROM documents WHERE id < 2".to_string());
174 let names = vec!["id".to_string(), "a\"b".to_string(), "period".to_string()];
175 for nullable in [false, true] {
176 let schema = vec![
177 PostgresTypeSystem::Int4(false),
178 PostgresTypeSystem::TsVector(nullable),
179 PostgresTypeSystem::Range(nullable),
180 ];
181 assert_eq!(
182 maybe_rewrite_text_query(&q, &names, &schema).as_str(),
183 "SELECT \"id\", \"a\"\"b\"::text, \"period\"::text FROM (SELECT * FROM documents WHERE id < 2) AS _cx_sub"
184 );
185 }
186 }
187
188 #[test]
189 fn rewrite_leaves_other_types_unchanged() {
190 for q in [
191 CXQuery::Naked("SELECT 'hello' AS text".to_string()),
192 CXQuery::Wrapped("SELECT 'hello' AS text".to_string()),
193 ] {
194 let rewritten = maybe_rewrite_text_query(
195 &q,
196 &["text".to_string()],
197 &[PostgresTypeSystem::Text(true)],
198 );
199 assert_eq!(rewritten.as_str(), q.as_str());
200 assert_eq!(
201 std::mem::discriminant(&rewritten),
202 std::mem::discriminant(&q)
203 );
204 }
205 }
206}
207
208fn convert_row<'b, R: TryFrom<usize> + postgres::types::FromSql<'b> + Clone>(row: &'b Row) -> R {
210 let nrows: Option<R> = row.get(0);
211 nrows.expect("Could not parse int result from count_query")
212}
213
214#[throws(PostgresSourceError)]
215fn get_total_rows<C>(conn: &mut PgConn<C>, query: &CXQuery<String>) -> usize
216where
217 C: MakeTlsConnect<Socket> + Clone + 'static + Sync + Send,
218 C::TlsConnect: Send,
219 C::Stream: Send,
220 <C::TlsConnect as TlsConnect<Socket>>::Future: Send,
221{
222 let dialect = PostgreSqlDialect {};
223
224 let row = conn.query_one(count_query(query, &dialect)?.as_str(), &[])?;
225 let col_type = PostgresTypeSystem::from(row.columns()[0].type_());
226 match col_type {
227 PostgresTypeSystem::Int2(_) => convert_row::<i16>(&row) as usize,
228 PostgresTypeSystem::Int4(_) => convert_row::<i32>(&row) as usize,
229 PostgresTypeSystem::Int8(_) => convert_row::<i64>(&row) as usize,
230 _ => throw!(anyhow!(
231 "The result of the count query was not an int, aborting."
232 )),
233 }
234}
235
236pub struct PostgresSource<P, C>
238where
239 C: MakeTlsConnect<Socket> + Clone + 'static + Sync + Send,
240 C::TlsConnect: Send,
241 C::Stream: Send,
242 <C::TlsConnect as TlsConnect<Socket>>::Future: Send,
243{
244 pool: Pool<PgManager<C>>,
245 origin_query: Option<String>,
246 queries: Vec<CXQuery<String>>,
247 names: Vec<String>,
248 schema: Vec<PostgresTypeSystem>,
249 pg_schema: Vec<postgres::types::Type>,
250 pre_execution_queries: Option<Vec<String>>,
251 _protocol: PhantomData<P>,
252}
253
254#[throws(PostgresSourceError)]
256fn pooled_conn<C>(
257 pool: &Pool<PgManager<C>>,
258 pre_execution_queries: &Option<Vec<String>>,
259) -> PgConn<C>
260where
261 C: MakeTlsConnect<Socket> + Clone + 'static + Sync + Send,
262 C::TlsConnect: Send,
263 C::Stream: Send,
264 <C::TlsConnect as TlsConnect<Socket>>::Future: Send,
265{
266 let mut conn = pool.get()?;
267 if let Some(pre_queries) = pre_execution_queries {
268 for pre_query in pre_queries {
269 conn.query(pre_query, &[])?;
270 }
271 }
272 conn
273}
274
275impl<P, C> PostgresSource<P, C>
276where
277 C: MakeTlsConnect<Socket> + Clone + 'static + Sync + Send,
278 C::TlsConnect: Send,
279 C::Stream: Send,
280 <C::TlsConnect as TlsConnect<Socket>>::Future: Send,
281{
282 #[throws(PostgresSourceError)]
284 pub fn new(config: Config, tls: C, nconn: usize) -> Self {
285 let manager = PostgresConnectionManager::new(config, tls);
286 let pool = Pool::builder().max_size(nconn as u32).build(manager)?;
287
288 Self {
289 pool,
290 origin_query: None,
291 queries: vec![],
292 names: vec![],
293 schema: vec![],
294 pg_schema: vec![],
295 pre_execution_queries: None,
296 _protocol: PhantomData,
297 }
298 }
299}
300
301impl<P, C> Source for PostgresSource<P, C>
302where
303 PostgresSourcePartition<P, C>:
304 SourcePartition<TypeSystem = PostgresTypeSystem, Error = PostgresSourceError>,
305 P: Send,
306 C: MakeTlsConnect<Socket> + Clone + 'static + Sync + Send,
307 C::TlsConnect: Send,
308 C::Stream: Send,
309 <C::TlsConnect as TlsConnect<Socket>>::Future: Send,
310{
311 const DATA_ORDERS: &'static [DataOrder] = &[DataOrder::RowMajor];
312 type Partition = PostgresSourcePartition<P, C>;
313 type TypeSystem = PostgresTypeSystem;
314 type Error = PostgresSourceError;
315
316 #[throws(PostgresSourceError)]
317 fn set_data_order(&mut self, data_order: DataOrder) {
318 if !matches!(data_order, DataOrder::RowMajor) {
319 throw!(ConnectorXError::UnsupportedDataOrder(data_order));
320 }
321 }
322
323 fn set_queries<Q: ToString>(&mut self, queries: &[CXQuery<Q>]) {
324 self.queries = queries.iter().map(|q| q.map(Q::to_string)).collect();
325 }
326
327 fn set_origin_query(&mut self, query: Option<String>) {
328 self.origin_query = query;
329 }
330
331 fn set_pre_execution_queries(&mut self, pre_execution_queries: Option<&[String]>) {
332 self.pre_execution_queries = pre_execution_queries.map(|s| s.to_vec());
333 }
334
335 #[throws(PostgresSourceError)]
336 fn fetch_metadata(&mut self) {
337 assert!(!self.queries.is_empty());
338
339 let mut conn = pooled_conn(&self.pool, &self.pre_execution_queries)?;
340 let first_query = &self.queries[0];
341
342 let stmt = conn.prepare(first_query.as_str())?;
343
344 let (names, pg_types): (Vec<String>, Vec<postgres::types::Type>) = stmt
345 .columns()
346 .iter()
347 .map(|col| (col.name().to_string(), col.type_().clone()))
348 .unzip();
349
350 self.names = names;
351 self.schema = pg_types.iter().map(PostgresTypeSystem::from).collect();
352 self.pg_schema = self
353 .schema
354 .iter()
355 .zip(pg_types.iter())
356 .map(|(t1, t2)| PostgresTypePairs(t2, t1).into())
357 .collect();
358 }
359
360 #[throws(PostgresSourceError)]
361 fn result_rows(&mut self) -> Option<usize> {
362 match &self.origin_query {
363 Some(q) => {
364 let cxq = CXQuery::Naked(q.clone());
365 let mut conn = pooled_conn(&self.pool, &self.pre_execution_queries)?;
366 let nrows = get_total_rows(&mut conn, &cxq)?;
367 Some(nrows)
368 }
369 None => None,
370 }
371 }
372
373 fn names(&self) -> Vec<String> {
374 self.names.clone()
375 }
376
377 fn schema(&self) -> Vec<Self::TypeSystem> {
378 self.schema.clone()
379 }
380
381 #[throws(PostgresSourceError)]
382 fn partition(self) -> Vec<Self::Partition> {
383 let mut ret = vec![];
384 for query in self.queries {
385 let conn = pooled_conn(&self.pool, &self.pre_execution_queries)?;
386 let rewritten = maybe_rewrite_text_query(&query, &self.names, &self.schema);
387
388 ret.push(PostgresSourcePartition::<P, C>::new(
389 conn,
390 &rewritten,
391 &self.schema,
392 &self.pg_schema,
393 ));
394 }
395 ret
396 }
397}
398
399pub struct PostgresSourcePartition<P, C>
401where
402 C: MakeTlsConnect<Socket> + Clone + 'static + Sync + Send,
403 C::TlsConnect: Send,
404 C::Stream: Send,
405 <C::TlsConnect as TlsConnect<Socket>>::Future: Send,
406{
407 conn: PgConn<C>,
408 query: CXQuery<String>,
409 schema: Vec<PostgresTypeSystem>,
410 pg_schema: Vec<postgres::types::Type>,
411 nrows: usize,
412 ncols: usize,
413 _protocol: PhantomData<P>,
414}
415
416impl<P, C> PostgresSourcePartition<P, C>
417where
418 C: MakeTlsConnect<Socket> + Clone + 'static + Sync + Send,
419 C::TlsConnect: Send,
420 C::Stream: Send,
421 <C::TlsConnect as TlsConnect<Socket>>::Future: Send,
422{
423 pub fn new(
425 conn: PgConn<C>,
426 query: &CXQuery<String>,
427 schema: &[PostgresTypeSystem],
428 pg_schema: &[postgres::types::Type],
429 ) -> Self {
430 Self {
431 conn,
432 query: query.clone(),
433 schema: schema.to_vec(),
434 pg_schema: pg_schema.to_vec(),
435 nrows: 0,
436 ncols: schema.len(),
437 _protocol: PhantomData,
438 }
439 }
440}
441
442impl<C> SourcePartition for PostgresSourcePartition<BinaryProtocol, C>
443where
444 C: MakeTlsConnect<Socket> + Clone + 'static + Sync + Send,
445 C::TlsConnect: Send,
446 C::Stream: Send,
447 <C::TlsConnect as TlsConnect<Socket>>::Future: Send,
448{
449 type TypeSystem = PostgresTypeSystem;
450 type Parser<'a> = PostgresBinarySourcePartitionParser<'a>;
451 type Error = PostgresSourceError;
452
453 #[throws(PostgresSourceError)]
454 fn result_rows(&mut self) -> () {
455 self.nrows = get_total_rows(&mut self.conn, &self.query)?;
456 }
457
458 #[throws(PostgresSourceError)]
459 fn parser(&mut self) -> Self::Parser<'_> {
460 let query = format!("COPY ({}) TO STDOUT WITH BINARY", self.query);
461 let reader = self.conn.copy_out(&*query)?; let iter = BinaryCopyOutIter::new(reader, &self.pg_schema);
463
464 PostgresBinarySourcePartitionParser::new(iter, &self.schema)
465 }
466
467 fn nrows(&self) -> usize {
468 self.nrows
469 }
470
471 fn ncols(&self) -> usize {
472 self.ncols
473 }
474}
475
476impl<C> SourcePartition for PostgresSourcePartition<CSVProtocol, C>
477where
478 C: MakeTlsConnect<Socket> + Clone + 'static + Sync + Send,
479 C::TlsConnect: Send,
480 C::Stream: Send,
481 <C::TlsConnect as TlsConnect<Socket>>::Future: Send,
482{
483 type TypeSystem = PostgresTypeSystem;
484 type Parser<'a> = PostgresCSVSourceParser<'a>;
485 type Error = PostgresSourceError;
486
487 #[throws(PostgresSourceError)]
488 fn result_rows(&mut self) {
489 self.nrows = get_total_rows(&mut self.conn, &self.query)?;
490 }
491
492 #[throws(PostgresSourceError)]
493 fn parser(&mut self) -> Self::Parser<'_> {
494 let query = format!("COPY ({}) TO STDOUT WITH CSV", self.query);
495 let reader = self.conn.copy_out(&*query)?; let iter = ReaderBuilder::new()
497 .has_headers(false)
498 .from_reader(reader)
499 .into_records();
500
501 PostgresCSVSourceParser::new(iter, &self.schema)
502 }
503
504 fn nrows(&self) -> usize {
505 self.nrows
506 }
507
508 fn ncols(&self) -> usize {
509 self.ncols
510 }
511}
512
513impl<C> SourcePartition for PostgresSourcePartition<CursorProtocol, C>
514where
515 C: MakeTlsConnect<Socket> + Clone + 'static + Sync + Send,
516 C::TlsConnect: Send,
517 C::Stream: Send,
518 <C::TlsConnect as TlsConnect<Socket>>::Future: Send,
519{
520 type TypeSystem = PostgresTypeSystem;
521 type Parser<'a> = PostgresRawSourceParser<'a>;
522 type Error = PostgresSourceError;
523
524 #[throws(PostgresSourceError)]
525 fn result_rows(&mut self) {
526 self.nrows = get_total_rows(&mut self.conn, &self.query)?;
527 }
528
529 #[throws(PostgresSourceError)]
530 fn parser(&mut self) -> Self::Parser<'_> {
531 let iter = self
532 .conn
533 .query_raw::<_, bool, _>(self.query.as_str(), vec![])?; PostgresRawSourceParser::new(iter, &self.schema)
535 }
536
537 fn nrows(&self) -> usize {
538 self.nrows
539 }
540
541 fn ncols(&self) -> usize {
542 self.ncols
543 }
544}
545pub struct PostgresBinarySourcePartitionParser<'a> {
547 iter: BinaryCopyOutIter<'a>,
548 rowbuf: Vec<BinaryCopyOutRow>,
549 ncols: usize,
550 current_col: usize,
551 current_row: usize,
552 is_finished: bool,
553}
554
555impl<'a> PostgresBinarySourcePartitionParser<'a> {
556 pub fn new(iter: BinaryCopyOutIter<'a>, schema: &[PostgresTypeSystem]) -> Self {
558 Self {
559 iter,
560 rowbuf: Vec::with_capacity(DB_BUFFER_SIZE),
561 ncols: schema.len(),
562 current_row: 0,
563 current_col: 0,
564 is_finished: false,
565 }
566 }
567
568 #[throws(PostgresSourceError)]
569 fn next_loc(&mut self) -> (usize, usize) {
570 let ret = (self.current_row, self.current_col);
571 self.current_row += (self.current_col + 1) / self.ncols;
572 self.current_col = (self.current_col + 1) % self.ncols;
573 ret
574 }
575}
576
577impl<'a> PartitionParser<'a> for PostgresBinarySourcePartitionParser<'a> {
578 type TypeSystem = PostgresTypeSystem;
579 type Error = PostgresSourceError;
580
581 #[throws(PostgresSourceError)]
582 fn fetch_next(&mut self) -> (usize, bool) {
583 assert!(self.current_col == 0);
584 let remaining_rows = self.rowbuf.len() - self.current_row;
585 if remaining_rows > 0 {
586 return (remaining_rows, self.is_finished);
587 } else if self.is_finished {
588 return (0, self.is_finished);
589 }
590
591 if !self.rowbuf.is_empty() {
593 self.rowbuf.drain(..);
594 }
595 for _ in 0..DB_BUFFER_SIZE {
596 match self.iter.next()? {
597 Some(row) => {
598 self.rowbuf.push(row);
599 }
600 None => {
601 self.is_finished = true;
602 break;
603 }
604 }
605 }
606
607 self.current_row = 0;
609 self.current_col = 0;
610
611 (self.rowbuf.len(), self.is_finished)
612 }
613}
614
615macro_rules! impl_produce {
616 ($($t: ty,)+) => {
617 $(
618 impl<'r, 'a> Produce<'r, $t> for PostgresBinarySourcePartitionParser<'a> {
619 type Error = PostgresSourceError;
620
621 #[throws(PostgresSourceError)]
622 fn produce(&'r mut self) -> $t {
623 let (ridx, cidx) = self.next_loc()?;
624 let row = &self.rowbuf[ridx];
625 let val = row.try_get(cidx)?;
626 val
627 }
628 }
629
630 impl<'r, 'a> Produce<'r, Option<$t>> for PostgresBinarySourcePartitionParser<'a> {
631 type Error = PostgresSourceError;
632
633 #[throws(PostgresSourceError)]
634 fn produce(&'r mut self) -> Option<$t> {
635 let (ridx, cidx) = self.next_loc()?;
636 let row = &self.rowbuf[ridx];
637 let val = row.try_get(cidx)?;
638 val
639 }
640 }
641 )+
642 };
643}
644
645impl_produce!(
646 i8,
647 i16,
648 i32,
649 i64,
650 u32,
651 f32,
652 f64,
653 Decimal,
654 bool,
655 &'r str,
656 Vec<u8>,
657 NaiveTime,
658 Uuid,
659 Value,
660 IpInet,
661 Vector,
662 HalfVector,
663 Bit,
664 SparseVector,
665 Vec<Option<bool>>,
666 Vec<Option<i16>>,
667 Vec<Option<i32>>,
668 Vec<Option<i64>>,
669 Vec<Option<Decimal>>,
670 Vec<Option<f32>>,
671 Vec<Option<f64>>,
672 Vec<Option<String>>,
673);
674
675impl<'r> Produce<'r, NaiveDateTime> for PostgresBinarySourcePartitionParser<'_> {
676 type Error = PostgresSourceError;
677
678 #[throws(PostgresSourceError)]
679 fn produce(&'r mut self) -> NaiveDateTime {
680 let (ridx, cidx) = self.next_loc()?;
681 let row = &self.rowbuf[ridx];
682 let val = row.try_get(cidx)?;
683 match val {
684 postgres::types::Timestamp::PosInfinity => NaiveDateTime::MAX,
685 postgres::types::Timestamp::NegInfinity => NaiveDateTime::MIN,
686 postgres::types::Timestamp::Value(t) => t,
687 }
688 }
689}
690
691impl<'r> Produce<'r, Option<NaiveDateTime>> for PostgresBinarySourcePartitionParser<'_> {
692 type Error = PostgresSourceError;
693
694 #[throws(PostgresSourceError)]
695 fn produce(&'r mut self) -> Option<NaiveDateTime> {
696 let (ridx, cidx) = self.next_loc()?;
697 let row = &self.rowbuf[ridx];
698 let val = row.try_get(cidx)?;
699 match val {
700 Some(postgres::types::Timestamp::PosInfinity) => Some(NaiveDateTime::MAX),
701 Some(postgres::types::Timestamp::NegInfinity) => Some(NaiveDateTime::MIN),
702 Some(postgres::types::Timestamp::Value(t)) => t,
703 None => None,
704 }
705 }
706}
707
708impl<'r> Produce<'r, DateTime<Utc>> for PostgresBinarySourcePartitionParser<'_> {
709 type Error = PostgresSourceError;
710
711 #[throws(PostgresSourceError)]
712 fn produce(&'r mut self) -> DateTime<Utc> {
713 let (ridx, cidx) = self.next_loc()?;
714 let row = &self.rowbuf[ridx];
715 let val = row.try_get(cidx)?;
716 match val {
717 postgres::types::Timestamp::PosInfinity => DateTime::<Utc>::MAX_UTC,
718 postgres::types::Timestamp::NegInfinity => DateTime::<Utc>::MIN_UTC,
719 postgres::types::Timestamp::Value(t) => t,
720 }
721 }
722}
723
724impl<'r> Produce<'r, Option<DateTime<Utc>>> for PostgresBinarySourcePartitionParser<'_> {
725 type Error = PostgresSourceError;
726
727 #[throws(PostgresSourceError)]
728 fn produce(&'r mut self) -> Option<DateTime<Utc>> {
729 let (ridx, cidx) = self.next_loc()?;
730 let row = &self.rowbuf[ridx];
731 let val = row.try_get(cidx)?;
732 match val {
733 Some(postgres::types::Timestamp::PosInfinity) => Some(DateTime::<Utc>::MAX_UTC),
734 Some(postgres::types::Timestamp::NegInfinity) => Some(DateTime::<Utc>::MIN_UTC),
735 Some(postgres::types::Timestamp::Value(t)) => t,
736 None => None,
737 }
738 }
739}
740
741impl<'r> Produce<'r, NaiveDate> for PostgresBinarySourcePartitionParser<'_> {
742 type Error = PostgresSourceError;
743
744 #[throws(PostgresSourceError)]
745 fn produce(&'r mut self) -> NaiveDate {
746 let (ridx, cidx) = self.next_loc()?;
747 let row = &self.rowbuf[ridx];
748 let val = row.try_get(cidx)?;
749 match val {
750 postgres::types::Date::PosInfinity => NaiveDate::MAX,
751 postgres::types::Date::NegInfinity => NaiveDate::MIN,
752 postgres::types::Date::Value(t) => t,
753 }
754 }
755}
756
757impl<'r> Produce<'r, Option<NaiveDate>> for PostgresBinarySourcePartitionParser<'_> {
758 type Error = PostgresSourceError;
759
760 #[throws(PostgresSourceError)]
761 fn produce(&'r mut self) -> Option<NaiveDate> {
762 let (ridx, cidx) = self.next_loc()?;
763 let row = &self.rowbuf[ridx];
764 let val = row.try_get(cidx)?;
765 match val {
766 Some(postgres::types::Date::PosInfinity) => Some(NaiveDate::MAX),
767 Some(postgres::types::Date::NegInfinity) => Some(NaiveDate::MIN),
768 Some(postgres::types::Date::Value(t)) => t,
769 None => None,
770 }
771 }
772}
773
774impl Produce<'_, HashMap<String, Option<String>>> for PostgresBinarySourcePartitionParser<'_> {
775 type Error = PostgresSourceError;
776 #[throws(PostgresSourceError)]
777 fn produce(&mut self) -> HashMap<String, Option<String>> {
778 unimplemented!("Please use `cursor` protocol for hstore type");
779 }
780}
781
782impl Produce<'_, Option<HashMap<String, Option<String>>>>
783 for PostgresBinarySourcePartitionParser<'_>
784{
785 type Error = PostgresSourceError;
786 #[throws(PostgresSourceError)]
787 fn produce(&mut self) -> Option<HashMap<String, Option<String>>> {
788 unimplemented!("Please use `cursor` protocol for hstore type");
789 }
790}
791
792pub struct PostgresCSVSourceParser<'a> {
794 iter: StringRecordsIntoIter<CopyOutReader<'a>>,
795 rowbuf: Vec<StringRecord>,
796 ncols: usize,
797 current_col: usize,
798 current_row: usize,
799 is_finished: bool,
800}
801
802impl<'a> PostgresCSVSourceParser<'a> {
803 pub fn new(
805 iter: StringRecordsIntoIter<CopyOutReader<'a>>,
806 schema: &[PostgresTypeSystem],
807 ) -> Self {
808 Self {
809 iter,
810 rowbuf: Vec::with_capacity(DB_BUFFER_SIZE),
811 ncols: schema.len(),
812 current_row: 0,
813 current_col: 0,
814 is_finished: false,
815 }
816 }
817
818 #[throws(PostgresSourceError)]
819 fn next_loc(&mut self) -> (usize, usize) {
820 let ret = (self.current_row, self.current_col);
821 self.current_row += (self.current_col + 1) / self.ncols;
822 self.current_col = (self.current_col + 1) % self.ncols;
823 ret
824 }
825}
826
827impl<'a> PartitionParser<'a> for PostgresCSVSourceParser<'a> {
828 type Error = PostgresSourceError;
829 type TypeSystem = PostgresTypeSystem;
830
831 #[throws(PostgresSourceError)]
832 fn fetch_next(&mut self) -> (usize, bool) {
833 assert!(self.current_col == 0);
834 let remaining_rows = self.rowbuf.len() - self.current_row;
835 if remaining_rows > 0 {
836 return (remaining_rows, self.is_finished);
837 } else if self.is_finished {
838 return (0, self.is_finished);
839 }
840
841 if !self.rowbuf.is_empty() {
842 self.rowbuf.drain(..);
843 }
844 for _ in 0..DB_BUFFER_SIZE {
845 if let Some(row) = self.iter.next() {
846 self.rowbuf.push(row?);
847 } else {
848 self.is_finished = true;
849 break;
850 }
851 }
852 self.current_row = 0;
853 self.current_col = 0;
854 (self.rowbuf.len(), self.is_finished)
855 }
856}
857
858macro_rules! impl_csv_produce {
859 ($($t: ty,)+) => {
860 $(
861 impl<'r, 'a> Produce<'r, $t> for PostgresCSVSourceParser<'a> {
862 type Error = PostgresSourceError;
863
864 #[throws(PostgresSourceError)]
865 fn produce(&'r mut self) -> $t {
866 let (ridx, cidx) = self.next_loc()?;
867 self.rowbuf[ridx][cidx].parse().map_err(|_| {
868 ConnectorXError::cannot_produce::<$t>(Some(self.rowbuf[ridx][cidx].into()))
869 })?
870 }
871 }
872
873 impl<'r, 'a> Produce<'r, Option<$t>> for PostgresCSVSourceParser<'a> {
874 type Error = PostgresSourceError;
875
876 #[throws(PostgresSourceError)]
877 fn produce(&'r mut self) -> Option<$t> {
878 let (ridx, cidx) = self.next_loc()?;
879 match &self.rowbuf[ridx][cidx][..] {
880 "" => None,
881 v => Some(v.parse().map_err(|_| {
882 ConnectorXError::cannot_produce::<$t>(Some(self.rowbuf[ridx][cidx].into()))
883 })?),
884 }
885 }
886 }
887 )+
888 };
889}
890
891impl_csv_produce!(i8, i16, i32, i64, u32, f32, f64, Uuid, IpInet,);
892
893macro_rules! impl_csv_vec_produce {
894 ($($t: ty,)+) => {
895 $(
896 impl<'r, 'a> Produce<'r, Vec<Option<$t>>> for PostgresCSVSourceParser<'a> {
897 type Error = PostgresSourceError;
898
899 #[throws(PostgresSourceError)]
900 fn produce(&mut self) -> Vec<Option<$t>> {
901 let (ridx, cidx) = self.next_loc()?;
902 let s = &self.rowbuf[ridx][cidx][..];
903 match s {
904 "{}" => vec![],
905 _ if s.len() < 3 => throw!(ConnectorXError::cannot_produce::<$t>(Some(s.into()))),
906 s => s[1..s.len() - 1]
907 .split(",")
908 .map(|v| {
909 if v == "NULL" {
910 Ok(None)
911 } else {
912 match v.parse() {
913 Ok(v) => Ok(Some(v)),
914 Err(e) => Err(e).map_err(|_| ConnectorXError::cannot_produce::<$t>(Some(s.into())))
915 }
916 }
917 })
918 .collect::<Result<Vec<Option<$t>>, ConnectorXError>>()?,
919 }
920 }
921 }
922
923 impl<'r, 'a> Produce<'r, Option<Vec<Option<$t>>>> for PostgresCSVSourceParser<'a> {
924 type Error = PostgresSourceError;
925
926 #[throws(PostgresSourceError)]
927 fn produce(&mut self) -> Option<Vec<Option<$t>>> {
928 let (ridx, cidx) = self.next_loc()?;
929 let s = &self.rowbuf[ridx][cidx][..];
930 match s {
931 "" => None,
932 "{}" => Some(vec![]),
933 _ if s.len() < 3 => throw!(ConnectorXError::cannot_produce::<$t>(Some(s.into()))),
934 s => Some(
935 s[1..s.len() - 1]
936 .split(",")
937 .map(|v| {
938 if v == "NULL" {
939 Ok(None)
940 } else {
941 match v.parse() {
942 Ok(v) => Ok(Some(v)),
943 Err(e) => Err(e).map_err(|_| ConnectorXError::cannot_produce::<$t>(Some(s.into())))
944 }
945 }
946 })
947 .collect::<Result<Vec<Option<$t>>, ConnectorXError>>()?,
948 ),
949 }
950 }
951 }
952 )+
953 };
954}
955
956impl_csv_vec_produce!(i8, i16, i32, i64, f32, f64, Decimal, String,);
957
958impl Produce<'_, bool> for PostgresCSVSourceParser<'_> {
959 type Error = PostgresSourceError;
960
961 #[throws(PostgresSourceError)]
962 fn produce(&mut self) -> bool {
963 let (ridx, cidx) = self.next_loc()?;
964 let ret = match &self.rowbuf[ridx][cidx][..] {
965 "t" => true,
966 "f" => false,
967 _ => throw!(ConnectorXError::cannot_produce::<bool>(Some(
968 self.rowbuf[ridx][cidx].into()
969 ))),
970 };
971 ret
972 }
973}
974
975impl Produce<'_, Option<bool>> for PostgresCSVSourceParser<'_> {
976 type Error = PostgresSourceError;
977
978 #[throws(PostgresSourceError)]
979 fn produce(&mut self) -> Option<bool> {
980 let (ridx, cidx) = self.next_loc()?;
981 let ret = match &self.rowbuf[ridx][cidx][..] {
982 "" => None,
983 "t" => Some(true),
984 "f" => Some(false),
985 _ => throw!(ConnectorXError::cannot_produce::<bool>(Some(
986 self.rowbuf[ridx][cidx].into()
987 ))),
988 };
989 ret
990 }
991}
992
993impl Produce<'_, Vec<Option<bool>>> for PostgresCSVSourceParser<'_> {
994 type Error = PostgresSourceError;
995
996 #[throws(PostgresSourceError)]
997 fn produce(&mut self) -> Vec<Option<bool>> {
998 let (ridx, cidx) = self.next_loc()?;
999 let s = &self.rowbuf[ridx][cidx][..];
1000 match s {
1001 "{}" => vec![],
1002 _ if s.len() < 3 => throw!(ConnectorXError::cannot_produce::<bool>(Some(s.into()))),
1003 s => s[1..s.len() - 1]
1004 .split(',')
1005 .map(|v| match v {
1006 "NULL" => Ok(None),
1007 "t" => Ok(Some(true)),
1008 "f" => Ok(Some(false)),
1009 _ => throw!(ConnectorXError::cannot_produce::<bool>(Some(s.into()))),
1010 })
1011 .collect::<Result<Vec<Option<bool>>, ConnectorXError>>()?,
1012 }
1013 }
1014}
1015
1016impl Produce<'_, Option<Vec<Option<bool>>>> for PostgresCSVSourceParser<'_> {
1017 type Error = PostgresSourceError;
1018
1019 #[throws(PostgresSourceError)]
1020 fn produce(&mut self) -> Option<Vec<Option<bool>>> {
1021 let (ridx, cidx) = self.next_loc()?;
1022 let s = &self.rowbuf[ridx][cidx][..];
1023 match s {
1024 "" => None,
1025 "{}" => Some(vec![]),
1026 _ if s.len() < 3 => throw!(ConnectorXError::cannot_produce::<bool>(Some(s.into()))),
1027 s => Some(
1028 s[1..s.len() - 1]
1029 .split(',')
1030 .map(|v| match v {
1031 "NULL" => Ok(None),
1032 "t" => Ok(Some(true)),
1033 "f" => Ok(Some(false)),
1034 _ => throw!(ConnectorXError::cannot_produce::<bool>(Some(s.into()))),
1035 })
1036 .collect::<Result<Vec<Option<bool>>, ConnectorXError>>()?,
1037 ),
1038 }
1039 }
1040}
1041
1042impl<'r> Produce<'r, Decimal> for PostgresCSVSourceParser<'_> {
1043 type Error = PostgresSourceError;
1044
1045 #[throws(PostgresSourceError)]
1046 fn produce(&'r mut self) -> Decimal {
1047 let (ridx, cidx) = self.next_loc()?;
1048 match &self.rowbuf[ridx][cidx][..] {
1049 "Infinity" => Decimal::MAX,
1050 "-Infinity" => Decimal::MIN,
1051 v => v
1052 .parse()
1053 .map_err(|_| ConnectorXError::cannot_produce::<Decimal>(Some(v.into())))?,
1054 }
1055 }
1056}
1057
1058impl<'r> Produce<'r, Option<Decimal>> for PostgresCSVSourceParser<'_> {
1059 type Error = PostgresSourceError;
1060
1061 #[throws(PostgresSourceError)]
1062 fn produce(&'r mut self) -> Option<Decimal> {
1063 let (ridx, cidx) = self.next_loc()?;
1064 match &self.rowbuf[ridx][cidx][..] {
1065 "" => None,
1066 "Infinity" => Some(Decimal::MAX),
1067 "-Infinity" => Some(Decimal::MIN),
1068 v => Some(
1069 v.parse()
1070 .map_err(|_| ConnectorXError::cannot_produce::<Decimal>(Some(v.into())))?,
1071 ),
1072 }
1073 }
1074}
1075
1076impl Produce<'_, DateTime<Utc>> for PostgresCSVSourceParser<'_> {
1077 type Error = PostgresSourceError;
1078
1079 #[throws(PostgresSourceError)]
1080 fn produce(&mut self) -> DateTime<Utc> {
1081 let (ridx, cidx) = self.next_loc()?;
1082 match &self.rowbuf[ridx][cidx][..] {
1083 "infinity" => DateTime::<Utc>::MAX_UTC,
1084 "-infinity" => DateTime::<Utc>::MIN_UTC,
1085 v => format!("{}:00", v)
1087 .parse()
1088 .map_err(|_| ConnectorXError::cannot_produce::<DateTime<Utc>>(Some(v.into())))?,
1089 }
1090 }
1091}
1092
1093impl Produce<'_, Option<DateTime<Utc>>> for PostgresCSVSourceParser<'_> {
1094 type Error = PostgresSourceError;
1095
1096 #[throws(PostgresSourceError)]
1097 fn produce(&mut self) -> Option<DateTime<Utc>> {
1098 let (ridx, cidx) = self.next_loc()?;
1099 match &self.rowbuf[ridx][cidx][..] {
1100 "" => None,
1101 "infinity" => Some(DateTime::<Utc>::MAX_UTC),
1102 "-infinity" => Some(DateTime::<Utc>::MIN_UTC),
1103 v => {
1104 Some(format!("{}:00", v).parse().map_err(|_| {
1106 ConnectorXError::cannot_produce::<DateTime<Utc>>(Some(v.into()))
1107 })?)
1108 }
1109 }
1110 }
1111}
1112
1113impl Produce<'_, NaiveDate> for PostgresCSVSourceParser<'_> {
1114 type Error = PostgresSourceError;
1115
1116 #[throws(PostgresSourceError)]
1117 fn produce(&mut self) -> NaiveDate {
1118 let (ridx, cidx) = self.next_loc()?;
1119 match &self.rowbuf[ridx][cidx][..] {
1120 "infinity" => NaiveDate::MAX,
1121 "-infinity" => NaiveDate::MIN,
1122 v => NaiveDate::parse_from_str(v, "%Y-%m-%d")
1123 .map_err(|_| ConnectorXError::cannot_produce::<NaiveDate>(Some(v.into())))?,
1124 }
1125 }
1126}
1127
1128impl Produce<'_, Option<NaiveDate>> for PostgresCSVSourceParser<'_> {
1129 type Error = PostgresSourceError;
1130
1131 #[throws(PostgresSourceError)]
1132 fn produce(&mut self) -> Option<NaiveDate> {
1133 let (ridx, cidx) = self.next_loc()?;
1134 match &self.rowbuf[ridx][cidx][..] {
1135 "" => None,
1136 "infinity" => Some(NaiveDate::MAX),
1137 "-infinity" => Some(NaiveDate::MIN),
1138 v => Some(
1139 NaiveDate::parse_from_str(v, "%Y-%m-%d")
1140 .map_err(|_| ConnectorXError::cannot_produce::<NaiveDate>(Some(v.into())))?,
1141 ),
1142 }
1143 }
1144}
1145
1146impl Produce<'_, NaiveDateTime> for PostgresCSVSourceParser<'_> {
1147 type Error = PostgresSourceError;
1148
1149 #[throws(PostgresSourceError)]
1150 fn produce(&mut self) -> NaiveDateTime {
1151 let (ridx, cidx) = self.next_loc()?;
1152 match &self.rowbuf[ridx][cidx] {
1153 "infinity" => NaiveDateTime::MAX,
1154 "-infinity" => NaiveDateTime::MIN,
1155 v => NaiveDateTime::parse_from_str(v, "%Y-%m-%d %H:%M:%S%.f")
1156 .map_err(|_| ConnectorXError::cannot_produce::<NaiveDateTime>(Some(v.into())))?,
1157 }
1158 }
1159}
1160
1161impl Produce<'_, Option<NaiveDateTime>> for PostgresCSVSourceParser<'_> {
1162 type Error = PostgresSourceError;
1163
1164 #[throws(PostgresSourceError)]
1165 fn produce(&mut self) -> Option<NaiveDateTime> {
1166 let (ridx, cidx) = self.next_loc()?;
1167 match &self.rowbuf[ridx][cidx][..] {
1168 "" => None,
1169 "infinity" => Some(NaiveDateTime::MAX),
1170 "-infinity" => Some(NaiveDateTime::MIN),
1171 v => Some(
1172 NaiveDateTime::parse_from_str(v, "%Y-%m-%d %H:%M:%S%.f").map_err(|_| {
1173 ConnectorXError::cannot_produce::<NaiveDateTime>(Some(v.into()))
1174 })?,
1175 ),
1176 }
1177 }
1178}
1179
1180impl Produce<'_, NaiveTime> for PostgresCSVSourceParser<'_> {
1181 type Error = PostgresSourceError;
1182
1183 #[throws(PostgresSourceError)]
1184 fn produce(&mut self) -> NaiveTime {
1185 let (ridx, cidx) = self.next_loc()?;
1186 NaiveTime::parse_from_str(&self.rowbuf[ridx][cidx], "%H:%M:%S%.f").map_err(|_| {
1187 ConnectorXError::cannot_produce::<NaiveTime>(Some(self.rowbuf[ridx][cidx].into()))
1188 })?
1189 }
1190}
1191
1192impl Produce<'_, Option<NaiveTime>> for PostgresCSVSourceParser<'_> {
1193 type Error = PostgresSourceError;
1194
1195 #[throws(PostgresSourceError)]
1196 fn produce(&mut self) -> Option<NaiveTime> {
1197 let (ridx, cidx) = self.next_loc()?;
1198 match &self.rowbuf[ridx][cidx][..] {
1199 "" => None,
1200 v => Some(
1201 NaiveTime::parse_from_str(v, "%H:%M:%S%.f")
1202 .map_err(|_| ConnectorXError::cannot_produce::<NaiveTime>(Some(v.into())))?,
1203 ),
1204 }
1205 }
1206}
1207
1208impl<'r> Produce<'r, &'r str> for PostgresCSVSourceParser<'_> {
1209 type Error = PostgresSourceError;
1210
1211 #[throws(PostgresSourceError)]
1212 fn produce(&'r mut self) -> &'r str {
1213 let (ridx, cidx) = self.next_loc()?;
1214 &self.rowbuf[ridx][cidx]
1215 }
1216}
1217
1218impl<'r> Produce<'r, Option<&'r str>> for PostgresCSVSourceParser<'_> {
1219 type Error = PostgresSourceError;
1220
1221 #[throws(PostgresSourceError)]
1222 fn produce(&'r mut self) -> Option<&'r str> {
1223 let (ridx, cidx) = self.next_loc()?;
1224 match &self.rowbuf[ridx][cidx][..] {
1225 "" => None,
1226 v => Some(v),
1227 }
1228 }
1229}
1230
1231impl<'r> Produce<'r, Vec<u8>> for PostgresCSVSourceParser<'_> {
1232 type Error = PostgresSourceError;
1233
1234 #[throws(PostgresSourceError)]
1235 fn produce(&'r mut self) -> Vec<u8> {
1236 let (ridx, cidx) = self.next_loc()?;
1237 decode(&self.rowbuf[ridx][cidx][2..])? }
1239}
1240
1241impl<'r> Produce<'r, Option<Vec<u8>>> for PostgresCSVSourceParser<'_> {
1242 type Error = PostgresSourceError;
1243
1244 #[throws(PostgresSourceError)]
1245 fn produce(&'r mut self) -> Option<Vec<u8>> {
1246 let (ridx, cidx) = self.next_loc()?;
1247 match &self.rowbuf[ridx][cidx] {
1248 "" => None,
1250 v => Some(decode(&v[2..])?),
1251 }
1252 }
1253}
1254
1255impl<'r> Produce<'r, Value> for PostgresCSVSourceParser<'_> {
1256 type Error = PostgresSourceError;
1257
1258 #[throws(PostgresSourceError)]
1259 fn produce(&'r mut self) -> Value {
1260 let (ridx, cidx) = self.next_loc()?;
1261 let v = &self.rowbuf[ridx][cidx];
1262 from_str(v).map_err(|_| ConnectorXError::cannot_produce::<Value>(Some(v.into())))?
1263 }
1264}
1265
1266impl<'r> Produce<'r, Option<Value>> for PostgresCSVSourceParser<'_> {
1267 type Error = PostgresSourceError;
1268
1269 #[throws(PostgresSourceError)]
1270 fn produce(&'r mut self) -> Option<Value> {
1271 let (ridx, cidx) = self.next_loc()?;
1272
1273 match &self.rowbuf[ridx][cidx][..] {
1274 "" => None,
1275 v => {
1276 from_str(v).map_err(|_| ConnectorXError::cannot_produce::<Value>(Some(v.into())))?
1277 }
1278 }
1279 }
1280}
1281
1282pub struct PostgresRawSourceParser<'a> {
1284 iter: RowIter<'a>,
1285 rowbuf: Vec<Row>,
1286 ncols: usize,
1287 current_col: usize,
1288 current_row: usize,
1289 is_finished: bool,
1290}
1291
1292impl<'a> PostgresRawSourceParser<'a> {
1293 pub fn new(iter: RowIter<'a>, schema: &[PostgresTypeSystem]) -> Self {
1295 Self {
1296 iter,
1297 rowbuf: Vec::with_capacity(DB_BUFFER_SIZE),
1298 ncols: schema.len(),
1299 current_row: 0,
1300 current_col: 0,
1301 is_finished: false,
1302 }
1303 }
1304
1305 #[throws(PostgresSourceError)]
1306 fn next_loc(&mut self) -> (usize, usize) {
1307 let ret = (self.current_row, self.current_col);
1308 self.current_row += (self.current_col + 1) / self.ncols;
1309 self.current_col = (self.current_col + 1) % self.ncols;
1310 ret
1311 }
1312}
1313
1314impl<'a> PartitionParser<'a> for PostgresRawSourceParser<'a> {
1315 type TypeSystem = PostgresTypeSystem;
1316 type Error = PostgresSourceError;
1317
1318 #[throws(PostgresSourceError)]
1319 fn fetch_next(&mut self) -> (usize, bool) {
1320 assert!(self.current_col == 0);
1321 let remaining_rows = self.rowbuf.len() - self.current_row;
1322 if remaining_rows > 0 {
1323 return (remaining_rows, self.is_finished);
1324 } else if self.is_finished {
1325 return (0, self.is_finished);
1326 }
1327
1328 if !self.rowbuf.is_empty() {
1329 self.rowbuf.drain(..);
1330 }
1331 for _ in 0..DB_BUFFER_SIZE {
1332 if let Some(row) = self.iter.next()? {
1333 self.rowbuf.push(row);
1334 } else {
1335 self.is_finished = true;
1336 break;
1337 }
1338 }
1339 self.current_row = 0;
1340 self.current_col = 0;
1341 (self.rowbuf.len(), self.is_finished)
1342 }
1343}
1344
1345macro_rules! impl_produce {
1346 ($($t: ty,)+) => {
1347 $(
1348 impl<'r, 'a> Produce<'r, $t> for PostgresRawSourceParser<'a> {
1349 type Error = PostgresSourceError;
1350
1351 #[throws(PostgresSourceError)]
1352 fn produce(&'r mut self) -> $t {
1353 let (ridx, cidx) = self.next_loc()?;
1354 let row = &self.rowbuf[ridx];
1355 let val = row.try_get(cidx)?;
1356 val
1357 }
1358 }
1359
1360 impl<'r, 'a> Produce<'r, Option<$t>> for PostgresRawSourceParser<'a> {
1361 type Error = PostgresSourceError;
1362
1363 #[throws(PostgresSourceError)]
1364 fn produce(&'r mut self) -> Option<$t> {
1365 let (ridx, cidx) = self.next_loc()?;
1366 let row = &self.rowbuf[ridx];
1367 let val = row.try_get(cidx)?;
1368 val
1369 }
1370 }
1371 )+
1372 };
1373}
1374
1375impl_produce!(
1376 i8,
1377 i16,
1378 i32,
1379 i64,
1380 u32,
1381 f32,
1382 f64,
1383 Decimal,
1384 bool,
1385 &'r str,
1386 Vec<u8>,
1387 NaiveTime,
1388 Uuid,
1389 Value,
1390 IpInet,
1391 Vector,
1392 HalfVector,
1393 Bit,
1394 SparseVector,
1395 HashMap<String, Option<String>>,
1396 Vec<Option<bool>>,
1397 Vec<Option<String>>,
1398 Vec<Option<i16>>,
1399 Vec<Option<i32>>,
1400 Vec<Option<i64>>,
1401 Vec<Option<f32>>,
1402 Vec<Option<f64>>,
1403 Vec<Option<Decimal>>,
1404);
1405
1406impl<'r> Produce<'r, DateTime<Utc>> for PostgresRawSourceParser<'_> {
1407 type Error = PostgresSourceError;
1408
1409 #[throws(PostgresSourceError)]
1410 fn produce(&'r mut self) -> DateTime<Utc> {
1411 let (ridx, cidx) = self.next_loc()?;
1412 let row = &self.rowbuf[ridx];
1413 let val: postgres::types::Timestamp<DateTime<Utc>> = row.try_get(cidx)?;
1414 match val {
1415 postgres::types::Timestamp::PosInfinity => DateTime::<Utc>::MAX_UTC,
1416 postgres::types::Timestamp::NegInfinity => DateTime::<Utc>::MIN_UTC,
1417 postgres::types::Timestamp::Value(t) => t,
1418 }
1419 }
1420}
1421
1422impl<'r> Produce<'r, Option<DateTime<Utc>>> for PostgresRawSourceParser<'_> {
1423 type Error = PostgresSourceError;
1424
1425 #[throws(PostgresSourceError)]
1426 fn produce(&'r mut self) -> Option<DateTime<Utc>> {
1427 let (ridx, cidx) = self.next_loc()?;
1428 let row = &self.rowbuf[ridx];
1429 let val = row.try_get(cidx)?;
1430 match val {
1431 Some(postgres::types::Timestamp::PosInfinity) => Some(DateTime::<Utc>::MAX_UTC),
1432 Some(postgres::types::Timestamp::NegInfinity) => Some(DateTime::<Utc>::MIN_UTC),
1433 Some(postgres::types::Timestamp::Value(t)) => t,
1434 None => None,
1435 }
1436 }
1437}
1438
1439impl<'r> Produce<'r, NaiveDateTime> for PostgresRawSourceParser<'_> {
1440 type Error = PostgresSourceError;
1441
1442 #[throws(PostgresSourceError)]
1443 fn produce(&'r mut self) -> NaiveDateTime {
1444 let (ridx, cidx) = self.next_loc()?;
1445 let row = &self.rowbuf[ridx];
1446 let val: postgres::types::Timestamp<NaiveDateTime> = row.try_get(cidx)?;
1447 match val {
1448 postgres::types::Timestamp::PosInfinity => NaiveDateTime::MAX,
1449 postgres::types::Timestamp::NegInfinity => NaiveDateTime::MIN,
1450 postgres::types::Timestamp::Value(t) => t,
1451 }
1452 }
1453}
1454
1455impl<'r> Produce<'r, Option<NaiveDateTime>> for PostgresRawSourceParser<'_> {
1456 type Error = PostgresSourceError;
1457
1458 #[throws(PostgresSourceError)]
1459 fn produce(&'r mut self) -> Option<NaiveDateTime> {
1460 let (ridx, cidx) = self.next_loc()?;
1461 let row = &self.rowbuf[ridx];
1462 let val = row.try_get(cidx)?;
1463 match val {
1464 Some(postgres::types::Timestamp::PosInfinity) => Some(NaiveDateTime::MAX),
1465 Some(postgres::types::Timestamp::NegInfinity) => Some(NaiveDateTime::MIN),
1466 Some(postgres::types::Timestamp::Value(t)) => t,
1467 None => None,
1468 }
1469 }
1470}
1471
1472impl<'r> Produce<'r, NaiveDate> for PostgresRawSourceParser<'_> {
1473 type Error = PostgresSourceError;
1474
1475 #[throws(PostgresSourceError)]
1476 fn produce(&'r mut self) -> NaiveDate {
1477 let (ridx, cidx) = self.next_loc()?;
1478 let row = &self.rowbuf[ridx];
1479 let val: postgres::types::Date<NaiveDate> = row.try_get(cidx)?;
1480 match val {
1481 postgres::types::Date::PosInfinity => NaiveDate::MAX,
1482 postgres::types::Date::NegInfinity => NaiveDate::MIN,
1483 postgres::types::Date::Value(t) => t,
1484 }
1485 }
1486}
1487
1488impl<'r> Produce<'r, Option<NaiveDate>> for PostgresRawSourceParser<'_> {
1489 type Error = PostgresSourceError;
1490
1491 #[throws(PostgresSourceError)]
1492 fn produce(&'r mut self) -> Option<NaiveDate> {
1493 let (ridx, cidx) = self.next_loc()?;
1494 let row = &self.rowbuf[ridx];
1495 let val = row.try_get(cidx)?;
1496 match val {
1497 Some(postgres::types::Date::PosInfinity) => Some(NaiveDate::MAX),
1498 Some(postgres::types::Date::NegInfinity) => Some(NaiveDate::MIN),
1499 Some(postgres::types::Date::Value(t)) => t,
1500 None => None,
1501 }
1502 }
1503}
1504
1505impl<C> SourcePartition for PostgresSourcePartition<SimpleProtocol, C>
1506where
1507 C: MakeTlsConnect<Socket> + Clone + 'static + Sync + Send,
1508 C::TlsConnect: Send,
1509 C::Stream: Send,
1510 <C::TlsConnect as TlsConnect<Socket>>::Future: Send,
1511{
1512 type TypeSystem = PostgresTypeSystem;
1513 type Parser<'a> = PostgresSimpleSourceParser;
1514 type Error = PostgresSourceError;
1515
1516 #[throws(PostgresSourceError)]
1517 fn result_rows(&mut self) {
1518 self.nrows = get_total_rows(&mut self.conn, &self.query)?;
1519 }
1520
1521 #[throws(PostgresSourceError)]
1522 fn parser(&mut self) -> Self::Parser<'_> {
1523 let rows = self.conn.simple_query(self.query.as_str())?; PostgresSimpleSourceParser::new(rows, &self.schema)
1525 }
1526
1527 fn nrows(&self) -> usize {
1528 self.nrows
1529 }
1530
1531 fn ncols(&self) -> usize {
1532 self.ncols
1533 }
1534}
1535
1536pub struct PostgresSimpleSourceParser {
1538 rows: Vec<SimpleQueryMessage>,
1539 ncols: usize,
1540 current_col: usize,
1541 current_row: usize,
1542}
1543impl PostgresSimpleSourceParser {
1544 pub fn new(rows: Vec<SimpleQueryMessage>, schema: &[PostgresTypeSystem]) -> Self {
1546 Self {
1547 rows,
1548 ncols: schema.len(),
1549 current_row: 0,
1550 current_col: 0,
1551 }
1552 }
1553
1554 #[throws(PostgresSourceError)]
1555 fn next_loc(&mut self) -> (usize, usize) {
1556 let ret = (self.current_row, self.current_col);
1557 self.current_row += (self.current_col + 1) / self.ncols;
1558 self.current_col = (self.current_col + 1) % self.ncols;
1559 ret
1560 }
1561}
1562
1563impl PartitionParser<'_> for PostgresSimpleSourceParser {
1564 type TypeSystem = PostgresTypeSystem;
1565 type Error = PostgresSourceError;
1566
1567 #[throws(PostgresSourceError)]
1568 fn fetch_next(&mut self) -> (usize, bool) {
1569 self.current_row = 0;
1570 self.current_col = 0;
1571 if !self.rows.is_empty() {
1572 if let SimpleQueryMessage::RowDescription(_) = &self.rows[0] {
1573 self.current_row = 1;
1574 }
1575 }
1576
1577 (self.rows.len() - 1 - self.current_row, true) }
1579}
1580
1581macro_rules! impl_simple_produce {
1582 ($($t: ty,)+) => {
1583 $(
1584 impl<'r> Produce<'r, $t> for PostgresSimpleSourceParser {
1585 type Error = PostgresSourceError;
1586
1587 #[throws(PostgresSourceError)]
1588 fn produce(&'r mut self) -> $t {
1589 let (ridx, cidx) = self.next_loc()?;
1590 let val = match &self.rows[ridx] {
1591 SimpleQueryMessage::Row(row) => match row.try_get(cidx)? {
1592 Some(s) => s
1593 .parse()
1594 .map_err(|_| ConnectorXError::cannot_produce::<$t>(Some(s.into())))?,
1595 None => throw!(anyhow!(
1596 "Cannot parse NULL in NOT NULL column."
1597 )),
1598 },
1599 SimpleQueryMessage::CommandComplete(c) => {
1600 panic!("get command: {}", c);
1601 }
1602 _ => {
1603 panic!("what?");
1604 }
1605 };
1606 val
1607 }
1608 }
1609
1610 impl<'r, 'a> Produce<'r, Option<$t>> for PostgresSimpleSourceParser {
1611 type Error = PostgresSourceError;
1612
1613 #[throws(PostgresSourceError)]
1614 fn produce(&'r mut self) -> Option<$t> {
1615 let (ridx, cidx) = self.next_loc()?;
1616 let val = match &self.rows[ridx] {
1617 SimpleQueryMessage::Row(row) => match row.try_get(cidx)? {
1618 Some(s) => Some(
1619 s.parse()
1620 .map_err(|_| ConnectorXError::cannot_produce::<$t>(Some(s.into())))?,
1621 ),
1622 None => None,
1623 },
1624 SimpleQueryMessage::CommandComplete(c) => {
1625 panic!("get command: {}", c);
1626 }
1627 _ => {
1628 panic!("what?");
1629 }
1630 };
1631 val
1632 }
1633 }
1634 )+
1635 };
1636}
1637
1638impl_simple_produce!(i8, i16, i32, i64, u32, f32, f64, Uuid, IpInet,);
1639
1640impl<'r> Produce<'r, bool> for PostgresSimpleSourceParser {
1641 type Error = PostgresSourceError;
1642
1643 #[throws(PostgresSourceError)]
1644 fn produce(&'r mut self) -> bool {
1645 let (ridx, cidx) = self.next_loc()?;
1646 let val = match &self.rows[ridx] {
1647 SimpleQueryMessage::Row(row) => match row.try_get(cidx)? {
1648 Some(s) => match s {
1649 "t" => true,
1650 "f" => false,
1651 _ => throw!(ConnectorXError::cannot_produce::<bool>(Some(s.into()))),
1652 },
1653 None => throw!(anyhow!("Cannot parse NULL in non-NULL column.")),
1654 },
1655 SimpleQueryMessage::CommandComplete(c) => {
1656 panic!("get command: {}", c);
1657 }
1658 _ => {
1659 panic!("what?");
1660 }
1661 };
1662 val
1663 }
1664}
1665
1666impl<'r> Produce<'r, Option<bool>> for PostgresSimpleSourceParser {
1667 type Error = PostgresSourceError;
1668
1669 #[throws(PostgresSourceError)]
1670 fn produce(&'r mut self) -> Option<bool> {
1671 let (ridx, cidx) = self.next_loc()?;
1672 let val = match &self.rows[ridx] {
1673 SimpleQueryMessage::Row(row) => match row.try_get(cidx)? {
1674 Some(s) => match s {
1675 "t" => Some(true),
1676 "f" => Some(false),
1677 _ => throw!(ConnectorXError::cannot_produce::<bool>(Some(s.into()))),
1678 },
1679 None => None,
1680 },
1681 SimpleQueryMessage::CommandComplete(c) => {
1682 panic!("get command: {}", c);
1683 }
1684 _ => {
1685 panic!("what?");
1686 }
1687 };
1688 val
1689 }
1690}
1691
1692impl<'r> Produce<'r, Decimal> for PostgresSimpleSourceParser {
1693 type Error = PostgresSourceError;
1694
1695 #[throws(PostgresSourceError)]
1696 fn produce(&'r mut self) -> Decimal {
1697 let (ridx, cidx) = self.next_loc()?;
1698 let val = match &self.rows[ridx] {
1699 SimpleQueryMessage::Row(row) => match row.try_get(cidx)? {
1700 Some("Infinity") => Decimal::MAX,
1701 Some("-Infinity") => Decimal::MIN,
1702 Some(s) => s
1703 .parse()
1704 .map_err(|_| ConnectorXError::cannot_produce::<Decimal>(Some(s.into())))?,
1705 None => throw!(anyhow!("Cannot parse NULL in NOT NULL column.")),
1706 },
1707 SimpleQueryMessage::CommandComplete(c) => {
1708 panic!("get command: {}", c);
1709 }
1710 _ => {
1711 panic!("what?");
1712 }
1713 };
1714 val
1715 }
1716}
1717
1718impl<'r> Produce<'r, Option<Decimal>> for PostgresSimpleSourceParser {
1719 type Error = PostgresSourceError;
1720
1721 #[throws(PostgresSourceError)]
1722 fn produce(&'r mut self) -> Option<Decimal> {
1723 let (ridx, cidx) = self.next_loc()?;
1724 let val = match &self.rows[ridx] {
1725 SimpleQueryMessage::Row(row) => match row.try_get(cidx)? {
1726 Some("Infinity") => Some(Decimal::MAX),
1727 Some("-Infinity") => Some(Decimal::MIN),
1728 Some(s) => Some(
1729 s.parse()
1730 .map_err(|_| ConnectorXError::cannot_produce::<Decimal>(Some(s.into())))?,
1731 ),
1732 None => None,
1733 },
1734 SimpleQueryMessage::CommandComplete(c) => {
1735 panic!("get command: {}", c);
1736 }
1737 _ => {
1738 panic!("what?");
1739 }
1740 };
1741 val
1742 }
1743}
1744
1745impl<'r> Produce<'r, &'r str> for PostgresSimpleSourceParser {
1746 type Error = PostgresSourceError;
1747
1748 #[throws(PostgresSourceError)]
1749 fn produce(&'r mut self) -> &'r str {
1750 let (ridx, cidx) = self.next_loc()?;
1751 let val = match &self.rows[ridx] {
1752 SimpleQueryMessage::Row(row) => match row.try_get(cidx)? {
1753 Some(s) => s,
1754 None => throw!(anyhow!("Cannot parse NULL in non-NULL column.")),
1755 },
1756 SimpleQueryMessage::CommandComplete(c) => {
1757 panic!("get command: {}", c);
1758 }
1759 _ => {
1760 panic!("what?");
1761 }
1762 };
1763 val
1764 }
1765}
1766
1767impl<'r> Produce<'r, Option<&'r str>> for PostgresSimpleSourceParser {
1768 type Error = PostgresSourceError;
1769
1770 #[throws(PostgresSourceError)]
1771 fn produce(&'r mut self) -> Option<&'r str> {
1772 let (ridx, cidx) = self.next_loc()?;
1773 let val = match &self.rows[ridx] {
1774 SimpleQueryMessage::Row(row) => row.try_get(cidx)?,
1775 SimpleQueryMessage::CommandComplete(c) => {
1776 panic!("get command: {}", c);
1777 }
1778 _ => {
1779 panic!("what?");
1780 }
1781 };
1782 val
1783 }
1784}
1785
1786impl<'r> Produce<'r, Vec<u8>> for PostgresSimpleSourceParser {
1787 type Error = PostgresSourceError;
1788
1789 #[throws(PostgresSourceError)]
1790 fn produce(&'r mut self) -> Vec<u8> {
1791 let (ridx, cidx) = self.next_loc()?;
1792 let val = match &self.rows[ridx] {
1793 SimpleQueryMessage::Row(row) => match row.try_get(cidx)? {
1794 Some(s) => {
1795 let mut res = s.chars();
1796 res.next();
1797 res.next();
1798 decode(
1799 res.enumerate()
1800 .fold(String::new(), |acc, (_i, c)| format!("{}{}", acc, c))
1801 .chars()
1802 .map(|c| c as u8)
1803 .collect::<Vec<u8>>(),
1804 )?
1805 }
1806 None => throw!(anyhow!("Cannot parse NULL in non-NULL column.")),
1807 },
1808 SimpleQueryMessage::CommandComplete(c) => {
1809 panic!("get command: {}", c);
1810 }
1811 _ => {
1812 panic!("what?");
1813 }
1814 };
1815 val
1816 }
1817}
1818
1819impl<'r> Produce<'r, Option<Vec<u8>>> for PostgresSimpleSourceParser {
1820 type Error = PostgresSourceError;
1821
1822 #[throws(PostgresSourceError)]
1823 fn produce(&'r mut self) -> Option<Vec<u8>> {
1824 let (ridx, cidx) = self.next_loc()?;
1825 let val = match &self.rows[ridx] {
1826 SimpleQueryMessage::Row(row) => match row.try_get(cidx)? {
1827 Some(s) => {
1828 let mut res = s.chars();
1829 res.next();
1830 res.next();
1831 Some(decode(
1832 res.enumerate()
1833 .fold(String::new(), |acc, (_i, c)| format!("{}{}", acc, c))
1834 .chars()
1835 .map(|c| c as u8)
1836 .collect::<Vec<u8>>(),
1837 )?)
1838 }
1839 None => None,
1840 },
1841 SimpleQueryMessage::CommandComplete(c) => {
1842 panic!("get command: {}", c);
1843 }
1844 _ => {
1845 panic!("what?");
1846 }
1847 };
1848 val
1849 }
1850}
1851
1852fn rem_first_and_last(value: &str) -> &str {
1853 let mut chars = value.chars();
1854 chars.next();
1855 chars.next_back();
1856 chars.as_str()
1857}
1858
1859macro_rules! impl_simple_vec_produce {
1860 ($($t: ty,)+) => {
1861 $(
1862 impl<'r> Produce<'r, Vec<Option<$t>>> for PostgresSimpleSourceParser {
1863 type Error = PostgresSourceError;
1864
1865 #[throws(PostgresSourceError)]
1866 fn produce(&'r mut self) -> Vec<Option<$t>> {
1867 let (ridx, cidx) = self.next_loc()?;
1868 let val = match &self.rows[ridx] {
1869 SimpleQueryMessage::Row(row) => match row.try_get(cidx)? {
1870 Some(s) => match s{
1871 "" => throw!(anyhow!("Cannot parse NULL in non-NULL column.")),
1872 "{}" => vec![],
1873 _ => rem_first_and_last(s).split(",").map(|v| {
1874 if v == "NULL" {
1875 Ok(None)
1876 } else {
1877 match v.parse() {
1878 Ok(v) => Ok(Some(v)),
1879 Err(e) => Err(e).map_err(|_| ConnectorXError::cannot_produce::<Vec<$t>>(Some(s.into())))
1880 }
1881 }
1882 }).collect::<Result<Vec<Option<$t>>, ConnectorXError>>()?
1883 },
1884 None => throw!(anyhow!("Cannot parse NULL in non-NULL column.")),
1885 },
1886 SimpleQueryMessage::CommandComplete(c) => {
1887 panic!("get command: {}", c);
1888 }
1889 _ => {
1890 panic!("what?");
1891 }
1892 };
1893 val
1894 }
1895 }
1896
1897 impl<'r, 'a> Produce<'r, Option<Vec<Option<$t>>>> for PostgresSimpleSourceParser {
1898 type Error = PostgresSourceError;
1899
1900 #[throws(PostgresSourceError)]
1901 fn produce(&'r mut self) -> Option<Vec<Option<$t>>> {
1902 let (ridx, cidx) = self.next_loc()?;
1903 let val = match &self.rows[ridx] {
1904
1905 SimpleQueryMessage::Row(row) => match row.try_get(cidx)? {
1906 Some(s) => match s{
1907 "" => None,
1908 "{}" => Some(vec![]),
1909 _ => Some(rem_first_and_last(s).split(",").map(|v| {
1910 if v == "NULL" {
1911 Ok(None)
1912 } else {
1913 match v.parse() {
1914 Ok(v) => Ok(Some(v)),
1915 Err(e) => Err(e).map_err(|_| ConnectorXError::cannot_produce::<Vec<$t>>(Some(s.into())))
1916 }
1917 }
1918 }).collect::<Result<Vec<Option<$t>>, ConnectorXError>>()?)
1919 },
1920 None => None,
1921 },
1922
1923 SimpleQueryMessage::CommandComplete(c) => {
1924 panic!("get command: {}", c);
1925 }
1926 _ => {
1927 panic!("what?");
1928 }
1929 };
1930 val
1931 }
1932 }
1933 )+
1934 };
1935}
1936impl_simple_vec_produce!(i16, i32, i64, f32, f64, Decimal, String,);
1937
1938impl<'r> Produce<'r, Vec<Option<bool>>> for PostgresSimpleSourceParser {
1939 type Error = PostgresSourceError;
1940
1941 #[throws(PostgresSourceError)]
1942 fn produce(&'r mut self) -> Vec<Option<bool>> {
1943 let (ridx, cidx) = self.next_loc()?;
1944 let val = match &self.rows[ridx] {
1945 SimpleQueryMessage::Row(row) => match row.try_get(cidx)? {
1946 Some(s) => match s {
1947 "" => throw!(anyhow!("Cannot parse NULL in non-NULL column.")),
1948 "{}" => vec![],
1949 _ => rem_first_and_last(s)
1950 .split(',')
1951 .map(|token| match token {
1952 "NULL" => Ok(None),
1953 "t" => Ok(Some(true)),
1954 "f" => Ok(Some(false)),
1955 _ => {
1956 throw!(ConnectorXError::cannot_produce::<Vec<bool>>(Some(s.into())))
1957 }
1958 })
1959 .collect::<Result<Vec<Option<bool>>, ConnectorXError>>()?,
1960 },
1961 None => throw!(anyhow!("Cannot parse NULL in non-NULL column.")),
1962 },
1963 SimpleQueryMessage::CommandComplete(c) => {
1964 panic!("get command: {}", c);
1965 }
1966 _ => {
1967 panic!("what?");
1968 }
1969 };
1970 val
1971 }
1972}
1973
1974impl<'r> Produce<'r, Option<Vec<Option<bool>>>> for PostgresSimpleSourceParser {
1975 type Error = PostgresSourceError;
1976
1977 #[throws(PostgresSourceError)]
1978 fn produce(&'r mut self) -> Option<Vec<Option<bool>>> {
1979 let (ridx, cidx) = self.next_loc()?;
1980 let val = match &self.rows[ridx] {
1981 SimpleQueryMessage::Row(row) => match row.try_get(cidx)? {
1982 Some(s) => match s {
1983 "" => None,
1984 "{}" => Some(vec![]),
1985 _ => Some(
1986 rem_first_and_last(s)
1987 .split(',')
1988 .map(|token| match token {
1989 "NULL" => Ok(None),
1990 "t" => Ok(Some(true)),
1991 "f" => Ok(Some(false)),
1992 _ => {
1993 throw!(ConnectorXError::cannot_produce::<Vec<bool>>(Some(
1994 s.into()
1995 )))
1996 }
1997 })
1998 .collect::<Result<Vec<Option<bool>>, ConnectorXError>>()?,
1999 ),
2000 },
2001 None => None,
2002 },
2003 SimpleQueryMessage::CommandComplete(c) => {
2004 panic!("get command: {}", c);
2005 }
2006 _ => {
2007 panic!("what?");
2008 }
2009 };
2010 val
2011 }
2012}
2013
2014impl<'r> Produce<'r, NaiveDate> for PostgresSimpleSourceParser {
2015 type Error = PostgresSourceError;
2016
2017 #[throws(PostgresSourceError)]
2018 fn produce(&'r mut self) -> NaiveDate {
2019 let (ridx, cidx) = self.next_loc()?;
2020 let val = match &self.rows[ridx] {
2021 SimpleQueryMessage::Row(row) => match row.try_get(cidx)? {
2022 Some(s) => match s {
2023 "infinity" => NaiveDate::MAX,
2024 "-infinity" => NaiveDate::MIN,
2025 s => NaiveDate::parse_from_str(s, "%Y-%m-%d").map_err(|_| {
2026 ConnectorXError::cannot_produce::<NaiveDate>(Some(s.into()))
2027 })?,
2028 },
2029 None => throw!(anyhow!("Cannot parse NULL in non-NULL column.")),
2030 },
2031 SimpleQueryMessage::CommandComplete(c) => {
2032 panic!("get command: {}", c);
2033 }
2034 _ => {
2035 panic!("what?");
2036 }
2037 };
2038 val
2039 }
2040}
2041
2042impl<'r> Produce<'r, Option<NaiveDate>> for PostgresSimpleSourceParser {
2043 type Error = PostgresSourceError;
2044
2045 #[throws(PostgresSourceError)]
2046 fn produce(&'r mut self) -> Option<NaiveDate> {
2047 let (ridx, cidx) = self.next_loc()?;
2048 let val = match &self.rows[ridx] {
2049 SimpleQueryMessage::Row(row) => match row.try_get(cidx)? {
2050 Some(s) => match s {
2051 "infinity" => Some(NaiveDate::MAX),
2052 "-infinity" => Some(NaiveDate::MIN),
2053 s => Some(NaiveDate::parse_from_str(s, "%Y-%m-%d").map_err(|_| {
2054 ConnectorXError::cannot_produce::<Option<NaiveDate>>(Some(s.into()))
2055 })?),
2056 },
2057 None => None,
2058 },
2059 SimpleQueryMessage::CommandComplete(c) => {
2060 panic!("get command: {}", c);
2061 }
2062 _ => {
2063 panic!("what?");
2064 }
2065 };
2066 val
2067 }
2068}
2069
2070impl<'r> Produce<'r, NaiveTime> for PostgresSimpleSourceParser {
2071 type Error = PostgresSourceError;
2072
2073 #[throws(PostgresSourceError)]
2074 fn produce(&'r mut self) -> NaiveTime {
2075 let (ridx, cidx) = self.next_loc()?;
2076 let val = match &self.rows[ridx] {
2077 SimpleQueryMessage::Row(row) => match row.try_get(cidx)? {
2078 Some(s) => NaiveTime::parse_from_str(s, "%H:%M:%S%.f")
2079 .map_err(|_| ConnectorXError::cannot_produce::<NaiveTime>(Some(s.into())))?,
2080 None => throw!(anyhow!("Cannot parse NULL in non-NULL column.")),
2081 },
2082 SimpleQueryMessage::CommandComplete(c) => {
2083 panic!("get command: {}", c);
2084 }
2085 _ => {
2086 panic!("what?");
2087 }
2088 };
2089 val
2090 }
2091}
2092
2093impl<'r> Produce<'r, Option<NaiveTime>> for PostgresSimpleSourceParser {
2094 type Error = PostgresSourceError;
2095
2096 #[throws(PostgresSourceError)]
2097 fn produce(&'r mut self) -> Option<NaiveTime> {
2098 let (ridx, cidx) = self.next_loc()?;
2099 let val = match &self.rows[ridx] {
2100 SimpleQueryMessage::Row(row) => match row.try_get(cidx)? {
2101 Some(s) => Some(NaiveTime::parse_from_str(s, "%H:%M:%S%.f").map_err(|_| {
2102 ConnectorXError::cannot_produce::<Option<NaiveTime>>(Some(s.into()))
2103 })?),
2104 None => None,
2105 },
2106 SimpleQueryMessage::CommandComplete(c) => {
2107 panic!("get command: {}", c);
2108 }
2109 _ => {
2110 panic!("what?");
2111 }
2112 };
2113 val
2114 }
2115}
2116
2117impl<'r> Produce<'r, NaiveDateTime> for PostgresSimpleSourceParser {
2118 type Error = PostgresSourceError;
2119
2120 #[throws(PostgresSourceError)]
2121 fn produce(&'r mut self) -> NaiveDateTime {
2122 let (ridx, cidx) = self.next_loc()?;
2123 let val =
2124 match &self.rows[ridx] {
2125 SimpleQueryMessage::Row(row) => match row.try_get(cidx)? {
2126 Some(s) => match s {
2127 "infinity" => NaiveDateTime::MAX,
2128 "-infinity" => NaiveDateTime::MIN,
2129 s => NaiveDateTime::parse_from_str(s, "%Y-%m-%d %H:%M:%S%.f").map_err(
2130 |_| ConnectorXError::cannot_produce::<NaiveDateTime>(Some(s.into())),
2131 )?,
2132 },
2133 None => throw!(anyhow!("Cannot parse NULL in non-NULL column.")),
2134 },
2135 SimpleQueryMessage::CommandComplete(c) => {
2136 panic!("get command: {}", c);
2137 }
2138 _ => {
2139 panic!("what?");
2140 }
2141 };
2142 val
2143 }
2144}
2145
2146impl<'r> Produce<'r, Option<NaiveDateTime>> for PostgresSimpleSourceParser {
2147 type Error = PostgresSourceError;
2148
2149 #[throws(PostgresSourceError)]
2150 fn produce(&'r mut self) -> Option<NaiveDateTime> {
2151 let (ridx, cidx) = self.next_loc()?;
2152 let val = match &self.rows[ridx] {
2153 SimpleQueryMessage::Row(row) => match row.try_get(cidx)? {
2154 Some(s) => match s {
2155 "infinity" => Some(NaiveDateTime::MAX),
2156 "-infinity" => Some(NaiveDateTime::MIN),
2157 s => Some(
2158 NaiveDateTime::parse_from_str(s, "%Y-%m-%d %H:%M:%S%.f").map_err(|_| {
2159 ConnectorXError::cannot_produce::<Option<NaiveDateTime>>(Some(s.into()))
2160 })?,
2161 ),
2162 },
2163 None => None,
2164 },
2165 SimpleQueryMessage::CommandComplete(c) => {
2166 panic!("get command: {}", c);
2167 }
2168 _ => {
2169 panic!("what?");
2170 }
2171 };
2172 val
2173 }
2174}
2175
2176impl<'r> Produce<'r, DateTime<Utc>> for PostgresSimpleSourceParser {
2177 type Error = PostgresSourceError;
2178
2179 #[throws(PostgresSourceError)]
2180 fn produce(&'r mut self) -> DateTime<Utc> {
2181 let (ridx, cidx) = self.next_loc()?;
2182 let val = match &self.rows[ridx] {
2183 SimpleQueryMessage::Row(row) => match row.try_get(cidx)? {
2184 Some("infinity") => DateTime::<Utc>::MAX_UTC,
2185 Some("-infinity") => DateTime::<Utc>::MIN_UTC,
2186 Some(s) => {
2187 let time_string = format!("{}:00", s).to_owned();
2188 let slice: &str = &time_string[..];
2189 let time: DateTime<FixedOffset> =
2190 DateTime::parse_from_str(slice, "%Y-%m-%d %H:%M:%S%.f%:z").unwrap();
2191
2192 time.with_timezone(&Utc)
2193 }
2194 None => throw!(anyhow!("Cannot parse NULL in non-NULL column.")),
2195 },
2196 SimpleQueryMessage::CommandComplete(c) => {
2197 panic!("get command: {}", c);
2198 }
2199 _ => {
2200 panic!("what?");
2201 }
2202 };
2203 val
2204 }
2205}
2206
2207impl<'r> Produce<'r, Option<DateTime<Utc>>> for PostgresSimpleSourceParser {
2208 type Error = PostgresSourceError;
2209
2210 #[throws(PostgresSourceError)]
2211 fn produce(&'r mut self) -> Option<DateTime<Utc>> {
2212 let (ridx, cidx) = self.next_loc()?;
2213 let val = match &self.rows[ridx] {
2214 SimpleQueryMessage::Row(row) => match row.try_get(cidx)? {
2215 Some("infinity") => Some(DateTime::<Utc>::MAX_UTC),
2216 Some("-infinity") => Some(DateTime::<Utc>::MIN_UTC),
2217 Some(s) => {
2218 let time_string = format!("{}:00", s).to_owned();
2219 let slice: &str = &time_string[..];
2220 let time: DateTime<FixedOffset> =
2221 DateTime::parse_from_str(slice, "%Y-%m-%d %H:%M:%S%.f%:z").unwrap();
2222
2223 Some(time.with_timezone(&Utc))
2224 }
2225 None => None,
2226 },
2227 SimpleQueryMessage::CommandComplete(c) => {
2228 panic!("get command: {}", c);
2229 }
2230 _ => {
2231 panic!("what?");
2232 }
2233 };
2234 val
2235 }
2236}