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
//! Native `tokio-postgres` backend for the ruprizzle runtime.
//!
//! This module is compiled only when the `postgres-tokio-postgres` feature is
//! enabled. It uses `deadpool-postgres` for pooling and `tokio-postgres` for
//! the wire protocol, giving PostgreSQL a direct binary-parameter path that
//! avoids the `sqlx` parameter-type and row-decoding overhead.

#![cfg(feature = "postgres-tokio-postgres")]

use std::borrow::Cow;
use std::fmt;
use std::str::FromStr;

use bytes::BytesMut;
use deadpool_postgres::{Manager, ManagerConfig, Object, Pool, RecyclingMethod, Runtime};
use ruprizzle_core::ir::Provider;
use ruprizzle_dialect::dialect_for;
use tokio_postgres::NoTls;
use tokio_postgres::types::{IsNull, ToSql, Type};

pub use tokio_postgres::Row;

use crate::types::chrono::{DateTime, NaiveDate, NaiveTime, Utc};
use crate::types::{Decimal, Uuid};

// Helpers for homogeneous Postgres arrays in the native `tokio-postgres` path.
macro_rules! pg_tokio_array_encode {
    ($values:expr, $ty:expr, $out:expr, $check:pat, $variant:pat, $rust_ty:ty, $convert:expr) => {
        if $values
            .iter()
            .find(|v| !v.is_null())
            .map_or(false, |v| matches!(v, $check))
        {
            let vec: Vec<Option<$rust_ty>> = $values
                .iter()
                .map(|val| match val {
                    Value::Null => Ok(None),
                    $variant => Ok(Some($convert)),
                    other => Err(format!(
                        "array contains mixed or unsupported element: expected {}, found {:?}",
                        std::any::type_name::<$rust_ty>(),
                        other
                    )
                    .into()),
                })
                .collect::<Result<Vec<Option<$rust_ty>>, Box<dyn std::error::Error + Sync + Send>>>(
                )?;
            return <Vec<Option<$rust_ty>> as ToSql>::to_sql_checked(&vec, $ty, $out);
        }
    };
}

use crate::BoxFuture;
use crate::Error;
use crate::executor::{BoxRowStream, Executor, RawRow, RowBatch};
use crate::pool::PoolConfig;
use crate::value::Value;
use futures_util::StreamExt as _;

/// A `tokio-postgres`-backed PostgreSQL connection pool.
#[derive(Clone)]
pub struct TokioPostgresPool {
    inner: Pool,
}

impl fmt::Debug for TokioPostgresPool {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("TokioPostgresPool")
            .field("status", &self.inner.status())
            .finish_non_exhaustive()
    }
}

impl TokioPostgresPool {
    /// Open a new `tokio-postgres` pool from a PostgreSQL URL and configuration.
    ///
    /// # Errors
    ///
    /// Returns an error if the URL cannot be parsed or the pool cannot be built.
    pub async fn connect(url: &str, config: &PoolConfig) -> Result<Self, Error> {
        let (uses_native, stripped) = strip_driver_param(url);
        if !uses_native {
            // The caller should have already routed based on `driver=tokio-postgres`.
            return Err(Error::Message(
                "expected `driver=tokio-postgres` in URL".into(),
            ));
        }

        let pg_config =
            tokio_postgres::Config::from_str(&stripped).map_err(|e| Error::ConnectionFailure {
                reason: e.to_string(),
            })?;

        tracing::info!(
            target: "ruprizzle::connection",
            event = "connect",
            backend = "tokio-postgres",
            "tokio-postgres pool opened"
        );

        // Apply the ruprizzle pool settings to the manager.
        //
        // `Clean` is the only method that scrubs session state, and it is not
        // the default: it measured around 2× the total per-query latency
        // against a local database, and the abandoned-transaction case it would
        // cover is already handled by `TokioPostgresTransaction`'s `Drop`. It is
        // available through `PoolConfig::reset_on_recycle` as defence in depth.
        let mgr_config = ManagerConfig {
            recycling_method: if config.reset_on_recycle {
                RecyclingMethod::Clean
            } else if config.test_before_acquire {
                RecyclingMethod::Verified
            } else {
                RecyclingMethod::Fast
            },
        };

        let mgr = Manager::from_config(pg_config, NoTls, mgr_config);

        let pool = Pool::builder(mgr)
            .max_size(config.max_connections as usize)
            .runtime(Runtime::Tokio1)
            .wait_timeout(Some(config.acquire_timeout))
            .create_timeout(Some(config.acquire_timeout))
            .recycle_timeout(Some(config.acquire_timeout))
            .build()
            .map_err(|e| Error::ConnectionFailure {
                reason: e.to_string(),
            })?;

        // Fill the pool to the requested minimum so the first query is not
        // penalised by cold-start connections.
        for _ in 0..config.min_connections {
            let _ = pool.get().await.map_err(tokio_postgres_pool_error)?;
        }

        Ok(Self { inner: pool })
    }

    /// Total connections currently held by the pool.
    #[must_use]
    pub fn size(&self) -> u32 {
        self.inner.status().size as u32
    }

    /// Connections immediately available for checkout.
    #[must_use]
    pub fn num_idle(&self) -> usize {
        self.inner.status().available
    }

    /// Connections currently waiting for a checkout.
    #[must_use]
    pub fn num_waiters(&self) -> usize {
        self.inner.status().waiting
    }

    /// Fetch all rows from `sql` with `binds`.
    pub(crate) async fn fetch_all(&self, sql: &str, binds: &[Value]) -> Result<RowBatch, Error> {
        let client = self.inner.get().await.map_err(tokio_postgres_pool_error)?;
        let params = bind_params(binds)?;
        let rows = client.query(sql, &params).await.map_err(Error::from)?;
        Ok(RowBatch::PostgresNative(rows))
    }

    /// Execute `sql` with `binds`, returning the number of affected rows.
    pub(crate) async fn execute(&self, sql: &str, binds: &[Value]) -> Result<u64, Error> {
        let client = self.inner.get().await.map_err(tokio_postgres_pool_error)?;
        let params = bind_params(binds)?;
        client.execute(sql, &params).await.map_err(Error::from)
    }

    /// Begin a new transaction on this pool.
    pub(crate) async fn begin(&self) -> Result<TokioPostgresTransaction, Error> {
        let client = self.inner.get().await.map_err(tokio_postgres_pool_error)?;
        client.execute("BEGIN", &[]).await.map_err(Error::from)?;
        Ok(TokioPostgresTransaction {
            client: Some(client),
            // Captured here rather than in `Drop`, which may run on a thread
            // with no runtime in context (a `block_on` teardown, say). `begin`
            // is `async`, so there is always one at this point.
            runtime: tokio::runtime::Handle::try_current().ok(),
        })
    }
}

impl Executor for TokioPostgresPool {
    fn dialect(&self) -> &dyn ruprizzle_dialect::DbDialect {
        dialect_for(Provider::Postgres)
    }

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

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

    fn stream_raw(&self, sql: Cow<'static, str>, binds: Vec<Value>) -> BoxRowStream<'_> {
        Box::pin(crate::executor::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<'_> {
        let sql = sql.into_owned();
        let pool = self.clone();

        Box::pin(futures_util::stream::unfold(
            (
                sql,
                binds,
                None::<std::pin::Pin<Box<tokio_postgres::RowStream>>>,
            ),
            move |(sql, binds, mut stream)| {
                let pool = pool.clone();
                async move {
                    if stream.is_none() {
                        let client = match pool.inner.get().await {
                            Ok(c) => c,
                            Err(e) => {
                                return Some((
                                    Err(tokio_postgres_pool_error(e)),
                                    (sql, binds, None),
                                ));
                            }
                        };
                        let row_stream = match client.query_raw(&sql, &binds).await {
                            Ok(s) => s,
                            Err(e) => return Some((Err(Error::from(e)), (sql, binds, None))),
                        };
                        stream = Some(Box::pin(row_stream));
                    }

                    let s = stream.as_mut()?;
                    match s.next().await {
                        Some(Ok(row)) => {
                            Some((Ok(RawRow::PostgresNative(row)), (sql, binds, stream)))
                        }
                        Some(Err(e)) => Some((Err(Error::from(e)), (sql, binds, None))),
                        None => None,
                    }
                }
            },
        ))
    }
}

/// A `tokio-postgres` transaction that owns its pooled connection.
///
/// **This type must never be `Clone`.** It owns its `Object` exclusively; two
/// handles to one pooled connection would let two callers issue statements
/// inside the same `BEGIN` while each believed it held the connection alone.
/// See BUG-06, which is that hazard on the `rusqlite` side.
pub(crate) struct TokioPostgresTransaction {
    /// `None` once the transaction has been committed or rolled back, which is
    /// how [`Drop`] tells a finished transaction from an abandoned one.
    client: Option<Object>,
    /// The runtime to spawn the rollback on when the transaction is abandoned.
    runtime: Option<tokio::runtime::Handle>,
}

impl fmt::Debug for TokioPostgresTransaction {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("TokioPostgresTransaction")
            .finish_non_exhaustive()
    }
}

impl TokioPostgresTransaction {
    /// The connection this transaction owns, or an error if it has finished.
    fn client(&self) -> Result<&Object, Error> {
        self.client
            .as_ref()
            .ok_or_else(|| Error::Message("transaction already finished".into()))
    }

    /// Commit the transaction and return the connection to the pool.
    pub(crate) async fn commit(mut self) -> Result<(), Error> {
        self.finish("COMMIT").await
    }

    /// Roll the transaction back and return the connection to the pool.
    pub(crate) async fn rollback(mut self) -> Result<(), Error> {
        self.finish("ROLLBACK").await
    }

    /// Run `stmt` (`COMMIT` or `ROLLBACK`) and release the connection.
    ///
    /// Taking the `Object` out first is what stops [`Drop`] from spawning a
    /// second, redundant `ROLLBACK` after an explicit finish.
    async fn finish(&mut self, stmt: &'static str) -> Result<(), Error> {
        let Some(client) = self.client.take() else {
            return Err(Error::Message("transaction already finished".into()));
        };

        let result = client.execute(stmt, &[]).await.map_err(Error::from);

        if result.is_err() && stmt != "ROLLBACK" {
            // A failed COMMIT leaves the transaction open (or aborted). The
            // connection is about to go back into rotation, so end it.
            let _ = client.execute("ROLLBACK", &[]).await;
        }

        result.map(|_| ())
    }

    /// Execute `sql` with `binds` inside the transaction.
    pub(crate) async fn execute(&self, sql: &str, binds: &[Value]) -> Result<u64, Error> {
        let params = bind_params(binds)?;
        self.client()?
            .execute(sql, &params)
            .await
            .map_err(Error::from)
    }

    /// Fetch all rows from `sql` with `binds` inside the transaction.
    pub(crate) async fn fetch_all(&self, sql: &str, binds: &[Value]) -> Result<RowBatch, Error> {
        let params = bind_params(binds)?;
        let rows = self
            .client()?
            .query(sql, &params)
            .await
            .map_err(Error::from)?;
        Ok(RowBatch::PostgresNative(rows))
    }
}

/// Roll back before releasing the connection when a transaction is abandoned.
///
/// Without this, dropping a transaction released the `Object` straight back to
/// `deadpool` with its `BEGIN` still open, and the next request to receive that
/// connection ran inside the previous request's transaction (BUG-03). Unlike
/// the `rusqlite` leak this was silent: the connection was never lost, only
/// dirty.
///
/// `ROLLBACK` is async and `Drop` is not, so the rollback is spawned — and the
/// `Object` moves *into* the spawned task. That ordering is the whole point:
/// `deadpool` reclaims the connection when the `Object` drops, so it must not
/// drop until the rollback has resolved.
impl Drop for TokioPostgresTransaction {
    fn drop(&mut self) {
        let Some(client) = self.client.take() else {
            return;
        };

        tracing::warn!(
            target: "ruprizzle::query",
            "transaction dropped without commit or rollback; rolling back"
        );

        let Some(runtime) = self.runtime.take() else {
            // No runtime to roll back on. Detaching the connection loses it
            // from the pool, which is the lesser evil: returning it would put
            // the next request inside this transaction.
            tracing::warn!(
                target: "ruprizzle::query",
                "no tokio runtime available to roll back an abandoned transaction; \
                 discarding the connection"
            );
            let _ = Object::take(client);
            return;
        };

        runtime.spawn(async move {
            if let Err(error) = client.execute("ROLLBACK", &[]).await {
                tracing::warn!(
                    target: "ruprizzle::query",
                    error = %error,
                    "failed to roll back an abandoned transaction"
                );
            }
            // `client` drops here, returning the connection to `deadpool` only
            // now that the rollback has completed.
            drop(client);
        });
    }
}

/// Convert a vector of [`Value`]s into a slice of `&(dyn ToSql + Sync)`.
///
/// [`Value`] implements `ToSql`, so this only needs to collect the references.
fn bind_params(binds: &[Value]) -> Result<Vec<&(dyn ToSql + Sync)>, Error> {
    let mut params = Vec::with_capacity(binds.len());
    for b in binds {
        params.push(b as &(dyn ToSql + Sync));
    }
    Ok(params)
}

/// A type that can be decoded from a `tokio_postgres::Row`.
pub trait FromTokioPostgresRow: Sized + Send + Sync + 'static {
    /// Decode `self` from an ordered row of PostgreSQL values.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Message`] if the row cannot be decoded.
    fn from_tokio_postgres_row(row: &Row) -> Result<Self, Error>;
}

macro_rules! tuple_from_tokio_postgres_row {
    ($($T:ident $idx:tt),+) => {
        impl<$($T: tokio_postgres::types::FromSqlOwned + Send + Sync + 'static),+> FromTokioPostgresRow for ($($T,)+) {
            fn from_tokio_postgres_row(row: &Row) -> Result<Self, Error> {
                Ok((
                    $(
                        row.try_get::<usize, $T>($idx)?
                    ,)+
                ))
            }
        }
    };
}

tuple_from_tokio_postgres_row! { A 0 }
tuple_from_tokio_postgres_row! { A 0, B 1 }
tuple_from_tokio_postgres_row! { A 0, B 1, C 2 }
tuple_from_tokio_postgres_row! { A 0, B 1, C 2, D 3 }
tuple_from_tokio_postgres_row! { A 0, B 1, C 2, D 3, E 4 }
tuple_from_tokio_postgres_row! { A 0, B 1, C 2, D 3, E 4, F 5 }
tuple_from_tokio_postgres_row! { A 0, B 1, C 2, D 3, E 4, F 5, G 6 }
tuple_from_tokio_postgres_row! { A 0, B 1, C 2, D 3, E 4, F 5, G 6, H 7 }

/// Convenience macro for tests and examples: implement `FromTokioPostgresRow`
/// by returning `Default::default()`.
///
/// This is only useful when the type is never actually decoded from a
/// `tokio-postgres` row (e.g. SQLite-only tests).
#[macro_export]
#[cfg(feature = "postgres-tokio-postgres")]
macro_rules! tokio_postgres_default_row {
    ($t:ty) => {
        impl $crate::tokio_postgres::FromTokioPostgresRow for $t {
            fn from_tokio_postgres_row(
                _: &$crate::tokio_postgres::Row,
            ) -> Result<Self, $crate::Error> {
                Ok(<$t>::default())
            }
        }
    };
}

impl TokioPostgresPool {
    /// Close the pool.
    pub(crate) async fn close(&self) {
        self.inner.close();
    }
}

/// Implement `ToSql` for [`Value`] so the generic query pipeline can bind
/// values without per-call allocation.
impl ToSql for Value {
    fn to_sql(
        &self,
        ty: &Type,
        out: &mut BytesMut,
    ) -> Result<IsNull, Box<dyn std::error::Error + Sync + Send>> {
        // Always go through `to_sql_checked` so each variant's real `ToSql`
        // implementation has a chance to verify the Postgres `Type`.
        self.to_sql_checked(ty, out)
    }

    fn accepts(_ty: &Type) -> bool
    where
        Self: Sized,
    {
        // `Value` is a runtime-discriminated union. The real compatibility check
        // happens inside `to_sql_checked` by delegating to the variant's real
        // `ToSql` implementation. Returning `true` here lets the driver send
        // `NULL` values to any column type without forcing a TEXT cast.
        true
    }

    fn to_sql_checked(
        &self,
        ty: &Type,
        out: &mut BytesMut,
    ) -> Result<IsNull, Box<dyn std::error::Error + Sync + Send>> {
        match self {
            Value::Null => Ok(IsNull::Yes),
            Value::Bool(b) => <bool as ToSql>::to_sql_checked(b, ty, out),
            Value::I32(i) => <i32 as ToSql>::to_sql_checked(i, ty, out),
            Value::I64(i) => <i64 as ToSql>::to_sql_checked(i, ty, out),
            Value::F64(f) => <f64 as ToSql>::to_sql_checked(f, ty, out),
            Value::Decimal(d) => <crate::types::Decimal as ToSql>::to_sql_checked(d, ty, out),
            Value::Str(s) => {
                let s_ref: &str = s.as_ref();
                <&str as ToSql>::to_sql_checked(&s_ref, ty, out)
            }
            Value::Uuid(u) => <crate::types::Uuid as ToSql>::to_sql_checked(u, ty, out),
            Value::DateTime(dt) => {
                <chrono::DateTime<chrono::Utc> as ToSql>::to_sql_checked(dt, ty, out)
            }
            Value::Date(d) => <chrono::NaiveDate as ToSql>::to_sql_checked(d, ty, out),
            Value::Time(t) => <chrono::NaiveTime as ToSql>::to_sql_checked(t, ty, out),
            Value::Json(v) => <serde_json::Value as ToSql>::to_sql_checked(v, ty, out),
            Value::Bytes(b) => {
                let bytes: &[u8] = b.as_ref();
                <&[u8] as ToSql>::to_sql_checked(&bytes, ty, out)
            }
            Value::Array(values) => {
                if values.iter().any(|v| matches!(v, Value::Array(_))) {
                    return Err("nested arrays are not supported".into());
                }
                pg_tokio_array_encode!(values, ty, out, Value::Bool(_), Value::Bool(b), bool, *b);
                pg_tokio_array_encode!(values, ty, out, Value::I32(_), Value::I32(i), i32, *i);
                pg_tokio_array_encode!(values, ty, out, Value::I64(_), Value::I64(i), i64, *i);
                pg_tokio_array_encode!(values, ty, out, Value::F64(_), Value::F64(f), f64, *f);
                pg_tokio_array_encode!(
                    values,
                    ty,
                    out,
                    Value::Decimal(_),
                    Value::Decimal(d),
                    Decimal,
                    *d
                );
                pg_tokio_array_encode!(
                    values,
                    ty,
                    out,
                    Value::Str(_),
                    Value::Str(s),
                    String,
                    s.to_string()
                );
                pg_tokio_array_encode!(values, ty, out, Value::Uuid(_), Value::Uuid(u), Uuid, *u);
                pg_tokio_array_encode!(
                    values,
                    ty,
                    out,
                    Value::DateTime(_),
                    Value::DateTime(dt),
                    DateTime<Utc>,
                    *dt
                );
                pg_tokio_array_encode!(
                    values,
                    ty,
                    out,
                    Value::Date(_),
                    Value::Date(d),
                    NaiveDate,
                    *d
                );
                pg_tokio_array_encode!(
                    values,
                    ty,
                    out,
                    Value::Time(_),
                    Value::Time(t),
                    NaiveTime,
                    *t
                );
                pg_tokio_array_encode!(
                    values,
                    ty,
                    out,
                    Value::Json(_),
                    Value::Json(v),
                    serde_json::Value,
                    v.clone()
                );
                pg_tokio_array_encode!(
                    values,
                    ty,
                    out,
                    Value::Bytes(_),
                    Value::Bytes(b),
                    Vec<u8>,
                    b.to_vec()
                );
                // Empty or all-NULL: bind as an empty text array. This is a safe default
                // because untyped placeholders are usually cast by the query.
                let empty: Vec<Option<String>> = Vec::new();
                <Vec<Option<String>> as ToSql>::to_sql_checked(&empty, ty, out)
            }
        }
    }
}

/// Strips the `driver=tokio-postgres` routing parameter from a PostgreSQL URL
/// so the remainder can be parsed by `tokio_postgres::Config`.
fn strip_driver_param(url: &str) -> (bool, String) {
    let Some((base, query)) = url.split_once('?') else {
        return (false, url.to_owned());
    };

    let mut parts = Vec::new();
    let mut uses_native = false;
    for part in query.split('&') {
        if part == "driver=tokio-postgres" || part.starts_with("driver=tokio-postgres&") {
            uses_native = true;
            continue;
        }
        parts.push(part);
    }

    let stripped = if parts.is_empty() {
        base.to_owned()
    } else {
        format!("{base}?{}", parts.join("&"))
    };

    (uses_native, stripped)
}

fn tokio_postgres_pool_error(e: deadpool_postgres::PoolError) -> Error {
    match e {
        deadpool_postgres::PoolError::Backend(e) => Error::from(e),
        deadpool_postgres::PoolError::Timeout(_) => Error::AcquireTimeout {
            reason: e.to_string(),
        },
        _ => Error::ConnectionFailure {
            reason: e.to_string(),
        },
    }
}