Skip to main content

neotales_dbapi/
lib.rs

1//! Driver-neutral async SQL execution and detached, bounded row access.
2//!
3//! This crate deliberately provides no query builder, ORM, runtime, or driver. A provider owns
4//! connection acquisition, type conversion, transaction behavior, and cleanup. All operations use
5//! boxed `Send` futures so the traits are object safe. This contract cannot directly wrap browser
6//! APIs whose futures are `!Send` (for example, D1 Workers bindings). The [`local`] module mirrors
7//! these traits without a `Send` future bound for that case; it is a local-thread API, not a
8//! thread-transfer grant.
9//!
10//! The [`sync`] module provides runtime-neutral synchronous counterparts that reuse the same rows,
11//! limits, options, and errors. The optional `blocking` feature adds `blocking::BlockingPool`,
12//! which drives an asynchronous pool on dedicated worker threads for callers that cannot await.
13//! The `blocking` feature is not supported on wasm32. Async or local traits may be used with
14//! providers that support them, but D1's local DBAPI operations currently fail closed.
15//!
16//! # Example
17//!
18//! ```no_run
19//! use neotales_dbapi::{DbType, Parameter, Pool, QueryOptions, RowLimit};
20//!
21//! # async fn run(pool: &dyn Pool) -> Result<(), neotales_dbapi::DbError> {
22//! let mut session = pool.acquire_async().await?;
23//! let params = [Parameter::new(DbType::I64, neotales_dbapi::Value::I64(7))?];
24//! // SQLite uses `?`; PostgreSQL uses `$1`. The provider does not rewrite SQL.
25//! let mut reader = session.fetch_async("SELECT name FROM users WHERE id = ?",
26//!     QueryOptions::new().bind_all(&params).limit(RowLimit::new(10, 4096)?)).await?;
27//! while let Some(row) = reader.next_row_async().await? {
28//!     if let Some(name) = row.read::<Option<String>>("name")? {
29//!         println!("{name}");
30//!     }
31//! }
32//! reader.finish_async().await?;
33//! # Ok(())
34//! # }
35//! ```
36//!
37//! A reader owns one statement's result sets until it is finished or dropped. `next_row_async` yields
38//! rows from the current set. `has_next_set_async` advances, discarding any unread rows in the current
39//! set, and reports whether another set exists. `finish_async` drains and discards the full batch so a
40//! later statement error is not hidden. A provider with unread results still attached must discard
41//! the connection when a reader is dropped; a provider that materializes the bounded batch before
42//! returning may already have made the connection reusable.
43//!
44//! The [`paging`] module adds page and row views over one existing reader. It dispatches no SQL and
45//! does not change the reader's parameters, telemetry, or bounded `RowLimit`; the page view exposes
46//! result-set boundaries, including empty sets. Its [`paging::multi`] submodule adds explicit
47//! multi-request paging where a caller-implemented source owns each request, continuation, and
48//! keyset/offset logic. [`local::paging`] mirrors both for `!Send` local futures, and
49//! [`sync::paging`] provides native blocking iterators over the synchronous reader.
50//!
51//! Native positional placeholder syntax is preserved (SQL is never rewritten):
52//!
53//! ```
54//! use neotales_dbapi::{DbType, Parameter, Value};
55//! let sqlite_sql = "SELECT name FROM users WHERE id = ?";
56//! let sqlite_parameters = [Parameter::new(DbType::I64, Value::I64(7))?];
57//! let postgres_sql = "SELECT name FROM users WHERE id = $1 AND active = $2";
58//! let postgres_parameters = [
59//!     Parameter::new(DbType::I64, Value::I64(7))?,
60//!     Parameter::new(DbType::Bool, Value::Bool(true))?,
61//! ];
62//! # let _ = (sqlite_sql, sqlite_parameters, postgres_sql, postgres_parameters);
63//! # Ok::<(), neotales_dbapi::DbError>(())
64//! ```
65
66#[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
96/// A `Send` boxed future returning a sanitized database result.
97pub type DbFuture<'a, T> = Pin<Box<dyn Future<Output = Result<T, DbError>> + Send + 'a>>;
98
99/// SQL logical type used to define typed null parameters and expected row values.
100#[derive(Clone, Copy, Debug, Eq, PartialEq)]
101pub enum DbType {
102    /// Boolean.
103    Bool,
104    /// Signed 64-bit integer.
105    I64,
106    /// 64-bit floating-point number.
107    F64,
108    /// UTF-8 text.
109    Text,
110    /// Opaque bytes.
111    Bytes,
112}
113
114/// A supported, owned parameter or cell value.
115#[derive(Clone, Debug, PartialEq)]
116pub enum Value {
117    /// Null with an explicit SQL type.
118    Null(DbType),
119    /// Boolean.
120    Bool(bool),
121    /// Signed 64-bit integer.
122    I64(i64),
123    /// Finite 64-bit float.
124    F64(f64),
125    /// UTF-8 text.
126    Text(String),
127    /// Opaque bytes.
128    Bytes(Vec<u8>),
129}
130impl Value {
131    /// Rejects non-finite floating-point values; providers must preserve all other variants exactly.
132    ///
133    /// # Errors
134    /// Returns `InvalidArgument` for NaN or infinity.
135    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/// A positional parameter whose value must match its declared type exactly.
145#[derive(Clone, Debug, PartialEq)]
146pub struct Parameter {
147    db_type: DbType,
148    value: Value,
149}
150impl Parameter {
151    /// Creates and validates one positional parameter without coercion.
152    ///
153    /// # Errors
154    /// Returns `InvalidArgument` for a type mismatch or non-finite float.
155    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    /// Returns the declared SQL type.
174    #[must_use]
175    pub const fn db_type(&self) -> DbType {
176        self.db_type
177    }
178    /// Returns the validated owned value.
179    #[must_use]
180    pub fn value(&self) -> &Value {
181        &self.value
182    }
183}
184
185/// Reported provider capabilities; true means the operation is supported as described.
186#[allow(clippy::struct_excessive_bools)] // Independent capability flags must be directly reportable.
187#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
188pub struct Capabilities {
189    /// Interactive transactions on one acquired connection.
190    pub transactions: bool,
191    /// Requested portable isolation levels can be applied.
192    pub isolation_level: bool,
193    /// Read-only transactions can be requested.
194    pub read_only_transactions: bool,
195    /// Trusted script execution is supported.
196    pub trusted_scripts: bool,
197}
198
199/// Portable transaction isolation level.
200#[derive(Clone, Copy, Debug, Eq, PartialEq)]
201pub enum IsolationLevel {
202    /// Serializable isolation.
203    Serializable,
204    /// Repeatable-read isolation.
205    RepeatableRead,
206    /// Read-committed isolation.
207    ReadCommitted,
208    /// Read-uncommitted isolation.
209    ReadUncommitted,
210}
211/// Portable transaction options; omitted values retain provider-defined defaults.
212#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
213pub struct TxOptions {
214    /// Requested isolation; unsupported requests fail before beginning.
215    pub isolation: Option<IsolationLevel>,
216    /// Requested read-only/access mode; unsupported requests fail before beginning.
217    pub read_only: Option<bool>,
218}
219/// Statement execution options.
220#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
221pub struct ExecuteOptions {
222    /// Provider-defined timeout in milliseconds; `None` means no requested timeout.
223    pub timeout_ms: Option<u64>,
224}
225
226/// Per-query inherit/off/on setting for telemetry or SQL capture.
227#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
228pub enum QuerySetting {
229    /// Use the configured pool default.
230    #[default]
231    Inherit,
232    /// Disable this query's setting, overriding an enabled pool default.
233    Off,
234    /// Enable this query's setting, overriding a disabled pool default.
235    On,
236}
237
238/// Whether a standalone pool operation may use the configured retry policy.
239#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
240pub enum ReplaySafety {
241    /// Do not retry. SQL shape is never used to infer safety.
242    #[default]
243    Never,
244    /// The caller asserts that repeating this standalone operation is safe.
245    ExplicitlyReplaySafe,
246}
247
248/// Pool retry configuration backed by `neotales-resilience`.
249#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
250pub enum RetryPolicy {
251    /// Execute once. This is the default.
252    #[default]
253    Disabled,
254    /// Retry explicitly replay-safe standalone statements, up to the configured attempt cap.
255    Enabled {
256        /// Existing resilience retry policy, including bounded attempts and delay shape.
257        policy: ResilienceRetryPolicy,
258        /// Whether sanitized `Timeout` errors are retry candidates.
259        retry_timeouts: bool,
260    },
261}
262impl RetryPolicy {
263    /// Builds an enabled retry policy using the resilience crate's bounded retry configuration.
264    ///
265    /// `retry_timeouts` is off unless explicitly requested. Busy and Connection failures are
266    /// candidates by default, but retries still require [`ReplaySafety::ExplicitlyReplaySafe`].
267    ///
268    /// # Errors
269    /// Returns [`InvalidRetryPolicy`] when `max_attempts` is zero.
270    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/// Retry configuration was invalid.
285#[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/// Per-operation retry configuration override.
295#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
296pub enum RetrySetting {
297    /// Use the containing pool's default.
298    #[default]
299    Inherit,
300    /// Disable retries for this operation.
301    Off,
302    /// Replace the containing pool's retry policy for this operation.
303    Use(RetryPolicy),
304}
305
306/// Caller-provided timer, backoff sleeper, cancellation flag, and random source for retries.
307///
308/// No runtime or task is created by this crate. The timer must measure the complete execution
309/// budget (acquisition, attempts, and backoff), and must wake the executor when it expires.
310/// Pool defaults share this value across calls; use [`QueryOptions::retry_runtime`] for a
311/// cancellation token scoped to an individual operation.
312pub 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    // Only operation-local copies carry this. Weak ownership prevents retained provider options
318    // from extending the operation's lifetime or imposing its gate on later independent calls.
319    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
333/// A boxed sendable caller-owned timer or sleeper future.
334pub type RetryWait = Pin<Box<dyn Future<Output = ()> + Send>>;
335
336impl RetryRuntime {
337    /// Creates retry runtime callbacks. For an enabled, explicitly replay-safe operation the timer
338    /// factory is called exactly once, before acquisition, even if the operation succeeds immediately.
339    /// The sleeper is called for each backoff. Use a pending timer when no total deadline is desired.
340    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/// Sanitized operation outcome used by the optional observer.
366#[derive(Clone, Copy, Debug, Eq, PartialEq)]
367pub enum TelemetryOutcome {
368    /// The operation succeeded. Row contents and affected-row counts are not included.
369    Success,
370    /// The operation failed with a stable database error category.
371    Error(ErrorKind),
372}
373
374/// Fixed-cardinality operation name; SQL is never used as a metric label.
375#[derive(Clone, Copy, Debug, Eq, PartialEq)]
376pub enum Operation {
377    /// One execute statement.
378    Execute,
379    /// One bounded fetch statement.
380    Fetch,
381}
382
383/// Safe telemetry event: no parameters, rows, results, driver text, or connection information.
384#[derive(Clone, Debug, Eq, PartialEq)]
385pub struct DbEvent {
386    /// Fixed operation name suitable for a bounded metric label.
387    pub operation: Operation,
388    /// Elapsed wall time for the statement operation.
389    pub duration: Duration,
390    /// Sanitized result category.
391    pub outcome: TelemetryOutcome,
392    /// Optional SQL text when capture was explicitly enabled and the hook retained it.
393    pub sql: Option<String>,
394}
395
396/// Optional SQL-only hook. Returning `None` suppresses SQL text; returning a string replaces it.
397///
398/// Panics are contained. A panic payload is intentionally forgotten to prevent a panicking
399/// destructor from unwinding after the database operation; each hook panic may leak its payload.
400pub type SqlCaptureHook = Arc<dyn Fn(&str) -> Option<String> + Send + Sync>;
401/// Optional per-pool observer.
402///
403/// Panics are contained and do not affect database results. Because a panic payload's destructor
404/// can itself panic, payloads from callback panics are intentionally forgotten; each such panic
405/// may leak its payload.
406pub type DbObserver = Arc<dyn Fn(&DbEvent) + Send + Sync>;
407
408/// Pool-level defaults for telemetry, SQL capture, and retry support.
409#[derive(Clone)]
410pub struct PoolPolicy {
411    /// Whether telemetry is enabled by default. No observer means no event is emitted.
412    pub telemetry_enabled: bool,
413    /// Whether exact SQL capture is enabled by default. SQL literals/comments may contain secrets.
414    pub sql_capture_enabled: bool,
415    /// SQL-only pool hook, called only when SQL capture is enabled.
416    pub sql_hook: Option<SqlCaptureHook>,
417    /// Optional observer. Its panic is isolated from the database operation.
418    pub observer: Option<DbObserver>,
419    /// Retry default for standalone pool `execute_async`/`fetch_async` calls; default is Disabled.
420    pub retry: RetryPolicy,
421    /// Caller-owned scheduling and cancellation dependencies required when retries are enabled.
422    pub retry_runtime: Option<RetryRuntime>,
423    /// Default statement timeout for operations that inherit. `None` inherits the wrapped
424    /// provider's default; use per-query `no_timeout()` to request disabling it.
425    pub default_timeout: Option<Duration>,
426    /// Default bounded fetch limit for operations that inherit.
427    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/// Owned parameters and policy overrides for one pool, session, transaction, or script operation.
470#[derive(Clone, Default)]
471pub struct QueryOptions {
472    /// Ordered operation-local parameters. Never inherited from pool defaults.
473    pub parameters: Vec<Parameter>,
474    /// Tri-state timeout override.
475    pub timeout: TimeoutSetting,
476    /// Tri-state bounded fetch-limit override.
477    pub limit: LimitSetting,
478    /// Resolved provider timeout, not a separate caller override.
479    execute: ExecuteOptions,
480    /// Whether telemetry is inherited, disabled, or enabled for this operation.
481    pub telemetry: QuerySetting,
482    /// Whether SQL capture is inherited, disabled, or enabled for this operation.
483    pub sql_capture: QuerySetting,
484    /// Per-query SQL hook, replacing the pool hook when present.
485    pub sql_hook: Option<SqlCaptureHook>,
486    /// Retry policy override for a standalone `PolicyPool` `execute_async`/`fetch_async` operation.
487    pub retry: RetrySetting,
488    /// Explicit caller assertion required before any retry can occur.
489    pub replay_safety: ReplaySafety,
490    /// Per-operation retry runtime, replacing the pool default when present.
491    pub retry_runtime: Option<RetryRuntime>,
492    // An enclosing policy handles telemetry and retry; callers cannot bypass validation.
493    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    /// Provider-facing execution settings after resolution.
514    #[must_use]
515    pub fn provider_execute_options(&self) -> ExecuteOptions {
516        self.execute
517    }
518    /// Creates options that inherit every global default, carry no parameters, and remain
519    /// non-replay-safe.
520    #[must_use]
521    pub fn new() -> Self {
522        Self::default()
523    }
524
525    /// Appends one already validated parameter in positional order.
526    #[must_use]
527    pub fn bind(mut self, parameter: Parameter) -> Self {
528        self.parameters.push(parameter);
529        self
530    }
531
532    /// Appends parameters in slice order.
533    #[must_use]
534    pub fn bind_all(mut self, parameters: &[Parameter]) -> Self {
535        self.parameters.extend_from_slice(parameters);
536        self
537    }
538
539    /// Appends finite float, text, or byte parameters with exact declared types.
540    ///
541    /// # Errors
542    /// Returns `InvalidArgument` for a non-finite float.
543    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    /// Appends a typed SQL null.
550    #[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    /// Replaces the pool timeout for this operation.
560    #[must_use]
561    pub fn timeout(mut self, timeout: Duration) -> Self {
562        self.timeout = TimeoutSetting::Set(timeout);
563        self
564    }
565
566    /// Explicitly requests no timeout for this operation.
567    #[must_use]
568    pub fn no_timeout(mut self) -> Self {
569        self.timeout = TimeoutSetting::Disabled;
570        self
571    }
572
573    /// Replaces the pool fetch limit for this operation.
574    #[must_use]
575    pub fn limit(mut self, limit: RowLimit) -> Self {
576        self.limit = LimitSetting::Set(limit);
577        self
578    }
579
580    /// Sets telemetry inheritance/off/on.
581    #[must_use]
582    pub fn telemetry(mut self, setting: QuerySetting) -> Self {
583        self.telemetry = setting;
584        self
585    }
586
587    /// Sets SQL-capture inheritance/off/on.
588    #[must_use]
589    pub fn sql_capture(mut self, setting: QuerySetting) -> Self {
590        self.sql_capture = setting;
591        self
592    }
593
594    /// Sets retry inheritance/off/explicit policy.
595    #[must_use]
596    pub fn retry(mut self, setting: RetrySetting) -> Self {
597        self.retry = setting;
598        self
599    }
600
601    /// Replaces the per-operation SQL capture hook.
602    #[must_use]
603    pub fn sql_hook(mut self, hook: SqlCaptureHook) -> Self {
604        self.sql_hook = Some(hook);
605        self
606    }
607
608    /// Replaces the retry runtime for this operation.
609    #[must_use]
610    pub fn retry_runtime(mut self, runtime: RetryRuntime) -> Self {
611        self.retry_runtime = Some(runtime);
612        self
613    }
614
615    /// Marks the operation explicitly replay-safe. Defaults remain `Never`.
616    #[must_use]
617    pub fn replay_safe(mut self) -> Self {
618        self.replay_safety = ReplaySafety::ExplicitlyReplaySafe;
619        self
620    }
621
622    /// Resolves the timeout against pool defaults.
623    #[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    /// Resolves the fetch limit against pool defaults.
633    #[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    /// Resolve provider-facing timeout and reject policy options no wrapper handles.
642    ///
643    /// # Errors
644    /// Returns `Unsupported` for policy facilities unavailable on a bare provider, or
645    /// `InvalidArgument` if the timeout cannot be represented in milliseconds.
646    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    /// Reject a fetch-only limit before dispatching a non-fetch statement.
657    ///
658    /// Inherited pool limits do not apply to execute operations.
659    ///
660    /// # Errors
661    /// Returns `InvalidArgument` when a per-operation fetch limit was supplied.
662    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    /// Validate and resolve options for a provider's execute operation.
670    ///
671    /// # Errors
672    /// Returns an error for an explicit fetch limit or unsupported provider settings.
673    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    /// Reject settings that cannot apply to an unparameterized trusted script.
680    ///
681    /// # Errors
682    /// Returns `InvalidArgument` if parameters or a fetch limit were supplied.
683    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    /// Resolve a trusted script's provider settings after rejecting inapplicable options.
691    ///
692    /// # Errors
693    /// Returns an error for inapplicable or unsupported settings.
694    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
701// The low-level provider boundary currently accepts millisecond timeouts. Round up so
702// a positive sub-millisecond timeout never accidentally becomes an immediate timeout.
703fn 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
726// A bare pool has no observer or retry runtime. Reject requests requiring those
727// facilities rather than silently dropping them at the provider boundary.
728fn 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/// Hard maximums for detached fetch results.
756///
757/// `rows` and `bytes` are aggregate across every result set. `max_sets` also counts empty
758/// sets, so a provider cannot return an unbounded number of empty boundaries.
759#[derive(Clone, Copy, Debug, Eq, PartialEq)]
760pub struct RowLimit {
761    rows: usize,
762    bytes: usize,
763    max_sets: usize,
764}
765impl RowLimit {
766    /// Creates a single-result-set limit with non-zero hard row and byte bounds.
767    ///
768    /// Use [`RowLimit::with_max_sets`] when the statement may return multiple sets.
769    ///
770    /// # Errors
771    /// Returns `InvalidArgument` if either bound is zero.
772    pub fn new(rows: usize, bytes: usize) -> Result<Self, DbError> {
773        Self::with_max_sets(rows, bytes, 1)
774    }
775    /// Creates a limit with non-zero row, byte, and aggregate result-set bounds.
776    ///
777    /// The set bound counts empty sets. Providers must fail, never truncate, when any bound is
778    /// exceeded.
779    ///
780    /// # Errors
781    /// Returns `InvalidArgument` with a static reason if any bound is zero.
782    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    /// Returns the maximum number of rows across all sets.
799    #[must_use]
800    pub const fn rows(self) -> usize {
801        self.rows
802    }
803    /// Returns the aggregate byte ceiling across all sets.
804    #[must_use]
805    pub const fn bytes(self) -> usize {
806        self.bytes
807    }
808    /// Returns the maximum number of result sets, including empty sets.
809    #[must_use]
810    pub const fn max_sets(self) -> usize {
811        self.max_sets
812    }
813}
814
815impl Default for RowLimit {
816    /// A bounded default: 1,000 rows, 1 MiB, one result set.
817    fn default() -> Self {
818        Self {
819            rows: 1_000,
820            bytes: 1_048_576,
821            max_sets: 1,
822        }
823    }
824}
825
826/// Tri-state timeout override. `Inherit` uses the pool default; `Disabled` explicitly requests
827/// no timeout; `Set` replaces the pool default for this operation.
828#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
829pub enum TimeoutSetting {
830    /// Use the pool default.
831    #[default]
832    Inherit,
833    /// Explicitly request no timeout. Use only when the caller owns a separate cancellation path.
834    Disabled,
835    /// Replace the pool default with this timeout.
836    Set(Duration),
837}
838
839/// Bounded fetch limit override. There is deliberately no unbounded variant.
840#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
841pub enum LimitSetting {
842    /// Use the pool default.
843    #[default]
844    Inherit,
845    /// Replace the pool default for this operation.
846    Set(RowLimit),
847}
848
849/// Defaults supplied by a pool for operations that inherit.
850#[derive(Clone, Copy, Debug, Eq, PartialEq)]
851pub struct PoolDefaults {
852    /// Default statement timeout. `None` means the pool chose no timeout.
853    pub timeout: Option<Duration>,
854    /// Default bounded fetch limit.
855    pub limit: RowLimit,
856    /// Whether telemetry is enabled by default.
857    pub telemetry_enabled: bool,
858    /// Whether exact SQL capture is enabled by default.
859    pub sql_capture_enabled: bool,
860    /// Default retry policy.
861    pub retry: RetryPolicy,
862}
863impl Default for PoolDefaults {
864    fn default() -> Self {
865        Self {
866            // A portable statement deadline cannot be promised by every provider. A provider
867            // may choose an enforceable deadline; unsupported explicit deadlines must fail.
868            timeout: None,
869            limit: RowLimit::default(),
870            telemetry_enabled: false,
871            sql_capture_enabled: false,
872            retry: RetryPolicy::Disabled,
873        }
874    }
875}
876
877/// Stable, sanitized error category. No driver message or query data is retained.
878#[derive(Clone, Copy, Debug, Eq, PartialEq)]
879pub enum ErrorKind {
880    /// Invalid argument, including a zero bound or invalid parameter value.
881    InvalidArgument,
882    /// Constraint violation.
883    Constraint,
884    /// Database is busy/locked.
885    Busy,
886    /// Deadline elapsed.
887    Timeout,
888    /// Operation was cancelled by provider.
889    Cancelled,
890    /// Requested capability is unavailable.
891    Unsupported,
892    /// A blocking adapter was called from the worker thread that would have to service it.
893    ///
894    /// The adapter refuses to wait on itself; a caller on its own worker thread must not block.
895    /// This category is never reported by a native asynchronous or synchronous provider.
896    Reentrant,
897    /// Parameter or result conversion/shape error.
898    Decode,
899    /// Connection or transport failure.
900    Connection,
901    /// A dispatched standalone write did not produce an authoritative result.
902    WriteOutcomeUnknown,
903    /// Commit was dispatched but its result is unknown.
904    CommitOutcomeUnknown,
905    /// Requested column or ordinal is absent.
906    Missing,
907    /// A cardinality-one convenience found no row.
908    NoRows,
909    /// A cardinality-one convenience found more than one row in the first result set.
910    TooManyRows,
911    /// Name identifies more than one column.
912    Ambiguous,
913    /// A SQL null was requested as a non-null value.
914    Null,
915    /// Exact numeric conversion exceeds the destination range.
916    Overflow,
917    /// Supplied value has an incompatible type.
918    WrongType,
919}
920/// Sanitized database error with a stable category and no source payload.
921#[derive(Clone, Copy, Debug, Eq, PartialEq)]
922pub struct DbError {
923    kind: ErrorKind,
924    reason: Option<InvalidArgumentReason>,
925}
926/// Static, safe explanation for invalid caller-supplied arguments.
927#[derive(Clone, Copy, Debug, Eq, PartialEq)]
928pub enum InvalidArgumentReason {
929    /// Parameter's value variant did not match its declared type.
930    ParameterTypeMismatch,
931    /// Floating-point value was NaN or infinite.
932    NonFiniteFloat,
933    /// Fetch row limit was zero.
934    ZeroFetchRowLimit,
935    /// Fetch byte limit was zero.
936    ZeroByteLimit,
937    /// Fetch result-set limit was zero.
938    ZeroSetLimit,
939}
940impl DbError {
941    /// Creates an error containing only its stable category.
942    #[must_use]
943    pub const fn new(kind: ErrorKind) -> Self {
944        Self { kind, reason: None }
945    }
946    /// Creates an invalid-argument error with a static, non-sensitive reason.
947    #[must_use]
948    pub const fn invalid(reason: InvalidArgumentReason) -> Self {
949        Self {
950            kind: ErrorKind::InvalidArgument,
951            reason: Some(reason),
952        }
953    }
954    /// Returns the safe static invalid-argument reason, if present.
955    #[must_use]
956    pub const fn reason(self) -> Option<InvalidArgumentReason> {
957        self.reason
958    }
959    /// Returns the stable error category.
960    #[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/// A detached row of owned values in ordinal order with provider-supplied names.
976#[derive(Clone, Debug, PartialEq)]
977pub struct Row {
978    columns: Vec<(String, Value)>,
979}
980impl Row {
981    /// Creates a row from owned name/value pairs; duplicate names remain representable but name lookup is ambiguous.
982    ///
983    /// # Errors
984    /// Returns `InvalidArgument` with a static reason if a cell contains a non-finite float.
985    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    /// Returns the number of columns.
992    #[must_use]
993    pub fn len(&self) -> usize {
994        self.columns.len()
995    }
996    /// Returns whether the row has no columns.
997    #[must_use]
998    pub fn is_empty(&self) -> bool {
999        self.columns.is_empty()
1000    }
1001    /// Returns a cell by zero-based ordinal, distinguishing missing columns and null values.
1002    ///
1003    /// # Errors
1004    /// Returns `Missing`, `Null`, `WrongType`, or `Overflow` as appropriate.
1005    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    /// Returns a cell by exact name; missing and duplicate names are decode errors.
1013    ///
1014    /// # Errors
1015    /// Returns `Missing`, `Ambiguous`, `Null`, `WrongType`, or `Overflow` as appropriate.
1016    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    /// Reads a cell by exact name with the same exact typing rules as [`Row::get`].
1027    ///
1028    /// # Errors
1029    /// Returns `Missing`, `Ambiguous`, `Null`, `WrongType`, or `Overflow` as appropriate.
1030    pub fn read<T: FromValue>(&self, name: &str) -> Result<T, DbError> {
1031        self.get(name)
1032    }
1033    /// Reads a cell by zero-based ordinal with the same exact typing rules as
1034    /// [`Row::get_ordinal`].
1035    ///
1036    /// # Errors
1037    /// Returns `Missing`, `Null`, `WrongType`, or `Overflow` as appropriate.
1038    pub fn read_at<T: FromValue>(&self, ordinal: usize) -> Result<T, DbError> {
1039        self.get_ordinal(ordinal)
1040    }
1041    /// Returns a cloned cell by zero-based ordinal, without typed conversion.
1042    ///
1043    /// # Errors
1044    /// Returns `Missing` when the ordinal is absent.
1045    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    /// Returns the row's portable byte cost: column-name UTF-8 bytes plus value payload bytes.
1052    ///
1053    /// Payload accounting is `Null = 0`, `Bool = 1`, `I64`/`F64 = 8`, and text/bytes length.
1054    /// Providers and buffering use the same rule so a limit means the same thing at every layer.
1055    ///
1056    /// # Errors
1057    /// Returns `Overflow` if the aggregate cannot be represented in `usize`.
1058    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    /// Reads a non-null value by exact name.
1076    ///
1077    /// # Errors
1078    /// Returns `Missing`, `Ambiguous`, `Null`, `WrongType`, or `Overflow`.
1079    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    /// Reads a non-null value by ordinal.
1097    ///
1098    /// # Errors
1099    /// Returns `Missing`, `Null`, `WrongType`, or `Overflow`.
1100    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}
1115/// Exact typed conversion from a row value; `Option<T>` represents a matching typed SQL null.
1116pub trait FromValue: Sized {
1117    /// SQL type accepted by this decoder.
1118    const DB_TYPE: DbType;
1119    /// Converts without lossy coercion.
1120    ///
1121    /// # Errors
1122    /// For non-nullable targets, returns `Null` for a matching typed SQL null, `WrongType` for
1123    /// incompatible types/null types, or `Overflow`.
1124    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);
1156/// Exact conversion from an SQL integer to a 32-bit integer.
1157impl 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
1170/// A statement's bounded result sets, consumed row by row.
1171///
1172/// A reader is not proof of a read: statements such as `INSERT ... RETURNING` can write.
1173/// `next_row_async` yields rows from the current result set and returns `None` at the end of that set.
1174/// `has_next_set_async` advances: it discards unread rows in the current set and reports whether another
1175/// set exists. `finish_async` drains and discards every remaining row and set, surfacing any later
1176/// statement error. A provider with unread results attached must discard its connection if an
1177/// unfinished reader is dropped. A provider that materializes the bounded batch before returning
1178/// may already have made the connection reusable and has nothing outstanding to discard.
1179///
1180/// `RowLimit` is a bound for the whole batch. A provider that supports multiple result sets counts
1181/// rows, bytes, and sets across the batch, including empty sets; a single-set provider may report
1182/// no next set instead of inventing a boundary it cannot observe. Buffering wrappers enforce the
1183/// same bounds while preserving boundaries.
1184pub trait Reader: Send {
1185    /// Returns the next row in the current result set, or `None` at the set's end.
1186    ///
1187    /// # Errors
1188    /// Returns a sanitized provider error. After an error the reader is finished; further calls
1189    /// return `None` or the same error. A provider with unread results attached must discard its
1190    /// connection when the reader is dropped.
1191    fn next_row_async(&mut self) -> DbFuture<'_, Option<Row>>;
1192
1193    /// Advances to the next result set, discarding any unread rows in the current one.
1194    ///
1195    /// Returns `true` when a next set is current, or `false` at the end of the batch. A single-set
1196    /// provider returns `false`; it must not fabricate result boundaries.
1197    ///
1198    /// # Errors
1199    /// Returns a sanitized provider error while draining or advancing.
1200    fn has_next_set_async(&mut self) -> DbFuture<'_, bool>;
1201
1202    /// Drains and discards every remaining row and result set.
1203    ///
1204    /// The reader is finished afterwards. A provider with unread results must give dropping the
1205    /// reader the same cleanup effect on the connection, but dropping cannot report a later
1206    /// statement error.
1207    ///
1208    /// # Errors
1209    /// Returns the first sanitized error encountered while draining.
1210    fn finish_async(&mut self) -> DbFuture<'_, ()>;
1211
1212    /// Drains every result set and returns the owned rows, flattening set boundaries.
1213    ///
1214    /// This is a convenience for callers that want the whole bounded batch. It does not add a
1215    /// limit of its own; providers apply the `RowLimit` supplied to `fetch_async`. Use
1216    /// [`Reader::read_sets_async`] when boundaries matter.
1217    ///
1218    /// # Errors
1219    /// Returns the first sanitized error encountered while reading or draining.
1220    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    /// Drains every result set and returns the rows grouped by set, including empty sets.
1232    ///
1233    /// This is a convenience for callers that want the whole bounded batch without losing
1234    /// boundaries. It does not add a limit of its own; providers apply the `RowLimit` supplied to
1235    /// `fetch_async`.
1236    ///
1237    /// # Errors
1238    /// Returns the first sanitized error encountered while reading or draining.
1239    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/// A reader over an already-materialized batch, preserving result-set boundaries.
1259///
1260/// Providers and wrappers that materialize the bounded batch before returning use this. It has no
1261/// unread wire results, so `finish_async` and `has_next_set_async` only discard the in-memory rows. Empty sets
1262/// remain representable and countable.
1263#[derive(Debug)]
1264pub struct BufferedReader {
1265    sets: VecDeque<VecDeque<Row>>,
1266    done: bool,
1267}
1268impl BufferedReader {
1269    /// Wraps owned rows as one result set.
1270    #[must_use]
1271    pub fn new(rows: Vec<Row>) -> Self {
1272        Self::from_sets(vec![rows])
1273    }
1274    /// Wraps owned rows grouped by result set, including empty sets.
1275    #[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
1322/// A pool able to acquire exclusive sessions and report truthful capabilities.
1323pub trait Pool: Send + Sync {
1324    /// Returns capabilities for this provider/configuration.
1325    fn capabilities(&self) -> Capabilities;
1326    /// Returns defaults used for options inherited by this pool.
1327    fn defaults(&self) -> PoolDefaults {
1328        PoolDefaults::default()
1329    }
1330    /// Acquires one exclusive session; the caller must drop it to release it.
1331    fn acquire_async(&self) -> DbFuture<'_, Box<dyn Session>>;
1332    /// Executes one statement through a newly acquired session with per-query policy overrides.
1333    /// Overrides must reject an explicit fetch limit before dispatch.
1334    ///
1335    /// # Errors
1336    /// Returns a sanitized provider error.
1337    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    /// Fetches one bounded batch through a newly acquired session with per-query overrides.
1347    ///
1348    /// The default implementation drains the batch and returns a reader over owned rows.
1349    ///
1350    /// # Errors
1351    /// Returns a sanitized provider error, including one found after the first row.
1352    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    /// Fetches and drains the whole bounded batch using default options.
1369    ///
1370    /// # Errors
1371    /// Returns a sanitized provider error, including one found after the first row.
1372    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    /// Fetches at most the first row of the first result set, then drains the full batch.
1385    ///
1386    /// # Errors
1387    /// Returns a sanitized provider error, including one found after the first row.
1388    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    /// Fetches a statement whose first result set must contain exactly one row.
1401    ///
1402    /// Remaining rows and later result sets are drained before returning. A later error wins over
1403    /// the cardinality result.
1404    ///
1405    /// # Errors
1406    /// Returns `NoRows`, `TooManyRows`, or a sanitized provider error found while reading.
1407    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    /// Fetches exactly one row and returns its first column.
1421    ///
1422    /// # Errors
1423    /// Returns `NoRows`, `TooManyRows`, `Missing` when the row has no columns, or a sanitized
1424    /// provider error found while reading.
1425    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}
1436/// An exclusively borrowed database session.
1437pub trait Session: Send {
1438    /// Defaults inherited by operations on this session.
1439    fn defaults(&self) -> PoolDefaults {
1440        PoolDefaults::default()
1441    }
1442    /// Executes one positional-parameter statement; parameters follow placeholder order, with no SQL rewriting.
1443    /// Providers must reject an explicit fetch limit before dispatch, e.g. via
1444    /// [`QueryOptions::prepare_execute_provider`]. An inherited limit is permitted.
1445    /// Providers reject placeholder/parameter count mismatches. SQLite uses `?`; PostgreSQL uses `$1`, `$2`.
1446    fn execute_async<'a>(&'a mut self, sql: &'a str, options: QueryOptions) -> DbFuture<'a, u64>;
1447    /// Fetches one bounded batch as a reader.
1448    ///
1449    /// The reader may borrow this session until it is finished or dropped; a provider that
1450    /// materializes the batch may release the session earlier. The limit applies to the whole
1451    /// batch; providers that support multiple result sets count rows and bytes across sets.
1452    /// Parameters are positional and ordered; providers reject count mismatches and do not rewrite
1453    /// SQL. Fetching does not imply read-only SQL: `INSERT ... RETURNING` can write. Providers must
1454    /// report uncertain write results as `WriteOutcomeUnknown`, not retryable transport errors.
1455    fn fetch_async<'a>(
1456        &'a mut self,
1457        sql: &'a str,
1458        options: QueryOptions,
1459    ) -> DbFuture<'a, Box<dyn Reader + 'a>>;
1460    /// Fetches and drains the whole bounded batch.
1461    ///
1462    /// # Errors
1463    /// Returns a sanitized provider error, including one found after the first row.
1464    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    /// Fetches at most the first row of the first result set, then drains the full batch.
1477    ///
1478    /// # Errors
1479    /// Returns a sanitized provider error, including one found after the first row.
1480    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    /// Fetches a statement whose first result set must contain exactly one row.
1493    ///
1494    /// Remaining rows and later result sets are drained before returning. A later error wins over
1495    /// the cardinality result.
1496    ///
1497    /// # Errors
1498    /// Returns `NoRows`, `TooManyRows`, or a sanitized provider error found while reading.
1499    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    /// Fetches exactly one row and returns its first column.
1513    ///
1514    /// # Errors
1515    /// Returns `NoRows`, `TooManyRows`, `Missing` when the row has no columns, or a sanitized
1516    /// provider error found while reading.
1517    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    /// Executes a multi-statement unparameterized script. Input must be trusted; scripts must not manage transactions.
1528    /// An interrupted operation requires provider cleanup before session reuse.
1529    fn execute_trusted_script_async<'a>(
1530        &'a mut self,
1531        sql: &'a str,
1532        options: QueryOptions,
1533    ) -> DbFuture<'a, ()>;
1534    /// Begins an interactive transaction on this same session; unsupported requested options fail before dispatch.
1535    /// If dropped after begin dispatch, the provider must roll back or discard the connection before reuse.
1536    fn begin_async<'a>(
1537        &'a mut self,
1538        options: TxOptions,
1539    ) -> DbFuture<'a, Box<dyn Transaction<'a> + 'a>>;
1540}
1541/// A transaction that exclusively borrows its session until consumed or dropped.
1542///
1543/// Dropping without commit or rollback, or interrupting a begin/commit/rollback future, must not leave
1544/// a connection reusable while a transaction may remain open. The provider must complete rollback
1545/// or discard that connection before allowing reuse. Dropping a Rust value alone is not proof of
1546/// rollback. A dispatched commit with unconfirmed success is an unknown outcome, not a rollback.
1547pub trait Transaction<'session>: Send {
1548    /// Defaults inherited by operations on this transaction.
1549    fn defaults(&self) -> PoolDefaults {
1550        PoolDefaults::default()
1551    }
1552    /// Executes one statement with positional parameters in slice order, without SQL rewriting.
1553    /// Providers must reject an explicit fetch limit before dispatch, e.g. via
1554    /// [`QueryOptions::prepare_execute_provider`]. An inherited limit is permitted.
1555    /// Providers reject placeholder/parameter count mismatches.
1556    fn execute_async<'a>(&'a mut self, sql: &'a str, options: QueryOptions) -> DbFuture<'a, u64>;
1557    /// Fetches one bounded batch as a reader.
1558    ///
1559    /// The reader may borrow this transaction until it is finished or dropped; a provider that
1560    /// materializes the batch may release it earlier. The limit applies to the whole batch;
1561    /// providers that support multiple result sets count rows and bytes across sets. Parameters are
1562    /// positional and ordered.
1563    fn fetch_async<'a>(
1564        &'a mut self,
1565        sql: &'a str,
1566        options: QueryOptions,
1567    ) -> DbFuture<'a, Box<dyn Reader + 'a>>;
1568    /// Fetches and drains the whole bounded batch.
1569    ///
1570    /// # Errors
1571    /// Returns a sanitized provider error, including one found after the first row.
1572    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    /// Fetches at most the first row of the first result set, then drains the full batch.
1585    ///
1586    /// # Errors
1587    /// Returns a sanitized provider error, including one found after the first row.
1588    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    /// Fetches a statement whose first result set must contain exactly one row.
1601    ///
1602    /// Remaining rows and later result sets are drained before returning. A later error wins over
1603    /// the cardinality result.
1604    ///
1605    /// # Errors
1606    /// Returns `NoRows`, `TooManyRows`, or a sanitized provider error found while reading.
1607    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    /// Fetches exactly one row and returns its first column.
1621    ///
1622    /// # Errors
1623    /// Returns `NoRows`, `TooManyRows`, `Missing` when the row has no columns, or a sanitized
1624    /// provider error found while reading.
1625    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    /// Executes a trusted multi-statement script that must not manage transactions. Interrupted work
1636    /// requires provider cleanup before transaction reuse.
1637    fn execute_trusted_script_async<'a>(
1638        &'a mut self,
1639        sql: &'a str,
1640        options: QueryOptions,
1641    ) -> DbFuture<'a, ()>;
1642    /// Commits and consumes this transaction. Before reuse, the provider must establish transaction
1643    /// closure and cleanup or discard the connection, including if this future is interrupted. If
1644    /// commit was dispatched but success is unknown, return `CommitOutcomeUnknown`; this does not
1645    /// imply rollback.
1646    fn commit_async(self: Box<Self>) -> DbFuture<'session, ()>;
1647    /// Rolls back and consumes this transaction. The provider must finish rollback or discard the
1648    /// connection before reuse, including if this future is interrupted; it must never return a
1649    /// possibly active connection.
1650    fn rollback_async(self: Box<Self>) -> DbFuture<'session, ()>;
1651}
1652/// Optional provider extension for SQLite-style immediate transaction starts without leaking driver types.
1653pub trait ImmediateTransaction: Session {
1654    /// Begins an immediate transaction on the same session or returns `Unsupported` before beginning.
1655    fn begin_immediate_async<'a>(&'a mut self) -> DbFuture<'a, Box<dyn Transaction<'a> + 'a>>;
1656}
1657
1658/// SQLite-specific pool capabilities shared by SQLite consumers without exposing a driver.
1659///
1660/// Implementations must apply `busy_timeout` to each acquired connection before returning the
1661/// immediate-transaction-capable session.
1662pub trait SqlitePool: Pool {
1663    /// Returns the configured SQLite busy timeout.
1664    fn busy_timeout(&self) -> Duration;
1665
1666    /// Acquires a session capable of starting `BEGIN IMMEDIATE`.
1667    fn acquire_sqlite_async(&self) -> DbFuture<'_, Box<dyn ImmediateTransaction>>;
1668}
1669
1670/// Policy and telemetry decorator for pool, session, transaction, and script operations.
1671///
1672/// Pool methods `execute_async`/`fetch_async` acquire a fresh session for each configured retry attempt.
1673/// Session, transaction, and trusted-script methods do not retry.
1674/// The total-budget timer is constructed once before acquisition and checked again before each
1675/// statement dispatch, including after every synchronous hook in nested policy session wrappers.
1676/// A pre-dispatch rejection remains `Cancelled`/`Timeout` and emits no statement events.
1677/// Already-dispatched success wins simultaneous cancellation/deadline.
1678/// Other interruptions during dispatch are `WriteOutcomeUnknown`, even for fetches; authoritative
1679/// provider unknown-outcome errors are never replaced by cancellation/deadline or retried.
1680/// Dropping an in-flight observed operation emits one `WriteOutcomeUnknown` event because dispatch
1681/// completion cannot be established.
1682/// Statement events cover execution only; acquisition and transaction begin/commit/rollback
1683/// boundaries are not separately observed.
1684pub 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    /// Wraps a provider and applies the supplied defaults to operations made through this wrapper.
1698    pub fn new<P: Pool + 'static>(pool: P, policy: PoolPolicy) -> Self {
1699        Self::from_shared(Arc::new(pool), policy)
1700    }
1701
1702    /// Wraps a shared provider trait object with per-pool policy.
1703    #[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// One pinned total-budget timer, shared by the resilience race and the SQL dispatch gate.
1937// Latch completion so neither consumer ever polls a completed timer again.
1938#[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        // Polling the caller's timer can itself make cancellation ready.
1957        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            // Construct the only timer before the first acquisition, not lazily inside a layer.
1992            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        // Acquisition may become ready in the engine's success probe. Check the actual timer,
2002        // not an expired flag that depends on the engine having polled its timer first.
2003        // A deeper policy layer is still preparing SQL, so no provider has been invoked yet.
2004        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    // Fetch is not proof of a read: INSERT ... RETURNING can have changed the database.
2042    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
2054/// Policy decorator that retains a pool's SQLite immediate-transaction capability.
2055///
2056/// It shares the observer, capture, timeout, and pool-operation retry implementation of
2057/// [`PolicyPool`]. Acquired SQLite sessions use the same observer helpers but intentionally do not
2058/// retry, matching ordinary policy sessions and transactions.
2059pub 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    /// Wraps a SQLite provider and preserves its immediate-transaction extension.
2075    pub fn new<P: SqlitePool + 'static>(pool: P, policy: PoolPolicy) -> Self {
2076        Self::from_shared(Arc::new(pool), policy)
2077    }
2078
2079    /// Wraps a shared SQLite provider while retaining one underlying pool for both APIs.
2080    #[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            // A panic payload may have a destructor that panics. Forget it so this callback
2425            // boundary cannot unwind while unwinding a post-operation observer/hook.
2426            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        // An inner hook can stop this operation before reaching the provider. Preserve that
2640        // rejection through every outer wrapper: it is neither a write nor a statement event.
2641        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}