Skip to main content

sqlx_json/
postgres.rs

1//! [`RowExt`](crate::RowExt) implementation for `PostgreSQL` rows.
2//!
3//! Type names are normalized to uppercase because sqlx may return either case
4//! depending on the query context. Integer types use size-specific Rust types
5//! (`i16`, `i32`, `i64`) because sqlx enforces strict type matching for
6//! `PostgreSQL`. Temporal types (`DATE`, `TIME`, `TIMESTAMP`, `TIMESTAMPTZ`)
7//! are decoded via sqlx's `chrono` integration and serialized as RFC 3339
8//! strings; `TIMESTAMPTZ` is normalized to UTC and emitted with a `Z` suffix.
9//! `NUMERIC` is decoded via `BigDecimal` to preserve precision; `MONEY`
10//! arrives as text (sqlx uses simple-query for parameterless statements)
11//! and is parsed locale-aware then routed through the same shape rule.
12
13use std::str::FromStr;
14
15use bigdecimal::BigDecimal;
16use sqlx::postgres::PgRow;
17use sqlx::types::chrono::{DateTime, NaiveDate, NaiveDateTime, NaiveTime, Utc};
18
19use crate::numeric::bigdecimal_to_json;
20use crate::prelude::*;
21
22/// Parses a locale-formatted Postgres `MONEY` text value into a `BigDecimal`.
23///
24/// Strips currency symbol and grouping separators (everything except digits,
25/// `.`, and `-`), then parses what remains. Tuned for the en_US.UTF-8
26/// `lc_monetary` default — locales using `,` as decimal separator are not
27/// supported.
28fn parse_pg_money_text(text: &str) -> Option<BigDecimal> {
29    let cleaned: String = text.chars().filter(|c| matches!(c, '0'..='9' | '.' | '-')).collect();
30    BigDecimal::from_str(&cleaned).ok()
31}
32
33impl RowExt for PgRow {
34    fn to_json(&self) -> Value {
35        let columns = self.columns();
36        let mut map = Map::with_capacity(columns.len());
37
38        for column in columns {
39            let idx = column.ordinal();
40            let type_name = column.type_info().name().to_ascii_uppercase();
41
42            let value = if self.try_get_raw(idx).is_ok_and(|v| v.is_null()) {
43                Value::Null
44            } else {
45                match type_name.as_str() {
46                    "BOOL" => self.try_get::<bool, _>(idx).map_or(Value::Null, Value::Bool),
47
48                    "INT8" => self
49                        .try_get::<i64, _>(idx)
50                        .map_or(Value::Null, |v| Value::Number(v.into())),
51
52                    "INT4" | "OID" => self
53                        .try_get::<i32, _>(idx)
54                        .map_or(Value::Null, |v| Value::Number(i64::from(v).into())),
55
56                    "INT2" => self
57                        .try_get::<i16, _>(idx)
58                        .map_or(Value::Null, |v| Value::Number(i64::from(v).into())),
59
60                    "NUMERIC" => self
61                        .try_get::<BigDecimal, _>(idx)
62                        .map_or(Value::Null, |v| bigdecimal_to_json(&v)),
63
64                    // dbmcp passes raw `&str` queries → sqlx uses Postgres' simple-query
65                    // (text) protocol, where `PgMoney` errors out (binary-only). Parse the
66                    // locale-formatted text form ($1,234.56, -$99.99) directly — assumes the
67                    // en_US.UTF-8 lc_monetary default (`$` symbol, `.` decimal).
68                    "MONEY" => self
69                        .try_get_raw(idx)
70                        .ok()
71                        .and_then(|v| v.as_str().ok())
72                        .and_then(parse_pg_money_text)
73                        .map_or(Value::Null, |bd| bigdecimal_to_json(&bd)),
74
75                    "FLOAT4" => self.try_get::<f32, _>(idx).map_or(Value::Null, Value::from),
76
77                    "FLOAT8" => self.try_get::<f64, _>(idx).map_or(Value::Null, Value::from),
78
79                    "BYTEA" => self
80                        .try_get::<Vec<u8>, _>(idx)
81                        .map_or(Value::Null, |bytes| Value::String(BASE64.encode(&bytes))),
82
83                    "JSON" | "JSONB" => self.try_get::<Value, _>(idx).unwrap_or(Value::Null),
84
85                    "DATE" => self
86                        .try_get::<NaiveDate, _>(idx)
87                        .map_or(Value::Null, |v| Value::String(v.to_string())),
88
89                    "TIME" => self
90                        .try_get::<NaiveTime, _>(idx)
91                        .map_or(Value::Null, |v| Value::String(v.to_string())),
92
93                    "TIMESTAMP" => self
94                        .try_get::<NaiveDateTime, _>(idx)
95                        .map_or(Value::Null, |v| Value::String(format!("{}T{}", v.date(), v.time()))),
96
97                    "TIMESTAMPTZ" => self.try_get::<DateTime<Utc>, _>(idx).map_or(Value::Null, |v| {
98                        let n = v.naive_utc();
99                        Value::String(format!("{}T{}Z", n.date(), n.time()))
100                    }),
101
102                    _ => self.try_get::<String, _>(idx).map_or(Value::Null, Value::String),
103                }
104            };
105
106            map.insert(column.name().to_string(), value);
107        }
108
109        Value::Object(map)
110    }
111}
112
113#[cfg(test)]
114mod tests {
115    use super::parse_pg_money_text;
116    use bigdecimal::BigDecimal;
117    use std::str::FromStr;
118
119    fn dec(s: &str) -> BigDecimal {
120        BigDecimal::from_str(s).expect("valid decimal literal")
121    }
122
123    #[test]
124    fn parses_plain_money() {
125        assert_eq!(parse_pg_money_text("$123.45"), Some(dec("123.45")));
126    }
127
128    #[test]
129    fn parses_money_with_thousand_separators() {
130        // Postgres MONEY in en_US.UTF-8 emits grouping commas in output:
131        // `$1,234,567.89`. The filter drops everything but digits/`.`/`-`,
132        // so commas vanish before parsing.
133        assert_eq!(parse_pg_money_text("$1,234.56"), Some(dec("1234.56")));
134        assert_eq!(parse_pg_money_text("$1,234,567.89"), Some(dec("1234567.89")));
135    }
136
137    #[test]
138    fn parses_zero_money() {
139        assert_eq!(parse_pg_money_text("$0.00"), Some(dec("0")));
140    }
141
142    #[test]
143    fn parses_negative_money_leading_minus_outside_symbol() {
144        // Default en_US.UTF-8 form: `-$99.99`.
145        assert_eq!(parse_pg_money_text("-$99.99"), Some(dec("-99.99")));
146    }
147
148    #[test]
149    fn parses_negative_money_with_minus_after_symbol() {
150        // Some locales render as `$-99.99`; filter retains `-` so the parse
151        // still produces a negative value.
152        assert_eq!(parse_pg_money_text("$-99.99"), Some(dec("-99.99")));
153    }
154
155    #[test]
156    fn empty_string_returns_none() {
157        assert!(parse_pg_money_text("").is_none());
158    }
159
160    #[test]
161    fn unparseable_returns_none() {
162        // After filtering: `..` — bigdecimal rejects this.
163        assert!(parse_pg_money_text("$.").is_none());
164        assert!(parse_pg_money_text("abc").is_none());
165    }
166
167    #[test]
168    fn accounting_parens_misparsed_as_positive() {
169        // Documents a known limitation: locales that wrap negatives in
170        // parentheses ($99.99) lose the negative sign because the filter
171        // strips `(` and `)`. Postgres en_US.UTF-8 default does not use
172        // this form; if a deployment customises lc_monetary to one that
173        // does, the wire form will be wrong. Test pins behaviour so any
174        // future fix surfaces as an obvious diff.
175        assert_eq!(parse_pg_money_text("($99.99)"), Some(dec("99.99")));
176    }
177
178    #[test]
179    fn large_money_at_i64_max_cents() {
180        // $92,233,720,368,547,758.07 — the maximum positive Postgres MONEY,
181        // beyond f64's 15-digit safe range.
182        assert_eq!(
183            parse_pg_money_text("$92,233,720,368,547,758.07"),
184            Some(dec("92233720368547758.07"))
185        );
186    }
187}