ruprizzle 1.6.0

A schema-first ORM for Rust: typed queries, relations, and automatic migrations
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
//! The `Executor` abstraction over a pool and a transaction.
//!
//! Every query builder runs against an `&dyn Executor` rather than a concrete
//! [`Pool`], which is what lets the same query work unchanged inside or outside
//! a transaction. Both [`Pool`] and [`Tx`](crate::tx::Tx) implement it, and
//! because `&Pool` coerces to `&dyn Executor` the call sites in generated code
//! do not have to know which one they hold.
//!
//! The trait deals in raw SQL and [`Value`] binds, not in typed rows: decoding
//! is the caller's job via `sqlx::FromRow`. Keeping decoding out of the trait is
//! what keeps it object-safe, and object safety is what makes the pool/tx
//! substitution possible at all.

use std::borrow::Cow;

use ruprizzle_dialect::DbDialect;
use sqlx::any::AnyRow;
use sqlx::mysql::MySqlRow;
use sqlx::postgres::PgRow;
use sqlx::sqlite::SqliteRow;

use std::sync::atomic::{AtomicU64, Ordering};
use std::time::Duration;

use futures_util::StreamExt as _;

use crate::pool::{InFlight, ReadRoute};

static FULL_TABLE_INCLUDE_LIMIT: AtomicU64 = AtomicU64::new(100_000);
static SLOW_QUERY_THRESHOLD_NS: AtomicU64 = AtomicU64::new(0);

/// Sets the duration above which a query is logged as a slow query.
///
/// `None` disables the warning.
pub fn set_slow_query_threshold(threshold: Option<Duration>) {
    let ns = threshold.map_or(0, |d| d.as_nanos() as u64);
    SLOW_QUERY_THRESHOLD_NS.store(ns, Ordering::Relaxed);
}

/// Returns the current slow-query threshold, if any.
#[must_use]
pub fn slow_query_threshold() -> Option<Duration> {
    let ns = SLOW_QUERY_THRESHOLD_NS.load(Ordering::Relaxed);
    if ns == 0 {
        None
    } else {
        Some(Duration::from_nanos(ns))
    }
}

/// Sets the process-wide full-table include limit.
///
/// `0` (or `None`) disables the fast path entirely.
pub(crate) fn set_full_table_include_limit(limit: Option<u64>) {
    FULL_TABLE_INCLUDE_LIMIT.store(limit.unwrap_or(0), Ordering::Relaxed);
}

fn full_table_include_limit() -> u64 {
    FULL_TABLE_INCLUDE_LIMIT.load(Ordering::Relaxed)
}

use crate::BoxFuture;
use crate::error::Error;
use crate::pool::Pool;
use crate::value::Value;

/// A batch of rows returned by an executor, before `FromRow` decoding.
///
/// `Executor` is object-safe, so it cannot be generic over the row type.
/// Returning a backend-tagged batch lets the same trait object carry `AnyRow`,
/// `PgRow`, or `SqliteRow` rows, and the caller decodes with the matching
/// `FromRow` implementation.
#[non_exhaustive]
pub enum RowBatch {
    /// Rows from the generic `sqlx::Any` driver.
    Any(Vec<AnyRow>),
    /// Rows from the native Postgres driver.
    Postgres(Vec<PgRow>),
    /// Rows from the native SQLite driver.
    Sqlite(Vec<SqliteRow>),
    /// Rows from the native MySQL / MariaDB driver.
    Mysql(Vec<MySqlRow>),
    /// Rows from the native `rusqlite` backend.
    #[cfg(feature = "sqlite-rusqlite")]
    Rusqlite(Vec<crate::rusqlite::Row>),
    /// Rows from the native `tokio-postgres` backend.
    #[cfg(feature = "postgres-tokio-postgres")]
    PostgresNative(Vec<tokio_postgres::Row>),
    /// Rows from edge and serverless adapters (Turso, Cloudflare D1, Neon).
    Edge(Vec<std::collections::HashMap<String, Value>>),
}

impl RowBatch {
    /// Returns `true` if the batch contains no rows.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        match self {
            Self::Any(rows) => rows.is_empty(),
            Self::Postgres(rows) => rows.is_empty(),
            Self::Sqlite(rows) => rows.is_empty(),
            Self::Mysql(rows) => rows.is_empty(),
            #[cfg(feature = "sqlite-rusqlite")]
            Self::Rusqlite(rows) => rows.is_empty(),
            #[cfg(feature = "postgres-tokio-postgres")]
            Self::PostgresNative(rows) => rows.is_empty(),
            Self::Edge(rows) => rows.is_empty(),
        }
    }

    /// Returns the number of rows in the batch.
    #[must_use]
    pub fn len(&self) -> usize {
        match self {
            Self::Any(rows) => rows.len(),
            Self::Postgres(rows) => rows.len(),
            Self::Sqlite(rows) => rows.len(),
            Self::Mysql(rows) => rows.len(),
            #[cfg(feature = "sqlite-rusqlite")]
            Self::Rusqlite(rows) => rows.len(),
            #[cfg(feature = "postgres-tokio-postgres")]
            Self::PostgresNative(rows) => rows.len(),
            Self::Edge(rows) => rows.len(),
        }
    }

    /// Merges another batch of the same backend into this one.
    ///
    /// Used by nested `INSERT ... RETURNING` to accumulate child rows across
    /// parameter-limit chunks.
    pub fn merge(&mut self, other: Self) -> Result<(), Error> {
        match (self, other) {
            (Self::Any(a), Self::Any(b)) => a.extend(b),
            (Self::Postgres(a), Self::Postgres(b)) => a.extend(b),
            (Self::Sqlite(a), Self::Sqlite(b)) => a.extend(b),
            (Self::Mysql(a), Self::Mysql(b)) => a.extend(b),
            #[cfg(feature = "sqlite-rusqlite")]
            (Self::Rusqlite(a), Self::Rusqlite(b)) => a.extend(b),
            #[cfg(feature = "postgres-tokio-postgres")]
            (Self::PostgresNative(a), Self::PostgresNative(b)) => a.extend(b),
            (Self::Edge(a), Self::Edge(b)) => a.extend(b),
            _ => {
                return Err(Error::Message(
                    "cannot merge row batches from different backends".into(),
                ));
            }
        }
        Ok(())
    }

    /// Returns the edge rows if this batch was produced by an edge driver.
    #[must_use]
    pub fn as_edge_rows(&self) -> Option<&[std::collections::HashMap<String, Value>]> {
        match self {
            Self::Edge(rows) => Some(rows),
            _ => None,
        }
    }
}

impl std::fmt::Debug for RowBatch {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Any(rows) => f.debug_tuple("Any").field(&rows.len()).finish(),
            Self::Postgres(rows) => f.debug_tuple("Postgres").field(&rows.len()).finish(),
            Self::Sqlite(rows) => f.debug_tuple("Sqlite").field(&rows.len()).finish(),
            Self::Mysql(rows) => f.debug_tuple("Mysql").field(&rows.len()).finish(),
            #[cfg(feature = "sqlite-rusqlite")]
            Self::Rusqlite(rows) => f.debug_tuple("Rusqlite").field(&rows.len()).finish(),
            #[cfg(feature = "postgres-tokio-postgres")]
            Self::PostgresNative(rows) => {
                f.debug_tuple("PostgresNative").field(&rows.len()).finish()
            }
            Self::Edge(rows) => f.debug_tuple("Edge").field(&rows.len()).finish(),
        }
    }
}

/// Something that can run SQL: a connection pool or an open transaction.
pub trait Executor: Send + Sync {
    /// The dialect for the backend behind this executor.
    ///
    /// Query compilation needs this to pick identifier quoting and placeholder
    /// syntax, so it must be answerable without touching the database. The
    /// reference is tied to the executor, which typically caches a `'static`
    /// dialect internally.
    fn dialect(&self) -> &dyn DbDialect;

    /// Maximum child-table rows the include loader may load in one query when
    /// using the full-table fast path.
    ///
    /// A value of `0` disables the fast path and forces chunked `IN (...)`. The
    /// default is `100_000` and is configured through `PoolConfig`.
    fn full_table_include_limit(&self) -> u64 {
        full_table_include_limit()
    }

    /// Runs a query and returns the raw rows.
    ///
    /// `sql` is a [`Cow`] so callers with an owned `String` can pass it without
    /// an extra clone, while the executor can still borrow the text to hand to
    /// `sqlx`. The returned future owns the `Cow` and the binds.
    fn fetch_all_raw(
        &self,
        sql: Cow<'static, str>,
        binds: Vec<Value>,
    ) -> BoxFuture<'_, Result<RowBatch, Error>>;

    /// Runs a statement and returns the number of affected rows.
    fn execute_raw(
        &self,
        sql: Cow<'static, str>,
        binds: Vec<Value>,
    ) -> BoxFuture<'_, Result<u64, Error>>;

    /// Runs a query and yields decoded rows from a buffered result set.
    ///
    /// This deliberately fetches all rows first and then streams them. A true
    /// cursor is slower on `sqlx-sqlite` (see `docs/BenchmarkResults.md`).
    fn stream_raw(&self, sql: Cow<'static, str>, binds: Vec<Value>) -> BoxRowStream<'_>;

    /// Runs a query and yields rows as the database produces them.
    ///
    /// The default implementation falls back to `stream_raw`. Backends that
    /// support true streaming override this to avoid materialising the whole
    /// result set in memory.
    fn stream_unbuffered_raw(&self, sql: Cow<'static, str>, binds: Vec<Value>) -> BoxRowStream<'_> {
        self.stream_raw(sql, binds)
    }

    /// Optional hook called right before a query is executed.
    ///
    /// The default is a no-op; wrappers such as [`CountingExecutor`](crate::CountingExecutor) override it
    /// to record the statement when the caller takes a backend-specific fast
    /// path.
    fn on_query(&self) {}

    /// Returns the underlying [`crate::rusqlite::RusqlitePool`] if this executor is
    /// backed by the native `rusqlite` backend.
    ///
    /// Used by query builders to take a direct, single-pass decode path on
    /// SQLite. Returns `None` by default.
    #[cfg(feature = "sqlite-rusqlite")]
    fn as_rusqlite(&self) -> Option<&crate::rusqlite::RusqlitePool> {
        None
    }
}

/// A single raw row from any backend.
///
/// Streaming keeps the executor object-safe by returning an untyped row that the
/// caller decodes with the matching `FromRow` implementation.
#[non_exhaustive]
pub enum RawRow {
    /// A row from the generic `sqlx::Any` driver.
    Any(AnyRow),
    /// A row from the native Postgres driver.
    Postgres(PgRow),
    /// A row from the native SQLite driver.
    Sqlite(SqliteRow),
    /// A row from the native MySQL / MariaDB driver.
    Mysql(MySqlRow),
    /// A row from the native `rusqlite` backend.
    #[cfg(feature = "sqlite-rusqlite")]
    Rusqlite(crate::rusqlite::Row),
    /// A row from the native `tokio-postgres` backend.
    #[cfg(feature = "postgres-tokio-postgres")]
    PostgresNative(tokio_postgres::Row),
    /// A row from edge and serverless adapters (Turso, Cloudflare D1, Neon).
    Edge(std::collections::HashMap<String, Value>),
}

/// A boxed stream of raw rows.
pub type BoxRowStream<'a> =
    std::pin::Pin<Box<dyn futures_core::Stream<Item = Result<RawRow, Error>> + Send + 'a>>;

/// Observes a completed `fut` for metrics, debug tracing, and slow-query warnings.
///
/// This is the single place where query execution is observed so that pools and
/// transactions cannot drift. `sql` is logged by shape only; `binds` is the
/// placeholder count, never the values.
fn infer_operation_and_table(sql: &str) -> (&'static str, String) {
    let trimmed = sql.trim();
    let upper = trimmed.to_ascii_uppercase();
    if upper.starts_with("SELECT") {
        let op = "SELECT";
        let table = if let Some(from_idx) = upper.find(" FROM ") {
            let rest = trimmed.get(from_idx + 6..).unwrap_or("").trim();
            rest.split(|c: char| c.is_whitespace() || c == '(' || c == ',' || c == ';')
                .next()
                .unwrap_or("")
                .trim_matches(|c| c == '"' || c == '`' || c == '\'')
                .to_string()
        } else {
            String::new()
        };
        (op, table)
    } else if upper.starts_with("INSERT") {
        let op = "INSERT";
        let table = if let Some(into_idx) = upper.find(" INTO ") {
            let rest = trimmed.get(into_idx + 6..).unwrap_or("").trim();
            rest.split(|c: char| c.is_whitespace() || c == '(' || c == ';')
                .next()
                .unwrap_or("")
                .trim_matches(|c| c == '"' || c == '`' || c == '\'')
                .to_string()
        } else {
            String::new()
        };
        (op, table)
    } else if upper.starts_with("UPDATE") {
        let op = "UPDATE";
        let rest = trimmed.get(6..).unwrap_or("").trim();
        let table = rest
            .split(|c: char| c.is_whitespace() || c == ';')
            .next()
            .unwrap_or("")
            .trim_matches(|c| c == '"' || c == '`' || c == '\'')
            .to_string();
        (op, table)
    } else if upper.starts_with("DELETE") {
        let op = "DELETE";
        let table = if let Some(from_idx) = upper.find(" FROM ") {
            let rest = trimmed.get(from_idx + 6..).unwrap_or("").trim();
            rest.split(|c: char| c.is_whitespace() || c == ';')
                .next()
                .unwrap_or("")
                .trim_matches(|c| c == '"' || c == '`' || c == '\'')
                .to_string()
        } else {
            String::new()
        };
        (op, table)
    } else {
        ("QUERY", String::new())
    }
}

/// Observes a completed `fut` for metrics, debug tracing, and slow-query warnings.
///
/// This is the single place where query execution is observed so that pools and
/// transactions cannot drift. `sql` is logged by shape only; `binds` is the
/// placeholder count, never the values.
pub(crate) async fn trace_and_record_query<F>(
    sql: Cow<'static, str>,
    bind_count: usize,
    fut: F,
) -> Result<RowBatch, Error>
where
    F: std::future::Future<Output = Result<RowBatch, Error>>,
{
    let (op, table) = infer_operation_and_table(&sql);
    let sanitized_sql = crate::compile::sanitize_sql(&sql);
    let span = tracing::info_span!(
        "db.query",
        "db.system" = "rdbms",
        "db.statement" = %sanitized_sql,
        "db.operation" = %op,
        "db.table" = %table,
    );
    let _guard = span.enter();

    crate::metrics::counter(crate::metrics::QUERY_TOTAL, 1);
    let started = std::time::Instant::now();
    let result = fut.await;
    let elapsed = started.elapsed();
    crate::metrics::histogram(
        crate::metrics::QUERY_DURATION_SECONDS,
        elapsed.as_secs_f64(),
    );
    if let Err(error) = &result {
        crate::metrics::counter_with(
            crate::metrics::QUERY_ERRORS_TOTAL,
            [("kind", error.kind())],
            1,
        );
        emit_connection_events(error);
    }

    if tracing::enabled!(target: "ruprizzle::query", tracing::Level::DEBUG) {
        let elapsed_ms = elapsed.as_millis() as u64;
        match &result {
            Ok(batch) => tracing::debug!(
                target: "ruprizzle::query",
                sql = %sql,
                binds = bind_count,
                rows = batch.len(),
                elapsed_ms,
                "query"
            ),
            Err(error) => tracing::warn!(
                target: "ruprizzle::query",
                sql = %sql,
                binds = bind_count,
                elapsed_ms,
                error = error.kind(),
                "query failed"
            ),
        }
    }

    if let Some(threshold) = slow_query_threshold() {
        if elapsed > threshold {
            crate::metrics::counter(crate::metrics::SLOW_QUERIES_TOTAL, 1);
            tracing::warn!(
                target: "ruprizzle::slow_query",
                sql = %sql,
                binds = bind_count,
                elapsed_ms = elapsed.as_millis(),
                "slow query"
            );
        }
    }

    result
}

/// Observes a completed execute `fut` for metrics, debug tracing, and slow-query warnings.
pub(crate) async fn trace_and_record_execute<F>(
    sql: Cow<'static, str>,
    bind_count: usize,
    fut: F,
) -> Result<u64, Error>
where
    F: std::future::Future<Output = Result<u64, Error>>,
{
    let (op, table) = infer_operation_and_table(&sql);
    let sanitized_sql = crate::compile::sanitize_sql(&sql);
    let span = tracing::info_span!(
        "db.execute",
        "db.system" = "rdbms",
        "db.statement" = %sanitized_sql,
        "db.operation" = %op,
        "db.table" = %table,
    );
    let _guard = span.enter();

    crate::metrics::counter(crate::metrics::QUERY_TOTAL, 1);
    let started = std::time::Instant::now();
    let result = fut.await;
    let elapsed = started.elapsed();
    crate::metrics::histogram(
        crate::metrics::QUERY_DURATION_SECONDS,
        elapsed.as_secs_f64(),
    );
    if let Ok(rows) = &result {
        crate::metrics::counter(crate::metrics::ROWS_AFFECTED_TOTAL, *rows);
    }
    if let Err(error) = &result {
        crate::metrics::counter_with(
            crate::metrics::QUERY_ERRORS_TOTAL,
            [("kind", error.kind())],
            1,
        );
        emit_connection_events(error);
    }

    if tracing::enabled!(target: "ruprizzle::query", tracing::Level::DEBUG) {
        let elapsed_ms = elapsed.as_millis() as u64;
        match &result {
            Ok(rows_affected) => tracing::debug!(
                target: "ruprizzle::query",
                sql = %sql,
                binds = bind_count,
                rows_affected,
                elapsed_ms,
                "execute"
            ),
            Err(error) => tracing::warn!(
                target: "ruprizzle::query",
                sql = %sql,
                binds = bind_count,
                elapsed_ms,
                error = error.kind(),
                "execute failed"
            ),
        }
    }

    if let Some(threshold) = slow_query_threshold() {
        if elapsed > threshold {
            crate::metrics::counter(crate::metrics::SLOW_QUERIES_TOTAL, 1);
            tracing::warn!(
                target: "ruprizzle::slow_query",
                sql = %sql,
                binds = bind_count,
                elapsed_ms = elapsed.as_millis(),
                "slow query"
            );
        }
    }

    result
}

/// Emit connection lifecycle tracing for error categories that represent the
/// pool or network rather than the SQL.
pub(crate) fn emit_connection_events(error: &crate::Error) {
    match error {
        crate::Error::AcquireTimeout { reason } => {
            tracing::warn!(
                target: "ruprizzle::connection",
                event = "acquire_timeout",
                reason,
                "connection acquire timed out"
            );
        }
        crate::Error::ConnectionFailure { reason } => {
            tracing::warn!(
                target: "ruprizzle::connection",
                event = "disconnect",
                reason,
                "connection lost"
            );
        }
        crate::Error::PoolExhausted { backend } => {
            tracing::warn!(
                target: "ruprizzle::connection",
                event = "acquire_timeout",
                backend,
                "connection pool exhausted"
            );
        }
        _ => {}
    }
}

/// Resolves a pending fetch, then yields its rows one at a time.
///
/// Both executors currently buffer: a `Tx` must, because it owns one connection
/// behind a mutex and an open cursor would block every other statement on the
/// transaction. The `Pool` shares this path so the two cannot drift; swapping
/// it for a true incremental cursor is a `Pool`-only change behind this type.
pub(crate) struct DeferredRowStream<'a> {
    fut: crate::BoxFuture<'a, Result<RowBatch, Error>>,
    done: bool,
    buffered: std::vec::IntoIter<RawRow>,
}

impl<'a> DeferredRowStream<'a> {
    pub(crate) fn new(fut: crate::BoxFuture<'a, Result<RowBatch, Error>>) -> Self {
        Self {
            fut,
            done: false,
            buffered: Vec::new().into_iter(),
        }
    }
}

impl futures_core::Stream for DeferredRowStream<'_> {
    type Item = Result<RawRow, Error>;

    fn poll_next(
        self: std::pin::Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<Option<Self::Item>> {
        use std::task::Poll;

        let this = self.get_mut();

        if !this.done {
            match this.fut.as_mut().poll(cx) {
                Poll::Pending => return Poll::Pending,
                Poll::Ready(Err(e)) => {
                    this.done = true;
                    return Poll::Ready(Some(Err(e)));
                }
                Poll::Ready(Ok(batch)) => {
                    this.done = true;
                    this.buffered = match batch {
                        RowBatch::Any(rows) => {
                            rows.into_iter().map(RawRow::Any).collect::<Vec<_>>()
                        }
                        RowBatch::Postgres(rows) => {
                            rows.into_iter().map(RawRow::Postgres).collect::<Vec<_>>()
                        }
                        RowBatch::Sqlite(rows) => {
                            rows.into_iter().map(RawRow::Sqlite).collect::<Vec<_>>()
                        }
                        RowBatch::Mysql(rows) => {
                            rows.into_iter().map(RawRow::Mysql).collect::<Vec<_>>()
                        }
                        #[cfg(feature = "sqlite-rusqlite")]
                        RowBatch::Rusqlite(rows) => {
                            rows.into_iter().map(RawRow::Rusqlite).collect::<Vec<_>>()
                        }
                        #[cfg(feature = "postgres-tokio-postgres")]
                        RowBatch::PostgresNative(rows) => rows
                            .into_iter()
                            .map(RawRow::PostgresNative)
                            .collect::<Vec<_>>(),
                        RowBatch::Edge(rows) => {
                            rows.into_iter().map(RawRow::Edge).collect::<Vec<_>>()
                        }
                    }
                    .into_iter();
                }
            }
        }

        Poll::Ready(this.buffered.next().map(Ok))
    }
}

impl Executor for Pool {
    fn dialect(&self) -> &dyn DbDialect {
        crate::compile::dialect_for_pool(self)
    }

    #[cfg(feature = "sqlite-rusqlite")]
    fn as_rusqlite(&self) -> Option<&crate::rusqlite::RusqlitePool> {
        match self {
            Pool::SqliteNative(p) => Some(p),
            _ => None,
        }
    }

    fn fetch_all_raw(
        &self,
        sql: Cow<'static, str>,
        binds: Vec<Value>,
    ) -> BoxFuture<'_, Result<RowBatch, Error>> {
        let bind_count = binds.len();
        let pool = self.clone();
        Box::pin(trace_and_record_query(
            sql.clone(),
            bind_count,
            async move { dispatch_raw_query(&pool, sql, binds).await },
        ))
    }

    fn execute_raw(
        &self,
        sql: Cow<'static, str>,
        binds: Vec<Value>,
    ) -> BoxFuture<'_, Result<u64, Error>> {
        let bind_count = binds.len();
        let pool = self.clone();
        Box::pin(trace_and_record_execute(
            sql.clone(),
            bind_count,
            async move { dispatch_raw_execute(&pool, sql, binds).await },
        ))
    }

    fn stream_raw(&self, sql: Cow<'static, str>, binds: Vec<Value>) -> BoxRowStream<'_> {
        Box::pin(DeferredRowStream::new(Box::pin(async move {
            self.fetch_all_raw(sql, binds).await
        })))
    }

    fn stream_unbuffered_raw(&self, sql: Cow<'static, str>, binds: Vec<Value>) -> BoxRowStream<'_> {
        match self {
            #[cfg(feature = "postgres-tokio-postgres")]
            Pool::PostgresNative(p) => Executor::stream_unbuffered_raw(p, sql, binds),
            _ => self.stream_raw(sql, binds),
        }
    }
}

async fn dispatch_raw_query(
    pool: &Pool,
    sql: Cow<'static, str>,
    binds: Vec<Value>,
) -> Result<RowBatch, Error> {
    match pool {
        Pool::Any(p) => {
            let mut q = sqlx::query::<sqlx::Any>(&sql);
            for bind in &binds {
                q = q.bind(bind);
            }
            q.fetch_all(p).await.map(RowBatch::Any).map_err(Error::from)
        }
        Pool::Postgres(p) => {
            let mut q = sqlx::query::<sqlx::Postgres>(&sql);
            for bind in &binds {
                q = q.bind(bind);
            }
            q.fetch_all(p)
                .await
                .map(RowBatch::Postgres)
                .map_err(Error::from)
        }
        Pool::Sqlite(p) => {
            let mut q = sqlx::query::<sqlx::Sqlite>(&sql);
            for bind in &binds {
                q = q.bind(bind);
            }
            q.fetch_all(p)
                .await
                .map(RowBatch::Sqlite)
                .map_err(Error::from)
        }
        Pool::Mysql(p) => {
            let mut q = sqlx::query::<sqlx::MySql>(&sql);
            for bind in &binds {
                q = q.bind(bind);
            }
            q.fetch_all(p)
                .await
                .map(RowBatch::Mysql)
                .map_err(Error::from)
        }
        #[cfg(feature = "sqlite-rusqlite")]
        Pool::SqliteNative(p) => Executor::fetch_all_raw(p, sql, binds).await,
        #[cfg(feature = "postgres-tokio-postgres")]
        Pool::PostgresNative(p) => Executor::fetch_all_raw(p, sql, binds).await,
    }
}

async fn dispatch_raw_execute(
    pool: &Pool,
    sql: Cow<'static, str>,
    binds: Vec<Value>,
) -> Result<u64, Error> {
    match pool {
        Pool::Any(p) => {
            let mut q = sqlx::query::<sqlx::Any>(&sql);
            for bind in &binds {
                q = q.bind(bind);
            }
            q.execute(p)
                .await
                .map(|r| r.rows_affected())
                .map_err(Error::from)
        }
        Pool::Postgres(p) => {
            let mut q = sqlx::query::<sqlx::Postgres>(&sql);
            for bind in &binds {
                q = q.bind(bind);
            }
            q.execute(p)
                .await
                .map(|r| r.rows_affected())
                .map_err(Error::from)
        }
        Pool::Sqlite(p) => {
            let mut q = sqlx::query::<sqlx::Sqlite>(&sql);
            for bind in &binds {
                q = q.bind(bind);
            }
            q.execute(p)
                .await
                .map(|r| r.rows_affected())
                .map_err(Error::from)
        }
        Pool::Mysql(p) => {
            let mut q = sqlx::query::<sqlx::MySql>(&sql);
            for bind in &binds {
                q = q.bind(bind);
            }
            q.execute(p)
                .await
                .map(|r| r.rows_affected())
                .map_err(Error::from)
        }
        #[cfg(feature = "sqlite-rusqlite")]
        Pool::SqliteNative(p) => Executor::execute_raw(p, sql, binds).await,
        #[cfg(feature = "postgres-tokio-postgres")]
        Pool::PostgresNative(p) => Executor::execute_raw(p, sql, binds).await,
    }
}

/// Decodes a batch of raw rows into a `FromRow` type.
///
/// Shared by every builder so that the pool and transaction paths cannot drift
/// apart in how they decode.
pub fn decode_rows<T>(batch: RowBatch) -> Result<Vec<T>, Error>
where
    T: crate::model::RowDecode,
{
    match batch {
        RowBatch::Any(rows) => rows
            .iter()
            .map(|r| T::from_row(r).map_err(Error::Sqlx))
            .collect(),
        RowBatch::Postgres(rows) => rows
            .iter()
            .map(|r| T::from_row(r).map_err(Error::Sqlx))
            .collect(),
        RowBatch::Sqlite(rows) => rows
            .iter()
            .map(|r| T::from_row(r).map_err(Error::Sqlx))
            .collect(),
        RowBatch::Mysql(rows) => rows
            .iter()
            .map(|r| T::from_row(r).map_err(Error::Sqlx))
            .collect(),
        #[cfg(feature = "sqlite-rusqlite")]
        RowBatch::Rusqlite(rows) => rows.iter().map(|r| T::from_owned_row(r)).collect(),
        #[cfg(feature = "postgres-tokio-postgres")]
        RowBatch::PostgresNative(rows) => {
            rows.iter().map(|r| T::from_tokio_postgres_row(r)).collect()
        }
        RowBatch::Edge(_) => Err(Error::Message(
            "RowBatch::Edge cannot be decoded via sqlx FromRow; use custom edge decoder or typed edge adapter".into(),
        )),
    }
}

impl Executor for crate::pool::RoutedPool {
    fn dialect(&self) -> &dyn DbDialect {
        self.primary().dialect()
    }

    fn fetch_all_raw(
        &self,
        sql: Cow<'static, str>,
        binds: Vec<Value>,
    ) -> BoxFuture<'_, Result<RowBatch, Error>> {
        if !crate::pool::is_replica_safe(&sql) {
            return self.primary().fetch_all_raw(sql, binds);
        }
        crate::metrics::counter(crate::metrics::REPLICA_ROUTING_TOTAL, 1);
        match self.route_read() {
            ReadRoute::Replica(replica) => {
                let in_flight = InFlight::start(replica);
                let pool = &replica.pool;
                Box::pin(async move {
                    let result = pool.fetch_all_raw(sql, binds).await;
                    drop(in_flight);
                    result
                })
            }
            ReadRoute::Primary => self.primary().fetch_all_raw(sql, binds),
            ReadRoute::NoHealthyReplica => Box::pin(async { Err(no_healthy_replica()) }),
        }
    }

    fn stream_raw<'a>(&'a self, sql: Cow<'static, str>, binds: Vec<Value>) -> BoxRowStream<'a> {
        if !crate::pool::is_replica_safe(&sql) {
            return self.primary().stream_raw(sql, binds);
        }
        crate::metrics::counter(crate::metrics::REPLICA_ROUTING_TOTAL, 1);
        match self.route_read() {
            ReadRoute::Replica(replica) => {
                // The count is held until the stream is dropped, not just until
                // the first row, so a slow consumer still counts as load.
                let in_flight = InFlight::start(replica);
                Box::pin(replica.pool.stream_raw(sql, binds).map(move |row| {
                    let _held = &in_flight;
                    row
                }))
            }
            ReadRoute::Primary => self.primary().stream_raw(sql, binds),
            ReadRoute::NoHealthyReplica => Box::pin(futures_util::stream::iter(std::iter::once(
                Err(no_healthy_replica()),
            ))),
        }
    }

    fn execute_raw(
        &self,
        sql: Cow<'static, str>,
        binds: Vec<Value>,
    ) -> BoxFuture<'_, Result<u64, Error>> {
        self.primary().execute_raw(sql, binds)
    }
}

fn no_healthy_replica() -> Error {
    Error::Message(
        "no healthy read replica, and fallback_to_primary is disabled; \
         call RoutedPool::check_health() or mark a replica healthy"
            .into(),
    )
}