shodh-redb 0.3.1

Multi-modal embedded database - vectors, blobs, TTL, merge operators, and causal tracking built on ACID B-trees
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
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
use crate::cdc::types::{CdcEvent, ChangeOp};
use crate::compat::Mutex;
use crate::db::TransactionGuard;
use crate::merge::MergeOperator;
use crate::sealed::Sealed;
use crate::tree_store::{
    AccessGuardMutInPlace, Btree, BtreeExtractIf, BtreeHeader, BtreeMut, BtreeRangeIter,
    MAX_PAIR_LENGTH, MAX_VALUE_LENGTH, PageHint, PageNumber, PageTrackerPolicy, RawBtree,
    RawEntryIter, TransactionalMemory,
};
use crate::types::{Key, MutInPlaceValue, Value};
use crate::{AccessGuard, AccessGuardMut, StorageError, WriteTransaction};
use crate::{Result, TableHandle};
use alloc::string::{String, ToString};
use alloc::sync::Arc;
use alloc::vec::Vec;
use core::borrow::Borrow;
use core::fmt::{Debug, Formatter};
use core::marker::PhantomData;
use core::ops::RangeBounds;

/// Informational storage stats about a table
#[derive(Debug, Clone, Copy)]
pub struct TableStats {
    pub(crate) tree_height: u32,
    pub(crate) leaf_pages: u64,
    pub(crate) branch_pages: u64,
    pub(crate) stored_leaf_bytes: u64,
    pub(crate) metadata_bytes: u64,
    pub(crate) fragmented_bytes: u64,
}

impl TableStats {
    /// Maximum traversal distance to reach the deepest (key, value) pair in the table
    pub fn tree_height(&self) -> u32 {
        self.tree_height
    }

    /// Number of leaf pages that store user data
    pub fn leaf_pages(&self) -> u64 {
        self.leaf_pages
    }

    /// Number of branch pages in the btree that store user data
    pub fn branch_pages(&self) -> u64 {
        self.branch_pages
    }

    /// Number of bytes consumed by keys and values that have been inserted.
    /// Does not include indexing overhead
    pub fn stored_bytes(&self) -> u64 {
        self.stored_leaf_bytes
    }

    /// Number of bytes consumed by keys in internal branch pages, plus other metadata
    pub fn metadata_bytes(&self) -> u64 {
        self.metadata_bytes
    }

    /// Number of bytes consumed by fragmentation, both in data pages and internal metadata tables
    pub fn fragmented_bytes(&self) -> u64 {
        self.fragmented_bytes
    }
}

/// A table containing key-value mappings
pub struct Table<'txn, K: Key + 'static, V: Value + 'static> {
    name: String,
    transaction: &'txn WriteTransaction,
    tree: BtreeMut<'txn, K, V>,
}

impl<K: Key + 'static, V: Value + 'static> TableHandle for Table<'_, K, V> {
    fn name(&self) -> &str {
        &self.name
    }
}

impl<'txn, K: Key + 'static, V: Value + 'static> Table<'txn, K, V> {
    pub(crate) fn new(
        name: &str,
        table_root: Option<BtreeHeader>,
        freed_pages: Arc<Mutex<Vec<PageNumber>>>,
        allocated_pages: Arc<Mutex<PageTrackerPolicy>>,
        mem: Arc<TransactionalMemory>,
        transaction: &'txn WriteTransaction,
    ) -> Table<'txn, K, V> {
        Table {
            name: name.to_string(),
            transaction,
            tree: BtreeMut::new(
                table_root,
                transaction.transaction_guard(),
                mem,
                freed_pages,
                allocated_pages,
            ),
        }
    }

    #[allow(dead_code)]
    #[cfg(feature = "std")]
    pub(crate) fn print_debug(&self, include_values: bool) -> Result {
        self.tree.print_debug(include_values)
    }

    /// Returns an accessor, which allows mutation, to the value corresponding to the given key
    pub fn get_mut<'k>(
        &mut self,
        key: impl Borrow<K::SelfType<'k>>,
    ) -> Result<Option<AccessGuardMut<'_, V>>> {
        self.tree.get_mut(key.borrow())
    }

    /// Removes and returns the first key-value pair in the table
    pub fn pop_first(&mut self) -> Result<Option<(AccessGuard<'_, K>, AccessGuard<'_, V>)>> {
        // TODO: optimize this
        let first = self
            .iter()?
            .next()
            .map(|x| x.map(|(key, _)| K::as_bytes(&key.value()).as_ref().to_vec()));
        if let Some(owned_key) = first {
            let owned_key = owned_key?;
            let key = K::from_bytes(&owned_key);
            let value = self.remove(&key)?.ok_or_else(|| {
                StorageError::Corrupted("key disappeared during pop operation".into())
            })?;
            drop(key);
            Ok(Some((AccessGuard::with_owned_value(owned_key), value)))
        } else {
            Ok(None)
        }
    }

    /// Removes and returns the last key-value pair in the table
    pub fn pop_last(&mut self) -> Result<Option<(AccessGuard<'_, K>, AccessGuard<'_, V>)>> {
        // TODO: optimize this
        let last = self
            .iter()?
            .next_back()
            .map(|x| x.map(|(key, _)| K::as_bytes(&key.value()).as_ref().to_vec()));
        if let Some(owned_key) = last {
            let owned_key = owned_key?;
            let key = K::from_bytes(&owned_key);
            let value = self.remove(&key)?.ok_or_else(|| {
                StorageError::Corrupted("key disappeared during pop operation".into())
            })?;
            drop(key);
            Ok(Some((AccessGuard::with_owned_value(owned_key), value)))
        } else {
            Ok(None)
        }
    }

    /// Applies `predicate` to all key-value pairs. All entries for which
    /// `predicate` evaluates to `true` are returned in an iterator, and those which are read from the iterator are removed
    ///
    /// Note: values not read from the iterator will not be removed
    pub fn extract_if<F: for<'f> FnMut(K::SelfType<'f>, V::SelfType<'f>) -> bool>(
        &mut self,
        predicate: F,
    ) -> Result<ExtractIf<'_, K, V, F>> {
        self.extract_from_if::<K::SelfType<'_>, F>(.., predicate)
    }

    /// Applies `predicate` to all key-value pairs in the specified range. All entries for which
    /// `predicate` evaluates to `true` are returned in an iterator, and those which are read from the iterator are removed
    ///
    /// Note: values not read from the iterator will not be removed
    pub fn extract_from_if<'a, KR, F: for<'f> FnMut(K::SelfType<'f>, V::SelfType<'f>) -> bool>(
        &mut self,
        range: impl RangeBounds<KR> + 'a,
        predicate: F,
    ) -> Result<ExtractIf<'_, K, V, F>>
    where
        KR: Borrow<K::SelfType<'a>> + 'a,
    {
        let inner = self.tree.extract_from_if(&range, predicate)?;
        if self.transaction.cdc_log.is_some() {
            Ok(ExtractIf::with_cdc(
                inner,
                self.transaction,
                self.name.clone(),
            ))
        } else {
            Ok(ExtractIf::new(inner))
        }
    }

    /// Applies `predicate` to all key-value pairs. All entries for which
    /// `predicate` evaluates to `false` are removed.
    ///
    pub fn retain<F: for<'f> FnMut(K::SelfType<'f>, V::SelfType<'f>) -> bool>(
        &mut self,
        predicate: F,
    ) -> Result {
        self.retain_in::<K::SelfType<'_>, F>(.., predicate)
    }

    /// Applies `predicate` to all key-value pairs in the range `start..end`. All entries for which
    /// `predicate` evaluates to `false` are removed.
    ///
    pub fn retain_in<'a, KR, F: for<'f> FnMut(K::SelfType<'f>, V::SelfType<'f>) -> bool>(
        &mut self,
        range: impl RangeBounds<KR> + 'a,
        mut predicate: F,
    ) -> Result
    where
        KR: Borrow<K::SelfType<'a>> + 'a,
    {
        if self.transaction.cdc_log.is_some() {
            // Route through extract_from_if so CDC events are recorded for each removal
            for result in self.extract_from_if(range, move |k, v| !predicate(k, v))? {
                result?;
            }
            Ok(())
        } else {
            self.tree.retain_in(predicate, range)
        }
    }

    /// Removes all key-value pairs in the given range
    ///
    /// Returns the number of entries removed
    pub fn drain<'a, KR>(&mut self, range: impl RangeBounds<KR> + 'a) -> Result<u64>
    where
        KR: Borrow<K::SelfType<'a>> + 'a,
    {
        let mut count = 0u64;
        for result in self.extract_from_if(range, |_, _| true)? {
            result?;
            count += 1;
        }
        Ok(count)
    }

    /// Removes all key-value pairs from the table
    ///
    /// Returns the number of entries removed
    pub fn drain_all(&mut self) -> Result<u64> {
        self.drain::<K::SelfType<'_>>(..)
    }

    /// Insert mapping of the given key to the given value
    ///
    /// If key is already present it is replaced
    ///
    /// Returns the old value, if the key was present in the table, otherwise None is returned
    pub fn insert<'k, 'v>(
        &mut self,
        key: impl Borrow<K::SelfType<'k>>,
        value: impl Borrow<V::SelfType<'v>>,
    ) -> Result<Option<AccessGuard<'_, V>>> {
        let value_len = V::as_bytes(value.borrow()).as_ref().len();
        if value_len > MAX_VALUE_LENGTH {
            return Err(StorageError::ValueTooLarge(value_len));
        }
        let key_len = K::as_bytes(key.borrow()).as_ref().len();
        if key_len > MAX_VALUE_LENGTH {
            return Err(StorageError::ValueTooLarge(key_len));
        }
        if value_len + key_len > MAX_PAIR_LENGTH {
            return Err(StorageError::ValueTooLarge(value_len + key_len));
        }
        let result = self.tree.insert(key.borrow(), value.borrow())?;
        if self.transaction.cdc_log.is_some() {
            let old_value = result
                .as_ref()
                .map(|g| V::as_bytes(&g.value()).as_ref().to_vec());
            self.transaction.record_cdc(CdcEvent {
                table_name: self.name.clone(),
                op: if old_value.is_some() {
                    ChangeOp::Update
                } else {
                    ChangeOp::Insert
                },
                key: K::as_bytes(key.borrow()).as_ref().to_vec(),
                new_value: Some(V::as_bytes(value.borrow()).as_ref().to_vec()),
                old_value,
            });
        }
        Ok(result)
    }

    /// Removes the given key
    ///
    /// Returns the old value, if the key was present in the table
    pub fn remove<'a>(
        &mut self,
        key: impl Borrow<K::SelfType<'a>>,
    ) -> Result<Option<AccessGuard<'_, V>>> {
        let result = self.tree.remove(key.borrow())?;
        if self.transaction.cdc_log.is_some() && result.is_some() {
            let old_value = result
                .as_ref()
                .map(|g| V::as_bytes(&g.value()).as_ref().to_vec());
            self.transaction.record_cdc(CdcEvent {
                table_name: self.name.clone(),
                op: ChangeOp::Delete,
                key: K::as_bytes(key.borrow()).as_ref().to_vec(),
                new_value: None,
                old_value,
            });
        }
        Ok(result)
    }

    /// Atomically read-modify-write a value using a [`MergeOperator`].
    ///
    /// Reads the current value for `key` (if any), passes the raw bytes to
    /// `operator.merge()` along with `operand`, and writes the result back.
    /// If the operator returns `None`, the key is removed.
    ///
    /// This is equivalent to a get-then-insert but expressed as a single call.
    /// The operation is atomic within the current write transaction.
    pub fn merge<'k>(
        &mut self,
        key: impl Borrow<K::SelfType<'k>>,
        operand: &[u8],
        operator: &dyn MergeOperator,
    ) -> Result<()> {
        let key_ref = key.borrow();

        // Copy key and existing value bytes, then drop the access guard
        // to release the immutable borrow before calling insert/remove.
        // This is the same pattern used by pop_first()/pop_last().
        let key_bytes = K::as_bytes(key_ref).as_ref().to_vec();
        let existing_bytes: Option<Vec<u8>> = {
            let guard = self.get(key_ref)?;
            guard.map(|g| V::as_bytes(&g.value()).as_ref().to_vec())
        };

        let merged = operator.merge(&key_bytes, existing_bytes.as_deref(), operand);

        let key_ref = K::from_bytes(&key_bytes);
        match merged {
            Some(new_bytes) => {
                let new_value = V::from_bytes(&new_bytes);
                self.insert(&key_ref, &new_value)?;
            }
            None => {
                self.remove(&key_ref)?;
            }
        }
        Ok(())
    }

    /// Type-safe variant of [`merge()`](Self::merge) that serializes the operand
    /// via `V::as_bytes()` before passing it to the operator.
    pub fn merge_in<'k, 'v>(
        &mut self,
        key: impl Borrow<K::SelfType<'k>>,
        operand: impl Borrow<V::SelfType<'v>>,
        operator: &dyn MergeOperator,
    ) -> Result<()> {
        let operand_bytes = V::as_bytes(operand.borrow()).as_ref().to_vec();
        self.merge(key, &operand_bytes, operator)
    }
}

impl<K: Key + 'static, V: MutInPlaceValue + 'static> Table<'_, K, V> {
    /// Reserve space to insert a key-value pair
    ///
    /// If key is already present it is replaced
    ///
    /// The returned reference will have length equal to `value_length`
    pub fn insert_reserve<'a>(
        &mut self,
        key: impl Borrow<K::SelfType<'a>>,
        value_length: usize,
    ) -> Result<AccessGuardMutInPlace<'_, V>> {
        if value_length > MAX_VALUE_LENGTH {
            return Err(StorageError::ValueTooLarge(value_length));
        }
        let key_len = K::as_bytes(key.borrow()).as_ref().len();
        if key_len > MAX_VALUE_LENGTH {
            return Err(StorageError::ValueTooLarge(key_len));
        }
        if value_length + key_len > MAX_PAIR_LENGTH {
            return Err(StorageError::ValueTooLarge(value_length + key_len));
        }
        self.tree.insert_reserve(key.borrow(), value_length)
    }
}

impl<K: Key + 'static, V: Value + 'static> ReadableTableMetadata for Table<'_, K, V> {
    fn stats(&self) -> Result<TableStats> {
        let tree_stats = self.tree.stats()?;

        Ok(TableStats {
            tree_height: tree_stats.tree_height,
            leaf_pages: tree_stats.leaf_pages,
            branch_pages: tree_stats.branch_pages,
            stored_leaf_bytes: tree_stats.stored_leaf_bytes,
            metadata_bytes: tree_stats.metadata_bytes,
            fragmented_bytes: tree_stats.fragmented_bytes,
        })
    }

    fn len(&self) -> Result<u64> {
        self.tree.len()
    }
}

impl<K: Key + 'static, V: Value + 'static> ReadableTable<K, V> for Table<'_, K, V> {
    fn get<'a>(&self, key: impl Borrow<K::SelfType<'a>>) -> Result<Option<AccessGuard<'_, V>>> {
        self.tree.get(key.borrow())
    }

    fn range<'a, KR>(&self, range: impl RangeBounds<KR> + 'a) -> Result<Range<'_, K, V>>
    where
        KR: Borrow<K::SelfType<'a>> + 'a,
    {
        self.tree
            .range(&range)
            .map(|x| Range::new(x, self.transaction.transaction_guard()))
    }

    fn first(&self) -> Result<Option<(AccessGuard<'_, K>, AccessGuard<'_, V>)>> {
        self.tree.first()
    }

    fn last(&self) -> Result<Option<(AccessGuard<'_, K>, AccessGuard<'_, V>)>> {
        self.tree.last()
    }
}

impl<K: Key, V: Value> Sealed for Table<'_, K, V> {}

impl<K: Key + 'static, V: Value + 'static> Drop for Table<'_, K, V> {
    fn drop(&mut self) {
        self.transaction.close_table(
            &self.name,
            &self.tree,
            self.tree.get_root().map(|x| x.length).unwrap_or_default(),
        );
    }
}

fn debug_helper<K: Key + 'static, V: Value + 'static>(
    f: &mut Formatter<'_>,
    name: &str,
    len: Result<u64>,
    first: Result<Option<(AccessGuard<K>, AccessGuard<V>)>>,
    last: Result<Option<(AccessGuard<K>, AccessGuard<V>)>>,
) -> core::fmt::Result {
    write!(f, "Table [ name: \"{name}\", ")?;
    if let Ok(len) = len {
        if len == 0 {
            write!(f, "No entries")?;
        } else if len == 1 {
            if let Ok(first) = first {
                let (key, value) = first.as_ref().unwrap();
                write!(f, "One key-value: {:?} = {:?}", key.value(), value.value())?;
            } else {
                write!(f, "I/O Error accessing table!")?;
            }
        } else {
            if let Ok(first) = first {
                let (key, value) = first.as_ref().unwrap();
                write!(f, "first: {:?} = {:?}, ", key.value(), value.value())?;
            } else {
                write!(f, "I/O Error accessing table!")?;
            }
            if len > 2 {
                write!(f, "...{} more entries..., ", len - 2)?;
            }
            if let Ok(last) = last {
                let (key, value) = last.as_ref().unwrap();
                write!(f, "last: {:?} = {:?}", key.value(), value.value())?;
            } else {
                write!(f, "I/O Error accessing table!")?;
            }
        }
    } else {
        write!(f, "I/O Error accessing table!")?;
    }
    write!(f, " ]")?;

    Ok(())
}

impl<K: Key + 'static, V: Value + 'static> Debug for Table<'_, K, V> {
    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
        debug_helper(f, &self.name, self.len(), self.first(), self.last())
    }
}

pub trait ReadableTableMetadata {
    /// Retrieves information about storage usage for the table
    fn stats(&self) -> Result<TableStats>;

    /// Returns the number of entries in the table
    fn len(&self) -> Result<u64>;

    /// Returns `true` if the table is empty
    fn is_empty(&self) -> Result<bool> {
        Ok(self.len()? == 0)
    }
}

pub trait ReadableTable<K: Key + 'static, V: Value + 'static>: ReadableTableMetadata {
    /// Returns the value corresponding to the given key
    fn get<'a>(&self, key: impl Borrow<K::SelfType<'a>>) -> Result<Option<AccessGuard<'_, V>>>;

    /// Returns a double-ended iterator over a range of elements in the table
    ///
    /// # Examples
    ///
    /// Usage:
    /// ```rust
    /// use shodh_redb::*;
    /// # use tempfile::NamedTempFile;
    /// const TABLE: TableDefinition<&str, u64> = TableDefinition::new("my_data");
    ///
    /// # fn main() -> Result<(), Error> {
    /// # #[cfg(not(target_os = "wasi"))]
    /// # let tmpfile = NamedTempFile::new().unwrap();
    /// # #[cfg(target_os = "wasi")]
    /// # let tmpfile = NamedTempFile::new_in("/tmp").unwrap();
    /// # let filename = tmpfile.path();
    /// let db = Database::create(filename)?;
    /// let write_txn = db.begin_write()?;
    /// {
    ///     let mut table = write_txn.open_table(TABLE)?;
    ///     table.insert("a", &0)?;
    ///     table.insert("b", &1)?;
    ///     table.insert("c", &2)?;
    /// }
    /// write_txn.commit()?;
    ///
    /// let read_txn = db.begin_read()?;
    /// let table = read_txn.open_table(TABLE)?;
    /// let mut iter = table.range("a".."c")?;
    /// let (key, value) = iter.next().unwrap()?;
    /// assert_eq!("a", key.value());
    /// assert_eq!(0, value.value());
    /// # Ok(())
    /// # }
    /// ```
    fn range<'a, KR>(&self, range: impl RangeBounds<KR> + 'a) -> Result<Range<'_, K, V>>
    where
        KR: Borrow<K::SelfType<'a>> + 'a;

    /// Returns the first key-value pair in the table, if it exists
    fn first(&self) -> Result<Option<(AccessGuard<'_, K>, AccessGuard<'_, V>)>>;

    /// Returns the last key-value pair in the table, if it exists
    fn last(&self) -> Result<Option<(AccessGuard<'_, K>, AccessGuard<'_, V>)>>;

    /// Returns a double-ended iterator over all elements in the table
    fn iter(&self) -> Result<Range<'_, K, V>> {
        self.range::<K::SelfType<'_>>(..)
    }
}

/// A read-only untyped table
pub struct ReadOnlyUntypedTable {
    tree: RawBtree,
}

impl Sealed for ReadOnlyUntypedTable {}

impl ReadableTableMetadata for ReadOnlyUntypedTable {
    /// Retrieves information about storage usage for the table
    fn stats(&self) -> Result<TableStats> {
        let tree_stats = self.tree.stats()?;

        Ok(TableStats {
            tree_height: tree_stats.tree_height,
            leaf_pages: tree_stats.leaf_pages,
            branch_pages: tree_stats.branch_pages,
            stored_leaf_bytes: tree_stats.stored_leaf_bytes,
            metadata_bytes: tree_stats.metadata_bytes,
            fragmented_bytes: tree_stats.fragmented_bytes,
        })
    }

    fn len(&self) -> Result<u64> {
        self.tree.len()
    }
}

impl ReadOnlyUntypedTable {
    pub(crate) fn new(
        root_page: Option<BtreeHeader>,
        fixed_key_size: Option<usize>,
        fixed_value_size: Option<usize>,
        mem: Arc<TransactionalMemory>,
    ) -> Self {
        Self {
            tree: RawBtree::new(root_page, fixed_key_size, fixed_value_size, mem),
        }
    }

    /// Iterate all entries as raw key/value byte slices.
    /// Useful for CLI tools, debugging, and migration without knowing types at compile time.
    pub fn iter_raw(&self) -> Result<RawEntryIter> {
        self.tree.raw_iter()
    }
}

/// A read-only table
pub struct ReadOnlyTable<K: Key + 'static, V: Value + 'static> {
    name: String,
    tree: Btree<K, V>,
    transaction_guard: Arc<TransactionGuard>,
}

impl<K: Key + 'static, V: Value + 'static> TableHandle for ReadOnlyTable<K, V> {
    fn name(&self) -> &str {
        &self.name
    }
}

impl<K: Key + 'static, V: Value + 'static> ReadOnlyTable<K, V> {
    pub(crate) fn new(
        name: String,
        root_page: Option<BtreeHeader>,
        hint: PageHint,
        guard: Arc<TransactionGuard>,
        mem: Arc<TransactionalMemory>,
    ) -> Result<ReadOnlyTable<K, V>> {
        Ok(ReadOnlyTable {
            name,
            tree: Btree::new(root_page, hint, guard.clone(), mem)?,
            transaction_guard: guard,
        })
    }

    /// Create a `ReadOnlyTable` that never applies value-level decompression.
    /// Used for system/internal tables whose values are always stored uncompressed.
    pub(crate) fn new_uncompressed(
        name: String,
        root_page: Option<BtreeHeader>,
        hint: PageHint,
        guard: Arc<TransactionGuard>,
        mem: Arc<TransactionalMemory>,
    ) -> Result<ReadOnlyTable<K, V>> {
        Ok(ReadOnlyTable {
            name,
            tree: Btree::new_uncompressed(root_page, hint, guard.clone(), mem)?,
            transaction_guard: guard,
        })
    }

    /// This method is like [`ReadableTable::get()`], but the [`AccessGuard`] is reference counted
    /// and keeps the transaction alive until it is dropped.
    pub fn get<'a>(
        &self,
        key: impl Borrow<K::SelfType<'a>>,
    ) -> Result<Option<AccessGuard<'static, V>>> {
        self.tree.get(key.borrow())
    }

    /// This method is like [`ReadableTable::range()`], but the iterator is reference counted and keeps the transaction
    /// alive until it is dropped.
    pub fn range<'a, KR>(&self, range: impl RangeBounds<KR>) -> Result<Range<'static, K, V>>
    where
        KR: Borrow<K::SelfType<'a>>,
    {
        self.tree
            .range(&range)
            .map(|x| Range::new(x, self.transaction_guard.clone()))
    }
}

impl<K: Key + 'static, V: Value + 'static> ReadableTableMetadata for ReadOnlyTable<K, V> {
    fn stats(&self) -> Result<TableStats> {
        let tree_stats = self.tree.stats()?;

        Ok(TableStats {
            tree_height: tree_stats.tree_height,
            leaf_pages: tree_stats.leaf_pages,
            branch_pages: tree_stats.branch_pages,
            stored_leaf_bytes: tree_stats.stored_leaf_bytes,
            metadata_bytes: tree_stats.metadata_bytes,
            fragmented_bytes: tree_stats.fragmented_bytes,
        })
    }

    fn len(&self) -> Result<u64> {
        self.tree.len()
    }
}

impl<K: Key + 'static, V: Value + 'static> ReadableTable<K, V> for ReadOnlyTable<K, V> {
    fn get<'a>(&self, key: impl Borrow<K::SelfType<'a>>) -> Result<Option<AccessGuard<'_, V>>> {
        self.tree.get(key.borrow())
    }

    fn range<'a, KR>(&self, range: impl RangeBounds<KR> + 'a) -> Result<Range<'_, K, V>>
    where
        KR: Borrow<K::SelfType<'a>> + 'a,
    {
        self.tree
            .range(&range)
            .map(|x| Range::new(x, self.transaction_guard.clone()))
    }

    fn first(&self) -> Result<Option<(AccessGuard<'_, K>, AccessGuard<'_, V>)>> {
        self.tree.first()
    }

    fn last(&self) -> Result<Option<(AccessGuard<'_, K>, AccessGuard<'_, V>)>> {
        self.tree.last()
    }
}

impl<K: Key, V: Value> Sealed for ReadOnlyTable<K, V> {}

impl<K: Key + 'static, V: Value + 'static> Debug for ReadOnlyTable<K, V> {
    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
        debug_helper(f, &self.name, self.len(), self.first(), self.last())
    }
}

pub struct ExtractIf<
    'a,
    K: Key + 'static,
    V: Value + 'static,
    F: for<'f> FnMut(K::SelfType<'f>, V::SelfType<'f>) -> bool,
> {
    inner: BtreeExtractIf<'a, K, V, F>,
    cdc: Option<(&'a WriteTransaction, String)>,
}

impl<
    'a,
    K: Key + 'static,
    V: Value + 'static,
    F: for<'f> FnMut(K::SelfType<'f>, V::SelfType<'f>) -> bool,
> ExtractIf<'a, K, V, F>
{
    pub(crate) fn new(inner: BtreeExtractIf<'a, K, V, F>) -> Self {
        Self { inner, cdc: None }
    }

    pub(crate) fn with_cdc(
        inner: BtreeExtractIf<'a, K, V, F>,
        transaction: &'a WriteTransaction,
        table_name: String,
    ) -> Self {
        Self {
            inner,
            cdc: Some((transaction, table_name)),
        }
    }
}

impl<
    'a,
    K: Key + 'static,
    V: Value + 'static,
    F: for<'f> FnMut(K::SelfType<'f>, V::SelfType<'f>) -> bool,
> Iterator for ExtractIf<'a, K, V, F>
{
    type Item = Result<(AccessGuard<'a, K>, AccessGuard<'a, V>)>;

    fn next(&mut self) -> Option<Self::Item> {
        let entry = self.inner.next()?;
        Some(entry.map(|entry| {
            let (page, key_range, value_range, decompressed_value) = entry.into_raw();
            let key = AccessGuard::with_page(page.clone(), key_range);
            let value = if let Some(bytes) = decompressed_value {
                AccessGuard::with_owned_value(bytes)
            } else {
                AccessGuard::with_page(page, value_range)
            };
            if let Some((txn, table_name)) = &self.cdc {
                txn.record_cdc(CdcEvent {
                    table_name: table_name.clone(),
                    op: ChangeOp::Delete,
                    key: K::as_bytes(&key.value()).as_ref().to_vec(),
                    new_value: None,
                    old_value: Some(V::as_bytes(&value.value()).as_ref().to_vec()),
                });
            }
            (key, value)
        }))
    }
}

impl<
    K: Key + 'static,
    V: Value + 'static,
    F: for<'f> FnMut(K::SelfType<'f>, V::SelfType<'f>) -> bool,
> DoubleEndedIterator for ExtractIf<'_, K, V, F>
{
    fn next_back(&mut self) -> Option<Self::Item> {
        let entry = self.inner.next_back()?;
        Some(entry.map(|entry| {
            let (page, key_range, value_range, decompressed_value) = entry.into_raw();
            let key = AccessGuard::with_page(page.clone(), key_range);
            let value = if let Some(bytes) = decompressed_value {
                AccessGuard::with_owned_value(bytes)
            } else {
                AccessGuard::with_page(page, value_range)
            };
            if let Some((txn, table_name)) = &self.cdc {
                txn.record_cdc(CdcEvent {
                    table_name: table_name.clone(),
                    op: ChangeOp::Delete,
                    key: K::as_bytes(&key.value()).as_ref().to_vec(),
                    new_value: None,
                    old_value: Some(V::as_bytes(&value.value()).as_ref().to_vec()),
                });
            }
            (key, value)
        }))
    }
}

#[derive(Clone)]
pub struct Range<'a, K: Key + 'static, V: Value + 'static> {
    inner: BtreeRangeIter<K, V>,
    _transaction_guard: Arc<TransactionGuard>,
    // This lifetime is here so that `&` can be held on `Table` preventing concurrent mutation
    _lifetime: PhantomData<&'a ()>,
}

impl<K: Key + 'static, V: Value + 'static> Range<'_, K, V> {
    pub(super) fn new(inner: BtreeRangeIter<K, V>, guard: Arc<TransactionGuard>) -> Self {
        Self {
            inner,
            _transaction_guard: guard,
            _lifetime: Default::default(),
        }
    }
}

impl<'a, K: Key + 'static, V: Value + 'static> Iterator for Range<'a, K, V> {
    type Item = Result<(AccessGuard<'a, K>, AccessGuard<'a, V>)>;

    fn next(&mut self) -> Option<Self::Item> {
        self.inner.next().map(|x| {
            x.map(|entry| {
                let (page, key_range, value_range, decompressed_value) = entry.into_raw();
                let key = AccessGuard::with_page(page.clone(), key_range);
                let value = if let Some(bytes) = decompressed_value {
                    AccessGuard::with_owned_value(bytes)
                } else {
                    AccessGuard::with_page(page, value_range)
                };
                (key, value)
            })
        })
    }
}

impl<K: Key + 'static, V: Value + 'static> DoubleEndedIterator for Range<'_, K, V> {
    fn next_back(&mut self) -> Option<Self::Item> {
        self.inner.next_back().map(|x| {
            x.map(|entry| {
                let (page, key_range, value_range, decompressed_value) = entry.into_raw();
                let key = AccessGuard::with_page(page.clone(), key_range);
                let value = if let Some(bytes) = decompressed_value {
                    AccessGuard::with_owned_value(bytes)
                } else {
                    AccessGuard::with_page(page, value_range)
                };
                (key, value)
            })
        })
    }
}

// ---------------------------------------------------------------------------
// storage_traits::WriteTable implementation for legacy Table
// ---------------------------------------------------------------------------

use crate::storage_traits::OwnedKv;

/// Iterator adapter that converts `(AccessGuard<K>, AccessGuard<V>)` pairs
/// into `(OwnedKv<K>, OwnedKv<V>)` pairs for the storage trait interface.
pub struct LegacyRangeIter<'a, K: Key + 'static, V: Value + 'static> {
    inner: Range<'a, K, V>,
}

impl<K: Key + 'static, V: Value + 'static> Iterator for LegacyRangeIter<'_, K, V> {
    type Item = crate::Result<(OwnedKv<K>, OwnedKv<V>)>;

    fn next(&mut self) -> Option<Self::Item> {
        self.inner.next().map(|result| {
            result.map(|(k_guard, v_guard)| {
                let k_bytes = K::as_bytes(&k_guard.value()).as_ref().to_vec();
                let v_bytes = V::as_bytes(&v_guard.value()).as_ref().to_vec();
                (OwnedKv::new(k_bytes), OwnedKv::new(v_bytes))
            })
        })
    }
}

impl<K: Key + 'static, V: Value + 'static> crate::storage_traits::WriteTable<K, V>
    for Table<'_, K, V>
{
    type RangeIter<'a>
        = LegacyRangeIter<'a, K, V>
    where
        Self: 'a;

    fn st_get(&self, key: &K::SelfType<'_>) -> crate::Result<Option<OwnedKv<V>>> {
        ReadableTable::get(self, key).map(|opt| {
            opt.map(|guard| {
                let bytes = V::as_bytes(&guard.value()).as_ref().to_vec();
                OwnedKv::new(bytes)
            })
        })
    }

    fn st_insert(
        &mut self,
        key: &K::SelfType<'_>,
        value: &V::SelfType<'_>,
    ) -> crate::Result<Option<OwnedKv<V>>> {
        self.insert(key, value).map(|opt| {
            opt.map(|guard| {
                let bytes = V::as_bytes(&guard.value()).as_ref().to_vec();
                OwnedKv::new(bytes)
            })
        })
    }

    fn st_remove(&mut self, key: &K::SelfType<'_>) -> crate::Result<Option<OwnedKv<V>>> {
        self.remove(key).map(|opt| {
            opt.map(|guard| {
                let bytes = V::as_bytes(&guard.value()).as_ref().to_vec();
                OwnedKv::new(bytes)
            })
        })
    }

    fn st_range<'a>(
        &'a self,
        start: Option<&K::SelfType<'_>>,
        end: Option<&K::SelfType<'_>>,
        start_inclusive: bool,
        end_inclusive: bool,
    ) -> crate::Result<Self::RangeIter<'a>> {
        let inner =
            legacy_build_range::<K, V, Self>(self, start, end, start_inclusive, end_inclusive)?;
        Ok(LegacyRangeIter { inner })
    }

    fn st_drain_all(&mut self) -> crate::Result<u64> {
        self.drain_all()
    }
}

// ---------------------------------------------------------------------------
// storage_traits::ReadTable for Table (writable tables are also readable)
// ---------------------------------------------------------------------------

impl<K: Key + 'static, V: Value + 'static> crate::storage_traits::ReadTable<K, V>
    for Table<'_, K, V>
{
    type RangeIter<'a>
        = LegacyRangeIter<'a, K, V>
    where
        Self: 'a;

    fn st_get(&self, key: &K::SelfType<'_>) -> crate::Result<Option<OwnedKv<V>>> {
        ReadableTable::get(self, key).map(|opt| {
            opt.map(|guard| {
                let bytes = V::as_bytes(&guard.value()).as_ref().to_vec();
                OwnedKv::new(bytes)
            })
        })
    }

    fn st_range<'a>(
        &'a self,
        start: Option<&K::SelfType<'_>>,
        end: Option<&K::SelfType<'_>>,
        start_inclusive: bool,
        end_inclusive: bool,
    ) -> crate::Result<Self::RangeIter<'a>> {
        let inner =
            legacy_build_range::<K, V, Self>(self, start, end, start_inclusive, end_inclusive)?;
        Ok(LegacyRangeIter { inner })
    }
}

// ---------------------------------------------------------------------------
// storage_traits::ReadTable for ReadOnlyTable
// ---------------------------------------------------------------------------

/// Iterator adapter for read-only table range scans.
pub struct LegacyReadOnlyRangeIter<'a, K: Key + 'static, V: Value + 'static> {
    inner: Range<'a, K, V>,
}

impl<K: Key + 'static, V: Value + 'static> Iterator for LegacyReadOnlyRangeIter<'_, K, V> {
    type Item = crate::Result<(OwnedKv<K>, OwnedKv<V>)>;

    fn next(&mut self) -> Option<Self::Item> {
        self.inner.next().map(|result| {
            result.map(|(k_guard, v_guard)| {
                let k_bytes = K::as_bytes(&k_guard.value()).as_ref().to_vec();
                let v_bytes = V::as_bytes(&v_guard.value()).as_ref().to_vec();
                (OwnedKv::new(k_bytes), OwnedKv::new(v_bytes))
            })
        })
    }
}

impl<K: Key + 'static, V: Value + 'static> crate::storage_traits::ReadTable<K, V>
    for ReadOnlyTable<K, V>
{
    type RangeIter<'a>
        = LegacyReadOnlyRangeIter<'a, K, V>
    where
        Self: 'a;

    fn st_get(&self, key: &K::SelfType<'_>) -> crate::Result<Option<OwnedKv<V>>> {
        self.get(key).map(|opt| {
            opt.map(|guard| {
                let bytes = V::as_bytes(&guard.value()).as_ref().to_vec();
                OwnedKv::new(bytes)
            })
        })
    }

    fn st_range<'a>(
        &'a self,
        start: Option<&K::SelfType<'_>>,
        end: Option<&K::SelfType<'_>>,
        start_inclusive: bool,
        end_inclusive: bool,
    ) -> crate::Result<Self::RangeIter<'a>> {
        let inner =
            legacy_build_range_ro::<K, V>(self, start, end, start_inclusive, end_inclusive)?;
        Ok(LegacyReadOnlyRangeIter { inner })
    }
}

// ---------------------------------------------------------------------------
// Range construction helpers (shared logic for building Range from bounds)
// ---------------------------------------------------------------------------

/// Build a `Range` from optional start/end keys for types implementing `ReadableTable`.
fn legacy_build_range<'a, K: Key + 'static, V: Value + 'static, T: ReadableTable<K, V>>(
    table: &'a T,
    start: Option<&K::SelfType<'_>>,
    end: Option<&K::SelfType<'_>>,
    start_inclusive: bool,
    end_inclusive: bool,
) -> crate::Result<Range<'a, K, V>> {
    match (start, end) {
        (None, None) => table.range::<K::SelfType<'_>>(..),
        (Some(s), None) => {
            let s_bytes = K::as_bytes(s).as_ref().to_vec();
            let s_val = K::from_bytes(&s_bytes);
            if start_inclusive {
                table.range::<K::SelfType<'_>>(s_val..)
            } else {
                // Exclusive start bound: start from inclusive, caller filters
                table.range::<K::SelfType<'_>>(s_val..)
            }
        }
        (None, Some(e)) => {
            let e_bytes = K::as_bytes(e).as_ref().to_vec();
            let e_val = K::from_bytes(&e_bytes);
            if end_inclusive {
                table.range::<K::SelfType<'_>>(..=e_val)
            } else {
                table.range::<K::SelfType<'_>>(..e_val)
            }
        }
        (Some(s), Some(e)) => {
            let s_bytes = K::as_bytes(s).as_ref().to_vec();
            let e_bytes = K::as_bytes(e).as_ref().to_vec();
            let s_val = K::from_bytes(&s_bytes);
            let e_val = K::from_bytes(&e_bytes);
            if start_inclusive && end_inclusive {
                table.range::<K::SelfType<'_>>(s_val..=e_val)
            } else if start_inclusive {
                table.range::<K::SelfType<'_>>(s_val..e_val)
            } else if end_inclusive {
                table.range::<K::SelfType<'_>>(s_val..=e_val)
            } else {
                table.range::<K::SelfType<'_>>(s_val..e_val)
            }
        }
    }
}

/// Build a `Range` from optional start/end keys for `ReadOnlyTable`.
///
/// `ReadOnlyTable` has its own `range()` method (not via `ReadableTable` trait)
/// with a slightly different signature (returns `Range<'static, K, V>`).
fn legacy_build_range_ro<'a, K: Key + 'static, V: Value + 'static>(
    table: &'a ReadOnlyTable<K, V>,
    start: Option<&K::SelfType<'_>>,
    end: Option<&K::SelfType<'_>>,
    start_inclusive: bool,
    end_inclusive: bool,
) -> crate::Result<Range<'a, K, V>> {
    match (start, end) {
        (None, None) => table.range::<K::SelfType<'_>>(..),
        (Some(s), None) => {
            let s_bytes = K::as_bytes(s).as_ref().to_vec();
            let s_val = K::from_bytes(&s_bytes);
            // Note: RangeFrom is always inclusive in Rust's std. Exclusive-start
            // semantics are handled by the caller via iterator-level filtering.
            table.range::<K::SelfType<'_>>(s_val..)
        }
        (None, Some(e)) => {
            let e_bytes = K::as_bytes(e).as_ref().to_vec();
            let e_val = K::from_bytes(&e_bytes);
            if end_inclusive {
                table.range::<K::SelfType<'_>>(..=e_val)
            } else {
                table.range::<K::SelfType<'_>>(..e_val)
            }
        }
        (Some(s), Some(e)) => {
            let s_bytes = K::as_bytes(s).as_ref().to_vec();
            let e_bytes = K::as_bytes(e).as_ref().to_vec();
            let s_val = K::from_bytes(&s_bytes);
            let e_val = K::from_bytes(&e_bytes);
            if start_inclusive && end_inclusive {
                table.range::<K::SelfType<'_>>(s_val..=e_val)
            } else if start_inclusive {
                table.range::<K::SelfType<'_>>(s_val..e_val)
            } else if end_inclusive {
                table.range::<K::SelfType<'_>>(s_val..=e_val)
            } else {
                table.range::<K::SelfType<'_>>(s_val..e_val)
            }
        }
    }
}