pgx/datum/numeric_support/
datum.rs

1use crate::{pg_sys, AnyNumeric, FromDatum, IntoDatum, Numeric};
2
3impl FromDatum for AnyNumeric {
4    #[inline]
5    unsafe fn from_polymorphic_datum(
6        datum: pg_sys::Datum,
7        is_null: bool,
8        _typoid: pg_sys::Oid,
9    ) -> Option<Self>
10    where
11        Self: Sized,
12    {
13        if is_null {
14            None
15        } else {
16            let numeric = pg_sys::pg_detoast_datum(datum.cast_mut_ptr()) as pg_sys::Numeric;
17            let is_copy = !std::ptr::eq(
18                numeric.cast::<pg_sys::NumericData>(),
19                datum.cast_mut_ptr::<pg_sys::NumericData>(),
20            );
21            Some(AnyNumeric { inner: numeric, need_pfree: is_copy })
22        }
23    }
24}
25
26impl IntoDatum for AnyNumeric {
27    #[inline]
28    fn into_datum(mut self) -> Option<pg_sys::Datum> {
29        // we're giving it to Postgres so we don't want our drop impl to free the inner pointer
30        self.need_pfree = false;
31        Some(pg_sys::Datum::from(self.inner))
32    }
33
34    #[inline]
35    fn type_oid() -> pg_sys::Oid {
36        pg_sys::NUMERICOID
37    }
38}
39
40impl<const P: u32, const S: u32> FromDatum for Numeric<P, S> {
41    #[inline]
42    unsafe fn from_polymorphic_datum(
43        datum: pg_sys::Datum,
44        is_null: bool,
45        typoid: pg_sys::Oid,
46    ) -> Option<Self>
47    where
48        Self: Sized,
49    {
50        if is_null {
51            None
52        } else {
53            Some(Numeric(AnyNumeric::from_polymorphic_datum(datum, false, typoid).unwrap()))
54        }
55    }
56}
57
58impl<const P: u32, const S: u32> IntoDatum for Numeric<P, S> {
59    #[inline]
60    fn into_datum(self) -> Option<pg_sys::Datum> {
61        self.0.into_datum()
62    }
63
64    #[inline]
65    fn type_oid() -> pg_sys::Oid {
66        pg_sys::NUMERICOID
67    }
68}