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
// 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, vardata_any, varsize_any_exhdr,
    void_mut_ptr, FromDatum, IntoDatum,
};
use serde::{Serialize, Serializer};
use serde_json::Value;

#[derive(Debug)]
pub struct Json(pub Value);

#[derive(Debug)]
pub struct JsonB(pub Value);

#[derive(Debug)]
pub struct JsonString(pub String);

/// for json
impl FromDatum for Json {
    #[inline]
    unsafe fn from_datum(datum: pg_sys::Datum, is_null: bool, _: pg_sys::Oid) -> Option<Json> {
        if is_null {
            None
        } else if datum == 0 {
            panic!("a json Datum was flagged as non-null but the datum is zero");
        } else {
            let varlena = pg_sys::pg_detoast_datum(datum as *mut pg_sys::varlena);
            let len = varsize_any_exhdr(varlena);
            let data = vardata_any(varlena);
            let slice = std::slice::from_raw_parts(data as *const u8, len);
            let value = serde_json::from_slice(slice).expect("failed to parse Json value");
            Some(Json(value))
        }
    }
}

/// for jsonb
impl FromDatum for JsonB {
    unsafe fn from_datum(datum: pg_sys::Datum, is_null: bool, _: pg_sys::Oid) -> Option<JsonB> {
        if is_null {
            None
        } else if datum == 0 {
            panic!("a jsonb Datum was flagged as non-null but the datum is zero")
        } else {
            let varlena = datum as *mut pg_sys::varlena;
            let detoasted = pg_sys::pg_detoast_datum_packed(varlena);

            let cstr = direct_function_call::<&std::ffi::CStr>(
                pg_sys::jsonb_out,
                vec![Some(detoasted as pg_sys::Datum)],
            )
            .expect("failed to convert jsonb to a cstring");

            let value = serde_json::from_str(
                cstr.to_str()
                    .expect("text version of jsonb is not valid UTF8"),
            )
            .expect("failed to parse JsonB value");

            // free the cstring returned from direct_function_call -- we don't need it anymore
            pg_sys::pfree(cstr.as_ptr() as void_mut_ptr);

            // free the detoasted datum if it turned out to be a copy
            if detoasted != varlena {
                pg_sys::pfree(detoasted as void_mut_ptr);
            }

            // return the parsed serde_json::Value
            Some(JsonB(value))
        }
    }
}

/// for `json` types to be represented as a wholly-owned Rust String copy
///
/// This returns a **copy**, allocated and managed by Rust, of the underlying `varlena` Datum
impl FromDatum for JsonString {
    #[inline]
    unsafe fn from_datum(
        datum: pg_sys::Datum,
        is_null: bool,
        _: pg_sys::Oid,
    ) -> Option<JsonString> {
        if is_null {
            None
        } else if datum == 0 {
            panic!("a varlena Datum was flagged as non-null but the datum is zero");
        } else {
            let varlena = datum as *mut pg_sys::varlena;
            let detoasted = pg_sys::pg_detoast_datum_packed(varlena);
            let len = varsize_any_exhdr(detoasted);
            let data = vardata_any(detoasted);

            let result =
                std::str::from_utf8_unchecked(std::slice::from_raw_parts(data as *mut u8, len))
                    .to_owned();

            if detoasted != varlena {
                pg_sys::pfree(detoasted as void_mut_ptr);
            }

            Some(JsonString(result))
        }
    }
}

/// for json
impl IntoDatum for Json {
    fn into_datum(self) -> Option<pg_sys::Datum> {
        let string = serde_json::to_string(&self.0).expect("failed to serialize Json value");
        string.into_datum()
    }

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

/// for jsonb
impl IntoDatum for JsonB {
    fn into_datum(self) -> Option<pg_sys::Datum> {
        let string = serde_json::to_string(&self.0).expect("failed to serialize JsonB value");
        let cstring =
            std::ffi::CString::new(string).expect("string version of jsonb is not valid UTF8");

        direct_function_call_as_datum(
            pg_sys::jsonb_in,
            vec![Some(cstring.as_ptr() as pg_sys::Datum)],
        )
    }

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

/// for jsonstring
impl IntoDatum for JsonString {
    fn into_datum(self) -> Option<pg_sys::Datum> {
        self.0.as_str().into_datum()
    }

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

impl Serialize for Json {
    fn serialize<S>(&self, serializer: S) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error>
    where
        S: Serializer,
    {
        self.0.serialize(serializer)
    }
}

impl Serialize for JsonB {
    fn serialize<S>(&self, serializer: S) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error>
    where
        S: Serializer,
    {
        self.0.serialize(serializer)
    }
}

impl Serialize for JsonString {
    fn serialize<S>(&self, serializer: S) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error>
    where
        S: Serializer,
    {
        serde_json::to_value(self.0.as_str())
            .expect("JsonString is not valid JSON")
            .serialize(serializer)
    }
}