Skip to main content

sqlx_json/
postgres.rs

1//! [`RowExt`](crate::RowExt) implementation for `PostgreSQL` rows.
2//!
3//! Maps each column's type name to a [`Cell`]; JSON shapes are owned by
4//! [`encode`](crate::cell::encode). Type names are normalized to uppercase
5//! because sqlx may return either case depending on the query context.
6//! Integer types use size-specific Rust types (`i16`, `i32`, `i64`) because
7//! sqlx enforces strict type matching for `PostgreSQL`. `TIMESTAMPTZ`
8//! decodes to `Cell::DateTimeUtc`. `MONEY` arrives as text (sqlx uses
9//! simple-query for parameterless statements) and is parsed locale-aware
10//! into `Cell::Decimal`, like `NUMERIC`.
11
12use std::str::FromStr;
13
14use bigdecimal::BigDecimal;
15use sqlx::postgres::PgRow;
16
17use crate::prelude::*;
18
19/// Parses a locale-formatted Postgres `MONEY` text value into a `BigDecimal`.
20///
21/// Strips currency symbol and grouping separators (everything except digits,
22/// `.`, and `-`), then parses what remains. Tuned for the en_US.UTF-8
23/// `lc_monetary` default — locales using `,` as decimal separator are not
24/// supported.
25fn parse_pg_money_text(text: &str) -> Option<BigDecimal> {
26    let cleaned: String = text.chars().filter(|c| matches!(c, '0'..='9' | '.' | '-')).collect();
27    BigDecimal::from_str(&cleaned).ok()
28}
29
30impl RowExt for PgRow {
31    fn to_json(&self) -> Value {
32        row_to_json(self)
33    }
34}
35
36impl DecodeCell for PgRow {
37    fn decode_cell(&self, idx: usize, type_name: &str) -> Cell {
38        match type_name.to_ascii_uppercase().as_str() {
39            "BOOL" => self.try_get(idx).map_or(Cell::Null, Cell::Bool),
40
41            "INT8" => self.try_get(idx).map_or(Cell::Null, Cell::Int),
42
43            "INT4" | "OID" => self.try_get(idx).map_or(Cell::Null, |v: i32| Cell::Int(v.into())),
44
45            "INT2" => self.try_get(idx).map_or(Cell::Null, |v: i16| Cell::Int(v.into())),
46
47            "NUMERIC" => self.try_get(idx).map_or(Cell::Null, Cell::Decimal),
48
49            // dbmcp passes raw `&str` queries → sqlx uses Postgres' simple-query
50            // (text) protocol, where `PgMoney` errors out (binary-only). Parse the
51            // locale-formatted text form ($1,234.56, -$99.99) directly — assumes the
52            // en_US.UTF-8 lc_monetary default (`$` symbol, `.` decimal).
53            "MONEY" => self
54                .try_get_raw(idx)
55                .ok()
56                .and_then(|v| v.as_str().ok())
57                .and_then(parse_pg_money_text)
58                .map_or(Cell::Null, Cell::Decimal),
59
60            "FLOAT4" => self.try_get(idx).map_or(Cell::Null, Cell::Float32),
61
62            "FLOAT8" => self.try_get(idx).map_or(Cell::Null, Cell::Float64),
63
64            "BYTEA" => self.try_get(idx).map_or(Cell::Null, Cell::Bytes),
65
66            "JSON" | "JSONB" => self.try_get(idx).map_or(Cell::Null, Cell::Json),
67
68            "DATE" => self.try_get(idx).map_or(Cell::Null, Cell::Date),
69
70            "TIME" => self.try_get(idx).map_or(Cell::Null, Cell::Time),
71
72            "TIMESTAMP" => self.try_get(idx).map_or(Cell::Null, Cell::DateTime),
73
74            "TIMESTAMPTZ" => self.try_get(idx).map_or(Cell::Null, Cell::DateTimeUtc),
75
76            _ => self.try_get(idx).map_or(Cell::Null, Cell::Text),
77        }
78    }
79}
80
81#[cfg(test)]
82mod tests {
83    use super::parse_pg_money_text;
84    use bigdecimal::BigDecimal;
85    use std::str::FromStr;
86
87    fn dec(s: &str) -> BigDecimal {
88        BigDecimal::from_str(s).expect("valid decimal literal")
89    }
90
91    #[test]
92    fn parses_plain_money() {
93        assert_eq!(parse_pg_money_text("$123.45"), Some(dec("123.45")));
94    }
95
96    #[test]
97    fn parses_money_with_thousand_separators() {
98        // Postgres MONEY in en_US.UTF-8 emits grouping commas in output:
99        // `$1,234,567.89`. The filter drops everything but digits/`.`/`-`,
100        // so commas vanish before parsing.
101        assert_eq!(parse_pg_money_text("$1,234.56"), Some(dec("1234.56")));
102        assert_eq!(parse_pg_money_text("$1,234,567.89"), Some(dec("1234567.89")));
103    }
104
105    #[test]
106    fn parses_zero_money() {
107        assert_eq!(parse_pg_money_text("$0.00"), Some(dec("0")));
108    }
109
110    #[test]
111    fn parses_negative_money_leading_minus_outside_symbol() {
112        // Default en_US.UTF-8 form: `-$99.99`.
113        assert_eq!(parse_pg_money_text("-$99.99"), Some(dec("-99.99")));
114    }
115
116    #[test]
117    fn parses_negative_money_with_minus_after_symbol() {
118        // Some locales render as `$-99.99`; filter retains `-` so the parse
119        // still produces a negative value.
120        assert_eq!(parse_pg_money_text("$-99.99"), Some(dec("-99.99")));
121    }
122
123    #[test]
124    fn empty_string_returns_none() {
125        assert!(parse_pg_money_text("").is_none());
126    }
127
128    #[test]
129    fn unparseable_returns_none() {
130        // After filtering: `..` — bigdecimal rejects this.
131        assert!(parse_pg_money_text("$.").is_none());
132        assert!(parse_pg_money_text("abc").is_none());
133    }
134
135    #[test]
136    fn accounting_parens_misparsed_as_positive() {
137        // Documents a known limitation: locales that wrap negatives in
138        // parentheses ($99.99) lose the negative sign because the filter
139        // strips `(` and `)`. Postgres en_US.UTF-8 default does not use
140        // this form; if a deployment customises lc_monetary to one that
141        // does, the wire form will be wrong. Test pins behaviour so any
142        // future fix surfaces as an obvious diff.
143        assert_eq!(parse_pg_money_text("($99.99)"), Some(dec("99.99")));
144    }
145
146    #[test]
147    fn large_money_at_i64_max_cents() {
148        // $92,233,720,368,547,758.07 — the maximum positive Postgres MONEY,
149        // beyond f64's 15-digit safe range.
150        assert_eq!(
151            parse_pg_money_text("$92,233,720,368,547,758.07"),
152            Some(dec("92233720368547758.07"))
153        );
154    }
155}