-
Notifications
You must be signed in to change notification settings - Fork 38
Expand file tree
/
Copy pathtransaction.rs
More file actions
3990 lines (3363 loc) · 141 KB
/
Copy pathtransaction.rs
File metadata and controls
3990 lines (3363 loc) · 141 KB
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
use std::collections::btree_map::Entry as BTreeEntry;
use std::collections::BTreeMap;
use std::ops::{Bound, RangeBounds};
use std::sync::Arc;
use bytes::Bytes;
use vart::VariableSizeKey;
use crate::entry::Entry;
use crate::error::{Error, Result};
use crate::iter::{KeyScanIterator, MergingScanIterator, VersionScanIterator};
use crate::option::IsolationLevel;
use crate::snapshot::Snapshot;
use crate::store::Core;
use crate::util::{convert_range_bounds, now};
/// `Mode` is an enumeration representing the different modes a transaction can have in an MVCC (Multi-Version Concurrency Control) system.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Mode {
/// `ReadWrite` mode allows the transaction to both read and write data.
ReadWrite,
/// `ReadOnly` mode allows the transaction to only read data.
ReadOnly,
/// `WriteOnly` mode allows the transaction to only write data.
WriteOnly,
}
impl Mode {
/// Checks whether the transaction mode can mutate data.
///
/// # Returns
///
/// * `bool` - `true` if the mode is either `ReadWrite` or `WriteOnly`, `false` otherwise.
pub(crate) fn mutable(&self) -> bool {
match self {
Self::ReadWrite => true,
Self::ReadOnly => false,
Self::WriteOnly => true,
}
}
/// Checks if the transaction mode is `WriteOnly`.
///
/// # Returns
///
/// * `bool` - `true` if the mode is `WriteOnly`, `false` otherwise.
pub(crate) fn is_write_only(&self) -> bool {
matches!(self, Self::WriteOnly)
}
/// Checks if the transaction mode is `ReadOnly`.
///
/// # Returns
///
/// * `bool` - `true` if the mode is `ReadOnly`, `false` otherwise.
pub(crate) fn is_read_only(&self) -> bool {
matches!(self, Self::ReadOnly)
}
}
/// ScanResult is a tuple containing the key, value, and commit timestamp of a key-value pair.
pub type ScanResult<'a> = (&'a [u8], Vec<u8>, u64);
/// ScanResult is a tuple containing the key, value, timestamp, and info about whether the key is deleted.
pub type ScanVersionResult<'a> = (&'a [u8], Vec<u8>, u64, bool);
#[derive(Default, Debug, Copy, Clone)]
pub enum Durability {
/// Commits with this durability level are guaranteed to be persistent eventually. The data
/// is written to the disk, but it is not fsynced before returning from [Transaction::commit].
#[default]
Eventual,
/// Commits with this durability level are guaranteed to be persistent as soon as
/// [Transaction::commit] returns.
///
/// Data is fsynced to disk before returning from [Transaction::commit]. This is the slowest
/// durability level, but it is the safest.
Immediate,
}
pub(crate) struct WriteSetEntry {
pub(crate) e: Entry,
savepoint_no: u32,
seqno: u32,
pub(crate) version: u64,
}
impl WriteSetEntry {
pub(crate) fn new(e: Entry, savepoint_no: u32, seqno: u32, version: u64) -> Self {
Self {
e,
savepoint_no,
seqno,
version,
}
}
}
pub(crate) struct ReadSetEntry {
pub(crate) key: Bytes,
pub(crate) ts: u64,
pub(crate) savepoint_no: u32,
}
impl ReadSetEntry {
pub(crate) fn new(key: &[u8], ts: u64, savepoint_no: u32) -> Self {
let key = Bytes::copy_from_slice(key);
Self {
key,
ts,
savepoint_no,
}
}
}
pub(crate) struct ReadScanEntry {
pub(crate) range: (Bound<VariableSizeKey>, Bound<VariableSizeKey>),
pub(crate) savepoint_no: u32,
}
impl ReadScanEntry {
pub(crate) fn new(
range: (Bound<VariableSizeKey>, Bound<VariableSizeKey>),
savepoint_no: u32,
) -> Self {
Self {
range,
savepoint_no,
}
}
}
pub(crate) type ReadSet = Vec<ReadSetEntry>;
pub(crate) type WriteSet = BTreeMap<Bytes, Vec<WriteSetEntry>>;
/// `Transaction` is a struct representing a transaction in a database.
pub struct Transaction {
/// `read_ts` is the read timestamp of the transaction. This is the time at which the transaction started.
pub(crate) read_ts: u64,
/// `mode` is the transaction mode. This can be either `ReadWrite`, `ReadOnly`, or `WriteOnly`.
mode: Mode,
/// `snapshot` is the snapshot that the transaction is running in. This is a consistent view of the data
/// at the time the transaction started.
pub(crate) snapshot: Option<Snapshot>,
/// `core` is the underlying core for the transaction. This is shared between transactions.
pub(crate) core: Arc<Core>,
/// `write_set` is a map of keys to entries.
/// These are the changes that the transaction intends to make to the data.
/// The entries vec is used to keep different values for the same key for
/// savepoints and rollbacks.
pub(crate) write_set: WriteSet,
/// Controls whether read keys and ranges should be stored in the read_set and read_key_ranges respectively.
/// Needed only when the transaction is using Serializable Snapshot Isolation.
track_reads: bool,
/// `read_set` is the keys that are read in the transaction from the snapshot. This is used for conflict detection.
pub(crate) read_set: ReadSet,
/// `read_key_ranges` is the key ranges that are read in the transaction from the snapshot. This is used for conflict detection.
pub(crate) read_key_ranges: Vec<ReadScanEntry>,
/// `durability` is the durability level of the transaction. This is used to determine how the transaction is committed.
durability: Durability,
/// `closed` indicates if the transaction is closed. A closed transaction cannot make any more changes to the data.
closed: bool,
/// `savepoints` indicates the current number of stacked savepoints; zero means none.
savepoints: u32,
/// write sequence number is used for real-time ordering of writes within a transaction.
write_seqno: u32,
/// `versionstamp` is a combination of the transaction ID and the commit timestamp. For internal use only.
versionstamp: Option<(u64, u64)>,
}
impl Transaction {
/// Prepare a new transaction in the given mode.
pub fn new(core: Arc<Core>, mode: Mode) -> Result<Self> {
let mut read_ts = core.read_ts();
let mut snapshot = None;
if !mode.is_write_only() {
let snap = Snapshot::take(&core)?;
// The version with which the snapshot was
// taken supersedes the version taken above.
read_ts = snap.version - 1;
snapshot = Some(snap);
}
// We only need to track reads for SSI.
let track_reads = matches!(
core.opts.isolation_level,
IsolationLevel::SerializableSnapshotIsolation
);
Ok(Self {
read_ts,
mode,
snapshot,
core,
write_set: BTreeMap::new(),
track_reads,
read_set: Vec::new(),
read_key_ranges: Vec::new(),
durability: Durability::Eventual,
closed: false,
savepoints: 0,
write_seqno: 0,
versionstamp: None,
})
}
/// Bump the write sequence number and return it.
fn next_write_seqno(&mut self) -> u32 {
self.write_seqno += 1;
self.write_seqno
}
/// Returns the transaction mode.
pub fn mode(&self) -> Mode {
self.mode
}
/// Sets the durability level of the transaction.
pub fn set_durability(&mut self, durability: Durability) {
self.durability = durability;
}
/// Adds a key-value pair to the store.
pub fn set(&mut self, key: &[u8], value: &[u8]) -> Result<()> {
let mut entry = Entry::new(key, value);
// Replace when versions are disabled.
entry.set_replace(!self.core.opts.enable_versions);
self.write(entry)?;
Ok(())
}
/// Inserts if not present or replaces an existing key-value pair.
pub fn insert_or_replace(&mut self, key: &[u8], value: &[u8]) -> Result<()> {
let mut entry = Entry::new(key, value);
entry.set_replace(true);
self.write(entry)?;
Ok(())
}
/// Adds a key-value pair to the store with the given timestamp.
pub fn set_at_ts(&mut self, key: &[u8], value: &[u8], ts: u64) -> Result<()> {
let mut entry = Entry::new(key, value);
entry.set_ts(ts);
// Replace when versions are disabled.
entry.set_replace(!self.core.opts.enable_versions);
self.write(entry)?;
Ok(())
}
/// Delete all the versions of a key. This is a hard delete.
/// This will remove the key from the index and disk.
pub fn delete(&mut self, key: &[u8]) -> Result<()> {
let value = Bytes::new();
let mut entry = Entry::new(key, &value);
entry.mark_delete();
self.write(entry)?;
Ok(())
}
/// Mark all versions of a key as deleted. This is a soft delete,
/// and does not remove the key from the index, or disk, rather
/// just marks it as deleted, and the key will remain hidden.
pub fn soft_delete(&mut self, key: &[u8]) -> Result<()> {
let value = Bytes::new();
let mut entry = Entry::new(key, &value);
entry.mark_tombstone();
// Replace when versions are disabled.
entry.set_replace(!self.core.opts.enable_versions);
self.write(entry)?;
Ok(())
}
/// Gets a value for a key if it exists.
pub fn get(&mut self, key: &[u8]) -> Result<Option<Vec<u8>>> {
// If the transaction is closed, return an error.
if self.closed {
return Err(Error::TransactionClosed);
}
// If the key is empty, return an error.
if key.is_empty() {
return Err(Error::EmptyKey);
}
// Do not allow reads if it is a write-only transaction
if self.mode.is_write_only() {
return Err(Error::TransactionWriteOnly);
}
// RYOW semantics: Read your own writes. If the value is in the write set, return it.
match self.get_in_write_set(key) {
Some((Some(val), _)) => return Ok(Some(val.to_vec())),
Some((None, _)) => return Ok(None), // Delete in the write set
None => {}
}
// The value is not in the write set, so attempt to get it from the snapshot.
match self.snapshot.as_ref().unwrap().get(&key[..].into()) {
Some((val, version)) => {
// If the transaction is not read-only add the key and its version
// to the read set for conflict detection.
if self.track_reads && !self.mode.is_read_only() {
Self::add_to_read_set(&mut self.read_set, key, version, self.savepoints);
}
// Resolve the value reference to get the actual value.
val.resolve(&self.core).map(Some)
}
None => {
// If the key is not found in the index, and the transaction is not read-only,
// add the key to the read set with a timestamp of 0.
if self.track_reads && !self.mode.is_read_only() {
Self::add_to_read_set(&mut self.read_set, key, 0, self.savepoints);
}
Ok(None)
}
}
}
/// Writes a value for a key. None is used for deletion.
fn write(&mut self, e: Entry) -> Result<()> {
// If the transaction mode is not mutable (i.e., it's read-only), return an error.
if !self.mode.mutable() {
return Err(Error::TransactionReadOnly);
}
// If the transaction is closed, return an error.
if self.closed {
return Err(Error::TransactionClosed);
}
// If the key is empty, return an error.
if e.key.is_empty() {
return Err(Error::EmptyKey);
}
// Set the transaction's latest savepoint number and add it to the write set.
let key = e.key.clone();
let write_seqno = self.next_write_seqno();
let ws_entry = WriteSetEntry::new(e, self.savepoints, write_seqno, self.read_ts);
match self.write_set.entry(key) {
BTreeEntry::Occupied(mut oe) => {
let entries = oe.get_mut();
// If the latest existing value for this key belongs to the same
// savepoint as the value we are about to write, then we can
// overwrite it with the new value.
if let Some(last_entry) = entries.last_mut() {
if last_entry.savepoint_no == ws_entry.savepoint_no {
*last_entry = ws_entry;
} else {
entries.push(ws_entry);
}
} else {
entries.push(ws_entry)
}
}
BTreeEntry::Vacant(ve) => {
ve.insert(vec![ws_entry]);
}
};
Ok(())
}
fn add_to_read_set(read_set: &mut ReadSet, key: &[u8], version: u64, savepoints: u32) {
let entry = ReadSetEntry::new(key, version, savepoints);
read_set.push(entry);
}
// Returning `Some(None, ts)` means that the value has been deleted by this transaction.
fn get_in_write_set(&self, key: &[u8]) -> Option<(Option<Bytes>, u64)> {
if let Some(last_entry) = self.write_set.get(key).and_then(|entries| entries.last()) {
if last_entry.e.is_deleted_or_tombstone() {
Some((None, last_entry.e.ts))
} else {
Some((Some(last_entry.e.value.clone()), last_entry.e.ts))
}
} else {
None
}
}
/// Scans a range of keys and returns a vector of tuples containing the value, version, and timestamp for each key.
pub fn scan<'b, R>(
&'b mut self,
range: R,
limit: Option<usize>,
) -> impl DoubleEndedIterator<Item = Result<ScanResult<'b>>>
where
R: RangeBounds<&'b [u8]>,
{
// Convert the range to a tuple of bounds of variable keys.
let bound_range = convert_range_bounds(&range);
// If enabled, keep track of the reads and range bound predicates for conflict detection
// in case of SSI.
let mut read_set_for_scan = None;
if self.track_reads {
read_set_for_scan = Some(&mut self.read_set);
let rs_entry = ReadScanEntry::new(bound_range.clone(), self.savepoints);
self.read_key_ranges.push(rs_entry);
}
// Get a snapshot iterator for the specified range.
let snap = self.snapshot.as_ref().unwrap();
let snap_iter = snap.range(bound_range.clone());
MergingScanIterator::new(
&self.core,
&self.write_set,
read_set_for_scan,
self.savepoints,
snap_iter,
&bound_range,
limit,
)
}
/// Returns all existing keys within the specified range, including soft-deleted
/// and thus hidden by tombstones.
/// The returned keys are not added to the read set and will not cause read-write conflicts.
pub fn keys_with_tombstones<'b, R>(
&'b self,
range: R,
limit: Option<usize>,
) -> impl Iterator<Item = &'b [u8]>
where
R: RangeBounds<&'b [u8]>,
{
// Convert the range to a tuple of bounds of variable keys.
let range = convert_range_bounds(&range);
let snap_iter = self
.snapshot
.as_ref()
.unwrap()
.range_with_deleted(range.clone());
KeyScanIterator::new(&self.write_set, snap_iter, &range, limit)
}
/// Commits the transaction, by writing all pending entries to the store.
pub fn commit(&mut self) -> Result<()> {
// If the transaction is closed, return an error.
if self.closed {
return Err(Error::TransactionClosed);
}
// If the transaction is read-only, return an error.
if self.mode.is_read_only() {
return Err(Error::TransactionReadOnly);
}
// If there are no pending writes, there's nothing to commit, so return early.
if self.write_set.is_empty() {
return Ok(()); // Return when there's nothing to commit
}
// Drop the snapshot to avoid holding references in the index.
self.snapshot.take();
// Serialize commits to the transaction log.
let write_ch_lock = self.core.commit_write_lock.lock();
// Prepare for the commit by getting a transaction ID.
let (tx_id, commit_ts) = self.prepare_commit()?;
// Extract the vector of entries for the current transaction,
// respecting the insertion order recorded with WriteSetEntry::seqno.
let mut latest_writes: Vec<WriteSetEntry> = std::mem::take(&mut self.write_set)
.into_values()
.filter_map(|mut entries| entries.pop())
.collect();
latest_writes.sort_by(|a, b| a.seqno.cmp(&b.seqno));
let entries: Vec<Entry> = latest_writes
.into_iter()
.map(|ws_entry| {
let mut e = ws_entry.e;
// Assigns commit timestamps to transaction entries.
if e.ts == 0 {
e.ts = commit_ts;
}
e
})
.collect();
// Commit the changes to the store index.
self.core.write_entries(entries, tx_id, self.durability)?;
drop(write_ch_lock);
// Mark the transaction as closed.
self.closed = true;
// Save the versionstamp for internal use.
self.versionstamp = Some((tx_id, commit_ts));
// Return the transaction ID and commit timestamp.
Ok(())
}
/// Prepares for the commit by checking for conflicts
/// and providing commit timestamp.
fn prepare_commit(&self) -> Result<(u64, u64)> {
let tx_id = self.core.oracle.new_commit_ts(self)?;
let commit_ts = now();
Ok((tx_id, commit_ts))
}
/// Rolls back the transaction by removing all updated entries.
pub fn rollback(&mut self) {
self.closed = true;
self.write_set.clear();
self.read_set.clear();
self.snapshot.take();
self.savepoints = 0;
self.write_seqno = 0;
}
/// After calling this method the subsequent modifications within this
/// transaction can be rolled back by calling [`rollback_to_savepoint`].
///
/// This method is stackable and can be called multiple times with the
/// corresponding calls to [`rollback_to_savepoint`].
///
/// [`rollback_to_savepoint`]: Transaction::rollback_to_savepoint
pub fn set_savepoint(&mut self) -> Result<()> {
// If the transaction mode is not mutable (i.e., it's read-only), return an error.
if !self.mode.mutable() {
return Err(Error::TransactionReadOnly);
}
// If the transaction is closed, return an error.
if self.closed {
return Err(Error::TransactionClosed);
}
// Bump the latest savepoint number.
self.savepoints += 1;
Ok(())
}
/// Rollback the state of the transaction to the latest savepoint set by
/// calling [`set_savepoint`].
///
/// [`set_savepoint`]: Transaction::set_savepoint
pub fn rollback_to_savepoint(&mut self) -> Result<()> {
// If the transaction mode is not mutable (i.e., it's read-only), return an error.
if !self.mode.mutable() {
return Err(Error::TransactionReadOnly);
}
// If the transaction is closed, return an error.
if self.closed {
return Err(Error::TransactionClosed);
}
// Check that the savepoint is set
if self.savepoints == 0 {
return Err(Error::TransactionWithoutSavepoint);
}
// For every key in the write set, remove entries marked
// for rollback since the last call to set_savepoint()
// from its vec.
for entries in self.write_set.values_mut() {
entries.retain(|entry| entry.savepoint_no != self.savepoints);
}
// Remove keys with no entries left after the rollback above.
self.write_set.retain(|_, entries| !entries.is_empty());
if self.track_reads {
// Remove marked entries from the read set to
// prevent unnecessary read-write conflicts.
self.read_set
.retain(|entry| entry.savepoint_no != self.savepoints);
// And also from the read scan set.
self.read_key_ranges
.retain(|entry| entry.savepoint_no != self.savepoints);
}
// Decrement the latest savepoint number unless it's zero.
// Cannot undeflow due to the zero check above.
self.savepoints -= 1;
Ok(())
}
}
/// Implement Versioned APIs for read-only transactions.
/// These APIs do not take part in conflict detection.
impl Transaction {
/// Returns the value associated with the key at the given version.
pub fn get_at_version(&self, key: &[u8], version: u64) -> Result<Option<Vec<u8>>> {
// If the key is empty, return an error.
if key.is_empty() {
return Err(Error::EmptyKey);
}
// Consider the value from the write set only if it's lower than of equal
// to the requested `version``.
let ws_val = self
.get_in_write_set(key)
.filter(|(_, ws_ts)| *ws_ts <= version);
let snap_val = self
.snapshot
.as_ref()
.unwrap()
.get_at_version(&key[..].into(), version);
// Similar to `Transaction::merging_scan`, we have to pick where
// the value should come from, the write set or the snapshot.
let result = match (snap_val, ws_val) {
(None, None) => None,
(Some(snap_val), None) => Some(snap_val.0.resolve(&self.core)?),
(None, Some((ws_val, _))) => ws_val.map(|v| v.to_vec()),
(Some(snap_val), Some((ws_val, ws_ts))) => {
assert!(snap_val.1 != ws_ts, "cannot overwrite historical values");
if ws_ts > snap_val.1 {
ws_val.map(|v| v.to_vec())
} else {
Some(snap_val.0.resolve(&self.core)?)
}
}
};
Ok(result)
}
/// Returns all the versioned values and versions associated with the key.
pub fn get_all_versions(&self, key: &[u8]) -> Result<Vec<(Vec<u8>, u64)>> {
// If the key is empty, return an error.
if key.is_empty() {
return Err(Error::EmptyKey);
}
let mut results = Vec::new();
// Check write set first
if let Some(write_val) = self.get_in_write_set(key) {
if let Some(val) = write_val.0 {
results.push((val.to_vec(), write_val.1));
}
}
// Attempt to get the value for the key from the snapshot.
match self
.snapshot
.as_ref()
.unwrap()
.get_version_history(&key[..].into())
{
Some(values) => {
// Resolve the value reference to get the actual value.
for (value, ts) in values {
let resolved_value = value.resolve(&self.core)?;
results.push((resolved_value, ts));
}
}
None => {
// Return the empty vec.
}
}
Ok(results)
}
/// Returns key-value pairs within the specified range, at the given version.
pub fn scan_at_version<'b, R>(
&'b mut self,
range: R,
version: u64,
limit: Option<usize>,
) -> impl Iterator<Item = Result<(&'b [u8], Vec<u8>)>>
where
R: RangeBounds<&'b [u8]>,
{
// Convert the range to a tuple of bounds of variable keys.
let range = convert_range_bounds(&range);
let snap_iter = self
.snapshot
.as_ref()
.unwrap()
.scan_at_version(range.clone(), version);
MergingScanIterator::new(
&self.core,
&self.write_set,
None,
self.savepoints,
snap_iter,
&range,
limit,
)
.map(|result| result.map(|(k, v, _)| (k, v)))
}
/// Returns keys within the specified range, at the given version.
pub fn keys_at_version<'b, R>(
&'b self,
range: R,
version: u64,
limit: Option<usize>,
) -> impl Iterator<Item = &'b [u8]>
where
R: RangeBounds<&'b [u8]>,
{
// Convert the range to a tuple of bounds of variable keys.
let range = convert_range_bounds(&range);
let snap_iter = self
.snapshot
.as_ref()
.unwrap()
.scan_at_version(range.clone(), version);
KeyScanIterator::new(&self.write_set, snap_iter, &range, limit)
}
/// Scans a range of keys and returns a vector of tuples containing the key, value, timestamp, and deletion status for each key.
pub fn scan_all_versions<'b, R>(
&'b self,
range: R,
limit: Option<usize>,
) -> impl Iterator<Item = Result<ScanVersionResult<'b>>>
where
R: RangeBounds<&'b [u8]>,
{
// Convert the range to a tuple of bounds of variable keys.
let range = convert_range_bounds(&range);
let snap = self.snapshot.as_ref().unwrap();
let snap_iter = snap.range_with_versions(range);
VersionScanIterator::new(&self.core, snap_iter, limit)
}
#[allow(unused)]
pub(crate) fn get_versionstamp(&self) -> Option<(u64, u64)> {
self.versionstamp
}
/// Returns only keys within the specified range.
pub fn keys<'b, R>(&'b self, range: R, limit: Option<usize>) -> impl Iterator<Item = &'b [u8]>
where
R: RangeBounds<&'b [u8]>,
{
// Convert the range to a tuple of bounds of variable keys.
let range = convert_range_bounds(&range);
// Get a snapshot iterator for the specified range.
let snap = self.snapshot.as_ref().unwrap();
let snap_iter = snap.range(range.clone());
KeyScanIterator::new(&self.write_set, snap_iter, &range, limit)
}
}
impl Drop for Transaction {
fn drop(&mut self) {
self.rollback();
}
}
#[cfg(test)]
mod tests {
use bytes::Bytes;
use std::collections::HashSet;
use tempdir::TempDir;
use super::*;
use crate::option::{IsolationLevel, Options};
use crate::store::Store;
fn create_temp_directory() -> TempDir {
TempDir::new("test").unwrap()
}
// Common setup logic for creating a store
fn create_store(is_ssi: bool) -> (Store, TempDir) {
let temp_dir = create_temp_directory();
let mut opts = Options::new();
opts.dir = temp_dir.path().to_path_buf();
if is_ssi {
opts.isolation_level = IsolationLevel::SerializableSnapshotIsolation;
}
(
Store::new(opts.clone()).expect("should create store"),
temp_dir,
)
}
// Basic transaction tests
mod basic_transaction_tests {
use super::*;
#[test]
fn basic_transaction() {
let (store, temp_dir) = create_store(false);
// Define key-value pairs for the test
let key1 = Bytes::from("foo1");
let key2 = Bytes::from("foo2");
let value1 = Bytes::from("baz");
let value2 = Bytes::from("bar");
{
// Start a new read-write transaction (txn1)
let mut txn1 = store.begin().unwrap();
txn1.set(&key1, &value1).unwrap();
txn1.set(&key2, &value1).unwrap();
txn1.commit().unwrap();
}
{
// Start a read-only transaction (txn3)
let mut txn3 = store.begin().unwrap();
let val = txn3.get(&key1).unwrap().unwrap();
assert_eq!(val, value1.as_ref());
}
{
// Start another read-write transaction (txn2)
let mut txn2 = store.begin().unwrap();
txn2.set(&key1, &value2).unwrap();
txn2.set(&key2, &value2).unwrap();
txn2.commit().unwrap();
}
// Drop the store to simulate closing it
store.close().unwrap();
// Create a new Core instance with VariableSizeKey after dropping the previous one
let mut opts = Options::new();
opts.dir = temp_dir.path().to_path_buf();
let store = Store::new(opts).expect("should create store");
// Start a read-only transaction (txn4)
let mut txn4 = store.begin().unwrap();
let val = txn4.get(&key1).unwrap().unwrap();
// Assert that the value retrieved in txn4 matches value2
assert_eq!(val, value2.as_ref());
}
#[test]
fn transaction_delete_scan() {
let (store, _) = create_store(false);
// Define key-value pairs for the test
let key1 = Bytes::from("k1");
let value1 = Bytes::from("baz");
{
// Start a new read-write transaction (txn1)
let mut txn1 = store.begin().unwrap();
txn1.set(&key1, &value1).unwrap();
txn1.set(&key1, &value1).unwrap();
txn1.commit().unwrap();
}
{
// Start a read-only transaction (txn)
let mut txn = store.begin().unwrap();
txn.delete(&key1).unwrap();
txn.commit().unwrap();
}
{
// Start another read-write transaction (txn)
let mut txn = store.begin().unwrap();
assert!(txn.get(&key1).unwrap().is_none());
}
{
let range = "k1".as_bytes()..="k3".as_bytes();
let mut txn = store.begin().unwrap();
let results: Vec<_> = txn.scan(range, None).collect();
assert_eq!(results.len(), 0);
}
}
#[test]
fn ryow() {
let temp_dir = create_temp_directory();
let mut opts = Options::new();
opts.dir = temp_dir.path().to_path_buf();
let store = Store::new(opts.clone()).expect("should create store");
let key1 = Bytes::from("k1");
let key2 = Bytes::from("k2");
let key3 = Bytes::from("k3");
let value1 = Bytes::from("v1");
let value2 = Bytes::from("v2");
// Set a key, delete it and read it in the same transaction. Should return None.
{
// Start a new read-write transaction (txn1)
let mut txn1 = store.begin().unwrap();
txn1.set(&key1, &value1).unwrap();
txn1.delete(&key1).unwrap();
let res = txn1.get(&key1).unwrap();
assert!(res.is_none());
txn1.commit().unwrap();
}
{
let mut txn = store.begin().unwrap();
txn.set(&key1, &value1).unwrap();
txn.commit().unwrap();
}
{
// Start a new read-write transaction (txn)
let mut txn = store.begin().unwrap();
txn.set(&key1, &value2).unwrap();
assert_eq!(txn.get(&key1).unwrap().unwrap(), value2.as_ref());
assert!(txn.get(&key3).unwrap().is_none());
txn.set(&key2, &value1).unwrap();
assert_eq!(txn.get(&key2).unwrap().unwrap(), value1.as_ref());
txn.commit().unwrap();
}
}
#[test]
fn transaction_delete_from_index() {
let (store, temp_dir) = create_store(false);
// Define key-value pairs for the test
let key1 = Bytes::from("foo1");
let value = Bytes::from("baz");
let key2 = Bytes::from("foo2");
{
// Start a new read-write transaction (txn1)
let mut txn1 = store.begin().unwrap();
txn1.set(&key1, &value).unwrap();
txn1.set(&key2, &value).unwrap();
txn1.commit().unwrap();
}
{
// Start another read-write transaction (txn2)
let mut txn2 = store.begin().unwrap();
txn2.delete(&key1).unwrap();
txn2.commit().unwrap();
}
{
// Start a read-only transaction (txn3)
let mut txn3 = store.begin().unwrap();
let val = txn3.get(&key1).unwrap();
assert!(val.is_none());
let val = txn3.get(&key2).unwrap().unwrap();
assert_eq!(val, value.as_ref());
}
// Drop the store to simulate closing it
store.close().unwrap();
// sleep for a while to ensure the store is closed
std::thread::sleep(std::time::Duration::from_millis(10));
// Create a new Core instance with VariableSizeKey after dropping the previous one
let mut opts = Options::new();
opts.dir = temp_dir.path().to_path_buf();
let store = Store::new(opts).expect("should create store");
// Start a read-only transaction (txn4)
let mut txn4 = store.begin().unwrap();
let val = txn4.get(&key1).unwrap();
assert!(val.is_none());
let val = txn4.get(&key2).unwrap().unwrap();
assert_eq!(val, value.as_ref());
}
#[test]
fn test_insert_clear_read_key() {
let (store, _) = create_store(false);
// Key-value pair for the test
let key = Bytes::from("test_key");
let value1 = Bytes::from("test_value1");
let value2 = Bytes::from("test_value2");
// Insert key-value pair in a new transaction
{
let mut txn = store.begin().unwrap();
txn.set(&key, &value1).unwrap();
txn.commit().unwrap();
}