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
use std::iter::IntoIterator;

use bytes::Bytes;

use crate::codec::{NamedTupleShape, ObjectShape, ShapeElement};
use crate::common::{Cardinality};
use crate::model::{BigInt, Decimal, Uuid, ConfigMemory, Range};
use crate::model::{LocalDatetime, LocalDate, LocalTime, Duration, Datetime};
use crate::model::{RelativeDuration, DateDuration, Json};
pub use crate::codec::EnumValue;

#[derive(Clone, Debug, PartialEq)]
pub enum Value {
    Nothing,
    Uuid(Uuid),
    Str(String),
    Bytes(Bytes),
    Int16(i16),
    Int32(i32),
    Int64(i64),
    Float32(f32),
    Float64(f64),
    BigInt(BigInt),
    ConfigMemory(ConfigMemory),
    Decimal(Decimal),
    Bool(bool),
    Datetime(Datetime),
    LocalDatetime(LocalDatetime),
    LocalDate(LocalDate),
    LocalTime(LocalTime),
    Duration(Duration),
    RelativeDuration(RelativeDuration),
    DateDuration(DateDuration),
    Json(Json),
    Set(Vec<Value>),
    Object { shape: ObjectShape, fields: Vec<Option<Value>> },
    SparseObject(SparseObject),
    Tuple(Vec<Value>),
    NamedTuple { shape: NamedTupleShape, fields: Vec<Value> },
    Array(Vec<Value>),
    Vector(Vec<f32>),
    Enum(EnumValue),
    Range(Range<Box<Value>>),
}

#[derive(Clone, Debug)]
pub struct SparseObject {
    pub(crate) shape: ObjectShape,
    pub(crate) fields: Vec<Option<Option<Value>>>,
}

impl Value {
    pub fn kind(&self) -> &'static str {
        use Value::*;
        match self {
            Nothing => "nothing",
            Uuid(..) => "uuid",
            Str(..) => "string",
            Bytes(..) => "bytes",
            Int16(..) => "int16",
            Int32(..) => "int32",
            Int64(..) => "int64",
            Float32(..) => "float32",
            Float64(..) => "float64",
            BigInt(..) => "bigint",
            ConfigMemory(..) => "cfg::memory",
            Decimal(..) => "decimal",
            Bool(..) => "bool",
            Datetime(..) => "datetime",
            LocalDatetime(..) => "cal::local_datetime",
            LocalDate(..) => "cal::local_date",
            LocalTime(..) => "cal::local_time",
            Duration(..) => "duration",
            RelativeDuration(..) => "cal::relative_duration",
            DateDuration(..) => "cal::date_duration",
            Json(..) => "json",
            Set(..) => "set",
            Object { .. } => "object",
            SparseObject { .. } => "sparse_object",
            Tuple(..) => "tuple",
            NamedTuple { .. } => "named_tuple",
            Array(..) => "array",
            Enum(..) => "enum",
            Range{..} => "range",
            Vector(..) => "ext::pgvector::vector",
        }
    }
    pub fn empty_tuple() -> Value {
        Value::Tuple(Vec::new())
    }
}

impl SparseObject {
    /// Create a new sparse object from key-value pairs
    ///
    /// Note: this method has two limitations:
    /// 1. Shape created uses `AtMostOne` cardinality for all the elements.
    /// 2. There are no extra shape elements
    /// Both of these are irrelevant when serializing the object.
    pub fn from_pairs<N: ToString, V: Into<Option<Value>>>(
        iter: impl IntoIterator<Item=(N, V)>)
        -> SparseObject
    {
        let mut elements = Vec::new();
        let mut fields = Vec::new();
        for (key, val) in iter.into_iter() {
            elements.push(ShapeElement {
                flag_implicit: false,
                flag_link_property: false,
                flag_link: false,
                cardinality: Some(Cardinality::AtMostOne),
                name: key.to_string(),
            });
            fields.push(Some(val.into()));
        }
        SparseObject {
            shape: ObjectShape::new(elements),
            fields,
        }
    }
    /// Create an empty sparse object
    pub fn empty() -> SparseObject {
        SparseObject {
            shape: ObjectShape::new(Vec::new()),
            fields: Vec::new(),
        }
    }
    pub fn pairs(&self) -> impl Iterator<Item=(&str, Option<&Value>)> {
        self.shape.0.elements.iter().zip(&self.fields).filter_map(|(el, opt)| {
            opt.as_ref().map(|opt| (&*el.name, opt.as_ref()))
        })
    }
}

impl PartialEq for SparseObject {
    fn eq(&self, other: &SparseObject) -> bool {
        let mut num = 0;
        let o = &other.shape.0.elements;
        for (el, value) in self.shape.0.elements.iter().zip(&self.fields) {
            if let Some(value) = value {
                num += 1;
                if let Some(pos) = o.iter().position(|e| e.name == el.name) {
                    if other.fields[pos].as_ref() != Some(value) {
                        return false;
                    }
                }
            }
        }
        let other_num = other.fields.iter().filter(|e| e.is_some()).count();
        return num == other_num;
    }
}

impl From<String> for Value {
    fn from(s: String) -> Value {
        Value::Str(s)
    }
}

impl From<i16> for Value {
    fn from(s: i16) -> Value {
        Value::Int16(s)
    }
}

impl From<i32> for Value {
    fn from(s: i32) -> Value {
        Value::Int32(s)
    }
}

impl From<i64> for Value {
    fn from(s: i64) -> Value {
        Value::Int64(s)
    }
}