Skip to main content

rust_ef_postgres/
type_conversion.rs

1use rust_ef::provider::DbValue;
2use tokio_postgres::types::ToSql;
3
4/// Converts `DbValue` parameters into boxed `ToSql` trait objects for
5/// `tokio_postgres`.
6///
7/// Native variants (`DateTime`/`NaiveDateTime`/`NaiveDate`/`Uuid`) are bound
8/// directly via `tokio_postgres`'s binary protocol (enabled by the
9/// `with-chrono-0_4`/`with-uuid-1` features). `Decimal` is bound as a string
10/// since `tokio_postgres` lacks a native `rust_decimal` adapter; PG's `NUMERIC`
11/// type accepts string input and round-trips losslessly.
12pub fn db_values_to_pg_params(params: &[DbValue]) -> Vec<Box<dyn ToSql + Sync + Send>> {
13    params
14        .iter()
15        .map(|v| match v {
16            DbValue::Null => Box::new(None::<String>) as Box<dyn ToSql + Sync + Send>,
17            DbValue::Bool(b) => Box::new(*b),
18            DbValue::I16(n) => Box::new(*n),
19            DbValue::I32(n) => Box::new(*n),
20            DbValue::I64(n) => Box::new(*n),
21            DbValue::F32(n) => Box::new(*n),
22            DbValue::F64(n) => Box::new(*n),
23            DbValue::String(s) => Box::new(s.clone()),
24            DbValue::Bytes(b) => Box::new(b.clone()),
25            DbValue::DateTime(dt) => Box::new(*dt),
26            DbValue::NaiveDateTime(ndt) => Box::new(*ndt),
27            DbValue::NaiveDate(nd) => Box::new(*nd),
28            DbValue::Uuid(u) => Box::new(*u),
29            // tokio_postgres has no native rust_decimal ToSql impl; bind as
30            // string. PG's NUMERIC column accepts string input and preserves
31            // full precision.
32            DbValue::Decimal(d) => Box::new(d.to_string()),
33        })
34        .collect()
35}