Skip to content

Commit 56a2a81

Browse files
committed
fix: do not panic when binding a large BigDecimal
1 parent 84d5760 commit 56a2a81

File tree

1 file changed

+9
-3
lines changed

1 file changed

+9
-3
lines changed

sqlx-postgres/src/types/bigdecimal.rs

+9-3
Original file line numberDiff line numberDiff line change
@@ -138,12 +138,18 @@ impl TryFrom<&'_ BigDecimal> for PgNumeric {
138138
}
139139
}
140140

141-
/// ### Panics
142-
/// If this `BigDecimal` cannot be represented by `PgNumeric`.
143141
impl Encode<'_, Postgres> for BigDecimal {
144142
fn encode_by_ref(&self, buf: &mut PgArgumentBuffer) -> IsNull {
143+
use std::str::FromStr;
144+
// If the argument is too big, then we replace it with a less big argument.
145+
// This less big argument is already outside the range of allowed PostgreSQL DECIMAL, which
146+
// means that PostgreSQL will return the 22P03 error kind upon receiving it. This is the
147+
// expected error, and the user should be ready to handle it anyway.
145148
PgNumeric::try_from(self)
146-
.expect("BigDecimal magnitude too great for Postgres NUMERIC type")
149+
.unwrap_or_else(|_| {
150+
PgNumeric::try_from(&BigDecimal::from_str(&format!("{:030000}", 0)).unwrap())
151+
.unwrap()
152+
})
147153
.encode(buf);
148154

149155
IsNull::No

0 commit comments

Comments
 (0)