1#[cfg(all(feature = "blocking", target_arch = "wasm32"))]
67compile_error!(
68 "neotales-dbapi's blocking feature is unsupported on wasm32; disable it and consult your provider's supported APIs"
69);
70
71#[cfg(all(feature = "blocking", not(target_arch = "wasm32")))]
72pub mod blocking;
73pub mod local;
74pub mod paging;
75pub mod sync;
76
77pub use neotales_resilience::{Cancellation, Delay};
78use neotales_resilience::{
79 RetryOutcome, RetryPolicy as ResilienceRetryPolicy, execute_idempotent_retry,
80};
81use std::{
82 collections::VecDeque,
83 error::Error,
84 fmt,
85 future::{Future, poll_fn},
86 panic::{AssertUnwindSafe, catch_unwind},
87 pin::Pin,
88 sync::{
89 Arc, Mutex, Weak,
90 atomic::{AtomicBool, Ordering},
91 },
92 task::{Context, Poll},
93 time::{Duration, Instant},
94};
95
96pub type DbFuture<'a, T> = Pin<Box<dyn Future<Output = Result<T, DbError>> + Send + 'a>>;
98
99#[derive(Clone, Copy, Debug, Eq, PartialEq)]
101pub enum DbType {
102 Bool,
104 I64,
106 F64,
108 Text,
110 Bytes,
112}
113
114#[derive(Clone, Debug, PartialEq)]
116pub enum Value {
117 Null(DbType),
119 Bool(bool),
121 I64(i64),
123 F64(f64),
125 Text(String),
127 Bytes(Vec<u8>),
129}
130impl Value {
131 pub fn validate(&self) -> Result<(), DbError> {
136 if matches!(self, Self::F64(value) if !value.is_finite()) {
137 Err(DbError::invalid(InvalidArgumentReason::NonFiniteFloat))
138 } else {
139 Ok(())
140 }
141 }
142}
143
144#[derive(Clone, Debug, PartialEq)]
146pub struct Parameter {
147 db_type: DbType,
148 value: Value,
149}
150impl Parameter {
151 pub fn new(db_type: DbType, value: Value) -> Result<Self, DbError> {
156 let matches = matches!((&value, db_type), (Value::Null(t), expected) if *t == expected)
157 || matches!(
158 (&value, db_type),
159 (Value::Bool(_), DbType::Bool)
160 | (Value::I64(_), DbType::I64)
161 | (Value::F64(_), DbType::F64)
162 | (Value::Text(_), DbType::Text)
163 | (Value::Bytes(_), DbType::Bytes)
164 );
165 if !matches {
166 return Err(DbError::invalid(
167 InvalidArgumentReason::ParameterTypeMismatch,
168 ));
169 }
170 value.validate()?;
171 Ok(Self { db_type, value })
172 }
173 #[must_use]
175 pub const fn db_type(&self) -> DbType {
176 self.db_type
177 }
178 #[must_use]
180 pub fn value(&self) -> &Value {
181 &self.value
182 }
183}
184
185#[allow(clippy::struct_excessive_bools)] #[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
188pub struct Capabilities {
189 pub transactions: bool,
191 pub isolation_level: bool,
193 pub read_only_transactions: bool,
195 pub trusted_scripts: bool,
197}
198
199#[derive(Clone, Copy, Debug, Eq, PartialEq)]
201pub enum IsolationLevel {
202 Serializable,
204 RepeatableRead,
206 ReadCommitted,
208 ReadUncommitted,
210}
211#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
213pub struct TxOptions {
214 pub isolation: Option<IsolationLevel>,
216 pub read_only: Option<bool>,
218}
219#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
221pub struct ExecuteOptions {
222 pub timeout_ms: Option<u64>,
224}
225
226#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
228pub enum QuerySetting {
229 #[default]
231 Inherit,
232 Off,
234 On,
236}
237
238#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
240pub enum ReplaySafety {
241 #[default]
243 Never,
244 ExplicitlyReplaySafe,
246}
247
248#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
250pub enum RetryPolicy {
251 #[default]
253 Disabled,
254 Enabled {
256 policy: ResilienceRetryPolicy,
258 retry_timeouts: bool,
260 },
261}
262impl RetryPolicy {
263 pub fn new(
271 max_attempts: u32,
272 delay: Delay,
273 retry_timeouts: bool,
274 ) -> Result<Self, InvalidRetryPolicy> {
275 let policy =
276 ResilienceRetryPolicy::new(max_attempts, delay).map_err(|_| InvalidRetryPolicy)?;
277 Ok(Self::Enabled {
278 policy,
279 retry_timeouts,
280 })
281 }
282}
283
284#[derive(Clone, Copy, Debug, Eq, PartialEq)]
286pub struct InvalidRetryPolicy;
287impl fmt::Display for InvalidRetryPolicy {
288 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
289 formatter.write_str("retry policy requires at least one attempt")
290 }
291}
292impl Error for InvalidRetryPolicy {}
293
294#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
296pub enum RetrySetting {
297 #[default]
299 Inherit,
300 Off,
302 Use(RetryPolicy),
304}
305
306pub struct RetryRuntime {
313 cancellation: Arc<Cancellation>,
314 timer: Arc<dyn Fn() -> RetryWait + Send + Sync>,
315 sleep: Arc<dyn Fn(Duration) -> RetryWait + Send + Sync>,
316 random: Arc<dyn Fn() -> u64 + Send + Sync>,
317 dispatch: Option<Weak<RetryDispatch>>,
320}
321impl Clone for RetryRuntime {
322 fn clone(&self) -> Self {
323 Self {
324 cancellation: Arc::clone(&self.cancellation),
325 timer: Arc::clone(&self.timer),
326 sleep: Arc::clone(&self.sleep),
327 random: Arc::clone(&self.random),
328 dispatch: self.dispatch.clone(),
329 }
330 }
331}
332
333pub type RetryWait = Pin<Box<dyn Future<Output = ()> + Send>>;
335
336impl RetryRuntime {
337 pub fn new(
341 cancellation: Arc<Cancellation>,
342 timer: impl Fn() -> RetryWait + Send + Sync + 'static,
343 sleep: impl Fn(Duration) -> RetryWait + Send + Sync + 'static,
344 random: impl Fn() -> u64 + Send + Sync + 'static,
345 ) -> Self {
346 Self {
347 cancellation,
348 timer: Arc::new(timer),
349 sleep: Arc::new(sleep),
350 random: Arc::new(random),
351 dispatch: None,
352 }
353 }
354}
355
356impl fmt::Debug for RetryRuntime {
357 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
358 formatter
359 .debug_struct("RetryRuntime")
360 .field("cancelled", &self.cancellation.is_cancelled())
361 .finish_non_exhaustive()
362 }
363}
364
365#[derive(Clone, Copy, Debug, Eq, PartialEq)]
367pub enum TelemetryOutcome {
368 Success,
370 Error(ErrorKind),
372}
373
374#[derive(Clone, Copy, Debug, Eq, PartialEq)]
376pub enum Operation {
377 Execute,
379 Fetch,
381}
382
383#[derive(Clone, Debug, Eq, PartialEq)]
385pub struct DbEvent {
386 pub operation: Operation,
388 pub duration: Duration,
390 pub outcome: TelemetryOutcome,
392 pub sql: Option<String>,
394}
395
396pub type SqlCaptureHook = Arc<dyn Fn(&str) -> Option<String> + Send + Sync>;
401pub type DbObserver = Arc<dyn Fn(&DbEvent) + Send + Sync>;
407
408#[derive(Clone)]
410pub struct PoolPolicy {
411 pub telemetry_enabled: bool,
413 pub sql_capture_enabled: bool,
415 pub sql_hook: Option<SqlCaptureHook>,
417 pub observer: Option<DbObserver>,
419 pub retry: RetryPolicy,
421 pub retry_runtime: Option<RetryRuntime>,
423 pub default_timeout: Option<Duration>,
426 pub default_limit: RowLimit,
428}
429impl Default for PoolPolicy {
430 fn default() -> Self {
431 let defaults = PoolDefaults::default();
432 Self {
433 telemetry_enabled: defaults.telemetry_enabled,
434 sql_capture_enabled: defaults.sql_capture_enabled,
435 sql_hook: None,
436 observer: None,
437 retry: defaults.retry,
438 retry_runtime: None,
439 default_timeout: defaults.timeout,
440 default_limit: defaults.limit,
441 }
442 }
443}
444fn policy_defaults(policy: &PoolPolicy) -> PoolDefaults {
445 PoolDefaults {
446 timeout: policy.default_timeout,
447 limit: policy.default_limit,
448 telemetry_enabled: policy.telemetry_enabled,
449 sql_capture_enabled: policy.sql_capture_enabled,
450 retry: policy.retry,
451 }
452}
453impl fmt::Debug for PoolPolicy {
454 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
455 formatter
456 .debug_struct("PoolPolicy")
457 .field("telemetry_enabled", &self.telemetry_enabled)
458 .field("sql_capture_enabled", &self.sql_capture_enabled)
459 .field("has_sql_hook", &self.sql_hook.is_some())
460 .field("has_observer", &self.observer.is_some())
461 .field("retry", &self.retry)
462 .field("has_retry_runtime", &self.retry_runtime.is_some())
463 .field("default_timeout", &self.default_timeout)
464 .field("default_limit", &self.default_limit)
465 .finish()
466 }
467}
468
469#[derive(Clone, Default)]
471pub struct QueryOptions {
472 pub parameters: Vec<Parameter>,
474 pub timeout: TimeoutSetting,
476 pub limit: LimitSetting,
478 execute: ExecuteOptions,
480 pub telemetry: QuerySetting,
482 pub sql_capture: QuerySetting,
484 pub sql_hook: Option<SqlCaptureHook>,
486 pub retry: RetrySetting,
488 pub replay_safety: ReplaySafety,
490 pub retry_runtime: Option<RetryRuntime>,
492 policy_applied: bool,
494}
495impl fmt::Debug for QueryOptions {
496 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
497 formatter
498 .debug_struct("QueryOptions")
499 .field("parameter_count", &self.parameters.len())
500 .field("timeout", &self.timeout)
501 .field("limit", &self.limit)
502 .field("execute", &self.execute)
503 .field("telemetry", &self.telemetry)
504 .field("sql_capture", &self.sql_capture)
505 .field("has_sql_hook", &self.sql_hook.is_some())
506 .field("retry", &self.retry)
507 .field("replay_safety", &self.replay_safety)
508 .field("has_retry_runtime", &self.retry_runtime.is_some())
509 .finish_non_exhaustive()
510 }
511}
512impl QueryOptions {
513 #[must_use]
515 pub fn provider_execute_options(&self) -> ExecuteOptions {
516 self.execute
517 }
518 #[must_use]
521 pub fn new() -> Self {
522 Self::default()
523 }
524
525 #[must_use]
527 pub fn bind(mut self, parameter: Parameter) -> Self {
528 self.parameters.push(parameter);
529 self
530 }
531
532 #[must_use]
534 pub fn bind_all(mut self, parameters: &[Parameter]) -> Self {
535 self.parameters.extend_from_slice(parameters);
536 self
537 }
538
539 pub fn bind_f64(mut self, value: f64) -> Result<Self, DbError> {
544 self.parameters
545 .push(Parameter::new(DbType::F64, Value::F64(value))?);
546 Ok(self)
547 }
548
549 #[must_use]
551 pub fn bind_null(mut self, db_type: DbType) -> Self {
552 self.parameters.push(Parameter {
553 db_type,
554 value: Value::Null(db_type),
555 });
556 self
557 }
558
559 #[must_use]
561 pub fn timeout(mut self, timeout: Duration) -> Self {
562 self.timeout = TimeoutSetting::Set(timeout);
563 self
564 }
565
566 #[must_use]
568 pub fn no_timeout(mut self) -> Self {
569 self.timeout = TimeoutSetting::Disabled;
570 self
571 }
572
573 #[must_use]
575 pub fn limit(mut self, limit: RowLimit) -> Self {
576 self.limit = LimitSetting::Set(limit);
577 self
578 }
579
580 #[must_use]
582 pub fn telemetry(mut self, setting: QuerySetting) -> Self {
583 self.telemetry = setting;
584 self
585 }
586
587 #[must_use]
589 pub fn sql_capture(mut self, setting: QuerySetting) -> Self {
590 self.sql_capture = setting;
591 self
592 }
593
594 #[must_use]
596 pub fn retry(mut self, setting: RetrySetting) -> Self {
597 self.retry = setting;
598 self
599 }
600
601 #[must_use]
603 pub fn sql_hook(mut self, hook: SqlCaptureHook) -> Self {
604 self.sql_hook = Some(hook);
605 self
606 }
607
608 #[must_use]
610 pub fn retry_runtime(mut self, runtime: RetryRuntime) -> Self {
611 self.retry_runtime = Some(runtime);
612 self
613 }
614
615 #[must_use]
617 pub fn replay_safe(mut self) -> Self {
618 self.replay_safety = ReplaySafety::ExplicitlyReplaySafe;
619 self
620 }
621
622 #[must_use]
624 pub fn resolved_timeout(&self, defaults: PoolDefaults) -> Option<Duration> {
625 match self.timeout {
626 TimeoutSetting::Inherit => defaults.timeout,
627 TimeoutSetting::Disabled => None,
628 TimeoutSetting::Set(timeout) => Some(timeout),
629 }
630 }
631
632 #[must_use]
634 pub fn resolved_limit(&self, defaults: PoolDefaults) -> RowLimit {
635 match self.limit {
636 LimitSetting::Inherit => defaults.limit,
637 LimitSetting::Set(limit) => limit,
638 }
639 }
640
641 pub fn prepare_provider(&mut self, defaults: PoolDefaults) -> Result<RowLimit, DbError> {
647 if !self.policy_applied {
648 reject_unhandled_pool_options(self)?;
649 }
650 let limit = self.resolved_limit(defaults);
651 self.limit = LimitSetting::Set(limit);
652 resolve_provider_timeout(self, defaults.timeout)?;
653 Ok(limit)
654 }
655
656 pub fn validate_execute(&self) -> Result<(), DbError> {
663 if matches!(self.limit, LimitSetting::Set(_)) {
664 return Err(DbError::new(ErrorKind::InvalidArgument));
665 }
666 Ok(())
667 }
668
669 pub fn prepare_execute_provider(&mut self, defaults: PoolDefaults) -> Result<(), DbError> {
674 self.validate_execute()?;
675 self.prepare_provider(defaults)?;
676 Ok(())
677 }
678
679 pub fn validate_script(&self) -> Result<(), DbError> {
684 if !self.parameters.is_empty() || !matches!(self.limit, LimitSetting::Inherit) {
685 return Err(DbError::new(ErrorKind::InvalidArgument));
686 }
687 Ok(())
688 }
689
690 pub fn prepare_script_provider(&mut self, defaults: PoolDefaults) -> Result<(), DbError> {
695 self.validate_script()?;
696 self.prepare_provider(defaults)?;
697 Ok(())
698 }
699}
700
701fn resolve_provider_timeout(
704 options: &mut QueryOptions,
705 default: Option<Duration>,
706) -> Result<(), DbError> {
707 let timeout = match options.timeout {
708 TimeoutSetting::Inherit => default,
709 TimeoutSetting::Disabled => None,
710 TimeoutSetting::Set(timeout) => Some(timeout),
711 };
712 options.timeout = timeout.map_or(TimeoutSetting::Disabled, TimeoutSetting::Set);
713 options.execute.timeout_ms = timeout
714 .map(|value| {
715 u64::try_from(
716 value
717 .as_millis()
718 .saturating_add(u128::from(value.subsec_nanos() % 1_000_000 != 0)),
719 )
720 .map_err(|_| DbError::new(ErrorKind::InvalidArgument))
721 })
722 .transpose()?;
723 Ok(())
724}
725
726fn reject_unhandled_pool_options(options: &QueryOptions) -> Result<(), DbError> {
729 if options.telemetry == QuerySetting::On
730 || options.sql_capture == QuerySetting::On
731 || options.sql_hook.is_some()
732 || matches!(
733 options.retry,
734 RetrySetting::Use(RetryPolicy::Enabled { .. })
735 )
736 || options.retry_runtime.is_some()
737 {
738 return Err(DbError::new(ErrorKind::Unsupported));
739 }
740 Ok(())
741}
742
743fn reject_session_retry(options: &QueryOptions) -> Result<(), DbError> {
744 if !options.policy_applied
745 && (matches!(
746 options.retry,
747 RetrySetting::Use(RetryPolicy::Enabled { .. })
748 ) || options.retry_runtime.is_some())
749 {
750 return Err(DbError::new(ErrorKind::Unsupported));
751 }
752 Ok(())
753}
754
755#[derive(Clone, Copy, Debug, Eq, PartialEq)]
760pub struct RowLimit {
761 rows: usize,
762 bytes: usize,
763 max_sets: usize,
764}
765impl RowLimit {
766 pub fn new(rows: usize, bytes: usize) -> Result<Self, DbError> {
773 Self::with_max_sets(rows, bytes, 1)
774 }
775 pub fn with_max_sets(rows: usize, bytes: usize, max_sets: usize) -> Result<Self, DbError> {
783 if rows == 0 {
784 return Err(DbError::invalid(InvalidArgumentReason::ZeroFetchRowLimit));
785 }
786 if bytes == 0 {
787 return Err(DbError::invalid(InvalidArgumentReason::ZeroByteLimit));
788 }
789 if max_sets == 0 {
790 return Err(DbError::invalid(InvalidArgumentReason::ZeroSetLimit));
791 }
792 Ok(Self {
793 rows,
794 bytes,
795 max_sets,
796 })
797 }
798 #[must_use]
800 pub const fn rows(self) -> usize {
801 self.rows
802 }
803 #[must_use]
805 pub const fn bytes(self) -> usize {
806 self.bytes
807 }
808 #[must_use]
810 pub const fn max_sets(self) -> usize {
811 self.max_sets
812 }
813}
814
815impl Default for RowLimit {
816 fn default() -> Self {
818 Self {
819 rows: 1_000,
820 bytes: 1_048_576,
821 max_sets: 1,
822 }
823 }
824}
825
826#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
829pub enum TimeoutSetting {
830 #[default]
832 Inherit,
833 Disabled,
835 Set(Duration),
837}
838
839#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
841pub enum LimitSetting {
842 #[default]
844 Inherit,
845 Set(RowLimit),
847}
848
849#[derive(Clone, Copy, Debug, Eq, PartialEq)]
851pub struct PoolDefaults {
852 pub timeout: Option<Duration>,
854 pub limit: RowLimit,
856 pub telemetry_enabled: bool,
858 pub sql_capture_enabled: bool,
860 pub retry: RetryPolicy,
862}
863impl Default for PoolDefaults {
864 fn default() -> Self {
865 Self {
866 timeout: None,
869 limit: RowLimit::default(),
870 telemetry_enabled: false,
871 sql_capture_enabled: false,
872 retry: RetryPolicy::Disabled,
873 }
874 }
875}
876
877#[derive(Clone, Copy, Debug, Eq, PartialEq)]
879pub enum ErrorKind {
880 InvalidArgument,
882 Constraint,
884 Busy,
886 Timeout,
888 Cancelled,
890 Unsupported,
892 Reentrant,
897 Decode,
899 Connection,
901 WriteOutcomeUnknown,
903 CommitOutcomeUnknown,
905 Missing,
907 NoRows,
909 TooManyRows,
911 Ambiguous,
913 Null,
915 Overflow,
917 WrongType,
919}
920#[derive(Clone, Copy, Debug, Eq, PartialEq)]
922pub struct DbError {
923 kind: ErrorKind,
924 reason: Option<InvalidArgumentReason>,
925}
926#[derive(Clone, Copy, Debug, Eq, PartialEq)]
928pub enum InvalidArgumentReason {
929 ParameterTypeMismatch,
931 NonFiniteFloat,
933 ZeroFetchRowLimit,
935 ZeroByteLimit,
937 ZeroSetLimit,
939}
940impl DbError {
941 #[must_use]
943 pub const fn new(kind: ErrorKind) -> Self {
944 Self { kind, reason: None }
945 }
946 #[must_use]
948 pub const fn invalid(reason: InvalidArgumentReason) -> Self {
949 Self {
950 kind: ErrorKind::InvalidArgument,
951 reason: Some(reason),
952 }
953 }
954 #[must_use]
956 pub const fn reason(self) -> Option<InvalidArgumentReason> {
957 self.reason
958 }
959 #[must_use]
961 pub const fn kind(self) -> ErrorKind {
962 self.kind
963 }
964}
965impl fmt::Display for DbError {
966 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
967 match self.reason {
968 Some(reason) => write!(f, "invalid database argument ({reason:?})"),
969 None => write!(f, "database operation failed ({:?})", self.kind),
970 }
971 }
972}
973impl Error for DbError {}
974
975#[derive(Clone, Debug, PartialEq)]
977pub struct Row {
978 columns: Vec<(String, Value)>,
979}
980impl Row {
981 pub fn new(columns: Vec<(String, Value)>) -> Result<Self, DbError> {
986 for (_, value) in &columns {
987 value.validate()?;
988 }
989 Ok(Self { columns })
990 }
991 #[must_use]
993 pub fn len(&self) -> usize {
994 self.columns.len()
995 }
996 #[must_use]
998 pub fn is_empty(&self) -> bool {
999 self.columns.is_empty()
1000 }
1001 pub fn get_ordinal<T: FromValue>(&self, ordinal: usize) -> Result<T, DbError> {
1006 let (_, value) = self
1007 .columns
1008 .get(ordinal)
1009 .ok_or_else(|| DbError::new(ErrorKind::Missing))?;
1010 T::from_value(value)
1011 }
1012 pub fn get<T: FromValue>(&self, name: &str) -> Result<T, DbError> {
1017 let mut found = self.columns.iter().filter(|(column, _)| column == name);
1018 let (_, value) = found
1019 .next()
1020 .ok_or_else(|| DbError::new(ErrorKind::Missing))?;
1021 if found.next().is_some() {
1022 return Err(DbError::new(ErrorKind::Ambiguous));
1023 }
1024 T::from_value(value)
1025 }
1026 pub fn read<T: FromValue>(&self, name: &str) -> Result<T, DbError> {
1031 self.get(name)
1032 }
1033 pub fn read_at<T: FromValue>(&self, ordinal: usize) -> Result<T, DbError> {
1039 self.get_ordinal(ordinal)
1040 }
1041 pub fn value_at(&self, ordinal: usize) -> Result<Value, DbError> {
1046 self.columns
1047 .get(ordinal)
1048 .map(|(_, value)| value.clone())
1049 .ok_or_else(|| DbError::new(ErrorKind::Missing))
1050 }
1051 pub fn encoded_bytes(&self) -> Result<usize, DbError> {
1059 self.columns
1060 .iter()
1061 .try_fold(0usize, |total, (name, value)| {
1062 let payload = match value {
1063 Value::Null(_) => 0,
1064 Value::Bool(_) => 1,
1065 Value::I64(_) | Value::F64(_) => 8,
1066 Value::Text(value) => value.len(),
1067 Value::Bytes(value) => value.len(),
1068 };
1069 total
1070 .checked_add(name.len())
1071 .and_then(|total| total.checked_add(payload))
1072 .ok_or_else(|| DbError::new(ErrorKind::Overflow))
1073 })
1074 }
1075 pub fn require<T: FromValue>(&self, name: &str) -> Result<T, DbError> {
1080 let mut found = self.columns.iter().filter(|(column, _)| column == name);
1081 let (_, value) = found
1082 .next()
1083 .ok_or_else(|| DbError::new(ErrorKind::Missing))?;
1084 if found.next().is_some() {
1085 return Err(DbError::new(ErrorKind::Ambiguous));
1086 }
1087 if let Value::Null(actual_type) = value {
1088 return Err(DbError::new(if *actual_type == T::DB_TYPE {
1089 ErrorKind::Null
1090 } else {
1091 ErrorKind::WrongType
1092 }));
1093 }
1094 T::from_value(value)
1095 }
1096 pub fn require_ordinal<T: FromValue>(&self, ordinal: usize) -> Result<T, DbError> {
1101 let (_, value) = self
1102 .columns
1103 .get(ordinal)
1104 .ok_or_else(|| DbError::new(ErrorKind::Missing))?;
1105 if let Value::Null(actual_type) = value {
1106 return Err(DbError::new(if *actual_type == T::DB_TYPE {
1107 ErrorKind::Null
1108 } else {
1109 ErrorKind::WrongType
1110 }));
1111 }
1112 T::from_value(value)
1113 }
1114}
1115pub trait FromValue: Sized {
1117 const DB_TYPE: DbType;
1119 fn from_value(value: &Value) -> Result<Self, DbError>;
1125}
1126macro_rules! exact_from {
1127 ($ty:ty, $variant:ident, $db:ident) => {
1128 impl FromValue for $ty {
1129 const DB_TYPE: DbType = DbType::$db;
1130 fn from_value(value: &Value) -> Result<Self, DbError> {
1131 match value {
1132 Value::Null(DbType::$db) => Err(DbError::new(ErrorKind::Null)),
1133 Value::Null(_) => Err(DbError::new(ErrorKind::WrongType)),
1134 Value::$variant(value) => Ok(value.clone()),
1135 _ => Err(DbError::new(ErrorKind::WrongType)),
1136 }
1137 }
1138 }
1139 };
1140}
1141impl<T: FromValue> FromValue for Option<T> {
1142 const DB_TYPE: DbType = T::DB_TYPE;
1143 fn from_value(value: &Value) -> Result<Self, DbError> {
1144 match value {
1145 Value::Null(db_type) if *db_type == T::DB_TYPE => Ok(None),
1146 Value::Null(_) => Err(DbError::new(ErrorKind::WrongType)),
1147 non_null => T::from_value(non_null).map(Some),
1148 }
1149 }
1150}
1151exact_from!(bool, Bool, Bool);
1152exact_from!(i64, I64, I64);
1153exact_from!(f64, F64, F64);
1154exact_from!(String, Text, Text);
1155exact_from!(Vec<u8>, Bytes, Bytes);
1156impl FromValue for i32 {
1158 const DB_TYPE: DbType = DbType::I64;
1159 fn from_value(value: &Value) -> Result<Self, DbError> {
1160 match value {
1161 Value::Null(DbType::I64) => Err(DbError::new(ErrorKind::Null)),
1162 Value::I64(value) => {
1163 i32::try_from(*value).map_err(|_| DbError::new(ErrorKind::Overflow))
1164 }
1165 _ => Err(DbError::new(ErrorKind::WrongType)),
1166 }
1167 }
1168}
1169
1170pub trait Reader: Send {
1185 fn next_row_async(&mut self) -> DbFuture<'_, Option<Row>>;
1192
1193 fn has_next_set_async(&mut self) -> DbFuture<'_, bool>;
1201
1202 fn finish_async(&mut self) -> DbFuture<'_, ()>;
1211
1212 fn read_all_async(&mut self) -> DbFuture<'_, Vec<Row>> {
1221 Box::pin(async move {
1222 Ok(self
1223 .read_sets_async()
1224 .await?
1225 .into_iter()
1226 .flatten()
1227 .collect())
1228 })
1229 }
1230
1231 fn read_sets_async(&mut self) -> DbFuture<'_, Vec<Vec<Row>>> {
1240 Box::pin(async move {
1241 let mut sets = Vec::new();
1242 loop {
1243 let mut set = Vec::new();
1244 while let Some(row) = self.next_row_async().await? {
1245 set.push(row);
1246 }
1247 sets.push(set);
1248 if !self.has_next_set_async().await? {
1249 break;
1250 }
1251 }
1252 self.finish_async().await?;
1253 Ok(sets)
1254 })
1255 }
1256}
1257
1258#[derive(Debug)]
1264pub struct BufferedReader {
1265 sets: VecDeque<VecDeque<Row>>,
1266 done: bool,
1267}
1268impl BufferedReader {
1269 #[must_use]
1271 pub fn new(rows: Vec<Row>) -> Self {
1272 Self::from_sets(vec![rows])
1273 }
1274 #[must_use]
1276 pub fn from_sets(sets: Vec<Vec<Row>>) -> Self {
1277 Self {
1278 sets: sets.into_iter().map(VecDeque::from).collect(),
1279 done: false,
1280 }
1281 }
1282}
1283impl Reader for BufferedReader {
1284 fn next_row_async(&mut self) -> DbFuture<'_, Option<Row>> {
1285 let row = if self.done {
1286 None
1287 } else {
1288 self.sets
1289 .front_mut()
1290 .and_then(std::collections::VecDeque::pop_front)
1291 };
1292 Box::pin(async move { Ok(row) })
1293 }
1294
1295 fn has_next_set_async(&mut self) -> DbFuture<'_, bool> {
1296 if self.done {
1297 return Box::pin(async { Ok(false) });
1298 }
1299 self.sets.pop_front();
1300 let more = !self.sets.is_empty();
1301 if !more {
1302 self.done = true;
1303 }
1304 Box::pin(async move { Ok(more) })
1305 }
1306
1307 fn finish_async(&mut self) -> DbFuture<'_, ()> {
1308 self.sets.clear();
1309 self.done = true;
1310 Box::pin(async { Ok(()) })
1311 }
1312}
1313
1314fn row_cardinality_error(more_than_one: bool) -> DbError {
1315 DbError::new(if more_than_one {
1316 ErrorKind::TooManyRows
1317 } else {
1318 ErrorKind::NoRows
1319 })
1320}
1321
1322pub trait Pool: Send + Sync {
1324 fn capabilities(&self) -> Capabilities;
1326 fn defaults(&self) -> PoolDefaults {
1328 PoolDefaults::default()
1329 }
1330 fn acquire_async(&self) -> DbFuture<'_, Box<dyn Session>>;
1332 fn execute_async<'a>(&'a self, sql: &'a str, mut options: QueryOptions) -> DbFuture<'a, u64> {
1338 Box::pin(async move {
1339 options.validate_execute()?;
1340 reject_unhandled_pool_options(&options)?;
1341 resolve_provider_timeout(&mut options, self.defaults().timeout)?;
1342 let mut session = self.acquire_async().await?;
1343 session.execute_async(sql, options).await
1344 })
1345 }
1346 fn fetch_async<'a>(
1353 &'a self,
1354 sql: &'a str,
1355 mut options: QueryOptions,
1356 ) -> DbFuture<'a, Box<dyn Reader + 'a>> {
1357 Box::pin(async move {
1358 reject_unhandled_pool_options(&options)?;
1359 let limit = options.resolved_limit(self.defaults());
1360 options.limit = LimitSetting::Set(limit);
1361 resolve_provider_timeout(&mut options, self.defaults().timeout)?;
1362 let mut session = self.acquire_async().await?;
1363 let mut reader = session.fetch_async(sql, options).await?;
1364 let sets = collect_sets(reader.as_mut(), limit).await?;
1365 Ok(Box::new(BufferedReader::from_sets(sets)) as Box<dyn Reader + 'a>)
1366 })
1367 }
1368 fn fetch_all_async<'a>(
1373 &'a self,
1374 sql: &'a str,
1375 options: QueryOptions,
1376 ) -> DbFuture<'a, Vec<Row>> {
1377 Box::pin(async move {
1378 let limit = options.resolved_limit(self.defaults());
1379 let mut reader = self.fetch_async(sql, options).await?;
1380 let sets = collect_sets(reader.as_mut(), limit).await?;
1381 Ok(sets.into_iter().flatten().collect())
1382 })
1383 }
1384 fn fetch_first_async<'a>(
1389 &'a self,
1390 sql: &'a str,
1391 options: QueryOptions,
1392 ) -> DbFuture<'a, Option<Row>> {
1393 Box::pin(async move {
1394 let mut reader = self.fetch_async(sql, options).await?;
1395 let first = reader.next_row_async().await?;
1396 reader.finish_async().await?;
1397 Ok(first)
1398 })
1399 }
1400 fn fetch_one_async<'a>(&'a self, sql: &'a str, options: QueryOptions) -> DbFuture<'a, Row> {
1408 Box::pin(async move {
1409 let mut reader = self.fetch_async(sql, options).await?;
1410 let first = reader.next_row_async().await?;
1411 let more = reader.next_row_async().await?.is_some();
1412 reader.finish_async().await?;
1413 match first {
1414 None => Err(row_cardinality_error(false)),
1415 Some(_) if more => Err(row_cardinality_error(true)),
1416 Some(row) => Ok(row),
1417 }
1418 })
1419 }
1420 fn fetch_scalar_async<'a>(
1426 &'a self,
1427 sql: &'a str,
1428 options: QueryOptions,
1429 ) -> DbFuture<'a, Value> {
1430 Box::pin(async move {
1431 let row = self.fetch_one_async(sql, options).await?;
1432 row.value_at(0)
1433 })
1434 }
1435}
1436pub trait Session: Send {
1438 fn defaults(&self) -> PoolDefaults {
1440 PoolDefaults::default()
1441 }
1442 fn execute_async<'a>(&'a mut self, sql: &'a str, options: QueryOptions) -> DbFuture<'a, u64>;
1447 fn fetch_async<'a>(
1456 &'a mut self,
1457 sql: &'a str,
1458 options: QueryOptions,
1459 ) -> DbFuture<'a, Box<dyn Reader + 'a>>;
1460 fn fetch_all_async<'a>(
1465 &'a mut self,
1466 sql: &'a str,
1467 options: QueryOptions,
1468 ) -> DbFuture<'a, Vec<Row>> {
1469 let limit = options.resolved_limit(self.defaults());
1470 Box::pin(async move {
1471 let mut reader = self.fetch_async(sql, options).await?;
1472 let sets = collect_sets(reader.as_mut(), limit).await?;
1473 Ok(sets.into_iter().flatten().collect())
1474 })
1475 }
1476 fn fetch_first_async<'a>(
1481 &'a mut self,
1482 sql: &'a str,
1483 options: QueryOptions,
1484 ) -> DbFuture<'a, Option<Row>> {
1485 Box::pin(async move {
1486 let mut reader = self.fetch_async(sql, options).await?;
1487 let first = reader.next_row_async().await?;
1488 reader.finish_async().await?;
1489 Ok(first)
1490 })
1491 }
1492 fn fetch_one_async<'a>(&'a mut self, sql: &'a str, options: QueryOptions) -> DbFuture<'a, Row> {
1500 Box::pin(async move {
1501 let mut reader = self.fetch_async(sql, options).await?;
1502 let first = reader.next_row_async().await?;
1503 let more = reader.next_row_async().await?.is_some();
1504 reader.finish_async().await?;
1505 match first {
1506 None => Err(row_cardinality_error(false)),
1507 Some(_) if more => Err(row_cardinality_error(true)),
1508 Some(row) => Ok(row),
1509 }
1510 })
1511 }
1512 fn fetch_scalar_async<'a>(
1518 &'a mut self,
1519 sql: &'a str,
1520 options: QueryOptions,
1521 ) -> DbFuture<'a, Value> {
1522 Box::pin(async move {
1523 let row = self.fetch_one_async(sql, options).await?;
1524 row.value_at(0)
1525 })
1526 }
1527 fn execute_trusted_script_async<'a>(
1530 &'a mut self,
1531 sql: &'a str,
1532 options: QueryOptions,
1533 ) -> DbFuture<'a, ()>;
1534 fn begin_async<'a>(
1537 &'a mut self,
1538 options: TxOptions,
1539 ) -> DbFuture<'a, Box<dyn Transaction<'a> + 'a>>;
1540}
1541pub trait Transaction<'session>: Send {
1548 fn defaults(&self) -> PoolDefaults {
1550 PoolDefaults::default()
1551 }
1552 fn execute_async<'a>(&'a mut self, sql: &'a str, options: QueryOptions) -> DbFuture<'a, u64>;
1557 fn fetch_async<'a>(
1564 &'a mut self,
1565 sql: &'a str,
1566 options: QueryOptions,
1567 ) -> DbFuture<'a, Box<dyn Reader + 'a>>;
1568 fn fetch_all_async<'a>(
1573 &'a mut self,
1574 sql: &'a str,
1575 options: QueryOptions,
1576 ) -> DbFuture<'a, Vec<Row>> {
1577 let limit = options.resolved_limit(self.defaults());
1578 Box::pin(async move {
1579 let mut reader = self.fetch_async(sql, options).await?;
1580 let sets = collect_sets(reader.as_mut(), limit).await?;
1581 Ok(sets.into_iter().flatten().collect())
1582 })
1583 }
1584 fn fetch_first_async<'a>(
1589 &'a mut self,
1590 sql: &'a str,
1591 options: QueryOptions,
1592 ) -> DbFuture<'a, Option<Row>> {
1593 Box::pin(async move {
1594 let mut reader = self.fetch_async(sql, options).await?;
1595 let first = reader.next_row_async().await?;
1596 reader.finish_async().await?;
1597 Ok(first)
1598 })
1599 }
1600 fn fetch_one_async<'a>(&'a mut self, sql: &'a str, options: QueryOptions) -> DbFuture<'a, Row> {
1608 Box::pin(async move {
1609 let mut reader = self.fetch_async(sql, options).await?;
1610 let first = reader.next_row_async().await?;
1611 let more = reader.next_row_async().await?.is_some();
1612 reader.finish_async().await?;
1613 match first {
1614 None => Err(row_cardinality_error(false)),
1615 Some(_) if more => Err(row_cardinality_error(true)),
1616 Some(row) => Ok(row),
1617 }
1618 })
1619 }
1620 fn fetch_scalar_async<'a>(
1626 &'a mut self,
1627 sql: &'a str,
1628 options: QueryOptions,
1629 ) -> DbFuture<'a, Value> {
1630 Box::pin(async move {
1631 let row = self.fetch_one_async(sql, options).await?;
1632 row.value_at(0)
1633 })
1634 }
1635 fn execute_trusted_script_async<'a>(
1638 &'a mut self,
1639 sql: &'a str,
1640 options: QueryOptions,
1641 ) -> DbFuture<'a, ()>;
1642 fn commit_async(self: Box<Self>) -> DbFuture<'session, ()>;
1647 fn rollback_async(self: Box<Self>) -> DbFuture<'session, ()>;
1651}
1652pub trait ImmediateTransaction: Session {
1654 fn begin_immediate_async<'a>(&'a mut self) -> DbFuture<'a, Box<dyn Transaction<'a> + 'a>>;
1656}
1657
1658pub trait SqlitePool: Pool {
1663 fn busy_timeout(&self) -> Duration;
1665
1666 fn acquire_sqlite_async(&self) -> DbFuture<'_, Box<dyn ImmediateTransaction>>;
1668}
1669
1670pub struct PolicyPool {
1685 inner: Arc<dyn Pool>,
1686 policy: Arc<PoolPolicy>,
1687}
1688impl fmt::Debug for PolicyPool {
1689 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1690 formatter
1691 .debug_struct("PolicyPool")
1692 .field("policy", &self.policy)
1693 .finish_non_exhaustive()
1694 }
1695}
1696impl PolicyPool {
1697 pub fn new<P: Pool + 'static>(pool: P, policy: PoolPolicy) -> Self {
1699 Self::from_shared(Arc::new(pool), policy)
1700 }
1701
1702 #[must_use]
1704 pub fn from_shared(pool: Arc<dyn Pool>, mut policy: PoolPolicy) -> Self {
1705 if policy.default_timeout.is_none() {
1706 policy.default_timeout = pool.defaults().timeout;
1707 }
1708 Self {
1709 inner: pool,
1710 policy: Arc::new(policy),
1711 }
1712 }
1713}
1714
1715impl Pool for PolicyPool {
1716 fn capabilities(&self) -> Capabilities {
1717 self.inner.capabilities()
1718 }
1719
1720 fn defaults(&self) -> PoolDefaults {
1721 policy_defaults(&self.policy)
1722 }
1723
1724 fn acquire_async(&self) -> DbFuture<'_, Box<dyn Session>> {
1725 let inner = Arc::clone(&self.inner);
1726 let policy = Arc::clone(&self.policy);
1727 Box::pin(async move {
1728 let session = inner.acquire_async().await?;
1729 Ok(Box::new(PolicySession { session, policy }) as Box<dyn Session>)
1730 })
1731 }
1732
1733 fn execute_async<'a>(&'a self, sql: &'a str, mut options: QueryOptions) -> DbFuture<'a, u64> {
1734 let pool = Arc::clone(&self.inner);
1735 let policy = Arc::clone(&self.policy);
1736 Box::pin(async move {
1737 options.validate_execute()?;
1738 resolve_provider_timeout(&mut options, policy.default_timeout)?;
1739 let retry = resolve_retry(options.retry, policy.retry);
1740 if options.replay_safety == ReplaySafety::ExplicitlyReplaySafe
1741 && let RetryPolicy::Enabled {
1742 policy: retry_policy,
1743 retry_timeouts,
1744 } = retry
1745 {
1746 let Some(mut runtime) = options
1747 .retry_runtime
1748 .clone()
1749 .or_else(|| policy.retry_runtime.clone())
1750 else {
1751 return Err(DbError::new(ErrorKind::Unsupported));
1752 };
1753 let dispatch = RetryDispatch::for_operation(&mut runtime);
1754 let cancellation = Arc::clone(&dispatch.cancellation);
1755 let deadline = dispatch.deadline.clone();
1756 let attempt_state = Arc::clone(&dispatch.state);
1757 let mut options = options;
1758 options.retry_runtime = Some(runtime.clone());
1759 let retry_if = |error: &DbError| {
1760 retry_allowed(*error, retry_timeouts, &cancellation, &deadline)
1761 };
1762 let outcome = execute_idempotent_retry(
1763 retry_policy,
1764 &cancellation,
1765 deadline.clone(),
1766 || {
1767 let pool = Arc::clone(&pool);
1768 let policy = Arc::clone(&policy);
1769 let cancellation = Arc::clone(&cancellation);
1770 let deadline = deadline.clone();
1771 let attempt_state = Arc::clone(&attempt_state);
1772 let options = options.clone();
1773 async move {
1774 attempt_state.reset();
1775 deadline.check(&cancellation).await?;
1776 let mut session = pool.acquire_async().await?;
1777 let result = execute_observed(
1778 session.as_mut(),
1779 sql,
1780 options,
1781 Arc::clone(&policy),
1782 )
1783 .await;
1784 drop(session);
1785 result
1786 }
1787 },
1788 retry_if,
1789 || (runtime.random)(),
1790 |delay| (runtime.sleep)(delay),
1791 )
1792 .await;
1793 drop(dispatch);
1794 return retry_result_with_interrupt(outcome, &attempt_state);
1795 }
1796
1797 let mut session = pool.acquire_async().await?;
1798 let result = execute_observed(session.as_mut(), sql, options, policy).await;
1799 drop(session);
1800 result
1801 })
1802 }
1803
1804 fn fetch_async<'a>(
1805 &'a self,
1806 sql: &'a str,
1807 mut options: QueryOptions,
1808 ) -> DbFuture<'a, Box<dyn Reader + 'a>> {
1809 let pool = Arc::clone(&self.inner);
1810 let policy = Arc::clone(&self.policy);
1811 Box::pin(async move {
1812 let limit = match options.limit {
1813 LimitSetting::Inherit => policy.default_limit,
1814 LimitSetting::Set(limit) => limit,
1815 };
1816 options.limit = LimitSetting::Set(limit);
1817 resolve_provider_timeout(&mut options, policy.default_timeout)?;
1818 let retry = resolve_retry(options.retry, policy.retry);
1819 if options.replay_safety == ReplaySafety::ExplicitlyReplaySafe
1820 && let RetryPolicy::Enabled {
1821 policy: retry_policy,
1822 retry_timeouts,
1823 } = retry
1824 {
1825 let Some(mut runtime) = options
1826 .retry_runtime
1827 .clone()
1828 .or_else(|| policy.retry_runtime.clone())
1829 else {
1830 return Err(DbError::new(ErrorKind::Unsupported));
1831 };
1832 let dispatch = RetryDispatch::for_operation(&mut runtime);
1833 let cancellation = Arc::clone(&dispatch.cancellation);
1834 let deadline = dispatch.deadline.clone();
1835 let attempt_state = Arc::clone(&dispatch.state);
1836 let mut options = options;
1837 options.retry_runtime = Some(runtime.clone());
1838 let retry_if = |error: &DbError| {
1839 retry_allowed(*error, retry_timeouts, &cancellation, &deadline)
1840 };
1841 let outcome = execute_idempotent_retry(
1842 retry_policy,
1843 &cancellation,
1844 deadline.clone(),
1845 || {
1846 let pool = Arc::clone(&pool);
1847 let policy = Arc::clone(&policy);
1848 let cancellation = Arc::clone(&cancellation);
1849 let deadline = deadline.clone();
1850 let attempt_state = Arc::clone(&attempt_state);
1851 let options = options.clone();
1852 async move {
1853 attempt_state.reset();
1854 deadline.check(&cancellation).await?;
1855 let mut session = pool.acquire_async().await?;
1856 let result = fetch_observed(
1857 session.as_mut(),
1858 sql,
1859 limit,
1860 options,
1861 Arc::clone(&policy),
1862 )
1863 .await;
1864 drop(session);
1865 result
1866 }
1867 },
1868 retry_if,
1869 || (runtime.random)(),
1870 |delay| (runtime.sleep)(delay),
1871 )
1872 .await;
1873 drop(dispatch);
1874 return retry_result_with_interrupt(outcome, &attempt_state)
1875 .map(|reader| Box::new(reader) as Box<dyn Reader + 'a>);
1876 }
1877
1878 let mut session = pool.acquire_async().await?;
1879 let result = fetch_observed(session.as_mut(), sql, limit, options, policy).await;
1880 drop(session);
1881 result.map(|reader| Box::new(reader) as Box<dyn Reader + 'a>)
1882 })
1883 }
1884}
1885
1886fn resolve_retry(setting: RetrySetting, default: RetryPolicy) -> RetryPolicy {
1887 match setting {
1888 RetrySetting::Inherit => default,
1889 RetrySetting::Off => RetryPolicy::Disabled,
1890 RetrySetting::Use(policy) => policy,
1891 }
1892}
1893
1894fn retry_allowed(
1895 error: DbError,
1896 retry_timeouts: bool,
1897 cancellation: &Cancellation,
1898 deadline: &RetryDeadline,
1899) -> bool {
1900 !cancellation.is_cancelled()
1901 && !deadline.is_expired()
1902 && (matches!(error.kind(), ErrorKind::Busy | ErrorKind::Connection)
1903 || (retry_timeouts && error.kind() == ErrorKind::Timeout))
1904}
1905
1906fn retry_result<T>(outcome: RetryOutcome<T, DbError>) -> Result<T, DbError> {
1907 match outcome {
1908 RetryOutcome::Success { value, .. } => Ok(value),
1909 RetryOutcome::Failure { error, .. } => Err(error),
1910 RetryOutcome::Cancelled { .. } => Err(DbError::new(ErrorKind::Cancelled)),
1911 RetryOutcome::TimedOut { .. } => Err(DbError::new(ErrorKind::Timeout)),
1912 }
1913}
1914
1915fn mutex_lock<T>(mutex: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
1916 mutex
1917 .lock()
1918 .unwrap_or_else(std::sync::PoisonError::into_inner)
1919}
1920
1921#[derive(Default)]
1922struct RetryAttemptState {
1923 dispatch_in_flight: AtomicBool,
1924 last_error: Mutex<Option<ErrorKind>>,
1925 dispatch_rejection: Mutex<Option<DbError>>,
1926}
1927
1928impl RetryAttemptState {
1929 fn reset(&self) {
1930 self.dispatch_in_flight.store(false, Ordering::Release);
1931 *mutex_lock(&self.last_error) = None;
1932 *mutex_lock(&self.dispatch_rejection) = None;
1933 }
1934}
1935
1936#[derive(Clone)]
1939struct RetryDeadline(Arc<Mutex<Option<RetryWait>>>);
1940
1941impl RetryDeadline {
1942 fn new(timer: RetryWait) -> Self {
1943 Self(Arc::new(Mutex::new(Some(timer))))
1944 }
1945
1946 fn is_expired(&self) -> bool {
1947 mutex_lock(&self.0).is_none()
1948 }
1949
1950 async fn check(&self, cancellation: &Cancellation) -> Result<(), DbError> {
1951 if cancellation.is_cancelled() {
1952 return Err(DbError::new(ErrorKind::Cancelled));
1953 }
1954 let mut deadline = self.clone();
1955 let expired = poll_fn(|cx| Poll::Ready(Pin::new(&mut deadline).poll(cx).is_ready())).await;
1956 if cancellation.is_cancelled() {
1958 Err(DbError::new(ErrorKind::Cancelled))
1959 } else if expired {
1960 Err(DbError::new(ErrorKind::Timeout))
1961 } else {
1962 Ok(())
1963 }
1964 }
1965}
1966
1967impl Future for RetryDeadline {
1968 type Output = ();
1969
1970 fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
1971 let mut timer = mutex_lock(&self.0);
1972 if let Some(wait) = timer.as_mut() {
1973 if wait.as_mut().poll(cx).is_pending() {
1974 return Poll::Pending;
1975 }
1976 *timer = None;
1977 }
1978 Poll::Ready(())
1979 }
1980}
1981
1982struct RetryDispatch {
1983 deadline: RetryDeadline,
1984 cancellation: Arc<Cancellation>,
1985 state: Arc<RetryAttemptState>,
1986}
1987
1988impl RetryDispatch {
1989 fn for_operation(runtime: &mut RetryRuntime) -> Arc<Self> {
1990 let dispatch = Arc::new(Self {
1991 deadline: RetryDeadline::new((runtime.timer)()),
1993 cancellation: Arc::clone(&runtime.cancellation),
1994 state: Arc::new(RetryAttemptState::default()),
1995 });
1996 runtime.dispatch = Some(Arc::downgrade(&dispatch));
1997 dispatch
1998 }
1999
2000 async fn start(&self) -> Result<(), DbError> {
2001 self.state
2005 .dispatch_in_flight
2006 .store(false, Ordering::Release);
2007 if let Err(error) = self.deadline.check(&self.cancellation).await {
2008 *mutex_lock(&self.state.dispatch_rejection) = Some(error);
2009 return Err(error);
2010 }
2011 self.state.dispatch_in_flight.store(true, Ordering::Release);
2012 Ok(())
2013 }
2014
2015 fn rejection(&self) -> Option<DbError> {
2016 *mutex_lock(&self.state.dispatch_rejection)
2017 }
2018
2019 fn finish(&self, result: Result<(), DbError>) {
2020 self.state
2021 .dispatch_in_flight
2022 .store(false, Ordering::Release);
2023 if let Err(error) = result {
2024 *mutex_lock(&self.state.last_error) = Some(error.kind());
2025 }
2026 }
2027}
2028
2029fn retry_result_with_interrupt<T>(
2030 outcome: RetryOutcome<T, DbError>,
2031 state: &RetryAttemptState,
2032) -> Result<T, DbError> {
2033 match outcome {
2034 RetryOutcome::Cancelled { .. } => Err(interruption_error(state, ErrorKind::Cancelled)),
2035 RetryOutcome::TimedOut { .. } => Err(interruption_error(state, ErrorKind::Timeout)),
2036 other => retry_result(other),
2037 }
2038}
2039
2040fn interruption_error(state: &RetryAttemptState, interruption: ErrorKind) -> DbError {
2041 if state.dispatch_in_flight.load(Ordering::Acquire) {
2043 return DbError::new(ErrorKind::WriteOutcomeUnknown);
2044 }
2045 let last_error = *mutex_lock(&state.last_error);
2046 match last_error {
2047 Some(kind @ (ErrorKind::WriteOutcomeUnknown | ErrorKind::CommitOutcomeUnknown)) => {
2048 DbError::new(kind)
2049 }
2050 _ => DbError::new(interruption),
2051 }
2052}
2053
2054pub struct SqlitePolicyPool {
2060 inner: Arc<dyn SqlitePool>,
2061 policy_pool: PolicyPool,
2062}
2063
2064impl fmt::Debug for SqlitePolicyPool {
2065 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2066 formatter
2067 .debug_struct("SqlitePolicyPool")
2068 .field("policy", &self.policy_pool.policy)
2069 .finish_non_exhaustive()
2070 }
2071}
2072
2073impl SqlitePolicyPool {
2074 pub fn new<P: SqlitePool + 'static>(pool: P, policy: PoolPolicy) -> Self {
2076 Self::from_shared(Arc::new(pool), policy)
2077 }
2078
2079 #[must_use]
2081 pub fn from_shared(inner: Arc<dyn SqlitePool>, policy: PoolPolicy) -> Self {
2082 let pool: Arc<dyn Pool> = inner.clone();
2083 Self {
2084 inner,
2085 policy_pool: PolicyPool::from_shared(pool, policy),
2086 }
2087 }
2088}
2089
2090impl Pool for SqlitePolicyPool {
2091 fn capabilities(&self) -> Capabilities {
2092 self.policy_pool.capabilities()
2093 }
2094
2095 fn defaults(&self) -> PoolDefaults {
2096 self.policy_pool.defaults()
2097 }
2098
2099 fn acquire_async(&self) -> DbFuture<'_, Box<dyn Session>> {
2100 self.policy_pool.acquire_async()
2101 }
2102
2103 fn execute_async<'a>(&'a self, sql: &'a str, options: QueryOptions) -> DbFuture<'a, u64> {
2104 self.policy_pool.execute_async(sql, options)
2105 }
2106
2107 fn fetch_async<'a>(
2108 &'a self,
2109 sql: &'a str,
2110 options: QueryOptions,
2111 ) -> DbFuture<'a, Box<dyn Reader + 'a>> {
2112 self.policy_pool.fetch_async(sql, options)
2113 }
2114}
2115
2116impl SqlitePool for SqlitePolicyPool {
2117 fn busy_timeout(&self) -> Duration {
2118 self.inner.busy_timeout()
2119 }
2120
2121 fn acquire_sqlite_async(&self) -> DbFuture<'_, Box<dyn ImmediateTransaction>> {
2122 let inner = Arc::clone(&self.inner);
2123 let policy = Arc::clone(&self.policy_pool.policy);
2124 Box::pin(async move {
2125 let session = inner.acquire_sqlite_async().await?;
2126 Ok(Box::new(PolicySqliteSession { session, policy }) as Box<dyn ImmediateTransaction>)
2127 })
2128 }
2129}
2130
2131struct PolicySession {
2132 session: Box<dyn Session>,
2133 policy: Arc<PoolPolicy>,
2134}
2135impl Session for PolicySession {
2136 fn defaults(&self) -> PoolDefaults {
2137 policy_defaults(&self.policy)
2138 }
2139
2140 fn execute_async<'a>(
2141 &'a mut self,
2142 sql: &'a str,
2143 mut options: QueryOptions,
2144 ) -> DbFuture<'a, u64> {
2145 Box::pin(async move {
2146 options.validate_execute()?;
2147 reject_session_retry(&options)?;
2148 resolve_provider_timeout(&mut options, self.policy.default_timeout)?;
2149 execute_observed(
2150 self.session.as_mut(),
2151 sql,
2152 options,
2153 Arc::clone(&self.policy),
2154 )
2155 .await
2156 })
2157 }
2158
2159 fn fetch_async<'a>(
2160 &'a mut self,
2161 sql: &'a str,
2162 mut options: QueryOptions,
2163 ) -> DbFuture<'a, Box<dyn Reader + 'a>> {
2164 Box::pin(async move {
2165 reject_session_retry(&options)?;
2166 let limit = options.resolved_limit(policy_defaults(&self.policy));
2167 options.limit = LimitSetting::Set(limit);
2168 resolve_provider_timeout(&mut options, self.policy.default_timeout)?;
2169 let reader = fetch_observed(
2170 self.session.as_mut(),
2171 sql,
2172 limit,
2173 options,
2174 Arc::clone(&self.policy),
2175 )
2176 .await?;
2177 Ok(Box::new(reader) as Box<dyn Reader + 'a>)
2178 })
2179 }
2180
2181 fn execute_trusted_script_async<'a>(
2182 &'a mut self,
2183 sql: &'a str,
2184 mut options: QueryOptions,
2185 ) -> DbFuture<'a, ()> {
2186 Box::pin(async move {
2187 options.validate_script()?;
2188 reject_session_retry(&options)?;
2189 resolve_provider_timeout(&mut options, self.policy.default_timeout)?;
2190 script_observed(
2191 self.session.as_mut(),
2192 sql,
2193 options,
2194 Arc::clone(&self.policy),
2195 )
2196 .await
2197 })
2198 }
2199
2200 fn begin_async<'a>(
2201 &'a mut self,
2202 options: TxOptions,
2203 ) -> DbFuture<'a, Box<dyn Transaction<'a> + 'a>> {
2204 let session = &mut self.session;
2205 let policy = Arc::clone(&self.policy);
2206 Box::pin(async move {
2207 let transaction = session.begin_async(options).await?;
2208 Ok(Box::new(PolicyTransaction {
2209 transaction,
2210 policy,
2211 }) as Box<dyn Transaction<'a> + 'a>)
2212 })
2213 }
2214}
2215
2216struct PolicySqliteSession {
2217 session: Box<dyn ImmediateTransaction>,
2218 policy: Arc<PoolPolicy>,
2219}
2220
2221impl Session for PolicySqliteSession {
2222 fn defaults(&self) -> PoolDefaults {
2223 policy_defaults(&self.policy)
2224 }
2225
2226 fn execute_async<'a>(
2227 &'a mut self,
2228 sql: &'a str,
2229 mut options: QueryOptions,
2230 ) -> DbFuture<'a, u64> {
2231 Box::pin(async move {
2232 options.validate_execute()?;
2233 reject_session_retry(&options)?;
2234 resolve_provider_timeout(&mut options, self.policy.default_timeout)?;
2235 execute_observed(
2236 self.session.as_mut(),
2237 sql,
2238 options,
2239 Arc::clone(&self.policy),
2240 )
2241 .await
2242 })
2243 }
2244
2245 fn fetch_async<'a>(
2246 &'a mut self,
2247 sql: &'a str,
2248 mut options: QueryOptions,
2249 ) -> DbFuture<'a, Box<dyn Reader + 'a>> {
2250 Box::pin(async move {
2251 reject_session_retry(&options)?;
2252 let limit = options.resolved_limit(policy_defaults(&self.policy));
2253 options.limit = LimitSetting::Set(limit);
2254 resolve_provider_timeout(&mut options, self.policy.default_timeout)?;
2255 let reader = fetch_observed(
2256 self.session.as_mut(),
2257 sql,
2258 limit,
2259 options,
2260 Arc::clone(&self.policy),
2261 )
2262 .await?;
2263 Ok(Box::new(reader) as Box<dyn Reader + 'a>)
2264 })
2265 }
2266
2267 fn execute_trusted_script_async<'a>(
2268 &'a mut self,
2269 sql: &'a str,
2270 mut options: QueryOptions,
2271 ) -> DbFuture<'a, ()> {
2272 Box::pin(async move {
2273 options.validate_script()?;
2274 reject_session_retry(&options)?;
2275 resolve_provider_timeout(&mut options, self.policy.default_timeout)?;
2276 script_observed(
2277 self.session.as_mut(),
2278 sql,
2279 options,
2280 Arc::clone(&self.policy),
2281 )
2282 .await
2283 })
2284 }
2285
2286 fn begin_async<'a>(
2287 &'a mut self,
2288 options: TxOptions,
2289 ) -> DbFuture<'a, Box<dyn Transaction<'a> + 'a>> {
2290 let session = &mut self.session;
2291 let policy = Arc::clone(&self.policy);
2292 Box::pin(async move {
2293 let transaction = session.begin_async(options).await?;
2294 Ok(Box::new(PolicyTransaction {
2295 transaction,
2296 policy,
2297 }) as Box<dyn Transaction<'a> + 'a>)
2298 })
2299 }
2300}
2301
2302impl ImmediateTransaction for PolicySqliteSession {
2303 fn begin_immediate_async<'a>(&'a mut self) -> DbFuture<'a, Box<dyn Transaction<'a> + 'a>> {
2304 let session = &mut self.session;
2305 let policy = Arc::clone(&self.policy);
2306 Box::pin(async move {
2307 let transaction = session.begin_immediate_async().await?;
2308 Ok(Box::new(PolicyTransaction {
2309 transaction,
2310 policy,
2311 }) as Box<dyn Transaction<'a> + 'a>)
2312 })
2313 }
2314}
2315
2316struct PolicyTransaction<'session> {
2317 transaction: Box<dyn Transaction<'session> + 'session>,
2318 policy: Arc<PoolPolicy>,
2319}
2320impl<'session> Transaction<'session> for PolicyTransaction<'session> {
2321 fn defaults(&self) -> PoolDefaults {
2322 policy_defaults(&self.policy)
2323 }
2324
2325 fn execute_async<'a>(
2326 &'a mut self,
2327 sql: &'a str,
2328 mut options: QueryOptions,
2329 ) -> DbFuture<'a, u64> {
2330 Box::pin(async move {
2331 options.validate_execute()?;
2332 reject_session_retry(&options)?;
2333 resolve_provider_timeout(&mut options, self.policy.default_timeout)?;
2334 execute_observed(
2335 self.transaction.as_mut(),
2336 sql,
2337 options,
2338 Arc::clone(&self.policy),
2339 )
2340 .await
2341 })
2342 }
2343
2344 fn fetch_async<'a>(
2345 &'a mut self,
2346 sql: &'a str,
2347 mut options: QueryOptions,
2348 ) -> DbFuture<'a, Box<dyn Reader + 'a>> {
2349 Box::pin(async move {
2350 reject_session_retry(&options)?;
2351 let limit = options.resolved_limit(policy_defaults(&self.policy));
2352 options.limit = LimitSetting::Set(limit);
2353 resolve_provider_timeout(&mut options, self.policy.default_timeout)?;
2354 let reader = fetch_observed(
2355 self.transaction.as_mut(),
2356 sql,
2357 limit,
2358 options,
2359 Arc::clone(&self.policy),
2360 )
2361 .await?;
2362 Ok(Box::new(reader) as Box<dyn Reader + 'a>)
2363 })
2364 }
2365
2366 fn execute_trusted_script_async<'a>(
2367 &'a mut self,
2368 sql: &'a str,
2369 mut options: QueryOptions,
2370 ) -> DbFuture<'a, ()> {
2371 Box::pin(async move {
2372 options.validate_script()?;
2373 reject_session_retry(&options)?;
2374 resolve_provider_timeout(&mut options, self.policy.default_timeout)?;
2375 script_observed(
2376 self.transaction.as_mut(),
2377 sql,
2378 options,
2379 Arc::clone(&self.policy),
2380 )
2381 .await
2382 })
2383 }
2384
2385 fn commit_async(self: Box<Self>) -> DbFuture<'session, ()> {
2386 let transaction = self.transaction;
2387 transaction.commit_async()
2388 }
2389
2390 fn rollback_async(self: Box<Self>) -> DbFuture<'session, ()> {
2391 let transaction = self.transaction;
2392 transaction.rollback_async()
2393 }
2394}
2395
2396fn resolve_setting(setting: QuerySetting, pool_default: bool) -> bool {
2397 match setting {
2398 QuerySetting::Inherit => pool_default,
2399 QuerySetting::Off => false,
2400 QuerySetting::On => true,
2401 }
2402}
2403
2404fn captured_sql(sql: &str, policy: &PoolPolicy, options: &QueryOptions) -> Option<String> {
2405 if !resolve_setting(options.sql_capture, policy.sql_capture_enabled)
2406 || !resolve_setting(options.telemetry, policy.telemetry_enabled)
2407 {
2408 return None;
2409 }
2410 policy.observer.as_ref()?;
2411 let hook = options.sql_hook.as_ref().or(policy.sql_hook.as_ref());
2412 match hook {
2413 Some(hook) => {
2414 contain_callback_panic(catch_unwind(AssertUnwindSafe(|| hook(sql)))).flatten()
2415 }
2416 None => Some(sql.to_owned()),
2417 }
2418}
2419
2420fn contain_callback_panic<T>(result: Result<T, Box<dyn std::any::Any + Send>>) -> Option<T> {
2421 match result {
2422 Ok(value) => Some(value),
2423 Err(payload) => {
2424 std::mem::forget(payload);
2427 None
2428 }
2429 }
2430}
2431
2432fn emit(
2433 operation: Operation,
2434 started: Instant,
2435 result: Result<(), DbError>,
2436 sql: Option<String>,
2437 policy: &PoolPolicy,
2438 options: &QueryOptions,
2439) {
2440 if !resolve_setting(options.telemetry, policy.telemetry_enabled) {
2441 return;
2442 }
2443 let Some(observer) = &policy.observer else {
2444 return;
2445 };
2446 let outcome = match result {
2447 Ok(()) => TelemetryOutcome::Success,
2448 Err(error) => TelemetryOutcome::Error(error.kind()),
2449 };
2450 let event = DbEvent {
2451 operation,
2452 duration: started.elapsed(),
2453 outcome,
2454 sql,
2455 };
2456 let _ = contain_callback_panic(catch_unwind(AssertUnwindSafe(|| observer(&event))));
2457}
2458
2459struct ObservationGuard {
2460 operation: Operation,
2461 started: Instant,
2462 captured: Option<String>,
2463 policy: Arc<PoolPolicy>,
2464 options: QueryOptions,
2465 active: bool,
2466}
2467
2468impl ObservationGuard {
2469 fn new(
2470 operation: Operation,
2471 started: Instant,
2472 captured: Option<String>,
2473 policy: Arc<PoolPolicy>,
2474 options: QueryOptions,
2475 ) -> Self {
2476 Self {
2477 operation,
2478 started,
2479 captured,
2480 policy,
2481 options,
2482 active: true,
2483 }
2484 }
2485
2486 fn finish(&mut self, result: Result<(), DbError>) {
2487 if self.active {
2488 self.active = false;
2489 emit(
2490 self.operation,
2491 self.started,
2492 result,
2493 self.captured.take(),
2494 &self.policy,
2495 &self.options,
2496 );
2497 }
2498 }
2499
2500 fn disarm(&mut self) {
2501 self.active = false;
2502 }
2503}
2504
2505impl Drop for ObservationGuard {
2506 fn drop(&mut self) {
2507 if self.active {
2508 self.finish(Err(DbError::new(ErrorKind::WriteOutcomeUnknown)));
2509 }
2510 }
2511}
2512
2513trait StatementExecutor: Send {
2514 fn execute_statement<'a>(
2515 &'a mut self,
2516 sql: &'a str,
2517 options: QueryOptions,
2518 ) -> DbFuture<'a, u64>;
2519 fn fetch_statement<'a>(
2520 &'a mut self,
2521 sql: &'a str,
2522 options: QueryOptions,
2523 ) -> DbFuture<'a, Box<dyn Reader + 'a>>;
2524 fn execute_script<'a>(&'a mut self, sql: &'a str, options: QueryOptions) -> DbFuture<'a, ()>;
2525}
2526impl StatementExecutor for dyn Session + '_ {
2527 fn execute_statement<'a>(
2528 &'a mut self,
2529 sql: &'a str,
2530 options: QueryOptions,
2531 ) -> DbFuture<'a, u64> {
2532 self.execute_async(sql, options)
2533 }
2534 fn fetch_statement<'a>(
2535 &'a mut self,
2536 sql: &'a str,
2537 options: QueryOptions,
2538 ) -> DbFuture<'a, Box<dyn Reader + 'a>> {
2539 self.fetch_async(sql, options)
2540 }
2541 fn execute_script<'a>(&'a mut self, sql: &'a str, options: QueryOptions) -> DbFuture<'a, ()> {
2542 self.execute_trusted_script_async(sql, options)
2543 }
2544}
2545impl StatementExecutor for dyn ImmediateTransaction + '_ {
2546 fn execute_statement<'a>(
2547 &'a mut self,
2548 sql: &'a str,
2549 options: QueryOptions,
2550 ) -> DbFuture<'a, u64> {
2551 self.execute_async(sql, options)
2552 }
2553 fn fetch_statement<'a>(
2554 &'a mut self,
2555 sql: &'a str,
2556 options: QueryOptions,
2557 ) -> DbFuture<'a, Box<dyn Reader + 'a>> {
2558 self.fetch_async(sql, options)
2559 }
2560 fn execute_script<'a>(&'a mut self, sql: &'a str, options: QueryOptions) -> DbFuture<'a, ()> {
2561 self.execute_trusted_script_async(sql, options)
2562 }
2563}
2564impl StatementExecutor for dyn Transaction<'_> + '_ {
2565 fn execute_statement<'a>(
2566 &'a mut self,
2567 sql: &'a str,
2568 options: QueryOptions,
2569 ) -> DbFuture<'a, u64> {
2570 self.execute_async(sql, options)
2571 }
2572 fn fetch_statement<'a>(
2573 &'a mut self,
2574 sql: &'a str,
2575 options: QueryOptions,
2576 ) -> DbFuture<'a, Box<dyn Reader + 'a>> {
2577 self.fetch_async(sql, options)
2578 }
2579 fn execute_script<'a>(&'a mut self, sql: &'a str, options: QueryOptions) -> DbFuture<'a, ()> {
2580 self.execute_trusted_script_async(sql, options)
2581 }
2582}
2583
2584fn script_observed<'a, S: StatementExecutor + ?Sized>(
2585 session: &'a mut S,
2586 sql: &'a str,
2587 query_options: QueryOptions,
2588 policy: Arc<PoolPolicy>,
2589) -> DbFuture<'a, ()> {
2590 Box::pin(async move {
2591 let captured = captured_sql(sql, &policy, &query_options);
2592 let started = Instant::now();
2593 let mut observation = ObservationGuard::new(
2594 Operation::Execute,
2595 started,
2596 captured,
2597 Arc::clone(&policy),
2598 query_options.clone(),
2599 );
2600 let mut provider_options = query_options.clone();
2601 provider_options.policy_applied = true;
2602 let result = session.execute_script(sql, provider_options).await;
2603 let observer_result = match &result {
2604 Ok(()) => Ok(()),
2605 Err(error) => Err(DbError::new(error.kind())),
2606 };
2607 observation.finish(observer_result);
2608 result
2609 })
2610}
2611
2612fn operation_dispatch(options: &QueryOptions) -> Option<Arc<RetryDispatch>> {
2613 options.retry_runtime.as_ref()?.dispatch.as_ref()?.upgrade()
2614}
2615
2616fn execute_observed<'a, S: StatementExecutor + ?Sized>(
2617 session: &'a mut S,
2618 sql: &'a str,
2619 options: QueryOptions,
2620 policy: Arc<PoolPolicy>,
2621) -> DbFuture<'a, u64> {
2622 Box::pin(async move {
2623 let dispatch = operation_dispatch(&options);
2624 let captured = captured_sql(sql, &policy, &options);
2625 if let Some(dispatch) = &dispatch {
2626 dispatch.start().await?;
2627 }
2628 let started = Instant::now();
2629 let mut observation = ObservationGuard::new(
2630 Operation::Execute,
2631 started,
2632 captured,
2633 Arc::clone(&policy),
2634 options.clone(),
2635 );
2636 let mut provider_options = options.clone();
2637 provider_options.policy_applied = true;
2638 let result = session.execute_statement(sql, provider_options).await;
2639 if let Some(error) = dispatch.as_ref().and_then(|dispatch| dispatch.rejection()) {
2642 observation.disarm();
2643 return Err(error);
2644 }
2645 let result = result.map_err(normalize_write_outcome);
2646 if let Some(dispatch) = &dispatch {
2647 dispatch.finish(result.as_ref().map(|_| ()).map_err(|error| *error));
2648 }
2649 observation.finish(result.as_ref().map(|_| ()).map_err(|error| *error));
2650 result
2651 })
2652}
2653
2654fn normalize_write_outcome(error: DbError) -> DbError {
2655 match error.kind() {
2656 ErrorKind::Connection | ErrorKind::Timeout | ErrorKind::Cancelled => {
2657 DbError::new(ErrorKind::WriteOutcomeUnknown)
2658 }
2659 _ => error,
2660 }
2661}
2662
2663async fn collect_sets(reader: &mut dyn Reader, limit: RowLimit) -> Result<Vec<Vec<Row>>, DbError> {
2664 let mut sets = Vec::new();
2665 let mut rows = 0usize;
2666 let mut bytes = 0usize;
2667 loop {
2668 let mut set = Vec::new();
2669 while let Some(row) = reader.next_row_async().await? {
2670 if rows == limit.rows() {
2671 return Err(DbError::new(ErrorKind::Overflow));
2672 }
2673 let size = row.encoded_bytes()?;
2674 bytes = bytes
2675 .checked_add(size)
2676 .ok_or_else(|| DbError::new(ErrorKind::Overflow))?;
2677 if bytes > limit.bytes() {
2678 return Err(DbError::new(ErrorKind::Overflow));
2679 }
2680 rows = rows
2681 .checked_add(1)
2682 .ok_or_else(|| DbError::new(ErrorKind::Overflow))?;
2683 set.push(row);
2684 }
2685 sets.push(set);
2686 if !reader.has_next_set_async().await? {
2687 break;
2688 }
2689 if sets.len() == limit.max_sets() {
2690 return Err(DbError::new(ErrorKind::Overflow));
2691 }
2692 }
2693 reader.finish_async().await?;
2694 Ok(sets)
2695}
2696
2697fn fetch_observed<'a, S: StatementExecutor + ?Sized>(
2698 session: &'a mut S,
2699 sql: &'a str,
2700 limit: RowLimit,
2701 options: QueryOptions,
2702 policy: Arc<PoolPolicy>,
2703) -> DbFuture<'a, BufferedReader> {
2704 Box::pin(async move {
2705 let dispatch = operation_dispatch(&options);
2706 let captured = captured_sql(sql, &policy, &options);
2707 if let Some(dispatch) = &dispatch {
2708 dispatch.start().await?;
2709 }
2710 let started = Instant::now();
2711 let mut observation = ObservationGuard::new(
2712 Operation::Fetch,
2713 started,
2714 captured,
2715 Arc::clone(&policy),
2716 options.clone(),
2717 );
2718 let result = async {
2719 let mut provider_options = options.clone();
2720 provider_options.policy_applied = true;
2721 let mut reader = session.fetch_statement(sql, provider_options).await?;
2722 collect_sets(reader.as_mut(), limit).await
2723 }
2724 .await;
2725 if let Some(error) = dispatch.as_ref().and_then(|dispatch| dispatch.rejection()) {
2726 observation.disarm();
2727 return Err(error);
2728 }
2729 if let Some(dispatch) = &dispatch {
2730 dispatch.finish(result.as_ref().map(|_| ()).map_err(|error| *error));
2731 }
2732 observation.finish(result.as_ref().map(|_| ()).map_err(|error| *error));
2733 result.map(BufferedReader::from_sets)
2734 })
2735}