Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
96 changes: 83 additions & 13 deletions src/binding.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
//! in the SQL text and pin the placeholder's `Type` to `TEXT` so tokio-postgres
//! doesn't fight the CAST.

use rust_decimal::Decimal;
use serde_json::Value;
use std::collections::HashMap;
use tokio_postgres::types::{Kind, ToSql, Type};
Expand Down Expand Up @@ -467,6 +466,60 @@ fn json_array_to_pg_literal(arr: &[Value]) -> Result<String, String> {
Ok(format!("ARRAY[{}]", parts.join(", ")))
}

/// Quick shape check for a numeric literal: an optional sign, then digits with
/// at most one `.`, and an optional exponent (`e`/`E` + optional sign + digits).
/// Used by [`bind_pg_numeric_string`]'s `NUMERIC`/`DECIMAL` fallback to tell a
/// wide valid numeric (which `rust_decimal::Decimal` rejected only for being
/// too wide) from a non-numeric string (which must be rejected client-side).
/// Conservative — rejects edge forms PostgreSQL also rejects, never accepts
/// garbage: it must have at least one digit, and `.`/`e` cannot be the only
/// content. Specials (`NaN`/`Infinity`/`-Infinity`) are handled separately by
/// the caller before this is reached.
fn looks_like_numeric_literal(s: &str) -> bool {
let s = s.trim();
if s.is_empty() {
return false;
}
let bytes = s.as_bytes();
let mut i = 0;
// Optional leading sign.
if bytes[i] == b'+' || bytes[i] == b'-' {
i += 1;
}
let mut saw_digit = false;
// Integer digits (at least one, unless a fraction follows).
while i < bytes.len() && bytes[i].is_ascii_digit() {
saw_digit = true;
i += 1;
}
// Optional fraction.
if i < bytes.len() && bytes[i] == b'.' {
i += 1;
while i < bytes.len() && bytes[i].is_ascii_digit() {
saw_digit = true;
i += 1;
}
}
if !saw_digit {
return false;
}
// Optional exponent.
if i < bytes.len() && (bytes[i] == b'e' || bytes[i] == b'E') {
i += 1;
if i < bytes.len() && (bytes[i] == b'+' || bytes[i] == b'-') {
i += 1;
}
let exp_start = i;
while i < bytes.len() && bytes[i].is_ascii_digit() {
i += 1;
}
if i == exp_start {
return false; // exponent with no digits
}
}
i == bytes.len()
}

/// Coerce a string value into a numeric PostgreSQL column (`smallint`
/// through `bigint`, `numeric`/`decimal`, `real`/`double precision`).
/// Returns `None` if the column is not numeric, so callers can fall through
Expand Down Expand Up @@ -495,20 +548,37 @@ fn bind_pg_numeric_string(
},
))
}
"NUMERIC" | "DECIMAL" => Some(s.parse::<Decimal>().map_or_else(
|_| {
Err(format!(
// NUMERIC/DECIMAL: always bind the exact string as TEXT and let the
// server cast it with `CAST($N AS numeric)`. `rust_decimal::Decimal`
// (the old path, `s.parse::<Decimal>()`) holds a 96-bit mantissa
// (~28-29 significant digits) and cannot represent `NaN`/`Infinity` —
// AND, critically, it silently *rounds* (not errors) on values with
// more than ~28 significant *fractional* digits, returning `Ok` with a
// truncated value that would then bind as `Type::NUMERIC` and corrupt
// the round-trip (a `numeric(40,36)` value would lose precision with
// no error). Always-TEXT+CAST avoids that: PostgreSQL's own `numeric`
// parser preserves the full precision, and `NaN`/`Infinity` are
// accepted exactly as `read_rows`' `PgNumeric` emits them (#214 item 1
// + review finding). Mirrors the UUID-shape fallback's TEXT+CAST
// pattern below. A non-numeric string is still rejected client-side by
// `looks_like_numeric_literal` so the PK path keeps its early rejection.
"NUMERIC" | "DECIMAL" => {
if s.eq_ignore_ascii_case("NaN")
|| s.eq_ignore_ascii_case("Infinity")
|| s.eq_ignore_ascii_case("-Infinity")
|| looks_like_numeric_literal(s)
{
Some(Ok(BoundValue {
sql: format!("CAST(${} AS numeric)", placeholder_idx),
param: Some((Box::new(s.to_string()), Type::TEXT)),
}))
} else {
Some(Err(format!(
"Cannot bind '{}' as numeric for target type {}",
s, base_type
))
},
|d| {
Ok(BoundValue {
sql: format!("CAST(${} AS numeric)", placeholder_idx),
param: Some((Box::new(d), Type::NUMERIC)),
})
},
)),
)))
}
}
"REAL" | "DOUBLE PRECISION" | "FLOAT4" | "FLOAT8" => Some(s.parse::<f64>().map_or_else(
|_| {
Err(format!(
Expand Down
92 changes: 91 additions & 1 deletion src/binding_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -236,6 +236,93 @@ mod bind_pg_value_tests {
assert_eq!(bound.sql, "CAST($1 AS numeric)");
}

/// A 38-digit numeric value that `rust_decimal::Decimal` cannot hold (the
/// old `s.parse::<Decimal>()` path rejected it) must still bind for the
/// table-copy write side (#214 item 1). The TEXT+CAST path has no such
/// ceiling — PostgreSQL parses the full-precision decimal text.
#[test]
fn numeric_column_binds_a_38_digit_string_via_text_cast() {
let options = BindOptions {
column_type: Some("numeric"),
enum_type: None,
allow_default: false,
hstore_oid: None,
};
let wide = "12345678901234567890123456789012345678.1234567890";
let bound = bind_pg_value(json!(wide), 1, &options).unwrap();
assert_eq!(bound.sql, "CAST($1 AS numeric)");
let (_, pg_type) = bound.param.unwrap();
assert_eq!(pg_type, tokio_postgres::types::Type::TEXT);
}

/// `NaN` (which `Decimal` cannot represent) binds through the TEXT+CAST
/// path; `CAST('NaN' AS numeric)` is the round-trip pair of `read_rows`'
/// `PgNumeric` `NaN` output.
#[test]
fn numeric_column_binds_nan_string() {
let options = BindOptions {
column_type: Some("numeric"),
enum_type: None,
allow_default: false,
hstore_oid: None,
};
let bound = bind_pg_value(json!("NaN"), 1, &options).unwrap();
assert_eq!(bound.sql, "CAST($1 AS numeric)");
let (_, pg_type) = bound.param.unwrap();
assert_eq!(pg_type, tokio_postgres::types::Type::TEXT);
}

/// `DECIMAL` is an alias for `NUMERIC` and takes the same TEXT+CAST path.
#[test]
fn decimal_column_binds_a_wide_string_via_text_cast() {
let options = BindOptions {
column_type: Some("decimal"),
enum_type: None,
allow_default: false,
hstore_oid: None,
};
let bound =
bind_pg_value(json!("99999999999999999999999999999999999999"), 1, &options).unwrap();
assert_eq!(bound.sql, "CAST($1 AS numeric)");
let (_, pg_type) = bound.param.unwrap();
assert_eq!(pg_type, tokio_postgres::types::Type::TEXT);
}

/// `looks_like_numeric_literal` must reject non-numeric garbage for a
/// NUMERIC column (the guard's whole purpose — keeps the PK-path's
/// client-side rejection) (#214 review finding: this was untested).
#[test]
fn numeric_column_rejects_non_numeric_garbage() {
let options = BindOptions {
column_type: Some("numeric"),
enum_type: None,
allow_default: false,
hstore_oid: None,
};
assert!(bind_pg_value(json!("abc"), 1, &options).is_err());
assert!(bind_pg_value(json!("1.2.3"), 1, &options).is_err());
assert!(bind_pg_value(json!("1e"), 1, &options).is_err());
}

/// `looks_like_numeric_literal` edge forms that ARE valid numeric
/// literals and must bind (not be rejected) (#214 review finding).
#[test]
fn numeric_column_accepts_edge_form_numeric_literals() {
let options = BindOptions {
column_type: Some("numeric"),
enum_type: None,
allow_default: false,
hstore_oid: None,
};
// Exponent form.
assert!(bind_pg_value(json!("1e10"), 1, &options).is_ok());
assert!(bind_pg_value(json!("1.5e-3"), 1, &options).is_ok());
// Leading + sign.
assert!(bind_pg_value(json!("+5"), 1, &options).is_ok());
// Fraction-only, no integer digits (.5 → valid PostgreSQL numeric).
assert!(bind_pg_value(json!(".5"), 1, &options).is_ok());
}

#[test]
fn timestamp_column_string_binds_with_timestamp_cast() {
let options = BindOptions {
Expand Down Expand Up @@ -627,10 +714,13 @@ mod bind_pk_value_tests {

#[test]
fn numeric_column_string_value_casts_to_numeric() {
// After the always-TEXT+CAST fix (#214 review), small numerics bind the
// exact string as Type::TEXT (not Type::NUMERIC via Decimal) — avoiding
// Decimal's silent rounding on high-scale values. The SQL is the same.
let bound = bind_pk_value(&json!("1500.00"), 2, Some("numeric")).unwrap();
assert_eq!(bound.sql, "CAST($2 AS numeric)");
let (_, pg_type) = bound.param.unwrap();
assert_eq!(pg_type, tokio_postgres::types::Type::NUMERIC);
assert_eq!(pg_type, tokio_postgres::types::Type::TEXT);
}

#[test]
Expand Down
Loading
Loading