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
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
//! B-tree indexing.

use crate::document::Document;
use crate::query::ConstraintDocument;
use crate::query::FieldPath;
use crate::value::Value;

use serde::{Deserialize, Serialize};

use std::collections::HashMap;
use std::ops::Bound;

#[derive(Debug, PartialEq, Eq, Hash, Clone, Serialize, Deserialize)]
pub struct FieldSpec {
    field_path: FieldPath,
    default: Value,
}

/// Store the field path and default value used for a field.
impl FieldSpec {
    pub fn new(field_path: FieldPath, default: Value) -> FieldSpec {
        FieldSpec {
            field_path: field_path,
            default: default,
        }
    }

    pub fn get_field_path(&self) -> &FieldPath {
        &self.field_path
    }

    pub fn get_default(&self) -> &Value {
        &self.default
    }
}

/// Store the fields used for an Index.
#[derive(Debug, PartialEq, Eq, Hash, Clone, Serialize, Deserialize)]
pub struct IndexSchema {
    fields: Vec<FieldSpec>,
}

impl IndexSchema {
    pub fn new(fields: Vec<FieldSpec>) -> IndexSchema {
        IndexSchema { fields: fields }
    }

    pub fn get_fields(&self) -> Vec<FieldPath> {
        self.fields.iter().map(|x| x.field_path.clone()).collect()
    }

    pub fn get_field_specs(&self) -> &Vec<FieldSpec> {
        &self.fields
    }

    /// Convert the Index Schema into a HashMap.
    pub fn get_as_hashmap(&self) -> HashMap<&FieldPath, &Value> {
        self.get_field_specs()
            .iter()
            .map(|x| (x.get_field_path(), x.get_default()))
            .collect()
    }

    /// Check if the Field Path is in the Index Schema and if it is, whether the
    /// default values have the same variant.
    ///
    /// Return false if the Field Path is not in the Index Schema or if the default values have the
    /// same variant.
    /// Return true if the default values do not have the same variant.
    fn is_field_spec_conflicting(
        &self,
        field_spec: &FieldSpec,
        index_schema: &HashMap<&FieldPath, &Value>,
    ) -> bool {
        !match index_schema.get(field_spec.get_field_path()) {
            Some(value) => field_spec.get_default().is_variant_equal(value),
            None => true,
        }
    }

    /// Compare the current Index Schema with another Index Schema.
    /// Check if any shared fields have conflicting Value variants (e.g. different types).
    pub fn is_conflicting(&self, index_schema: &IndexSchema) -> bool {
        let index_schema_as_hashmap = index_schema.get_as_hashmap();
        for field_spec in self.get_field_specs() {
            if self.is_field_spec_conflicting(&field_spec, &index_schema_as_hashmap) {
                return true;
            }
        }

        false
    }

    /// Create an Index from the provided Document.
    pub fn create_index(&self, doc: &Document) -> Option<Index> {
        // Extract the Values from the Document
        let mut values = Vec::new();
        for spec in self.get_field_specs() {
            let doc_value = doc.get_or_default(spec.get_field_path(), spec.get_default().clone());

            // Check if type of the Document Value matches the type of the default Value
            // If not, the Index is invalid (mismatched types)
            if !spec.default.is_variant_equal(&doc_value) {
                return Option::None;
            }
            values.push(doc_value);
        }

        Option::from(Index::new(values))
    }

    // ToDo: Decide if public or private
    /// Count the number of matched index fields in the query fields.
    pub fn get_num_matched_fields(&self, query_fields: &HashMap<&FieldPath, &Value>) -> i32 {
        let index_fields = self.get_field_specs();

        // Check that each constraint doesn't conflict with the index fields
        // and that each index field exists in the constraints
        let mut cur_matched = 0;
        for field_spec in index_fields {
            if !self.is_field_spec_conflicting(&field_spec, query_fields)
                && query_fields.contains_key(field_spec.get_field_path())
            {
                cur_matched += 1;
            }
        }

        cur_matched
    }

    /// Calculate the non-overlapping b-tree query ranges for a ConstraintDocument.
    pub fn generate_btree_ranges(
        &self,
        constraints: &ConstraintDocument,
    ) -> Vec<(Bound<Index>, Bound<Index>)> {
        // Loop through each field of Index, in order
        // Convert each constraint to a range or set of ranges on that field
        let field_ranges = self
            .get_fields()
            .iter()
            .map(|field_path| constraints.get(field_path).unwrap().generate_value_ranges())
            .collect();

        // Generate all combinations of one range from each field
        Self::generate_combinations(&field_ranges, 0)
    }

    // Helper function to generate combinations for generate_btree_ranges.
    // The base case is messy but it works.
    fn generate_combinations(
        field_ranges: &Vec<Vec<(Bound<Value>, Bound<Value>)>>,
        i: usize,
    ) -> Vec<(Bound<Index>, Bound<Index>)> {
        assert!(i <= field_ranges.len() - 1);

        // Base case: convert each field/value range into a singleton index range
        if i == field_ranges.len() - 1 {
            return field_ranges
                .last()
                .unwrap()
                .iter()
                .map(|field_range| match field_range {
                    (Bound::Included(value_low), Bound::Included(value_high)) => (
                        Bound::Included(Index::new(vec![value_low.clone()])),
                        Bound::Included(Index::new(vec![value_high.clone()])),
                    ),
                    _ => panic!("non-inclusive value ranges"),
                })
                .collect();
        }

        let next_combinations_indices = Self::generate_combinations(field_ranges, i + 1);
        let next_combinations =
            next_combinations_indices
                .iter()
                .map(|index_range| match index_range {
                    (Bound::Included(index_range_low), Bound::Included(index_range_high)) => {
                        (index_range_low.get_values(), index_range_high.get_values())
                    }
                    _ => panic!("invalid index range"),
                });

        let mut combinations = Vec::new();
        for (value_low, value_high) in &field_ranges[i] {
            // For now, assert these bounds are inclusive; they should always be inclusive
            let (value_low, value_high) = match (value_low, value_high) {
                (Bound::Included(value_low), Bound::Included(value_high)) => {
                    (value_low, value_high)
                }
                _ => panic!("non-inclusive value ranges"),
            };

            for (next_range_low, next_range_high) in next_combinations.clone() {
                // Create new range ((value_low:next_range_low), (value_high:next_range_high))
                let mut low_range = vec![value_low.clone()];
                low_range.append(&mut next_range_low.clone());

                let mut high_range = vec![value_high.clone()];
                high_range.append(&mut next_range_high.clone());

                combinations.push((
                    Bound::Included(Index::new(low_range)),
                    Bound::Included(Index::new(high_range)),
                ));
            }
        }
        combinations
    }
}

/// Store the values for the fields for a particular document.
#[derive(Debug, Clone, PartialOrd, Ord, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Index {
    values: Vec<Value>,
}

impl Index {
    fn new(values: Vec<Value>) -> Index {
        Index { values: values }
    }

    fn get_values(&self) -> &Vec<Value> {
        &self.values
    }
}

// This needs to be in this module since Index::new() is private
#[cfg(test)]
pub mod tests {
    use super::*;
    use crate::query::Constraint;
    use std::collections::{HashMap, HashSet};

    type IndexRange = (Bound<Index>, Bound<Index>);
    fn are_ranges_equal_unordered(v1: &Vec<IndexRange>, v2: &Vec<IndexRange>) -> bool {
        let hm1 = v1
            .iter()
            .map(|range| range.clone())
            .collect::<HashSet<IndexRange>>();

        let hm2 = v2
            .iter()
            .map(|range| range.clone())
            .collect::<HashSet<IndexRange>>();

        hm1 == hm2
    }

    // Test IndexSchema::generate_btree_ranges() and IndexSchema::generate_combinations().
    #[test]
    fn test_generate_btree_ranges_simple() {
        let index_schema = IndexSchema::new(vec![FieldSpec::new(
            vec![String::from("a")],
            Value::Int32(0),
        )]);

        let constraint = &HashMap::from([(
            vec![String::from("a")],
            Constraint::LessThan(Value::Int32(2)),
        )]);

        assert!(are_ranges_equal_unordered(
            &index_schema.generate_btree_ranges(constraint),
            &vec![(
                Bound::Included(Index::new(vec![Value::Int32(0).get_min_value()])),
                Bound::Included(Index::new(vec![Value::Int32(2)]))
            )]
        ));
    }

    // Test generate_btree_ranges() on multi-field indices.
    #[test]
    fn test_generate_btree_ranges_multi() {
        let index_schema = IndexSchema::new(vec![
            FieldSpec::new(vec![String::from("a")], Value::Int32(0)),
            FieldSpec::new(vec![String::from("b")], Value::Int32(0)),
            FieldSpec::new(vec![String::from("c")], Value::Int32(0)),
        ]);

        let constraint = &HashMap::from([
            (
                vec![String::from("a")],
                Constraint::LessThan(Value::Int32(2)),
            ),
            (vec![String::from("b")], Constraint::Equals(Value::Int32(5))),
            (
                vec![String::from("c")],
                Constraint::GreaterThan(Value::Int32(4)),
            ),
        ]);

        assert!(are_ranges_equal_unordered(
            &index_schema.generate_btree_ranges(constraint),
            &vec![(
                Bound::Included(Index::new(vec![
                    Value::Int32(0).get_min_value(),
                    Value::Int32(5),
                    Value::Int32(4)
                ])),
                Bound::Included(Index::new(vec![
                    Value::Int32(2),
                    Value::Int32(5),
                    Value::Int32(0).get_max_value()
                ]))
            )]
        ));
    }

    // Test conjunction btree range generation
    #[test]
    fn test_generate_btree_ranges_conj() {
        let index_schema = IndexSchema::new(vec![FieldSpec::new(
            vec![String::from("a")],
            Value::Int32(0),
        )]);

        let constraint = &HashMap::from([(
            vec![String::from("a")],
            Constraint::And(
                Box::new(Constraint::GreaterThan(Value::Int32(-0))),
                Box::new(Constraint::LessThan(Value::Int32(3))),
            ),
        )]);

        assert!(are_ranges_equal_unordered(
            &index_schema.generate_btree_ranges(constraint),
            &vec![(
                Bound::Included(Index::new(vec![Value::Int32(0)])),
                Bound::Included(Index::new(vec![Value::Int32(3)])),
            )]
        ));
    }

    // Test non-intersecting conjunction (empty set)
    #[test]
    fn test_generate_btree_ranges_conj_empty() {
        let index_schema = IndexSchema::new(vec![FieldSpec::new(
            vec![String::from("a")],
            Value::Int32(0),
        )]);

        let constraint = &HashMap::from([(
            vec![String::from("a")],
            Constraint::And(
                Box::new(Constraint::GreaterThan(Value::Int32(3))),
                Box::new(Constraint::LessThan(Value::Int32(0))),
            ),
        )]);

        assert!(are_ranges_equal_unordered(
            &index_schema.generate_btree_ranges(constraint),
            &vec![]
        ));
    }

    // Test disjunction btree range generation
    #[test]
    fn test_generate_btree_ranges_disj() {
        let index_schema = IndexSchema::new(vec![FieldSpec::new(
            vec![String::from("a")],
            Value::Int32(0),
        )]);

        let constraint = &HashMap::from([(
            vec![String::from("a")],
            Constraint::Or(
                Box::new(Constraint::GreaterThan(Value::Int32(3))),
                Box::new(Constraint::LessThan(Value::Int32(0))),
            ),
        )]);

        assert!(are_ranges_equal_unordered(
            &index_schema.generate_btree_ranges(constraint),
            &vec![
                (
                    Bound::Included(Index::new(vec![Value::Int32(3)])),
                    Bound::Included(Index::new(vec![Value::Int32(0).get_max_value()])),
                ),
                (
                    Bound::Included(Index::new(vec![Value::Int32(0).get_min_value()])),
                    Bound::Included(Index::new(vec![Value::Int32(0)])),
                ),
            ]
        ));
    }

    // Test combining overlapping ranges (i.e., double-counting)
    #[test]
    fn test_generate_btree_ranges_disj_overlap() {
        let index_schema = IndexSchema::new(vec![FieldSpec::new(
            vec![String::from("a")],
            Value::Int32(0),
        )]);

        let constraint = &HashMap::from([(
            vec![String::from("a")],
            Constraint::Or(
                Box::new(Constraint::LessThan(Value::Int32(3))),
                Box::new(Constraint::GreaterThan(Value::Int32(0))),
            ),
        )]);

        assert!(are_ranges_equal_unordered(
            &index_schema.generate_btree_ranges(constraint),
            &vec![(
                Bound::Included(Index::new(vec![Value::Int32(0).get_min_value()])),
                Bound::Included(Index::new(vec![Value::Int32(0).get_max_value()])),
            )]
        ));
    }

    // Test combining non-overlapping ranges into DNF.
    #[test]
    fn test_generate_btree_ranges_dnf() {
        let index_schema = IndexSchema::new(vec![FieldSpec::new(
            vec![String::from("a")],
            Value::Int32(0),
        )]);

        let constraint = &HashMap::from([(
            vec![String::from("a")],
            Constraint::Or(
                Box::new(Constraint::And(
                    Box::new(Constraint::LessThan(Value::Int32(10))),
                    Box::new(Constraint::GreaterThan(Value::Int32(5))),
                )),
                Box::new(Constraint::LessThan(Value::Int32(0))),
            ),
        )]);

        assert!(are_ranges_equal_unordered(
            &index_schema.generate_btree_ranges(constraint),
            &vec![
                (
                    Bound::Included(Index::new(vec![Value::Int32(5)])),
                    Bound::Included(Index::new(vec![Value::Int32(10)])),
                ),
                (
                    Bound::Included(Index::new(vec![Value::Int32(0).get_min_value()])),
                    Bound::Included(Index::new(vec![Value::Int32(0)])),
                ),
            ]
        ));
    }

    // Test multi-index fields with disjoint ranges.
    #[test]
    fn test_generate_btree_ranges_complex() {
        let index_schema = IndexSchema::new(vec![
            FieldSpec::new(vec![String::from("a")], Value::Int32(0)),
            FieldSpec::new(vec![String::from("b")], Value::Int32(0)),
            FieldSpec::new(vec![String::from("c")], Value::Int32(0)),
        ]);

        let constraint = &HashMap::from([
            (
                vec![String::from("a")],
                Constraint::Or(
                    Box::new(Constraint::LessThan(Value::Int32(2))),
                    Box::new(Constraint::GreaterThan(Value::Int32(8))),
                ),
            ),
            (
                vec![String::from("b")],
                Constraint::Or(
                    Box::new(Constraint::Equals(Value::Int32(5))),
                    Box::new(Constraint::LessThan(Value::Int32(3))),
                ),
            ),
            (
                vec![String::from("c")],
                Constraint::And(
                    Box::new(Constraint::GreaterThan(Value::Int32(4))),
                    Box::new(Constraint::LessThan(Value::Int32(9))),
                ),
            ),
        ]);

        assert!(are_ranges_equal_unordered(
            &index_schema.generate_btree_ranges(constraint),
            &vec![
                (
                    Bound::Included(Index::new(vec![
                        Value::Int32(0).get_min_value(),
                        Value::Int32(5),
                        Value::Int32(4),
                    ])),
                    Bound::Included(Index::new(vec![
                        Value::Int32(2),
                        Value::Int32(5),
                        Value::Int32(9),
                    ]))
                ),
                (
                    Bound::Included(Index::new(vec![
                        Value::Int32(0).get_min_value(),
                        Value::Int32(0).get_min_value(),
                        Value::Int32(4),
                    ])),
                    Bound::Included(Index::new(vec![
                        Value::Int32(2),
                        Value::Int32(3),
                        Value::Int32(9),
                    ]))
                ),
                (
                    Bound::Included(Index::new(vec![
                        Value::Int32(8),
                        Value::Int32(5),
                        Value::Int32(4),
                    ])),
                    Bound::Included(Index::new(vec![
                        Value::Int32(0,).get_max_value(),
                        Value::Int32(5,),
                        Value::Int32(9,),
                    ]))
                ),
                (
                    Bound::Included(Index::new(vec![
                        Value::Int32(8),
                        Value::Int32(0).get_min_value(),
                        Value::Int32(4),
                    ])),
                    Bound::Included(Index::new(vec![
                        Value::Int32(0).get_max_value(),
                        Value::Int32(3),
                        Value::Int32(9),
                    ]))
                )
            ]
        ));
    }
}