#ifndef ROCKSDB_LITE
#include "rocksdb/db.h"
#include "rocksdb/options.h"
#include "rocksdb/slice.h"
#include "rocksdb/utilities/transaction.h"
#include "rocksdb/utilities/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;
TransactionDBOptions txn_db_options;
options.create_if_missing = true;
TransactionDB* txn_db;
Status s = TransactionDB::Open(options, txn_db_options, kDBPath, &txn_db);
assert(s.ok());
WriteOptions write_options;
ReadOptions read_options;
TransactionOptions 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", "def");
assert(s.ok());
s = txn_db->Get(read_options, "abc", &value);
assert(s.IsNotFound());
s = txn_db->Put(write_options, "xyz", "zzz");
assert(s.ok());
s = txn_db->Put(write_options, "abc", "def");
assert(s.subcode() == Status::kLockTimeout);
s = txn->Get(read_options, "xyz", &value);
assert(s.ok());
assert(value == "zzz");
s = txn->Commit();
assert(s.ok());
delete txn;
s = txn_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 = txn_db->Put(write_options, "abc", "xyz");
assert(s.ok());
s = txn->Get(read_options, "abc", &value);
assert(s.ok());
assert(value == "xyz");
read_options.snapshot = snapshot;
s = txn->Get(read_options, "abc", &value);
assert(s.ok());
assert(value == "def");
s = txn->GetForUpdate(read_options, "abc", &value);
assert(s.IsBusy());
txn->Rollback();
delete txn;
read_options.snapshot = nullptr;
snapshot = nullptr;
txn_options.set_snapshot = true;
txn = txn_db->BeginTransaction(write_options, txn_options);
read_options.snapshot = txn_db->GetSnapshot();
s = txn->Get(read_options, "x", &value);
assert(s.IsNotFound());
s = txn->Put("x", "x");
assert(s.ok());
s = txn_db->Put(write_options, "y", "y1");
assert(s.ok());
txn->SetSnapshot();
txn->SetSavePoint();
read_options.snapshot = txn_db->GetSnapshot();
s = txn->GetForUpdate(read_options, "y", &value);
assert(s.ok());
assert(value == "y1");
s = txn->Put("y", "y2");
assert(s.ok());
txn->RollbackToSavePoint();
s = txn->Commit();
assert(s.ok());
delete txn;
read_options.snapshot = nullptr;
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");
delete txn_db;
DestroyDB(kDBPath, options);
return 0;
}
#endif