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
use std::collections::HashMap;

/**
 * Rust type for [hstore](https://www.postgresql.org/docs/current/hstore.html).
 */
#[derive(Clone, Debug, Default, Eq, PartialEq)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
pub struct Hstore(HashMap<String, Option<String>>);

impl Hstore {
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    fn read_string(buf: &mut &[u8]) -> crate::Result<Option<String>> {
        let len = crate::from_sql::read_i32(buf)?;

        let s = if len < 0 {
            None
        } else {
            let mut vec = Vec::new();
            for _ in 0..len {
                vec.push(crate::from_sql::read_u8(buf)?);
            }

            Some(String::from_utf8(vec)?)
        };

        Ok(s)
    }
}

impl std::ops::DerefMut for Hstore {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

impl std::ops::Deref for Hstore {
    type Target = HashMap<String, Option<String>>;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl crate::ToSql for crate::Hstore {
    fn ty(&self) -> crate::pq::Type {
        crate::pq::Type {
            descr: "HSTORE - data type for storing sets of (key, value) pairs",
            name: "hstore",

            ..crate::pq::types::UNKNOWN
        }
    }

    /*
     * https://github.com/postgres/postgres/blob/REL_12_0/contrib/hstore/hstore_io.c#L407
     */
    fn to_text(&self) -> crate::Result<Option<String>> {
        let mut vec = Vec::new();

        for (key, value) in self.iter() {
            let v = value
                .as_ref()
                .map_or_else(|| "NULL".to_string(), |x| format!("\"{x}\""));

            vec.push(format!("\"{key}\"=>{v}"));
        }

        vec.join(", ").to_text()
    }

    /*
     * https://github.com/postgres/postgres/blob/REL_12_0/contrib/hstore/hstore_io.c#L1226
     */
    fn to_binary(&self) -> crate::Result<Option<Vec<u8>>> {
        let mut buf = Vec::new();

        crate::to_sql::write_i32(&mut buf, self.len() as i32)?;

        for (key, value) in self.iter() {
            let k = key.to_text()?.unwrap();
            crate::to_sql::write_i32(&mut buf, k.len() as i32)?;
            buf.append(&mut k.into_bytes());

            if let Some(v) = value.to_text()? {
                crate::to_sql::write_i32(&mut buf, v.len() as i32)?;
                buf.append(&mut v.into_bytes());
            } else {
                crate::to_sql::write_i32(&mut buf, -1)?;
            }
        }

        Ok(Some(buf))
    }
}

impl crate::FromSql for Hstore {
    /*
     * https://github.com/postgres/postgres/blob/REL_12_0/contrib/hstore/hstore_io.c#L1155
     */
    fn from_text(_: &crate::pq::Type, raw: Option<&str>) -> crate::Result<Self> {
        let regex = crate::regex!("\"(?P<key>.*?)\"=>(\"(?P<value>.*?)\"|(?P<null>NULL))");

        let mut hstore = Self::new();

        for capture in regex.captures_iter(crate::not_null(raw)?) {
            let key = capture.name("key").unwrap().as_str().to_string();
            let value = if capture.name("null").is_some() {
                None
            } else {
                Some(capture.name("value").unwrap().as_str().to_string())
            };
            hstore.insert(key, value);
        }

        Ok(hstore)
    }

    /*
     * https://github.com/postgres/postgres/blob/REL_12_0/contrib/hstore/hstore_io.c#L427
     */
    fn from_binary(ty: &crate::pq::Type, raw: Option<&[u8]>) -> crate::Result<Self> {
        let mut hstore = Self::new();
        let mut buf = crate::from_sql::not_null(raw)?;
        let count = crate::from_sql::read_i32(&mut buf)?;

        for _ in 0..count {
            let key = Self::read_string(&mut buf)?.ok_or_else(|| Self::error(ty, raw))?;
            let value = Self::read_string(&mut buf)?;

            hstore.insert(key, value);
        }

        Ok(hstore)
    }
}

impl crate::entity::Simple for Hstore {}

#[cfg(test)]
mod test {
    crate::sql_test!(
        hstore,
        crate::Hstore,
        [("'a=>1, b => 2, c=>null'", {
            let mut hstore = crate::Hstore::new();
            hstore.insert("a".to_string(), Some("1".to_string()));
            hstore.insert("b".to_string(), Some("2".to_string()));
            hstore.insert("c".to_string(), None);

            hstore
        })]
    );
}