keepass 0.13.3

KeePass .kdbx database file parser
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
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
use std::{
    collections::{HashMap, HashSet},
    ops::{Deref, DerefMut},
};

use thiserror::Error;
use uuid::Uuid;

use crate::{
    db::{
        CustomDataItem, CustomIcon, CustomIconId, CustomIconMut, CustomIconNotFoundError, CustomIconRef, Entry,
        EntryId, EntryMut, EntryRef, Icon, Times,
    },
    Database,
};

/// Unique identifier for a [Group]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serialization", derive(serde::Serialize))]
pub struct GroupId(Uuid);

impl GroupId {
    pub(crate) fn new() -> Self {
        Self(Uuid::new_v4())
    }

    /// Build a `GroupId` from an existing [Uuid].
    ///
    /// Useful when a group's identifier needs to be pinned (e.g. test fixtures or migrations).
    /// Pair with [Group::add_group_with_id][GroupMut::add_group_with_id] to insert
    /// a group under a chosen identifier.
    pub const fn from_uuid(uuid: Uuid) -> Self {
        Self(uuid)
    }

    /// Get the Uuid contained inside
    pub fn uuid(&self) -> Uuid {
        self.0
    }
}

impl From<Uuid> for GroupId {
    fn from(uuid: Uuid) -> Self {
        Self::from_uuid(uuid)
    }
}

impl std::fmt::Display for GroupId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

/// A database group with child groups and entries
#[derive(Debug, Eq, PartialEq, Clone)]
#[cfg_attr(feature = "serialization", derive(serde::Serialize))]
pub struct Group {
    /// The unique identifier of the group
    pub(crate) id: GroupId,

    /// The unique identifier for the parent group
    pub(crate) parent: Option<GroupId>,

    /// The name of the group
    pub name: String,

    /// Notes for the group
    pub notes: Option<String>,

    /// The list of tags for this group
    pub tags: Vec<String>,

    /// Icon for the group
    pub(crate) icon: Option<Icon>,

    /// The list of child group identifiers
    pub(crate) groups: HashSet<GroupId>,

    /// The list of entry identifiers directly under this group
    pub(crate) entries: HashSet<EntryId>,

    /// The list of time fields for this group
    pub times: Times,

    /// Custom Data
    pub custom_data: HashMap<String, CustomDataItem>,

    /// Whether the group is expanded in the user interface
    pub is_expanded: bool,

    /// Default autotype sequence
    pub default_autotype_sequence: Option<String>,

    /// Whether autotype is enabled
    pub enable_autotype: Option<bool>,

    /// Whether searching is enabled
    pub enable_searching: Option<bool>,

    /// UUID for the last top visible entry
    pub(crate) last_top_visible_entry: Option<EntryId>,

    pub(crate) previous_parent_group: Option<GroupId>,
}

impl Group {
    /// Get the unique identifier for this group
    pub fn id(&self) -> GroupId {
        self.id
    }

    pub(crate) fn new(parent: Option<GroupId>) -> Group {
        Group {
            id: GroupId::new(),
            parent,
            name: String::new(),
            notes: None,
            tags: Vec::new(),
            icon: None,
            groups: HashSet::new(),
            entries: HashSet::new(),
            times: Times::new(),
            custom_data: HashMap::new(),
            is_expanded: true,
            default_autotype_sequence: None,
            enable_autotype: None,
            enable_searching: None,
            last_top_visible_entry: None,
            previous_parent_group: None,
        }
    }

    pub(crate) fn with_id(id: GroupId, parent: Option<GroupId>) -> Group {
        Group {
            id,
            parent,
            name: String::new(),
            notes: None,
            tags: Vec::new(),
            icon: None,
            groups: HashSet::new(),
            entries: HashSet::new(),
            times: Times::new(),
            custom_data: HashMap::new(),
            is_expanded: true,
            default_autotype_sequence: None,
            enable_autotype: None,
            enable_searching: None,
            last_top_visible_entry: None,
            previous_parent_group: None,
        }
    }

    /// Get an iterator over the IDs of all contained groups
    pub fn group_ids(&self) -> impl Iterator<Item = GroupId> + '_ {
        self.groups.iter().cloned()
    }

    /// Get an iterator over the IDs of all contained entries
    pub fn entry_ids(&self) -> impl Iterator<Item = EntryId> + '_ {
        self.entries.iter().cloned()
    }

    /// Get a reference to the icon of this group, if any
    pub fn icon(&self) -> Option<&Icon> {
        self.icon.as_ref()
    }
}

/// Immutable reference to a [Group]. Implements [Deref] to [&Group][Group].
#[derive(Clone)]
pub struct GroupRef<'a> {
    database: &'a crate::db::Database,
    id: GroupId,
}

impl GroupRef<'_> {
    pub(crate) fn new(database: &Database, id: GroupId) -> GroupRef<'_> {
        GroupRef { database, id }
    }

    /// Get a contained group by ID
    pub fn group(&self, id: GroupId) -> Option<GroupRef<'_>> {
        self.groups
            .contains(&id)
            .then(move || GroupRef::new(self.database, id))
    }

    /// Get a contained entry by ID
    pub fn entry(&self, id: EntryId) -> Option<EntryRef<'_>> {
        self.entries
            .contains(&id)
            .then(move || EntryRef::new(self.database, id))
    }

    /// Get an iterator over all contained groups
    pub fn groups(&self) -> impl Iterator<Item = GroupRef<'_>> + '_ {
        self.groups
            .iter()
            .map(move |id| GroupRef::new(self.database, *id))
    }

    /// Get an iterator over all contained entries
    pub fn entries(&self) -> impl Iterator<Item = EntryRef<'_>> + '_ {
        self.entries
            .iter()
            .map(move |id| EntryRef::new(self.database, *id))
    }

    /// Find a contained group by name, case-insensitively.
    pub fn group_by_name(&self, name: &str) -> Option<GroupRef<'_>> {
        self.groups().find(|g| g.name.eq_ignore_ascii_case(name))
    }

    /// Find a contained entry by title, case-insensitively.
    pub fn entry_by_name(&self, title: &str) -> Option<EntryRef<'_>> {
        self.entries().find(|e| {
            e.get(crate::db::fields::TITLE)
                .is_some_and(|t| t.eq_ignore_ascii_case(title))
        })
    }

    /// Find a contained group by a path of names, case-insensitively.
    pub fn group_by_path(&self, path: &[&str]) -> Option<GroupRef<'_>> {
        let mut current = self.id;

        for part in path {
            current = self
                .database
                .groups
                .get(&current)?
                .groups
                .iter()
                .filter_map(|id| self.database.groups.get(id))
                .find(|g| g.name.eq_ignore_ascii_case(part))?
                .id;
        }

        Some(GroupRef::new(self.database, current))
    }

    /// Get the database this group belongs to
    pub fn database(&self) -> &Database {
        self.database
    }

    /// Get a reference to the parent group, if any
    pub fn parent(&self) -> Option<GroupRef<'_>> {
        self.parent.map(|id| GroupRef::new(self.database, id))
    }

    /// Get a reference to the previous parent group, if any
    pub fn previous_parent(&self) -> Option<GroupRef<'_>> {
        self.previous_parent_group
            .and_then(|id| self.database().group(id))
    }

    /// Get a reference to the custom icon of this group, if it has one and it is a custom icon
    pub fn custom_icon(&self) -> Option<CustomIconRef<'_>> {
        if let Some(Icon::Custom(cid)) = self.icon {
            Some(CustomIconRef::new(self.database, cid))
        } else {
            None
        }
    }
}

impl Deref for GroupRef<'_> {
    type Target = Group;

    #[allow(clippy::expect_used, clippy::missing_panics_doc)] // group existence is guaranteed
    fn deref(&self) -> &Self::Target {
        self.database
            .groups
            .get(&self.id)
            .expect("GroupRef points to a non-existing group")
    }
}

/// Mutable reference to a [Group]. Implements [DerefMut] to [&mut Group][Group]
pub struct GroupMut<'a> {
    database: &'a mut crate::db::Database,
    id: GroupId,
}

impl GroupMut<'_> {
    pub(crate) fn new(database: &mut Database, id: GroupId) -> GroupMut<'_> {
        GroupMut { database, id }
    }

    /// Get an immutable reference to this group
    pub fn as_ref(&self) -> GroupRef<'_> {
        GroupRef::new(self.database, self.id)
    }

    /// Get a mutable reference to a contained group by ID
    pub fn group_mut(&mut self, id: GroupId) -> Option<GroupMut<'_>> {
        self.groups
            .contains(&id)
            .then(move || GroupMut::new(self.database, id))
    }

    /// Get a mutable reference to a contained entry by ID
    pub fn entry_mut(&mut self, id: EntryId) -> Option<EntryMut<'_>> {
        self.entries
            .contains(&id)
            .then(move || EntryMut::new(self.database, id))
    }

    /// Convenience method to edit the group in a closure.
    pub fn edit(&mut self, f: impl FnOnce(&mut GroupMut<'_>)) -> &mut Self {
        f(self);
        self
    }

    /// Convenience method to edit the group in a closure that tracks changes.
    pub fn edit_tracking(&mut self, f: impl FnOnce(&mut GroupTrack<'_>)) -> &mut Self {
        let mut tracker = self.track_changes();
        f(&mut tracker);
        tracker.as_mut().times.last_modification = Some(Times::now());
        self
    }

    /// Adds a new subgroup to this group and returns a mutable reference to it.
    #[allow(clippy::missing_panics_doc)]
    pub fn add_group(&mut self) -> GroupMut<'_> {
        let new_group = Group::new(Some(self.id));
        let id = new_group.id;

        // A freshly-generated v4 UUID does not collide with an existing identifier in any
        // realistic scenario, so the duplicate check inside `add_group_with_id` cannot trip
        // here.
        #[allow(clippy::expect_used)] // fresh v4 UUID cannot collide
        self.add_group_with_id(id)
            .expect("fresh v4 UUID cannot collide with an existing group identifier")
    }

    /// Adds a new entry to this group and returns a mutable reference to it.
    #[allow(clippy::missing_panics_doc)]
    pub fn add_entry(&mut self) -> EntryMut<'_> {
        let new_entry = Entry::new(self.id);
        let id = new_entry.id();

        // A freshly-generated v4 UUID does not collide with an existing identifier in any
        // realistic scenario, so the duplicate check inside `add_entry_with_id` cannot trip
        // here.
        #[allow(clippy::expect_used)] // fresh v4 UUID cannot collide
        self.add_entry_with_id(id)
            .expect("fresh v4 UUID cannot collide with an existing entry identifier")
    }

    /// Adds a new entry under a caller-supplied [EntryId] and returns a mutable reference to it.
    ///
    /// Returns [DuplicateEntryIdError] if an entry with the same identifier already
    /// exists anywhere in the database.
    ///
    /// # Example
    ///
    /// ```
    /// use keepass::db::{Database, EntryId, fields};
    /// use uuid::uuid;
    ///
    /// let mut db = Database::new();
    /// let entry_id: EntryId = uuid!("00000000-0000-0000-0000-000000000001").into();
    /// db.root_mut()
    ///     .add_entry_with_id(entry_id)
    ///     .unwrap()
    ///     .edit(|e| {
    ///         e.set_unprotected(fields::TITLE, "My entry with defined UUID");
    ///     });
    /// ```
    pub fn add_entry_with_id(&mut self, id: EntryId) -> Result<EntryMut<'_>, DuplicateEntryIdError> {
        if self.database.entries.contains_key(&id) {
            return Err(DuplicateEntryIdError(id));
        }

        let new_entry = Entry::with_id(id, self.id);
        self.entries.insert(id);
        self.database.entries.insert(id, new_entry);

        Ok(EntryMut::new(self.database, id))
    }

    /// Adds a new subgroup under a caller-supplied [GroupId] and returns a mutable reference to
    /// it.
    ///
    /// Returns [DuplicateGroupIdError] if a group with the same identifier already
    /// exists anywhere in the database.
    ///
    /// # Example
    ///
    /// ```
    /// use keepass::db::{Database, GroupId};
    /// use uuid::uuid;
    ///
    /// let mut db = Database::new();
    /// let group_id: GroupId = uuid!("00000000-0000-0000-0000-000000000002").into();
    /// db.root_mut()
    ///     .add_group_with_id(group_id)
    ///     .unwrap()
    ///     .edit(|g| g.name = "Pinned group".to_string());
    /// ```
    pub fn add_group_with_id(&mut self, id: GroupId) -> Result<GroupMut<'_>, DuplicateGroupIdError> {
        if self.database.groups.contains_key(&id) {
            return Err(DuplicateGroupIdError(id));
        }

        let new_group = Group::with_id(id, Some(self.id));
        self.groups.insert(id);
        self.database.groups.insert(id, new_group);

        Ok(GroupMut::new(self.database, id))
    }

    /// Get a mutable reference to the database this group belongs to
    pub fn database_mut(&mut self) -> &mut Database {
        self.database
    }

    /// Get a mutable reference to the parent group, if any
    pub fn parent_mut(&mut self) -> Option<GroupMut<'_>> {
        self.parent.map(move |id| GroupMut::new(self.database, id))
    }

    /// Get a mutable reference to the previous parent group, if any
    pub fn previous_parent_mut(&mut self) -> Option<GroupMut<'_>> {
        self.previous_parent_group
            .and_then(move |id| self.database_mut().group_mut(id))
    }

    /// Find a contained group by name, case-insensitively, and return a mutable reference to it.
    pub fn group_by_name_mut(&mut self, name: &str) -> Option<GroupMut<'_>> {
        let gid = self.as_ref().groups().find_map(|g| {
            if g.name.eq_ignore_ascii_case(name) {
                Some(g.id)
            } else {
                None
            }
        });

        gid.map(move |id| GroupMut::new(self.database, id))
    }

    /// Find a contained entry by title, case-insensitively, and return a mutable reference to it.
    pub fn entry_by_name_mut(&mut self, title: &str) -> Option<EntryMut<'_>> {
        let eid = self.as_ref().entries().find_map(|e| {
            e.get(crate::db::fields::TITLE)
                .is_some_and(|t| t.eq_ignore_ascii_case(title))
                .then(|| e.id())
        });

        eid.map(move |id| EntryMut::new(self.database, id))
    }

    /// Find a contained group by a path of names, case-insensitively, and return a mutable
    /// reference to it.
    pub fn group_by_path_mut(&mut self, path: &[&str]) -> Option<GroupMut<'_>> {
        let mut current = self.id;

        for part in path {
            current = self
                .database
                .groups
                .get(&current)?
                .groups
                .iter()
                .filter_map(|id| self.database.groups.get(id))
                .find(|g| g.name.eq_ignore_ascii_case(part))?
                .id;
        }

        Some(GroupMut::new(self.database, current))
    }

    /// Remove the icon from this group, if it exists.
    pub fn set_icon_none(&mut self) {
        let id = self.id;

        if let Some(Icon::Custom(custom_icon_id)) = self.icon {
            // if this group had a custom icon, remove this group from the icon's reference list
            if let Some(mut custom_icon) = self.database.custom_icon_mut(custom_icon_id) {
                custom_icon.groups.retain(|&group_id| group_id != id);
            }
        }

        self.icon = None;
    }

    /// Set a built-in icon for this group by its ID, removing any existing icon.
    pub fn set_icon_builtin(&mut self, icon_id: usize) {
        self.set_icon_none();
        self.icon = Some(Icon::BuiltIn(icon_id));
    }

    /// Set a custom icon for this group by its ID, removing any existing icon.
    pub fn set_icon_custom(&mut self, custom_icon_id: CustomIconId) -> Result<(), CustomIconNotFoundError> {
        self.set_icon_none();

        let id = self.id;

        let mut custom_icon = self
            .database
            .custom_icon_mut(custom_icon_id)
            .ok_or(CustomIconNotFoundError(custom_icon_id))?;

        custom_icon.groups.insert(id);

        self.icon = Some(Icon::Custom(custom_icon_id));

        Ok(())
    }

    /// Set a custom icon for this group by providing the raw data, removing any existing icon.
    /// Returns a mutable reference to the newly created custom icon.
    pub fn set_icon_custom_new(&mut self, data: Vec<u8>) -> CustomIconMut<'_> {
        self.set_icon_none();

        let custom_icon_id = CustomIconId::new();

        let id = self.id;

        self.database.custom_icons.insert(
            custom_icon_id,
            CustomIcon {
                id: custom_icon_id,
                entries: HashSet::new(),
                groups: vec![id].into_iter().collect(),
                name: None,
                last_modification_time: Some(Times::now()),
                data,
            },
        );

        self.icon = Some(Icon::Custom(custom_icon_id));

        CustomIconMut::new(self.database, custom_icon_id)
    }

    /// Get a mutable reference to the custom icon of this group, if it exists and is a custom
    /// icon.
    pub fn custom_icon_mut(&mut self) -> Option<CustomIconMut<'_>> {
        if let Some(Icon::Custom(custom_icon_id)) = self.icon {
            Some(CustomIconMut::new(self.database, custom_icon_id))
        } else {
            None
        }
    }

    /// Move this group to a new parent group.
    ///
    /// Performs sanity checking and will return an error if the destination does not exist,
    /// belongs to a different database, or if the move would create a cycle in the group
    /// hierarchy.
    pub fn move_to(&mut self, new_parent_id: GroupId) -> Result<(), MoveGroupError> {
        let old_parent_id = self.parent.ok_or(MoveGroupError::CannotMoveRoot)?;

        if !self.database.groups.contains_key(&new_parent_id) {
            return Err(MoveGroupError::NotFound(new_parent_id));
        }

        // Check for cycles
        let mut current = Some(new_parent_id);
        while let Some(curr_id) = current {
            if curr_id == self.id {
                return Err(MoveGroupError::WouldCreateCycle);
            }
            current = self.database.groups.get(&curr_id).and_then(|g| g.parent);
        }

        // Remove from old parent
        #[allow(clippy::unwrap_used, clippy::missing_panics_doc)] // we checked that old_parent_id exists
        let mut old_parent = self.database.group_mut(old_parent_id).unwrap();
        old_parent.groups.remove(&self.id);

        // Insert into new parent
        #[allow(clippy::unwrap_used, clippy::missing_panics_doc)] // we checked that new_parent_id exists
        let mut new_parent = self.database.group_mut(new_parent_id).unwrap();
        new_parent.groups.insert(self.id);

        // Update parent reference
        self.parent = Some(new_parent_id);
        self.previous_parent_group = Some(old_parent_id);

        Ok(())
    }

    /// Deletes this group and all its child groups and entries from the database.
    pub fn remove(mut self) {
        // Remove this group's back-reference from its custom icon (if any) before
        // the group is erased from db.groups, so the back-ref set stays consistent.
        self.set_icon_none();

        // Remove from parent
        if let Some(parent_id) = self.parent {
            if let Some(mut parent) = self.database.group_mut(parent_id) {
                parent.groups.remove(&self.id);
            }
        }

        // Delete entries
        let entry_ids: Vec<EntryId> = self.entries.iter().cloned().collect();
        for entry_id in entry_ids {
            if let Some(entry) = self.database.entry_mut(entry_id) {
                entry.remove();
            }
        }

        // Recursively delete child groups
        let child_group_ids: Vec<GroupId> = self.groups.iter().cloned().collect();
        for child_id in child_group_ids {
            if let Some(child_group) = self.database.group_mut(child_id) {
                child_group.remove();
            }
        }

        // Finally, remove this group from the database
        self.database.groups.remove(&self.id);

        // Clear any Meta UUID fields that referenced this group, so they don't
        // silently hold stale UUIDs that would be round-tripped back to disk.
        let uuid = self.id.0;
        let meta = &mut self.database.meta;
        if meta.recyclebin_uuid == Some(uuid) {
            meta.recyclebin_uuid = None;
        }
        if meta.entry_templates_group == Some(uuid) {
            meta.entry_templates_group = None;
        }
        if meta.last_selected_group == Some(uuid) {
            meta.last_selected_group = None;
        }
        if meta.last_top_visible_group == Some(uuid) {
            meta.last_top_visible_group = None;
        }
    }

    /// Convert this mutable group reference into a history-tracking variant that will record
    /// changes such as deletions and moves.
    pub fn track_changes(&mut self) -> GroupTrack<'_> {
        GroupTrack {
            database: self.database,
            id: self.id,
        }
    }
}

/// Attempted to add a group with an ID that already exists in the database.
#[derive(Debug, Error)]
#[error("a group with ID {0} already exists in the database")]
pub struct DuplicateGroupIdError(pub GroupId);

/// Attempted to add an entry with an ID that already exists in the database.
#[derive(Debug, Error)]
#[error("an entry with ID {0} already exists in the database")]
pub struct DuplicateEntryIdError(pub EntryId);

/// Errors that can occur when moving a group to a new parent.
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum MoveGroupError {
    /// The root group cannot be moved
    #[error("Cannot move the root group")]
    CannotMoveRoot,

    /// The destination group was not found in the database.
    ///
    /// This error can also occur if the destination group belongs to a different database.
    #[error("Destination group with ID {0} not found")]
    NotFound(GroupId),

    /// Moving the group would create a cycle in the group hierarchy, which is not allowed.
    #[error("Cannot move a group into itself or one of its descendants")]
    WouldCreateCycle,
}

impl Deref for GroupMut<'_> {
    type Target = Group;

    #[allow(clippy::expect_used, clippy::missing_panics_doc)] // group existence is guaranteed
    fn deref(&self) -> &Self::Target {
        self.database
            .groups
            .get(&self.id)
            .expect("GroupMut points to a non-existing group")
    }
}

impl DerefMut for GroupMut<'_> {
    #[allow(clippy::expect_used, clippy::missing_panics_doc)] // group existence is guaranteed
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.database
            .groups
            .get_mut(&self.id)
            .expect("GroupMut points to a non-existing group")
    }
}

/// A variant of [GroupMut] that tracks changes to the group, such as deletions and moves, and
/// updates the location changed time when the group is moved.
pub struct GroupTrack<'a> {
    database: &'a mut crate::db::Database,
    id: GroupId,
}

impl GroupTrack<'_> {
    /// Turn the GroupTrack back into a regular GroupMut
    pub fn as_mut(&mut self) -> GroupMut<'_> {
        GroupMut::new(self.database, self.id)
    }

    /// Move this group to a new parent group, updating the location changed time.
    pub fn move_to(&mut self, new_parent_id: GroupId) -> Result<(), MoveGroupError> {
        self.as_mut().move_to(new_parent_id)?;
        self.times.location_changed = Some(Times::now());
        Ok(())
    }

    /// Deletes this group and all its child groups and entries from the database,
    /// adding them to the deleted entries and groups sets.
    pub fn remove(self) -> Result<(), CannotDeleteRootError> {
        if self.id() == self.database.root().id() {
            return Err(CannotDeleteRootError);
        }

        // Remove from parent
        if let Some(parent_id) = self.parent {
            if let Some(mut parent) = self.database.group_mut(parent_id) {
                parent.groups.remove(&self.id);
            }
        }

        // Delete entries
        let entry_ids: Vec<EntryId> = self.entries.iter().cloned().collect();

        for entry_id in entry_ids {
            if let Some(mut entry) = self.database.entry_mut(entry_id) {
                entry.track_changes().remove();
            }
        }

        // Recursively delete child groups
        let child_group_ids: Vec<GroupId> = self.groups.iter().cloned().collect();
        for child_id in child_group_ids {
            if let Some(mut child_group) = self.database.group_mut(child_id) {
                child_group.track_changes().remove()?;
            }
        }

        // Finally, remove this group from the database and add to deleted groups
        self.database.groups.remove(&self.id);
        self.database
            .deleted_objects
            .insert(self.id.uuid(), Some(Times::now()));

        Ok(())
    }

    /// Convenience method to edit the group in a closure, updating the last modification time.
    pub fn edit(&mut self, f: impl FnOnce(&mut GroupTrack<'_>)) -> &mut Self {
        f(self);
        self.as_mut().times.last_modification = Some(Times::now());
        self
    }
}

impl Deref for GroupTrack<'_> {
    type Target = Group;

    #[allow(clippy::expect_used, clippy::missing_panics_doc)] // group existence is guaranteed
    fn deref(&self) -> &Self::Target {
        self.database.groups.get(&self.id).expect("Group not found")
    }
}

impl DerefMut for GroupTrack<'_> {
    #[allow(clippy::expect_used, clippy::missing_panics_doc)] // group existence is guaranteed
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.database.groups.get_mut(&self.id).expect("Group not found")
    }
}

/// Error returned when attempting to delete the root group, which is not allowed.
#[derive(Debug, Error)]
#[error("Cannot delete the root group")]
pub struct CannotDeleteRootError;

#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod group_tests {
    use crate::db::fields;
    use crate::Database;

    #[test]
    fn get() {
        let mut db = Database::new();

        let general_group_id = db.root_mut().add_group().edit(|g| g.name = "General".into()).id();

        let sample_entry_id = db
            .group_mut(general_group_id)
            .unwrap()
            .add_entry()
            .edit(|e| {
                e.set_unprotected(fields::TITLE, "Sample Entry #2");
            })
            .id();

        assert_eq!(
            db.entry(sample_entry_id).unwrap().get(fields::TITLE),
            Some("Sample Entry #2")
        );

        let root = db.root();

        assert!(root.group(general_group_id).is_some());
        assert!(db
            .group(general_group_id)
            .unwrap()
            .entry(sample_entry_id)
            .is_some());

        let grp = root.group_by_path(&["General"]).unwrap();

        assert!(grp.entry_by_name("Sample Entry #2").is_some());

        assert!(root.group_by_name("General").is_some());

        assert!(root.group_by_name("Invalid Group").is_none());

        assert!(root.group_by_path(&[]).is_some());
    }

    #[test]
    fn get_mut() {
        let mut db = Database::new();

        let general_group_id = db.root_mut().add_group().edit(|g| g.name = "General".into()).id();

        let sample_entry_id = db
            .group_mut(general_group_id)
            .unwrap()
            .add_entry()
            .edit(|e| {
                e.set_unprotected(fields::TITLE, "Sample Entry #2");
            })
            .id();

        assert_eq!(
            db.entry_mut(sample_entry_id).unwrap().get(fields::TITLE),
            Some("Sample Entry #2")
        );

        let mut root = db.root_mut();
        assert!(root.group_mut(general_group_id).is_some());

        let mut grp = root.group_by_path_mut(&["General"]).unwrap();

        assert!(grp.entry_by_name_mut("Sample Entry #2").is_some());

        assert!(root.group_by_name_mut("General").is_some());
        assert!(root.group_by_name_mut("Invalid Group").is_none());
        assert!(root.group_by_path_mut(&[]).is_some());

        assert!(db
            .group_mut(general_group_id)
            .unwrap()
            .entry_mut(sample_entry_id)
            .is_some());
    }

    #[test]
    fn add_entry_with_id_uses_supplied_uuid() {
        use crate::db::EntryId;
        use uuid::uuid;

        let mut db = Database::new();
        let pinned_uuid = uuid!("00000000-0000-0000-0000-0000000000aa");
        let pinned: EntryId = pinned_uuid.into();

        let inserted_id = db
            .root_mut()
            .add_entry_with_id(pinned)
            .unwrap()
            .edit(|e| {
                e.set_unprotected(fields::TITLE, "pinned");
            })
            .id();

        assert_eq!(inserted_id, pinned);
        assert_eq!(inserted_id.uuid(), pinned_uuid);
        assert_eq!(db.entry(pinned).unwrap().get(fields::TITLE), Some("pinned"),);
    }

    #[test]
    fn add_entry_with_id_duplicate_returns_error() {
        use crate::db::{DuplicateEntryIdError, EntryId};
        use uuid::uuid;

        let mut db = Database::new();
        let pinned: EntryId = uuid!("00000000-0000-0000-0000-0000000000ab").into();

        db.root_mut().add_entry_with_id(pinned).unwrap();

        assert!(matches!(
            db.root_mut().add_entry_with_id(pinned),
            Err(DuplicateEntryIdError(eid)) if eid == pinned
        ));
    }

    #[test]
    fn add_group_with_id_uses_supplied_uuid() {
        use crate::db::GroupId;
        use uuid::uuid;

        let mut db = Database::new();
        let pinned_uuid = uuid!("00000000-0000-0000-0000-0000000000ba");
        let pinned: GroupId = pinned_uuid.into();

        let inserted_id = db
            .root_mut()
            .add_group_with_id(pinned)
            .unwrap()
            .edit(|g| g.name = "pinned".into())
            .id();

        assert_eq!(inserted_id, pinned);
        assert_eq!(inserted_id.uuid(), pinned_uuid);
        assert_eq!(db.group(pinned).unwrap().name, "pinned");
    }

    #[test]
    fn add_group_with_id_duplicate_returns_error() {
        use crate::db::{DuplicateGroupIdError, GroupId};
        use uuid::uuid;

        let mut db = Database::new();
        let pinned: GroupId = uuid!("00000000-0000-0000-0000-0000000000bb").into();

        db.root_mut().add_group_with_id(pinned).unwrap();

        assert!(matches!(
            db.root_mut().add_group_with_id(pinned),
            Err(DuplicateGroupIdError(gid)) if gid == pinned
        ));
    }

    #[test]
    fn from_uuid_impls_match_constructors() {
        use crate::db::{EntryId, GroupId};
        use uuid::uuid;

        let raw = uuid!("00000000-0000-0000-0000-0000000000cc");
        let from_entry: EntryId = raw.into();
        let from_entry_ctor = EntryId::from_uuid(raw);
        assert_eq!(from_entry, from_entry_ctor);
        assert_eq!(from_entry.uuid(), raw);

        let from_group: GroupId = raw.into();
        let from_group_ctor = GroupId::from_uuid(raw);
        assert_eq!(from_group, from_group_ctor);
        assert_eq!(from_group.uuid(), raw);
    }
}