Skip to main content

prax_postgres/
row_ref.rs

1//! Bridge between `tokio_postgres::Row` and `prax_query::row::RowRef`.
2//!
3//! `RowRef` is defined in `prax-query` and `Row` is defined in `tokio-postgres`;
4//! both are foreign to this crate, so Rust's orphan rules forbid a direct
5//! `impl RowRef for Row`. We wrap the row in a `#[repr(transparent)]` newtype
6//! (`PgRow`) and implement the trait on the wrapper.
7//!
8//! ## Dual API surface
9//!
10//! `PgRow` derefs to the wrapped `Row`, so callers can use either API:
11//! * The generic `RowRef` interface (`pg_row.get_i32("id")`) — portable across
12//!   drivers and what generated `FromRow` impls use.
13//! * The native `tokio_postgres::Row` interface (`pg_row.try_get::<_, i32>("id")`)
14//!   — full access to the driver's type system for columns `RowRef` does not
15//!   model (arrays, range types, etc.).
16//!
17//! ## `rust_decimal` support
18//!
19//! `tokio-postgres` 0.7 ships no `with-rust_decimal-*` feature gate of its
20//! own; instead the `rust_decimal` crate's `db-tokio-postgres` feature
21//! (enabled in this crate's `Cargo.toml`) provides the `FromSql`/`ToSql`
22//! impls bridging NUMERIC and `rust_decimal::Decimal`. `PgRow::get_decimal`
23//! and `PgRow::get_decimal_opt` therefore decode NUMERIC columns directly
24//! through the driver, the same way `decode_aggregate_cell` reads AVG()
25//! results.
26
27use std::error::Error as StdError;
28
29use prax_query::row::{RowError, RowRef, into_row_error};
30use tokio_postgres::Row;
31use tokio_postgres::types::{FromSql, Kind, Type};
32
33/// `FromSql` shim that accepts any column type and decodes its raw
34/// bytes as UTF-8.
35///
36/// Used to read postgres `ENUM` columns into a Rust `String`, since
37/// `&str: FromSql` only `accepts` TEXT/VARCHAR/BPCHAR/NAME/UNKNOWN
38/// (plus a few citext-shaped names). User-defined enums encode as
39/// raw UTF-8 on the wire — the same shape `text_from_sql` would
40/// produce — so this just runs the bytes through `str::from_utf8`.
41struct AnyText(String);
42
43impl<'a> FromSql<'a> for AnyText {
44    fn from_sql(_ty: &Type, raw: &'a [u8]) -> Result<Self, Box<dyn StdError + Sync + Send>> {
45        Ok(AnyText(std::str::from_utf8(raw)?.to_owned()))
46    }
47    fn accepts(_ty: &Type) -> bool {
48        true
49    }
50}
51
52/// `FromSql` shim decoding TIMESTAMPTZ *and* TIMESTAMP into
53/// `DateTime<Utc>`.
54///
55/// `chrono::DateTime<Utc>: FromSql` only accepts TIMESTAMPTZ, but schemas
56/// (Prisma's `DateTime` maps to `timestamp(3)`) often store UTC wall time
57/// in `timestamp without time zone` columns that generated models declare
58/// as `DateTime<Utc>`. A TIMESTAMP value is read as UTC, matching how
59/// `PgString` binds a `DateTime<Utc>` to a TIMESTAMP parameter.
60struct UtcDateTime(chrono::DateTime<chrono::Utc>);
61
62impl<'a> FromSql<'a> for UtcDateTime {
63    fn from_sql(ty: &Type, raw: &'a [u8]) -> Result<Self, Box<dyn StdError + Sync + Send>> {
64        if *ty == Type::TIMESTAMP {
65            let naive = chrono::NaiveDateTime::from_sql(ty, raw)?;
66            return Ok(UtcDateTime(naive.and_utc()));
67        }
68        Ok(UtcDateTime(chrono::DateTime::<chrono::Utc>::from_sql(
69            ty, raw,
70        )?))
71    }
72    fn accepts(ty: &Type) -> bool {
73        *ty == Type::TIMESTAMP || <chrono::DateTime<chrono::Utc> as FromSql>::accepts(ty)
74    }
75}
76
77/// `FromSql` shim used exclusively for null-probe logic.
78///
79/// `NullProbe` accepts every Postgres wire type and discards the bytes
80/// entirely — we only care whether the column is NULL, not what the
81/// value is. This avoids the UTF-8 conversion failure that `AnyText`
82/// would incur on binary-encoded types (UUID, INTEGER, BYTEA, etc.)
83/// when probing a non-null column.
84///
85/// `Option<NullProbe>` deserialises to `None` on NULL and `Some(NullProbe)`
86/// on any non-null value regardless of the column's OID, making it the
87/// correct type for `RowRef::is_null` overrides on drivers where the
88/// default `get_str_opt` fallback would reject non-text columns.
89struct NullProbe;
90
91impl<'a> FromSql<'a> for NullProbe {
92    fn from_sql(_ty: &Type, _raw: &'a [u8]) -> Result<Self, Box<dyn StdError + Sync + Send>> {
93        Ok(NullProbe)
94    }
95    fn accepts(_ty: &Type) -> bool {
96        true
97    }
98}
99
100/// Newtype wrapper around `tokio_postgres::Row` that implements
101/// `prax_query::row::RowRef`.
102///
103/// The inner row is private; use [`PgRow::into_inner`] when ownership is
104/// needed (e.g., forwarding to a tokio-postgres API that consumes `Row`).
105/// For read-only access, the `Deref<Target = Row>` impl lets you call
106/// any `Row` method directly.
107#[repr(transparent)]
108pub struct PgRow(Row);
109
110impl PgRow {
111    /// Move the wrapped `tokio_postgres::Row` out of this wrapper.
112    pub fn into_inner(self) -> Row {
113        self.0
114    }
115}
116
117impl std::ops::Deref for PgRow {
118    type Target = Row;
119    fn deref(&self) -> &Self::Target {
120        &self.0
121    }
122}
123
124impl From<Row> for PgRow {
125    fn from(row: Row) -> Self {
126        PgRow(row)
127    }
128}
129
130impl RowRef for PgRow {
131    fn get_i32(&self, c: &str) -> Result<i32, RowError> {
132        into_row_error(c, self.try_get::<_, i32>(c))
133    }
134    fn get_i32_opt(&self, c: &str) -> Result<Option<i32>, RowError> {
135        into_row_error(c, self.try_get::<_, Option<i32>>(c))
136    }
137    fn get_i64(&self, c: &str) -> Result<i64, RowError> {
138        into_row_error(c, self.try_get::<_, i64>(c))
139    }
140    fn get_i64_opt(&self, c: &str) -> Result<Option<i64>, RowError> {
141        into_row_error(c, self.try_get::<_, Option<i64>>(c))
142    }
143    fn get_f64(&self, c: &str) -> Result<f64, RowError> {
144        into_row_error(c, self.try_get::<_, f64>(c))
145    }
146    fn get_f64_opt(&self, c: &str) -> Result<Option<f64>, RowError> {
147        into_row_error(c, self.try_get::<_, Option<f64>>(c))
148    }
149    fn get_bool(&self, c: &str) -> Result<bool, RowError> {
150        into_row_error(c, self.try_get::<_, bool>(c))
151    }
152    fn get_bool_opt(&self, c: &str) -> Result<Option<bool>, RowError> {
153        into_row_error(c, self.try_get::<_, Option<bool>>(c))
154    }
155    fn get_str(&self, c: &str) -> Result<&str, RowError> {
156        into_row_error(c, self.try_get::<_, &str>(c))
157    }
158    fn get_str_opt(&self, c: &str) -> Result<Option<&str>, RowError> {
159        into_row_error(c, self.try_get::<_, Option<&str>>(c))
160    }
161    /// Override the trait default (which is `get_str + to_string`) so
162    /// we can decode columns whose Postgres-side type is *not* TEXT but
163    /// whose Rust-side codegen has emitted `pub field: String`:
164    ///
165    /// * `UUID` columns — emitted as `String` for Prisma `String @db.Uuid`
166    ///   fields. We decode via `uuid::Uuid::from_sql` and stringify.
167    /// * User-defined `ENUM` columns — also emitted as `String` via
168    ///   `FromColumn`'s `get_string` call (see codegen for `enum`
169    ///   variants). We decode via `AnyText` since `&str: FromSql` does
170    ///   not accept enum types.
171    ///
172    /// Without this override, the row decode fails with `"error
173    /// deserializing column N"` and the whole query bubbles up a
174    /// `[P6003] type conversion error`.
175    ///
176    /// A matching override on `get_string_opt` covers nullable variants.
177    fn get_string(&self, c: &str) -> Result<String, RowError> {
178        let columns = self.0.columns();
179        if let Some(col) = columns.iter().find(|col| col.name() == c) {
180            let ty = col.type_();
181            if *ty == Type::UUID {
182                return into_row_error(c, self.try_get::<_, ::uuid::Uuid>(c))
183                    .map(|u| u.to_string());
184            }
185            if matches!(ty.kind(), Kind::Enum(_)) {
186                return into_row_error(c, self.try_get::<_, AnyText>(c)).map(|t| t.0);
187            }
188        }
189        into_row_error(c, self.try_get::<_, &str>(c)).map(|s| s.to_string())
190    }
191    fn get_string_opt(&self, c: &str) -> Result<Option<String>, RowError> {
192        let columns = self.0.columns();
193        if let Some(col) = columns.iter().find(|col| col.name() == c) {
194            let ty = col.type_();
195            if *ty == Type::UUID {
196                return into_row_error(c, self.try_get::<_, Option<::uuid::Uuid>>(c))
197                    .map(|opt| opt.map(|u| u.to_string()));
198            }
199            if matches!(ty.kind(), Kind::Enum(_)) {
200                return into_row_error(c, self.try_get::<_, Option<AnyText>>(c))
201                    .map(|opt| opt.map(|t| t.0));
202            }
203        }
204        into_row_error(c, self.try_get::<_, Option<&str>>(c)).map(|opt| opt.map(|s| s.to_string()))
205    }
206    /// Override the trait default (which falls back to `get_str_opt`, and
207    /// therefore fails for non-TEXT column types like INTEGER, UUID, etc.)
208    /// with a type-agnostic null probe.
209    ///
210    /// `NullProbe: FromSql` accepts every Postgres wire type and discards
211    /// the payload entirely, so `Option<NullProbe>` deserialises to `None`
212    /// on NULL and `Some(NullProbe)` on any non-null value — regardless of
213    /// the column's OID — without attempting any byte interpretation. This
214    /// is exactly what the blanket `impl<T: FromColumn> FromColumn for
215    /// Option<T>` needs to short-circuit nullable columns of any type.
216    fn is_null(&self, c: &str) -> Result<bool, RowError> {
217        into_row_error(c, self.try_get::<_, Option<NullProbe>>(c)).map(|opt| opt.is_none())
218    }
219
220    fn get_bytes(&self, c: &str) -> Result<&[u8], RowError> {
221        into_row_error(c, self.try_get::<_, &[u8]>(c))
222    }
223    fn get_bytes_opt(&self, c: &str) -> Result<Option<&[u8]>, RowError> {
224        into_row_error(c, self.try_get::<_, Option<&[u8]>>(c))
225    }
226    fn get_datetime_utc(&self, c: &str) -> Result<chrono::DateTime<chrono::Utc>, RowError> {
227        into_row_error(c, self.try_get::<_, UtcDateTime>(c).map(|v| v.0))
228    }
229    fn get_datetime_utc_opt(
230        &self,
231        c: &str,
232    ) -> Result<Option<chrono::DateTime<chrono::Utc>>, RowError> {
233        into_row_error(
234            c,
235            self.try_get::<_, Option<UtcDateTime>>(c)
236                .map(|v| v.map(|v| v.0)),
237        )
238    }
239    fn get_naive_datetime(&self, c: &str) -> Result<chrono::NaiveDateTime, RowError> {
240        into_row_error(c, self.try_get::<_, chrono::NaiveDateTime>(c))
241    }
242    fn get_naive_datetime_opt(&self, c: &str) -> Result<Option<chrono::NaiveDateTime>, RowError> {
243        into_row_error(c, self.try_get::<_, Option<chrono::NaiveDateTime>>(c))
244    }
245    fn get_naive_date(&self, c: &str) -> Result<chrono::NaiveDate, RowError> {
246        into_row_error(c, self.try_get::<_, chrono::NaiveDate>(c))
247    }
248    fn get_naive_date_opt(&self, c: &str) -> Result<Option<chrono::NaiveDate>, RowError> {
249        into_row_error(c, self.try_get::<_, Option<chrono::NaiveDate>>(c))
250    }
251    fn get_naive_time(&self, c: &str) -> Result<chrono::NaiveTime, RowError> {
252        into_row_error(c, self.try_get::<_, chrono::NaiveTime>(c))
253    }
254    fn get_naive_time_opt(&self, c: &str) -> Result<Option<chrono::NaiveTime>, RowError> {
255        into_row_error(c, self.try_get::<_, Option<chrono::NaiveTime>>(c))
256    }
257    fn get_uuid(&self, c: &str) -> Result<uuid::Uuid, RowError> {
258        into_row_error(c, self.try_get::<_, uuid::Uuid>(c))
259    }
260    fn get_uuid_opt(&self, c: &str) -> Result<Option<uuid::Uuid>, RowError> {
261        into_row_error(c, self.try_get::<_, Option<uuid::Uuid>>(c))
262    }
263    fn get_json(&self, c: &str) -> Result<serde_json::Value, RowError> {
264        into_row_error(c, self.try_get::<_, serde_json::Value>(c))
265    }
266    fn get_json_opt(&self, c: &str) -> Result<Option<serde_json::Value>, RowError> {
267        into_row_error(c, self.try_get::<_, Option<serde_json::Value>>(c))
268    }
269    fn get_decimal(&self, c: &str) -> Result<rust_decimal::Decimal, RowError> {
270        into_row_error(c, self.try_get::<_, rust_decimal::Decimal>(c))
271    }
272    fn get_decimal_opt(&self, c: &str) -> Result<Option<rust_decimal::Decimal>, RowError> {
273        into_row_error(c, self.try_get::<_, Option<rust_decimal::Decimal>>(c))
274    }
275    /// `TEXT[]` / `VARCHAR[]` / `CHAR[]` / `NAME[]` columns. A NULL element
276    /// inside the array is a decode error: `Vec<String>` has no slot for it.
277    fn get_string_array(&self, c: &str) -> Result<Vec<String>, RowError> {
278        into_row_error(c, self.try_get::<_, Vec<String>>(c))
279    }
280}
281
282#[cfg(test)]
283mod tests {
284    use super::*;
285    use tokio_postgres::types::ToSql;
286
287    fn encode(value: &(dyn ToSql + Sync), ty: &Type) -> bytes::BytesMut {
288        let mut buf = bytes::BytesMut::new();
289        value.to_sql_checked(ty, &mut buf).unwrap();
290        buf
291    }
292
293    #[test]
294    fn utc_datetime_reads_timestamp_as_utc() {
295        let naive = chrono::NaiveDate::from_ymd_opt(2024, 1, 2)
296            .unwrap()
297            .and_hms_micro_opt(3, 4, 5, 123_456)
298            .unwrap();
299        let buf = encode(&naive, &Type::TIMESTAMP);
300        let decoded = UtcDateTime::from_sql(&Type::TIMESTAMP, &buf).unwrap();
301        assert_eq!(decoded.0, naive.and_utc());
302    }
303
304    #[test]
305    fn utc_datetime_reads_timestamptz_unchanged() {
306        let at = chrono::DateTime::parse_from_rfc3339("2024-01-02T03:04:05+02:00")
307            .unwrap()
308            .with_timezone(&chrono::Utc);
309        let buf = encode(&at, &Type::TIMESTAMPTZ);
310        let decoded = UtcDateTime::from_sql(&Type::TIMESTAMPTZ, &buf).unwrap();
311        assert_eq!(decoded.0, at);
312    }
313
314    #[test]
315    fn utc_datetime_accepts_only_timestamp_types() {
316        assert!(<UtcDateTime as FromSql>::accepts(&Type::TIMESTAMP));
317        assert!(<UtcDateTime as FromSql>::accepts(&Type::TIMESTAMPTZ));
318        assert!(!<UtcDateTime as FromSql>::accepts(&Type::DATE));
319        assert!(!<UtcDateTime as FromSql>::accepts(&Type::TEXT));
320    }
321}