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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
use crate::schema::IntOptions;
use crate::schema::TextOptions;

use crate::schema::FieldType;
use serde::de::{self, MapAccess, Visitor};
use serde::ser::SerializeStruct;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::fmt;

/// A `FieldEntry` represents a field and its configuration.
/// `Schema` are a collection of `FieldEntry`
///
/// It consists of
/// - a field name
/// - a field type, itself wrapping up options describing
/// how the field should be indexed.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct FieldEntry {
    name: String,
    field_type: FieldType,
}

impl FieldEntry {
    /// Creates a new u64 field entry in the schema, given
    /// a name, and some options.
    pub fn new_text(field_name: String, text_options: TextOptions) -> FieldEntry {
        FieldEntry {
            name: field_name,
            field_type: FieldType::Str(text_options),
        }
    }

    /// Creates a new u64 field entry in the schema, given
    /// a name, and some options.
    pub fn new_u64(field_name: String, field_type: IntOptions) -> FieldEntry {
        FieldEntry {
            name: field_name,
            field_type: FieldType::U64(field_type),
        }
    }

    /// Creates a new i64 field entry in the schema, given
    /// a name, and some options.
    pub fn new_i64(field_name: String, field_type: IntOptions) -> FieldEntry {
        FieldEntry {
            name: field_name,
            field_type: FieldType::I64(field_type),
        }
    }

    /// Creates a new date field entry in the schema, given
    /// a name, and some options.
    pub fn new_date(field_name: String, field_type: IntOptions) -> FieldEntry {
        FieldEntry {
            name: field_name,
            field_type: FieldType::Date(field_type),
        }
    }

    /// Creates a field entry for a facet.
    pub fn new_facet(field_name: String) -> FieldEntry {
        FieldEntry {
            name: field_name,
            field_type: FieldType::HierarchicalFacet,
        }
    }

    /// Creates a field entry for a bytes field
    pub fn new_bytes(field_name: String) -> FieldEntry {
        FieldEntry {
            name: field_name,
            field_type: FieldType::Bytes,
        }
    }

    /// Returns the name of the field
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Returns the field type
    pub fn field_type(&self) -> &FieldType {
        &self.field_type
    }

    /// Returns true iff the field is indexed
    pub fn is_indexed(&self) -> bool {
        match self.field_type {
            FieldType::Str(ref options) => options.get_indexing_options().is_some(),
            FieldType::U64(ref options)
            | FieldType::I64(ref options)
            | FieldType::Date(ref options) => options.is_indexed(),
            FieldType::HierarchicalFacet => true,
            FieldType::Bytes => false,
        }
    }

    /// Returns true iff the field is a int (signed or unsigned) fast field
    pub fn is_int_fast(&self) -> bool {
        match self.field_type {
            FieldType::U64(ref options) | FieldType::I64(ref options) => options.is_fast(),
            _ => false,
        }
    }

    /// Returns true iff the field is stored
    pub fn is_stored(&self) -> bool {
        match self.field_type {
            FieldType::U64(ref options)
            | FieldType::I64(ref options)
            | FieldType::Date(ref options) => options.is_stored(),
            FieldType::Str(ref options) => options.is_stored(),
            // TODO make stored hierarchical facet optional
            FieldType::HierarchicalFacet => true,
            FieldType::Bytes => false,
        }
    }
}

impl Serialize for FieldEntry {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut s = serializer.serialize_struct("field_entry", 3)?;
        s.serialize_field("name", &self.name)?;

        match self.field_type {
            FieldType::Str(ref options) => {
                s.serialize_field("type", "text")?;
                s.serialize_field("options", options)?;
            }
            FieldType::U64(ref options) => {
                s.serialize_field("type", "u64")?;
                s.serialize_field("options", options)?;
            }
            FieldType::I64(ref options) => {
                s.serialize_field("type", "i64")?;
                s.serialize_field("options", options)?;
            }
            FieldType::Date(ref options) => {
                s.serialize_field("type", "date")?;
                s.serialize_field("options", options)?;
            }
            FieldType::HierarchicalFacet => {
                s.serialize_field("type", "hierarchical_facet")?;
            }
            FieldType::Bytes => {
                s.serialize_field("type", "bytes")?;
            }
        }

        s.end()
    }
}

impl<'de> Deserialize<'de> for FieldEntry {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        #[derive(Deserialize)]
        #[serde(field_identifier, rename_all = "lowercase")]
        enum Field {
            Name,
            Type,
            Options,
        };

        const FIELDS: &[&str] = &["name", "type", "options"];

        struct FieldEntryVisitor;

        impl<'de> Visitor<'de> for FieldEntryVisitor {
            type Value = FieldEntry;

            fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
                formatter.write_str("struct FieldEntry")
            }

            fn visit_map<V>(self, mut map: V) -> Result<FieldEntry, V::Error>
            where
                V: MapAccess<'de>,
            {
                let mut name = None;
                let mut ty = None;
                let mut field_type = None;
                while let Some(key) = map.next_key()? {
                    match key {
                        Field::Name => {
                            if name.is_some() {
                                return Err(de::Error::duplicate_field("name"));
                            }
                            name = Some(map.next_value()?);
                        }
                        Field::Type => {
                            if ty.is_some() {
                                return Err(de::Error::duplicate_field("type"));
                            }
                            let type_string = map.next_value()?;
                            match type_string {
                                "hierarchical_facet" => {
                                    field_type = Some(FieldType::HierarchicalFacet);
                                }
                                "bytes" => {
                                    field_type = Some(FieldType::Bytes);
                                }
                                "text" | "u64" | "i64" | "date" => {
                                    // These types require additional options to create a field_type
                                }
                                _ => panic!("unhandled type"),
                            }
                            ty = Some(type_string);
                        }
                        Field::Options => match ty {
                            None => {
                                let msg = "The `type` field must be \
                                           specified before `options`";
                                return Err(de::Error::custom(msg));
                            }
                            Some(ty) => match ty {
                                "text" => field_type = Some(FieldType::Str(map.next_value()?)),
                                "u64" => field_type = Some(FieldType::U64(map.next_value()?)),
                                "i64" => field_type = Some(FieldType::I64(map.next_value()?)),
                                "date" => field_type = Some(FieldType::Date(map.next_value()?)),
                                _ => {
                                    let msg = format!("Unrecognised type {}", ty);
                                    return Err(de::Error::custom(msg));
                                }
                            },
                        },
                    }
                }

                let name = name.ok_or_else(|| de::Error::missing_field("name"))?;
                ty.ok_or_else(|| de::Error::missing_field("ty"))?;
                let field_type = field_type.ok_or_else(|| de::Error::missing_field("options"))?;

                Ok(FieldEntry { name, field_type })
            }
        }

        deserializer.deserialize_struct("field_entry", FIELDS, FieldEntryVisitor)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::schema::TEXT;
    use serde_json;

    #[test]
    fn test_json_serialization() {
        let field_value = FieldEntry::new_text(String::from("title"), TEXT);

        let expected = r#"{
  "name": "title",
  "type": "text",
  "options": {
    "indexing": {
      "record": "position",
      "tokenizer": "default"
    },
    "stored": false
  }
}"#;
        let field_value_json = serde_json::to_string_pretty(&field_value).unwrap();

        assert_eq!(expected, &field_value_json);

        let field_value: FieldEntry = serde_json::from_str(expected).unwrap();

        assert_eq!("title", field_value.name);

        match field_value.field_type {
            FieldType::Str(_) => assert!(true),
            _ => panic!("expected FieldType::Str"),
        }
    }
}