1use super::driver;
34use super::errors::MsSQLSourceError;
35use super::typesystem::{FloatN, IntN, MsSQLTypeSystem};
36use crate::constants::DB_BUFFER_SIZE;
37use crate::{
38 data_order::DataOrder,
39 errors::ConnectorXError,
40 sources::{PartitionParser, Produce, Source, SourcePartition},
41 sql::{count_query, get_partition_range_query, CXQuery},
42};
43use anyhow::anyhow;
44use bb8::{ManageConnection, Pool, PooledConnection};
45use chrono::{DateTime, NaiveDate, NaiveDateTime, NaiveTime, Utc};
46use fehler::{throw, throws};
47use log::{debug, warn};
48use mssql_tds::connection::client_context::{ClientContext, TdsAuthenticationMethod};
49use mssql_tds::connection::tds_client::{ResultSet, TdsClient};
50use mssql_tds::connection_provider::tds_connection_provider::TdsConnectionProvider;
51use mssql_tds::core::{EncryptionOptions, EncryptionSetting};
52use mssql_tds::datatypes::column_values::{
53 ColumnValues, SqlDate, SqlDateTime, SqlDateTime2, SqlDateTimeOffset, SqlSmallDateTime, SqlTime,
54};
55use mssql_tds::datatypes::decoder::DecimalParts;
56use mssql_tds::datatypes::sqldatatypes::TdsDataType;
57use rust_decimal::Decimal;
58use sqlparser::dialect::MsSqlDialect;
59use std::collections::HashMap;
60use std::convert::TryFrom;
61use std::ops::{Deref, DerefMut};
62use std::sync::{Arc, OnceLock};
63use std::time::Duration;
64use tokio::runtime::Runtime;
65use url::Url;
66use urlencoding::decode;
67use uuid_old::Uuid;
68
69#[derive(Clone, PartialEq)]
70struct UserAgentInfo {
71 version: String,
72 runtime: String,
73}
74
75static USER_AGENT_INFO: OnceLock<UserAgentInfo> = OnceLock::new();
76
77pub fn set_user_agent_info(version: String, runtime: String) -> Result<(), &'static str> {
81 if version.is_empty() {
82 return Err("MSSQL User-Agent version must not be empty");
83 }
84 if runtime.is_empty() {
85 return Err("MSSQL User-Agent runtime must not be empty");
86 }
87 let info = UserAgentInfo { version, runtime };
88 if USER_AGENT_INFO.get_or_init(|| info.clone()) != &info {
89 return Err("MSSQL User-Agent is already initialized with different values");
90 }
91 Ok(())
92}
93
94#[throws(MsSQLSourceError)]
99fn build_client_context(url: &Url) -> (String, ClientContext) {
100 let host = decode(url.host_str().unwrap_or("localhost"))?.into_owned();
101 let port = url.port().unwrap_or(1433);
102 let hosts: Vec<&str> = host.split('\\').collect();
103 let datasource = match hosts.len() {
104 1 => format!("tcp:{},{}", hosts[0], port),
105 2 => format!("{}\\{}", hosts[0], hosts[1]),
108 _ => throw!(anyhow!("MsSQL hostname parse error: {}", host)),
109 };
110
111 let mut context = ClientContext::with_data_source(&datasource);
112 context
114 .user_agent
115 .set_library_name("connectorx".to_string());
116 if let Some(info) = USER_AGENT_INFO.get() {
117 context.user_agent.set_driver_version(info.version.clone());
118 context.user_agent.set_runtime(info.runtime.clone());
119 }
120 context.application_name = "ConnectorX".to_string();
121 context.database = decode(&url.path()[1..])?.into_owned();
122
123 let params: HashMap<String, String> = url.query_pairs().into_owned().collect();
124
125 match params.get("trusted_connection") {
126 Some(v) if v == "true" && cfg!(any(windows, feature = "integrated-auth-gssapi")) => {
127 debug!("mssql-tds auth through integrated (SSPI) authentication");
128 context.tds_authentication_method = TdsAuthenticationMethod::SSPI;
129 }
130 _ => {
131 debug!("mssql-tds auth through sqlserver authentication");
132 context.tds_authentication_method = TdsAuthenticationMethod::Password;
133 context.user_name = decode(url.username())?.into_owned();
134 context.password = decode(url.password().unwrap_or(""))?.into_owned();
135 }
136 }
137
138 if let Some(v) = params.get("trust_server_certificate_ca") {
139 throw!(anyhow!(
143 "trust_server_certificate_ca={} is not supported with the src_mssql_tds backend: \
144 mssql-tds only supports exact-match certificate pinning, not CA validation",
145 v
146 ));
147 }
148
149 let mut encryption = EncryptionOptions::new();
150 encryption.mode = EncryptionSetting::PreferOff;
151 match params.get("encrypt") {
152 Some(v) if v.to_lowercase() == "true" => encryption.mode = EncryptionSetting::Required,
153 Some(v) if v.to_lowercase() == "false" => encryption.mode = EncryptionSetting::PreferOff,
154 _ => {}
155 }
156 if let Some(v) = params.get("trust_server_certificate") {
157 if v.to_lowercase() == "true" {
158 encryption.trust_server_certificate = true;
159 }
160 }
161 context.encryption_options = encryption;
162
163 if let Some(appname) = params.get("appname") {
164 context.application_name = decode(appname)?.into_owned();
165 }
166
167 (datasource, context)
168}
169
170#[cfg(test)]
171mod configuration_tests {
172 use super::*;
173
174 #[test]
175 fn python_user_agent_info_preserves_login_version() {
176 let version = "0.4.7a1";
177 let runtime = "Python 3.12.3";
178 assert!(set_user_agent_info(String::new(), runtime.to_string()).is_err());
179 assert!(set_user_agent_info(version.to_string(), String::new()).is_err());
180 set_user_agent_info(version.to_string(), runtime.to_string()).unwrap();
181 set_user_agent_info(version.to_string(), runtime.to_string()).unwrap();
182 assert!(set_user_agent_info("0.4.8".to_string(), runtime.to_string()).is_err());
183 assert!(set_user_agent_info(version.to_string(), "Python 3.13.0".to_string()).is_err());
184
185 let url = Url::parse("mssql://localhost/db").unwrap();
186 let (_, context) = build_client_context(&url).unwrap();
187 assert_eq!(context.user_agent.driver_version, version);
188 assert_eq!(context.user_agent.runtime, runtime);
189 assert_eq!(
190 context.driver_version,
191 ClientContext::with_data_source("tcp:localhost,1433").driver_version
192 );
193 }
194
195 #[test]
196 fn driver_identity_and_application_name() {
197 for (query, expected_appname) in [
198 ("", "ConnectorX"),
199 ("?appname=Custom%20Application", "Custom Application"),
200 ("?appname=", ""),
201 ] {
202 let url = Url::parse(&format!("mssql://localhost/db{query}")).unwrap();
203 let (_, context) = build_client_context(&url).unwrap();
204 assert_eq!(
205 context.library_name,
206 ClientContext::with_data_source("tcp:localhost,1433").library_name
207 );
208 assert_eq!(context.user_agent.library_name, "connectorx");
209 assert_eq!(context.application_name, expected_appname);
210 }
211 }
212
213 #[test]
214 fn integrated_auth_respects_tiberius_platform_and_feature_gates() {
215 for trusted in ["true", "false", "TrUe"] {
216 let url = Url::parse(&format!(
217 "mssql://test_user:test_password@localhost/db?trusted_connection={trusted}"
218 ))
219 .unwrap();
220 let (_, context) = build_client_context(&url).unwrap();
221 if trusted == "true" && cfg!(any(windows, feature = "integrated-auth-gssapi")) {
222 assert!(matches!(
223 context.tds_authentication_method,
224 TdsAuthenticationMethod::SSPI
225 ));
226 } else {
227 assert!(matches!(
228 context.tds_authentication_method,
229 TdsAuthenticationMethod::Password
230 ));
231 assert_eq!(context.user_name, "test_user");
232 assert_eq!(context.password, "test_password");
233 }
234 }
235 }
236
237 #[test]
238 fn tls_mapping_preserves_explicit_encryption_and_trust() {
239 for (encrypt, mode) in [
240 ("", EncryptionSetting::PreferOff),
241 ("true", EncryptionSetting::Required),
242 ("TrUe", EncryptionSetting::Required),
243 ("false", EncryptionSetting::PreferOff),
244 ("FaLsE", EncryptionSetting::PreferOff),
245 ("invalid", EncryptionSetting::PreferOff),
246 ] {
247 for (trust, expected_trust) in [
248 ("", false),
249 ("true", true),
250 ("TrUe", true),
251 ("false", false),
252 ("FaLsE", false),
253 ("invalid", false),
254 ] {
255 let mut url = Url::parse("mssql://user:password@localhost/db").unwrap();
256 if !encrypt.is_empty() {
257 url.query_pairs_mut().append_pair("encrypt", encrypt);
258 }
259 if !trust.is_empty() {
260 url.query_pairs_mut()
261 .append_pair("trust_server_certificate", trust);
262 }
263 let (_, context) = build_client_context(&url).unwrap();
264 assert_eq!(
265 context.encryption_options,
266 EncryptionOptions {
267 mode,
268 trust_server_certificate: expected_trust,
269 host_name_in_cert: None,
270 server_certificate: None,
271 },
272 "encrypt={encrypt:?}, trust_server_certificate={trust:?}"
273 );
274 }
275 }
276 }
277
278 #[test]
279 fn custom_ca_is_rejected_even_when_trust_is_enabled() {
280 for trust in ["true", "false"] {
281 let url = Url::parse(&format!(
282 "mssql://localhost/db?encrypt=true&trust_server_certificate={trust}\
283 &trust_server_certificate_ca=ca.pem"
284 ))
285 .unwrap();
286 let err = build_client_context(&url).err().unwrap();
287 assert!(err.to_string().contains("not CA validation"));
288 }
289 }
290
291 #[test]
292 fn pool_size_must_be_positive_and_fit_u32() {
293 let rt = Arc::new(Runtime::new().unwrap());
294 assert!(MsSQLSource::new(rt.clone(), "mssql://localhost/db", 0).is_err());
295 if usize::BITS > 32 {
296 assert!(MsSQLSource::new(rt, "mssql://localhost/db", usize::MAX).is_err());
297 }
298 }
299}
300
301#[throws(MsSQLSourceError)]
302fn open_connection(rt: &Runtime, url: &Url) -> TdsClient {
303 let (datasource, context) = build_client_context(url)?;
304 let provider = TdsConnectionProvider::new();
305 rt.block_on(provider.create_client(context, &datasource, None))?
306}
307
308struct ConnectionManager {
309 url: Url,
310}
311
312impl ManageConnection for ConnectionManager {
313 type Connection = TdsClient;
314 type Error = MsSQLSourceError;
315
316 async fn connect(&self) -> Result<TdsClient, Self::Error> {
317 let (datasource, context) = build_client_context(&self.url)?;
318 Ok(TdsConnectionProvider::new()
319 .create_client(context, &datasource, None)
320 .await?)
321 }
322
323 async fn is_valid(&self, client: &mut TdsClient) -> Result<(), Self::Error> {
324 if client.is_connection_dead() {
325 return Err(anyhow!("MsSQL pooled connection is closed").into());
326 }
327 client.prepare_reset_connection(false);
329 Ok(())
330 }
331
332 fn has_broken(&self, client: &mut TdsClient) -> bool {
333 client.is_connection_dead() || client.has_open_batch()
334 }
335}
336
337#[throws(MsSQLSourceError)]
338fn connection_pool(rt: &Runtime, url: &Url, nconn: usize) -> Pool<ConnectionManager> {
339 let max_size = u32::try_from(nconn)
340 .ok()
341 .filter(|&size| size > 0)
342 .ok_or_else(|| anyhow!("MsSQL pool size must be between 1 and {}", u32::MAX))?;
343 build_client_context(url)?;
345 rt.block_on(
346 Pool::builder()
347 .max_size(max_size)
348 .test_on_check_out(true)
349 .build(ConnectionManager { url: url.clone() }),
350 )?
351}
352
353struct Connection {
355 rt: Arc<Runtime>,
356 lease: Option<PooledConnection<'static, ConnectionManager>>,
357}
358
359impl Connection {
360 #[throws(MsSQLSourceError)]
361 fn get(rt: Arc<Runtime>, pool: &Pool<ConnectionManager>) -> Self {
362 let lease = rt.block_on(pool.get_owned()).map_err(|err| match err {
363 bb8::RunError::User(err) => err,
364 bb8::RunError::TimedOut => anyhow!("Timed out waiting for an MsSQL connection").into(),
365 })?;
366 Self {
367 rt,
368 lease: Some(lease),
369 }
370 }
371
372 #[throws(MsSQLSourceError)]
373 fn finish(&mut self) {
374 let client = self.lease.as_mut().unwrap();
375 if let Err(err) = self.rt.block_on(client.close_query()) {
376 client.mark_connection_dead();
377 throw!(err);
378 }
379 }
380}
381
382impl Deref for Connection {
383 type Target = TdsClient;
384
385 fn deref(&self) -> &TdsClient {
386 self.lease.as_ref().unwrap()
387 }
388}
389
390impl DerefMut for Connection {
391 fn deref_mut(&mut self) -> &mut TdsClient {
392 self.lease.as_mut().unwrap()
393 }
394}
395
396impl Drop for Connection {
397 fn drop(&mut self) {
398 let mut client = self.lease.take().unwrap();
399 if !client.is_connection_dead() && client.has_open_batch() {
400 match self.rt.block_on(async {
403 tokio::time::timeout(Duration::from_secs(5), client.close_query()).await
404 }) {
405 Ok(Ok(())) => {}
406 Ok(Err(err)) => {
407 warn!("Discarding MsSQL connection after cleanup failure: {}", err);
408 client.mark_connection_dead();
409 }
410 Err(_) => {
411 warn!("Discarding MsSQL connection after cleanup timeout");
412 client.mark_connection_dead();
413 }
414 }
415 }
416 let _guard = self.rt.enter();
418 drop(client);
419 }
420}
421
422#[throws(MsSQLSourceError)]
424fn first_row(rt: &Runtime, client: &mut TdsClient, sql: String) -> Option<Vec<ColumnValues>> {
425 rt.block_on(client.execute(sql, ()))?;
426 rt.block_on(client.next_row())?
427}
428
429#[throws(MsSQLSourceError)]
430pub(crate) fn tds_get_partition_range(url: &Url, query: &str, col: &str) -> (i64, i64) {
431 let range_query = get_partition_range_query(query, col, &MsSqlDialect {})?;
432 let rt = Runtime::new().map_err(anyhow::Error::from)?;
433 let mut client = open_connection(&rt, url)?;
434 rt.block_on(client.execute(range_query, ()))?;
435 let types: Vec<_> = client
436 .get_metadata()
437 .iter()
438 .map(|column| column.data_type)
439 .collect();
440 let row = rt
441 .block_on(client.next_row())?
442 .ok_or_else(|| anyhow!("MsSQL partition range query returned no row"))?;
443 if row.len() != 2 || types.len() != 2 {
444 throw!(anyhow!(
445 "MsSQL partition range query must return two columns"
446 ));
447 }
448 (
449 partition_range_value(&row[0], types[0])?,
450 partition_range_value(&row[1], types[1])?,
451 )
452}
453
454#[throws(MsSQLSourceError)]
455fn partition_range_value(value: &ColumnValues, ty: TdsDataType) -> i64 {
456 if !matches!(
457 ty,
458 TdsDataType::Int1
459 | TdsDataType::Int2
460 | TdsDataType::Int4
461 | TdsDataType::Int8
462 | TdsDataType::IntN
463 | TdsDataType::Flt4
464 | TdsDataType::Flt8
465 | TdsDataType::FltN
466 ) {
467 throw!(anyhow!(
468 "Partition can only be done on int or float columns"
469 ));
470 }
471 match value {
473 ColumnValues::Null => 0,
474 ColumnValues::TinyInt(n) => i64::from(*n),
475 ColumnValues::SmallInt(n) => i64::from(*n),
476 ColumnValues::Int(n) => i64::from(*n),
477 ColumnValues::BigInt(n) => *n,
478 ColumnValues::Real(n) => *n as i64,
479 ColumnValues::Float(n) => *n as i64,
480 other => throw!(anyhow!(
481 "Unexpected MsSQL partition range value: {:?}",
482 other
483 )),
484 }
485}
486
487#[cfg(test)]
488mod partition_range_tests {
489 use super::*;
490
491 #[test]
492 fn numeric_bounds_preserve_tiberius_conversions() {
493 for (value, ty, expected) in [
494 (ColumnValues::TinyInt(255), TdsDataType::Int1, 255),
495 (ColumnValues::SmallInt(-32768), TdsDataType::Int2, -32768),
496 (
497 ColumnValues::Int(i32::MIN),
498 TdsDataType::Int4,
499 i64::from(i32::MIN),
500 ),
501 (ColumnValues::BigInt(i64::MIN), TdsDataType::Int8, i64::MIN),
502 (ColumnValues::BigInt(i64::MAX), TdsDataType::IntN, i64::MAX),
503 (ColumnValues::Real(-12.75), TdsDataType::Flt4, -12),
504 (ColumnValues::Float(23.5), TdsDataType::Flt8, 23),
505 (ColumnValues::Float(-12.75), TdsDataType::FltN, -12),
506 (ColumnValues::Null, TdsDataType::IntN, 0),
507 (ColumnValues::Null, TdsDataType::FltN, 0),
508 ] {
509 assert_eq!(partition_range_value(&value, ty).unwrap(), expected);
510 }
511 }
512
513 #[test]
514 fn unsupported_bounds_are_errors_even_when_null() {
515 for ty in [
516 TdsDataType::BigVarChar,
517 TdsDataType::DecimalN,
518 TdsDataType::MoneyN,
519 ] {
520 let err = partition_range_value(&ColumnValues::Null, ty).unwrap_err();
521 assert!(err
522 .to_string()
523 .contains("Partition can only be done on int or float columns"));
524 }
525 assert!(partition_range_value(&ColumnValues::Bit(true), TdsDataType::IntN).is_err());
526 }
527}
528
529pub struct MsSQLSource {
531 rt: Arc<Runtime>,
532 conn_url: Url,
533 pool: Pool<ConnectionManager>,
534 origin_query: Option<String>,
535 queries: Vec<CXQuery<String>>,
536 names: Vec<String>,
537 schema: Vec<MsSQLTypeSystem>,
538}
539
540impl MsSQLSource {
541 #[throws(MsSQLSourceError)]
543 pub fn new(rt: Arc<Runtime>, conn: &str, nconn: usize) -> Self {
544 debug!("mssql source using driver: {:?}", driver::active_driver());
545 let conn_url = Url::parse(conn)?;
546 let pool = connection_pool(&rt, &conn_url, nconn)?;
547
548 Self {
549 rt,
550 conn_url,
551 pool,
552 origin_query: None,
553 queries: vec![],
554 names: vec![],
555 schema: vec![],
556 }
557 }
558}
559
560impl Source for MsSQLSource
561where
562 MsSQLSourcePartition: SourcePartition<TypeSystem = MsSQLTypeSystem, Error = MsSQLSourceError>,
563{
564 const DATA_ORDERS: &'static [DataOrder] = &[DataOrder::RowMajor];
565 type Partition = MsSQLSourcePartition;
566 type TypeSystem = MsSQLTypeSystem;
567 type Error = MsSQLSourceError;
568
569 #[throws(MsSQLSourceError)]
570 fn set_data_order(&mut self, data_order: DataOrder) {
571 if !matches!(data_order, DataOrder::RowMajor) {
572 throw!(ConnectorXError::UnsupportedDataOrder(data_order));
573 }
574 }
575
576 fn set_queries<Q: ToString>(&mut self, queries: &[CXQuery<Q>]) {
577 self.queries = queries.iter().map(|q| q.map(Q::to_string)).collect();
578 }
579
580 fn set_origin_query(&mut self, query: Option<String>) {
581 self.origin_query = query;
582 }
583
584 #[throws(MsSQLSourceError)]
585 fn fetch_metadata(&mut self) {
586 assert!(!self.queries.is_empty());
587
588 let first_query = self.queries[0].clone();
589 let mut client = Connection::get(self.rt.clone(), &self.pool)?;
590 self.rt
591 .block_on(client.execute(first_query.as_str().to_string(), ()))?;
592
593 let metadata = client.get_metadata();
594 if metadata.is_empty() {
595 throw!(anyhow!(
596 "MsSQL returned no columns for query: {}",
597 first_query
598 ));
599 }
600
601 let (names, types) = metadata
602 .iter()
603 .map(|col| (col.column_name.clone(), MsSQLTypeSystem::from(col)))
604 .unzip();
605 client.finish()?;
606
607 self.names = names;
608 self.schema = types;
609 }
610
611 #[throws(MsSQLSourceError)]
612 fn result_rows(&mut self) -> Option<usize> {
613 match &self.origin_query {
614 Some(q) => {
615 let cxq = CXQuery::Naked(q.clone());
616 let cquery = count_query(&cxq, &MsSqlDialect {})?;
617 let mut client = Connection::get(self.rt.clone(), &self.pool)?;
618 let row = first_row(&self.rt, &mut client, cquery.as_str().to_string())?
619 .ok_or_else(|| anyhow!("MsSQL failed to get the count of query: {}", q))?;
620 client.finish()?;
621 Some(row_count_value(&row, q)?)
622 }
623 None => None,
624 }
625 }
626
627 fn names(&self) -> Vec<String> {
628 self.names.clone()
629 }
630
631 fn schema(&self) -> Vec<Self::TypeSystem> {
632 self.schema.clone()
633 }
634
635 #[throws(MsSQLSourceError)]
636 fn partition(self) -> Vec<Self::Partition> {
637 let mut ret = vec![];
638 for query in self.queries {
639 let mut partition = MsSQLSourcePartition::new(
640 self.rt.clone(),
641 self.conn_url.clone(),
642 &query,
643 &self.schema,
644 );
645 partition.pool = Some(self.pool.clone());
646 ret.push(partition);
647 }
648 ret
649 }
650}
651
652#[throws(MsSQLSourceError)]
655fn row_count_value(row: &[ColumnValues], query: &str) -> usize {
656 match row.first() {
657 Some(ColumnValues::Int(n)) => *n as usize,
658 Some(ColumnValues::BigInt(n)) => *n as usize,
659 other => throw!(anyhow!(
660 "MsSQL count query for '{}' returned unexpected value: {:?}",
661 query,
662 other
663 )),
664 }
665}
666
667pub struct MsSQLSourcePartition {
669 rt: Arc<Runtime>,
670 conn_url: Url,
671 pool: Option<Pool<ConnectionManager>>,
672 query: CXQuery<String>,
673 schema: Vec<MsSQLTypeSystem>,
674 nrows: usize,
675 ncols: usize,
676}
677
678impl MsSQLSourcePartition {
679 pub fn new(
681 rt: Arc<Runtime>,
682 conn_url: Url,
683 query: &CXQuery<String>,
684 schema: &[MsSQLTypeSystem],
685 ) -> Self {
686 Self {
687 rt,
688 conn_url,
689 pool: None,
690 query: query.clone(),
691 schema: schema.to_vec(),
692 nrows: 0,
693 ncols: schema.len(),
694 }
695 }
696
697 #[throws(MsSQLSourceError)]
698 fn connection(&mut self) -> Connection {
699 if self.pool.is_none() {
701 self.pool = Some(connection_pool(&self.rt, &self.conn_url, 1)?);
702 }
703 Connection::get(self.rt.clone(), self.pool.as_ref().unwrap())?
704 }
705}
706
707impl SourcePartition for MsSQLSourcePartition {
708 type TypeSystem = MsSQLTypeSystem;
709 type Parser<'a> = MsSQLSourceParser;
711 type Error = MsSQLSourceError;
712
713 #[throws(MsSQLSourceError)]
714 fn result_rows(&mut self) {
715 let cquery = count_query(&self.query, &MsSqlDialect {})?;
716 let mut client = self.connection()?;
717 let row = first_row(&self.rt, &mut client, cquery.as_str().to_string())?
718 .ok_or_else(|| anyhow!("MsSQL failed to get the count of query: {}", self.query))?;
719 client.finish()?;
720 self.nrows = row_count_value(&row, self.query.as_str())?;
721 }
722
723 #[throws(MsSQLSourceError)]
724 fn parser<'a>(&'a mut self) -> Self::Parser<'a> {
725 let mut client = self.connection()?;
726 self.rt
727 .block_on(client.execute(self.query.as_str().to_string(), ()))?;
728 MsSQLSourceParser::new(self.rt.clone(), client, self.schema.len())
729 }
730
731 fn nrows(&self) -> usize {
732 self.nrows
733 }
734
735 fn ncols(&self) -> usize {
736 self.ncols
737 }
738}
739
740#[derive(Debug)]
746enum TdsCell {
747 Null,
748 U8(u8),
749 I16(i16),
750 I32(i32),
751 I64(i64),
752 F32(f32),
753 F64(f64),
754 Bool(bool),
755 Str(String),
756 Bytes(Vec<u8>),
757 Uuid(Uuid),
758 Decimal(Decimal),
759 NaiveDate(NaiveDate),
760 NaiveTime(NaiveTime),
761 NaiveDateTime(NaiveDateTime),
762 DateTimeUtc(DateTime<Utc>),
763}
764
765pub struct MsSQLSourceParser {
767 rt: Arc<Runtime>,
768 client: Connection,
769 rowbuf: Vec<Vec<TdsCell>>,
770 ncols: usize,
771 current_col: usize,
772 current_row: usize,
773 is_finished: bool,
774}
775
776impl MsSQLSourceParser {
777 fn new(rt: Arc<Runtime>, client: Connection, ncols: usize) -> Self {
778 Self {
779 rt,
780 client,
781 rowbuf: Vec::with_capacity(DB_BUFFER_SIZE),
782 ncols,
783 current_row: 0,
784 current_col: 0,
785 is_finished: false,
786 }
787 }
788
789 #[throws(MsSQLSourceError)]
790 fn next_loc(&mut self) -> (usize, usize) {
791 let ret = (self.current_row, self.current_col);
792 self.current_row += (self.current_col + 1) / self.ncols;
793 self.current_col = (self.current_col + 1) % self.ncols;
794 ret
795 }
796
797 fn take_cell(&mut self, ridx: usize, cidx: usize) -> TdsCell {
801 std::mem::replace(&mut self.rowbuf[ridx][cidx], TdsCell::Null)
802 }
803}
804
805impl<'a> PartitionParser<'a> for MsSQLSourceParser {
806 type TypeSystem = MsSQLTypeSystem;
807 type Error = MsSQLSourceError;
808
809 #[throws(MsSQLSourceError)]
810 fn fetch_next(&mut self) -> (usize, bool) {
811 assert!(self.current_col == 0);
812 let remaining_rows = self.rowbuf.len() - self.current_row;
813 if remaining_rows > 0 {
814 return (remaining_rows, self.is_finished);
815 } else if self.is_finished {
816 return (0, self.is_finished);
817 }
818
819 self.rowbuf.clear();
820
821 for _ in 0..DB_BUFFER_SIZE {
822 match self.rt.block_on(self.client.next_row())? {
823 Some(row) => {
824 let mut cells = Vec::with_capacity(row.len());
825 for value in row {
826 cells.push(column_value_to_cell(value)?);
827 }
828 self.rowbuf.push(cells);
829 }
830 None => {
831 self.client.finish()?;
832 self.is_finished = true;
833 break;
834 }
835 }
836 }
837 self.current_row = 0;
838 self.current_col = 0;
839 (self.rowbuf.len(), self.is_finished)
840 }
841}
842
843#[throws(MsSQLSourceError)]
844fn column_value_to_cell(value: ColumnValues) -> TdsCell {
845 match value {
846 ColumnValues::Null => TdsCell::Null,
847 ColumnValues::TinyInt(n) => TdsCell::U8(n),
848 ColumnValues::SmallInt(n) => TdsCell::I16(n),
849 ColumnValues::Int(n) => TdsCell::I32(n),
850 ColumnValues::BigInt(n) => TdsCell::I64(n),
851 ColumnValues::Real(f) => TdsCell::F32(f),
852 ColumnValues::Float(f) => TdsCell::F64(f),
853 ColumnValues::Bit(b) => TdsCell::Bool(b),
854 ColumnValues::String(s) => TdsCell::Str(s.to_utf8_string()),
855 ColumnValues::Bytes(b) => TdsCell::Bytes(b),
856 ColumnValues::Uuid(u) => TdsCell::Uuid(Uuid::from_bytes(*u.as_bytes())),
857 ColumnValues::Decimal(parts) | ColumnValues::Numeric(parts) => {
858 TdsCell::Decimal(decimal_parts_to_decimal(&parts)?)
859 }
860 ColumnValues::Date(d) => TdsCell::NaiveDate(sql_date_to_naive_date(&d)?),
861 ColumnValues::Time(t) => TdsCell::NaiveTime(sql_time_to_naive_time(&t)),
862 ColumnValues::DateTime(dt) => TdsCell::NaiveDateTime(sql_datetime_to_naive_datetime(&dt)?),
863 ColumnValues::DateTime2(dt2) => {
864 TdsCell::NaiveDateTime(sql_datetime2_to_naive_datetime(&dt2)?)
865 }
866 ColumnValues::SmallDateTime(sdt) => {
867 TdsCell::NaiveDateTime(sql_smalldatetime_to_naive_datetime(&sdt))
868 }
869 ColumnValues::DateTimeOffset(dto) => {
870 TdsCell::DateTimeUtc(sql_datetimeoffset_to_datetime_utc(&dto)?)
871 }
872 ColumnValues::Money(m) => TdsCell::F64(sql_money_to_f64(&m)),
873 ColumnValues::SmallMoney(sm) => TdsCell::F64((sm.int_val as f64) / 10_000.0),
883 other => throw!(anyhow!(
884 "MsSQL: unsupported value for src_mssql_tds backend: {:?}",
885 other
886 )),
887 }
888}
889
890#[throws(MsSQLSourceError)]
897fn decimal_parts_to_decimal(parts: &DecimalParts) -> Decimal {
898 let magnitude = parts.magnitude();
899 let mantissa = i128::try_from(magnitude)
900 .map_err(|_| anyhow!("MsSQL decimal/numeric value overflows 128 bits"))?;
901 let mantissa = if parts.is_positive {
902 mantissa
903 } else {
904 -mantissa
905 };
906 Decimal::try_from_i128_with_scale(mantissa, parts.scale as u32)
907 .map_err(|e| anyhow!("MsSQL decimal/numeric value out of range: {}", e))?
908}
909
910#[throws(MsSQLSourceError)]
913fn sql_date_to_naive_date(d: &SqlDate) -> NaiveDate {
914 NaiveDate::from_ymd_opt(1, 1, 1)
915 .unwrap()
916 .checked_add_signed(chrono::Duration::days(d.get_days() as i64))
917 .ok_or_else(|| {
918 anyhow!(
919 "MsSQL date out of range: {} days since 0001-01-01",
920 d.get_days()
921 )
922 })?
923}
924
925fn sql_time_to_naive_time(t: &SqlTime) -> NaiveTime {
932 let ns = t.time_nanoseconds * 100;
933 let secs = (ns / 1_000_000_000) as u32;
934 let nanos = (ns % 1_000_000_000) as u32;
935 NaiveTime::from_num_seconds_from_midnight_opt(secs, nanos).unwrap_or_default()
936}
937
938#[throws(MsSQLSourceError)]
939fn sql_datetime2_to_naive_datetime(dt2: &SqlDateTime2) -> NaiveDateTime {
940 let date = NaiveDate::from_ymd_opt(1, 1, 1)
941 .unwrap()
942 .checked_add_signed(chrono::Duration::days(dt2.days as i64))
943 .ok_or_else(|| {
944 anyhow!(
945 "MsSQL datetime2 out of range: {} days since 0001-01-01",
946 dt2.days
947 )
948 })?;
949 date.and_time(sql_time_to_naive_time(&dt2.time))
950}
951
952fn sql_smalldatetime_to_naive_datetime(sdt: &SqlSmallDateTime) -> NaiveDateTime {
953 let date = NaiveDate::from_ymd_opt(1900, 1, 1)
955 .unwrap()
956 .checked_add_signed(chrono::Duration::days(sdt.days as i64))
957 .expect("smalldatetime day count is always in range (u16 days since 1900-01-01)");
958 let time = NaiveTime::from_hms_opt((sdt.time / 60) as u32, (sdt.time % 60) as u32, 0)
959 .unwrap_or_default();
960 date.and_time(time)
961}
962
963#[throws(MsSQLSourceError)]
969fn sql_datetime_to_naive_datetime(dt: &SqlDateTime) -> NaiveDateTime {
970 let total_ms = (dt.time as i64 * 10 + 1) / 3;
971 let (extra_days, ms_in_day) = if total_ms >= 86_400_000 {
972 (1i64, total_ms - 86_400_000)
973 } else {
974 (0, total_ms)
975 };
976
977 let time = NaiveTime::from_num_seconds_from_midnight_opt(
978 (ms_in_day / 1000) as u32,
979 ((ms_in_day % 1000) * 1_000_000) as u32,
980 )
981 .ok_or_else(|| anyhow!("MsSQL datetime: invalid tick count {}", dt.time))?;
982
983 let date = NaiveDate::from_ymd_opt(1900, 1, 1)
984 .unwrap()
985 .checked_add_signed(chrono::Duration::days(dt.days as i64 + extra_days))
986 .ok_or_else(|| {
987 anyhow!(
988 "MsSQL datetime out of range: {} days since 1900-01-01",
989 dt.days
990 )
991 })?;
992
993 date.and_time(time)
994}
995
996#[throws(MsSQLSourceError)]
997fn sql_datetimeoffset_to_datetime_utc(dto: &SqlDateTimeOffset) -> DateTime<Utc> {
998 let naive_local = sql_datetime2_to_naive_datetime(&dto.datetime2)?;
1004 let naive_utc = naive_local - chrono::Duration::minutes(dto.offset as i64);
1005 DateTime::<Utc>::from_naive_utc_and_offset(naive_utc, Utc)
1006}
1007
1008fn sql_money_to_f64(m: &mssql_tds::datatypes::column_values::SqlMoney) -> f64 {
1011 let lsb_in_i64 = (m.lsb_part as i64) & 0x0000_0000_FFFF_FFFF;
1012 let money_val = lsb_in_i64 | ((m.msb_part as i64) << 32);
1013 (money_val as f64) / 10_000.0
1014}
1015
1016macro_rules! impl_produce_direct {
1017 ($($t:ty => $variant:ident),+ $(,)?) => {
1018 $(
1019 impl<'r> Produce<'r, $t> for MsSQLSourceParser {
1020 type Error = MsSQLSourceError;
1021
1022 #[throws(MsSQLSourceError)]
1023 fn produce(&'r mut self) -> $t {
1024 let (ridx, cidx) = self.next_loc()?;
1025 match self.take_cell(ridx, cidx) {
1026 TdsCell::$variant(v) => v,
1027 TdsCell::Null => throw!(anyhow!("MsSQL get None at position: ({}, {})", ridx, cidx)),
1028 other => throw!(anyhow!("MsSQL type mismatch at ({}, {}): {:?}", ridx, cidx, other)),
1029 }
1030 }
1031 }
1032
1033 impl<'r> Produce<'r, Option<$t>> for MsSQLSourceParser {
1034 type Error = MsSQLSourceError;
1035
1036 #[throws(MsSQLSourceError)]
1037 fn produce(&'r mut self) -> Option<$t> {
1038 let (ridx, cidx) = self.next_loc()?;
1039 match self.take_cell(ridx, cidx) {
1040 TdsCell::$variant(v) => Some(v),
1041 TdsCell::Null => None,
1042 other => throw!(anyhow!("MsSQL type mismatch at ({}, {}): {:?}", ridx, cidx, other)),
1043 }
1044 }
1045 }
1046 )+
1047 };
1048}
1049
1050impl_produce_direct!(
1051 u8 => U8,
1052 i16 => I16,
1053 i32 => I32,
1054 i64 => I64,
1055 bool => Bool,
1056 Uuid => Uuid,
1057 Decimal => Decimal,
1058 NaiveDateTime => NaiveDateTime,
1059 NaiveDate => NaiveDate,
1060 NaiveTime => NaiveTime,
1061 DateTime<Utc> => DateTimeUtc,
1062);
1063
1064impl<'r> Produce<'r, f32> for MsSQLSourceParser {
1070 type Error = MsSQLSourceError;
1071
1072 #[throws(MsSQLSourceError)]
1073 fn produce(&'r mut self) -> f32 {
1074 let (ridx, cidx) = self.next_loc()?;
1075 match self.take_cell(ridx, cidx) {
1076 TdsCell::F32(v) => v,
1077 TdsCell::F64(v) => v as f32,
1078 TdsCell::Null => throw!(anyhow!("MsSQL get None at position: ({}, {})", ridx, cidx)),
1079 other => throw!(anyhow!(
1080 "MsSQL type mismatch at ({}, {}): {:?}",
1081 ridx,
1082 cidx,
1083 other
1084 )),
1085 }
1086 }
1087}
1088
1089impl<'r> Produce<'r, Option<f32>> for MsSQLSourceParser {
1090 type Error = MsSQLSourceError;
1091
1092 #[throws(MsSQLSourceError)]
1093 fn produce(&'r mut self) -> Option<f32> {
1094 let (ridx, cidx) = self.next_loc()?;
1095 match self.take_cell(ridx, cidx) {
1096 TdsCell::F32(v) => Some(v),
1097 TdsCell::F64(v) => Some(v as f32),
1098 TdsCell::Null => None,
1099 other => throw!(anyhow!(
1100 "MsSQL type mismatch at ({}, {}): {:?}",
1101 ridx,
1102 cidx,
1103 other
1104 )),
1105 }
1106 }
1107}
1108
1109impl<'r> Produce<'r, f64> for MsSQLSourceParser {
1117 type Error = MsSQLSourceError;
1118
1119 #[throws(MsSQLSourceError)]
1120 fn produce(&'r mut self) -> f64 {
1121 let (ridx, cidx) = self.next_loc()?;
1122 match self.take_cell(ridx, cidx) {
1123 TdsCell::F64(v) => v,
1124 TdsCell::F32(v) => v as f64,
1125 TdsCell::Null => throw!(anyhow!("MsSQL get None at position: ({}, {})", ridx, cidx)),
1126 other => throw!(anyhow!(
1127 "MsSQL type mismatch at ({}, {}): {:?}",
1128 ridx,
1129 cidx,
1130 other
1131 )),
1132 }
1133 }
1134}
1135
1136impl<'r> Produce<'r, Option<f64>> for MsSQLSourceParser {
1137 type Error = MsSQLSourceError;
1138
1139 #[throws(MsSQLSourceError)]
1140 fn produce(&'r mut self) -> Option<f64> {
1141 let (ridx, cidx) = self.next_loc()?;
1142 match self.take_cell(ridx, cidx) {
1143 TdsCell::F64(v) => Some(v),
1144 TdsCell::F32(v) => Some(v as f64),
1145 TdsCell::Null => None,
1146 other => throw!(anyhow!(
1147 "MsSQL type mismatch at ({}, {}): {:?}",
1148 ridx,
1149 cidx,
1150 other
1151 )),
1152 }
1153 }
1154}
1155
1156impl<'r> Produce<'r, IntN> for MsSQLSourceParser {
1157 type Error = MsSQLSourceError;
1158
1159 #[throws(MsSQLSourceError)]
1160 fn produce(&'r mut self) -> IntN {
1161 let (ridx, cidx) = self.next_loc()?;
1162 match self.take_cell(ridx, cidx) {
1163 TdsCell::U8(v) => IntN(v as i64),
1164 TdsCell::I16(v) => IntN(v as i64),
1165 TdsCell::I32(v) => IntN(v as i64),
1166 TdsCell::I64(v) => IntN(v),
1167 TdsCell::Null => throw!(anyhow!("MsSQL get None at position: ({}, {})", ridx, cidx)),
1168 other => throw!(anyhow!(
1169 "MsSQL type mismatch at ({}, {}): {:?}",
1170 ridx,
1171 cidx,
1172 other
1173 )),
1174 }
1175 }
1176}
1177
1178impl<'r> Produce<'r, Option<IntN>> for MsSQLSourceParser {
1179 type Error = MsSQLSourceError;
1180
1181 #[throws(MsSQLSourceError)]
1182 fn produce(&'r mut self) -> Option<IntN> {
1183 let (ridx, cidx) = self.next_loc()?;
1184 match self.take_cell(ridx, cidx) {
1185 TdsCell::U8(v) => Some(IntN(v as i64)),
1186 TdsCell::I16(v) => Some(IntN(v as i64)),
1187 TdsCell::I32(v) => Some(IntN(v as i64)),
1188 TdsCell::I64(v) => Some(IntN(v)),
1189 TdsCell::Null => None,
1190 other => throw!(anyhow!(
1191 "MsSQL type mismatch at ({}, {}): {:?}",
1192 ridx,
1193 cidx,
1194 other
1195 )),
1196 }
1197 }
1198}
1199
1200impl<'r> Produce<'r, FloatN> for MsSQLSourceParser {
1201 type Error = MsSQLSourceError;
1202
1203 #[throws(MsSQLSourceError)]
1204 fn produce(&'r mut self) -> FloatN {
1205 let (ridx, cidx) = self.next_loc()?;
1206 match self.take_cell(ridx, cidx) {
1207 TdsCell::F32(v) => FloatN(v as f64),
1208 TdsCell::F64(v) => FloatN(v),
1209 TdsCell::Null => throw!(anyhow!("MsSQL get None at position: ({}, {})", ridx, cidx)),
1210 other => throw!(anyhow!(
1211 "MsSQL type mismatch at ({}, {}): {:?}",
1212 ridx,
1213 cidx,
1214 other
1215 )),
1216 }
1217 }
1218}
1219
1220impl<'r> Produce<'r, Option<FloatN>> for MsSQLSourceParser {
1221 type Error = MsSQLSourceError;
1222
1223 #[throws(MsSQLSourceError)]
1224 fn produce(&'r mut self) -> Option<FloatN> {
1225 let (ridx, cidx) = self.next_loc()?;
1226 match self.take_cell(ridx, cidx) {
1227 TdsCell::F32(v) => Some(FloatN(v as f64)),
1228 TdsCell::F64(v) => Some(FloatN(v)),
1229 TdsCell::Null => None,
1230 other => throw!(anyhow!(
1231 "MsSQL type mismatch at ({}, {}): {:?}",
1232 ridx,
1233 cidx,
1234 other
1235 )),
1236 }
1237 }
1238}
1239
1240impl<'r> Produce<'r, &'r str> for MsSQLSourceParser {
1241 type Error = MsSQLSourceError;
1242
1243 #[throws(MsSQLSourceError)]
1244 fn produce(&'r mut self) -> &'r str {
1245 let (ridx, cidx) = self.next_loc()?;
1246 match &self.rowbuf[ridx][cidx] {
1247 TdsCell::Str(s) => s.as_str(),
1248 TdsCell::Null => throw!(anyhow!("MsSQL get None at position: ({}, {})", ridx, cidx)),
1249 other => throw!(anyhow!(
1250 "MsSQL type mismatch at ({}, {}): {:?}",
1251 ridx,
1252 cidx,
1253 other
1254 )),
1255 }
1256 }
1257}
1258
1259impl<'r> Produce<'r, Option<&'r str>> for MsSQLSourceParser {
1260 type Error = MsSQLSourceError;
1261
1262 #[throws(MsSQLSourceError)]
1263 fn produce(&'r mut self) -> Option<&'r str> {
1264 let (ridx, cidx) = self.next_loc()?;
1265 match &self.rowbuf[ridx][cidx] {
1266 TdsCell::Str(s) => Some(s.as_str()),
1267 TdsCell::Null => None,
1268 other => throw!(anyhow!(
1269 "MsSQL type mismatch at ({}, {}): {:?}",
1270 ridx,
1271 cidx,
1272 other
1273 )),
1274 }
1275 }
1276}
1277
1278impl<'r> Produce<'r, &'r [u8]> for MsSQLSourceParser {
1279 type Error = MsSQLSourceError;
1280
1281 #[throws(MsSQLSourceError)]
1282 fn produce(&'r mut self) -> &'r [u8] {
1283 let (ridx, cidx) = self.next_loc()?;
1284 match &self.rowbuf[ridx][cidx] {
1285 TdsCell::Bytes(b) => b.as_slice(),
1286 TdsCell::Null => throw!(anyhow!("MsSQL get None at position: ({}, {})", ridx, cidx)),
1287 other => throw!(anyhow!(
1288 "MsSQL type mismatch at ({}, {}): {:?}",
1289 ridx,
1290 cidx,
1291 other
1292 )),
1293 }
1294 }
1295}
1296
1297impl<'r> Produce<'r, Option<&'r [u8]>> for MsSQLSourceParser {
1298 type Error = MsSQLSourceError;
1299
1300 #[throws(MsSQLSourceError)]
1301 fn produce(&'r mut self) -> Option<&'r [u8]> {
1302 let (ridx, cidx) = self.next_loc()?;
1303 match &self.rowbuf[ridx][cidx] {
1304 TdsCell::Bytes(b) => Some(b.as_slice()),
1305 TdsCell::Null => None,
1306 other => throw!(anyhow!(
1307 "MsSQL type mismatch at ({}, {}): {:?}",
1308 ridx,
1309 cidx,
1310 other
1311 )),
1312 }
1313 }
1314}