1use 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
22fn 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 "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 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 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 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 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 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 assert_eq!(
183 parse_pg_money_text("$92,233,720,368,547,758.07"),
184 Some(dec("92233720368547758.07"))
185 );
186 }
187}