1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
// Copyright 2020 ZomboDB, LLC <zombodb@gmail.com>. All rights reserved. Use of this source code is
// governed by the MIT license that can be found in the LICENSE file.

use crate::{
    direct_function_call, direct_function_call_as_datum, pg_sys, void_mut_ptr, FromDatum, IntoDatum,
};
use pgx_pg_sys::pg_try;
use serde::de::{Error, Visitor};
use serde::{de, Deserialize, Deserializer, Serialize};
use serde_json::Number;
use std::fmt;

#[derive(Serialize)]
pub struct Numeric(pub String);

impl<'de> Deserialize<'de> for Numeric {
    fn deserialize<D>(deserializer: D) -> Result<Self, <D as Deserializer<'de>>::Error>
    where
        D: Deserializer<'de>,
    {
        struct NumericVisitor;

        impl<'de> Visitor<'de> for NumericVisitor {
            type Value = Numeric;

            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                formatter.write_str("a JSON number or a \"quoted JSON number\"")
            }

            #[inline]
            fn visit_i64<E>(self, value: i64) -> Result<Numeric, E> {
                Ok(value.into())
            }

            #[inline]
            fn visit_u64<E>(self, value: u64) -> Result<Numeric, E> {
                Ok(value.into())
            }

            #[inline]
            fn visit_f64<E>(self, value: f64) -> Result<Numeric, E>
            where
                E: de::Error,
            {
                let result =
                    Number::from_f64(value).ok_or_else(|| de::Error::custom("not a JSON number"));
                match result {
                    Ok(num) => Ok(num.as_f64().unwrap().into()),
                    Err(e) => Err(e),
                }
            }

            #[inline]
            fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
            where
                E: Error,
            {
                self.visit_string(v.to_owned())
            }

            #[inline]
            fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
            where
                E: Error,
            {
                // try to convert the provided String value into a Postgres Numeric Datum
                // if it doesn't raise an ERROR, then we're good
                unsafe {
                    pg_try(|| {
                        // this might throw, but that's okay
                        let datum = Numeric(v.clone()).into_datum().unwrap();

                        // and don't leak the NumericData datum Postgres created
                        pg_sys::pfree(datum as void_mut_ptr);

                        // we have it as a valid String
                        Ok(Numeric(v.clone()))
                    })
                    .unwrap_or(Err(Error::custom(format!("invalid Numeric value: {}", v))))
                }
            }
        }

        deserializer.deserialize_any(NumericVisitor)
    }
}

impl Into<Numeric> for i8 {
    fn into(self) -> Numeric {
        Numeric(format!("{}", self))
    }
}

impl Into<Numeric> for i16 {
    fn into(self) -> Numeric {
        Numeric(format!("{}", self))
    }
}

impl Into<Numeric> for i32 {
    fn into(self) -> Numeric {
        Numeric(format!("{}", self))
    }
}

impl Into<Numeric> for i64 {
    fn into(self) -> Numeric {
        Numeric(format!("{}", self))
    }
}

impl Into<Numeric> for u8 {
    fn into(self) -> Numeric {
        Numeric(format!("{}", self))
    }
}

impl Into<Numeric> for u16 {
    fn into(self) -> Numeric {
        Numeric(format!("{}", self))
    }
}

impl Into<Numeric> for u32 {
    fn into(self) -> Numeric {
        Numeric(format!("{}", self))
    }
}

impl Into<Numeric> for u64 {
    fn into(self) -> Numeric {
        Numeric(format!("{}", self))
    }
}

impl Into<Numeric> for f32 {
    fn into(self) -> Numeric {
        Numeric(format!("{}", self))
    }
}

impl Into<Numeric> for f64 {
    fn into(self) -> Numeric {
        Numeric(format!("{}", self))
    }
}

impl FromDatum for Numeric {
    unsafe fn from_datum(datum: usize, is_null: bool, _typoid: u32) -> Option<Self>
    where
        Self: Sized,
    {
        if is_null {
            None
        } else {
            let cstr =
                direct_function_call::<&std::ffi::CStr>(pg_sys::numeric_out, vec![Some(datum)])
                    .expect("numeric_out returned null");
            Some(Numeric(cstr.to_str().unwrap().into()))
        }
    }
}

impl IntoDatum for Numeric {
    fn into_datum(self) -> Option<pg_sys::Datum> {
        let cstring =
            std::ffi::CString::new(self.0).expect("failed to convert numeric string into CString");
        let cstr = cstring.as_c_str();
        direct_function_call_as_datum(
            pg_sys::numeric_in,
            vec![
                cstr.into_datum(),
                pg_sys::InvalidOid.into_datum(),
                0i32.into_datum(),
            ],
        )
    }

    fn type_oid() -> u32 {
        pg_sys::NUMERICOID
    }
}