Add example to show the effect of Get in snapshot isolation (#6059)

Summary:
Adds example to show the difference of reading from snapshot and from the latest state.
Pull Request resolved: https://github.com/facebook/rocksdb/pull/6059

Test Plan: cd examples && make transaction_example && ./transaction_example

Differential Revision: D18797616

fbshipit-source-id: f17a2cb12187092ea243159e6ccf55790859e0c0
This commit is contained in:
Cheng Chang 2019-12-11 09:55:20 -08:00 committed by Facebook Github Bot
parent 383f5071f0
commit 77565d7532

View File

@ -94,14 +94,25 @@ int main() {
s = txn_db->Put(write_options, "abc", "xyz");
assert(s.ok());
// Read the latest committed value.
s = txn->Get(read_options, "abc", &value);
assert(s.ok());
assert(value == "xyz");
// Read the snapshotted value.
read_options.snapshot = snapshot;
s = txn->Get(read_options, "abc", &value);
assert(s.ok());
assert(value == "def");
// Attempt to read a key using the snapshot. This will fail since
// the previous write outside this txn conflicts with this read.
read_options.snapshot = snapshot;
s = txn->GetForUpdate(read_options, "abc", &value);
assert(s.IsBusy());
txn->Rollback();
// Snapshot will be released upon deleting the transaction.
delete txn;
// Clear snapshot from read options since it is no longer valid
read_options.snapshot = nullptr;
@ -125,10 +136,13 @@ int main() {
// Do some reads and writes to key "x"
read_options.snapshot = txn_db->GetSnapshot();
s = txn->Get(read_options, "x", &value);
txn->Put("x", "x");
assert(s.IsNotFound());
s = txn->Put("x", "x");
assert(s.ok());
// Do a write outside of the transaction to key "y"
s = txn_db->Put(write_options, "y", "y");
s = txn_db->Put(write_options, "y", "y1");
assert(s.ok());
// Set a new snapshot in the transaction
txn->SetSnapshot();
@ -139,7 +153,10 @@ int main() {
// Since the snapshot was advanced, the write done outside of the
// transaction does not conflict.
s = txn->GetForUpdate(read_options, "y", &value);
txn->Put("y", "y");
assert(s.ok());
assert(value == "y1");
s = txn->Put("y", "y2");
assert(s.ok());
// Decide we want to revert the last write from this transaction.
txn->RollbackToSavePoint();
@ -151,6 +168,15 @@ int main() {
// Clear snapshot from read options since it is no longer valid
read_options.snapshot = nullptr;
// db state is at the save point.
s = txn_db->Get(read_options, "x", &value);
assert(s.ok());
assert(value == "x");
s = txn_db->Get(read_options, "y", &value);
assert(s.ok());
assert(value == "y1");
// Cleanup
delete txn_db;
DestroyDB(kDBPath, options);