1#![cfg_attr(
5 not(any(
6 feature = "src_postgres",
7 feature = "src_sqlite",
8 feature = "src_mysql",
9 feature = "src_mssql_common",
10 feature = "src_oracle",
11 feature = "src_bigquery",
12 feature = "src_trino",
13 feature = "src_clickhouse",
14 )),
15 allow(unused_imports, unused_variables, unreachable_code)
16)]
17
18use std::convert::TryFrom;
19#[cfg(feature = "src_clickhouse")]
20use std::sync::Arc;
21
22use crate::errors::{ConnectorXOutError, OutResult};
23use crate::source_router::{SourceConn, SourceType};
24#[cfg(feature = "src_bigquery")]
25use crate::sources::bigquery::BigQueryDialect;
26#[cfg(feature = "src_clickhouse")]
27use crate::sources::clickhouse::{ClickHouseSource, ClickHouseSourceError};
28#[cfg(feature = "src_mssql_tiberius")]
29use crate::sources::mssql::{mssql_config, FloatN, IntN, MsSQLTypeSystem};
30#[cfg(feature = "src_mysql")]
31use crate::sources::mysql::{build_opts, MySQLTypeSystem};
32#[cfg(feature = "src_oracle")]
33use crate::sources::oracle::{OracleDialect, OracleSource};
34#[cfg(feature = "src_postgres")]
35use crate::sources::postgres::{rewrite_tls_args, PostgresTypeSystem};
36#[cfg(feature = "src_trino")]
37use crate::sources::trino::TrinoDialect;
38#[cfg(any(
39 feature = "src_postgres",
40 feature = "src_mysql",
41 feature = "src_mssql_tiberius",
42 feature = "src_oracle",
43 feature = "src_bigquery",
44 feature = "src_trino",
45 feature = "src_clickhouse",
46))]
47use crate::sql::get_partition_range_query;
48#[cfg(feature = "src_sqlite")]
49use crate::sql::get_partition_range_query_sep;
50use crate::sql::{single_col_partition_query, CXQuery};
51use anyhow::anyhow;
52use fehler::{throw, throws};
53#[cfg(feature = "src_bigquery")]
54use gcp_bigquery_client;
55#[cfg(feature = "src_mysql")]
56use r2d2_mysql::mysql::{prelude::Queryable, Pool, Row};
57#[cfg(feature = "src_sqlite")]
58use rusqlite::{types::Type, Connection};
59#[cfg(feature = "src_postgres")]
60use rust_decimal::{prelude::ToPrimitive, Decimal};
61#[cfg(feature = "src_postgres")]
62use rust_decimal_macros::dec;
63#[cfg(feature = "src_clickhouse")]
64use serde::Deserialize;
65#[cfg(feature = "src_clickhouse")]
66use serde_json::Value as JsonValue;
67#[cfg(feature = "src_clickhouse")]
68use sqlparser::dialect::ClickHouseDialect;
69#[cfg(feature = "src_mssql_common")]
70use sqlparser::dialect::MsSqlDialect;
71#[cfg(feature = "src_mysql")]
72use sqlparser::dialect::MySqlDialect;
73#[cfg(feature = "src_postgres")]
74use sqlparser::dialect::PostgreSqlDialect;
75#[cfg(feature = "src_sqlite")]
76use sqlparser::dialect::SQLiteDialect;
77#[cfg(feature = "src_mssql_tiberius")]
78use tiberius::Client;
79#[cfg(feature = "src_mssql_tiberius")]
80use tokio::net::TcpStream;
81#[cfg(any(
82 feature = "src_bigquery",
83 feature = "src_mssql_tiberius",
84 feature = "src_trino"
85))]
86use tokio::runtime::Runtime;
87#[cfg(feature = "src_mssql_tiberius")]
88use tokio_util::compat::TokioAsyncWriteCompatExt;
89#[cfg(any(
90 feature = "src_postgres",
91 feature = "src_mysql",
92 feature = "src_mssql_tiberius",
93 feature = "src_oracle",
94 feature = "src_bigquery",
95 feature = "src_trino",
96 feature = "src_clickhouse",
97 feature = "src_sqlite",
98))]
99use url::Url;
100
101pub struct PartitionQuery {
103 query: String,
104 column: String,
105 min: Option<i64>,
106 max: Option<i64>,
107 num: usize,
108 pre_execution_queries: Option<Vec<String>>,
109}
110
111impl PartitionQuery {
112 pub fn new(query: &str, column: &str, min: Option<i64>, max: Option<i64>, num: usize) -> Self {
114 Self {
115 query: query.into(),
116 column: column.into(),
117 min,
118 max,
119 num,
120 pre_execution_queries: None,
121 }
122 }
123
124 pub fn with_pre_execution_queries(mut self, pre_execution_queries: Option<&[String]>) -> Self {
126 self.pre_execution_queries = pre_execution_queries.map(|s| s.to_vec());
127 self
128 }
129}
130
131pub fn partition(part: &PartitionQuery, source_conn: &SourceConn) -> OutResult<Vec<CXQuery>> {
133 let mut queries = vec![];
134
135 if part.num == 0 {
136 throw!(anyhow!("partition count (num) must be greater than zero"));
137 }
138
139 let num = i64::try_from(part.num).map_err(|_| {
140 anyhow!(
141 "partition count (num) is too large to represent safely: {}",
142 part.num
143 )
144 })?;
145
146 let (min, max) = match (part.min, part.max) {
147 (None, None) => get_col_range_with_pre_queries(
148 source_conn,
149 &part.query,
150 &part.column,
151 part.pre_execution_queries.as_deref(),
152 )?,
153 (Some(min), Some(max)) => (min, max),
154 _ => throw!(anyhow!(
155 "partition_query range can not be partially specified",
156 )),
157 };
158
159 if max < min {
160 throw!(anyhow!(
161 "partition range is invalid: max ({}) must be greater than or equal to min ({})",
162 max,
163 min
164 ));
165 }
166
167 let range_len = max
168 .checked_sub(min)
169 .and_then(|value| value.checked_add(1))
170 .ok_or_else(|| {
171 anyhow!(
172 "partition range overflow: min={}, max={} is too large",
173 min,
174 max
175 )
176 })?;
177
178 let partition_size = range_len / num;
179
180 let final_upper = max.checked_add(1).ok_or_else(|| {
181 anyhow!(
182 "partition upper bound overflow: max={} cannot be incremented safely",
183 max
184 )
185 })?;
186
187 for i in 0i64..num {
188 let lower = i
189 .checked_mul(partition_size)
190 .and_then(|offset| min.checked_add(offset))
191 .ok_or_else(|| {
192 anyhow!(
193 "partition lower bound overflow: min={}, step={}, partition_size={}",
194 min,
195 i,
196 partition_size
197 )
198 })?;
199 let upper = if i == num - 1 {
200 final_upper
201 } else {
202 (i + 1)
203 .checked_mul(partition_size)
204 .and_then(|offset| min.checked_add(offset))
205 .ok_or_else(|| {
206 anyhow!(
207 "partition upper bound overflow: min={}, step={}, partition_size={}",
208 min,
209 i + 1,
210 partition_size
211 )
212 })?
213 };
214 let partition_query = get_part_query(source_conn, &part.query, &part.column, lower, upper)?;
215 queries.push(partition_query);
216 }
217 Ok(queries)
218}
219
220pub fn get_col_range(source_conn: &SourceConn, query: &str, col: &str) -> OutResult<(i64, i64)> {
222 get_col_range_with_pre_queries(source_conn, query, col, None)
223}
224
225pub fn get_col_range_with_pre_queries(
227 source_conn: &SourceConn,
228 query: &str,
229 col: &str,
230 #[allow(unused_variables)] pre_execution_queries: Option<&[String]>,
231) -> OutResult<(i64, i64)> {
232 match source_conn.ty {
233 #[cfg(feature = "src_postgres")]
234 SourceType::Postgres => {
235 pg_get_partition_range(&source_conn.conn, query, col, pre_execution_queries)
236 }
237 #[cfg(feature = "src_sqlite")]
238 SourceType::SQLite => sqlite_get_partition_range(&source_conn.conn, query, col),
239 #[cfg(feature = "src_mysql")]
240 SourceType::MySQL => {
241 mysql_get_partition_range(&source_conn.conn, query, col, pre_execution_queries)
242 }
243 #[cfg(all(feature = "src_mssql_tiberius", not(feature = "src_mssql_tds")))]
244 SourceType::MsSQL => mssql_get_partition_range(&source_conn.conn, query, col),
245 #[cfg(all(feature = "src_mssql_tiberius", feature = "src_mssql_tds"))]
246 SourceType::MsSQL => match crate::sources::mssql::active_driver() {
247 crate::sources::mssql::MsSQLDriverKind::Tiberius => {
248 mssql_get_partition_range(&source_conn.conn, query, col)
249 }
250 crate::sources::mssql::MsSQLDriverKind::MssqlTds => Ok(
251 crate::sources::mssql::tds_get_partition_range(&source_conn.conn, query, col)?,
252 ),
253 },
254 #[cfg(all(feature = "src_mssql_tds", not(feature = "src_mssql_tiberius")))]
255 SourceType::MsSQL => Ok(crate::sources::mssql::tds_get_partition_range(
256 &source_conn.conn,
257 query,
258 col,
259 )?),
260 #[cfg(feature = "src_oracle")]
261 SourceType::Oracle => oracle_get_partition_range(&source_conn.conn, query, col),
262 #[cfg(feature = "src_bigquery")]
263 SourceType::BigQuery => bigquery_get_partition_range(&source_conn.conn, query, col),
264 #[cfg(feature = "src_trino")]
265 SourceType::Trino => trino_get_partition_range(&source_conn.conn, query, col),
266 #[cfg(feature = "src_clickhouse")]
267 SourceType::ClickHouse => clickhouse_get_partition_range(&source_conn.conn, query, col),
268 _ => Err(ConnectorXOutError::SourceNotSupport(format!(
269 "{:?}",
270 source_conn.ty
271 ))),
272 }
273}
274
275#[throws(ConnectorXOutError)]
277pub fn get_part_query(
278 source_conn: &SourceConn,
279 query: &str,
280 col: &str,
281 lower: i64,
282 upper: i64,
283) -> CXQuery<String> {
284 let query = match source_conn.ty {
285 #[cfg(feature = "src_postgres")]
286 SourceType::Postgres => {
287 single_col_partition_query(query, col, lower, upper, &PostgreSqlDialect {})?
288 }
289 #[cfg(feature = "src_sqlite")]
290 SourceType::SQLite => {
291 single_col_partition_query(query, col, lower, upper, &SQLiteDialect {})?
292 }
293 #[cfg(feature = "src_mysql")]
294 SourceType::MySQL => {
295 single_col_partition_query(query, col, lower, upper, &MySqlDialect {})?
296 }
297 #[cfg(feature = "src_mssql_common")]
298 SourceType::MsSQL => {
299 single_col_partition_query(query, col, lower, upper, &MsSqlDialect {})?
300 }
301 #[cfg(feature = "src_oracle")]
302 SourceType::Oracle => {
303 single_col_partition_query(query, col, lower, upper, &OracleDialect {})?
304 }
305 #[cfg(feature = "src_bigquery")]
306 SourceType::BigQuery => {
307 single_col_partition_query(query, col, lower, upper, &BigQueryDialect {})?
308 }
309 #[cfg(feature = "src_trino")]
310 SourceType::Trino => {
311 single_col_partition_query(query, col, lower, upper, &TrinoDialect {})?
312 }
313 #[cfg(feature = "src_clickhouse")]
314 SourceType::ClickHouse => {
315 single_col_partition_query(query, col, lower, upper, &ClickHouseDialect {})?
316 }
317 _ => throw!(ConnectorXOutError::SourceNotSupport(format!(
318 "{:?}",
319 source_conn.ty
320 ))),
321 };
322 CXQuery::Wrapped(query)
323}
324
325#[cfg(feature = "src_postgres")]
326#[throws(ConnectorXOutError)]
327fn pg_get_partition_range(
328 conn: &Url,
329 query: &str,
330 col: &str,
331 pre_execution_queries: Option<&[String]>,
332) -> (i64, i64) {
333 let (config, tls) = rewrite_tls_args(conn)?;
334 let mut client = match tls {
335 None => config.connect(postgres::NoTls)?,
336 Some(tls_conn) => config.connect(tls_conn)?,
337 };
338 for pre_query in pre_execution_queries.unwrap_or_default() {
339 client.query(pre_query.as_str(), &[])?;
340 }
341 let range_query = get_partition_range_query(query, col, &PostgreSqlDialect {})?;
342 let row = client.query_one(range_query.as_str(), &[])?;
343
344 let col_type = PostgresTypeSystem::from(row.columns()[0].type_());
345 let (min_v, max_v) = match col_type {
346 PostgresTypeSystem::Int2(_) => {
347 let min_v: Option<i16> = row.get(0);
348 let max_v: Option<i16> = row.get(1);
349 (min_v.unwrap_or(0) as i64, max_v.unwrap_or(0) as i64)
350 }
351 PostgresTypeSystem::Int4(_) => {
352 let min_v: Option<i32> = row.get(0);
353 let max_v: Option<i32> = row.get(1);
354 (min_v.unwrap_or(0) as i64, max_v.unwrap_or(0) as i64)
355 }
356 PostgresTypeSystem::Int8(_) => {
357 let min_v: Option<i64> = row.get(0);
358 let max_v: Option<i64> = row.get(1);
359 (min_v.unwrap_or(0), max_v.unwrap_or(0))
360 }
361 PostgresTypeSystem::Float4(_) => {
362 let min_v: Option<f32> = row.get(0);
363 let max_v: Option<f32> = row.get(1);
364 (min_v.unwrap_or(0.0) as i64, max_v.unwrap_or(0.0) as i64)
365 }
366 PostgresTypeSystem::Float8(_) => {
367 let min_v: Option<f64> = row.get(0);
368 let max_v: Option<f64> = row.get(1);
369 (min_v.unwrap_or(0.0) as i64, max_v.unwrap_or(0.0) as i64)
370 }
371 PostgresTypeSystem::Numeric(_) => {
372 let min_v: Option<Decimal> = row.get(0);
373 let max_v: Option<Decimal> = row.get(1);
374 (
375 min_v.unwrap_or(dec!(0.0)).to_i64().unwrap_or(0),
376 max_v.unwrap_or(dec!(0.0)).to_i64().unwrap_or(0),
377 )
378 }
379 _ => throw!(anyhow!(
380 "Partition can only be done on int or float columns"
381 )),
382 };
383
384 (min_v, max_v)
385}
386
387#[cfg(feature = "src_sqlite")]
388#[throws(ConnectorXOutError)]
389fn sqlite_get_partition_range(conn: &Url, query: &str, col: &str) -> (i64, i64) {
390 let path = urlencoding::decode(&conn.as_str()[9..]).map_err(|e| anyhow!(e))?;
394 let conn = Connection::open(path.as_ref())?;
395 let (min_query, max_query) = get_partition_range_query_sep(query, col, &SQLiteDialect {})?;
398 let mut error = None;
399 let min_v = conn.query_row(min_query.as_str(), [], |row| {
400 let col_type = row.get_ref(0)?.data_type();
402 match col_type {
403 Type::Integer => row.get(0),
404 Type::Real => {
405 let v: f64 = row.get(0)?;
406 Ok(v as i64)
407 }
408 Type::Null => Ok(0),
409 _ => {
410 error = Some(anyhow!("Partition can only be done on integer columns"));
411 Ok(0)
412 }
413 }
414 })?;
415 match error {
416 None => {}
417 Some(e) => throw!(e),
418 }
419 let max_v = conn.query_row(max_query.as_str(), [], |row| {
420 let col_type = row.get_ref(0)?.data_type();
421 match col_type {
422 Type::Integer => row.get(0),
423 Type::Real => {
424 let v: f64 = row.get(0)?;
425 Ok(v as i64)
426 }
427 Type::Null => Ok(0),
428 _ => {
429 error = Some(anyhow!("Partition can only be done on integer columns"));
430 Ok(0)
431 }
432 }
433 })?;
434 match error {
435 None => {}
436 Some(e) => throw!(e),
437 }
438
439 (min_v, max_v)
440}
441
442#[cfg(feature = "src_mysql")]
443#[throws(ConnectorXOutError)]
444fn mysql_get_partition_range(
445 conn: &Url,
446 query: &str,
447 col: &str,
448 pre_execution_queries: Option<&[String]>,
449) -> (i64, i64) {
450 let pool = Pool::new(build_opts(conn.as_str())?)?;
451 let mut conn = pool.get_conn()?;
452 for pre_query in pre_execution_queries.unwrap_or_default() {
453 conn.query_drop(pre_query)?;
454 }
455 let range_query = get_partition_range_query(query, col, &MySqlDialect {})?;
456 let row: Row = conn
457 .query_first(range_query)?
458 .ok_or_else(|| anyhow!("mysql range: no row returns"))?;
459
460 let col_type = MySQLTypeSystem::from((
461 &row.columns()[0].column_type(),
462 &row.columns()[0].flags(),
463 row.columns()[0].character_set(),
464 ));
465
466 let (min_v, max_v) = match col_type {
467 MySQLTypeSystem::Tiny(_) => {
468 let min_v: Option<i8> = row
469 .get(0)
470 .ok_or_else(|| anyhow!("mysql range: cannot get min value"))?;
471 let max_v: Option<i8> = row
472 .get(1)
473 .ok_or_else(|| anyhow!("mysql range: cannot get max value"))?;
474 (min_v.unwrap_or(0) as i64, max_v.unwrap_or(0) as i64)
475 }
476 MySQLTypeSystem::Short(_) => {
477 let min_v: Option<i16> = row
478 .get(0)
479 .ok_or_else(|| anyhow!("mysql range: cannot get min value"))?;
480 let max_v: Option<i16> = row
481 .get(1)
482 .ok_or_else(|| anyhow!("mysql range: cannot get max value"))?;
483 (min_v.unwrap_or(0) as i64, max_v.unwrap_or(0) as i64)
484 }
485 MySQLTypeSystem::Int24(_) => {
486 let min_v: Option<i32> = row
487 .get(0)
488 .ok_or_else(|| anyhow!("mysql range: cannot get min value"))?;
489 let max_v: Option<i32> = row
490 .get(1)
491 .ok_or_else(|| anyhow!("mysql range: cannot get max value"))?;
492 (min_v.unwrap_or(0) as i64, max_v.unwrap_or(0) as i64)
493 }
494 MySQLTypeSystem::Long(_) => {
495 let min_v: Option<i64> = row
496 .get(0)
497 .ok_or_else(|| anyhow!("mysql range: cannot get min value"))?;
498 let max_v: Option<i64> = row
499 .get(1)
500 .ok_or_else(|| anyhow!("mysql range: cannot get max value"))?;
501 (min_v.unwrap_or(0), max_v.unwrap_or(0))
502 }
503 MySQLTypeSystem::LongLong(_) => {
504 let min_v: Option<i64> = row
505 .get(0)
506 .ok_or_else(|| anyhow!("mysql range: cannot get min value"))?;
507 let max_v: Option<i64> = row
508 .get(1)
509 .ok_or_else(|| anyhow!("mysql range: cannot get max value"))?;
510 (min_v.unwrap_or(0), max_v.unwrap_or(0))
511 }
512 MySQLTypeSystem::UTiny(_) => {
513 let min_v: Option<u8> = row
514 .get(0)
515 .ok_or_else(|| anyhow!("mysql range: cannot get min value"))?;
516 let max_v: Option<u8> = row
517 .get(1)
518 .ok_or_else(|| anyhow!("mysql range: cannot get max value"))?;
519 (min_v.unwrap_or(0) as i64, max_v.unwrap_or(0) as i64)
520 }
521 MySQLTypeSystem::UShort(_) => {
522 let min_v: Option<u16> = row
523 .get(0)
524 .ok_or_else(|| anyhow!("mysql range: cannot get min value"))?;
525 let max_v: Option<u16> = row
526 .get(1)
527 .ok_or_else(|| anyhow!("mysql range: cannot get max value"))?;
528 (min_v.unwrap_or(0) as i64, max_v.unwrap_or(0) as i64)
529 }
530 MySQLTypeSystem::UInt24(_) => {
531 let min_v: Option<u32> = row
532 .get(0)
533 .ok_or_else(|| anyhow!("mysql range: cannot get min value"))?;
534 let max_v: Option<u32> = row
535 .get(1)
536 .ok_or_else(|| anyhow!("mysql range: cannot get max value"))?;
537 (min_v.unwrap_or(0) as i64, max_v.unwrap_or(0) as i64)
538 }
539 MySQLTypeSystem::ULong(_) => {
540 let min_v: Option<u32> = row
541 .get(0)
542 .ok_or_else(|| anyhow!("mysql range: cannot get min value"))?;
543 let max_v: Option<u32> = row
544 .get(1)
545 .ok_or_else(|| anyhow!("mysql range: cannot get max value"))?;
546 (min_v.unwrap_or(0) as i64, max_v.unwrap_or(0) as i64)
547 }
548 MySQLTypeSystem::ULongLong(_) => {
549 let min_v: Option<u64> = row
550 .get(0)
551 .ok_or_else(|| anyhow!("mysql range: cannot get min value"))?;
552 let max_v: Option<u64> = row
553 .get(1)
554 .ok_or_else(|| anyhow!("mysql range: cannot get max value"))?;
555 (min_v.unwrap_or(0) as i64, max_v.unwrap_or(0) as i64)
556 }
557 MySQLTypeSystem::Float(_) => {
558 let min_v: Option<f32> = row
559 .get(0)
560 .ok_or_else(|| anyhow!("mysql range: cannot get min value"))?;
561 let max_v: Option<f32> = row
562 .get(1)
563 .ok_or_else(|| anyhow!("mysql range: cannot get max value"))?;
564 (min_v.unwrap_or(0.0) as i64, max_v.unwrap_or(0.0) as i64)
565 }
566 MySQLTypeSystem::Double(_) => {
567 let min_v: Option<f64> = row
568 .get(0)
569 .ok_or_else(|| anyhow!("mysql range: cannot get min value"))?;
570 let max_v: Option<f64> = row
571 .get(1)
572 .ok_or_else(|| anyhow!("mysql range: cannot get max value"))?;
573 (min_v.unwrap_or(0.0) as i64, max_v.unwrap_or(0.0) as i64)
574 }
575 _ => throw!(anyhow!("Partition can only be done on int columns")),
576 };
577
578 (min_v, max_v)
579}
580
581#[cfg(feature = "src_mssql_tiberius")]
582#[throws(ConnectorXOutError)]
583fn mssql_get_partition_range(conn: &Url, query: &str, col: &str) -> (i64, i64) {
584 let rt = Runtime::new().expect("Failed to create runtime");
585 let config = mssql_config(conn)?;
586 let tcp = rt.block_on(TcpStream::connect(config.get_addr()))?;
587 tcp.set_nodelay(true)?;
588
589 let mut client = rt.block_on(Client::connect(config, tcp.compat_write()))?;
590
591 let range_query = get_partition_range_query(query, col, &MsSqlDialect {})?;
592 let query_result = rt.block_on(client.query(range_query.as_str(), &[]))?;
593 let row = rt.block_on(query_result.into_row())?.unwrap();
594
595 let col_type = MsSQLTypeSystem::from(&row.columns()[0].column_type());
596 let (min_v, max_v) = match col_type {
597 MsSQLTypeSystem::Tinyint(_) => {
598 let min_v: u8 = row.get(0).unwrap_or(0);
599 let max_v: u8 = row.get(1).unwrap_or(0);
600 (min_v as i64, max_v as i64)
601 }
602 MsSQLTypeSystem::Smallint(_) => {
603 let min_v: i16 = row.get(0).unwrap_or(0);
604 let max_v: i16 = row.get(1).unwrap_or(0);
605 (min_v as i64, max_v as i64)
606 }
607 MsSQLTypeSystem::Int(_) => {
608 let min_v: i32 = row.get(0).unwrap_or(0);
609 let max_v: i32 = row.get(1).unwrap_or(0);
610 (min_v as i64, max_v as i64)
611 }
612 MsSQLTypeSystem::Bigint(_) => {
613 let min_v: i64 = row.get(0).unwrap_or(0);
614 let max_v: i64 = row.get(1).unwrap_or(0);
615 (min_v, max_v)
616 }
617 MsSQLTypeSystem::Intn(_) => {
618 let min_v: IntN = row.get(0).unwrap_or(IntN(0));
619 let max_v: IntN = row.get(1).unwrap_or(IntN(0));
620 (min_v.0, max_v.0)
621 }
622 MsSQLTypeSystem::Float24(_) => {
623 let min_v: f32 = row.get(0).unwrap_or(0.0);
624 let max_v: f32 = row.get(1).unwrap_or(0.0);
625 (min_v as i64, max_v as i64)
626 }
627 MsSQLTypeSystem::Float53(_) => {
628 let min_v: f64 = row.get(0).unwrap_or(0.0);
629 let max_v: f64 = row.get(1).unwrap_or(0.0);
630 (min_v as i64, max_v as i64)
631 }
632 MsSQLTypeSystem::Floatn(_) => {
633 let min_v: FloatN = row.get(0).unwrap_or(FloatN(0.0));
634 let max_v: FloatN = row.get(1).unwrap_or(FloatN(0.0));
635 (min_v.0 as i64, max_v.0 as i64)
636 }
637 _ => throw!(anyhow!(
638 "Partition can only be done on int or float columns"
639 )),
640 };
641
642 (min_v, max_v)
643}
644
645#[cfg(feature = "src_oracle")]
646#[throws(ConnectorXOutError)]
647fn oracle_get_partition_range(conn: &Url, query: &str, col: &str) -> (i64, i64) {
648 let source = OracleSource::new(conn.as_str(), 1)?;
649 let conn = source.get_conn()?;
650 let range_query = get_partition_range_query(query, col, &OracleDialect {})?;
651 let row = conn.query_row(range_query.as_str(), &[])?;
652 let min_v: i64 = row.get(0).unwrap_or(0);
653 let max_v: i64 = row.get(1).unwrap_or(0);
654 (min_v, max_v)
655}
656
657#[cfg(feature = "src_bigquery")]
658#[throws(ConnectorXOutError)] fn bigquery_get_partition_range(conn: &Url, query: &str, col: &str) -> (i64, i64) {
660 let rt = Runtime::new().expect("Failed to create runtime");
661 let url = Url::parse(conn.as_str())?;
662 let sa_key_path = url.path();
663 let client = rt.block_on(gcp_bigquery_client::Client::from_service_account_key_file(
664 sa_key_path,
665 ))?;
666
667 let auth_data = std::fs::read_to_string(sa_key_path)?;
668 let auth_json: serde_json::Value = serde_json::from_str(&auth_data)?;
669 let project_id = auth_json
670 .get("project_id")
671 .ok_or_else(|| anyhow!("Cannot get project_id from auth file"))?
672 .as_str()
673 .ok_or_else(|| anyhow!("Cannot get project_id as string from auth file"))?;
674 let range_query = get_partition_range_query(query, col, &BigQueryDialect {})?;
675
676 let query_result = rt.block_on(client.job().query(
677 project_id,
678 gcp_bigquery_client::model::query_request::QueryRequest::new(range_query.as_str()),
679 ))?;
680 let mut rs = gcp_bigquery_client::model::query_response::ResultSet::new_from_query_response(
681 query_result,
682 );
683 rs.next_row();
684 let min_v = rs.get_i64(0)?.unwrap_or(0);
685 let max_v = rs.get_i64(1)?.unwrap_or(0);
686
687 (min_v, max_v)
688}
689
690#[cfg(feature = "src_trino")]
691#[throws(ConnectorXOutError)]
692fn trino_get_partition_range(conn: &Url, query: &str, col: &str) -> (i64, i64) {
693 use crate::sources::trino::{build_client_from_url, TrinoDialect, TrinoPartitionQueryResult};
694
695 let rt = Runtime::new().expect("Failed to create runtime");
696
697 let client =
698 build_client_from_url(conn).map_err(|e| anyhow!("Failed to build Trino client: {}", e))?;
699
700 let range_query = get_partition_range_query(query, col, &TrinoDialect {})?;
701 let query_result = rt.block_on(client.get_all::<TrinoPartitionQueryResult>(range_query));
702
703 let query_result = match query_result {
704 Ok(query_result) => Ok(query_result.into_vec()),
705 Err(e) => match e {
706 prusto::error::Error::EmptyData => {
707 Ok(vec![TrinoPartitionQueryResult { _col0: 0, _col1: 0 }])
708 }
709 _ => Err(anyhow!("Failed to get query result: {}", e)),
710 },
711 }?;
712
713 let result = query_result
714 .first()
715 .unwrap_or(&TrinoPartitionQueryResult { _col0: 0, _col1: 0 });
716
717 (result._col0, result._col1)
718}
719
720#[cfg(feature = "src_clickhouse")]
721#[throws(ConnectorXOutError)]
722fn clickhouse_get_partition_range(conn: &Url, query: &str, col: &str) -> (i64, i64) {
723 use sqlparser::dialect::ClickHouseDialect;
724
725 let rt = Arc::new(tokio::runtime::Runtime::new().expect("Failed to create runtime"));
726 let clickhouse_source = ClickHouseSource::new(rt.clone(), conn.as_str())
727 .expect("Failed to create ClickHouse client");
728
729 let range_query = get_partition_range_query(query, col, &ClickHouseDialect {})?;
730
731 let response = rt.block_on(async {
732 let mut cursor = clickhouse_source
733 .client
734 .query(range_query.as_str())
735 .fetch_bytes("JSONCompact")
736 .map_err(|e| anyhow!("ClickHouse error: {}", e))?;
737 let bytes = cursor
738 .collect()
739 .await
740 .map_err(|e| anyhow!("ClickHouse error: {}", e))?;
741 Ok::<_, ClickHouseSourceError>(bytes)
742 })?;
743
744 #[derive(Debug, Deserialize)]
745 struct MinMaxResponse {
746 data: Vec<Vec<JsonValue>>,
747 }
748
749 let parsed: MinMaxResponse = serde_json::from_slice(&response)
750 .map_err(|e| anyhow!("Failed to parse min max response: {}", e))?;
751
752 let (min_v, max_v) = if let Some(row) = parsed.data.first() {
753 let min_v = row.first().and_then(|v| v.as_i64()).unwrap_or(0);
754 let max_v = row.get(1).and_then(|v| v.as_i64()).unwrap_or(0);
755
756 (min_v, max_v)
757 } else {
758 (0, 0)
759 };
760
761 (min_v, max_v)
762}
763
764#[cfg(test)]
765mod tests {
766 use super::*;
767
768 #[cfg(feature = "src_sqlite")]
772 fn sqlite_source_conn() -> SourceConn {
773 SourceConn::new(
774 SourceType::SQLite,
775 Url::parse("sqlite://test.db").unwrap(),
776 "binary".to_string(),
777 )
778 }
779
780 #[cfg(feature = "src_sqlite")]
781 fn queries_as_strings(queries: &[CXQuery]) -> Vec<String> {
782 queries.iter().map(|q| q.to_string()).collect()
783 }
784
785 #[cfg(feature = "src_sqlite")]
786 #[test]
787 fn partitions_evenly_divisible_range() {
788 let part = PartitionQuery::new("SELECT * FROM test", "id", Some(0), Some(9), 2);
789 let source_conn = sqlite_source_conn();
790 let queries = partition(&part, &source_conn).unwrap();
791
792 assert_eq!(queries.len(), 2);
793 let strings = queries_as_strings(&queries);
794 assert!(strings[0].contains("0 <=") && strings[0].contains("< 5"));
795 assert!(strings[1].contains("5 <=") && strings[1].contains("< 10"));
796 }
797
798 #[cfg(feature = "src_sqlite")]
799 #[test]
800 fn partitions_range_not_evenly_divisible() {
801 let part = PartitionQuery::new("SELECT * FROM test", "id", Some(0), Some(10), 3);
804 let source_conn = sqlite_source_conn();
805 let queries = partition(&part, &source_conn).unwrap();
806
807 assert_eq!(queries.len(), 3);
808 let strings = queries_as_strings(&queries);
809 assert!(strings[0].contains("0 <=") && strings[0].contains("< 3"));
810 assert!(strings[1].contains("3 <=") && strings[1].contains("< 6"));
811 assert!(strings[2].contains("6 <=") && strings[2].contains("< 11"));
813 }
814
815 #[cfg(feature = "src_sqlite")]
816 #[test]
817 fn single_partition_covers_whole_range() {
818 let part = PartitionQuery::new("SELECT * FROM test", "id", Some(5), Some(15), 1);
819 let source_conn = sqlite_source_conn();
820 let queries = partition(&part, &source_conn).unwrap();
821
822 assert_eq!(queries.len(), 1);
823 let strings = queries_as_strings(&queries);
824 assert!(strings[0].contains("5 <=") && strings[0].contains("< 16"));
825 }
826
827 #[cfg(feature = "src_sqlite")]
828 #[test]
829 fn min_equals_max_single_row_range() {
830 let part = PartitionQuery::new("SELECT * FROM test", "id", Some(7), Some(7), 1);
831 let source_conn = sqlite_source_conn();
832 let queries = partition(&part, &source_conn).unwrap();
833
834 assert_eq!(queries.len(), 1);
835 let strings = queries_as_strings(&queries);
836 assert!(strings[0].contains("7 <=") && strings[0].contains("< 8"));
837 }
838
839 #[cfg(feature = "src_sqlite")]
840 #[test]
841 fn negative_range_partitions_correctly() {
842 let part = PartitionQuery::new("SELECT * FROM test", "id", Some(-10), Some(-1), 2);
843 let source_conn = sqlite_source_conn();
844 let queries = partition(&part, &source_conn).unwrap();
845
846 assert_eq!(queries.len(), 2);
847 let strings = queries_as_strings(&queries);
848 assert!(strings[0].contains("-10 <=") && strings[0].contains("< -5"));
849 assert!(strings[1].contains("-5 <=") && strings[1].contains("< 0"));
850 }
851
852 #[cfg(feature = "src_sqlite")]
853 #[test]
854 fn partially_specified_range_returns_error() {
855 let part = PartitionQuery::new("SELECT * FROM test", "id", Some(0), None, 2);
856 let source_conn = sqlite_source_conn();
857 let result = partition(&part, &source_conn);
858
859 assert!(result.is_err());
860 }
861
862 #[cfg(feature = "src_sqlite")]
863 #[test]
864 fn zero_partitions_returns_error_on_division_by_zero() {
865 let part = PartitionQuery::new("SELECT * FROM test", "id", Some(0), Some(9), 0);
866 let source_conn = sqlite_source_conn();
867 let result = partition(&part, &source_conn);
868 assert!(result.is_err());
869 let err = result.unwrap_err().to_string();
870 assert!(err.contains("partition count (num) must be greater than zero"));
871 }
872
873 #[cfg(feature = "src_sqlite")]
874 #[test]
875 fn inverted_range_returns_error() {
876 let part = PartitionQuery::new("SELECT * FROM test", "id", Some(10), Some(0), 2);
877 let source_conn = sqlite_source_conn();
878 let result = partition(&part, &source_conn);
879 assert!(result.is_err());
880 let err = result.unwrap_err().to_string();
881 assert!(
882 err.contains("partition range is invalid"),
883 "unexpected error message: {}",
884 err
885 );
886 }
887
888 #[cfg(feature = "src_sqlite")]
889 #[test]
890 fn more_partitions_than_range_values_preserves_partition_count() {
891 let part = PartitionQuery::new("SELECT * FROM test", "id", Some(0), Some(1), 4);
892 let source_conn = sqlite_source_conn();
893 let queries = partition(&part, &source_conn).unwrap();
894
895 assert_eq!(queries.len(), 4);
896 let strings = queries_as_strings(&queries);
897 assert!(strings[0].contains("0 <=") && strings[0].contains("< 0"));
898 assert!(strings[1].contains("0 <=") && strings[1].contains("< 0"));
899 assert!(strings[2].contains("0 <=") && strings[2].contains("< 0"));
900 assert!(strings[3].contains("0 <=") && strings[3].contains("< 2"));
901 }
902
903 #[cfg(feature = "src_sqlite")]
904 #[test]
905 fn large_range_does_not_overflow_with_small_num() {
906 let part = PartitionQuery::new(
909 "SELECT * FROM test",
910 "id",
911 Some(0),
912 Some(1_000_000_000_000),
913 4,
914 );
915 let source_conn = sqlite_source_conn();
916 let queries = partition(&part, &source_conn).unwrap();
917
918 assert_eq!(queries.len(), 4);
919 let strings = queries_as_strings(&queries);
920 assert!(strings[0].contains("0 <="));
921 assert!(strings[3].contains("< 1000000000001"));
922 }
923
924 #[cfg(feature = "src_sqlite")]
925 #[test]
926 fn many_small_partitions_produce_correct_count_and_bounds() {
927 let part = PartitionQuery::new("SELECT * FROM test", "id", Some(1), Some(100), 10);
928 let source_conn = sqlite_source_conn();
929 let queries = partition(&part, &source_conn).unwrap();
930
931 assert_eq!(queries.len(), 10);
932 let strings = queries_as_strings(&queries);
933 assert!(strings[0].contains("1 <=") && strings[0].contains("< 11"));
934 assert!(strings[9].contains("91 <=") && strings[9].contains("< 101"));
935 }
936
937 #[cfg(feature = "src_sqlite")]
938 #[test]
939 fn partition_range_overflow() {
940 let part = PartitionQuery::new(
942 "SELECT * FROM test",
943 "id",
944 Some(i64::MIN),
945 Some(i64::MAX),
946 2,
947 );
948 let source_conn = sqlite_source_conn();
949 let res = partition(&part, &source_conn);
950 assert!(res.is_err());
951 let err = res.unwrap_err().to_string();
952 assert!(
953 err.contains("partition range overflow"),
954 "unexpected error message: {}",
955 err
956 );
957 }
958
959 #[cfg(feature = "src_sqlite")]
960 #[test]
961 fn partition_upper_overflow_at_i64_max() {
962 let part = PartitionQuery::new(
965 "SELECT * FROM test",
966 "id",
967 Some(i64::MAX - 5),
968 Some(i64::MAX),
969 1,
970 );
971 let source_conn = sqlite_source_conn();
972 let res = partition(&part, &source_conn);
973 assert!(res.is_err());
974 let err = res.unwrap_err().to_string();
975 assert!(
976 err.contains("partition upper bound overflow"),
977 "unexpected error message: {}",
978 err
979 );
980 }
981
982 #[cfg(feature = "src_sqlite")]
983 #[test]
984 fn partition_upper_overflow_multi_partition() {
985 let part = PartitionQuery::new(
987 "SELECT * FROM test",
988 "id",
989 Some(i64::MAX - 5),
990 Some(i64::MAX),
991 2,
992 );
993 let source_conn = sqlite_source_conn();
994 let res = partition(&part, &source_conn);
995 assert!(res.is_err());
996 let err = res.unwrap_err().to_string();
997 assert!(
998 err.contains("partition upper bound overflow"),
999 "unexpected error message: {}",
1000 err
1001 );
1002 }
1003
1004 #[test]
1007 fn unsupported_source_is_an_error() {
1008 let conn = SourceConn::try_from("nosuchdb://127.0.0.1:1/db").unwrap();
1009
1010 let err = get_col_range(&conn, "SELECT * FROM t", "id").unwrap_err();
1011 assert_eq!(err.to_string(), "Source Unknown not supported.");
1012
1013 let part = PartitionQuery::new("SELECT * FROM t", "id", Some(0), Some(9), 2);
1014 let err = partition(&part, &conn).unwrap_err();
1015 assert_eq!(err.to_string(), "Source Unknown not supported.");
1016 }
1017}