notmongo 0.1.5

In-process, bad database with an API similar to MongoDB
Documentation
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
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
use crate::{helpers, parsing, FindQuery, Projection, Sort, UpdateQuery};
use bson;
use bson::Bson;
use rand::Rng;
use std::collections::HashMap;
use std::convert::TryFrom;
use std::fs;
use std::path::Path;

pub struct DeleteResult {
    pub n_deleted: usize,
}

pub struct UpdateResult {
    pub matched_count: usize,
    pub modified_count: usize,
    pub upserted_id: Option<Bson>,
}

pub struct InsertOneResult {
    pub inserted_id: Bson,
}

pub struct InsertManyResult {
    pub inserted_ids: Vec<Bson>,
}

pub struct Collection {
    pub documents: Vec<bson::Document>,
}

#[derive(Clone, Copy, PartialEq)]
pub enum Compression {
    None,
    Zip,
}

impl Collection {
    pub fn new_empty() -> Collection {
        Collection {
            documents: Vec::new(),
        }
    }

    fn find_by_id(&self, id: &Bson) -> Option<&bson::Document> {
        self.documents
            .iter()
            .find(|doc| doc.get("_id").unwrap() == id)
    }

    fn new_from_bson(db: &Bson) -> Result<Collection, String> {
        let db = parsing::ensure_is_object(db, "collection root")?;
        let documents = parsing::get_key(db, "documents", "collection documents")?;
        let documents = parsing::ensure_is_array(documents, "collection documents")?;

        let mut result = Collection::new_empty();
        // let mut visited_ids = HashSet::new();

        for document in documents.iter() {
            // Is an object?
            let document = parsing::ensure_is_object(document, "document")?;

            // Make sure the document has an `_id`
            match document.get("_id") {
                Some(id) => id,
                None => {
                    return Err(format!(
                        "Document is missing the `_id` field: {:?}",
                        document
                    ))
                }
            };

            // TODO: Ensure the id is unique. This is nontrivial because BSON
            // values aren't comparable/hashable. Looking up the object via
            // `find_by_id` is possible, but incurs quadratic cost. This is how
            // this function used to be implemented, but real world databases
            // were slowed down FAR too much.
            // if !visited_ids.insert(doc_id) {
            //     return Err(format!(
            //         "Multiple documents share the same `_id` field {:?}",
            //         document
            //     ));
            // }

            // TOOD: Make sure the values are valid ids? Which types does
            // mongodb allow as ids?

            result.documents.push(document.clone());
        }

        Ok(result)
    }

    pub fn new_from_json_string(json: &str) -> Result<Collection, String> {
        let as_json: serde_json::Value = match serde_json::from_str(json) {
            Ok(value) => value,
            Err(_) => {
                return Err("The string is not valid JSON".to_string());
            }
        };

        let as_bson = match bson::Bson::try_from(as_json) {
            Ok(value) => value,
            Err(_) => {
                return Err("The string is valid JSON, but not valid BSON".to_owned());
            }
        };

        Collection::new_from_bson(&as_bson)
    }

    pub fn new_from_json_file<P: AsRef<Path>>(path: P) -> Result<Collection, String> {
        let json_string = match fs::read_to_string(path) {
            std::io::Result::Ok(value) => value,
            std::io::Result::Err(value) => {
                return Err(format!("Failed to read file: {}", value));
            }
        };

        Collection::new_from_json_string(&json_string)
    }

    pub fn dump_to_bson_value(&self) -> bson::Document {
        // Gather all documents
        let mut documents_field = Vec::<Bson>::new();

        for entry in self.documents.iter() {
            documents_field.push(Bson::Document(entry.clone()));
        }

        // Construct the result and return
        bson::doc! {
            "documents": documents_field
        }
    }

    pub fn len(&self) -> usize {
        self.documents.len()
    }

    pub fn is_empty(&self) -> bool {
        self.documents.is_empty()
    }

    /// Recently accessed documents are often soon accessed again. This
    /// function moves them forward in the array so they are found quickly
    /// during linear scans. The exact position is undefined.
    fn optimize_move_document_forward(&mut self, current_index: usize) {
        // Just moving the document to position 0 would make it slow to find the
        // document previously there. This isn't good, because that document was
        // likely put there just recently by this exact optimizaion. So instead,
        // move the document to a random location close to the start, but not
        // actually at the start.
        let mut rng = rand::thread_rng();
        let target_pos = std::cmp::min(rng.gen_range(0..100), self.documents.len() - 1);
        self.documents.swap(current_index, target_pos)
    }

    pub fn count_documents(
        &self,
        filter: &FindQuery,
        skip: usize,
        limit: usize,
    ) -> Result<usize, String> {
        // Never visit more documents than this many
        let max_visit_counter = match limit {
            0 => self.documents.len(),
            value => skip + value,
        };

        // Count the matching documents, respecting the limit
        let mut counter = 0;

        for (ii, document) in self.documents.iter().enumerate() {
            if ii > max_visit_counter {
                break;
            }

            if filter.matches(document) {
                counter += 1;
            }
        }

        // Apply the skip value
        if counter > skip {
            Ok(counter - skip)
        } else {
            Ok(0)
        }
    }

    pub fn delete_many(&mut self, filter: &FindQuery) -> Result<DeleteResult, String> {
        // Remove mismatching documents

        // FIXME there has got to be a better way of doing this.
        // Filter + Collect doesn't work, because the resulting values are
        // references, not proper documents.

        // This method needs to repeatedly move all remaining documents in the
        // array forward.
        let len_before = self.documents.len();
        let mut ii = 0;
        while ii < self.documents.len() {
            if !filter.matches(&self.documents[ii]) {
                ii += 1;
                continue;
            }

            self.documents.remove(ii);
        }

        // Construct the result and return
        return Ok(DeleteResult {
            n_deleted: len_before - self.documents.len(),
        });
    }

    pub fn delete_one(&mut self, filter: &FindQuery) -> Result<DeleteResult, String> {
        // Try to find a matching document
        for (ii, document) in self.documents.iter().enumerate() {
            // Does it match the query?
            if !filter.matches(document) {
                continue;
            }

            // Delete
            self.documents.remove(ii);

            return Ok(DeleteResult { n_deleted: 1 });
        }

        // No matching document found, return
        Ok(DeleteResult { n_deleted: 0 })
    }

    pub fn find(
        &mut self,
        filter: &FindQuery,
        projection: &Projection,
        skip: usize,
        limit: usize,
        sort: &Sort,
    ) -> impl IntoIterator<Item = bson::Document> {
        // Don't copy documents that will be skipped and don't visit more
        // documents than required. Take care not to miss any documents if
        // sorting is used.
        let mut pre_skip;
        let post_skip;
        let max_keep;

        if sort.is_no_op() {
            pre_skip = skip;
            post_skip = 0;
            max_keep = limit;
        } else {
            pre_skip = 0;
            post_skip = skip;
            max_keep = self.documents.len();
        }

        // Find all matching documents
        let mut results = Vec::new();
        for doc_ii in 0..self.documents.len() {
            let doc = &self.documents[doc_ii];

            // Does the document match the query?
            if !filter.matches(doc) {
                continue;
            }

            // Will this document be skipped anyway?
            if pre_skip > 0 {
                pre_skip -= 1;
                continue;
            }

            // Keep the document
            results.push(doc.clone());

            // Move the document forward to accelerate future queries involving
            // it
            self.documents.swap(doc_ii, results.len() - 1);

            // Found the maximum required number of documents
            if results.len() == max_keep {
                break;
            }
        }

        // Sort if required
        if !sort.is_no_op() {
            results.sort_unstable_by(|a, b| sort.compare(&a, &b));
        }

        // Apply the skip value
        results.drain(0..post_skip);

        // Apply the limit
        if limit > 0 {
            results.truncate(limit);
        }

        // Apply the projection
        if !projection.is_keep_all() {
            for document in results.iter_mut() {
                projection.apply_in_place(document);
            }
        }

        // Done
        results
    }

    pub fn find_one(
        &mut self,
        filter: &FindQuery,
        projection: &Projection,
        skip: usize,
        sort: &Sort,
    ) -> Option<bson::Document> {
        let mut iter = self.find(filter, projection, skip, 1, sort).into_iter();

        match iter.next() {
            Some(value) => Some(value.clone()),
            None => None,
        }
    }

    pub fn insert_one(&mut self, mut document: bson::Document) -> Result<InsertOneResult, String> {
        // Add an _id if there is none
        let entry_id = match document.get("_id") {
            None => {
                let id = Bson::ObjectId(bson::oid::ObjectId::new());
                document.insert("_id", id.clone());
                id
            }
            Some(id) => id.clone(),
        };

        // Make sure there are no duplicate IDs
        match self.find_by_id(&entry_id) {
            None => {}
            Some(_) => {
                return Err(format!("Duplicate ID found: {:?}", entry_id));
            }
        }

        // Insert & return
        self.documents.push(document);
        self.optimize_move_document_forward(self.documents.len() - 1);

        // Construct the reply and return
        return Ok(InsertOneResult {
            inserted_id: entry_id,
        });
    }

    pub fn insert_many<I: IntoIterator<Item = bson::Document>>(
        &mut self,
        documents: I,
    ) -> Result<InsertManyResult, String> {
        // TODO: The current implementation is inefficient. It iterates over the
        //       entire collection for every inserted element just to make sure
        //       the ids are unique. This could be done in just one iteration
        //       for all documents.

        // Insert all values, remembering the IDs
        let mut ids = Vec::new();

        for document in documents.into_iter() {
            let insert_result = self.insert_one(document)?;
            ids.push(insert_result.inserted_id);
        }

        // Construct the result and return
        return Ok(InsertManyResult { inserted_ids: ids });
    }

    pub fn replace_one(
        &mut self,
        filter: &FindQuery,
        replacement: bson::Document,
        upsert: bool,
    ) -> Result<UpdateResult, String> {
        // Try to find a matching document
        for (ii, document) in self.documents.iter().enumerate() {
            // Does it match the query?
            if !filter.matches(document) {
                continue;
            }

            // Replace it
            // TODO: Verify the document? What if the resulting document causes
            // duplicate ids for example?
            self.documents[ii] = replacement;
            self.optimize_move_document_forward(ii);

            return Ok(UpdateResult {
                matched_count: 1,
                modified_count: 1,
                upserted_id: None,
            });
        }

        // No matching document found, upsert?
        if upsert {
            let insert_result = self.insert_one(replacement)?;
            return Ok(UpdateResult {
                matched_count: 0,
                modified_count: 1,
                upserted_id: Some(insert_result.inserted_id),
            });
        }

        // No matching document found, return
        return Ok(UpdateResult {
            matched_count: 0,
            modified_count: 0,
            upserted_id: None,
        });
    }

    pub fn update_one(
        &mut self,
        filter: &FindQuery,
        update: &UpdateQuery,
        upsert: bool,
    ) -> Result<UpdateResult, String> {
        for (ii, document) in self.documents.iter_mut().enumerate() {
            // Does it match the query?
            if !filter.matches(document) {
                continue;
            }

            // Apply the update
            // TODO: Verify the resulting document?
            // - What if it causes duplicate ids for example
            // - What if the document doesn't have an id at all?
            update.apply_inplace(document);
            self.optimize_move_document_forward(ii);

            return Ok(UpdateResult {
                matched_count: 1,
                modified_count: 1,
                upserted_id: None,
            });
        }

        // No matching document found, upsert?
        if upsert {
            let insert_result = self.insert_one(update.apply_to_empty())?;
            return Ok(UpdateResult {
                matched_count: 0,
                modified_count: 1,
                upserted_id: Some(insert_result.inserted_id),
            });
        }

        // No matching document found, return
        Ok(UpdateResult {
            matched_count: 0,
            modified_count: 0,
            upserted_id: None,
        })
    }

    pub fn update_many(
        &mut self,
        filter: &FindQuery,
        update: &UpdateQuery,
        upsert: bool,
    ) -> Result<UpdateResult, String> {
        let mut result = UpdateResult {
            matched_count: 0,
            modified_count: 0,
            upserted_id: None,
        };

        for document in self.documents.iter_mut() {
            // Does it match the query?
            if !filter.matches(document) {
                continue;
            }
            result.matched_count += 1;

            // Apply the update
            // TODO: Verify the resulting document?
            // - What if it causes duplicate ids for example
            // - What if the document doesn't have an id at all?
            update.apply_inplace(document);
            result.modified_count += 1;
        }

        // No matching document found, upsert?
        if result.matched_count == 0 && upsert {
            let insert_result = self.insert_one(update.apply_to_empty())?;
            return Ok(UpdateResult {
                matched_count: 0,
                modified_count: 1,
                upserted_id: Some(insert_result.inserted_id),
            });
        }

        Ok(result)
    }
}

pub struct Database {
    all_collections: HashMap<String, Collection>,
}

impl Database {
    pub fn new_empty() -> Database {
        Database {
            all_collections: HashMap::new(),
        }
    }

    pub fn new_from_bson_value(db: &Bson) -> Result<Database, String> {
        let db = parsing::ensure_is_object(db, "database root")?;
        let collections = parsing::get_key(db, "collections", "database collections")?;
        let collections = parsing::ensure_is_object(collections, "database collections")?;

        let mut result = Database::new_empty();

        for (name, collection) in collections.iter() {
            result
                .all_collections
                .insert(name.to_string(), Collection::new_from_bson(collection)?);
        }

        Ok(result)
    }

    pub fn new_from_json_string(json: &str) -> Result<Database, String> {
        let as_json: serde_json::Value = match serde_json::from_str(json) {
            Ok(value) => value,
            Err(_) => {
                return Err("The string is not valid JSON".to_string());
            }
        };

        let as_bson = match bson::Bson::try_from(as_json) {
            Ok(value) => value,
            Err(_) => {
                return Err("The string is valid JSON, but not valid BSON".to_owned());
            }
        };

        let res = Database::new_from_bson_value(&as_bson);
        res
    }

    pub fn new_from_bson_file<P: AsRef<Path>>(
        path: P,
        compression: Compression,
    ) -> Result<Database, String> {
        // Read the file into a buffer
        let buffer = helpers::read_compressed_file(path, compression)?;

        // Parse the buffer as BSON
        let as_document = bson::Document::from_reader(buffer.as_slice())
            .map_err(|_| "The BSON file is not valid BSON".to_string())?;

        let as_bson = bson::Bson::try_from(as_document).unwrap();

        // Load the database from the BSON
        Database::new_from_bson_value(&as_bson)
    }

    pub fn new_from_json_file<P: AsRef<Path>>(
        path: P,
        compression: Compression,
    ) -> Result<Database, String> {
        // Read the file into a string
        let utf8_string = helpers::read_compressed_file(path, compression)?;
        let json_string = String::from_utf8(utf8_string)
            .map_err(|_| "The JSON file is not valid UTF-8..".to_string())?;

        // Load the database from the string
        Database::new_from_json_string(&json_string)
    }

    pub fn dump_to_bson_value(&self) -> bson::Document {
        // Convert all collections
        let mut collections_field = bson::Document::new();

        for entry in self.all_collections.iter() {
            // No point in serializing empty collections. These shouldn't even
            // exist as far as MongoDB is concerned.
            if entry.1.is_empty() {
                continue;
            }

            collections_field.insert(entry.0.clone(), entry.1.dump_to_bson_value());
        }

        // Construct the result and return
        bson::doc! {
            "collections": collections_field
        }
    }

    pub fn dump_to_bson_file<P: AsRef<Path>>(
        &self,
        path: &P,
        n_backups: u32,
        compression: Compression,
    ) -> Result<(), String> {
        helpers::dump_to_bson_file(
            &self.dump_to_bson_value().into(),
            path,
            n_backups,
            compression,
        )
    }

    pub fn dump_to_json_file<P: AsRef<Path>>(
        &self,
        path: &P,
        relaxed: bool,
        format: bool,
        n_backups: u32,
        compression: Compression,
    ) -> Result<(), String> {
        helpers::dump_to_json_file(
            self.dump_to_bson_value().into(),
            relaxed,
            format,
            path,
            n_backups,
            compression,
        )
    }

    pub fn dump_to_json_string(&self, relaxed: bool, format: bool) -> Result<String, String> {
        helpers::dump_to_json_string(self.dump_to_bson_value().into(), relaxed, format)
    }

    pub fn collection_mut(&mut self, name: &str) -> &mut Collection {
        // Reuse any existing collection, or create a new one of none is
        // present.
        return self
            .all_collections
            .entry(name.to_string())
            .or_insert(Collection::new_empty());
    }

    pub fn drop_collection(&mut self, name: &str) -> bool {
        // FIXME: Note that this will return `true` for empty collections. This
        //        is a bit weird, because saving, then reloading will wipe those
        //        collections. Empty collections aren't really supposed to exist
        //        in MongoDB...
        //
        // -> Check what the real mongo does in this case
        return self.all_collections.remove(name).is_some();
    }

    pub fn n_collections(&self) -> usize {
        self.all_collections.len()
    }

    pub fn collection_names(&self) -> impl IntoIterator<Item = String> {
        let as_vector: Vec<String> = self.all_collections.keys().cloned().collect();
        as_vector
    }
}