1use std::{collections::HashMap, marker::PhantomData, sync::Arc};
2
3use chrono::{NaiveDate, NaiveDateTime, NaiveTime};
4use fehler::{throw, throws};
5use prusto::{auth::Auth, Client, ClientBuilder, DataSet, Presto, Row};
6use serde_json::Value;
7use sqlparser::dialect::{Dialect, GenericDialect};
8use std::convert::TryFrom;
9use tokio::runtime::Runtime;
10
11use crate::{
12 data_order::DataOrder,
13 errors::ConnectorXError,
14 sources::Produce,
15 sql::{count_query, limit0_query, CXQuery},
16};
17
18pub use self::{errors::TrinoSourceError, typesystem::TrinoTypeSystem};
19use urlencoding::decode;
20
21use super::{PartitionParser, Source, SourcePartition};
22
23use anyhow::anyhow;
24
25pub mod errors;
27pub mod typesystem;
29
30#[throws(TrinoSourceError)]
31fn get_total_rows(rt: Arc<Runtime>, client: Arc<Client>, query: &CXQuery<String>) -> usize {
32 let cquery = count_query(query, &TrinoDialect {})?;
33
34 let row = rt
35 .block_on(client.get_all::<Row>(cquery.to_string()))
36 .map_err(TrinoSourceError::PrustoError)?
37 .split()
38 .1[0]
39 .clone();
40
41 let value = row
42 .value()
43 .first()
44 .ok_or_else(|| anyhow!("Trino count dataset is empty"))?;
45
46 value
47 .as_i64()
48 .ok_or_else(|| anyhow!("Trino cannot parse i64"))? as usize
49}
50
51pub use self::partition_query::TrinoPartitionQueryResult;
52
53#[allow(missing_docs)]
56mod partition_query {
57 use prusto::Presto;
58
59 #[derive(Presto, Debug)]
61 pub struct TrinoPartitionQueryResult {
62 pub _col0: i64,
64 pub _col1: i64,
66 }
67}
68
69#[derive(Debug)]
71pub struct TrinoDialect {}
72
73impl Dialect for TrinoDialect {
75 fn is_identifier_start(&self, ch: char) -> bool {
76 ch.is_ascii_lowercase() || ch.is_ascii_uppercase()
77 }
78
79 fn is_identifier_part(&self, ch: char) -> bool {
80 ch.is_ascii_lowercase() || ch.is_ascii_uppercase() || ch.is_ascii_digit() || ch == '_'
81 }
82}
83
84pub struct TrinoSource {
86 client: Arc<Client>,
87 rt: Arc<Runtime>,
88 origin_query: Option<String>,
89 queries: Vec<CXQuery<String>>,
90 names: Vec<String>,
91 schema: Vec<TrinoTypeSystem>,
92}
93
94#[throws(TrinoSourceError)]
101fn credentials_from_url(url: &url::Url) -> (String, Option<String>) {
102 let username = match url.username() {
103 "" => "connectorx".to_owned(),
104 username => decode(username)?.into_owned(),
105 };
106
107 let password = match url.password() {
108 None => None,
109 Some(password) => Some(decode(password)?.into_owned()),
110 };
111
112 (username, password)
113}
114
115#[throws(TrinoSourceError)]
116fn catalog_from_url(url: &url::Url) -> String {
117 match url.path_segments().and_then(|mut s| s.next_back()) {
118 Some(segment) => decode(segment)?.into_owned(),
119 None => "hive".to_owned(),
120 }
121}
122
123fn host_from_url(url: &url::Url) -> &str {
124 url.host_str().unwrap_or("localhost")
125}
126
127#[throws(TrinoSourceError)]
133pub fn build_client_from_url(url: &url::Url) -> Client {
134 let (username, password) = credentials_from_url(url)?;
135
136 let no_verify = url
137 .query_pairs()
138 .any(|(k, v)| k == "verify" && v == "false");
139
140 let catalog = catalog_from_url(url)?;
141
142 let mut builder = ClientBuilder::new(&username, host_from_url(url).to_owned())
143 .port(url.port().unwrap_or(8080))
144 .ssl(prusto::ssl::Ssl { root_cert: None })
145 .no_verify(no_verify)
146 .secure(url.scheme() == "trino+https")
147 .catalog(&catalog);
148
149 let mut session_props: HashMap<String, String> = HashMap::new();
150 let mut extra_creds: HashMap<String, String> = HashMap::new();
151
152 for (key, value) in url.query_pairs() {
153 match key.as_ref() {
154 "source" => builder = builder.source(value.as_ref()),
155 "schema" => builder = builder.schema(value.as_ref()),
156 "client_tags" => {
157 for tag in value.split(',') {
158 let tag = tag.trim();
159 if !tag.is_empty() {
160 builder = builder.client_tag(tag);
161 }
162 }
163 }
164 "client_info" => builder = builder.client_info(value.as_ref()),
165 "trace_token" => builder = builder.trace_token(value.as_ref()),
166 k if k.starts_with("session.") => {
167 if let Some(prop) = k.strip_prefix("session.").filter(|s| !s.is_empty()) {
168 session_props.insert(prop.to_string(), value.to_string());
169 }
170 }
171 k if k.starts_with("extra_credential.") => {
172 if let Some(cred) = k
173 .strip_prefix("extra_credential.")
174 .filter(|s| !s.is_empty())
175 {
176 extra_creds.insert(cred.to_string(), value.to_string());
177 }
178 }
179 _ => {}
180 }
181 }
182
183 if !session_props.is_empty() {
184 builder = builder.properties(session_props);
185 }
186 if !extra_creds.is_empty() {
187 builder = builder.extra_credentials(extra_creds);
188 }
189
190 let builder = match password {
191 None => builder,
192 Some(password) => builder.auth(Auth::Basic(username, Some(password))),
193 };
194
195 builder.build().map_err(TrinoSourceError::PrustoError)?
196}
197
198impl TrinoSource {
199 #[throws(TrinoSourceError)]
201 pub fn new(rt: Arc<Runtime>, conn: &str) -> Self {
202 let url = conn
207 .parse::<url::Url>()
208 .map_err(TrinoSourceError::UrlParseError)?;
209
210 let client = build_client_from_url(&url)?;
211
212 Self {
213 client: Arc::new(client),
214 rt,
215 origin_query: None,
216 queries: vec![],
217 names: vec![],
218 schema: vec![],
219 }
220 }
221}
222
223impl Source for TrinoSource
224where
225 TrinoSourcePartition: SourcePartition<TypeSystem = TrinoTypeSystem, Error = TrinoSourceError>,
226{
227 const DATA_ORDERS: &'static [DataOrder] = &[DataOrder::RowMajor];
228 type TypeSystem = TrinoTypeSystem;
229 type Partition = TrinoSourcePartition;
230 type Error = TrinoSourceError;
231
232 #[throws(TrinoSourceError)]
233 fn set_data_order(&mut self, data_order: DataOrder) {
234 if !matches!(data_order, DataOrder::RowMajor) {
235 throw!(ConnectorXError::UnsupportedDataOrder(data_order));
236 }
237 }
238
239 fn set_queries<Q: ToString>(&mut self, queries: &[CXQuery<Q>]) {
240 self.queries = queries.iter().map(|q| q.map(Q::to_string)).collect();
241 }
242
243 fn set_origin_query(&mut self, query: Option<String>) {
244 self.origin_query = query;
245 }
246
247 #[throws(TrinoSourceError)]
248 fn fetch_metadata(&mut self) {
249 assert!(!self.queries.is_empty());
250
251 let first_query = &self.queries[0];
252 let cxq = limit0_query(first_query, &GenericDialect {})?;
253
254 let dataset: DataSet<Row> = self
255 .rt
256 .block_on(self.client.get_all::<Row>(cxq.to_string()))
257 .map_err(TrinoSourceError::PrustoError)?;
258
259 let schema = dataset.split().0;
260
261 for (name, t) in schema {
262 self.names.push(name.clone());
263 self.schema.push(TrinoTypeSystem::try_from(t.clone())?);
264 }
265 }
266
267 #[throws(TrinoSourceError)]
268 fn result_rows(&mut self) -> Option<usize> {
269 match &self.origin_query {
270 Some(q) => {
271 let cxq = CXQuery::Naked(q.clone());
272 let nrows = get_total_rows(self.rt.clone(), self.client.clone(), &cxq)?;
273 Some(nrows)
274 }
275 None => None,
276 }
277 }
278
279 fn names(&self) -> Vec<String> {
280 self.names.clone()
281 }
282
283 fn schema(&self) -> Vec<Self::TypeSystem> {
284 self.schema.clone()
285 }
286
287 #[throws(TrinoSourceError)]
288 fn partition(self) -> Vec<Self::Partition> {
289 let mut ret = vec![];
290
291 for query in self.queries {
292 ret.push(TrinoSourcePartition::new(
293 self.client.clone(),
294 query,
295 self.schema.clone(),
296 self.rt.clone(),
297 )?);
298 }
299 ret
300 }
301}
302
303pub struct TrinoSourcePartition {
305 client: Arc<Client>,
306 query: CXQuery<String>,
307 schema: Vec<TrinoTypeSystem>,
308 rt: Arc<Runtime>,
309 nrows: usize,
310}
311
312impl TrinoSourcePartition {
313 #[throws(TrinoSourceError)]
315 pub fn new(
316 client: Arc<Client>,
317 query: CXQuery<String>,
318 schema: Vec<TrinoTypeSystem>,
319 rt: Arc<Runtime>,
320 ) -> Self {
321 Self {
322 client,
323 query: query.clone(),
324 schema: schema.to_vec(),
325 rt,
326 nrows: 0,
327 }
328 }
329}
330
331impl SourcePartition for TrinoSourcePartition {
332 type TypeSystem = TrinoTypeSystem;
333 type Parser<'a> = TrinoSourcePartitionParser<'a>;
334 type Error = TrinoSourceError;
335
336 #[throws(TrinoSourceError)]
337 fn result_rows(&mut self) {
338 self.nrows = get_total_rows(self.rt.clone(), self.client.clone(), &self.query)?;
339 }
340
341 #[throws(TrinoSourceError)]
342 fn parser(&mut self) -> Self::Parser<'_> {
343 TrinoSourcePartitionParser::new(
344 self.rt.clone(),
345 self.client.clone(),
346 self.query.clone(),
347 &self.schema,
348 )?
349 }
350
351 fn nrows(&self) -> usize {
352 self.nrows
353 }
354
355 fn ncols(&self) -> usize {
356 self.schema.len()
357 }
358}
359
360pub struct TrinoSourcePartitionParser<'a> {
362 rt: Arc<Runtime>,
363 client: Arc<Client>,
364 next_uri: Option<String>,
365 rows: Vec<Row>,
366 ncols: usize,
367 current_col: usize,
368 current_row: usize,
369 _phantom: &'a PhantomData<DataSet<Row>>,
370}
371
372impl<'a> TrinoSourcePartitionParser<'a> {
373 #[throws(TrinoSourceError)]
375 pub fn new(
376 rt: Arc<Runtime>,
377 client: Arc<Client>,
378 query: CXQuery,
379 schema: &[TrinoTypeSystem],
380 ) -> Self {
381 let results = rt
382 .block_on(client.get::<Row>(query.to_string()))
383 .map_err(TrinoSourceError::PrustoError)?;
384
385 let rows = match results.data_set {
386 Some(x) => x.into_vec(),
387 _ => vec![],
388 };
389
390 Self {
391 rt,
392 client,
393 next_uri: results.next_uri,
394 rows,
395 ncols: schema.len(),
396 current_row: 0,
397 current_col: 0,
398 _phantom: &PhantomData,
399 }
400 }
401
402 #[throws(TrinoSourceError)]
403 fn next_loc(&mut self) -> (usize, usize) {
404 let ret = (self.current_row, self.current_col);
405 self.current_row += (self.current_col + 1) / self.ncols;
406 self.current_col = (self.current_col + 1) % self.ncols;
407 ret
408 }
409}
410
411impl<'a> PartitionParser<'a> for TrinoSourcePartitionParser<'a> {
412 type TypeSystem = TrinoTypeSystem;
413 type Error = TrinoSourceError;
414
415 #[throws(TrinoSourceError)]
416 fn fetch_next(&mut self) -> (usize, bool) {
417 assert!(self.current_col == 0);
418
419 match self.next_uri.clone() {
420 Some(uri) => {
421 let results = self
422 .rt
423 .block_on(self.client.get_next::<Row>(&uri))
424 .map_err(TrinoSourceError::PrustoError)?;
425
426 self.rows = match results.data_set {
427 Some(x) => x.into_vec(),
428 _ => vec![],
429 };
430
431 self.current_row = 0;
432 self.next_uri = results.next_uri;
433
434 (self.rows.len(), false)
435 }
436 None => return (self.rows.len(), true),
437 }
438 }
439}
440
441macro_rules! impl_produce_int {
442 ($($t: ty,)+) => {
443 $(
444 impl<'r, 'a> Produce<'r, $t> for TrinoSourcePartitionParser<'a> {
445 type Error = TrinoSourceError;
446
447 #[throws(TrinoSourceError)]
448 fn produce(&'r mut self) -> $t {
449 let (ridx, cidx) = self.next_loc()?;
450 let value = &self.rows[ridx].value()[cidx];
451
452 match value {
453 Value::Number(x) => {
454 if (x.is_i64()) {
455 <$t>::try_from(x.as_i64().unwrap()).map_err(|_| anyhow!("Trino cannot parse i64 at position: ({}, {}) {:?}", ridx, cidx, value))?
456 } else {
457 throw!(anyhow!("Trino cannot parse Number at position: ({}, {}) {:?}", ridx, cidx, x))
458 }
459 }
460 _ => throw!(anyhow!("Trino cannot parse Number at position: ({}, {}) {:?}", ridx, cidx, value))
461 }
462 }
463 }
464
465 impl<'r, 'a> Produce<'r, Option<$t>> for TrinoSourcePartitionParser<'a> {
466 type Error = TrinoSourceError;
467
468 #[throws(TrinoSourceError)]
469 fn produce(&'r mut self) -> Option<$t> {
470 let (ridx, cidx) = self.next_loc()?;
471 let value = &self.rows[ridx].value()[cidx];
472
473 match value {
474 Value::Null => None,
475 Value::Number(x) => {
476 if (x.is_i64()) {
477 Some(<$t>::try_from(x.as_i64().unwrap()).map_err(|_| anyhow!("Trino cannot parse i64 at position: ({}, {}) {:?}", ridx, cidx, value))?)
478 } else {
479 throw!(anyhow!("Trino cannot parse Number at position: ({}, {}) {:?}", ridx, cidx, x))
480 }
481 }
482 _ => throw!(anyhow!("Trino cannot parse Number at position: ({}, {}) {:?}", ridx, cidx, value))
483 }
484 }
485 }
486 )+
487 };
488}
489
490macro_rules! impl_produce_float {
491 ($($t: ty,)+) => {
492 $(
493 impl<'r, 'a> Produce<'r, $t> for TrinoSourcePartitionParser<'a> {
494 type Error = TrinoSourceError;
495
496 #[throws(TrinoSourceError)]
497 fn produce(&'r mut self) -> $t {
498 let (ridx, cidx) = self.next_loc()?;
499 let value = &self.rows[ridx].value()[cidx];
500
501 match value {
502 Value::Number(x) => {
503 if (x.is_f64()) {
504 x.as_f64().unwrap() as $t
505 } else {
506 throw!(anyhow!("Trino cannot parse Number at position: ({}, {}) {:?}", ridx, cidx, x))
507 }
508 }
509 Value::String(x) => x.parse::<$t>().map_err(|_| anyhow!("Trino cannot parse String at position: ({}, {}) {:?}", ridx, cidx, value))?,
510 _ => throw!(anyhow!("Trino cannot parse Number at position: ({}, {}) {:?}", ridx, cidx, value))
511 }
512 }
513 }
514
515 impl<'r, 'a> Produce<'r, Option<$t>> for TrinoSourcePartitionParser<'a> {
516 type Error = TrinoSourceError;
517
518 #[throws(TrinoSourceError)]
519 fn produce(&'r mut self) -> Option<$t> {
520 let (ridx, cidx) = self.next_loc()?;
521 let value = &self.rows[ridx].value()[cidx];
522
523 match value {
524 Value::Null => None,
525 Value::Number(x) => {
526 if (x.is_f64()) {
527 Some(x.as_f64().unwrap() as $t)
528 } else {
529 throw!(anyhow!("Trino cannot parse Number at position: ({}, {}) {:?}", ridx, cidx, x))
530 }
531 }
532 Value::String(x) => Some(x.parse::<$t>().map_err(|_| anyhow!("Trino cannot parse String at position: ({}, {}) {:?}", ridx, cidx, value))?),
533 _ => throw!(anyhow!("Trino cannot parse Number at position: ({}, {}) {:?}", ridx, cidx, value))
534 }
535 }
536 }
537 )+
538 };
539}
540
541macro_rules! impl_produce_text {
542 ($($t: ty,)+) => {
543 $(
544 impl<'r, 'a> Produce<'r, $t> for TrinoSourcePartitionParser<'a> {
545 type Error = TrinoSourceError;
546
547 #[throws(TrinoSourceError)]
548 fn produce(&'r mut self) -> $t {
549 let (ridx, cidx) = self.next_loc()?;
550 let value = &self.rows[ridx].value()[cidx];
551
552 match value {
553 Value::String(x) => {
554 x.parse().map_err(|_| anyhow!("Trino cannot parse String at position: ({}, {}): {:?}", ridx, cidx, value))?
555 }
556 Value::Array(_) | Value::Object(_) | Value::Number(_) | Value::Bool(_) => {
557 serde_json::to_string(value)
558 .unwrap_or_else(|_| value.to_string())
559 .parse()
560 .map_err(|_| anyhow!("Trino cannot convert complex value at ({}, {}): {:?}", ridx, cidx, value))?
561 }
562 _ => throw!(anyhow!("Trino unknown value at position: ({}, {}): {:?}", ridx, cidx, value))
563 }
564 }
565 }
566
567 impl<'r, 'a> Produce<'r, Option<$t>> for TrinoSourcePartitionParser<'a> {
568 type Error = TrinoSourceError;
569
570 #[throws(TrinoSourceError)]
571 fn produce(&'r mut self) -> Option<$t> {
572 let (ridx, cidx) = self.next_loc()?;
573 let value = &self.rows[ridx].value()[cidx];
574
575 match value {
576 Value::Null => None,
577 Value::String(x) => {
578 Some(x.parse().map_err(|_| anyhow!("Trino cannot parse String at position: ({}, {}): {:?}", ridx, cidx, value))?)
579 }
580 Value::Array(_) | Value::Object(_) | Value::Number(_) | Value::Bool(_) => {
581 Some(serde_json::to_string(value)
582 .unwrap_or_else(|_| value.to_string())
583 .parse()
584 .map_err(|_| anyhow!("Trino cannot convert complex value at ({}, {}): {:?}", ridx, cidx, value))?)
585 }
586 }
587 }
588 }
589 )+
590 };
591}
592
593macro_rules! impl_produce_timestamp {
594 ($($t: ty,)+) => {
595 $(
596 impl<'r, 'a> Produce<'r, $t> for TrinoSourcePartitionParser<'a> {
597 type Error = TrinoSourceError;
598
599 #[throws(TrinoSourceError)]
600 fn produce(&'r mut self) -> $t {
601 let (ridx, cidx) = self.next_loc()?;
602 let value = &self.rows[ridx].value()[cidx];
603
604 match value {
605 Value::String(x) => NaiveDateTime::parse_from_str(x, "%Y-%m-%d %H:%M:%S%.f").map_err(|_| anyhow!("Trino cannot parse String at position: ({}, {}): {:?}", ridx, cidx, value))?,
606 _ => throw!(anyhow!("Trino unknown value at position: ({}, {}): {:?}", ridx, cidx, value))
607 }
608 }
609 }
610
611 impl<'r, 'a> Produce<'r, Option<$t>> for TrinoSourcePartitionParser<'a> {
612 type Error = TrinoSourceError;
613
614 #[throws(TrinoSourceError)]
615 fn produce(&'r mut self) -> Option<$t> {
616 let (ridx, cidx) = self.next_loc()?;
617 let value = &self.rows[ridx].value()[cidx];
618
619 match value {
620 Value::Null => None,
621 Value::String(x) => Some(NaiveDateTime::parse_from_str(x, "%Y-%m-%d %H:%M:%S%.f").map_err(|_| anyhow!("Trino cannot parse String at position: ({}, {}): {:?}", ridx, cidx, value))?),
622 _ => throw!(anyhow!("Trino unknown value at position: ({}, {}): {:?}", ridx, cidx, value))
623 }
624 }
625 }
626 )+
627 };
628}
629
630macro_rules! impl_produce_bool {
631 ($($t: ty,)+) => {
632 $(
633 impl<'r, 'a> Produce<'r, $t> for TrinoSourcePartitionParser<'a> {
634 type Error = TrinoSourceError;
635
636 #[throws(TrinoSourceError)]
637 fn produce(&'r mut self) -> $t {
638 let (ridx, cidx) = self.next_loc()?;
639 let value = &self.rows[ridx].value()[cidx];
640
641 match value {
642 Value::Bool(x) => *x,
643 _ => throw!(anyhow!("Trino unknown value at position: ({}, {}): {:?}", ridx, cidx, value))
644 }
645 }
646 }
647
648 impl<'r, 'a> Produce<'r, Option<$t>> for TrinoSourcePartitionParser<'a> {
649 type Error = TrinoSourceError;
650
651 #[throws(TrinoSourceError)]
652 fn produce(&'r mut self) -> Option<$t> {
653 let (ridx, cidx) = self.next_loc()?;
654 let value = &self.rows[ridx].value()[cidx];
655
656 match value {
657 Value::Null => None,
658 Value::Bool(x) => Some(*x),
659 _ => throw!(anyhow!("Trino unknown value at position: ({}, {}): {:?}", ridx, cidx, value))
660 }
661 }
662 }
663 )+
664 };
665}
666
667impl_produce_bool!(bool,);
668impl_produce_int!(i8, i16, i32, i64,);
669impl_produce_float!(f32, f64,);
670impl_produce_timestamp!(NaiveDateTime,);
671impl_produce_text!(String, char,);
672
673impl<'r, 'a> Produce<'r, NaiveTime> for TrinoSourcePartitionParser<'a> {
674 type Error = TrinoSourceError;
675
676 #[throws(TrinoSourceError)]
677 fn produce(&'r mut self) -> NaiveTime {
678 let (ridx, cidx) = self.next_loc()?;
679 let value = &self.rows[ridx].value()[cidx];
680
681 match value {
682 Value::String(x) => NaiveTime::parse_from_str(x, "%H:%M:%S%.f").map_err(|_| {
683 anyhow!(
684 "Trino cannot parse String at position: ({}, {}): {:?}",
685 ridx,
686 cidx,
687 value
688 )
689 })?,
690 _ => throw!(anyhow!(
691 "Trino unknown value at position: ({}, {}): {:?}",
692 ridx,
693 cidx,
694 value
695 )),
696 }
697 }
698}
699
700impl<'r, 'a> Produce<'r, Option<NaiveTime>> for TrinoSourcePartitionParser<'a> {
701 type Error = TrinoSourceError;
702
703 #[throws(TrinoSourceError)]
704 fn produce(&'r mut self) -> Option<NaiveTime> {
705 let (ridx, cidx) = self.next_loc()?;
706 let value = &self.rows[ridx].value()[cidx];
707
708 match value {
709 Value::Null => None,
710 Value::String(x) => {
711 Some(NaiveTime::parse_from_str(x, "%H:%M:%S%.f").map_err(|_| {
712 anyhow!(
713 "Trino cannot parse Time at position: ({}, {}): {:?}",
714 ridx,
715 cidx,
716 value
717 )
718 })?)
719 }
720 _ => throw!(anyhow!(
721 "Trino unknown value at position: ({}, {}): {:?}",
722 ridx,
723 cidx,
724 value
725 )),
726 }
727 }
728}
729
730impl<'r, 'a> Produce<'r, NaiveDate> for TrinoSourcePartitionParser<'a> {
731 type Error = TrinoSourceError;
732
733 #[throws(TrinoSourceError)]
734 fn produce(&'r mut self) -> NaiveDate {
735 let (ridx, cidx) = self.next_loc()?;
736 let value = &self.rows[ridx].value()[cidx];
737
738 match value {
739 Value::String(x) => NaiveDate::parse_from_str(x, "%Y-%m-%d").map_err(|_| {
740 anyhow!(
741 "Trino cannot parse Date at position: ({}, {}): {:?}",
742 ridx,
743 cidx,
744 value
745 )
746 })?,
747 _ => throw!(anyhow!(
748 "Trino unknown value at position: ({}, {}): {:?}",
749 ridx,
750 cidx,
751 value
752 )),
753 }
754 }
755}
756
757impl<'r, 'a> Produce<'r, Option<NaiveDate>> for TrinoSourcePartitionParser<'a> {
758 type Error = TrinoSourceError;
759
760 #[throws(TrinoSourceError)]
761 fn produce(&'r mut self) -> Option<NaiveDate> {
762 let (ridx, cidx) = self.next_loc()?;
763 let value = &self.rows[ridx].value()[cidx];
764
765 match value {
766 Value::Null => None,
767 Value::String(x) => Some(NaiveDate::parse_from_str(x, "%Y-%m-%d").map_err(|_| {
768 anyhow!(
769 "Trino cannot parse Date at position: ({}, {}): {:?}",
770 ridx,
771 cidx,
772 value
773 )
774 })?),
775 _ => throw!(anyhow!(
776 "Trino unknown value at position: ({}, {}): {:?}",
777 ridx,
778 cidx,
779 value
780 )),
781 }
782 }
783}
784
785#[cfg(test)]
786pub(crate) mod fake_server;
787
788#[cfg(all(test, feature = "dst_arrow"))]
789mod fake_server_tests;
790
791#[cfg(test)]
792mod tests {
793 use super::*;
794
795 #[test]
796 fn test_new_with_all_params() {
797 let rt = Arc::new(Runtime::new().unwrap());
798 let conn = "trino+https://myuser:mypass@localhost:8443/mycatalog?\
799 source=connectorx-test&schema=myschema&\
800 client_tags=tag1,tag2,tag3&client_info=test-run&\
801 trace_token=abc123&\
802 session.query_max_execution_time=10m&\
803 extra_credential.token=secret123&verify=false";
804 assert!(TrinoSource::new(rt, conn).is_ok());
805 }
806
807 #[test]
808 fn test_new_minimal_url() {
809 let rt = Arc::new(Runtime::new().unwrap());
810 assert!(TrinoSource::new(rt, "trino://test@localhost:8080/memory").is_ok());
811 }
812
813 #[test]
814 fn catalog_is_percent_decoded() {
815 let url = "trino://test@localhost:8080/my%5Fcatalog"
816 .parse::<url::Url>()
817 .unwrap();
818
819 assert_eq!(catalog_from_url(&url).unwrap(), "my_catalog");
820 }
821
822 #[test]
823 fn catalog_defaults_to_hive_without_path_segments() {
824 let url = "trino:memory".parse::<url::Url>().unwrap();
825
826 assert_eq!(catalog_from_url(&url).unwrap(), "hive");
827 }
828
829 #[test]
830 fn hostless_url_defaults_to_localhost() {
831 let url = "trino:///memory".parse::<url::Url>().unwrap();
832
833 assert_eq!(host_from_url(&url), "localhost");
834 }
835
836 #[test]
837 fn test_new_ignores_empty_keys() {
838 let rt = Arc::new(Runtime::new().unwrap());
839 let conn = "trino://test@localhost:8080/memory?session.=val&extra_credential.=x";
840 assert!(TrinoSource::new(rt, conn).is_ok());
841 }
842
843 #[test]
847 fn credentials_are_percent_decoded() {
848 for (encoded, expected) in [
849 ("p%40ss", "p@ss"),
850 ("pa%3Ass", "pa:ss"),
851 ("pa%2Fss", "pa/ss"),
852 ("pa%23ss", "pa#ss"),
853 ("pa%3Fss", "pa?ss"),
854 ("pa%20ss", "pa ss"),
855 ("plain", "plain"),
856 ] {
857 let url = format!("trino+https://me:{encoded}@localhost:8443/hive")
858 .parse::<url::Url>()
859 .unwrap();
860 let (username, password) = credentials_from_url(&url).unwrap();
861
862 assert_eq!(username, "me");
863 assert_eq!(password.as_deref(), Some(expected), "for {encoded}");
864 }
865 }
866
867 #[test]
870 fn username_is_percent_decoded() {
871 let url = "trino+https://svc%2Dname:pw@localhost:8443/hive"
872 .parse::<url::Url>()
873 .unwrap();
874 let (username, _) = credentials_from_url(&url).unwrap();
875
876 assert_eq!(username, "svc-name");
877 }
878
879 #[test]
881 fn credentials_default_without_userinfo() {
882 let url = "trino://localhost:8080/memory".parse::<url::Url>().unwrap();
883 let (username, password) = credentials_from_url(&url).unwrap();
884
885 assert_eq!(username, "connectorx");
886 assert_eq!(password, None);
887 }
888}