#ifndef ROCKSDB_LITE
#include "rocksdb/db.h"
#include "rocksdb/options.h"
#include "rocksdb/slice.h"
#include "rocksdb/utilities/transaction.h"
#include "rocksdb/utilities/optimistic_transaction_db.h"
using namespace ROCKSDB_NAMESPACE;
#if defined(OS_WIN)
std::string kDBPath = "C:\\Windows\\TEMP\\rocksdb_transaction_example";
#else
std::string kDBPath = "/tmp/rocksdb_transaction_example";
#endif
int main() {
Options options;
options.create_if_missing = true;
DB* db;
OptimisticTransactionDB* txn_db;
Status s = OptimisticTransactionDB::Open(options, kDBPath, &txn_db);
assert(s.ok());
db = txn_db->GetBaseDB();
WriteOptions write_options;
ReadOptions read_options;
OptimisticTransactionOptions txn_options;
std::string value;
Transaction* txn = txn_db->BeginTransaction(write_options);
assert(txn);
s = txn->Get(read_options, "abc", &value);
assert(s.IsNotFound());
s = txn->Put("abc", "xyz");
assert(s.ok());
s = db->Get(read_options, "abc", &value);
assert(s.IsNotFound());
s = db->Put(write_options, "xyz", "zzz");
assert(s.ok());
s = db->Put(write_options, "abc", "def");
assert(s.ok());
s = txn->Commit();
assert(s.IsBusy());
delete txn;
s = db->Get(read_options, "xyz", &value);
assert(s.ok());
assert(value == "zzz");
s = db->Get(read_options, "abc", &value);
assert(s.ok());
assert(value == "def");
txn_options.set_snapshot = true;
txn = txn_db->BeginTransaction(write_options, txn_options);
const Snapshot* snapshot = txn->GetSnapshot();
s = db->Put(write_options, "abc", "xyz");
assert(s.ok());
read_options.snapshot = snapshot;
s = txn->GetForUpdate(read_options, "abc", &value);
assert(s.ok());
assert(value == "def");
s = txn->Commit();
assert(s.IsBusy());
delete txn;
read_options.snapshot = nullptr;
snapshot = nullptr;
s = db->Get(read_options, "abc", &value);
assert(s.ok());
assert(value == "xyz");
txn_options.set_snapshot = true;
txn = txn_db->BeginTransaction(write_options, txn_options);
read_options.snapshot = db->GetSnapshot();
s = txn->Get(read_options, "x", &value);
assert(s.IsNotFound());
s = txn->Put("x", "x");
assert(s.ok());
s = db->Get(read_options, "x", &value);
assert(s.IsNotFound());
s = db->Put(write_options, "y", "z");
assert(s.ok());
txn->SetSnapshot();
read_options.snapshot = db->GetSnapshot();
s = txn->GetForUpdate(read_options, "y", &value);
assert(s.ok());
assert(value == "z");
txn->Put("y", "y");
s = txn->Commit();
assert(s.ok());
delete txn;
read_options.snapshot = nullptr;
s = db->Get(read_options, "x", &value);
assert(s.ok());
assert(value == "x");
s = db->Get(read_options, "y", &value);
assert(s.ok());
assert(value == "y");
delete txn_db;
DestroyDB(kDBPath, options);
return 0;
}
#endif