Skip to main content

prax_postgres/
engine.rs

1//! PostgreSQL query engine implementation.
2
3use std::marker::PhantomData;
4use std::sync::Arc;
5
6use prax_query::QueryResult;
7use prax_query::filter::FilterValue;
8use prax_query::traits::{BoxFuture, Model, QueryEngine};
9use tracing::{error, trace};
10
11use crate::error::checkout_error;
12use crate::notify::{validate_channel, validate_payload};
13use crate::pool::PgPool;
14use crate::types::filter_value_to_sql;
15
16/// Statement behind [`PgEngine::notify`].
17const NOTIFY_SQL: &str = "SELECT pg_notify($1, $2)";
18
19/// PostgreSQL query engine that implements the Prax `QueryEngine`
20/// trait.
21///
22/// Two modes, controlled by the `tx_conn` field:
23///
24/// - **Pool mode** (`tx_conn == None`, the default): each query
25///   acquires a fresh connection from [`PgPool`] and drops it after
26///   the call.
27/// - **Transaction mode** (`tx_conn == Some(conn)`): each query routes
28///   through the single pinned [`deadpool_postgres::Object`]. The
29///   tx-bound engine is built by [`PgEngine::transaction`], which
30///   issues a raw `BEGIN`; the outer future then runs `COMMIT` or
31///   `ROLLBACK` on the same connection based on the closure's
32///   `Ok` / `Err` result.
33///
34/// We lean on raw `BEGIN` / `COMMIT` / `ROLLBACK` strings instead of
35/// `tokio_postgres::Transaction<'_>` because `Transaction<'_>` borrows
36/// from its owning `Client`, and bundling both into a heap cell
37/// requires `mem::transmute` gymnastics to launder the lifetime to
38/// `'static`. Since `Object` implements `Deref<Target = Client>` and
39/// `Client::query` / `execute` take `&self`, an `Arc<Object>` is all
40/// we need — every engine clone can share it freely, and the last
41/// clone drops the `Arc`, which drops the `Object` back to the pool.
42/// This path is explicitly sanctioned by the task plan's "fall back"
43/// guardrail.
44#[derive(Clone)]
45pub struct PgEngine {
46    pool: PgPool,
47    /// Present when this engine is bound to an in-flight transaction.
48    /// `None` in the normal pool-backed case.
49    tx_conn: Option<Arc<deadpool_postgres::Object>>,
50}
51
52impl PgEngine {
53    /// Create a new PostgreSQL engine with the given connection pool.
54    pub fn new(pool: PgPool) -> Self {
55        Self {
56            pool,
57            tx_conn: None,
58        }
59    }
60
61    /// Get a reference to the connection pool.
62    pub fn pool(&self) -> &PgPool {
63        &self.pool
64    }
65
66    /// Send a notification on `channel` (`SELECT pg_notify($1, $2)`).
67    ///
68    /// On the transaction-bound engine that
69    /// `PraxClient::<PgEngine>::transaction` hands its closure (reach it with
70    /// `tx.engine()`), the notification is part of that transaction:
71    /// delivered when it commits, discarded if it rolls back. Otherwise it
72    /// runs on a pooled connection and is delivered at once.
73    ///
74    /// The channel name is matched verbatim (case preserved) by a
75    /// [`PgListener`](crate::listener::PgListener) subscribed to the same
76    /// string. It must be non-empty, at most 63 bytes and free of NUL, and
77    /// the payload shorter than 8000 bytes; both are checked before
78    /// anything is sent (an invalid-input error otherwise).
79    pub async fn notify(&self, channel: &str, payload: &str) -> QueryResult<()> {
80        validate_channel(channel)
81            .and_then(|()| validate_payload(payload))
82            .map_err(|e| prax_query::QueryError::invalid_input("notify", e.to_string()))?;
83        let params: [&(dyn tokio_postgres::types::ToSql + Sync); 2] = [&channel, &payload];
84        if let Some(tx) = &self.tx_conn {
85            tx.execute(NOTIFY_SQL, &params)
86                .await
87                .map_err(map_driver_err)?;
88        } else {
89            let conn = self.pool.get().await.map_err(checkout_error)?;
90            conn.execute(NOTIFY_SQL, &params)
91                .await
92                .map_err(map_driver_err)?;
93        }
94        Ok(())
95    }
96
97    /// Convert filter values to PostgreSQL parameters.
98    #[allow(clippy::result_large_err)]
99    fn to_params(
100        values: &[FilterValue],
101    ) -> Result<Vec<Box<dyn tokio_postgres::types::ToSql + Sync + Send>>, prax_query::QueryError>
102    {
103        values
104            .iter()
105            .map(|v| {
106                filter_value_to_sql(v).map_err(|e| {
107                    let msg = e.to_string();
108                    prax_query::QueryError::database(msg).with_source(e)
109                })
110            })
111            .collect()
112    }
113}
114
115/// Map a `tokio_postgres` driver error onto the [`prax_query::QueryError`]
116/// taxonomy, categorizing by SQLSTATE when the server supplied one.
117///
118/// Route a driver-layer error through the SQLSTATE categorization in
119/// [`crate::error`] (`From<PgError> for QueryError`): unique (23505) and
120/// foreign-key (23503) violations become `constraint_violation`, not-null
121/// violations (23502) become `invalid_input`, and anything else stays a
122/// generic database error. The driver error is preserved as the source.
123/// Accepts both `PgError` (pool-mode path) and `tokio_postgres::Error`
124/// (tx-mode path, converted via the `#[from]` variant).
125fn map_driver_err<E: Into<crate::error::PgError>>(e: E) -> prax_query::QueryError {
126    prax_query::QueryError::from(e.into())
127}
128
129/// Panic/cancellation guard for the transaction path.
130///
131/// Armed right after `BEGIN` and disarmed once the closure's future has
132/// resolved and the explicit `COMMIT`/`ROLLBACK` step takes over. If the
133/// guard is dropped while still armed — the closure panicked and the
134/// transaction future is unwinding, or the outer task was cancelled —
135/// the pinned connection would otherwise return to the pool with the
136/// transaction still open: dropping the last `Arc` merely recycles the
137/// `Object`, and no `PgRecycling` method rolls back an open transaction
138/// (`Clean` resets session state but runs inside it), so the next checkout
139/// would silently inherit the live transaction. The armed guard therefore
140/// retires the connection instead: when it holds the last `Arc` handle it takes the `Object`
141/// out of the pool so the session closes and the server aborts the
142/// transaction; when the caller stashed a tx-engine clone the handle
143/// cannot be reclaimed and it can only log.
144struct TxPanicGuard {
145    tx_conn: Option<Arc<deadpool_postgres::Object>>,
146}
147
148impl TxPanicGuard {
149    fn new(tx_conn: Arc<deadpool_postgres::Object>) -> Self {
150        Self {
151            tx_conn: Some(tx_conn),
152        }
153    }
154
155    /// Disarm the guard and hand the connection back for explicit
156    /// COMMIT/ROLLBACK handling. Call only after the closure's future
157    /// has resolved normally.
158    fn disarm(mut self) -> Arc<deadpool_postgres::Object> {
159        self.tx_conn
160            .take()
161            .expect("TxPanicGuard always holds a connection until disarmed")
162    }
163}
164
165impl Drop for TxPanicGuard {
166    fn drop(&mut self) {
167        let Some(tx_conn) = self.tx_conn.take() else {
168            // Disarmed: the transaction was settled explicitly.
169            return;
170        };
171        match Arc::try_unwrap(tx_conn) {
172            Ok(conn) => {
173                // Last handle: dropping the bare `Client` closes the
174                // session (the server then aborts the open tx) and
175                // shrinks the pool by one instead of recycling a
176                // connection with a live transaction.
177                error!(
178                    "transaction closure panicked (or was cancelled) with BEGIN still \
179                     open; retiring the pinned connection from the pool so the open \
180                     transaction aborts with the session"
181                );
182                let _client = deadpool_postgres::Object::take(conn);
183            }
184            Err(_) => {
185                error!(
186                    "transaction closure panicked (or was cancelled) with BEGIN still \
187                     open, and a cloned tx engine may still reference the pinned \
188                     connection; it cannot be retired, so the open transaction may \
189                     leak back into the pool"
190                );
191            }
192        }
193    }
194}
195
196impl QueryEngine for PgEngine {
197    fn dialect(&self) -> &dyn prax_query::dialect::SqlDialect {
198        &prax_query::dialect::Postgres
199    }
200
201    fn query_many<T: Model + prax_query::row::FromRow + Send + 'static>(
202        &self,
203        sql: &str,
204        params: Vec<FilterValue>,
205    ) -> BoxFuture<'_, QueryResult<Vec<T>>> {
206        let sql = sql.to_string();
207        Box::pin(async move {
208            trace!(sql = %sql, "Executing query_many");
209
210            let pg_params = Self::to_params(&params)?;
211            let param_refs: Vec<&(dyn tokio_postgres::types::ToSql + Sync)> =
212                pg_params.iter().map(|p| p.as_ref() as _).collect();
213
214            let rows = if let Some(tx) = &self.tx_conn {
215                // Tx mode: drive the pinned connection directly so the
216                // query lands inside the same BEGIN…COMMIT block as
217                // every sibling call.
218                tx.query(&sql, &param_refs).await.map_err(map_driver_err)?
219            } else {
220                let conn = self.pool.get().await.map_err(checkout_error)?;
221                conn.query(&sql, &param_refs)
222                    .await
223                    .map_err(map_driver_err)?
224            };
225
226            crate::deserialize::rows_into::<T>(rows)
227        })
228    }
229
230    fn query_one<T: Model + prax_query::row::FromRow + Send + 'static>(
231        &self,
232        sql: &str,
233        params: Vec<FilterValue>,
234    ) -> BoxFuture<'_, QueryResult<T>> {
235        let sql = sql.to_string();
236        Box::pin(async move {
237            trace!(sql = %sql, "Executing query_one");
238
239            let pg_params = Self::to_params(&params)?;
240            let param_refs: Vec<&(dyn tokio_postgres::types::ToSql + Sync)> =
241                pg_params.iter().map(|p| p.as_ref() as _).collect();
242
243            // Use `query_opt` and detect the zero-row case structurally:
244            // tokio-postgres reports `query_one`'s zero-row outcome as a
245            // `Kind::RowCount` error ("query returned an unexpected number
246            // of rows"), which error-text matching cannot reliably
247            // distinguish from a genuine driver failure.
248            let row = if let Some(tx) = &self.tx_conn {
249                tx.query_opt(&sql, &param_refs)
250                    .await
251                    .map_err(map_driver_err)?
252            } else {
253                let conn = self.pool.get().await.map_err(checkout_error)?;
254                conn.query_opt(&sql, &param_refs)
255                    .await
256                    .map_err(map_driver_err)?
257            };
258
259            let row = row.ok_or_else(|| prax_query::QueryError::not_found(T::MODEL_NAME))?;
260            crate::deserialize::row_into::<T>(row)
261        })
262    }
263
264    fn query_optional<T: Model + prax_query::row::FromRow + Send + 'static>(
265        &self,
266        sql: &str,
267        params: Vec<FilterValue>,
268    ) -> BoxFuture<'_, QueryResult<Option<T>>> {
269        let sql = sql.to_string();
270        Box::pin(async move {
271            trace!(sql = %sql, "Executing query_optional");
272
273            let pg_params = Self::to_params(&params)?;
274            let param_refs: Vec<&(dyn tokio_postgres::types::ToSql + Sync)> =
275                pg_params.iter().map(|p| p.as_ref() as _).collect();
276
277            let row = if let Some(tx) = &self.tx_conn {
278                tx.query_opt(&sql, &param_refs)
279                    .await
280                    .map_err(map_driver_err)?
281            } else {
282                let conn = self.pool.get().await.map_err(checkout_error)?;
283                conn.query_opt(&sql, &param_refs)
284                    .await
285                    .map_err(map_driver_err)?
286            };
287
288            row.map(crate::deserialize::row_into::<T>).transpose()
289        })
290    }
291
292    fn execute_insert<T: Model + prax_query::row::FromRow + Send + 'static>(
293        &self,
294        sql: &str,
295        params: Vec<FilterValue>,
296    ) -> BoxFuture<'_, QueryResult<T>> {
297        let sql = sql.to_string();
298        Box::pin(async move {
299            trace!(sql = %sql, "Executing insert");
300
301            let pg_params = Self::to_params(&params)?;
302            let param_refs: Vec<&(dyn tokio_postgres::types::ToSql + Sync)> =
303                pg_params.iter().map(|p| p.as_ref() as _).collect();
304
305            let row = if let Some(tx) = &self.tx_conn {
306                tx.query_one(&sql, &param_refs)
307                    .await
308                    .map_err(map_driver_err)?
309            } else {
310                let conn = self.pool.get().await.map_err(checkout_error)?;
311                conn.query_one(&sql, &param_refs)
312                    .await
313                    .map_err(map_driver_err)?
314            };
315
316            crate::deserialize::row_into::<T>(row)
317        })
318    }
319
320    fn execute_update<T: Model + prax_query::row::FromRow + Send + 'static>(
321        &self,
322        sql: &str,
323        params: Vec<FilterValue>,
324    ) -> BoxFuture<'_, QueryResult<Vec<T>>> {
325        let sql = sql.to_string();
326        Box::pin(async move {
327            trace!(sql = %sql, "Executing update");
328
329            let pg_params = Self::to_params(&params)?;
330            let param_refs: Vec<&(dyn tokio_postgres::types::ToSql + Sync)> =
331                pg_params.iter().map(|p| p.as_ref() as _).collect();
332
333            let rows = if let Some(tx) = &self.tx_conn {
334                tx.query(&sql, &param_refs).await.map_err(map_driver_err)?
335            } else {
336                let conn = self.pool.get().await.map_err(checkout_error)?;
337                conn.query(&sql, &param_refs)
338                    .await
339                    .map_err(map_driver_err)?
340            };
341
342            crate::deserialize::rows_into::<T>(rows)
343        })
344    }
345
346    fn execute_delete(
347        &self,
348        sql: &str,
349        params: Vec<FilterValue>,
350    ) -> BoxFuture<'_, QueryResult<u64>> {
351        let sql = sql.to_string();
352        Box::pin(async move {
353            trace!(sql = %sql, "Executing delete");
354
355            let pg_params = Self::to_params(&params)?;
356            let param_refs: Vec<&(dyn tokio_postgres::types::ToSql + Sync)> =
357                pg_params.iter().map(|p| p.as_ref() as _).collect();
358
359            if let Some(tx) = &self.tx_conn {
360                tx.execute(&sql, &param_refs).await.map_err(map_driver_err)
361            } else {
362                let conn = self.pool.get().await.map_err(checkout_error)?;
363                conn.execute(&sql, &param_refs)
364                    .await
365                    .map_err(map_driver_err)
366            }
367        })
368    }
369
370    fn execute_raw(&self, sql: &str, params: Vec<FilterValue>) -> BoxFuture<'_, QueryResult<u64>> {
371        let sql = sql.to_string();
372        Box::pin(async move {
373            trace!(sql = %sql, "Executing raw SQL");
374
375            let pg_params = Self::to_params(&params)?;
376            let param_refs: Vec<&(dyn tokio_postgres::types::ToSql + Sync)> =
377                pg_params.iter().map(|p| p.as_ref() as _).collect();
378
379            if let Some(tx) = &self.tx_conn {
380                tx.execute(&sql, &param_refs).await.map_err(map_driver_err)
381            } else {
382                let conn = self.pool.get().await.map_err(checkout_error)?;
383                conn.execute(&sql, &param_refs)
384                    .await
385                    .map_err(map_driver_err)
386            }
387        })
388    }
389
390    fn count(&self, sql: &str, params: Vec<FilterValue>) -> BoxFuture<'_, QueryResult<u64>> {
391        let sql = sql.to_string();
392        Box::pin(async move {
393            trace!(sql = %sql, "Executing count");
394
395            let pg_params = Self::to_params(&params)?;
396            let param_refs: Vec<&(dyn tokio_postgres::types::ToSql + Sync)> =
397                pg_params.iter().map(|p| p.as_ref() as _).collect();
398
399            let row = if let Some(tx) = &self.tx_conn {
400                tx.query_one(&sql, &param_refs)
401                    .await
402                    .map_err(map_driver_err)?
403            } else {
404                let conn = self.pool.get().await.map_err(checkout_error)?;
405                conn.query_one(&sql, &param_refs)
406                    .await
407                    .map_err(map_driver_err)?
408            };
409
410            let count: i64 = row.try_get::<_, i64>(0).map_err(map_driver_err)?;
411            Ok(count as u64)
412        })
413    }
414
415    fn aggregate_query(
416        &self,
417        sql: &str,
418        params: Vec<FilterValue>,
419    ) -> BoxFuture<'_, QueryResult<Vec<std::collections::HashMap<String, FilterValue>>>> {
420        let sql = sql.to_string();
421        Box::pin(async move {
422            trace!(sql = %sql, "Executing aggregate_query");
423
424            let pg_params = Self::to_params(&params)?;
425            let param_refs: Vec<&(dyn tokio_postgres::types::ToSql + Sync)> =
426                pg_params.iter().map(|p| p.as_ref() as _).collect();
427
428            let rows = if let Some(tx) = &self.tx_conn {
429                tx.query(&sql, &param_refs).await.map_err(map_driver_err)?
430            } else {
431                let conn = self.pool.get().await.map_err(checkout_error)?;
432                conn.query(&sql, &param_refs)
433                    .await
434                    .map_err(map_driver_err)?
435            };
436
437            Ok(rows
438                .into_iter()
439                .map(|row| {
440                    let mut map = std::collections::HashMap::new();
441                    for (i, col) in row.columns().iter().enumerate() {
442                        let name = col.name().to_string();
443                        let value = decode_aggregate_cell(&row, i, col.type_());
444                        map.insert(name, value);
445                    }
446                    map
447                })
448                .collect())
449        })
450    }
451
452    fn transaction<'a, R, Fut, F>(&'a self, f: F) -> BoxFuture<'a, QueryResult<R>>
453    where
454        F: FnOnce(Self) -> Fut + Send + 'a,
455        Fut: std::future::Future<Output = QueryResult<R>> + Send + 'a,
456        R: Send + 'a,
457        Self: Clone,
458    {
459        Box::pin(async move {
460            // Refuse nested transactions until dialect-aware SAVEPOINT
461            // support lands. Users can still run SAVEPOINT / RELEASE
462            // manually via `execute_raw` if they need it.
463            if self.tx_conn.is_some() {
464                return Err(prax_query::QueryError::internal(
465                    "nested transactions not yet implemented \
466                     (call .transaction() on the outer engine only, or \
467                     issue SAVEPOINT via execute_raw)",
468                ));
469            }
470
471            // Acquire a dedicated raw `deadpool_postgres::Object`.
472            // Going through `PgPool::inner()` keeps the connection
473            // pinned to this future — every query the closure emits
474            // will run on the same physical connection.
475            let conn = self.pool.inner().get().await.map_err(checkout_error)?;
476
477            // Issue `BEGIN` directly as a batch_execute on the raw
478            // connection. Using `tokio_postgres::Transaction<'_>`
479            // would bundle a borrow back into `conn`; instead we rely
480            // on the connection's session state (postgres tracks the
481            // BEGIN/COMMIT/ROLLBACK on the connection itself, so every
482            // subsequent query on the same `Object` sees the same
483            // transaction). This is the approach sanctioned by the
484            // task plan's fallback guardrail.
485            conn.batch_execute("BEGIN").await.map_err(map_driver_err)?;
486
487            let tx_conn = Arc::new(conn);
488            let tx_engine = PgEngine {
489                pool: self.pool.clone(),
490                tx_conn: Some(tx_conn.clone()),
491            };
492
493            // Arm the panic guard while the closure runs: if the
494            // closure's future panics (or this future is cancelled at
495            // the await) the `BEGIN` is still open, and the guard
496            // retires the pinned connection instead of letting it
497            // recycle into the pool with a live transaction.
498            let guard = TxPanicGuard::new(tx_conn);
499
500            // Run the caller's closure on the tx-bound engine clone.
501            // When the future resolves the closure's engine clone has
502            // dropped, so the guard's `Arc` is the only remaining handle
503            // (unless the caller stashed a clone of the tx engine).
504            let result = f(tx_engine).await;
505
506            // The closure returned normally: take the connection back
507            // from the guard and settle the transaction explicitly.
508            let tx_conn = guard.disarm();
509
510            // Finalise: COMMIT on success, best-effort ROLLBACK on
511            // failure. Preserve the caller's error if rollback fails —
512            // but note the pinned `Object` does *not* close on drop:
513            // dropping the last `Arc` merely returns it to the pool, and
514            // no `PgRecycling` method rolls back an open transaction
515            // (`Clean` resets session state but runs inside it). A
516            // failed ROLLBACK on a still-live connection would
517            // therefore leak a still-open transaction back into the
518            // pool, contaminating whatever checks it out next. To
519            // avoid that, take the connection out of the pool
520            // permanently when rollback fails — possible only when this
521            // is the last `Arc` handle (if the caller stashed a clone of
522            // the tx engine somewhere, the connection recycles as
523            // before, which is the best we can do).
524            match result {
525                Ok(v) => {
526                    tx_conn
527                        .batch_execute("COMMIT")
528                        .await
529                        .map_err(map_driver_err)?;
530                    Ok(v)
531                }
532                Err(e) => {
533                    if tx_conn.batch_execute("ROLLBACK").await.is_err()
534                        && let Ok(conn) = Arc::try_unwrap(tx_conn)
535                    {
536                        // Dropping the bare `Client` closes the session
537                        // (server then aborts the tx) and shrinks the
538                        // pool by one instead of recycling a dirty conn.
539                        let _client = deadpool_postgres::Object::take(conn);
540                    }
541                    Err(e)
542                }
543            }
544        })
545    }
546}
547
548/// A typed query builder that uses the PostgreSQL engine.
549pub struct PgQueryBuilder<T: Model> {
550    engine: PgEngine,
551    _marker: PhantomData<T>,
552}
553
554impl<T: Model> PgQueryBuilder<T> {
555    /// Create a new query builder.
556    pub fn new(engine: PgEngine) -> Self {
557        Self {
558            engine,
559            _marker: PhantomData,
560        }
561    }
562
563    /// Get the underlying engine.
564    pub fn engine(&self) -> &PgEngine {
565        &self.engine
566    }
567}
568
569/// Decode a single aggregate result cell by its Postgres column type.
570///
571/// Aggregate result sets don't have a fixed schema — SUM over an
572/// INT4 column comes back as BIGINT, AVG returns NUMERIC, MIN/MAX
573/// preserves the source column's type, and COUNT is always BIGINT.
574/// Rather than route these through the `FromRow` machinery (which
575/// needs a model whose columns are known at compile time), we
576/// type-dispatch at runtime on `Column::type_()` and project into a
577/// [`FilterValue`].
578///
579/// NULL maps to `FilterValue::Null`. NUMERIC (what AVG returns) is
580/// decoded through `rust_decimal::Decimal` — tokio-postgres has no
581/// `FromSql for String` impl for NUMERIC, so the `db-tokio-postgres`
582/// feature of `rust_decimal` supplies the decoder — and then rendered
583/// to its text form as `FilterValue::String`; the aggregate result
584/// folder's numeric parser reads that text back into a float for the
585/// sum/avg accessors.
586///
587/// Unknown types fall through to `try_get::<String>` so a novel
588/// column type doesn't silently drop. Decoding failures record
589/// `FilterValue::Null` rather than aborting the whole query.
590fn decode_aggregate_cell(
591    row: &tokio_postgres::Row,
592    idx: usize,
593    ty: &tokio_postgres::types::Type,
594) -> FilterValue {
595    use tokio_postgres::types::Type;
596    match *ty {
597        Type::BOOL => row
598            .try_get::<_, Option<bool>>(idx)
599            .ok()
600            .flatten()
601            .map(FilterValue::Bool)
602            .unwrap_or(FilterValue::Null),
603        Type::INT2 => row
604            .try_get::<_, Option<i16>>(idx)
605            .ok()
606            .flatten()
607            .map(|n| FilterValue::Int(n as i64))
608            .unwrap_or(FilterValue::Null),
609        Type::INT4 => row
610            .try_get::<_, Option<i32>>(idx)
611            .ok()
612            .flatten()
613            .map(|n| FilterValue::Int(n as i64))
614            .unwrap_or(FilterValue::Null),
615        Type::INT8 => row
616            .try_get::<_, Option<i64>>(idx)
617            .ok()
618            .flatten()
619            .map(FilterValue::Int)
620            .unwrap_or(FilterValue::Null),
621        Type::FLOAT4 => row
622            .try_get::<_, Option<f32>>(idx)
623            .ok()
624            .flatten()
625            .map(|f| FilterValue::Float(f as f64))
626            .unwrap_or(FilterValue::Null),
627        Type::FLOAT8 => row
628            .try_get::<_, Option<f64>>(idx)
629            .ok()
630            .flatten()
631            .map(FilterValue::Float)
632            .unwrap_or(FilterValue::Null),
633        // NUMERIC has no `FromSql for String` impl in tokio-postgres, so it
634        // must be decoded through `rust_decimal::Decimal` (enabled via the
635        // crate's `db-tokio-postgres` feature) and then rendered to its text
636        // form. The aggregate result folder parses this back into an f64 for
637        // the sum/avg accessors. This is the type AVG() returns, so getting it
638        // wrong silently drops every average.
639        Type::NUMERIC => row
640            .try_get::<_, Option<rust_decimal::Decimal>>(idx)
641            .ok()
642            .flatten()
643            .map(|d| FilterValue::String(d.to_string()))
644            .unwrap_or(FilterValue::Null),
645        Type::TEXT | Type::VARCHAR | Type::CHAR | Type::NAME | Type::BPCHAR => row
646            .try_get::<_, Option<String>>(idx)
647            .ok()
648            .flatten()
649            .map(FilterValue::String)
650            .unwrap_or(FilterValue::Null),
651        Type::JSON | Type::JSONB => row
652            .try_get::<_, Option<serde_json::Value>>(idx)
653            .ok()
654            .flatten()
655            .map(FilterValue::Json)
656            .unwrap_or(FilterValue::Null),
657        _ => row
658            .try_get::<_, Option<String>>(idx)
659            .ok()
660            .flatten()
661            .map(FilterValue::String)
662            .unwrap_or(FilterValue::Null),
663    }
664}
665
666#[cfg(test)]
667mod tests {
668    // Integration tests would require a real PostgreSQL database.
669    // `TxPanicGuard`'s armed-drop path manipulates real pool objects
670    // (`deadpool_postgres::Object` cannot be fabricated without a live
671    // connection), so it is covered only by live integration testing,
672    // not unit tests.
673
674    use super::*;
675
676    #[tokio::test]
677    async fn notify_validates_before_connecting() {
678        // deadpool connects lazily, and nothing listens on port 1: only
679        // validation can answer these.
680        let pool = crate::pool::PgPoolBuilder::new()
681            .url("postgres://prax@127.0.0.1:1/prax")
682            .min_connections(0)
683            .build()
684            .await
685            .unwrap();
686        let engine = PgEngine::new(pool);
687        let too_long = "a".repeat(64);
688        let oversized = "x".repeat(8000);
689        for (channel, payload) in [
690            ("", "x"),
691            (too_long.as_str(), "x"),
692            ("a\0b", "x"),
693            ("ok", oversized.as_str()),
694        ] {
695            let err = engine.notify(channel, payload).await.unwrap_err();
696            assert_eq!(
697                err.code,
698                prax_query::ErrorCode::InvalidParameter,
699                "{channel:?}: {err}"
700            );
701        }
702    }
703}