Refactored tests to use try-with-resources

main
Adam Retter 9 years ago
parent f8e02c7825
commit 0f2d2fcff6
  1. 82
      java/samples/src/main/java/RocksDBColumnFamilySample.java
  2. 510
      java/samples/src/main/java/RocksDBSample.java
  3. 206
      java/src/test/java/org/rocksdb/AbstractComparatorTest.java
  4. 231
      java/src/test/java/org/rocksdb/BackupEngineTest.java
  5. 230
      java/src/test/java/org/rocksdb/BackupableDBOptionsTest.java
  6. 457
      java/src/test/java/org/rocksdb/BackupableDBTest.java
  7. 24
      java/src/test/java/org/rocksdb/BlockBasedTableConfigTest.java
  8. 91
      java/src/test/java/org/rocksdb/CheckPointTest.java
  9. 459
      java/src/test/java/org/rocksdb/ColumnFamilyOptionsTest.java
  10. 1057
      java/src/test/java/org/rocksdb/ColumnFamilyTest.java
  11. 9
      java/src/test/java/org/rocksdb/ComparatorOptionsTest.java
  12. 219
      java/src/test/java/org/rocksdb/ComparatorTest.java
  13. 5
      java/src/test/java/org/rocksdb/CompressionOptionsTest.java
  14. 412
      java/src/test/java/org/rocksdb/DBOptionsTest.java
  15. 70
      java/src/test/java/org/rocksdb/DirectSliceTest.java
  16. 42
      java/src/test/java/org/rocksdb/FilterTest.java
  17. 56
      java/src/test/java/org/rocksdb/FlushTest.java
  18. 66
      java/src/test/java/org/rocksdb/InfoLogLevelTest.java
  19. 110
      java/src/test/java/org/rocksdb/KeyMayExistTest.java
  20. 260
      java/src/test/java/org/rocksdb/LoggerTest.java
  21. 34
      java/src/test/java/org/rocksdb/MemTableTest.java
  22. 359
      java/src/test/java/org/rocksdb/MergeTest.java
  23. 57
      java/src/test/java/org/rocksdb/MixedOptionsTest.java
  24. 2
      java/src/test/java/org/rocksdb/NativeLibraryLoaderTest.java
  25. 743
      java/src/test/java/org/rocksdb/OptionsTest.java
  26. 10
      java/src/test/java/org/rocksdb/PlainTableConfigTest.java
  27. 2
      java/src/test/java/org/rocksdb/PlatformRandomHelper.java
  28. 492
      java/src/test/java/org/rocksdb/ReadOnlyTest.java
  29. 128
      java/src/test/java/org/rocksdb/ReadOptionsTest.java
  30. 835
      java/src/test/java/org/rocksdb/RocksDBTest.java
  31. 35
      java/src/test/java/org/rocksdb/RocksEnvTest.java
  32. 68
      java/src/test/java/org/rocksdb/RocksIteratorTest.java
  33. 162
      java/src/test/java/org/rocksdb/RocksMemEnvTest.java
  34. 4
      java/src/test/java/org/rocksdb/RocksMemoryResource.java
  35. 68
      java/src/test/java/org/rocksdb/SliceTest.java
  36. 288
      java/src/test/java/org/rocksdb/SnapshotTest.java
  37. 32
      java/src/test/java/org/rocksdb/StatisticsCollectorTest.java
  38. 210
      java/src/test/java/org/rocksdb/TransactionLogIteratorTest.java
  39. 160
      java/src/test/java/org/rocksdb/TtlDBTest.java
  40. 83
      java/src/test/java/org/rocksdb/WriteBatchHandlerTest.java
  41. 130
      java/src/test/java/org/rocksdb/WriteBatchTest.java
  42. 232
      java/src/test/java/org/rocksdb/WriteBatchWithIndexTest.java
  43. 21
      java/src/test/java/org/rocksdb/WriteOptionsTest.java

@ -22,73 +22,57 @@ public class RocksDBColumnFamilySample {
String db_path = args[0]; String db_path = args[0];
System.out.println("RocksDBColumnFamilySample"); System.out.println("RocksDBColumnFamilySample");
RocksDB db = null; try(final Options options = new Options().setCreateIfMissing(true);
Options options = null; final RocksDB db = RocksDB.open(options, db_path)) {
ColumnFamilyHandle columnFamilyHandle = null;
WriteBatch wb = null;
try {
options = new Options().setCreateIfMissing(true);
db = RocksDB.open(options, db_path);
assert(db != null); assert(db != null);
// create column family // create column family
columnFamilyHandle = db.createColumnFamily( try(final ColumnFamilyHandle columnFamilyHandle = db.createColumnFamily(
new ColumnFamilyDescriptor("new_cf".getBytes(), new ColumnFamilyDescriptor("new_cf".getBytes(),
new ColumnFamilyOptions())); new ColumnFamilyOptions()))) {
assert(columnFamilyHandle != null); assert (columnFamilyHandle != null);
} finally {
if (columnFamilyHandle != null) {
columnFamilyHandle.dispose();
}
if (db != null) {
db.close();
db = null;
}
if (options != null) {
options.dispose();
} }
} }
// open DB with two column families // open DB with two column families
List<ColumnFamilyDescriptor> columnFamilyDescriptors = new ArrayList<>(); final List<ColumnFamilyDescriptor> columnFamilyDescriptors =
new ArrayList<>();
// have to open default column family // have to open default column family
columnFamilyDescriptors.add(new ColumnFamilyDescriptor( columnFamilyDescriptors.add(new ColumnFamilyDescriptor(
RocksDB.DEFAULT_COLUMN_FAMILY, new ColumnFamilyOptions())); RocksDB.DEFAULT_COLUMN_FAMILY, new ColumnFamilyOptions()));
// open the new one, too // open the new one, too
columnFamilyDescriptors.add(new ColumnFamilyDescriptor( columnFamilyDescriptors.add(new ColumnFamilyDescriptor(
"new_cf".getBytes(), new ColumnFamilyOptions())); "new_cf".getBytes(), new ColumnFamilyOptions()));
List<ColumnFamilyHandle> columnFamilyHandles = new ArrayList<>(); final List<ColumnFamilyHandle> columnFamilyHandles = new ArrayList<>();
try { try(final DBOptions options = new DBOptions();
db = RocksDB.open(new DBOptions(), db_path, final RocksDB db = RocksDB.open(options, db_path,
columnFamilyDescriptors, columnFamilyHandles); columnFamilyDescriptors, columnFamilyHandles)) {
assert(db != null); assert(db != null);
// put and get from non-default column family try {
db.put(columnFamilyHandles.get(0), new WriteOptions(), // put and get from non-default column family
"key".getBytes(), "value".getBytes()); db.put(columnFamilyHandles.get(0), new WriteOptions(),
String value = new String(db.get(columnFamilyHandles.get(0), "key".getBytes(), "value".getBytes());
"key".getBytes())); String value = new String(db.get(columnFamilyHandles.get(0),
"key".getBytes()));
// atomic write // atomic write
wb = new WriteBatch(); try (final WriteBatch wb = new WriteBatch()) {
wb.put(columnFamilyHandles.get(0), "key2".getBytes(), "value2".getBytes()); wb.put(columnFamilyHandles.get(0), "key2".getBytes(),
wb.put(columnFamilyHandles.get(1), "key3".getBytes(), "value3".getBytes()); "value2".getBytes());
wb.remove(columnFamilyHandles.get(0), "key".getBytes()); wb.put(columnFamilyHandles.get(1), "key3".getBytes(),
db.write(new WriteOptions(), wb); "value3".getBytes());
wb.remove(columnFamilyHandles.get(0), "key".getBytes());
db.write(new WriteOptions(), wb);
}
// drop column family // drop column family
db.dropColumnFamily(columnFamilyHandles.get(1)); db.dropColumnFamily(columnFamilyHandles.get(1));
} finally {
} finally { for (final ColumnFamilyHandle handle : columnFamilyHandles) {
for (ColumnFamilyHandle handle : columnFamilyHandles){ handle.close();
handle.dispose(); }
}
if (db != null) {
db.close();
}
if (wb != null) {
wb.dispose();
} }
} }
} }

@ -8,8 +8,10 @@ import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.ArrayList; import java.util.ArrayList;
import org.rocksdb.*; import org.rocksdb.*;
import org.rocksdb.util.SizeUnit; import org.rocksdb.util.SizeUnit;
import java.io.IOException; import java.io.IOException;
public class RocksDBSample { public class RocksDBSample {
@ -26,287 +28,273 @@ public class RocksDBSample {
String db_path_not_found = db_path + "_not_found"; String db_path_not_found = db_path + "_not_found";
System.out.println("RocksDBSample"); System.out.println("RocksDBSample");
RocksDB db = null; try (final Options options = new Options();
Options options = new Options(); final Filter bloomFilter = new BloomFilter(10);
try { final ReadOptions readOptions = new ReadOptions()
db = RocksDB.open(options, db_path_not_found); .setFillCache(false)) {
assert(false);
} catch (RocksDBException e) { try (final RocksDB db = RocksDB.open(options, db_path_not_found)) {
System.out.format("caught the expceted exception -- %s\n", e); assert (false);
assert(db == null); } catch (RocksDBException e) {
} System.out.format("caught the expected exception -- %s\n", e);
}
try { try {
options.setCreateIfMissing(true) options.setCreateIfMissing(true)
.createStatistics() .createStatistics()
.setWriteBufferSize(8 * SizeUnit.KB) .setWriteBufferSize(8 * SizeUnit.KB)
.setMaxWriteBufferNumber(3) .setMaxWriteBufferNumber(3)
.setMaxBackgroundCompactions(10) .setMaxBackgroundCompactions(10)
.setCompressionType(CompressionType.SNAPPY_COMPRESSION) .setCompressionType(CompressionType.SNAPPY_COMPRESSION)
.setCompactionStyle(CompactionStyle.UNIVERSAL); .setCompactionStyle(CompactionStyle.UNIVERSAL);
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
assert(false); assert (false);
} }
Statistics stats = options.statisticsPtr(); Statistics stats = options.statisticsPtr();
assert(options.createIfMissing() == true); assert (options.createIfMissing() == true);
assert(options.writeBufferSize() == 8 * SizeUnit.KB); assert (options.writeBufferSize() == 8 * SizeUnit.KB);
assert(options.maxWriteBufferNumber() == 3); assert (options.maxWriteBufferNumber() == 3);
assert(options.maxBackgroundCompactions() == 10); assert (options.maxBackgroundCompactions() == 10);
assert(options.compressionType() == CompressionType.SNAPPY_COMPRESSION); assert (options.compressionType() == CompressionType.SNAPPY_COMPRESSION);
assert(options.compactionStyle() == CompactionStyle.UNIVERSAL); assert (options.compactionStyle() == CompactionStyle.UNIVERSAL);
assert(options.memTableFactoryName().equals("SkipListFactory")); assert (options.memTableFactoryName().equals("SkipListFactory"));
options.setMemTableConfig( options.setMemTableConfig(
new HashSkipListMemTableConfig() new HashSkipListMemTableConfig()
.setHeight(4) .setHeight(4)
.setBranchingFactor(4) .setBranchingFactor(4)
.setBucketCount(2000000)); .setBucketCount(2000000));
assert(options.memTableFactoryName().equals("HashSkipListRepFactory")); assert (options.memTableFactoryName().equals("HashSkipListRepFactory"));
options.setMemTableConfig( options.setMemTableConfig(
new HashLinkedListMemTableConfig() new HashLinkedListMemTableConfig()
.setBucketCount(100000)); .setBucketCount(100000));
assert(options.memTableFactoryName().equals("HashLinkedListRepFactory")); assert (options.memTableFactoryName().equals("HashLinkedListRepFactory"));
options.setMemTableConfig( options.setMemTableConfig(
new VectorMemTableConfig().setReservedSize(10000)); new VectorMemTableConfig().setReservedSize(10000));
assert(options.memTableFactoryName().equals("VectorRepFactory")); assert (options.memTableFactoryName().equals("VectorRepFactory"));
options.setMemTableConfig(new SkipListMemTableConfig()); options.setMemTableConfig(new SkipListMemTableConfig());
assert(options.memTableFactoryName().equals("SkipListFactory")); assert (options.memTableFactoryName().equals("SkipListFactory"));
options.setTableFormatConfig(new PlainTableConfig()); options.setTableFormatConfig(new PlainTableConfig());
// Plain-Table requires mmap read // Plain-Table requires mmap read
options.setAllowMmapReads(true); options.setAllowMmapReads(true);
assert(options.tableFactoryName().equals("PlainTable")); assert (options.tableFactoryName().equals("PlainTable"));
options.setRateLimiterConfig(new GenericRateLimiterConfig(10000000, options.setRateLimiterConfig(new GenericRateLimiterConfig(10000000,
10000, 10)); 10000, 10));
options.setRateLimiterConfig(new GenericRateLimiterConfig(10000000)); options.setRateLimiterConfig(new GenericRateLimiterConfig(10000000));
final BlockBasedTableConfig table_options = new BlockBasedTableConfig();
Filter bloomFilter = new BloomFilter(10); table_options.setBlockCacheSize(64 * SizeUnit.KB)
BlockBasedTableConfig table_options = new BlockBasedTableConfig(); .setFilter(bloomFilter)
table_options.setBlockCacheSize(64 * SizeUnit.KB) .setCacheNumShardBits(6)
.setFilter(bloomFilter) .setBlockSizeDeviation(5)
.setCacheNumShardBits(6) .setBlockRestartInterval(10)
.setBlockSizeDeviation(5) .setCacheIndexAndFilterBlocks(true)
.setBlockRestartInterval(10) .setHashIndexAllowCollision(false)
.setCacheIndexAndFilterBlocks(true) .setBlockCacheCompressedSize(64 * SizeUnit.KB)
.setHashIndexAllowCollision(false) .setBlockCacheCompressedNumShardBits(10);
.setBlockCacheCompressedSize(64 * SizeUnit.KB)
.setBlockCacheCompressedNumShardBits(10); assert (table_options.blockCacheSize() == 64 * SizeUnit.KB);
assert (table_options.cacheNumShardBits() == 6);
assert(table_options.blockCacheSize() == 64 * SizeUnit.KB); assert (table_options.blockSizeDeviation() == 5);
assert(table_options.cacheNumShardBits() == 6); assert (table_options.blockRestartInterval() == 10);
assert(table_options.blockSizeDeviation() == 5); assert (table_options.cacheIndexAndFilterBlocks() == true);
assert(table_options.blockRestartInterval() == 10); assert (table_options.hashIndexAllowCollision() == false);
assert(table_options.cacheIndexAndFilterBlocks() == true); assert (table_options.blockCacheCompressedSize() == 64 * SizeUnit.KB);
assert(table_options.hashIndexAllowCollision() == false); assert (table_options.blockCacheCompressedNumShardBits() == 10);
assert(table_options.blockCacheCompressedSize() == 64 * SizeUnit.KB);
assert(table_options.blockCacheCompressedNumShardBits() == 10); options.setTableFormatConfig(table_options);
assert (options.tableFactoryName().equals("BlockBasedTable"));
options.setTableFormatConfig(table_options);
assert(options.tableFactoryName().equals("BlockBasedTable")); try (final RocksDB db = RocksDB.open(options, db_path)) {
db.put("hello".getBytes(), "world".getBytes());
try { byte[] value = db.get("hello".getBytes());
db = RocksDB.open(options, db_path); assert ("world".equals(new String(value)));
db.put("hello".getBytes(), "world".getBytes()); String str = db.getProperty("rocksdb.stats");
byte[] value = db.get("hello".getBytes()); assert (str != null && !str.equals(""));
assert("world".equals(new String(value))); } catch (RocksDBException e) {
String str = db.getProperty("rocksdb.stats"); System.out.format("[ERROR] caught the unexpceted exception -- %s\n", e);
assert(str != null && !str.equals("")); assert (false);
} catch (RocksDBException e) {
System.out.format("[ERROR] caught the unexpceted exception -- %s\n", e);
assert(db == null);
assert(false);
}
// be sure to release the c++ pointer
db.close();
ReadOptions readOptions = new ReadOptions();
readOptions.setFillCache(false);
try {
db = RocksDB.open(options, db_path);
db.put("hello".getBytes(), "world".getBytes());
byte[] value = db.get("hello".getBytes());
System.out.format("Get('hello') = %s\n",
new String(value));
for (int i = 1; i <= 9; ++i) {
for (int j = 1; j <= 9; ++j) {
db.put(String.format("%dx%d", i, j).getBytes(),
String.format("%d", i * j).getBytes());
}
} }
for (int i = 1; i <= 9; ++i) { try (final RocksDB db = RocksDB.open(options, db_path)) {
for (int j = 1; j <= 9; ++j) { db.put("hello".getBytes(), "world".getBytes());
System.out.format("%s ", new String(db.get( byte[] value = db.get("hello".getBytes());
String.format("%dx%d", i, j).getBytes()))); System.out.format("Get('hello') = %s\n",
new String(value));
for (int i = 1; i <= 9; ++i) {
for (int j = 1; j <= 9; ++j) {
db.put(String.format("%dx%d", i, j).getBytes(),
String.format("%d", i * j).getBytes());
}
}
for (int i = 1; i <= 9; ++i) {
for (int j = 1; j <= 9; ++j) {
System.out.format("%s ", new String(db.get(
String.format("%dx%d", i, j).getBytes())));
}
System.out.println("");
} }
System.out.println("");
}
// write batch test // write batch test
WriteOptions writeOpt = new WriteOptions(); try (final WriteOptions writeOpt = new WriteOptions()) {
for (int i = 10; i <= 19; ++i) { for (int i = 10; i <= 19; ++i) {
WriteBatch batch = new WriteBatch(); try (final WriteBatch batch = new WriteBatch()) {
for (int j = 10; j <= 19; ++j) { for (int j = 10; j <= 19; ++j) {
batch.put(String.format("%dx%d", i, j).getBytes(), batch.put(String.format("%dx%d", i, j).getBytes(),
String.format("%d", i * j).getBytes()); String.format("%d", i * j).getBytes());
}
db.write(writeOpt, batch);
}
}
} }
db.write(writeOpt, batch); for (int i = 10; i <= 19; ++i) {
batch.dispose(); for (int j = 10; j <= 19; ++j) {
} assert (new String(
for (int i = 10; i <= 19; ++i) { db.get(String.format("%dx%d", i, j).getBytes())).equals(
for (int j = 10; j <= 19; ++j) { String.format("%d", i * j)));
assert(new String( System.out.format("%s ", new String(db.get(
db.get(String.format("%dx%d", i, j).getBytes())).equals( String.format("%dx%d", i, j).getBytes())));
String.format("%d", i * j))); }
System.out.format("%s ", new String(db.get( System.out.println("");
String.format("%dx%d", i, j).getBytes())));
} }
System.out.println("");
}
writeOpt.dispose();
value = db.get("1x1".getBytes());
assert(value != null);
value = db.get("world".getBytes());
assert(value == null);
value = db.get(readOptions, "world".getBytes());
assert(value == null);
byte[] testKey = "asdf".getBytes();
byte[] testValue =
"asdfghjkl;'?><MNBVCXZQWERTYUIOP{+_)(*&^%$#@".getBytes();
db.put(testKey, testValue);
byte[] testResult = db.get(testKey);
assert(testResult != null);
assert(Arrays.equals(testValue, testResult));
assert(new String(testValue).equals(new String(testResult)));
testResult = db.get(readOptions, testKey);
assert(testResult != null);
assert(Arrays.equals(testValue, testResult));
assert(new String(testValue).equals(new String(testResult)));
byte[] insufficientArray = new byte[10];
byte[] enoughArray = new byte[50];
int len;
len = db.get(testKey, insufficientArray);
assert(len > insufficientArray.length);
len = db.get("asdfjkl;".getBytes(), enoughArray);
assert(len == RocksDB.NOT_FOUND);
len = db.get(testKey, enoughArray);
assert(len == testValue.length);
len = db.get(readOptions, testKey, insufficientArray);
assert(len > insufficientArray.length);
len = db.get(readOptions, "asdfjkl;".getBytes(), enoughArray);
assert(len == RocksDB.NOT_FOUND);
len = db.get(readOptions, testKey, enoughArray);
assert(len == testValue.length);
db.remove(testKey);
len = db.get(testKey, enoughArray);
assert(len == RocksDB.NOT_FOUND);
// repeat the test with WriteOptions
WriteOptions writeOpts = new WriteOptions();
writeOpts.setSync(true);
writeOpts.setDisableWAL(true);
db.put(writeOpts, testKey, testValue);
len = db.get(testKey, enoughArray);
assert(len == testValue.length);
assert(new String(testValue).equals(
new String(enoughArray, 0, len)));
writeOpts.dispose();
try { value = db.get("1x1".getBytes());
for (TickerType statsType : TickerType.values()) { assert (value != null);
stats.getTickerCount(statsType); value = db.get("world".getBytes());
assert (value == null);
value = db.get(readOptions, "world".getBytes());
assert (value == null);
byte[] testKey = "asdf".getBytes();
byte[] testValue =
"asdfghjkl;'?><MNBVCXZQWERTYUIOP{+_)(*&^%$#@".getBytes();
db.put(testKey, testValue);
byte[] testResult = db.get(testKey);
assert (testResult != null);
assert (Arrays.equals(testValue, testResult));
assert (new String(testValue).equals(new String(testResult)));
testResult = db.get(readOptions, testKey);
assert (testResult != null);
assert (Arrays.equals(testValue, testResult));
assert (new String(testValue).equals(new String(testResult)));
byte[] insufficientArray = new byte[10];
byte[] enoughArray = new byte[50];
int len;
len = db.get(testKey, insufficientArray);
assert (len > insufficientArray.length);
len = db.get("asdfjkl;".getBytes(), enoughArray);
assert (len == RocksDB.NOT_FOUND);
len = db.get(testKey, enoughArray);
assert (len == testValue.length);
len = db.get(readOptions, testKey, insufficientArray);
assert (len > insufficientArray.length);
len = db.get(readOptions, "asdfjkl;".getBytes(), enoughArray);
assert (len == RocksDB.NOT_FOUND);
len = db.get(readOptions, testKey, enoughArray);
assert (len == testValue.length);
db.remove(testKey);
len = db.get(testKey, enoughArray);
assert (len == RocksDB.NOT_FOUND);
// repeat the test with WriteOptions
try (final WriteOptions writeOpts = new WriteOptions()) {
writeOpts.setSync(true);
writeOpts.setDisableWAL(true);
db.put(writeOpts, testKey, testValue);
len = db.get(testKey, enoughArray);
assert (len == testValue.length);
assert (new String(testValue).equals(
new String(enoughArray, 0, len)));
} }
System.out.println("getTickerCount() passed.");
} catch (Exception e) {
System.out.println("Failed in call to getTickerCount()");
assert(false); //Should never reach here.
}
try { try {
for (HistogramType histogramType : HistogramType.values()) { for (TickerType statsType : TickerType.values()) {
HistogramData data = stats.geHistogramData(histogramType); stats.getTickerCount(statsType);
}
System.out.println("getTickerCount() passed.");
} catch (Exception e) {
System.out.println("Failed in call to getTickerCount()");
assert (false); //Should never reach here.
} }
System.out.println("geHistogramData() passed.");
} catch (Exception e) {
System.out.println("Failed in call to geHistogramData()");
assert(false); //Should never reach here.
}
RocksIterator iterator = db.newIterator();
boolean seekToFirstPassed = false;
for (iterator.seekToFirst(); iterator.isValid(); iterator.next()) {
iterator.status();
assert(iterator.key() != null);
assert(iterator.value() != null);
seekToFirstPassed = true;
}
if(seekToFirstPassed) {
System.out.println("iterator seekToFirst tests passed.");
}
boolean seekToLastPassed = false;
for (iterator.seekToLast(); iterator.isValid(); iterator.prev()) {
iterator.status();
assert(iterator.key() != null);
assert(iterator.value() != null);
seekToLastPassed = true;
}
if(seekToLastPassed) {
System.out.println("iterator seekToLastPassed tests passed.");
}
iterator.seekToFirst(); try {
iterator.seek(iterator.key()); for (HistogramType histogramType : HistogramType.values()) {
assert(iterator.key() != null); HistogramData data = stats.geHistogramData(histogramType);
assert(iterator.value() != null); }
System.out.println("geHistogramData() passed.");
} catch (Exception e) {
System.out.println("Failed in call to geHistogramData()");
assert (false); //Should never reach here.
}
System.out.println("iterator seek test passed."); try (final RocksIterator iterator = db.newIterator()) {
boolean seekToFirstPassed = false;
for (iterator.seekToFirst(); iterator.isValid(); iterator.next()) {
iterator.status();
assert (iterator.key() != null);
assert (iterator.value() != null);
seekToFirstPassed = true;
}
if (seekToFirstPassed) {
System.out.println("iterator seekToFirst tests passed.");
}
boolean seekToLastPassed = false;
for (iterator.seekToLast(); iterator.isValid(); iterator.prev()) {
iterator.status();
assert (iterator.key() != null);
assert (iterator.value() != null);
seekToLastPassed = true;
}
if (seekToLastPassed) {
System.out.println("iterator seekToLastPassed tests passed.");
}
iterator.seekToFirst();
iterator.seek(iterator.key());
assert (iterator.key() != null);
assert (iterator.value() != null);
System.out.println("iterator seek test passed.");
iterator.dispose(); }
System.out.println("iterator tests passed."); System.out.println("iterator tests passed.");
iterator = db.newIterator(); final List<byte[]> keys = new ArrayList<>();
List<byte[]> keys = new ArrayList<byte[]>(); try (final RocksIterator iterator = db.newIterator()) {
for (iterator.seekToLast(); iterator.isValid(); iterator.prev()) { for (iterator.seekToLast(); iterator.isValid(); iterator.prev()) {
keys.add(iterator.key()); keys.add(iterator.key());
} }
iterator.dispose(); }
Map<byte[], byte[]> values = db.multiGet(keys); Map<byte[], byte[]> values = db.multiGet(keys);
assert(values.size() == keys.size()); assert (values.size() == keys.size());
for(byte[] value1 : values.values()) { for (byte[] value1 : values.values()) {
assert(value1 != null); assert (value1 != null);
} }
values = db.multiGet(new ReadOptions(), keys); values = db.multiGet(new ReadOptions(), keys);
assert(values.size() == keys.size()); assert (values.size() == keys.size());
for(byte[] value1 : values.values()) { for (byte[] value1 : values.values()) {
assert(value1 != null); assert (value1 != null);
}
} catch (RocksDBException e) {
System.err.println(e);
} }
} catch (RocksDBException e) {
System.err.println(e);
}
if (db != null) {
db.close();
} }
// be sure to dispose c++ pointers
options.dispose();
readOptions.dispose();
} }
} }

@ -8,6 +8,7 @@ package org.rocksdb;
import java.io.IOException; import java.io.IOException;
import java.nio.file.*; import java.nio.file.*;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.Random; import java.util.Random;
@ -39,57 +40,43 @@ public abstract class AbstractComparatorTest {
* *
* @throws java.io.IOException if IO error happens. * @throws java.io.IOException if IO error happens.
*/ */
public void testRoundtrip(final Path db_path) throws IOException, RocksDBException { public void testRoundtrip(final Path db_path) throws IOException,
RocksDBException {
Options opt = null; try (final AbstractComparator comparator = getAscendingIntKeyComparator();
RocksDB db = null; final Options opt = new Options()
.setCreateIfMissing(true)
try { .setComparator(comparator)) {
opt = new Options();
opt.setCreateIfMissing(true);
opt.setComparator(getAscendingIntKeyComparator());
// store 10,000 random integer keys // store 10,000 random integer keys
final int ITERATIONS = 10000; final int ITERATIONS = 10000;
try (final RocksDB db = RocksDB.open(opt, db_path.toString())) {
db = RocksDB.open(opt, db_path.toString()); final Random random = new Random();
final Random random = new Random(); for (int i = 0; i < ITERATIONS; i++) {
for (int i = 0; i < ITERATIONS; i++) { final byte key[] = intToByte(random.nextInt());
final byte key[] = intToByte(random.nextInt()); // does key already exist (avoid duplicates)
if (i > 0 && db.get(key) != null) { // does key already exist (avoid duplicates) if (i > 0 && db.get(key) != null) {
i--; // generate a different key i--; // generate a different key
} else { } else {
db.put(key, "value".getBytes()); db.put(key, "value".getBytes());
}
} }
} }
db.close();
// re-open db and read from start to end // re-open db and read from start to end
// integer keys should be in ascending // integer keys should be in ascending
// order as defined by SimpleIntComparator // order as defined by SimpleIntComparator
db = RocksDB.open(opt, db_path.toString()); try (final RocksDB db = RocksDB.open(opt, db_path.toString());
final RocksIterator it = db.newIterator(); final RocksIterator it = db.newIterator()) {
it.seekToFirst(); it.seekToFirst();
int lastKey = Integer.MIN_VALUE; int lastKey = Integer.MIN_VALUE;
int count = 0; int count = 0;
for (it.seekToFirst(); it.isValid(); it.next()) { for (it.seekToFirst(); it.isValid(); it.next()) {
final int thisKey = byteToInt(it.key()); final int thisKey = byteToInt(it.key());
assertThat(thisKey).isGreaterThan(lastKey); assertThat(thisKey).isGreaterThan(lastKey);
lastKey = thisKey; lastKey = thisKey;
count++; count++;
} }
it.dispose(); assertThat(count).isEqualTo(ITERATIONS);
db.close();
assertThat(count).isEqualTo(ITERATIONS);
} finally {
if (db != null) {
db.close();
}
if (opt != null) {
opt.dispose();
} }
} }
} }
@ -109,80 +96,75 @@ public abstract class AbstractComparatorTest {
public void testRoundtripCf(final Path db_path) throws IOException, public void testRoundtripCf(final Path db_path) throws IOException,
RocksDBException { RocksDBException {
DBOptions opt = null; try(final AbstractComparator comparator = getAscendingIntKeyComparator()) {
RocksDB db = null; final List<ColumnFamilyDescriptor> cfDescriptors = Arrays.asList(
List<ColumnFamilyDescriptor> cfDescriptors = new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY),
new ArrayList<>(); new ColumnFamilyDescriptor("new_cf".getBytes(),
cfDescriptors.add(new ColumnFamilyDescriptor( new ColumnFamilyOptions().setComparator(comparator))
RocksDB.DEFAULT_COLUMN_FAMILY)); );
cfDescriptors.add(new ColumnFamilyDescriptor("new_cf".getBytes(),
new ColumnFamilyOptions().setComparator(
getAscendingIntKeyComparator())));
List<ColumnFamilyHandle> cfHandles = new ArrayList<>();
try {
opt = new DBOptions().
setCreateIfMissing(true).
setCreateMissingColumnFamilies(true);
// store 10,000 random integer keys
final int ITERATIONS = 10000;
db = RocksDB.open(opt, db_path.toString(), cfDescriptors, cfHandles); final List<ColumnFamilyHandle> cfHandles = new ArrayList<>();
assertThat(cfDescriptors.size()).isEqualTo(2);
assertThat(cfHandles.size()).isEqualTo(2);
final Random random = new Random(); try (final DBOptions opt = new DBOptions().
for (int i = 0; i < ITERATIONS; i++) { setCreateIfMissing(true).
final byte key[] = intToByte(random.nextInt()); setCreateMissingColumnFamilies(true)) {
if (i > 0 && db.get(cfHandles.get(1), key) != null) {
// does key already exist (avoid duplicates) // store 10,000 random integer keys
i--; // generate a different key final int ITERATIONS = 10000;
} else {
db.put(cfHandles.get(1), key, "value".getBytes()); try (final RocksDB db = RocksDB.open(opt, db_path.toString(),
cfDescriptors, cfHandles)) {
try {
assertThat(cfDescriptors.size()).isEqualTo(2);
assertThat(cfHandles.size()).isEqualTo(2);
final Random random = new Random();
for (int i = 0; i < ITERATIONS; i++) {
final byte key[] = intToByte(random.nextInt());
if (i > 0 && db.get(cfHandles.get(1), key) != null) {
// does key already exist (avoid duplicates)
i--; // generate a different key
} else {
db.put(cfHandles.get(1), key, "value".getBytes());
}
}
} finally {
for (final ColumnFamilyHandle handle : cfHandles) {
handle.close();
}
}
cfHandles.clear();
} }
}
for (ColumnFamilyHandle handle : cfHandles) {
handle.dispose();
}
cfHandles.clear();
db.close();
// re-open db and read from start to end
// integer keys should be in ascending
// order as defined by SimpleIntComparator
db = RocksDB.open(opt, db_path.toString(), cfDescriptors, cfHandles);
assertThat(cfDescriptors.size()).isEqualTo(2);
assertThat(cfHandles.size()).isEqualTo(2);
final RocksIterator it = db.newIterator(cfHandles.get(1));
it.seekToFirst();
int lastKey = Integer.MIN_VALUE;
int count = 0;
for (it.seekToFirst(); it.isValid(); it.next()) {
final int thisKey = byteToInt(it.key());
assertThat(thisKey).isGreaterThan(lastKey);
lastKey = thisKey;
count++;
}
it.dispose(); // re-open db and read from start to end
for (ColumnFamilyHandle handle : cfHandles) { // integer keys should be in ascending
handle.dispose(); // order as defined by SimpleIntComparator
} try (final RocksDB db = RocksDB.open(opt, db_path.toString(),
cfHandles.clear(); cfDescriptors, cfHandles);
db.close(); final RocksIterator it = db.newIterator(cfHandles.get(1))) {
assertThat(count).isEqualTo(ITERATIONS); try {
assertThat(cfDescriptors.size()).isEqualTo(2);
} finally { assertThat(cfHandles.size()).isEqualTo(2);
for (ColumnFamilyHandle handle : cfHandles) {
handle.dispose(); it.seekToFirst();
} int lastKey = Integer.MIN_VALUE;
int count = 0;
if (db != null) { for (it.seekToFirst(); it.isValid(); it.next()) {
db.close(); final int thisKey = byteToInt(it.key());
} assertThat(thisKey).isGreaterThan(lastKey);
lastKey = thisKey;
if (opt != null) { count++;
opt.dispose(); }
assertThat(count).isEqualTo(ITERATIONS);
} finally {
for (final ColumnFamilyHandle handle : cfHandles) {
handle.close();
}
}
cfHandles.clear();
}
} }
} }
} }

@ -28,148 +28,96 @@ public class BackupEngineTest {
@Test @Test
public void backupDb() throws RocksDBException { public void backupDb() throws RocksDBException {
Options opt = null; // Open empty database.
RocksDB db = null; try(final Options opt = new Options().setCreateIfMissing(true);
try { final RocksDB db = RocksDB.open(opt,
opt = new Options().setCreateIfMissing(true); dbFolder.getRoot().getAbsolutePath())) {
// Open empty database.
db = RocksDB.open(opt,
dbFolder.getRoot().getAbsolutePath());
// Fill database with some test values // Fill database with some test values
prepareDatabase(db); prepareDatabase(db);
// Create two backups // Create two backups
BackupableDBOptions bopt = null; try(final BackupableDBOptions bopt = new BackupableDBOptions(
try {
bopt = new BackupableDBOptions(
backupFolder.getRoot().getAbsolutePath()); backupFolder.getRoot().getAbsolutePath());
try(final BackupEngine be = BackupEngine.open(opt.getEnv(), bopt)) { final BackupEngine be = BackupEngine.open(opt.getEnv(), bopt)) {
be.createNewBackup(db, false); be.createNewBackup(db, false);
be.createNewBackup(db, true); be.createNewBackup(db, true);
verifyNumberOfValidBackups(be, 2); verifyNumberOfValidBackups(be, 2);
}
} finally {
if(bopt != null) {
bopt.dispose();
}
}
} finally {
if (db != null) {
db.close();
}
if (opt != null) {
opt.dispose();
} }
} }
} }
@Test @Test
public void deleteBackup() throws RocksDBException { public void deleteBackup() throws RocksDBException {
Options opt = null; // Open empty database.
RocksDB db = null; try(final Options opt = new Options().setCreateIfMissing(true);
try { final RocksDB db = RocksDB.open(opt,
opt = new Options().setCreateIfMissing(true); dbFolder.getRoot().getAbsolutePath())) {
// Open empty database.
db = RocksDB.open(opt,
dbFolder.getRoot().getAbsolutePath());
// Fill database with some test values // Fill database with some test values
prepareDatabase(db); prepareDatabase(db);
// Create two backups // Create two backups
BackupableDBOptions bopt = null; try(final BackupableDBOptions bopt = new BackupableDBOptions(
try { backupFolder.getRoot().getAbsolutePath());
bopt = new BackupableDBOptions( final BackupEngine be = BackupEngine.open(opt.getEnv(), bopt)) {
backupFolder.getRoot().getAbsolutePath()); be.createNewBackup(db, false);
try(final BackupEngine be = BackupEngine.open(opt.getEnv(), bopt)) { be.createNewBackup(db, true);
be.createNewBackup(db, false); final List<BackupInfo> backupInfo =
be.createNewBackup(db, true); verifyNumberOfValidBackups(be, 2);
final List<BackupInfo> backupInfo = // Delete the first backup
verifyNumberOfValidBackups(be, 2); be.deleteBackup(backupInfo.get(0).backupId());
// Delete the first backup final List<BackupInfo> newBackupInfo =
be.deleteBackup(backupInfo.get(0).backupId()); verifyNumberOfValidBackups(be, 1);
final List<BackupInfo> newBackupInfo =
verifyNumberOfValidBackups(be, 1); // The second backup must remain.
assertThat(newBackupInfo.get(0).backupId()).
// The second backup must remain. isEqualTo(backupInfo.get(1).backupId());
assertThat(newBackupInfo.get(0).backupId()).
isEqualTo(backupInfo.get(1).backupId());
}
} finally {
if(bopt != null) {
bopt.dispose();
}
}
} finally {
if (db != null) {
db.close();
}
if (opt != null) {
opt.dispose();
} }
} }
} }
@Test @Test
public void purgeOldBackups() throws RocksDBException { public void purgeOldBackups() throws RocksDBException {
Options opt = null; // Open empty database.
RocksDB db = null; try(final Options opt = new Options().setCreateIfMissing(true);
try { final RocksDB db = RocksDB.open(opt,
opt = new Options().setCreateIfMissing(true); dbFolder.getRoot().getAbsolutePath())) {
// Open empty database.
db = RocksDB.open(opt,
dbFolder.getRoot().getAbsolutePath());
// Fill database with some test values // Fill database with some test values
prepareDatabase(db); prepareDatabase(db);
// Create four backups // Create four backups
BackupableDBOptions bopt = null; try(final BackupableDBOptions bopt = new BackupableDBOptions(
try { backupFolder.getRoot().getAbsolutePath());
bopt = new BackupableDBOptions( final BackupEngine be = BackupEngine.open(opt.getEnv(), bopt)) {
backupFolder.getRoot().getAbsolutePath()); be.createNewBackup(db, false);
try(final BackupEngine be = BackupEngine.open(opt.getEnv(), bopt)) { be.createNewBackup(db, true);
be.createNewBackup(db, false); be.createNewBackup(db, true);
be.createNewBackup(db, true); be.createNewBackup(db, true);
be.createNewBackup(db, true); final List<BackupInfo> backupInfo =
be.createNewBackup(db, true); verifyNumberOfValidBackups(be, 4);
final List<BackupInfo> backupInfo = // Delete everything except the latest backup
verifyNumberOfValidBackups(be, 4); be.purgeOldBackups(1);
// Delete everything except the latest backup final List<BackupInfo> newBackupInfo =
be.purgeOldBackups(1); verifyNumberOfValidBackups(be, 1);
final List<BackupInfo> newBackupInfo = // The latest backup must remain.
verifyNumberOfValidBackups(be, 1); assertThat(newBackupInfo.get(0).backupId()).
// The latest backup must remain. isEqualTo(backupInfo.get(3).backupId());
assertThat(newBackupInfo.get(0).backupId()).
isEqualTo(backupInfo.get(3).backupId());
}
} finally {
if(bopt != null) {
bopt.dispose();
}
}
} finally {
if (db != null) {
db.close();
}
if (opt != null) {
opt.dispose();
} }
} }
} }
@Test @Test
public void restoreLatestBackup() public void restoreLatestBackup() throws RocksDBException {
throws RocksDBException { try(final Options opt = new Options().setCreateIfMissing(true)) {
Options opt = null;
RocksDB db = null;
try {
opt = new Options().setCreateIfMissing(true);
// Open empty database. // Open empty database.
db = RocksDB.open(opt, RocksDB db = null;
dbFolder.getRoot().getAbsolutePath());
// Fill database with some test values
prepareDatabase(db);
BackupableDBOptions bopt = null;
try { try {
bopt = new BackupableDBOptions( db = RocksDB.open(opt,
dbFolder.getRoot().getAbsolutePath());
// Fill database with some test values
prepareDatabase(db);
try (final BackupableDBOptions bopt = new BackupableDBOptions(
backupFolder.getRoot().getAbsolutePath()); backupFolder.getRoot().getAbsolutePath());
try (final BackupEngine be = BackupEngine.open(opt.getEnv(), bopt)) { final BackupEngine be = BackupEngine.open(opt.getEnv(), bopt)) {
be.createNewBackup(db, true); be.createNewBackup(db, true);
verifyNumberOfValidBackups(be, 1); verifyNumberOfValidBackups(be, 1);
db.put("key1".getBytes(), "valueV2".getBytes()); db.put("key1".getBytes(), "valueV2".getBytes());
@ -182,51 +130,44 @@ public class BackupEngineTest {
assertThat(new String(db.get("key2".getBytes()))).endsWith("V3"); assertThat(new String(db.get("key2".getBytes()))).endsWith("V3");
db.close(); db.close();
db = null;
verifyNumberOfValidBackups(be, 2); verifyNumberOfValidBackups(be, 2);
// restore db from latest backup // restore db from latest backup
be.restoreDbFromLatestBackup(dbFolder.getRoot().getAbsolutePath(), try(final RestoreOptions ropts = new RestoreOptions(false)) {
dbFolder.getRoot().getAbsolutePath(), be.restoreDbFromLatestBackup(dbFolder.getRoot().getAbsolutePath(),
new RestoreOptions(false)); dbFolder.getRoot().getAbsolutePath(), ropts);
}
// Open database again. // Open database again.
db = RocksDB.open(opt, db = RocksDB.open(opt, dbFolder.getRoot().getAbsolutePath());
dbFolder.getRoot().getAbsolutePath());
// Values must have suffix V2 because of restoring latest backup. // Values must have suffix V2 because of restoring latest backup.
assertThat(new String(db.get("key1".getBytes()))).endsWith("V2"); assertThat(new String(db.get("key1".getBytes()))).endsWith("V2");
assertThat(new String(db.get("key2".getBytes()))).endsWith("V2"); assertThat(new String(db.get("key2".getBytes()))).endsWith("V2");
} }
} finally { } finally {
if(bopt != null) { if(db != null) {
bopt.dispose(); db.close();
} }
} }
} finally {
if (db != null) {
db.close();
}
if (opt != null) {
opt.dispose();
}
} }
} }
@Test @Test
public void restoreFromBackup() public void restoreFromBackup()
throws RocksDBException { throws RocksDBException {
Options opt = null; try(final Options opt = new Options().setCreateIfMissing(true)) {
RocksDB db = null; RocksDB db = null;
try {
opt = new Options().setCreateIfMissing(true);
// Open empty database.
db = RocksDB.open(opt,
dbFolder.getRoot().getAbsolutePath());
// Fill database with some test values
prepareDatabase(db);
BackupableDBOptions bopt = null;
try { try {
bopt = new BackupableDBOptions( // Open empty database.
db = RocksDB.open(opt,
dbFolder.getRoot().getAbsolutePath());
// Fill database with some test values
prepareDatabase(db);
try (final BackupableDBOptions bopt = new BackupableDBOptions(
backupFolder.getRoot().getAbsolutePath()); backupFolder.getRoot().getAbsolutePath());
try (final BackupEngine be = BackupEngine.open(opt.getEnv(), bopt)) { final BackupEngine be = BackupEngine.open(opt.getEnv(), bopt)) {
be.createNewBackup(db, true); be.createNewBackup(db, true);
verifyNumberOfValidBackups(be, 1); verifyNumberOfValidBackups(be, 1);
db.put("key1".getBytes(), "valueV2".getBytes()); db.put("key1".getBytes(), "valueV2".getBytes());
@ -240,9 +181,10 @@ public class BackupEngineTest {
//close the database //close the database
db.close(); db.close();
db = null;
//restore the backup //restore the backup
List<BackupInfo> backupInfo = verifyNumberOfValidBackups(be, 2); final List<BackupInfo> backupInfo = verifyNumberOfValidBackups(be, 2);
// restore db from first backup // restore db from first backup
be.restoreDbFromBackup(backupInfo.get(0).backupId(), be.restoreDbFromBackup(backupInfo.get(0).backupId(),
dbFolder.getRoot().getAbsolutePath(), dbFolder.getRoot().getAbsolutePath(),
@ -256,17 +198,10 @@ public class BackupEngineTest {
assertThat(new String(db.get("key2".getBytes()))).endsWith("V1"); assertThat(new String(db.get("key2".getBytes()))).endsWith("V1");
} }
} finally { } finally {
if(bopt != null) { if(db != null) {
bopt.dispose(); db.close();
} }
} }
} finally {
if (db != null) {
db.close();
}
if (opt != null) {
opt.dispose();
}
} }
} }

@ -16,7 +16,8 @@ import org.junit.rules.ExpectedException;
public class BackupableDBOptionsTest { public class BackupableDBOptionsTest {
private final static String ARBITRARY_PATH = System.getProperty("java.io.tmpdir"); private final static String ARBITRARY_PATH =
System.getProperty("java.io.tmpdir");
@ClassRule @ClassRule
public static final RocksMemoryResource rocksMemoryResource = public static final RocksMemoryResource rocksMemoryResource =
@ -30,87 +31,61 @@ public class BackupableDBOptionsTest {
@Test @Test
public void backupDir() { public void backupDir() {
BackupableDBOptions backupableDBOptions = null; try (final BackupableDBOptions backupableDBOptions =
try { new BackupableDBOptions(ARBITRARY_PATH)) {
backupableDBOptions = new BackupableDBOptions(ARBITRARY_PATH);
assertThat(backupableDBOptions.backupDir()). assertThat(backupableDBOptions.backupDir()).
isEqualTo(ARBITRARY_PATH); isEqualTo(ARBITRARY_PATH);
} finally {
if (backupableDBOptions != null) {
backupableDBOptions.dispose();
}
} }
} }
@Test @Test
public void shareTableFiles() { public void shareTableFiles() {
BackupableDBOptions backupableDBOptions = null; try (final BackupableDBOptions backupableDBOptions =
try { new BackupableDBOptions(ARBITRARY_PATH)) {
backupableDBOptions = new BackupableDBOptions(ARBITRARY_PATH); final boolean value = rand.nextBoolean();
boolean value = rand.nextBoolean();
backupableDBOptions.setShareTableFiles(value); backupableDBOptions.setShareTableFiles(value);
assertThat(backupableDBOptions.shareTableFiles()). assertThat(backupableDBOptions.shareTableFiles()).
isEqualTo(value); isEqualTo(value);
} finally {
if (backupableDBOptions != null) {
backupableDBOptions.dispose();
}
} }
} }
@Test @Test
public void sync() { public void sync() {
BackupableDBOptions backupableDBOptions = null; try (final BackupableDBOptions backupableDBOptions =
try { new BackupableDBOptions(ARBITRARY_PATH)) {
backupableDBOptions = new BackupableDBOptions(ARBITRARY_PATH); final boolean value = rand.nextBoolean();
boolean value = rand.nextBoolean();
backupableDBOptions.setSync(value); backupableDBOptions.setSync(value);
assertThat(backupableDBOptions.sync()).isEqualTo(value); assertThat(backupableDBOptions.sync()).isEqualTo(value);
} finally {
if (backupableDBOptions != null) {
backupableDBOptions.dispose();
}
} }
} }
@Test @Test
public void destroyOldData() { public void destroyOldData() {
BackupableDBOptions backupableDBOptions = null; try (final BackupableDBOptions backupableDBOptions =
try { new BackupableDBOptions(ARBITRARY_PATH);) {
backupableDBOptions = new BackupableDBOptions(ARBITRARY_PATH); final boolean value = rand.nextBoolean();
boolean value = rand.nextBoolean();
backupableDBOptions.setDestroyOldData(value); backupableDBOptions.setDestroyOldData(value);
assertThat(backupableDBOptions.destroyOldData()). assertThat(backupableDBOptions.destroyOldData()).
isEqualTo(value); isEqualTo(value);
} finally {
if (backupableDBOptions != null) {
backupableDBOptions.dispose();
}
} }
} }
@Test @Test
public void backupLogFiles() { public void backupLogFiles() {
BackupableDBOptions backupableDBOptions = null; try (final BackupableDBOptions backupableDBOptions =
try { new BackupableDBOptions(ARBITRARY_PATH)) {
backupableDBOptions = new BackupableDBOptions(ARBITRARY_PATH); final boolean value = rand.nextBoolean();
boolean value = rand.nextBoolean();
backupableDBOptions.setBackupLogFiles(value); backupableDBOptions.setBackupLogFiles(value);
assertThat(backupableDBOptions.backupLogFiles()). assertThat(backupableDBOptions.backupLogFiles()).
isEqualTo(value); isEqualTo(value);
} finally {
if (backupableDBOptions != null) {
backupableDBOptions.dispose();
}
} }
} }
@Test @Test
public void backupRateLimit() { public void backupRateLimit() {
BackupableDBOptions backupableDBOptions = null; try (final BackupableDBOptions backupableDBOptions =
try { new BackupableDBOptions(ARBITRARY_PATH)) {
backupableDBOptions = new BackupableDBOptions(ARBITRARY_PATH); final long value = Math.abs(rand.nextLong());
long value = Math.abs(rand.nextLong());
backupableDBOptions.setBackupRateLimit(value); backupableDBOptions.setBackupRateLimit(value);
assertThat(backupableDBOptions.backupRateLimit()). assertThat(backupableDBOptions.backupRateLimit()).
isEqualTo(value); isEqualTo(value);
@ -118,19 +93,14 @@ public class BackupableDBOptionsTest {
backupableDBOptions.setBackupRateLimit(-1); backupableDBOptions.setBackupRateLimit(-1);
assertThat(backupableDBOptions.backupRateLimit()). assertThat(backupableDBOptions.backupRateLimit()).
isEqualTo(0); isEqualTo(0);
} finally {
if (backupableDBOptions != null) {
backupableDBOptions.dispose();
}
} }
} }
@Test @Test
public void restoreRateLimit() { public void restoreRateLimit() {
BackupableDBOptions backupableDBOptions = null; try (final BackupableDBOptions backupableDBOptions =
try { new BackupableDBOptions(ARBITRARY_PATH)) {
backupableDBOptions = new BackupableDBOptions(ARBITRARY_PATH); final long value = Math.abs(rand.nextLong());
long value = Math.abs(rand.nextLong());
backupableDBOptions.setRestoreRateLimit(value); backupableDBOptions.setRestoreRateLimit(value);
assertThat(backupableDBOptions.restoreRateLimit()). assertThat(backupableDBOptions.restoreRateLimit()).
isEqualTo(value); isEqualTo(value);
@ -138,145 +108,153 @@ public class BackupableDBOptionsTest {
backupableDBOptions.setRestoreRateLimit(-1); backupableDBOptions.setRestoreRateLimit(-1);
assertThat(backupableDBOptions.restoreRateLimit()). assertThat(backupableDBOptions.restoreRateLimit()).
isEqualTo(0); isEqualTo(0);
} finally {
if (backupableDBOptions != null) {
backupableDBOptions.dispose();
}
} }
} }
@Test @Test
public void shareFilesWithChecksum() { public void shareFilesWithChecksum() {
BackupableDBOptions backupableDBOptions = null; try (final BackupableDBOptions backupableDBOptions =
try { new BackupableDBOptions(ARBITRARY_PATH)) {
backupableDBOptions = new BackupableDBOptions(ARBITRARY_PATH);
boolean value = rand.nextBoolean(); boolean value = rand.nextBoolean();
backupableDBOptions.setShareFilesWithChecksum(value); backupableDBOptions.setShareFilesWithChecksum(value);
assertThat(backupableDBOptions.shareFilesWithChecksum()). assertThat(backupableDBOptions.shareFilesWithChecksum()).
isEqualTo(value); isEqualTo(value);
} finally {
if (backupableDBOptions != null) {
backupableDBOptions.dispose();
}
} }
} }
@Test @Test
public void failBackupDirIsNull() { public void failBackupDirIsNull() {
exception.expect(IllegalArgumentException.class); exception.expect(IllegalArgumentException.class);
new BackupableDBOptions(null); try (final BackupableDBOptions opts = new BackupableDBOptions(null)) {
//no-op
}
} }
@Test @Test
public void failBackupDirIfDisposed(){ public void failBackupDirIfDisposed() {
BackupableDBOptions options = setupUninitializedBackupableDBOptions( try (final BackupableDBOptions options =
exception); setupUninitializedBackupableDBOptions(exception)) {
options.backupDir(); options.backupDir();
}
} }
@Test @Test
public void failSetShareTableFilesIfDisposed(){ public void failSetShareTableFilesIfDisposed() {
BackupableDBOptions options = setupUninitializedBackupableDBOptions( try (final BackupableDBOptions options =
exception); setupUninitializedBackupableDBOptions(exception)) {
options.setShareTableFiles(true); options.setShareTableFiles(true);
}
} }
@Test @Test
public void failShareTableFilesIfDisposed(){ public void failShareTableFilesIfDisposed() {
BackupableDBOptions options = setupUninitializedBackupableDBOptions( try (BackupableDBOptions options =
exception); setupUninitializedBackupableDBOptions(exception)) {
options.shareTableFiles(); options.shareTableFiles();
}
} }
@Test @Test
public void failSetSyncIfDisposed(){ public void failSetSyncIfDisposed() {
BackupableDBOptions options = setupUninitializedBackupableDBOptions( try (final BackupableDBOptions options =
exception); setupUninitializedBackupableDBOptions(exception)) {
options.setSync(true); options.setSync(true);
}
} }
@Test @Test
public void failSyncIfDisposed(){ public void failSyncIfDisposed() {
BackupableDBOptions options = setupUninitializedBackupableDBOptions( try (final BackupableDBOptions options =
exception); setupUninitializedBackupableDBOptions(exception)) {
options.sync(); options.sync();
}
} }
@Test @Test
public void failSetDestroyOldDataIfDisposed(){ public void failSetDestroyOldDataIfDisposed() {
BackupableDBOptions options = setupUninitializedBackupableDBOptions( try (final BackupableDBOptions options =
exception); setupUninitializedBackupableDBOptions(exception)) {
options.setDestroyOldData(true); options.setDestroyOldData(true);
}
} }
@Test @Test
public void failDestroyOldDataIfDisposed(){ public void failDestroyOldDataIfDisposed() {
BackupableDBOptions options = setupUninitializedBackupableDBOptions( try (final BackupableDBOptions options =
exception); setupUninitializedBackupableDBOptions(exception)) {
options.destroyOldData(); options.destroyOldData();
}
} }
@Test @Test
public void failSetBackupLogFilesIfDisposed(){ public void failSetBackupLogFilesIfDisposed() {
BackupableDBOptions options = setupUninitializedBackupableDBOptions( try (final BackupableDBOptions options =
exception); setupUninitializedBackupableDBOptions(exception)) {
options.setBackupLogFiles(true); options.setBackupLogFiles(true);
}
} }
@Test @Test
public void failBackupLogFilesIfDisposed(){ public void failBackupLogFilesIfDisposed() {
BackupableDBOptions options = setupUninitializedBackupableDBOptions( try (final BackupableDBOptions options =
exception); setupUninitializedBackupableDBOptions(exception)) {
options.backupLogFiles(); options.backupLogFiles();
}
} }
@Test @Test
public void failSetBackupRateLimitIfDisposed(){ public void failSetBackupRateLimitIfDisposed() {
BackupableDBOptions options = setupUninitializedBackupableDBOptions( try (final BackupableDBOptions options =
exception); setupUninitializedBackupableDBOptions(exception)) {
options.setBackupRateLimit(1); options.setBackupRateLimit(1);
}
} }
@Test @Test
public void failBackupRateLimitIfDisposed(){ public void failBackupRateLimitIfDisposed() {
BackupableDBOptions options = setupUninitializedBackupableDBOptions( try (final BackupableDBOptions options =
exception); setupUninitializedBackupableDBOptions(exception)) {
options.backupRateLimit(); options.backupRateLimit();
}
} }
@Test @Test
public void failSetRestoreRateLimitIfDisposed(){ public void failSetRestoreRateLimitIfDisposed() {
BackupableDBOptions options = setupUninitializedBackupableDBOptions( try (final BackupableDBOptions options =
exception); setupUninitializedBackupableDBOptions(exception)) {
options.setRestoreRateLimit(1); options.setRestoreRateLimit(1);
}
} }
@Test @Test
public void failRestoreRateLimitIfDisposed(){ public void failRestoreRateLimitIfDisposed() {
BackupableDBOptions options = setupUninitializedBackupableDBOptions( try (final BackupableDBOptions options =
exception); setupUninitializedBackupableDBOptions(exception)) {
options.restoreRateLimit(); options.restoreRateLimit();
}
} }
@Test @Test
public void failSetShareFilesWithChecksumIfDisposed(){ public void failSetShareFilesWithChecksumIfDisposed() {
BackupableDBOptions options = setupUninitializedBackupableDBOptions( try (final BackupableDBOptions options =
exception); setupUninitializedBackupableDBOptions(exception)) {
options.setShareFilesWithChecksum(true); options.setShareFilesWithChecksum(true);
}
} }
@Test @Test
public void failShareFilesWithChecksumIfDisposed(){ public void failShareFilesWithChecksumIfDisposed() {
BackupableDBOptions options = setupUninitializedBackupableDBOptions( try (final BackupableDBOptions options =
exception); setupUninitializedBackupableDBOptions(exception)) {
options.shareFilesWithChecksum(); options.shareFilesWithChecksum();
}
} }
private BackupableDBOptions setupUninitializedBackupableDBOptions( private BackupableDBOptions setupUninitializedBackupableDBOptions(
ExpectedException exception) { ExpectedException exception) {
BackupableDBOptions backupableDBOptions = final BackupableDBOptions backupableDBOptions =
new BackupableDBOptions(ARBITRARY_PATH); new BackupableDBOptions(ARBITRARY_PATH);
backupableDBOptions.dispose(); backupableDBOptions.close();
exception.expect(AssertionError.class); exception.expect(AssertionError.class);
return backupableDBOptions; return backupableDBOptions;
} }

@ -28,74 +28,48 @@ public class BackupableDBTest {
@Test @Test
public void backupDb() throws RocksDBException { public void backupDb() throws RocksDBException {
Options opt = null; try (final Options opt = new Options().setCreateIfMissing(true);
BackupableDBOptions bopt = null; final BackupableDBOptions bopt = new BackupableDBOptions(
BackupableDB bdb = null; backupFolder.getRoot().getAbsolutePath())) {
try {
opt = new Options().setCreateIfMissing(true);
bopt = new BackupableDBOptions(
backupFolder.getRoot().getAbsolutePath());
assertThat(bopt.backupDir()).isEqualTo( assertThat(bopt.backupDir()).isEqualTo(
backupFolder.getRoot().getAbsolutePath()); backupFolder.getRoot().getAbsolutePath());
// Open empty database. // Open empty database.
bdb = BackupableDB.open(opt, bopt, try (final BackupableDB bdb = BackupableDB.open(opt, bopt,
dbFolder.getRoot().getAbsolutePath()); dbFolder.getRoot().getAbsolutePath())) {
// Fill database with some test values // Fill database with some test values
prepareDatabase(bdb); prepareDatabase(bdb);
// Create two backups // Create two backups
bdb.createNewBackup(false); bdb.createNewBackup(false);
bdb.createNewBackup(true); bdb.createNewBackup(true);
verifyNumberOfValidBackups(bdb, 2); verifyNumberOfValidBackups(bdb, 2);
} finally {
if (bdb != null) {
bdb.close();
}
if (bopt != null) {
bopt.dispose();
}
if (opt != null) {
opt.dispose();
} }
} }
} }
@Test @Test
public void deleteBackup() throws RocksDBException { public void deleteBackup() throws RocksDBException {
Options opt = null; try (final Options opt = new Options().setCreateIfMissing(true);
BackupableDBOptions bopt = null; final BackupableDBOptions bopt = new BackupableDBOptions(
BackupableDB bdb = null; backupFolder.getRoot().getAbsolutePath())) {
try {
opt = new Options().setCreateIfMissing(true);
bopt = new BackupableDBOptions(
backupFolder.getRoot().getAbsolutePath());
assertThat(bopt.backupDir()).isEqualTo( assertThat(bopt.backupDir()).isEqualTo(
backupFolder.getRoot().getAbsolutePath()); backupFolder.getRoot().getAbsolutePath());
// Open empty database. // Open empty database.
bdb = BackupableDB.open(opt, bopt, try (final BackupableDB bdb = BackupableDB.open(opt, bopt,
dbFolder.getRoot().getAbsolutePath()); dbFolder.getRoot().getAbsolutePath())) {
// Fill database with some test values // Fill database with some test values
prepareDatabase(bdb); prepareDatabase(bdb);
// Create two backups // Create two backups
bdb.createNewBackup(false); bdb.createNewBackup(false);
bdb.createNewBackup(true); bdb.createNewBackup(true);
List<BackupInfo> backupInfo = List<BackupInfo> backupInfo =
verifyNumberOfValidBackups(bdb, 2); verifyNumberOfValidBackups(bdb, 2);
// Delete the first backup // Delete the first backup
bdb.deleteBackup(backupInfo.get(0).backupId()); bdb.deleteBackup(backupInfo.get(0).backupId());
List<BackupInfo> newBackupInfo = final List<BackupInfo> newBackupInfo =
verifyNumberOfValidBackups(bdb, 1); verifyNumberOfValidBackups(bdb, 1);
// The second backup must remain. // The second backup must remain.
assertThat(newBackupInfo.get(0).backupId()). assertThat(newBackupInfo.get(0).backupId()).
isEqualTo(backupInfo.get(1).backupId()); isEqualTo(backupInfo.get(1).backupId());
} finally {
if (bdb != null) {
bdb.close();
}
if (bopt != null) {
bopt.dispose();
}
if (opt != null) {
opt.dispose();
} }
} }
} }
@ -103,90 +77,61 @@ public class BackupableDBTest {
@Test @Test
public void deleteBackupWithRestoreBackupableDB() public void deleteBackupWithRestoreBackupableDB()
throws RocksDBException { throws RocksDBException {
Options opt = null; try (final Options opt = new Options().setCreateIfMissing(true);
BackupableDBOptions bopt = null; final BackupableDBOptions bopt = new BackupableDBOptions(
BackupableDB bdb = null; backupFolder.getRoot().getAbsolutePath())) {
RestoreBackupableDB rdb = null;
try {
opt = new Options().setCreateIfMissing(true);
bopt = new BackupableDBOptions(
backupFolder.getRoot().getAbsolutePath());
assertThat(bopt.backupDir()).isEqualTo( assertThat(bopt.backupDir()).isEqualTo(
backupFolder.getRoot().getAbsolutePath()); backupFolder.getRoot().getAbsolutePath());
// Open empty database. // Open empty database.
bdb = BackupableDB.open(opt, bopt, try (final BackupableDB bdb = BackupableDB.open(opt, bopt,
dbFolder.getRoot().getAbsolutePath()); dbFolder.getRoot().getAbsolutePath())) {
// Fill database with some test values // Fill database with some test values
prepareDatabase(bdb); prepareDatabase(bdb);
// Create two backups // Create two backups
bdb.createNewBackup(false); bdb.createNewBackup(false);
bdb.createNewBackup(true); bdb.createNewBackup(true);
List<BackupInfo> backupInfo = final List<BackupInfo> backupInfo =
verifyNumberOfValidBackups(bdb, 2); verifyNumberOfValidBackups(bdb, 2);
// init RestoreBackupableDB // init RestoreBackupableDB
rdb = new RestoreBackupableDB(bopt); try (final RestoreBackupableDB rdb = new RestoreBackupableDB(bopt)) {
// Delete the first backup // Delete the first backup
rdb.deleteBackup(backupInfo.get(0).backupId()); rdb.deleteBackup(backupInfo.get(0).backupId());
// Fetch backup info using RestoreBackupableDB // Fetch backup info using RestoreBackupableDB
List<BackupInfo> newBackupInfo = verifyNumberOfValidBackups(rdb, 1); List<BackupInfo> newBackupInfo = verifyNumberOfValidBackups(rdb, 1);
// The second backup must remain. // The second backup must remain.
assertThat(newBackupInfo.get(0).backupId()). assertThat(newBackupInfo.get(0).backupId()).
isEqualTo(backupInfo.get(1).backupId()); isEqualTo(backupInfo.get(1).backupId());
} finally { }
if (bdb != null) {
bdb.close();
}
if (rdb != null) {
rdb.dispose();
}
if (bopt != null) {
bopt.dispose();
}
if (opt != null) {
opt.dispose();
} }
} }
} }
@Test @Test
public void purgeOldBackups() throws RocksDBException { public void purgeOldBackups() throws RocksDBException {
Options opt = null; try (final Options opt = new Options().setCreateIfMissing(true);
BackupableDBOptions bopt = null; final BackupableDBOptions bopt = new BackupableDBOptions(
BackupableDB bdb = null; backupFolder.getRoot().getAbsolutePath())) {
try {
opt = new Options().setCreateIfMissing(true);
bopt = new BackupableDBOptions(
backupFolder.getRoot().getAbsolutePath());
assertThat(bopt.backupDir()).isEqualTo( assertThat(bopt.backupDir()).isEqualTo(
backupFolder.getRoot().getAbsolutePath()); backupFolder.getRoot().getAbsolutePath());
// Open empty database. // Open empty database.
bdb = BackupableDB.open(opt, bopt, try (final BackupableDB bdb = BackupableDB.open(opt, bopt,
dbFolder.getRoot().getAbsolutePath()); dbFolder.getRoot().getAbsolutePath())) {
// Fill database with some test values // Fill database with some test values
prepareDatabase(bdb); prepareDatabase(bdb);
// Create two backups // Create two backups
bdb.createNewBackup(false); bdb.createNewBackup(false);
bdb.createNewBackup(true); bdb.createNewBackup(true);
bdb.createNewBackup(true); bdb.createNewBackup(true);
bdb.createNewBackup(true); bdb.createNewBackup(true);
List<BackupInfo> backupInfo = final List<BackupInfo> backupInfo =
verifyNumberOfValidBackups(bdb, 4); verifyNumberOfValidBackups(bdb, 4);
// Delete everything except the latest backup // Delete everything except the latest backup
bdb.purgeOldBackups(1); bdb.purgeOldBackups(1);
List<BackupInfo> newBackupInfo = final List<BackupInfo> newBackupInfo =
verifyNumberOfValidBackups(bdb, 1); verifyNumberOfValidBackups(bdb, 1);
// The latest backup must remain. // The latest backup must remain.
assertThat(newBackupInfo.get(0).backupId()). assertThat(newBackupInfo.get(0).backupId()).
isEqualTo(backupInfo.get(3).backupId()); isEqualTo(backupInfo.get(3).backupId());
} finally {
if (bdb != null) {
bdb.close();
}
if (bopt != null) {
bopt.dispose();
}
if (opt != null) {
opt.dispose();
} }
} }
} }
@ -194,58 +139,43 @@ public class BackupableDBTest {
@Test @Test
public void purgeOldBackupsWithRestoreBackupableDb() public void purgeOldBackupsWithRestoreBackupableDb()
throws RocksDBException { throws RocksDBException {
Options opt = null; try (final Options opt = new Options().setCreateIfMissing(true);
BackupableDBOptions bopt = null; final BackupableDBOptions bopt =
BackupableDB bdb = null; new BackupableDBOptions(backupFolder.getRoot().getAbsolutePath())
RestoreBackupableDB rdb = null; ) {
try {
opt = new Options().setCreateIfMissing(true);
bopt = new BackupableDBOptions(
backupFolder.getRoot().getAbsolutePath());
assertThat(bopt.backupDir()).isEqualTo( assertThat(bopt.backupDir()).isEqualTo(
backupFolder.getRoot().getAbsolutePath()); backupFolder.getRoot().getAbsolutePath());
// Open empty database. // Open empty database.
bdb = BackupableDB.open(opt, bopt, try (final BackupableDB bdb = BackupableDB.open(opt, bopt,
dbFolder.getRoot().getAbsolutePath()); dbFolder.getRoot().getAbsolutePath())) {
// Fill database with some test values // Fill database with some test values
prepareDatabase(bdb); prepareDatabase(bdb);
// Create two backups // Create two backups
bdb.createNewBackup(false); bdb.createNewBackup(false);
bdb.createNewBackup(true); bdb.createNewBackup(true);
bdb.createNewBackup(true); bdb.createNewBackup(true);
bdb.createNewBackup(true); bdb.createNewBackup(true);
List<BackupInfo> infos = verifyNumberOfValidBackups(bdb, 4); List<BackupInfo> infos = verifyNumberOfValidBackups(bdb, 4);
assertThat(infos.get(1).size()). assertThat(infos.get(1).size()).
isEqualTo(infos.get(2).size()); isEqualTo(infos.get(2).size());
assertThat(infos.get(1).numberFiles()). assertThat(infos.get(1).numberFiles()).
isEqualTo(infos.get(2).numberFiles()); isEqualTo(infos.get(2).numberFiles());
long maxTimeBeforePurge = Long.MIN_VALUE; long maxTimeBeforePurge = Long.MIN_VALUE;
for (BackupInfo backupInfo : infos) { for (BackupInfo backupInfo : infos) {
if (maxTimeBeforePurge < backupInfo.timestamp()) { if (maxTimeBeforePurge < backupInfo.timestamp()) {
maxTimeBeforePurge = backupInfo.timestamp(); maxTimeBeforePurge = backupInfo.timestamp();
}
}
// init RestoreBackupableDB
try (final RestoreBackupableDB rdb = new RestoreBackupableDB(bopt)) {
// the same number of backups must
// exist using RestoreBackupableDB.
verifyNumberOfValidBackups(rdb, 4);
rdb.purgeOldBackups(1);
infos = verifyNumberOfValidBackups(rdb, 1);
assertThat(infos.get(0).timestamp()).
isEqualTo(maxTimeBeforePurge);
} }
}
// init RestoreBackupableDB
rdb = new RestoreBackupableDB(bopt);
// the same number of backups must
// exist using RestoreBackupableDB.
verifyNumberOfValidBackups(rdb, 4);
rdb.purgeOldBackups(1);
infos = verifyNumberOfValidBackups(rdb, 1);
assertThat(infos.get(0).timestamp()).
isEqualTo(maxTimeBeforePurge);
} finally {
if (bdb != null) {
bdb.close();
}
if (rdb != null) {
rdb.dispose();
}
if (bopt != null) {
bopt.dispose();
}
if (opt != null) {
opt.dispose();
} }
} }
} }
@ -253,58 +183,44 @@ public class BackupableDBTest {
@Test @Test
public void restoreLatestBackup() public void restoreLatestBackup()
throws RocksDBException { throws RocksDBException {
Options opt = null; try (final Options opt = new Options().setCreateIfMissing(true);
BackupableDBOptions bopt = null; final BackupableDBOptions bopt =
BackupableDB bdb = null; new BackupableDBOptions(
RestoreBackupableDB rdb = null; backupFolder.getRoot().getAbsolutePath())) {
try {
opt = new Options().setCreateIfMissing(true);
bopt = new BackupableDBOptions(
backupFolder.getRoot().getAbsolutePath());
assertThat(bopt.backupDir()).isEqualTo( assertThat(bopt.backupDir()).isEqualTo(
backupFolder.getRoot().getAbsolutePath()); backupFolder.getRoot().getAbsolutePath());
// Open empty database. // Open empty database.
bdb = BackupableDB.open(opt, bopt, try (final BackupableDB bdb = BackupableDB.open(opt, bopt,
dbFolder.getRoot().getAbsolutePath()); dbFolder.getRoot().getAbsolutePath())) {
// Fill database with some test values // Fill database with some test values
prepareDatabase(bdb); prepareDatabase(bdb);
bdb.createNewBackup(true); bdb.createNewBackup(true);
verifyNumberOfValidBackups(bdb, 1); verifyNumberOfValidBackups(bdb, 1);
bdb.put("key1".getBytes(), "valueV2".getBytes()); bdb.put("key1".getBytes(), "valueV2".getBytes());
bdb.put("key2".getBytes(), "valueV2".getBytes()); bdb.put("key2".getBytes(), "valueV2".getBytes());
bdb.createNewBackup(true); bdb.createNewBackup(true);
verifyNumberOfValidBackups(bdb, 2); verifyNumberOfValidBackups(bdb, 2);
bdb.put("key1".getBytes(), "valueV3".getBytes()); bdb.put("key1".getBytes(), "valueV3".getBytes());
bdb.put("key2".getBytes(), "valueV3".getBytes()); bdb.put("key2".getBytes(), "valueV3".getBytes());
assertThat(new String(bdb.get("key1".getBytes()))).endsWith("V3"); assertThat(new String(bdb.get("key1".getBytes()))).endsWith("V3");
assertThat(new String(bdb.get("key2".getBytes()))).endsWith("V3"); assertThat(new String(bdb.get("key2".getBytes()))).endsWith("V3");
bdb.close(); }
// init RestoreBackupableDB // init RestoreBackupableDB
rdb = new RestoreBackupableDB(bopt); try (final RestoreBackupableDB rdb = new RestoreBackupableDB(bopt)) {
verifyNumberOfValidBackups(rdb, 2); verifyNumberOfValidBackups(rdb, 2);
// restore db from latest backup // restore db from latest backup
rdb.restoreDBFromLatestBackup(dbFolder.getRoot().getAbsolutePath(), rdb.restoreDBFromLatestBackup(dbFolder.getRoot().getAbsolutePath(),
dbFolder.getRoot().getAbsolutePath(), dbFolder.getRoot().getAbsolutePath(),
new RestoreOptions(false)); new RestoreOptions(false));
// Open database again.
bdb = BackupableDB.open(opt, bopt,
dbFolder.getRoot().getAbsolutePath());
// Values must have suffix V2 because of restoring latest backup.
assertThat(new String(bdb.get("key1".getBytes()))).endsWith("V2");
assertThat(new String(bdb.get("key2".getBytes()))).endsWith("V2");
} finally {
if (bdb != null) {
bdb.close();
}
if (rdb != null) {
rdb.dispose();
}
if (bopt != null) {
bopt.dispose();
} }
if (opt != null) {
opt.dispose(); // Open database again.
try (final BackupableDB bdb = BackupableDB.open(opt, bopt,
dbFolder.getRoot().getAbsolutePath())) {
// Values must have suffix V2 because of restoring latest backup.
assertThat(new String(bdb.get("key1".getBytes()))).endsWith("V2");
assertThat(new String(bdb.get("key2".getBytes()))).endsWith("V2");
} }
} }
} }
@ -312,59 +228,44 @@ public class BackupableDBTest {
@Test @Test
public void restoreFromBackup() public void restoreFromBackup()
throws RocksDBException { throws RocksDBException {
Options opt = null; try (final Options opt = new Options().setCreateIfMissing(true);
BackupableDBOptions bopt = null; final BackupableDBOptions bopt = new BackupableDBOptions(
BackupableDB bdb = null; backupFolder.getRoot().getAbsolutePath())) {
RestoreBackupableDB rdb = null;
try {
opt = new Options().setCreateIfMissing(true);
bopt = new BackupableDBOptions(
backupFolder.getRoot().getAbsolutePath());
assertThat(bopt.backupDir()).isEqualTo( assertThat(bopt.backupDir()).isEqualTo(
backupFolder.getRoot().getAbsolutePath()); backupFolder.getRoot().getAbsolutePath());
// Open empty database. // Open empty database.
bdb = BackupableDB.open(opt, bopt, try (final BackupableDB bdb = BackupableDB.open(opt, bopt,
dbFolder.getRoot().getAbsolutePath()); dbFolder.getRoot().getAbsolutePath())) {
// Fill database with some test values // Fill database with some test values
prepareDatabase(bdb); prepareDatabase(bdb);
bdb.createNewBackup(true); bdb.createNewBackup(true);
verifyNumberOfValidBackups(bdb, 1); verifyNumberOfValidBackups(bdb, 1);
bdb.put("key1".getBytes(), "valueV2".getBytes()); bdb.put("key1".getBytes(), "valueV2".getBytes());
bdb.put("key2".getBytes(), "valueV2".getBytes()); bdb.put("key2".getBytes(), "valueV2".getBytes());
bdb.createNewBackup(true); bdb.createNewBackup(true);
verifyNumberOfValidBackups(bdb, 2); verifyNumberOfValidBackups(bdb, 2);
bdb.put("key1".getBytes(), "valueV3".getBytes()); bdb.put("key1".getBytes(), "valueV3".getBytes());
bdb.put("key2".getBytes(), "valueV3".getBytes()); bdb.put("key2".getBytes(), "valueV3".getBytes());
assertThat(new String(bdb.get("key1".getBytes()))).endsWith("V3"); assertThat(new String(bdb.get("key1".getBytes()))).endsWith("V3");
assertThat(new String(bdb.get("key2".getBytes()))).endsWith("V3"); assertThat(new String(bdb.get("key2".getBytes()))).endsWith("V3");
bdb.close(); }
// init RestoreBackupableDB // init RestoreBackupableDB
rdb = new RestoreBackupableDB(bopt); try (final RestoreBackupableDB rdb = new RestoreBackupableDB(bopt)) {
List<BackupInfo> backupInfo = verifyNumberOfValidBackups(rdb, 2); final List<BackupInfo> backupInfo = verifyNumberOfValidBackups(rdb, 2);
// restore db from first backup // restore db from first backup
rdb.restoreDBFromBackup(backupInfo.get(0).backupId(), rdb.restoreDBFromBackup(backupInfo.get(0).backupId(),
dbFolder.getRoot().getAbsolutePath(), dbFolder.getRoot().getAbsolutePath(),
dbFolder.getRoot().getAbsolutePath(), dbFolder.getRoot().getAbsolutePath(),
new RestoreOptions(false)); new RestoreOptions(false));
// Open database again.
bdb = BackupableDB.open(opt, bopt,
dbFolder.getRoot().getAbsolutePath());
// Values must have suffix V2 because of restoring latest backup.
assertThat(new String(bdb.get("key1".getBytes()))).endsWith("V1");
assertThat(new String(bdb.get("key2".getBytes()))).endsWith("V1");
} finally {
if (bdb != null) {
bdb.close();
} }
if (rdb != null) {
rdb.dispose(); // Open database again.
} try (final BackupableDB bdb = BackupableDB.open(opt, bopt,
if (bopt != null) { dbFolder.getRoot().getAbsolutePath())) {
bopt.dispose(); // Values must have suffix V2 because of restoring latest backup.
} assertThat(new String(bdb.get("key1".getBytes()))).endsWith("V1");
if (opt != null) { assertThat(new String(bdb.get("key2".getBytes()))).endsWith("V1");
opt.dispose();
} }
} }
} }
@ -372,13 +273,13 @@ public class BackupableDBTest {
/** /**
* Verify backups. * Verify backups.
* *
* @param bdb {@link BackupableDB} instance. * @param bdb {@link BackupableDB} instance.
* @param expectedNumberOfBackups numerical value * @param expectedNumberOfBackups numerical value
* @throws RocksDBException thrown if an error occurs within the native * @throws RocksDBException thrown if an error occurs within the native
* part of the library. * part of the library.
*/ */
private List<BackupInfo> verifyNumberOfValidBackups(BackupableDB bdb, private List<BackupInfo> verifyNumberOfValidBackups(final BackupableDB bdb,
int expectedNumberOfBackups) throws RocksDBException { final int expectedNumberOfBackups) throws RocksDBException {
// Verify that backups exist // Verify that backups exist
assertThat(bdb.getCorruptedBackups().length). assertThat(bdb.getCorruptedBackups().length).
isEqualTo(0); isEqualTo(0);
@ -392,13 +293,13 @@ public class BackupableDBTest {
/** /**
* Verify backups. * Verify backups.
* *
* @param rdb {@link RestoreBackupableDB} instance. * @param rdb {@link RestoreBackupableDB} instance.
* @param expectedNumberOfBackups numerical value * @param expectedNumberOfBackups numerical value
* @throws RocksDBException thrown if an error occurs within the native * @throws RocksDBException thrown if an error occurs within the native
* part of the library. * part of the library.
*/ */
private List<BackupInfo> verifyNumberOfValidBackups( private List<BackupInfo> verifyNumberOfValidBackups(
RestoreBackupableDB rdb, int expectedNumberOfBackups) final RestoreBackupableDB rdb, final int expectedNumberOfBackups)
throws RocksDBException { throws RocksDBException {
// Verify that backups exist // Verify that backups exist
assertThat(rdb.getCorruptedBackups().length). assertThat(rdb.getCorruptedBackups().length).
@ -415,9 +316,9 @@ public class BackupableDBTest {
* *
* @param db {@link RocksDB} instance. * @param db {@link RocksDB} instance.
* @throws RocksDBException thrown if an error occurs within the native * @throws RocksDBException thrown if an error occurs within the native
* part of the library. * part of the library.
*/ */
private void prepareDatabase(RocksDB db) private void prepareDatabase(final RocksDB db)
throws RocksDBException { throws RocksDBException {
db.put("key1".getBytes(), "valueV1".getBytes()); db.put("key1".getBytes(), "valueV1".getBytes());
db.put("key2".getBytes(), "valueV1".getBytes()); db.put("key2".getBytes(), "valueV1".getBytes());

@ -131,34 +131,20 @@ public class BlockBasedTableConfigTest {
@Test @Test
public void blockBasedTableWithFilter() { public void blockBasedTableWithFilter() {
Options options = null; try(final Options options = new Options()
try { .setTableFormatConfig(new BlockBasedTableConfig()
options = new Options(); .setFilter(new BloomFilter(10)))) {
options.setTableFormatConfig(
new BlockBasedTableConfig().setFilter(
new BloomFilter(10)));
assertThat(options.tableFactoryName()). assertThat(options.tableFactoryName()).
isEqualTo("BlockBasedTable"); isEqualTo("BlockBasedTable");
} finally {
if (options != null) {
options.dispose();
}
} }
} }
@Test @Test
public void blockBasedTableWithoutFilter() { public void blockBasedTableWithoutFilter() {
Options options = null; try(final Options options = new Options().setTableFormatConfig(
try { new BlockBasedTableConfig().setFilter(null))) {
options = new Options();
options.setTableFormatConfig(
new BlockBasedTableConfig().setFilter(null));
assertThat(options.tableFactoryName()). assertThat(options.tableFactoryName()).
isEqualTo("BlockBasedTable"); isEqualTo("BlockBasedTable");
} finally {
if (options != null) {
options.dispose();
}
} }
} }

@ -22,76 +22,61 @@ public class CheckPointTest {
@Test @Test
public void checkPoint() throws RocksDBException { public void checkPoint() throws RocksDBException {
RocksDB db = null; try (final Options options = new Options().
Options options = null; setCreateIfMissing(true)) {
Checkpoint checkpoint = null;
try { try (final RocksDB db = RocksDB.open(options,
options = new Options(). dbFolder.getRoot().getAbsolutePath())) {
setCreateIfMissing(true); db.put("key".getBytes(), "value".getBytes());
db = RocksDB.open(options, try (final Checkpoint checkpoint = Checkpoint.create(db)) {
dbFolder.getRoot().getAbsolutePath()); checkpoint.createCheckpoint(checkpointFolder.
db.put("key".getBytes(), "value".getBytes()); getRoot().getAbsolutePath() + "/snapshot1");
checkpoint = Checkpoint.create(db); db.put("key2".getBytes(), "value2".getBytes());
checkpoint.createCheckpoint(checkpointFolder. checkpoint.createCheckpoint(checkpointFolder.
getRoot().getAbsolutePath() + "/snapshot1"); getRoot().getAbsolutePath() + "/snapshot2");
db.put("key2".getBytes(), "value2".getBytes()); }
checkpoint.createCheckpoint(checkpointFolder.
getRoot().getAbsolutePath() + "/snapshot2");
db.close();
db = RocksDB.open(options,
checkpointFolder.getRoot().getAbsolutePath() +
"/snapshot1");
assertThat(new String(db.get("key".getBytes()))).
isEqualTo("value");
assertThat(db.get("key2".getBytes())).isNull();
db.close();
db = RocksDB.open(options,
checkpointFolder.getRoot().getAbsolutePath() +
"/snapshot2");
assertThat(new String(db.get("key".getBytes()))).
isEqualTo("value");
assertThat(new String(db.get("key2".getBytes()))).
isEqualTo("value2");
} finally {
if (db != null) {
db.close();
} }
if (options != null) {
options.dispose(); try (final RocksDB db = RocksDB.open(options,
checkpointFolder.getRoot().getAbsolutePath() +
"/snapshot1")) {
assertThat(new String(db.get("key".getBytes()))).
isEqualTo("value");
assertThat(db.get("key2".getBytes())).isNull();
} }
if (checkpoint != null) {
checkpoint.dispose(); try (final RocksDB db = RocksDB.open(options,
checkpointFolder.getRoot().getAbsolutePath() +
"/snapshot2")) {
assertThat(new String(db.get("key".getBytes()))).
isEqualTo("value");
assertThat(new String(db.get("key2".getBytes()))).
isEqualTo("value2");
} }
} }
} }
@Test(expected = IllegalArgumentException.class) @Test(expected = IllegalArgumentException.class)
public void failIfDbIsNull() { public void failIfDbIsNull() {
Checkpoint.create(null); try (final Checkpoint checkpoint = Checkpoint.create(null)) {
}
} }
@Test(expected = IllegalStateException.class) @Test(expected = IllegalStateException.class)
public void failIfDbNotInitialized() throws RocksDBException { public void failIfDbNotInitialized() throws RocksDBException {
RocksDB db = RocksDB.open(dbFolder.getRoot().getAbsolutePath()); try (final RocksDB db = RocksDB.open(
db.dispose(); dbFolder.getRoot().getAbsolutePath())) {
Checkpoint.create(db); db.close();
Checkpoint.create(db);
}
} }
@Test(expected = RocksDBException.class) @Test(expected = RocksDBException.class)
public void failWithIllegalPath() throws RocksDBException { public void failWithIllegalPath() throws RocksDBException {
RocksDB db = null; try (final RocksDB db = RocksDB.open(dbFolder.getRoot().getAbsolutePath());
Checkpoint checkpoint = null; final Checkpoint checkpoint = Checkpoint.create(db)) {
try {
db = RocksDB.open(dbFolder.getRoot().getAbsolutePath());
checkpoint = Checkpoint.create(db);
checkpoint.createCheckpoint("/Z:///:\\C:\\TZ/-"); checkpoint.createCheckpoint("/Z:///:\\C:\\TZ/-");
} finally {
if (db != null) {
db.close();
}
if (checkpoint != null) {
checkpoint.dispose();
}
} }
} }
} }

@ -26,616 +26,386 @@ public class ColumnFamilyOptionsTest {
@Test @Test
public void getColumnFamilyOptionsFromProps() { public void getColumnFamilyOptionsFromProps() {
ColumnFamilyOptions opt = null; Properties properties = new Properties();
try { properties.put("write_buffer_size", "112");
properties.put("max_write_buffer_number", "13");
try (final ColumnFamilyOptions opt = ColumnFamilyOptions.
getColumnFamilyOptionsFromProps(properties)) {
// setup sample properties // setup sample properties
Properties properties = new Properties();
properties.put("write_buffer_size", "112");
properties.put("max_write_buffer_number", "13");
opt = ColumnFamilyOptions.
getColumnFamilyOptionsFromProps(properties);
assertThat(opt).isNotNull(); assertThat(opt).isNotNull();
assertThat(String.valueOf(opt.writeBufferSize())). assertThat(String.valueOf(opt.writeBufferSize())).
isEqualTo(properties.get("write_buffer_size")); isEqualTo(properties.get("write_buffer_size"));
assertThat(String.valueOf(opt.maxWriteBufferNumber())). assertThat(String.valueOf(opt.maxWriteBufferNumber())).
isEqualTo(properties.get("max_write_buffer_number")); isEqualTo(properties.get("max_write_buffer_number"));
} finally {
if (opt != null) {
opt.dispose();
}
} }
} }
@Test @Test
public void failColumnFamilyOptionsFromPropsWithIllegalValue() { public void failColumnFamilyOptionsFromPropsWithIllegalValue() {
ColumnFamilyOptions opt = null; // setup sample properties
try { final Properties properties = new Properties();
// setup sample properties properties.put("tomato", "1024");
Properties properties = new Properties(); properties.put("burger", "2");
properties.put("tomato", "1024");
properties.put("burger", "2"); try (final ColumnFamilyOptions opt =
opt = ColumnFamilyOptions. ColumnFamilyOptions.getColumnFamilyOptionsFromProps(properties)) {
getColumnFamilyOptionsFromProps(properties);
assertThat(opt).isNull(); assertThat(opt).isNull();
} finally {
if (opt != null) {
opt.dispose();
}
} }
} }
@Test(expected = IllegalArgumentException.class) @Test(expected = IllegalArgumentException.class)
public void failColumnFamilyOptionsFromPropsWithNullValue() { public void failColumnFamilyOptionsFromPropsWithNullValue() {
ColumnFamilyOptions.getColumnFamilyOptionsFromProps(null); try (final ColumnFamilyOptions opt =
ColumnFamilyOptions.getColumnFamilyOptionsFromProps(null)) {
}
} }
@Test(expected = IllegalArgumentException.class) @Test(expected = IllegalArgumentException.class)
public void failColumnFamilyOptionsFromPropsWithEmptyProps() { public void failColumnFamilyOptionsFromPropsWithEmptyProps() {
ColumnFamilyOptions.getColumnFamilyOptionsFromProps( try (final ColumnFamilyOptions opt =
new Properties()); ColumnFamilyOptions.getColumnFamilyOptionsFromProps(
new Properties())) {
}
} }
@Test @Test
public void writeBufferSize() throws RocksDBException { public void writeBufferSize() throws RocksDBException {
ColumnFamilyOptions opt = null; try (final ColumnFamilyOptions opt = new ColumnFamilyOptions()) {
try { final long longValue = rand.nextLong();
opt = new ColumnFamilyOptions();
long longValue = rand.nextLong();
opt.setWriteBufferSize(longValue); opt.setWriteBufferSize(longValue);
assertThat(opt.writeBufferSize()).isEqualTo(longValue); assertThat(opt.writeBufferSize()).isEqualTo(longValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
} }
@Test @Test
public void maxWriteBufferNumber() { public void maxWriteBufferNumber() {
ColumnFamilyOptions opt = null; try (final ColumnFamilyOptions opt = new ColumnFamilyOptions()) {
try { final int intValue = rand.nextInt();
opt = new ColumnFamilyOptions();
int intValue = rand.nextInt();
opt.setMaxWriteBufferNumber(intValue); opt.setMaxWriteBufferNumber(intValue);
assertThat(opt.maxWriteBufferNumber()).isEqualTo(intValue); assertThat(opt.maxWriteBufferNumber()).isEqualTo(intValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
} }
@Test @Test
public void minWriteBufferNumberToMerge() { public void minWriteBufferNumberToMerge() {
ColumnFamilyOptions opt = null; try (final ColumnFamilyOptions opt = new ColumnFamilyOptions()) {
try { final int intValue = rand.nextInt();
opt = new ColumnFamilyOptions();
int intValue = rand.nextInt();
opt.setMinWriteBufferNumberToMerge(intValue); opt.setMinWriteBufferNumberToMerge(intValue);
assertThat(opt.minWriteBufferNumberToMerge()).isEqualTo(intValue); assertThat(opt.minWriteBufferNumberToMerge()).isEqualTo(intValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
} }
@Test @Test
public void numLevels() { public void numLevels() {
ColumnFamilyOptions opt = null; try (final ColumnFamilyOptions opt = new ColumnFamilyOptions()) {
try { final int intValue = rand.nextInt();
opt = new ColumnFamilyOptions();
int intValue = rand.nextInt();
opt.setNumLevels(intValue); opt.setNumLevels(intValue);
assertThat(opt.numLevels()).isEqualTo(intValue); assertThat(opt.numLevels()).isEqualTo(intValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
} }
@Test @Test
public void levelZeroFileNumCompactionTrigger() { public void levelZeroFileNumCompactionTrigger() {
ColumnFamilyOptions opt = null; try (final ColumnFamilyOptions opt = new ColumnFamilyOptions()) {
try { final int intValue = rand.nextInt();
opt = new ColumnFamilyOptions();
int intValue = rand.nextInt();
opt.setLevelZeroFileNumCompactionTrigger(intValue); opt.setLevelZeroFileNumCompactionTrigger(intValue);
assertThat(opt.levelZeroFileNumCompactionTrigger()).isEqualTo(intValue); assertThat(opt.levelZeroFileNumCompactionTrigger()).isEqualTo(intValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
} }
@Test @Test
public void levelZeroSlowdownWritesTrigger() { public void levelZeroSlowdownWritesTrigger() {
ColumnFamilyOptions opt = null; try (final ColumnFamilyOptions opt = new ColumnFamilyOptions()) {
try { final int intValue = rand.nextInt();
opt = new ColumnFamilyOptions();
int intValue = rand.nextInt();
opt.setLevelZeroSlowdownWritesTrigger(intValue); opt.setLevelZeroSlowdownWritesTrigger(intValue);
assertThat(opt.levelZeroSlowdownWritesTrigger()).isEqualTo(intValue); assertThat(opt.levelZeroSlowdownWritesTrigger()).isEqualTo(intValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
} }
@Test @Test
public void levelZeroStopWritesTrigger() { public void levelZeroStopWritesTrigger() {
ColumnFamilyOptions opt = null; try (final ColumnFamilyOptions opt = new ColumnFamilyOptions()) {
try { final int intValue = rand.nextInt();
opt = new ColumnFamilyOptions();
int intValue = rand.nextInt();
opt.setLevelZeroStopWritesTrigger(intValue); opt.setLevelZeroStopWritesTrigger(intValue);
assertThat(opt.levelZeroStopWritesTrigger()).isEqualTo(intValue); assertThat(opt.levelZeroStopWritesTrigger()).isEqualTo(intValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
} }
@Test @Test
public void targetFileSizeBase() { public void targetFileSizeBase() {
ColumnFamilyOptions opt = null; try (final ColumnFamilyOptions opt = new ColumnFamilyOptions()) {
try { final long longValue = rand.nextLong();
opt = new ColumnFamilyOptions();
long longValue = rand.nextLong();
opt.setTargetFileSizeBase(longValue); opt.setTargetFileSizeBase(longValue);
assertThat(opt.targetFileSizeBase()).isEqualTo(longValue); assertThat(opt.targetFileSizeBase()).isEqualTo(longValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
} }
@Test @Test
public void targetFileSizeMultiplier() { public void targetFileSizeMultiplier() {
ColumnFamilyOptions opt = null; try (final ColumnFamilyOptions opt = new ColumnFamilyOptions()) {
try { final int intValue = rand.nextInt();
opt = new ColumnFamilyOptions();
int intValue = rand.nextInt();
opt.setTargetFileSizeMultiplier(intValue); opt.setTargetFileSizeMultiplier(intValue);
assertThat(opt.targetFileSizeMultiplier()).isEqualTo(intValue); assertThat(opt.targetFileSizeMultiplier()).isEqualTo(intValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
} }
@Test @Test
public void maxBytesForLevelBase() { public void maxBytesForLevelBase() {
ColumnFamilyOptions opt = null; try (final ColumnFamilyOptions opt = new ColumnFamilyOptions()) {
try { final long longValue = rand.nextLong();
opt = new ColumnFamilyOptions();
long longValue = rand.nextLong();
opt.setMaxBytesForLevelBase(longValue); opt.setMaxBytesForLevelBase(longValue);
assertThat(opt.maxBytesForLevelBase()).isEqualTo(longValue); assertThat(opt.maxBytesForLevelBase()).isEqualTo(longValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
} }
@Test @Test
public void levelCompactionDynamicLevelBytes() { public void levelCompactionDynamicLevelBytes() {
ColumnFamilyOptions opt = null; try (final ColumnFamilyOptions opt = new ColumnFamilyOptions()) {
try {
opt = new ColumnFamilyOptions();
final boolean boolValue = rand.nextBoolean(); final boolean boolValue = rand.nextBoolean();
opt.setLevelCompactionDynamicLevelBytes(boolValue); opt.setLevelCompactionDynamicLevelBytes(boolValue);
assertThat(opt.levelCompactionDynamicLevelBytes()) assertThat(opt.levelCompactionDynamicLevelBytes())
.isEqualTo(boolValue); .isEqualTo(boolValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
} }
@Test @Test
public void maxBytesForLevelMultiplier() { public void maxBytesForLevelMultiplier() {
ColumnFamilyOptions opt = null; try (final ColumnFamilyOptions opt = new ColumnFamilyOptions()) {
try { final int intValue = rand.nextInt();
opt = new ColumnFamilyOptions();
int intValue = rand.nextInt();
opt.setMaxBytesForLevelMultiplier(intValue); opt.setMaxBytesForLevelMultiplier(intValue);
assertThat(opt.maxBytesForLevelMultiplier()).isEqualTo(intValue); assertThat(opt.maxBytesForLevelMultiplier()).isEqualTo(intValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
} }
@Test @Test
public void expandedCompactionFactor() { public void expandedCompactionFactor() {
ColumnFamilyOptions opt = null; try (final ColumnFamilyOptions opt = new ColumnFamilyOptions()) {
try { final int intValue = rand.nextInt();
opt = new ColumnFamilyOptions();
int intValue = rand.nextInt();
opt.setExpandedCompactionFactor(intValue); opt.setExpandedCompactionFactor(intValue);
assertThat(opt.expandedCompactionFactor()).isEqualTo(intValue); assertThat(opt.expandedCompactionFactor()).isEqualTo(intValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
} }
@Test @Test
public void sourceCompactionFactor() { public void sourceCompactionFactor() {
ColumnFamilyOptions opt = null; try (final ColumnFamilyOptions opt = new ColumnFamilyOptions()) {
try { final int intValue = rand.nextInt();
opt = new ColumnFamilyOptions();
int intValue = rand.nextInt();
opt.setSourceCompactionFactor(intValue); opt.setSourceCompactionFactor(intValue);
assertThat(opt.sourceCompactionFactor()).isEqualTo(intValue); assertThat(opt.sourceCompactionFactor()).isEqualTo(intValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
} }
@Test @Test
public void maxGrandparentOverlapFactor() { public void maxGrandparentOverlapFactor() {
ColumnFamilyOptions opt = null; try (final ColumnFamilyOptions opt = new ColumnFamilyOptions()) {
try { final int intValue = rand.nextInt();
opt = new ColumnFamilyOptions();
int intValue = rand.nextInt();
opt.setMaxGrandparentOverlapFactor(intValue); opt.setMaxGrandparentOverlapFactor(intValue);
assertThat(opt.maxGrandparentOverlapFactor()).isEqualTo(intValue); assertThat(opt.maxGrandparentOverlapFactor()).isEqualTo(intValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
} }
@Test @Test
public void softRateLimit() { public void softRateLimit() {
ColumnFamilyOptions opt = null; try (final ColumnFamilyOptions opt = new ColumnFamilyOptions()) {
try { final double doubleValue = rand.nextDouble();
opt = new ColumnFamilyOptions();
double doubleValue = rand.nextDouble();
opt.setSoftRateLimit(doubleValue); opt.setSoftRateLimit(doubleValue);
assertThat(opt.softRateLimit()).isEqualTo(doubleValue); assertThat(opt.softRateLimit()).isEqualTo(doubleValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
} }
@Test @Test
public void hardRateLimit() { public void hardRateLimit() {
ColumnFamilyOptions opt = null; try (final ColumnFamilyOptions opt = new ColumnFamilyOptions()) {
try { final double doubleValue = rand.nextDouble();
opt = new ColumnFamilyOptions();
double doubleValue = rand.nextDouble();
opt.setHardRateLimit(doubleValue); opt.setHardRateLimit(doubleValue);
assertThat(opt.hardRateLimit()).isEqualTo(doubleValue); assertThat(opt.hardRateLimit()).isEqualTo(doubleValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
} }
@Test @Test
public void rateLimitDelayMaxMilliseconds() { public void rateLimitDelayMaxMilliseconds() {
ColumnFamilyOptions opt = null; try (final ColumnFamilyOptions opt = new ColumnFamilyOptions()) {
try { final int intValue = rand.nextInt();
opt = new ColumnFamilyOptions();
int intValue = rand.nextInt();
opt.setRateLimitDelayMaxMilliseconds(intValue); opt.setRateLimitDelayMaxMilliseconds(intValue);
assertThat(opt.rateLimitDelayMaxMilliseconds()).isEqualTo(intValue); assertThat(opt.rateLimitDelayMaxMilliseconds()).isEqualTo(intValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
} }
@Test @Test
public void arenaBlockSize() throws RocksDBException { public void arenaBlockSize() throws RocksDBException {
ColumnFamilyOptions opt = null; try (final ColumnFamilyOptions opt = new ColumnFamilyOptions()) {
try { final long longValue = rand.nextLong();
opt = new ColumnFamilyOptions();
long longValue = rand.nextLong();
opt.setArenaBlockSize(longValue); opt.setArenaBlockSize(longValue);
assertThat(opt.arenaBlockSize()).isEqualTo(longValue); assertThat(opt.arenaBlockSize()).isEqualTo(longValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
} }
@Test @Test
public void disableAutoCompactions() { public void disableAutoCompactions() {
ColumnFamilyOptions opt = null; try (final ColumnFamilyOptions opt = new ColumnFamilyOptions()) {
try { final boolean boolValue = rand.nextBoolean();
opt = new ColumnFamilyOptions();
boolean boolValue = rand.nextBoolean();
opt.setDisableAutoCompactions(boolValue); opt.setDisableAutoCompactions(boolValue);
assertThat(opt.disableAutoCompactions()).isEqualTo(boolValue); assertThat(opt.disableAutoCompactions()).isEqualTo(boolValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
} }
@Test @Test
public void purgeRedundantKvsWhileFlush() { public void purgeRedundantKvsWhileFlush() {
ColumnFamilyOptions opt = null; try (final ColumnFamilyOptions opt = new ColumnFamilyOptions()) {
try { final boolean boolValue = rand.nextBoolean();
opt = new ColumnFamilyOptions();
boolean boolValue = rand.nextBoolean();
opt.setPurgeRedundantKvsWhileFlush(boolValue); opt.setPurgeRedundantKvsWhileFlush(boolValue);
assertThat(opt.purgeRedundantKvsWhileFlush()).isEqualTo(boolValue); assertThat(opt.purgeRedundantKvsWhileFlush()).isEqualTo(boolValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
} }
@Test @Test
public void verifyChecksumsInCompaction() { public void verifyChecksumsInCompaction() {
ColumnFamilyOptions opt = null; try (final ColumnFamilyOptions opt = new ColumnFamilyOptions()) {
try { final boolean boolValue = rand.nextBoolean();
opt = new ColumnFamilyOptions();
boolean boolValue = rand.nextBoolean();
opt.setVerifyChecksumsInCompaction(boolValue); opt.setVerifyChecksumsInCompaction(boolValue);
assertThat(opt.verifyChecksumsInCompaction()).isEqualTo(boolValue); assertThat(opt.verifyChecksumsInCompaction()).isEqualTo(boolValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
} }
@Test @Test
public void filterDeletes() { public void filterDeletes() {
ColumnFamilyOptions opt = null; try (final ColumnFamilyOptions opt = new ColumnFamilyOptions()) {
try { final boolean boolValue = rand.nextBoolean();
opt = new ColumnFamilyOptions();
boolean boolValue = rand.nextBoolean();
opt.setFilterDeletes(boolValue); opt.setFilterDeletes(boolValue);
assertThat(opt.filterDeletes()).isEqualTo(boolValue); assertThat(opt.filterDeletes()).isEqualTo(boolValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
} }
@Test @Test
public void maxSequentialSkipInIterations() { public void maxSequentialSkipInIterations() {
ColumnFamilyOptions opt = null; try (final ColumnFamilyOptions opt = new ColumnFamilyOptions()) {
try { final long longValue = rand.nextLong();
opt = new ColumnFamilyOptions();
long longValue = rand.nextLong();
opt.setMaxSequentialSkipInIterations(longValue); opt.setMaxSequentialSkipInIterations(longValue);
assertThat(opt.maxSequentialSkipInIterations()).isEqualTo(longValue); assertThat(opt.maxSequentialSkipInIterations()).isEqualTo(longValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
} }
@Test @Test
public void inplaceUpdateSupport() { public void inplaceUpdateSupport() {
ColumnFamilyOptions opt = null; try (final ColumnFamilyOptions opt = new ColumnFamilyOptions()) {
try { final boolean boolValue = rand.nextBoolean();
opt = new ColumnFamilyOptions();
boolean boolValue = rand.nextBoolean();
opt.setInplaceUpdateSupport(boolValue); opt.setInplaceUpdateSupport(boolValue);
assertThat(opt.inplaceUpdateSupport()).isEqualTo(boolValue); assertThat(opt.inplaceUpdateSupport()).isEqualTo(boolValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
} }
@Test @Test
public void inplaceUpdateNumLocks() throws RocksDBException { public void inplaceUpdateNumLocks() throws RocksDBException {
ColumnFamilyOptions opt = null; try (final ColumnFamilyOptions opt = new ColumnFamilyOptions()) {
try { final long longValue = rand.nextLong();
opt = new ColumnFamilyOptions();
long longValue = rand.nextLong();
opt.setInplaceUpdateNumLocks(longValue); opt.setInplaceUpdateNumLocks(longValue);
assertThat(opt.inplaceUpdateNumLocks()).isEqualTo(longValue); assertThat(opt.inplaceUpdateNumLocks()).isEqualTo(longValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
} }
@Test @Test
public void memtablePrefixBloomBits() { public void memtablePrefixBloomBits() {
ColumnFamilyOptions opt = null; try (final ColumnFamilyOptions opt = new ColumnFamilyOptions()) {
try { final int intValue = rand.nextInt();
opt = new ColumnFamilyOptions();
int intValue = rand.nextInt();
opt.setMemtablePrefixBloomBits(intValue); opt.setMemtablePrefixBloomBits(intValue);
assertThat(opt.memtablePrefixBloomBits()).isEqualTo(intValue); assertThat(opt.memtablePrefixBloomBits()).isEqualTo(intValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
} }
@Test @Test
public void memtablePrefixBloomProbes() { public void memtablePrefixBloomProbes() {
ColumnFamilyOptions opt = null; try (final ColumnFamilyOptions opt = new ColumnFamilyOptions()) {
try { final int intValue = rand.nextInt();
int intValue = rand.nextInt();
opt = new ColumnFamilyOptions();
opt.setMemtablePrefixBloomProbes(intValue); opt.setMemtablePrefixBloomProbes(intValue);
assertThat(opt.memtablePrefixBloomProbes()).isEqualTo(intValue); assertThat(opt.memtablePrefixBloomProbes()).isEqualTo(intValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
} }
@Test @Test
public void bloomLocality() { public void bloomLocality() {
ColumnFamilyOptions opt = null; try (final ColumnFamilyOptions opt = new ColumnFamilyOptions()) {
try { final int intValue = rand.nextInt();
int intValue = rand.nextInt();
opt = new ColumnFamilyOptions();
opt.setBloomLocality(intValue); opt.setBloomLocality(intValue);
assertThat(opt.bloomLocality()).isEqualTo(intValue); assertThat(opt.bloomLocality()).isEqualTo(intValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
} }
@Test @Test
public void maxSuccessiveMerges() throws RocksDBException { public void maxSuccessiveMerges() throws RocksDBException {
ColumnFamilyOptions opt = null; try (final ColumnFamilyOptions opt = new ColumnFamilyOptions()) {
try { final long longValue = rand.nextLong();
long longValue = rand.nextLong();
opt = new ColumnFamilyOptions();
opt.setMaxSuccessiveMerges(longValue); opt.setMaxSuccessiveMerges(longValue);
assertThat(opt.maxSuccessiveMerges()).isEqualTo(longValue); assertThat(opt.maxSuccessiveMerges()).isEqualTo(longValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
} }
@Test @Test
public void minPartialMergeOperands() { public void minPartialMergeOperands() {
ColumnFamilyOptions opt = null; try (final ColumnFamilyOptions opt = new ColumnFamilyOptions()) {
try { final int intValue = rand.nextInt();
int intValue = rand.nextInt();
opt = new ColumnFamilyOptions();
opt.setMinPartialMergeOperands(intValue); opt.setMinPartialMergeOperands(intValue);
assertThat(opt.minPartialMergeOperands()).isEqualTo(intValue); assertThat(opt.minPartialMergeOperands()).isEqualTo(intValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
} }
@Test @Test
public void optimizeFiltersForHits() { public void optimizeFiltersForHits() {
ColumnFamilyOptions opt = null; try (final ColumnFamilyOptions opt = new ColumnFamilyOptions()) {
try { final boolean aBoolean = rand.nextBoolean();
boolean aBoolean = rand.nextBoolean();
opt = new ColumnFamilyOptions();
opt.setOptimizeFiltersForHits(aBoolean); opt.setOptimizeFiltersForHits(aBoolean);
assertThat(opt.optimizeFiltersForHits()).isEqualTo(aBoolean); assertThat(opt.optimizeFiltersForHits()).isEqualTo(aBoolean);
} finally {
if (opt != null) {
opt.dispose();
}
} }
} }
@Test @Test
public void memTable() throws RocksDBException { public void memTable() throws RocksDBException {
ColumnFamilyOptions opt = null; try (final ColumnFamilyOptions opt = new ColumnFamilyOptions()) {
try {
opt = new ColumnFamilyOptions();
opt.setMemTableConfig(new HashLinkedListMemTableConfig()); opt.setMemTableConfig(new HashLinkedListMemTableConfig());
assertThat(opt.memTableFactoryName()). assertThat(opt.memTableFactoryName()).
isEqualTo("HashLinkedListRepFactory"); isEqualTo("HashLinkedListRepFactory");
} finally {
if (opt != null) {
opt.dispose();
}
} }
} }
@Test @Test
public void comparator() throws RocksDBException { public void comparator() throws RocksDBException {
ColumnFamilyOptions opt = null; try (final ColumnFamilyOptions opt = new ColumnFamilyOptions()) {
try {
opt = new ColumnFamilyOptions();
opt.setComparator(BuiltinComparator.BYTEWISE_COMPARATOR); opt.setComparator(BuiltinComparator.BYTEWISE_COMPARATOR);
} finally {
if (opt != null) {
opt.dispose();
}
} }
} }
@Test @Test
public void linkageOfPrepMethods() { public void linkageOfPrepMethods() {
ColumnFamilyOptions options = null; try (final ColumnFamilyOptions options = new ColumnFamilyOptions()) {
try {
options = new ColumnFamilyOptions();
options.optimizeUniversalStyleCompaction(); options.optimizeUniversalStyleCompaction();
options.optimizeUniversalStyleCompaction(4000); options.optimizeUniversalStyleCompaction(4000);
options.optimizeLevelStyleCompaction(); options.optimizeLevelStyleCompaction();
options.optimizeLevelStyleCompaction(3000); options.optimizeLevelStyleCompaction(3000);
options.optimizeForPointLookup(10); options.optimizeForPointLookup(10);
} finally {
if (options != null) {
options.dispose();
}
} }
} }
@Test @Test
public void shouldSetTestPrefixExtractor() { public void shouldSetTestPrefixExtractor() {
ColumnFamilyOptions options = null; try (final ColumnFamilyOptions options = new ColumnFamilyOptions()) {
try {
options = new ColumnFamilyOptions();
options.useFixedLengthPrefixExtractor(100); options.useFixedLengthPrefixExtractor(100);
options.useFixedLengthPrefixExtractor(10); options.useFixedLengthPrefixExtractor(10);
} finally {
if (options != null) {
options.dispose();
}
} }
} }
@Test @Test
public void shouldSetTestCappedPrefixExtractor() { public void shouldSetTestCappedPrefixExtractor() {
ColumnFamilyOptions options = null; try (final ColumnFamilyOptions options = new ColumnFamilyOptions()) {
try {
options = new ColumnFamilyOptions();
options.useCappedPrefixExtractor(100); options.useCappedPrefixExtractor(100);
options.useCappedPrefixExtractor(10); options.useCappedPrefixExtractor(10);
} finally {
if (options != null) {
options.dispose();
}
} }
} }
@Test @Test
public void compressionTypes() { public void compressionTypes() {
ColumnFamilyOptions columnFamilyOptions = null; try (final ColumnFamilyOptions columnFamilyOptions
try { = new ColumnFamilyOptions()) {
columnFamilyOptions = new ColumnFamilyOptions(); for (final CompressionType compressionType :
for (CompressionType compressionType :
CompressionType.values()) { CompressionType.values()) {
columnFamilyOptions.setCompressionType(compressionType); columnFamilyOptions.setCompressionType(compressionType);
assertThat(columnFamilyOptions.compressionType()). assertThat(columnFamilyOptions.compressionType()).
@ -643,21 +413,16 @@ public class ColumnFamilyOptionsTest {
assertThat(CompressionType.valueOf("NO_COMPRESSION")). assertThat(CompressionType.valueOf("NO_COMPRESSION")).
isEqualTo(CompressionType.NO_COMPRESSION); isEqualTo(CompressionType.NO_COMPRESSION);
} }
} finally {
if (columnFamilyOptions != null) {
columnFamilyOptions.dispose();
}
} }
} }
@Test @Test
public void compressionPerLevel() { public void compressionPerLevel() {
ColumnFamilyOptions columnFamilyOptions = null; try (final ColumnFamilyOptions columnFamilyOptions
try { = new ColumnFamilyOptions()) {
columnFamilyOptions = new ColumnFamilyOptions();
assertThat(columnFamilyOptions.compressionPerLevel()).isEmpty(); assertThat(columnFamilyOptions.compressionPerLevel()).isEmpty();
List<CompressionType> compressionTypeList = new ArrayList<>(); List<CompressionType> compressionTypeList = new ArrayList<>();
for (int i=0; i < columnFamilyOptions.numLevels(); i++) { for (int i = 0; i < columnFamilyOptions.numLevels(); i++) {
compressionTypeList.add(CompressionType.NO_COMPRESSION); compressionTypeList.add(CompressionType.NO_COMPRESSION);
} }
columnFamilyOptions.setCompressionPerLevel(compressionTypeList); columnFamilyOptions.setCompressionPerLevel(compressionTypeList);
@ -666,18 +431,13 @@ public class ColumnFamilyOptionsTest {
assertThat(compressionType).isEqualTo( assertThat(compressionType).isEqualTo(
CompressionType.NO_COMPRESSION); CompressionType.NO_COMPRESSION);
} }
} finally {
if (columnFamilyOptions != null) {
columnFamilyOptions.dispose();
}
} }
} }
@Test @Test
public void differentCompressionsPerLevel() { public void differentCompressionsPerLevel() {
ColumnFamilyOptions columnFamilyOptions = null; try (final ColumnFamilyOptions columnFamilyOptions
try { = new ColumnFamilyOptions()) {
columnFamilyOptions = new ColumnFamilyOptions();
columnFamilyOptions.setNumLevels(3); columnFamilyOptions.setNumLevels(3);
assertThat(columnFamilyOptions.compressionPerLevel()).isEmpty(); assertThat(columnFamilyOptions.compressionPerLevel()).isEmpty();
@ -697,38 +457,27 @@ public class ColumnFamilyOptionsTest {
CompressionType.SNAPPY_COMPRESSION, CompressionType.SNAPPY_COMPRESSION,
CompressionType.LZ4_COMPRESSION); CompressionType.LZ4_COMPRESSION);
} finally {
if (columnFamilyOptions != null) {
columnFamilyOptions.dispose();
}
} }
} }
@Test @Test
public void compactionStyles() { public void compactionStyles() {
ColumnFamilyOptions ColumnFamilyOptions = null; try (final ColumnFamilyOptions columnFamilyOptions
try { = new ColumnFamilyOptions()) {
ColumnFamilyOptions = new ColumnFamilyOptions(); for (final CompactionStyle compactionStyle :
for (CompactionStyle compactionStyle :
CompactionStyle.values()) { CompactionStyle.values()) {
ColumnFamilyOptions.setCompactionStyle(compactionStyle); columnFamilyOptions.setCompactionStyle(compactionStyle);
assertThat(ColumnFamilyOptions.compactionStyle()). assertThat(columnFamilyOptions.compactionStyle()).
isEqualTo(compactionStyle); isEqualTo(compactionStyle);
assertThat(CompactionStyle.valueOf("FIFO")). assertThat(CompactionStyle.valueOf("FIFO")).
isEqualTo(CompactionStyle.FIFO); isEqualTo(CompactionStyle.FIFO);
} }
} finally {
if (ColumnFamilyOptions != null) {
ColumnFamilyOptions.dispose();
}
} }
} }
@Test @Test
public void maxTableFilesSizeFIFO() { public void maxTableFilesSizeFIFO() {
ColumnFamilyOptions opt = null; try (final ColumnFamilyOptions opt = new ColumnFamilyOptions()) {
try {
opt = new ColumnFamilyOptions();
long longValue = rand.nextLong(); long longValue = rand.nextLong();
// Size has to be positive // Size has to be positive
longValue = (longValue < 0) ? -longValue : longValue; longValue = (longValue < 0) ? -longValue : longValue;
@ -736,10 +485,6 @@ public class ColumnFamilyOptionsTest {
opt.setMaxTableFilesSizeFIFO(longValue); opt.setMaxTableFilesSizeFIFO(longValue);
assertThat(opt.maxTableFilesSizeFIFO()). assertThat(opt.maxTableFilesSizeFIFO()).
isEqualTo(longValue); isEqualTo(longValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
} }
} }

File diff suppressed because it is too large Load Diff

@ -18,18 +18,15 @@ public class ComparatorOptionsTest {
@Test @Test
public void comparatorOptions() { public void comparatorOptions() {
final ComparatorOptions copt = new ComparatorOptions(); try(final ComparatorOptions copt = new ComparatorOptions()) {
assertThat(copt).isNotNull(); assertThat(copt).isNotNull();
// UseAdaptiveMutex test
{ // UseAdaptiveMutex test
copt.setUseAdaptiveMutex(true); copt.setUseAdaptiveMutex(true);
assertThat(copt.useAdaptiveMutex()).isTrue(); assertThat(copt.useAdaptiveMutex()).isTrue();
copt.setUseAdaptiveMutex(false); copt.setUseAdaptiveMutex(false);
assertThat(copt.useAdaptiveMutex()).isFalse(); assertThat(copt.useAdaptiveMutex()).isFalse();
} }
copt.dispose();
} }
} }

@ -79,66 +79,52 @@ public class ComparatorTest {
@Test @Test
public void builtinForwardComparator() public void builtinForwardComparator()
throws RocksDBException { throws RocksDBException {
Options options = null; try (final Options options = new Options()
RocksDB rocksDB = null; .setCreateIfMissing(true)
RocksIterator rocksIterator = null; .setComparator(BuiltinComparator.BYTEWISE_COMPARATOR);
try { final RocksDB rocksDb = RocksDB.open(options,
options = new Options(); dbFolder.getRoot().getAbsolutePath())
options.setCreateIfMissing(true); ) {
options.setComparator(BuiltinComparator.BYTEWISE_COMPARATOR); rocksDb.put("abc1".getBytes(), "abc1".getBytes());
rocksDB = RocksDB.open(options, rocksDb.put("abc2".getBytes(), "abc2".getBytes());
dbFolder.getRoot().getAbsolutePath()); rocksDb.put("abc3".getBytes(), "abc3".getBytes());
rocksDB.put("abc1".getBytes(), "abc1".getBytes()); try(final RocksIterator rocksIterator = rocksDb.newIterator()) {
rocksDB.put("abc2".getBytes(), "abc2".getBytes()); // Iterate over keys using a iterator
rocksDB.put("abc3".getBytes(), "abc3".getBytes()); rocksIterator.seekToFirst();
assertThat(rocksIterator.isValid()).isTrue();
rocksIterator = rocksDB.newIterator(); assertThat(rocksIterator.key()).isEqualTo(
// Iterate over keys using a iterator "abc1".getBytes());
rocksIterator.seekToFirst(); assertThat(rocksIterator.value()).isEqualTo(
assertThat(rocksIterator.isValid()).isTrue(); "abc1".getBytes());
assertThat(rocksIterator.key()).isEqualTo( rocksIterator.next();
"abc1".getBytes()); assertThat(rocksIterator.isValid()).isTrue();
assertThat(rocksIterator.value()).isEqualTo( assertThat(rocksIterator.key()).isEqualTo(
"abc1".getBytes()); "abc2".getBytes());
rocksIterator.next(); assertThat(rocksIterator.value()).isEqualTo(
assertThat(rocksIterator.isValid()).isTrue(); "abc2".getBytes());
assertThat(rocksIterator.key()).isEqualTo( rocksIterator.next();
"abc2".getBytes()); assertThat(rocksIterator.isValid()).isTrue();
assertThat(rocksIterator.value()).isEqualTo( assertThat(rocksIterator.key()).isEqualTo(
"abc2".getBytes()); "abc3".getBytes());
rocksIterator.next(); assertThat(rocksIterator.value()).isEqualTo(
assertThat(rocksIterator.isValid()).isTrue(); "abc3".getBytes());
assertThat(rocksIterator.key()).isEqualTo( rocksIterator.next();
"abc3".getBytes()); assertThat(rocksIterator.isValid()).isFalse();
assertThat(rocksIterator.value()).isEqualTo( // Get last one
"abc3".getBytes()); rocksIterator.seekToLast();
rocksIterator.next(); assertThat(rocksIterator.isValid()).isTrue();
assertThat(rocksIterator.isValid()).isFalse(); assertThat(rocksIterator.key()).isEqualTo(
// Get last one "abc3".getBytes());
rocksIterator.seekToLast(); assertThat(rocksIterator.value()).isEqualTo(
assertThat(rocksIterator.isValid()).isTrue(); "abc3".getBytes());
assertThat(rocksIterator.key()).isEqualTo( // Seek for abc
"abc3".getBytes()); rocksIterator.seek("abc".getBytes());
assertThat(rocksIterator.value()).isEqualTo( assertThat(rocksIterator.isValid()).isTrue();
"abc3".getBytes()); assertThat(rocksIterator.key()).isEqualTo(
// Seek for abc "abc1".getBytes());
rocksIterator.seek("abc".getBytes()); assertThat(rocksIterator.value()).isEqualTo(
assertThat(rocksIterator.isValid()).isTrue(); "abc1".getBytes());
assertThat(rocksIterator.key()).isEqualTo(
"abc1".getBytes());
assertThat(rocksIterator.value()).isEqualTo(
"abc1".getBytes());
} finally {
if (rocksIterator != null) {
rocksIterator.dispose();
}
if (rocksDB != null) {
rocksDB.close();
}
if (options != null) {
options.dispose();
} }
} }
} }
@ -146,69 +132,56 @@ public class ComparatorTest {
@Test @Test
public void builtinReverseComparator() public void builtinReverseComparator()
throws RocksDBException { throws RocksDBException {
Options options = null; try (final Options options = new Options()
RocksDB rocksDB = null; .setCreateIfMissing(true)
RocksIterator rocksIterator = null; .setComparator(BuiltinComparator.REVERSE_BYTEWISE_COMPARATOR);
try { final RocksDB rocksDb = RocksDB.open(options,
options = new Options(); dbFolder.getRoot().getAbsolutePath())
options.setCreateIfMissing(true); ) {
options.setComparator(
BuiltinComparator.REVERSE_BYTEWISE_COMPARATOR); rocksDb.put("abc1".getBytes(), "abc1".getBytes());
rocksDB = RocksDB.open(options, rocksDb.put("abc2".getBytes(), "abc2".getBytes());
dbFolder.getRoot().getAbsolutePath()); rocksDb.put("abc3".getBytes(), "abc3".getBytes());
rocksDB.put("abc1".getBytes(), "abc1".getBytes()); try (final RocksIterator rocksIterator = rocksDb.newIterator()) {
rocksDB.put("abc2".getBytes(), "abc2".getBytes()); // Iterate over keys using a iterator
rocksDB.put("abc3".getBytes(), "abc3".getBytes()); rocksIterator.seekToFirst();
assertThat(rocksIterator.isValid()).isTrue();
rocksIterator = rocksDB.newIterator(); assertThat(rocksIterator.key()).isEqualTo(
// Iterate over keys using a iterator "abc3".getBytes());
rocksIterator.seekToFirst(); assertThat(rocksIterator.value()).isEqualTo(
assertThat(rocksIterator.isValid()).isTrue(); "abc3".getBytes());
assertThat(rocksIterator.key()).isEqualTo( rocksIterator.next();
"abc3".getBytes()); assertThat(rocksIterator.isValid()).isTrue();
assertThat(rocksIterator.value()).isEqualTo( assertThat(rocksIterator.key()).isEqualTo(
"abc3".getBytes()); "abc2".getBytes());
rocksIterator.next(); assertThat(rocksIterator.value()).isEqualTo(
assertThat(rocksIterator.isValid()).isTrue(); "abc2".getBytes());
assertThat(rocksIterator.key()).isEqualTo( rocksIterator.next();
"abc2".getBytes()); assertThat(rocksIterator.isValid()).isTrue();
assertThat(rocksIterator.value()).isEqualTo( assertThat(rocksIterator.key()).isEqualTo(
"abc2".getBytes()); "abc1".getBytes());
rocksIterator.next(); assertThat(rocksIterator.value()).isEqualTo(
assertThat(rocksIterator.isValid()).isTrue(); "abc1".getBytes());
assertThat(rocksIterator.key()).isEqualTo( rocksIterator.next();
"abc1".getBytes()); assertThat(rocksIterator.isValid()).isFalse();
assertThat(rocksIterator.value()).isEqualTo( // Get last one
"abc1".getBytes()); rocksIterator.seekToLast();
rocksIterator.next(); assertThat(rocksIterator.isValid()).isTrue();
assertThat(rocksIterator.isValid()).isFalse(); assertThat(rocksIterator.key()).isEqualTo(
// Get last one "abc1".getBytes());
rocksIterator.seekToLast(); assertThat(rocksIterator.value()).isEqualTo(
assertThat(rocksIterator.isValid()).isTrue(); "abc1".getBytes());
assertThat(rocksIterator.key()).isEqualTo( // Will be invalid because abc is after abc1
"abc1".getBytes()); rocksIterator.seek("abc".getBytes());
assertThat(rocksIterator.value()).isEqualTo( assertThat(rocksIterator.isValid()).isFalse();
"abc1".getBytes()); // Will be abc3 because the next one after abc999
// Will be invalid because abc is after abc1 // is abc3
rocksIterator.seek("abc".getBytes()); rocksIterator.seek("abc999".getBytes());
assertThat(rocksIterator.isValid()).isFalse(); assertThat(rocksIterator.key()).isEqualTo(
// Will be abc3 because the next one after abc999 "abc3".getBytes());
// is abc3 assertThat(rocksIterator.value()).isEqualTo(
rocksIterator.seek("abc999".getBytes()); "abc3".getBytes());
assertThat(rocksIterator.key()).isEqualTo(
"abc3".getBytes());
assertThat(rocksIterator.value()).isEqualTo(
"abc3".getBytes());
} finally {
if (rocksIterator != null) {
rocksIterator.dispose();
}
if (rocksDB != null) {
rocksDB.close();
}
if (options != null) {
options.dispose();
} }
} }
} }

@ -8,11 +8,10 @@ package org.rocksdb;
import org.junit.Test; import org.junit.Test;
public class CompressionOptionsTest public class CompressionOptionsTest {
{
@Test @Test
public void getCompressionType() { public void getCompressionType() {
for (CompressionType compressionType : CompressionType.values()) { for (final CompressionType compressionType : CompressionType.values()) {
String libraryName = compressionType.getLibraryName(); String libraryName = compressionType.getLibraryName();
compressionType.equals(CompressionType.getCompressionType( compressionType.equals(CompressionType.getCompressionType(
libraryName)); libraryName));

@ -24,547 +24,339 @@ public class DBOptionsTest {
@Test @Test
public void getDBOptionsFromProps() { public void getDBOptionsFromProps() {
DBOptions opt = null; // setup sample properties
try { final Properties properties = new Properties();
// setup sample properties properties.put("allow_mmap_reads", "true");
Properties properties = new Properties(); properties.put("bytes_per_sync", "13");
properties.put("allow_mmap_reads", "true"); try(final DBOptions opt = DBOptions.getDBOptionsFromProps(properties)) {
properties.put("bytes_per_sync", "13");
opt = DBOptions.getDBOptionsFromProps(properties);
assertThat(opt).isNotNull(); assertThat(opt).isNotNull();
assertThat(String.valueOf(opt.allowMmapReads())). assertThat(String.valueOf(opt.allowMmapReads())).
isEqualTo(properties.get("allow_mmap_reads")); isEqualTo(properties.get("allow_mmap_reads"));
assertThat(String.valueOf(opt.bytesPerSync())). assertThat(String.valueOf(opt.bytesPerSync())).
isEqualTo(properties.get("bytes_per_sync")); isEqualTo(properties.get("bytes_per_sync"));
} finally {
if (opt != null) {
opt.dispose();
}
} }
} }
@Test @Test
public void failDBOptionsFromPropsWithIllegalValue() { public void failDBOptionsFromPropsWithIllegalValue() {
DBOptions opt = null; // setup sample properties
try { final Properties properties = new Properties();
// setup sample properties properties.put("tomato", "1024");
Properties properties = new Properties(); properties.put("burger", "2");
properties.put("tomato", "1024"); try(final DBOptions opt = DBOptions.getDBOptionsFromProps(properties)) {
properties.put("burger", "2");
opt = DBOptions.
getDBOptionsFromProps(properties);
assertThat(opt).isNull(); assertThat(opt).isNull();
} finally {
if (opt != null) {
opt.dispose();
}
} }
} }
@Test(expected = IllegalArgumentException.class) @Test(expected = IllegalArgumentException.class)
public void failDBOptionsFromPropsWithNullValue() { public void failDBOptionsFromPropsWithNullValue() {
DBOptions.getDBOptionsFromProps(null); try(final DBOptions opt = DBOptions.getDBOptionsFromProps(null)) {
//no-op
}
} }
@Test(expected = IllegalArgumentException.class) @Test(expected = IllegalArgumentException.class)
public void failDBOptionsFromPropsWithEmptyProps() { public void failDBOptionsFromPropsWithEmptyProps() {
DBOptions.getDBOptionsFromProps( try(final DBOptions opt = DBOptions.getDBOptionsFromProps(
new Properties()); new Properties())) {
//no-op
}
} }
@Test @Test
public void setIncreaseParallelism() { public void setIncreaseParallelism() {
DBOptions opt = null; try(final DBOptions opt = new DBOptions()) {
try {
opt = new DBOptions();
final int threads = Runtime.getRuntime().availableProcessors() * 2; final int threads = Runtime.getRuntime().availableProcessors() * 2;
opt.setIncreaseParallelism(threads); opt.setIncreaseParallelism(threads);
} finally {
if (opt != null) {
opt.dispose();
}
} }
} }
@Test @Test
public void createIfMissing() { public void createIfMissing() {
DBOptions opt = null; try(final DBOptions opt = new DBOptions()) {
try { final boolean boolValue = rand.nextBoolean();
opt = new DBOptions();
boolean boolValue = rand.nextBoolean();
opt.setCreateIfMissing(boolValue); opt.setCreateIfMissing(boolValue);
assertThat(opt.createIfMissing()). assertThat(opt.createIfMissing()).isEqualTo(boolValue);
isEqualTo(boolValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
} }
@Test @Test
public void createMissingColumnFamilies() { public void createMissingColumnFamilies() {
DBOptions opt = null; try(final DBOptions opt = new DBOptions()) {
try { final boolean boolValue = rand.nextBoolean();
opt = new DBOptions();
boolean boolValue = rand.nextBoolean();
opt.setCreateMissingColumnFamilies(boolValue); opt.setCreateMissingColumnFamilies(boolValue);
assertThat(opt.createMissingColumnFamilies()). assertThat(opt.createMissingColumnFamilies()).isEqualTo(boolValue);
isEqualTo(boolValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
} }
@Test @Test
public void errorIfExists() { public void errorIfExists() {
DBOptions opt = null; try(final DBOptions opt = new DBOptions()) {
try { final boolean boolValue = rand.nextBoolean();
opt = new DBOptions();
boolean boolValue = rand.nextBoolean();
opt.setErrorIfExists(boolValue); opt.setErrorIfExists(boolValue);
assertThat(opt.errorIfExists()).isEqualTo(boolValue); assertThat(opt.errorIfExists()).isEqualTo(boolValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
} }
@Test @Test
public void paranoidChecks() { public void paranoidChecks() {
DBOptions opt = null; try(final DBOptions opt = new DBOptions()) {
try { final boolean boolValue = rand.nextBoolean();
opt = new DBOptions();
boolean boolValue = rand.nextBoolean();
opt.setParanoidChecks(boolValue); opt.setParanoidChecks(boolValue);
assertThat(opt.paranoidChecks()). assertThat(opt.paranoidChecks()).isEqualTo(boolValue);
isEqualTo(boolValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
} }
@Test @Test
public void maxTotalWalSize() { public void maxTotalWalSize() {
DBOptions opt = null; try(final DBOptions opt = new DBOptions()) {
try { final long longValue = rand.nextLong();
opt = new DBOptions();
long longValue = rand.nextLong();
opt.setMaxTotalWalSize(longValue); opt.setMaxTotalWalSize(longValue);
assertThat(opt.maxTotalWalSize()). assertThat(opt.maxTotalWalSize()).isEqualTo(longValue);
isEqualTo(longValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
} }
@Test @Test
public void maxOpenFiles() { public void maxOpenFiles() {
DBOptions opt = null; try(final DBOptions opt = new DBOptions()) {
try { final int intValue = rand.nextInt();
opt = new DBOptions();
int intValue = rand.nextInt();
opt.setMaxOpenFiles(intValue); opt.setMaxOpenFiles(intValue);
assertThat(opt.maxOpenFiles()).isEqualTo(intValue); assertThat(opt.maxOpenFiles()).isEqualTo(intValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
} }
@Test @Test
public void disableDataSync() { public void disableDataSync() {
DBOptions opt = null; try(final DBOptions opt = new DBOptions()) {
try { final boolean boolValue = rand.nextBoolean();
opt = new DBOptions();
boolean boolValue = rand.nextBoolean();
opt.setDisableDataSync(boolValue); opt.setDisableDataSync(boolValue);
assertThat(opt.disableDataSync()). assertThat(opt.disableDataSync()).isEqualTo(boolValue);
isEqualTo(boolValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
} }
@Test @Test
public void useFsync() { public void useFsync() {
DBOptions opt = null; try(final DBOptions opt = new DBOptions()) {
try { final boolean boolValue = rand.nextBoolean();
opt = new DBOptions();
boolean boolValue = rand.nextBoolean();
opt.setUseFsync(boolValue); opt.setUseFsync(boolValue);
assertThat(opt.useFsync()).isEqualTo(boolValue); assertThat(opt.useFsync()).isEqualTo(boolValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
} }
@Test @Test
public void dbLogDir() { public void dbLogDir() {
DBOptions opt = null; try(final DBOptions opt = new DBOptions()) {
try { final String str = "path/to/DbLogDir";
opt = new DBOptions();
String str = "path/to/DbLogDir";
opt.setDbLogDir(str); opt.setDbLogDir(str);
assertThat(opt.dbLogDir()).isEqualTo(str); assertThat(opt.dbLogDir()).isEqualTo(str);
} finally {
if (opt != null) {
opt.dispose();
}
} }
} }
@Test @Test
public void walDir() { public void walDir() {
DBOptions opt = null; try(final DBOptions opt = new DBOptions()) {
try { final String str = "path/to/WalDir";
opt = new DBOptions();
String str = "path/to/WalDir";
opt.setWalDir(str); opt.setWalDir(str);
assertThat(opt.walDir()).isEqualTo(str); assertThat(opt.walDir()).isEqualTo(str);
} finally {
if (opt != null) {
opt.dispose();
}
} }
} }
@Test @Test
public void deleteObsoleteFilesPeriodMicros() { public void deleteObsoleteFilesPeriodMicros() {
DBOptions opt = null; try(final DBOptions opt = new DBOptions()) {
try { final long longValue = rand.nextLong();
opt = new DBOptions();
long longValue = rand.nextLong();
opt.setDeleteObsoleteFilesPeriodMicros(longValue); opt.setDeleteObsoleteFilesPeriodMicros(longValue);
assertThat(opt.deleteObsoleteFilesPeriodMicros()). assertThat(opt.deleteObsoleteFilesPeriodMicros()).isEqualTo(longValue);
isEqualTo(longValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
} }
@Test @Test
public void maxBackgroundCompactions() { public void maxBackgroundCompactions() {
DBOptions opt = null; try(final DBOptions opt = new DBOptions()) {
try { final int intValue = rand.nextInt();
opt = new DBOptions();
int intValue = rand.nextInt();
opt.setMaxBackgroundCompactions(intValue); opt.setMaxBackgroundCompactions(intValue);
assertThat(opt.maxBackgroundCompactions()). assertThat(opt.maxBackgroundCompactions()).isEqualTo(intValue);
isEqualTo(intValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
} }
@Test @Test
public void maxBackgroundFlushes() { public void maxBackgroundFlushes() {
DBOptions opt = null; try(final DBOptions opt = new DBOptions()) {
try { final int intValue = rand.nextInt();
opt = new DBOptions();
int intValue = rand.nextInt();
opt.setMaxBackgroundFlushes(intValue); opt.setMaxBackgroundFlushes(intValue);
assertThat(opt.maxBackgroundFlushes()). assertThat(opt.maxBackgroundFlushes()).isEqualTo(intValue);
isEqualTo(intValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
} }
@Test @Test
public void maxLogFileSize() throws RocksDBException { public void maxLogFileSize() throws RocksDBException {
DBOptions opt = null; try(final DBOptions opt = new DBOptions()) {
try { final long longValue = rand.nextLong();
opt = new DBOptions();
long longValue = rand.nextLong();
opt.setMaxLogFileSize(longValue); opt.setMaxLogFileSize(longValue);
assertThat(opt.maxLogFileSize()).isEqualTo(longValue); assertThat(opt.maxLogFileSize()).isEqualTo(longValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
} }
@Test @Test
public void logFileTimeToRoll() throws RocksDBException { public void logFileTimeToRoll() throws RocksDBException {
DBOptions opt = null; try(final DBOptions opt = new DBOptions()) {
try { final long longValue = rand.nextLong();
opt = new DBOptions();
long longValue = rand.nextLong();
opt.setLogFileTimeToRoll(longValue); opt.setLogFileTimeToRoll(longValue);
assertThat(opt.logFileTimeToRoll()). assertThat(opt.logFileTimeToRoll()).isEqualTo(longValue);
isEqualTo(longValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
} }
@Test @Test
public void keepLogFileNum() throws RocksDBException { public void keepLogFileNum() throws RocksDBException {
DBOptions opt = null; try(final DBOptions opt = new DBOptions()) {
try { final long longValue = rand.nextLong();
opt = new DBOptions();
long longValue = rand.nextLong();
opt.setKeepLogFileNum(longValue); opt.setKeepLogFileNum(longValue);
assertThat(opt.keepLogFileNum()).isEqualTo(longValue); assertThat(opt.keepLogFileNum()).isEqualTo(longValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
} }
@Test @Test
public void maxManifestFileSize() { public void maxManifestFileSize() {
DBOptions opt = null; try(final DBOptions opt = new DBOptions()) {
try { final long longValue = rand.nextLong();
opt = new DBOptions();
long longValue = rand.nextLong();
opt.setMaxManifestFileSize(longValue); opt.setMaxManifestFileSize(longValue);
assertThat(opt.maxManifestFileSize()). assertThat(opt.maxManifestFileSize()).isEqualTo(longValue);
isEqualTo(longValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
} }
@Test @Test
public void tableCacheNumshardbits() { public void tableCacheNumshardbits() {
DBOptions opt = null; try(final DBOptions opt = new DBOptions()) {
try { final int intValue = rand.nextInt();
opt = new DBOptions();
int intValue = rand.nextInt();
opt.setTableCacheNumshardbits(intValue); opt.setTableCacheNumshardbits(intValue);
assertThat(opt.tableCacheNumshardbits()). assertThat(opt.tableCacheNumshardbits()).isEqualTo(intValue);
isEqualTo(intValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
} }
@Test @Test
public void walSizeLimitMB() { public void walSizeLimitMB() {
DBOptions opt = null; try(final DBOptions opt = new DBOptions()) {
try { final long longValue = rand.nextLong();
opt = new DBOptions();
long longValue = rand.nextLong();
opt.setWalSizeLimitMB(longValue); opt.setWalSizeLimitMB(longValue);
assertThat(opt.walSizeLimitMB()).isEqualTo(longValue); assertThat(opt.walSizeLimitMB()).isEqualTo(longValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
} }
@Test @Test
public void walTtlSeconds() { public void walTtlSeconds() {
DBOptions opt = null; try(final DBOptions opt = new DBOptions()) {
try { final long longValue = rand.nextLong();
opt = new DBOptions();
long longValue = rand.nextLong();
opt.setWalTtlSeconds(longValue); opt.setWalTtlSeconds(longValue);
assertThat(opt.walTtlSeconds()).isEqualTo(longValue); assertThat(opt.walTtlSeconds()).isEqualTo(longValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
} }
@Test @Test
public void manifestPreallocationSize() throws RocksDBException { public void manifestPreallocationSize() throws RocksDBException {
DBOptions opt = null; try(final DBOptions opt = new DBOptions()) {
try { final long longValue = rand.nextLong();
opt = new DBOptions();
long longValue = rand.nextLong();
opt.setManifestPreallocationSize(longValue); opt.setManifestPreallocationSize(longValue);
assertThat(opt.manifestPreallocationSize()). assertThat(opt.manifestPreallocationSize()).isEqualTo(longValue);
isEqualTo(longValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
} }
@Test @Test
public void allowOsBuffer() { public void allowOsBuffer() {
DBOptions opt = null; try(final DBOptions opt = new DBOptions()) {
try { final boolean boolValue = rand.nextBoolean();
opt = new DBOptions();
boolean boolValue = rand.nextBoolean();
opt.setAllowOsBuffer(boolValue); opt.setAllowOsBuffer(boolValue);
assertThat(opt.allowOsBuffer()).isEqualTo(boolValue); assertThat(opt.allowOsBuffer()).isEqualTo(boolValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
} }
@Test @Test
public void allowMmapReads() { public void allowMmapReads() {
DBOptions opt = null; try(final DBOptions opt = new DBOptions()) {
try { final boolean boolValue = rand.nextBoolean();
opt = new DBOptions();
boolean boolValue = rand.nextBoolean();
opt.setAllowMmapReads(boolValue); opt.setAllowMmapReads(boolValue);
assertThat(opt.allowMmapReads()).isEqualTo(boolValue); assertThat(opt.allowMmapReads()).isEqualTo(boolValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
} }
@Test @Test
public void allowMmapWrites() { public void allowMmapWrites() {
DBOptions opt = null; try(final DBOptions opt = new DBOptions()) {
try { final boolean boolValue = rand.nextBoolean();
opt = new DBOptions();
boolean boolValue = rand.nextBoolean();
opt.setAllowMmapWrites(boolValue); opt.setAllowMmapWrites(boolValue);
assertThat(opt.allowMmapWrites()).isEqualTo(boolValue); assertThat(opt.allowMmapWrites()).isEqualTo(boolValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
} }
@Test @Test
public void isFdCloseOnExec() { public void isFdCloseOnExec() {
DBOptions opt = null; try(final DBOptions opt = new DBOptions()) {
try { final boolean boolValue = rand.nextBoolean();
opt = new DBOptions();
boolean boolValue = rand.nextBoolean();
opt.setIsFdCloseOnExec(boolValue); opt.setIsFdCloseOnExec(boolValue);
assertThat(opt.isFdCloseOnExec()).isEqualTo(boolValue); assertThat(opt.isFdCloseOnExec()).isEqualTo(boolValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
} }
@Test @Test
public void statsDumpPeriodSec() { public void statsDumpPeriodSec() {
DBOptions opt = null; try(final DBOptions opt = new DBOptions()) {
try { final int intValue = rand.nextInt();
opt = new DBOptions();
int intValue = rand.nextInt();
opt.setStatsDumpPeriodSec(intValue); opt.setStatsDumpPeriodSec(intValue);
assertThat(opt.statsDumpPeriodSec()).isEqualTo(intValue); assertThat(opt.statsDumpPeriodSec()).isEqualTo(intValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
} }
@Test @Test
public void adviseRandomOnOpen() { public void adviseRandomOnOpen() {
DBOptions opt = null; try(final DBOptions opt = new DBOptions()) {
try { final boolean boolValue = rand.nextBoolean();
opt = new DBOptions();
boolean boolValue = rand.nextBoolean();
opt.setAdviseRandomOnOpen(boolValue); opt.setAdviseRandomOnOpen(boolValue);
assertThat(opt.adviseRandomOnOpen()).isEqualTo(boolValue); assertThat(opt.adviseRandomOnOpen()).isEqualTo(boolValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
} }
@Test @Test
public void useAdaptiveMutex() { public void useAdaptiveMutex() {
DBOptions opt = null; try(final DBOptions opt = new DBOptions()) {
try { final boolean boolValue = rand.nextBoolean();
opt = new DBOptions();
boolean boolValue = rand.nextBoolean();
opt.setUseAdaptiveMutex(boolValue); opt.setUseAdaptiveMutex(boolValue);
assertThat(opt.useAdaptiveMutex()).isEqualTo(boolValue); assertThat(opt.useAdaptiveMutex()).isEqualTo(boolValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
} }
@Test @Test
public void bytesPerSync() { public void bytesPerSync() {
DBOptions opt = null; try(final DBOptions opt = new DBOptions()) {
try { final long longValue = rand.nextLong();
opt = new DBOptions();
long longValue = rand.nextLong();
opt.setBytesPerSync(longValue); opt.setBytesPerSync(longValue);
assertThat(opt.bytesPerSync()).isEqualTo(longValue); assertThat(opt.bytesPerSync()).isEqualTo(longValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
} }
@Test @Test
public void rateLimiterConfig() { public void rateLimiterConfig() {
DBOptions options = null; try(final DBOptions options = new DBOptions();
DBOptions anotherOptions = null; final DBOptions anotherOptions = new DBOptions()) {
try { final RateLimiterConfig rateLimiterConfig =
options = new DBOptions();
RateLimiterConfig rateLimiterConfig =
new GenericRateLimiterConfig(1000, 100 * 1000, 1); new GenericRateLimiterConfig(1000, 100 * 1000, 1);
options.setRateLimiterConfig(rateLimiterConfig); options.setRateLimiterConfig(rateLimiterConfig);
// Test with parameter initialization // Test with parameter initialization
anotherOptions = new DBOptions();
anotherOptions.setRateLimiterConfig( anotherOptions.setRateLimiterConfig(
new GenericRateLimiterConfig(1000)); new GenericRateLimiterConfig(1000));
} finally {
if (options != null) {
options.dispose();
}
if (anotherOptions != null) {
anotherOptions.dispose();
}
} }
} }
@Test @Test
public void statistics() { public void statistics() {
DBOptions options = new DBOptions(); try(final DBOptions options = new DBOptions()) {
Statistics statistics = options.createStatistics(). Statistics statistics = options.createStatistics().
statisticsPtr(); statisticsPtr();
assertThat(statistics).isNotNull(); assertThat(statistics).isNotNull();
DBOptions anotherOptions = new DBOptions(); try(final DBOptions anotherOptions = new DBOptions()) {
statistics = anotherOptions.statisticsPtr(); statistics = anotherOptions.statisticsPtr();
assertThat(statistics).isNotNull(); assertThat(statistics).isNotNull();
}
}
} }
} }

@ -18,11 +18,8 @@ public class DirectSliceTest {
@Test @Test
public void directSlice() { public void directSlice() {
DirectSlice directSlice = null; try(final DirectSlice directSlice = new DirectSlice("abc");
DirectSlice otherSlice = null; final DirectSlice otherSlice = new DirectSlice("abc")) {
try {
directSlice = new DirectSlice("abc");
otherSlice = new DirectSlice("abc");
assertThat(directSlice.toString()).isEqualTo("abc"); assertThat(directSlice.toString()).isEqualTo("abc");
// clear first slice // clear first slice
directSlice.clear(); directSlice.clear();
@ -32,75 +29,46 @@ public class DirectSliceTest {
// remove prefix // remove prefix
otherSlice.removePrefix(1); otherSlice.removePrefix(1);
assertThat(otherSlice.toString()).isEqualTo("bc"); assertThat(otherSlice.toString()).isEqualTo("bc");
} finally {
if (directSlice != null) {
directSlice.dispose();
}
if (otherSlice != null) {
otherSlice.dispose();
}
} }
} }
@Test @Test
public void directSliceWithByteBuffer() { public void directSliceWithByteBuffer() {
DirectSlice directSlice = null; final byte[] data = "Some text".getBytes();
try { final ByteBuffer buffer = ByteBuffer.allocateDirect(data.length + 1);
byte[] data = "Some text".getBytes(); buffer.put(data);
ByteBuffer buffer = ByteBuffer.allocateDirect(data.length + 1); buffer.put(data.length, (byte)0);
buffer.put(data);
buffer.put(data.length, (byte)0);
directSlice = new DirectSlice(buffer); try(final DirectSlice directSlice = new DirectSlice(buffer)) {
assertThat(directSlice.toString()).isEqualTo("Some text"); assertThat(directSlice.toString()).isEqualTo("Some text");
} finally {
if (directSlice != null) {
directSlice.dispose();
}
} }
} }
@Test @Test
public void directSliceWithByteBufferAndLength() { public void directSliceWithByteBufferAndLength() {
DirectSlice directSlice = null; final byte[] data = "Some text".getBytes();
try { final ByteBuffer buffer = ByteBuffer.allocateDirect(data.length);
byte[] data = "Some text".getBytes(); buffer.put(data);
ByteBuffer buffer = ByteBuffer.allocateDirect(data.length); try(final DirectSlice directSlice = new DirectSlice(buffer, 4)) {
buffer.put(data);
directSlice = new DirectSlice(buffer, 4);
assertThat(directSlice.toString()).isEqualTo("Some"); assertThat(directSlice.toString()).isEqualTo("Some");
} finally {
if (directSlice != null) {
directSlice.dispose();
}
} }
} }
@Test(expected = AssertionError.class) @Test(expected = AssertionError.class)
public void directSliceInitWithoutDirectAllocation() { public void directSliceInitWithoutDirectAllocation() {
DirectSlice directSlice = null; final byte[] data = "Some text".getBytes();
try { final ByteBuffer buffer = ByteBuffer.wrap(data);
byte[] data = "Some text".getBytes(); try(final DirectSlice directSlice = new DirectSlice(buffer)) {
ByteBuffer buffer = ByteBuffer.wrap(data); //no-op
directSlice = new DirectSlice(buffer);
} finally {
if (directSlice != null) {
directSlice.dispose();
}
} }
} }
@Test(expected = AssertionError.class) @Test(expected = AssertionError.class)
public void directSlicePrefixInitWithoutDirectAllocation() { public void directSlicePrefixInitWithoutDirectAllocation() {
DirectSlice directSlice = null; final byte[] data = "Some text".getBytes();
try { final ByteBuffer buffer = ByteBuffer.wrap(data);
byte[] data = "Some text".getBytes(); try(final DirectSlice directSlice = new DirectSlice(buffer, 4)) {
ByteBuffer buffer = ByteBuffer.wrap(data); //no-op
directSlice = new DirectSlice(buffer, 4);
} finally {
if (directSlice != null) {
directSlice.dispose();
}
} }
} }
} }

@ -16,31 +16,23 @@ public class FilterTest {
@Test @Test
public void filter() { public void filter() {
Options options = null; // new Bloom filter
try { final BlockBasedTableConfig blockConfig = new BlockBasedTableConfig();
options = new Options(); try(final Options options = new Options()) {
// test table config
options.setTableFormatConfig(new BlockBasedTableConfig(). try(final Filter bloomFilter = new BloomFilter()) {
setFilter(new BloomFilter())); blockConfig.setFilter(bloomFilter);
options.dispose(); options.setTableFormatConfig(blockConfig);
System.gc(); }
System.runFinalization();
// new Bloom filter try(final Filter bloomFilter = new BloomFilter(10)) {
options = new Options(); blockConfig.setFilter(bloomFilter);
BlockBasedTableConfig blockConfig = new BlockBasedTableConfig(); options.setTableFormatConfig(blockConfig);
blockConfig.setFilter(new BloomFilter()); }
options.setTableFormatConfig(blockConfig);
BloomFilter bloomFilter = new BloomFilter(10); try(final Filter bloomFilter = new BloomFilter(10, false)) {
blockConfig.setFilter(bloomFilter); blockConfig.setFilter(bloomFilter);
options.setTableFormatConfig(blockConfig); options.setTableFormatConfig(blockConfig);
System.gc();
System.runFinalization();
blockConfig.setFilter(new BloomFilter(10, false));
options.setTableFormatConfig(blockConfig);
} finally {
if (options != null) {
options.dispose();
} }
} }
} }

@ -22,44 +22,28 @@ public class FlushTest {
@Test @Test
public void flush() throws RocksDBException { public void flush() throws RocksDBException {
RocksDB db = null; try(final Options options = new Options()
Options options = null; .setCreateIfMissing(true)
WriteOptions wOpt = null; .setMaxWriteBufferNumber(10)
FlushOptions flushOptions = null; .setMinWriteBufferNumberToMerge(10);
try { final WriteOptions wOpt = new WriteOptions()
options = new Options(); .setDisableWAL(true);
// Setup options final FlushOptions flushOptions = new FlushOptions()
options.setCreateIfMissing(true); .setWaitForFlush(true)) {
options.setMaxWriteBufferNumber(10);
options.setMinWriteBufferNumberToMerge(10);
wOpt = new WriteOptions();
flushOptions = new FlushOptions();
flushOptions.setWaitForFlush(true);
assertThat(flushOptions.waitForFlush()).isTrue(); assertThat(flushOptions.waitForFlush()).isTrue();
wOpt.setDisableWAL(true);
db = RocksDB.open(options, dbFolder.getRoot().getAbsolutePath());
db.put(wOpt, "key1".getBytes(), "value1".getBytes());
db.put(wOpt, "key2".getBytes(), "value2".getBytes());
db.put(wOpt, "key3".getBytes(), "value3".getBytes());
db.put(wOpt, "key4".getBytes(), "value4".getBytes());
assertThat(db.getProperty("rocksdb.num-entries-active-mem-table")).isEqualTo("4");
db.flush(flushOptions);
assertThat(db.getProperty("rocksdb.num-entries-active-mem-table")).
isEqualTo("0");
} finally {
if (flushOptions != null) {
flushOptions.dispose();
}
if (db != null) {
db.close();
}
if (options != null) {
options.dispose();
}
if (wOpt != null) {
wOpt.dispose();
}
try(final RocksDB db = RocksDB.open(options,
dbFolder.getRoot().getAbsolutePath())) {
db.put(wOpt, "key1".getBytes(), "value1".getBytes());
db.put(wOpt, "key2".getBytes(), "value2".getBytes());
db.put(wOpt, "key3".getBytes(), "value3".getBytes());
db.put(wOpt, "key4".getBytes(), "value4".getBytes());
assertThat(db.getProperty("rocksdb.num-entries-active-mem-table"))
.isEqualTo("4");
db.flush(flushOptions);
assertThat(db.getProperty("rocksdb.num-entries-active-mem-table"))
.isEqualTo("0");
}
} }
} }
} }

@ -24,81 +24,52 @@ public class InfoLogLevelTest {
@Test @Test
public void testInfoLogLevel() throws RocksDBException, public void testInfoLogLevel() throws RocksDBException,
IOException { IOException {
RocksDB db = null; try (final RocksDB db =
try { RocksDB.open(dbFolder.getRoot().getAbsolutePath())) {
db = RocksDB.open(dbFolder.getRoot().getAbsolutePath());
db.put("key".getBytes(), "value".getBytes()); db.put("key".getBytes(), "value".getBytes());
assertThat(getLogContentsWithoutHeader()).isNotEmpty(); assertThat(getLogContentsWithoutHeader()).isNotEmpty();
} finally {
if (db != null) {
db.close();
}
} }
} }
@Test @Test
public void testFatalLogLevel() throws RocksDBException, public void testFatalLogLevel() throws RocksDBException,
IOException { IOException {
RocksDB db = null; try (final Options options = new Options().
Options options = null; setCreateIfMissing(true).
try { setInfoLogLevel(InfoLogLevel.FATAL_LEVEL);
options = new Options(). final RocksDB db = RocksDB.open(options,
setCreateIfMissing(true). dbFolder.getRoot().getAbsolutePath())) {
setInfoLogLevel(InfoLogLevel.FATAL_LEVEL);
assertThat(options.infoLogLevel()). assertThat(options.infoLogLevel()).
isEqualTo(InfoLogLevel.FATAL_LEVEL); isEqualTo(InfoLogLevel.FATAL_LEVEL);
db = RocksDB.open(options,
dbFolder.getRoot().getAbsolutePath());
db.put("key".getBytes(), "value".getBytes()); db.put("key".getBytes(), "value".getBytes());
// As InfoLogLevel is set to FATAL_LEVEL, here we expect the log // As InfoLogLevel is set to FATAL_LEVEL, here we expect the log
// content to be empty. // content to be empty.
assertThat(getLogContentsWithoutHeader()).isEmpty(); assertThat(getLogContentsWithoutHeader()).isEmpty();
} finally {
if (db != null) {
db.close();
}
if (options != null) {
options.dispose();
}
} }
} }
@Test @Test
public void testFatalLogLevelWithDBOptions() public void testFatalLogLevelWithDBOptions()
throws RocksDBException, IOException { throws RocksDBException, IOException {
RocksDB db = null; try (final DBOptions dbOptions = new DBOptions().
Options options = null; setInfoLogLevel(InfoLogLevel.FATAL_LEVEL);
DBOptions dbOptions = null; final Options options = new Options(dbOptions,
try { new ColumnFamilyOptions()).
dbOptions = new DBOptions(). setCreateIfMissing(true);
setInfoLogLevel(InfoLogLevel.FATAL_LEVEL); final RocksDB db =
options = new Options(dbOptions, RocksDB.open(options, dbFolder.getRoot().getAbsolutePath())) {
new ColumnFamilyOptions()).
setCreateIfMissing(true);
assertThat(dbOptions.infoLogLevel()). assertThat(dbOptions.infoLogLevel()).
isEqualTo(InfoLogLevel.FATAL_LEVEL); isEqualTo(InfoLogLevel.FATAL_LEVEL);
assertThat(options.infoLogLevel()). assertThat(options.infoLogLevel()).
isEqualTo(InfoLogLevel.FATAL_LEVEL); isEqualTo(InfoLogLevel.FATAL_LEVEL);
db = RocksDB.open(options,
dbFolder.getRoot().getAbsolutePath());
db.put("key".getBytes(), "value".getBytes()); db.put("key".getBytes(), "value".getBytes());
assertThat(getLogContentsWithoutHeader()).isEmpty(); assertThat(getLogContentsWithoutHeader()).isEmpty();
} finally {
if (db != null) {
db.close();
}
if (options != null) {
options.dispose();
}
if (dbOptions != null) {
dbOptions.dispose();
}
} }
} }
@Test(expected = IllegalArgumentException.class) @Test(expected = IllegalArgumentException.class)
public void failIfIllegalByteValueProvided() { public void failIfIllegalByteValueProvided() {
InfoLogLevel.getInfoLogLevel((byte)-1); InfoLogLevel.getInfoLogLevel((byte) -1);
} }
@Test @Test
@ -114,9 +85,10 @@ public class InfoLogLevelTest {
* @throws IOException if file is not found. * @throws IOException if file is not found.
*/ */
private String getLogContentsWithoutHeader() throws IOException { private String getLogContentsWithoutHeader() throws IOException {
final String separator = Environment.isWindows() ? "\n" : System.getProperty("line.separator"); final String separator = Environment.isWindows() ?
"\n" : System.getProperty("line.separator");
final String[] lines = new String(readAllBytes(get( final String[] lines = new String(readAllBytes(get(
dbFolder.getRoot().getAbsolutePath()+ "/LOG"))).split(separator); dbFolder.getRoot().getAbsolutePath() + "/LOG"))).split(separator);
int first_non_header = lines.length; int first_non_header = lines.length;
// Identify the last line of the header // Identify the last line of the header

@ -10,6 +10,7 @@ import org.junit.Test;
import org.junit.rules.TemporaryFolder; import org.junit.rules.TemporaryFolder;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays;
import java.util.List; import java.util.List;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
@ -25,70 +26,61 @@ public class KeyMayExistTest {
@Test @Test
public void keyMayExist() throws RocksDBException { public void keyMayExist() throws RocksDBException {
RocksDB db = null; final List<ColumnFamilyDescriptor> cfDescriptors = Arrays.asList(
DBOptions options = null; new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY),
List<ColumnFamilyDescriptor> cfDescriptors = new ColumnFamilyDescriptor("new_cf".getBytes())
new ArrayList<>(); );
List<ColumnFamilyHandle> columnFamilyHandleList =
new ArrayList<>();
try {
options = new DBOptions();
options.setCreateIfMissing(true)
.setCreateMissingColumnFamilies(true);
// open database using cf names
cfDescriptors.add(new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY)); final List<ColumnFamilyHandle> columnFamilyHandleList = new ArrayList<>();
cfDescriptors.add(new ColumnFamilyDescriptor("new_cf".getBytes())); try (final DBOptions options = new DBOptions()
db = RocksDB.open(options, .setCreateIfMissing(true)
dbFolder.getRoot().getAbsolutePath(), .setCreateMissingColumnFamilies(true);
cfDescriptors, columnFamilyHandleList); final RocksDB db = RocksDB.open(options,
assertThat(columnFamilyHandleList.size()). dbFolder.getRoot().getAbsolutePath(),
isEqualTo(2); cfDescriptors, columnFamilyHandleList)) {
db.put("key".getBytes(), "value".getBytes()); try {
// Test without column family assertThat(columnFamilyHandleList.size()).
StringBuffer retValue = new StringBuffer(); isEqualTo(2);
boolean exists = db.keyMayExist("key".getBytes(), retValue); db.put("key".getBytes(), "value".getBytes());
assertThat(exists).isTrue(); // Test without column family
assertThat(retValue.toString()). StringBuffer retValue = new StringBuffer();
isEqualTo("value"); boolean exists = db.keyMayExist("key".getBytes(), retValue);
assertThat(exists).isTrue();
assertThat(retValue.toString()).isEqualTo("value");
// Test without column family but with readOptions // Test without column family but with readOptions
retValue = new StringBuffer(); try (final ReadOptions readOptions = new ReadOptions()) {
exists = db.keyMayExist(new ReadOptions(), "key".getBytes(), retValue = new StringBuffer();
retValue); exists = db.keyMayExist(readOptions, "key".getBytes(), retValue);
assertThat(exists).isTrue(); assertThat(exists).isTrue();
assertThat(retValue.toString()). assertThat(retValue.toString()).isEqualTo("value");
isEqualTo("value"); }
// Test with column family // Test with column family
retValue = new StringBuffer(); retValue = new StringBuffer();
exists = db.keyMayExist(columnFamilyHandleList.get(0), "key".getBytes(), exists = db.keyMayExist(columnFamilyHandleList.get(0), "key".getBytes(),
retValue); retValue);
assertThat(exists).isTrue(); assertThat(exists).isTrue();
assertThat(retValue.toString()). assertThat(retValue.toString()).isEqualTo("value");
isEqualTo("value");
// Test with column family and readOptions // Test with column family and readOptions
retValue = new StringBuffer(); try (final ReadOptions readOptions = new ReadOptions()) {
exists = db.keyMayExist(new ReadOptions(), retValue = new StringBuffer();
columnFamilyHandleList.get(0), "key".getBytes(), exists = db.keyMayExist(readOptions,
retValue); columnFamilyHandleList.get(0), "key".getBytes(),
assertThat(exists).isTrue(); retValue);
assertThat(retValue.toString()). assertThat(exists).isTrue();
isEqualTo("value"); assertThat(retValue.toString()).isEqualTo("value");
}
// KeyMayExist in CF1 must return false // KeyMayExist in CF1 must return false
assertThat(db.keyMayExist(columnFamilyHandleList.get(1), assertThat(db.keyMayExist(columnFamilyHandleList.get(1),
"key".getBytes(), retValue)).isFalse(); "key".getBytes(), retValue)).isFalse();
} finally { } finally {
for (ColumnFamilyHandle columnFamilyHandle : columnFamilyHandleList) { for (final ColumnFamilyHandle columnFamilyHandle :
columnFamilyHandle.dispose(); columnFamilyHandleList) {
} columnFamilyHandle.close();
if (db != null) { }
db.close();
}
if (options != null) {
options.dispose();
} }
} }
} }

@ -6,6 +6,7 @@ import org.junit.Test;
import org.junit.rules.TemporaryFolder; import org.junit.rules.TemporaryFolder;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
@ -19,202 +20,165 @@ public class LoggerTest {
@Rule @Rule
public TemporaryFolder dbFolder = new TemporaryFolder(); public TemporaryFolder dbFolder = new TemporaryFolder();
private AtomicInteger logMessageCounter = new AtomicInteger();
@Test @Test
public void customLogger() throws RocksDBException { public void customLogger() throws RocksDBException {
RocksDB db = null; final AtomicInteger logMessageCounter = new AtomicInteger();
logMessageCounter.set(0); try (final Options options = new Options().
try { setInfoLogLevel(InfoLogLevel.DEBUG_LEVEL).
setCreateIfMissing(true);
// Setup options final Logger logger = new Logger(options) {
final Options options = new Options(). // Create new logger with max log level passed by options
setInfoLogLevel(InfoLogLevel.DEBUG_LEVEL). @Override
setCreateIfMissing(true); protected void log(InfoLogLevel infoLogLevel, String logMsg) {
assertThat(logMsg).isNotNull();
// Create new logger with max log level passed by options assertThat(logMsg.length()).isGreaterThan(0);
Logger logger = new Logger(options) { logMessageCounter.incrementAndGet();
@Override }
protected void log(InfoLogLevel infoLogLevel, String logMsg) { }
assertThat(logMsg).isNotNull(); ) {
assertThat(logMsg.length()).isGreaterThan(0);
logMessageCounter.incrementAndGet();
}
};
// Set custom logger to options // Set custom logger to options
options.setLogger(logger); options.setLogger(logger);
db = RocksDB.open(options, dbFolder.getRoot().getAbsolutePath()); try (final RocksDB db = RocksDB.open(options,
dbFolder.getRoot().getAbsolutePath())) {
// there should be more than zero received log messages in // there should be more than zero received log messages in
// debug level. // debug level.
assertThat(logMessageCounter.get()).isGreaterThan(0); assertThat(logMessageCounter.get()).isGreaterThan(0);
} finally {
if (db != null) {
db.close();
} }
} }
logMessageCounter.set(0);
} }
@Test @Test
public void fatalLogger() throws RocksDBException { public void fatalLogger() throws RocksDBException {
RocksDB db = null; final AtomicInteger logMessageCounter = new AtomicInteger();
logMessageCounter.set(0); try (final Options options = new Options().
setInfoLogLevel(InfoLogLevel.FATAL_LEVEL).
try { setCreateIfMissing(true);
// Setup options
final Options options = new Options(). final Logger logger = new Logger(options) {
setInfoLogLevel(InfoLogLevel.FATAL_LEVEL). // Create new logger with max log level passed by options
setCreateIfMissing(true); @Override
protected void log(InfoLogLevel infoLogLevel, String logMsg) {
// Create new logger with max log level passed by options assertThat(logMsg).isNotNull();
Logger logger = new Logger(options) { assertThat(logMsg.length()).isGreaterThan(0);
@Override logMessageCounter.incrementAndGet();
protected void log(InfoLogLevel infoLogLevel, String logMsg) { }
assertThat(logMsg).isNotNull(); }
assertThat(logMsg.length()).isGreaterThan(0); ) {
logMessageCounter.incrementAndGet();
}
};
// Set custom logger to options // Set custom logger to options
options.setLogger(logger); options.setLogger(logger);
db = RocksDB.open(options, dbFolder.getRoot().getAbsolutePath()); try (final RocksDB db = RocksDB.open(options,
dbFolder.getRoot().getAbsolutePath())) {
// there should be zero messages // there should be zero messages
// using fatal level as log level. // using fatal level as log level.
assertThat(logMessageCounter.get()).isEqualTo(0); assertThat(logMessageCounter.get()).isEqualTo(0);
} finally {
if (db != null) {
db.close();
} }
} }
logMessageCounter.set(0);
} }
@Test @Test
public void dbOptionsLogger() throws RocksDBException { public void dbOptionsLogger() throws RocksDBException {
RocksDB db = null; final AtomicInteger logMessageCounter = new AtomicInteger();
Logger logger = null; try (final DBOptions options = new DBOptions().
List<ColumnFamilyHandle> cfHandles = new ArrayList<>(); setInfoLogLevel(InfoLogLevel.FATAL_LEVEL).
List<ColumnFamilyDescriptor> cfDescriptors = new ArrayList<>(); setCreateIfMissing(true);
cfDescriptors.add(new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY)); final Logger logger = new Logger(options) {
// Create new logger with max log level passed by options
logMessageCounter.set(0); @Override
try { protected void log(InfoLogLevel infoLogLevel, String logMsg) {
// Setup options assertThat(logMsg).isNotNull();
final DBOptions options = new DBOptions(). assertThat(logMsg.length()).isGreaterThan(0);
setInfoLogLevel(InfoLogLevel.FATAL_LEVEL). logMessageCounter.incrementAndGet();
setCreateIfMissing(true); }
}
// Create new logger with max log level passed by options ) {
logger = new Logger(options) {
@Override
protected void log(InfoLogLevel infoLogLevel, String logMsg) {
assertThat(logMsg).isNotNull();
assertThat(logMsg.length()).isGreaterThan(0);
logMessageCounter.incrementAndGet();
}
};
// Set custom logger to options // Set custom logger to options
options.setLogger(logger); options.setLogger(logger);
db = RocksDB.open(options, dbFolder.getRoot().getAbsolutePath(),
cfDescriptors, cfHandles); final List<ColumnFamilyDescriptor> cfDescriptors =
// there should be zero messages Arrays.asList(
// using fatal level as log level. new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY));
assertThat(logMessageCounter.get()).isEqualTo(0); final List<ColumnFamilyHandle> cfHandles = new ArrayList<>();
logMessageCounter.set(0);
} finally { try (final RocksDB db = RocksDB.open(options,
for (ColumnFamilyHandle columnFamilyHandle : cfHandles) { dbFolder.getRoot().getAbsolutePath(),
columnFamilyHandle.dispose(); cfDescriptors, cfHandles)) {
} try {
if (db != null) { // there should be zero messages
db.close(); // using fatal level as log level.
} assertThat(logMessageCounter.get()).isEqualTo(0);
if (logger != null) { } finally {
logger.dispose(); for (final ColumnFamilyHandle columnFamilyHandle : cfHandles) {
columnFamilyHandle.close();
}
}
} }
} }
} }
@Test @Test
public void setInfoLogLevel() { public void setInfoLogLevel() {
Logger logger = null; final AtomicInteger logMessageCounter = new AtomicInteger();
try { try (final Options options = new Options().
// Setup options setInfoLogLevel(InfoLogLevel.FATAL_LEVEL).
final Options options = new Options(). setCreateIfMissing(true);
setInfoLogLevel(InfoLogLevel.FATAL_LEVEL). final Logger logger = new Logger(options) {
setCreateIfMissing(true); // Create new logger with max log level passed by options
@Override
// Create new logger with max log level passed by options protected void log(InfoLogLevel infoLogLevel, String logMsg) {
logger = new Logger(options) { assertThat(logMsg).isNotNull();
@Override assertThat(logMsg.length()).isGreaterThan(0);
protected void log(InfoLogLevel infoLogLevel, String logMsg) { logMessageCounter.incrementAndGet();
assertThat(logMsg).isNotNull(); }
assertThat(logMsg.length()).isGreaterThan(0); }
logMessageCounter.incrementAndGet(); ) {
}
};
assertThat(logger.infoLogLevel()). assertThat(logger.infoLogLevel()).
isEqualTo(InfoLogLevel.FATAL_LEVEL); isEqualTo(InfoLogLevel.FATAL_LEVEL);
logger.setInfoLogLevel(InfoLogLevel.DEBUG_LEVEL); logger.setInfoLogLevel(InfoLogLevel.DEBUG_LEVEL);
assertThat(logger.infoLogLevel()). assertThat(logger.infoLogLevel()).
isEqualTo(InfoLogLevel.DEBUG_LEVEL); isEqualTo(InfoLogLevel.DEBUG_LEVEL);
} finally {
if (logger != null) {
logger.dispose();
}
} }
} }
@Test @Test
public void changeLogLevelAtRuntime() throws RocksDBException { public void changeLogLevelAtRuntime() throws RocksDBException {
RocksDB db = null; final AtomicInteger logMessageCounter = new AtomicInteger();
logMessageCounter.set(0); try (final Options options = new Options().
setInfoLogLevel(InfoLogLevel.FATAL_LEVEL).
try { setCreateIfMissing(true);
// Setup options
final Options options = new Options(). // Create new logger with max log level passed by options
setInfoLogLevel(InfoLogLevel.FATAL_LEVEL). final Logger logger = new Logger(options) {
setCreateIfMissing(true); @Override
protected void log(InfoLogLevel infoLogLevel, String logMsg) {
// Create new logger with max log level passed by options assertThat(logMsg).isNotNull();
Logger logger = new Logger(options) { assertThat(logMsg.length()).isGreaterThan(0);
@Override logMessageCounter.incrementAndGet();
protected void log(InfoLogLevel infoLogLevel, String logMsg) { }
assertThat(logMsg).isNotNull(); }
assertThat(logMsg.length()).isGreaterThan(0); ) {
logMessageCounter.incrementAndGet();
}
};
// Set custom logger to options // Set custom logger to options
options.setLogger(logger); options.setLogger(logger);
db = RocksDB.open(options, dbFolder.getRoot().getAbsolutePath());
// there should be zero messages try (final RocksDB db = RocksDB.open(options,
// using fatal level as log level. dbFolder.getRoot().getAbsolutePath())) {
assertThat(logMessageCounter.get()).isEqualTo(0);
// change log level to debug level // there should be zero messages
logger.setInfoLogLevel(InfoLogLevel.DEBUG_LEVEL); // using fatal level as log level.
assertThat(logMessageCounter.get()).isEqualTo(0);
db.put("key".getBytes(), "value".getBytes()); // change log level to debug level
db.flush(new FlushOptions().setWaitForFlush(true)); logger.setInfoLogLevel(InfoLogLevel.DEBUG_LEVEL);
// messages shall be received due to previous actions. db.put("key".getBytes(), "value".getBytes());
assertThat(logMessageCounter.get()).isNotEqualTo(0); db.flush(new FlushOptions().setWaitForFlush(true));
} finally { // messages shall be received due to previous actions.
if (db != null) { assertThat(logMessageCounter.get()).isNotEqualTo(0);
db.close();
} }
} }
logMessageCounter.set(0);
} }
} }

@ -18,9 +18,7 @@ public class MemTableTest {
@Test @Test
public void hashSkipListMemTable() throws RocksDBException { public void hashSkipListMemTable() throws RocksDBException {
Options options = null; try(final Options options = new Options()) {
try {
options = new Options();
// Test HashSkipListMemTableConfig // Test HashSkipListMemTableConfig
HashSkipListMemTableConfig memTableConfig = HashSkipListMemTableConfig memTableConfig =
new HashSkipListMemTableConfig(); new HashSkipListMemTableConfig();
@ -40,18 +38,12 @@ public class MemTableTest {
assertThat(memTableConfig.branchingFactor()). assertThat(memTableConfig.branchingFactor()).
isEqualTo(6); isEqualTo(6);
options.setMemTableConfig(memTableConfig); options.setMemTableConfig(memTableConfig);
} finally {
if (options != null) {
options.dispose();
}
} }
} }
@Test @Test
public void skipListMemTable() throws RocksDBException { public void skipListMemTable() throws RocksDBException {
Options options = null; try(final Options options = new Options()) {
try {
options = new Options();
SkipListMemTableConfig skipMemTableConfig = SkipListMemTableConfig skipMemTableConfig =
new SkipListMemTableConfig(); new SkipListMemTableConfig();
assertThat(skipMemTableConfig.lookahead()). assertThat(skipMemTableConfig.lookahead()).
@ -60,19 +52,12 @@ public class MemTableTest {
assertThat(skipMemTableConfig.lookahead()). assertThat(skipMemTableConfig.lookahead()).
isEqualTo(20); isEqualTo(20);
options.setMemTableConfig(skipMemTableConfig); options.setMemTableConfig(skipMemTableConfig);
options.dispose();
} finally {
if (options != null) {
options.dispose();
}
} }
} }
@Test @Test
public void hashLinkedListMemTable() throws RocksDBException { public void hashLinkedListMemTable() throws RocksDBException {
Options options = null; try(final Options options = new Options()) {
try {
options = new Options();
HashLinkedListMemTableConfig hashLinkedListMemTableConfig = HashLinkedListMemTableConfig hashLinkedListMemTableConfig =
new HashLinkedListMemTableConfig(); new HashLinkedListMemTableConfig();
assertThat(hashLinkedListMemTableConfig.bucketCount()). assertThat(hashLinkedListMemTableConfig.bucketCount()).
@ -107,18 +92,12 @@ public class MemTableTest {
thresholdUseSkiplist()). thresholdUseSkiplist()).
isEqualTo(29); isEqualTo(29);
options.setMemTableConfig(hashLinkedListMemTableConfig); options.setMemTableConfig(hashLinkedListMemTableConfig);
} finally {
if (options != null) {
options.dispose();
}
} }
} }
@Test @Test
public void vectorMemTable() throws RocksDBException { public void vectorMemTable() throws RocksDBException {
Options options = null; try(final Options options = new Options()) {
try {
options = new Options();
VectorMemTableConfig vectorMemTableConfig = VectorMemTableConfig vectorMemTableConfig =
new VectorMemTableConfig(); new VectorMemTableConfig();
assertThat(vectorMemTableConfig.reservedSize()). assertThat(vectorMemTableConfig.reservedSize()).
@ -127,11 +106,6 @@ public class MemTableTest {
assertThat(vectorMemTableConfig.reservedSize()). assertThat(vectorMemTableConfig.reservedSize()).
isEqualTo(123); isEqualTo(123);
options.setMemTableConfig(vectorMemTableConfig); options.setMemTableConfig(vectorMemTableConfig);
options.dispose();
} finally {
if (options != null) {
options.dispose();
}
} }
} }
} }

@ -5,6 +5,7 @@
package org.rocksdb; package org.rocksdb;
import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.ArrayList; import java.util.ArrayList;
@ -27,78 +28,60 @@ public class MergeTest {
@Test @Test
public void stringOption() public void stringOption()
throws InterruptedException, RocksDBException { throws InterruptedException, RocksDBException {
RocksDB db = null; try (final Options opt = new Options()
Options opt = null; .setCreateIfMissing(true)
try { .setMergeOperatorName("stringappend");
String db_path_string = final RocksDB db = RocksDB.open(opt,
dbFolder.getRoot().getAbsolutePath(); dbFolder.getRoot().getAbsolutePath())) {
opt = new Options();
opt.setCreateIfMissing(true);
opt.setMergeOperatorName("stringappend");
db = RocksDB.open(opt, db_path_string);
// writing aa under key // writing aa under key
db.put("key".getBytes(), "aa".getBytes()); db.put("key".getBytes(), "aa".getBytes());
// merge bb under key // merge bb under key
db.merge("key".getBytes(), "bb".getBytes()); db.merge("key".getBytes(), "bb".getBytes());
byte[] value = db.get("key".getBytes()); final byte[] value = db.get("key".getBytes());
String strValue = new String(value); final String strValue = new String(value);
assertThat(strValue).isEqualTo("aa,bb"); assertThat(strValue).isEqualTo("aa,bb");
} finally {
if (db != null) {
db.close();
}
if (opt != null) {
opt.dispose();
}
} }
} }
@Test @Test
public void cFStringOption() public void cFStringOption()
throws InterruptedException, RocksDBException { throws InterruptedException, RocksDBException {
RocksDB db = null;
DBOptions opt = null;
List<ColumnFamilyHandle> columnFamilyHandleList =
new ArrayList<>();
try {
String db_path_string =
dbFolder.getRoot().getAbsolutePath();
opt = new DBOptions();
opt.setCreateIfMissing(true);
opt.setCreateMissingColumnFamilies(true);
List<ColumnFamilyDescriptor> cfDescriptors = try (final ColumnFamilyOptions cfOpt1 = new ColumnFamilyOptions()
new ArrayList<>(); .setMergeOperatorName("stringappend");
cfDescriptors.add(new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY, final ColumnFamilyOptions cfOpt2 = new ColumnFamilyOptions()
new ColumnFamilyOptions().setMergeOperatorName( .setMergeOperatorName("stringappend")
"stringappend"))); ) {
cfDescriptors.add(new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY, final List<ColumnFamilyDescriptor> cfDescriptors = Arrays.asList(
new ColumnFamilyOptions().setMergeOperatorName( new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY, cfOpt1),
"stringappend"))); new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY, cfOpt2)
db = RocksDB.open(opt, db_path_string, );
cfDescriptors, columnFamilyHandleList);
final List<ColumnFamilyHandle> columnFamilyHandleList = new ArrayList<>();
// writing aa under key try (final DBOptions opt = new DBOptions()
db.put(columnFamilyHandleList.get(1), .setCreateIfMissing(true)
"cfkey".getBytes(), "aa".getBytes()); .setCreateMissingColumnFamilies(true);
// merge bb under key final RocksDB db = RocksDB.open(opt,
db.merge(columnFamilyHandleList.get(1), dbFolder.getRoot().getAbsolutePath(), cfDescriptors,
"cfkey".getBytes(), "bb".getBytes()); columnFamilyHandleList)) {
try {
byte[] value = db.get(columnFamilyHandleList.get(1), "cfkey".getBytes()); // writing aa under key
String strValue = new String(value); db.put(columnFamilyHandleList.get(1),
assertThat(strValue).isEqualTo("aa,bb"); "cfkey".getBytes(), "aa".getBytes());
} finally { // merge bb under key
for (ColumnFamilyHandle handle : columnFamilyHandleList) { db.merge(columnFamilyHandleList.get(1),
handle.dispose(); "cfkey".getBytes(), "bb".getBytes());
}
if (db != null) { byte[] value = db.get(columnFamilyHandleList.get(1),
db.close(); "cfkey".getBytes());
} String strValue = new String(value);
if (opt != null) { assertThat(strValue).isEqualTo("aa,bb");
opt.dispose(); } finally {
for (final ColumnFamilyHandle handle : columnFamilyHandleList) {
handle.close();
}
}
} }
} }
} }
@ -106,99 +89,85 @@ public class MergeTest {
@Test @Test
public void operatorOption() public void operatorOption()
throws InterruptedException, RocksDBException { throws InterruptedException, RocksDBException {
RocksDB db = null; final StringAppendOperator stringAppendOperator =
Options opt = null; new StringAppendOperator();
try { try (final Options opt = new Options()
String db_path_string = .setCreateIfMissing(true)
dbFolder.getRoot().getAbsolutePath(); .setMergeOperator(stringAppendOperator);
opt = new Options(); final RocksDB db = RocksDB.open(opt,
opt.setCreateIfMissing(true); dbFolder.getRoot().getAbsolutePath())) {
StringAppendOperator stringAppendOperator = new StringAppendOperator();
opt.setMergeOperator(stringAppendOperator);
db = RocksDB.open(opt, db_path_string);
// Writing aa under key // Writing aa under key
db.put("key".getBytes(), "aa".getBytes()); db.put("key".getBytes(), "aa".getBytes());
// Writing bb under key // Writing bb under key
db.merge("key".getBytes(), "bb".getBytes()); db.merge("key".getBytes(), "bb".getBytes());
byte[] value = db.get("key".getBytes()); final byte[] value = db.get("key".getBytes());
String strValue = new String(value); final String strValue = new String(value);
assertThat(strValue).isEqualTo("aa,bb"); assertThat(strValue).isEqualTo("aa,bb");
} finally {
if (db != null) {
db.close();
}
if (opt != null) {
opt.dispose();
}
} }
} }
@Test @Test
public void cFOperatorOption() public void cFOperatorOption()
throws InterruptedException, RocksDBException { throws InterruptedException, RocksDBException {
RocksDB db = null; final StringAppendOperator stringAppendOperator =
DBOptions opt = null; new StringAppendOperator();
ColumnFamilyHandle cfHandle = null; try (final ColumnFamilyOptions cfOpt1 = new ColumnFamilyOptions()
List<ColumnFamilyDescriptor> cfDescriptors = .setMergeOperator(stringAppendOperator);
new ArrayList<>(); final ColumnFamilyOptions cfOpt2 = new ColumnFamilyOptions()
List<ColumnFamilyHandle> columnFamilyHandleList = .setMergeOperator(stringAppendOperator)
new ArrayList<>(); ) {
try { final List<ColumnFamilyDescriptor> cfDescriptors = Arrays.asList(
String db_path_string = new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY, cfOpt1),
dbFolder.getRoot().getAbsolutePath(); new ColumnFamilyDescriptor("new_cf".getBytes(), cfOpt2)
opt = new DBOptions(); );
opt.setCreateIfMissing(true); final List<ColumnFamilyHandle> columnFamilyHandleList = new ArrayList<>();
opt.setCreateMissingColumnFamilies(true); try (final DBOptions opt = new DBOptions()
StringAppendOperator stringAppendOperator = new StringAppendOperator(); .setCreateIfMissing(true)
.setCreateMissingColumnFamilies(true);
cfDescriptors.add(new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY, final RocksDB db = RocksDB.open(opt,
new ColumnFamilyOptions().setMergeOperator( dbFolder.getRoot().getAbsolutePath(), cfDescriptors,
stringAppendOperator))); columnFamilyHandleList)
cfDescriptors.add(new ColumnFamilyDescriptor("new_cf".getBytes(), ) {
new ColumnFamilyOptions().setMergeOperator( try {
stringAppendOperator))); // writing aa under key
db = RocksDB.open(opt, db_path_string, db.put(columnFamilyHandleList.get(1),
cfDescriptors, columnFamilyHandleList); "cfkey".getBytes(), "aa".getBytes());
// merge bb under key
// writing aa under key db.merge(columnFamilyHandleList.get(1),
db.put(columnFamilyHandleList.get(1), "cfkey".getBytes(), "bb".getBytes());
"cfkey".getBytes(), "aa".getBytes()); byte[] value = db.get(columnFamilyHandleList.get(1),
// merge bb under key "cfkey".getBytes());
db.merge(columnFamilyHandleList.get(1), String strValue = new String(value);
"cfkey".getBytes(), "bb".getBytes());
byte[] value = db.get(columnFamilyHandleList.get(1), "cfkey".getBytes()); // Test also with createColumnFamily
String strValue = new String(value); try (final ColumnFamilyOptions cfHandleOpts =
new ColumnFamilyOptions()
// Test also with createColumnFamily .setMergeOperator(stringAppendOperator);
cfHandle = db.createColumnFamily( final ColumnFamilyHandle cfHandle =
new ColumnFamilyDescriptor("new_cf2".getBytes(), db.createColumnFamily(
new ColumnFamilyOptions().setMergeOperator(stringAppendOperator))); new ColumnFamilyDescriptor("new_cf2".getBytes(),
// writing xx under cfkey2 cfHandleOpts))
db.put(cfHandle, "cfkey2".getBytes(), "xx".getBytes()); ) {
// merge yy under cfkey2 // writing xx under cfkey2
db.merge(cfHandle, new WriteOptions(), "cfkey2".getBytes(), "yy".getBytes()); db.put(cfHandle, "cfkey2".getBytes(), "xx".getBytes());
value = db.get(cfHandle, "cfkey2".getBytes()); // merge yy under cfkey2
String strValueTmpCf = new String(value); db.merge(cfHandle, new WriteOptions(), "cfkey2".getBytes(),
"yy".getBytes());
assertThat(strValue).isEqualTo("aa,bb"); value = db.get(cfHandle, "cfkey2".getBytes());
assertThat(strValueTmpCf).isEqualTo("xx,yy"); String strValueTmpCf = new String(value);
} finally {
for (ColumnFamilyHandle columnFamilyHandle : columnFamilyHandleList) { assertThat(strValue).isEqualTo("aa,bb");
columnFamilyHandle.dispose(); assertThat(strValueTmpCf).isEqualTo("xx,yy");
} }
if (cfHandle != null) { } finally {
cfHandle.dispose(); for (final ColumnFamilyHandle columnFamilyHandle :
} columnFamilyHandleList) {
if (db != null) { columnFamilyHandle.close();
db.close(); }
} }
if (opt != null) {
opt.dispose();
} }
} }
} }
@ -206,97 +175,67 @@ public class MergeTest {
@Test @Test
public void operatorGcBehaviour() public void operatorGcBehaviour()
throws RocksDBException { throws RocksDBException {
Options opt = null; final StringAppendOperator stringAppendOperator
RocksDB db = null; = new StringAppendOperator();
try { try (final Options opt = new Options()
String db_path_string = .setCreateIfMissing(true)
dbFolder.getRoot().getAbsolutePath(); .setMergeOperator(stringAppendOperator);
opt = new Options(); final RocksDB db = RocksDB.open(opt,
opt.setCreateIfMissing(true); dbFolder.getRoot().getAbsolutePath())) {
StringAppendOperator stringAppendOperator = new StringAppendOperator(); //no-op
opt.setMergeOperator(stringAppendOperator); }
db = RocksDB.open(opt, db_path_string);
db.close(); // test reuse
opt.dispose(); try (final Options opt = new Options()
System.gc(); .setMergeOperator(stringAppendOperator);
System.runFinalization(); final RocksDB db = RocksDB.open(opt,
// test reuse dbFolder.getRoot().getAbsolutePath())) {
opt = new Options(); //no-op
opt.setMergeOperator(stringAppendOperator); }
db = RocksDB.open(opt, db_path_string);
db.close(); // test param init
opt.dispose(); try (final Options opt = new Options()
System.gc(); .setMergeOperator(new StringAppendOperator());
System.runFinalization(); final RocksDB db = RocksDB.open(opt,
// test param init dbFolder.getRoot().getAbsolutePath())) {
opt = new Options(); //no-op
opt.setMergeOperator(new StringAppendOperator()); }
db = RocksDB.open(opt, db_path_string);
db.close(); // test replace one with another merge operator instance
opt.dispose(); try (final Options opt = new Options()
System.gc(); .setMergeOperator(stringAppendOperator)) {
System.runFinalization(); final StringAppendOperator newStringAppendOperator
// test replace one with another merge operator instance = new StringAppendOperator();
opt = new Options();
opt.setMergeOperator(stringAppendOperator);
StringAppendOperator newStringAppendOperator = new StringAppendOperator();
opt.setMergeOperator(newStringAppendOperator); opt.setMergeOperator(newStringAppendOperator);
db = RocksDB.open(opt, db_path_string); try (final RocksDB db = RocksDB.open(opt,
db.close(); dbFolder.getRoot().getAbsolutePath())) {
opt.dispose(); //no-op
} finally {
if (db != null) {
db.close();
}
if (opt != null) {
opt.dispose();
} }
} }
} }
@Test @Test
public void emptyStringInSetMergeOperatorByName() { public void emptyStringInSetMergeOperatorByName() {
Options opt = null; try (final Options opt = new Options()
ColumnFamilyOptions cOpt = null; .setMergeOperatorName("");
try { final ColumnFamilyOptions cOpt = new ColumnFamilyOptions()
opt = new Options(); .setMergeOperatorName("")) {
cOpt = new ColumnFamilyOptions(); //no-op
opt.setMergeOperatorName("");
cOpt.setMergeOperatorName("");
} finally {
if (opt != null) {
opt.dispose();
}
if (cOpt != null) {
cOpt.dispose();
}
} }
} }
@Test(expected = IllegalArgumentException.class) @Test(expected = IllegalArgumentException.class)
public void nullStringInSetMergeOperatorByNameOptions() { public void nullStringInSetMergeOperatorByNameOptions() {
Options opt = null; try (final Options opt = new Options()) {
try {
opt = new Options();
opt.setMergeOperatorName(null); opt.setMergeOperatorName(null);
} finally {
if (opt != null) {
opt.dispose();
}
} }
} }
@Test(expected = IllegalArgumentException.class) @Test(expected = IllegalArgumentException.class)
public void public void
nullStringInSetMergeOperatorByNameColumnFamilyOptions() { nullStringInSetMergeOperatorByNameColumnFamilyOptions() {
ColumnFamilyOptions opt = null; try (final ColumnFamilyOptions opt = new ColumnFamilyOptions()) {
try {
opt = new ColumnFamilyOptions();
opt.setMergeOperatorName(null); opt.setMergeOperatorName(null);
} finally {
if (opt != null) {
opt.dispose();
}
} }
} }
} }

@ -19,38 +19,37 @@ public class MixedOptionsTest {
@Test @Test
public void mixedOptionsTest(){ public void mixedOptionsTest(){
// Set a table factory and check the names // Set a table factory and check the names
ColumnFamilyOptions cfOptions = new ColumnFamilyOptions(); try(final Filter bloomFilter = new BloomFilter();
cfOptions.setTableFormatConfig(new BlockBasedTableConfig(). final ColumnFamilyOptions cfOptions = new ColumnFamilyOptions()
setFilter(new BloomFilter())); .setTableFormatConfig(
assertThat(cfOptions.tableFactoryName()).isEqualTo( new BlockBasedTableConfig().setFilter(bloomFilter))
"BlockBasedTable"); ) {
cfOptions.setTableFormatConfig(new PlainTableConfig()); assertThat(cfOptions.tableFactoryName()).isEqualTo(
assertThat(cfOptions.tableFactoryName()).isEqualTo("PlainTable"); "BlockBasedTable");
// Initialize a dbOptions object from cf options and cfOptions.setTableFormatConfig(new PlainTableConfig());
// db options assertThat(cfOptions.tableFactoryName()).isEqualTo("PlainTable");
DBOptions dbOptions = new DBOptions(); // Initialize a dbOptions object from cf options and
Options options = new Options(dbOptions, cfOptions); // db options
assertThat(options.tableFactoryName()).isEqualTo("PlainTable"); try (final DBOptions dbOptions = new DBOptions();
// Free instances final Options options = new Options(dbOptions, cfOptions)) {
options.dispose(); assertThat(options.tableFactoryName()).isEqualTo("PlainTable");
options = null; // Free instances
cfOptions.dispose(); }
cfOptions = null; }
dbOptions.dispose();
dbOptions = null;
System.gc();
System.runFinalization();
// Test Optimize for statements // Test Optimize for statements
cfOptions = new ColumnFamilyOptions(); try(final ColumnFamilyOptions cfOptions = new ColumnFamilyOptions()) {
cfOptions.optimizeUniversalStyleCompaction(); cfOptions.optimizeUniversalStyleCompaction();
cfOptions.optimizeLevelStyleCompaction(); cfOptions.optimizeLevelStyleCompaction();
cfOptions.optimizeForPointLookup(1024); cfOptions.optimizeForPointLookup(1024);
options = new Options(); try(final Options options = new Options()) {
options.optimizeLevelStyleCompaction(); options.optimizeLevelStyleCompaction();
options.optimizeLevelStyleCompaction(400); options.optimizeLevelStyleCompaction(400);
options.optimizeUniversalStyleCompaction(); options.optimizeUniversalStyleCompaction();
options.optimizeUniversalStyleCompaction(400); options.optimizeUniversalStyleCompaction(400);
options.optimizeForPointLookup(1024); options.optimizeForPointLookup(1024);
options.prepareForBulkLoad(); options.prepareForBulkLoad();
}
}
} }
} }

@ -23,7 +23,7 @@ public class NativeLibraryLoaderTest {
public void tempFolder() throws IOException { public void tempFolder() throws IOException {
NativeLibraryLoader.getInstance().loadLibraryFromJarToTemp( NativeLibraryLoader.getInstance().loadLibraryFromJarToTemp(
temporaryFolder.getRoot().getAbsolutePath()); temporaryFolder.getRoot().getAbsolutePath());
Path path = Paths.get(temporaryFolder.getRoot().getAbsolutePath(), final Path path = Paths.get(temporaryFolder.getRoot().getAbsolutePath(),
Environment.getJniLibraryFileName("rocksdb")); Environment.getJniLibraryFileName("rocksdb"));
assertThat(Files.exists(path)).isTrue(); assertThat(Files.exists(path)).isTrue();
assertThat(Files.isReadable(path)).isTrue(); assertThat(Files.isReadable(path)).isTrue();

File diff suppressed because it is too large Load Diff

@ -80,16 +80,10 @@ public class PlainTableConfigTest {
@Test @Test
public void plainTableConfig() { public void plainTableConfig() {
Options opt = null; try(final Options opt = new Options()) {
try { final PlainTableConfig plainTableConfig = new PlainTableConfig();
opt = new Options();
PlainTableConfig plainTableConfig = new PlainTableConfig();
opt.setTableFormatConfig(plainTableConfig); opt.setTableFormatConfig(plainTableConfig);
assertThat(opt.tableFactoryName()).isEqualTo("PlainTable"); assertThat(opt.tableFactoryName()).isEqualTo("PlainTable");
} finally {
if (opt != null) {
opt.dispose();
}
} }
} }
} }

@ -18,7 +18,7 @@ public class PlatformRandomHelper {
* @return boolean value indicating if operating system is 64 Bit. * @return boolean value indicating if operating system is 64 Bit.
*/ */
public static boolean isOs64Bit(){ public static boolean isOs64Bit(){
boolean is64Bit; final boolean is64Bit;
if (System.getProperty("os.name").contains("Windows")) { if (System.getProperty("os.name").contains("Windows")) {
is64Bit = (System.getenv("ProgramFiles(x86)") != null); is64Bit = (System.getenv("ProgramFiles(x86)") != null);
} else { } else {

@ -10,6 +10,7 @@ import org.junit.Test;
import org.junit.rules.TemporaryFolder; import org.junit.rules.TemporaryFolder;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays;
import java.util.List; import java.util.List;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
@ -25,340 +26,279 @@ public class ReadOnlyTest {
@Test @Test
public void readOnlyOpen() throws RocksDBException { public void readOnlyOpen() throws RocksDBException {
RocksDB db = null; try (final Options options = new Options()
RocksDB db2 = null; .setCreateIfMissing(true);
RocksDB db3 = null; final RocksDB db = RocksDB.open(options,
Options options = null; dbFolder.getRoot().getAbsolutePath())) {
List<ColumnFamilyHandle> columnFamilyHandleList =
new ArrayList<>();
List<ColumnFamilyHandle> readOnlyColumnFamilyHandleList =
new ArrayList<>();
List<ColumnFamilyHandle> readOnlyColumnFamilyHandleList2 =
new ArrayList<>();
try {
options = new Options();
options.setCreateIfMissing(true);
db = RocksDB.open(options,
dbFolder.getRoot().getAbsolutePath());
db.put("key".getBytes(), "value".getBytes()); db.put("key".getBytes(), "value".getBytes());
db2 = RocksDB.openReadOnly( try (final RocksDB db2 = RocksDB.openReadOnly(
dbFolder.getRoot().getAbsolutePath()); dbFolder.getRoot().getAbsolutePath())) {
assertThat("value"). assertThat("value").
isEqualTo(new String(db2.get("key".getBytes()))); isEqualTo(new String(db2.get("key".getBytes())));
db.close();
db2.close();
List<ColumnFamilyDescriptor> cfDescriptors = new ArrayList<>();
cfDescriptors.add(
new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY,
new ColumnFamilyOptions()));
db = RocksDB.open(
dbFolder.getRoot().getAbsolutePath(), cfDescriptors, columnFamilyHandleList);
columnFamilyHandleList.add(db.createColumnFamily(
new ColumnFamilyDescriptor("new_cf".getBytes(), new ColumnFamilyOptions())));
columnFamilyHandleList.add(db.createColumnFamily(
new ColumnFamilyDescriptor("new_cf2".getBytes(), new ColumnFamilyOptions())));
db.put(columnFamilyHandleList.get(2), "key2".getBytes(),
"value2".getBytes());
db2 = RocksDB.openReadOnly(
dbFolder.getRoot().getAbsolutePath(), cfDescriptors,
readOnlyColumnFamilyHandleList);
assertThat(db2.get("key2".getBytes())).isNull();
assertThat(db2.get(readOnlyColumnFamilyHandleList.get(0), "key2".getBytes())).
isNull();
cfDescriptors.clear();
cfDescriptors.add(
new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY,
new ColumnFamilyOptions()));
cfDescriptors.add(
new ColumnFamilyDescriptor("new_cf2".getBytes(), new ColumnFamilyOptions()));
db3 = RocksDB.openReadOnly(
dbFolder.getRoot().getAbsolutePath(), cfDescriptors, readOnlyColumnFamilyHandleList2);
assertThat(new String(db3.get(readOnlyColumnFamilyHandleList2.get(1),
"key2".getBytes()))).isEqualTo("value2");
} finally {
for (ColumnFamilyHandle columnFamilyHandle : columnFamilyHandleList) {
columnFamilyHandle.dispose();
}
if (db != null) {
db.close();
}
for (ColumnFamilyHandle columnFamilyHandle : readOnlyColumnFamilyHandleList) {
columnFamilyHandle.dispose();
} }
if (db2 != null) { }
db2.close();
} try (final ColumnFamilyOptions cfOpts = new ColumnFamilyOptions()) {
for (ColumnFamilyHandle columnFamilyHandle : readOnlyColumnFamilyHandleList2) { final List<ColumnFamilyDescriptor> cfDescriptors = new ArrayList<>();
columnFamilyHandle.dispose(); cfDescriptors.add(new ColumnFamilyDescriptor(
} RocksDB.DEFAULT_COLUMN_FAMILY, cfOpts));
if (db3 != null) {
db3.close(); final List<ColumnFamilyHandle> columnFamilyHandleList = new ArrayList<>();
} try (final RocksDB db = RocksDB.open(dbFolder.getRoot().getAbsolutePath(),
if (options != null) { cfDescriptors, columnFamilyHandleList)) {
options.dispose(); try (final ColumnFamilyOptions newCfOpts = new ColumnFamilyOptions();
final ColumnFamilyOptions newCf2Opts = new ColumnFamilyOptions()
) {
columnFamilyHandleList.add(db.createColumnFamily(
new ColumnFamilyDescriptor("new_cf".getBytes(), newCfOpts)));
columnFamilyHandleList.add(db.createColumnFamily(
new ColumnFamilyDescriptor("new_cf2".getBytes(), newCf2Opts)));
db.put(columnFamilyHandleList.get(2), "key2".getBytes(),
"value2".getBytes());
final List<ColumnFamilyHandle> readOnlyColumnFamilyHandleList =
new ArrayList<>();
try (final RocksDB db2 = RocksDB.openReadOnly(
dbFolder.getRoot().getAbsolutePath(), cfDescriptors,
readOnlyColumnFamilyHandleList)) {
try (final ColumnFamilyOptions newCfOpts2 =
new ColumnFamilyOptions();
final ColumnFamilyOptions newCf2Opts2 =
new ColumnFamilyOptions()
) {
assertThat(db2.get("key2".getBytes())).isNull();
assertThat(db2.get(readOnlyColumnFamilyHandleList.get(0),
"key2".getBytes())).
isNull();
cfDescriptors.clear();
cfDescriptors.add(
new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY,
newCfOpts2));
cfDescriptors.add(new ColumnFamilyDescriptor("new_cf2".getBytes(),
newCf2Opts2));
final List<ColumnFamilyHandle> readOnlyColumnFamilyHandleList2
= new ArrayList<>();
try (final RocksDB db3 = RocksDB.openReadOnly(
dbFolder.getRoot().getAbsolutePath(), cfDescriptors,
readOnlyColumnFamilyHandleList2)) {
try {
assertThat(new String(db3.get(
readOnlyColumnFamilyHandleList2.get(1),
"key2".getBytes()))).isEqualTo("value2");
} finally {
for (final ColumnFamilyHandle columnFamilyHandle :
readOnlyColumnFamilyHandleList2) {
columnFamilyHandle.close();
}
}
}
} finally {
for (final ColumnFamilyHandle columnFamilyHandle :
readOnlyColumnFamilyHandleList) {
columnFamilyHandle.close();
}
}
}
} finally {
for (final ColumnFamilyHandle columnFamilyHandle :
columnFamilyHandleList) {
columnFamilyHandle.close();
}
}
} }
} }
} }
@Test(expected = RocksDBException.class) @Test(expected = RocksDBException.class)
public void failToWriteInReadOnly() throws RocksDBException { public void failToWriteInReadOnly() throws RocksDBException {
RocksDB db = null; try (final Options options = new Options()
RocksDB rDb = null; .setCreateIfMissing(true)) {
Options options = null;
List<ColumnFamilyDescriptor> cfDescriptors = new ArrayList<>();
List<ColumnFamilyHandle> readOnlyColumnFamilyHandleList =
new ArrayList<>();
try {
cfDescriptors.add( try (final RocksDB db = RocksDB.open(options,
new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY, dbFolder.getRoot().getAbsolutePath())) {
new ColumnFamilyOptions())); //no-op
}
}
options = new Options(); try (final ColumnFamilyOptions cfOpts = new ColumnFamilyOptions()) {
options.setCreateIfMissing(true); final List<ColumnFamilyDescriptor> cfDescriptors = Arrays.asList(
new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY, cfOpts)
);
db = RocksDB.open(options, final List<ColumnFamilyHandle> readOnlyColumnFamilyHandleList =
dbFolder.getRoot().getAbsolutePath()); new ArrayList<>();
db.close(); try (final RocksDB rDb = RocksDB.openReadOnly(
rDb = RocksDB.openReadOnly(
dbFolder.getRoot().getAbsolutePath(), cfDescriptors, dbFolder.getRoot().getAbsolutePath(), cfDescriptors,
readOnlyColumnFamilyHandleList); readOnlyColumnFamilyHandleList)) {
try {
// test that put fails in readonly mode // test that put fails in readonly mode
rDb.put("key".getBytes(), "value".getBytes()); rDb.put("key".getBytes(), "value".getBytes());
} finally { } finally {
for (ColumnFamilyHandle columnFamilyHandle : readOnlyColumnFamilyHandleList) { for (final ColumnFamilyHandle columnFamilyHandle :
columnFamilyHandle.dispose(); readOnlyColumnFamilyHandleList) {
} columnFamilyHandle.close();
if (db != null) { }
db.close(); }
}
if (rDb != null) {
rDb.close();
}
if (options != null) {
options.dispose();
} }
} }
} }
@Test(expected = RocksDBException.class) @Test(expected = RocksDBException.class)
public void failToCFWriteInReadOnly() throws RocksDBException { public void failToCFWriteInReadOnly() throws RocksDBException {
RocksDB db = null; try (final Options options = new Options().setCreateIfMissing(true);
RocksDB rDb = null; final RocksDB db = RocksDB.open(options,
Options options = null; dbFolder.getRoot().getAbsolutePath())) {
List<ColumnFamilyDescriptor> cfDescriptors = new ArrayList<>(); //no-op
List<ColumnFamilyHandle> readOnlyColumnFamilyHandleList = }
new ArrayList<>();
try {
cfDescriptors.add(
new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY,
new ColumnFamilyOptions()));
options = new Options();
options.setCreateIfMissing(true);
db = RocksDB.open(options, try (final ColumnFamilyOptions cfOpts = new ColumnFamilyOptions()) {
dbFolder.getRoot().getAbsolutePath()); final List<ColumnFamilyDescriptor> cfDescriptors = Arrays.asList(
db.close(); new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY, cfOpts)
rDb = RocksDB.openReadOnly( );
final List<ColumnFamilyHandle> readOnlyColumnFamilyHandleList =
new ArrayList<>();
try (final RocksDB rDb = RocksDB.openReadOnly(
dbFolder.getRoot().getAbsolutePath(), cfDescriptors, dbFolder.getRoot().getAbsolutePath(), cfDescriptors,
readOnlyColumnFamilyHandleList); readOnlyColumnFamilyHandleList)) {
try {
rDb.put(readOnlyColumnFamilyHandleList.get(0), rDb.put(readOnlyColumnFamilyHandleList.get(0),
"key".getBytes(), "value".getBytes()); "key".getBytes(), "value".getBytes());
} finally { } finally {
for (ColumnFamilyHandle columnFamilyHandle : readOnlyColumnFamilyHandleList) { for (final ColumnFamilyHandle columnFamilyHandle :
columnFamilyHandle.dispose(); readOnlyColumnFamilyHandleList) {
} columnFamilyHandle.close();
if (db != null) { }
db.close(); }
}
if (rDb != null) {
rDb.close();
}
if (options != null) {
options.dispose();
} }
} }
} }
@Test(expected = RocksDBException.class) @Test(expected = RocksDBException.class)
public void failToRemoveInReadOnly() throws RocksDBException { public void failToRemoveInReadOnly() throws RocksDBException {
RocksDB db = null; try (final Options options = new Options().setCreateIfMissing(true);
RocksDB rDb = null; final RocksDB db = RocksDB.open(options,
Options options = null; dbFolder.getRoot().getAbsolutePath())) {
List<ColumnFamilyDescriptor> cfDescriptors = new ArrayList<>(); //no-op
List<ColumnFamilyHandle> readOnlyColumnFamilyHandleList = }
new ArrayList<>();
try {
cfDescriptors.add(
new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY,
new ColumnFamilyOptions()));
options = new Options(); try (final ColumnFamilyOptions cfOpts = new ColumnFamilyOptions()) {
options.setCreateIfMissing(true); final List<ColumnFamilyDescriptor> cfDescriptors = Arrays.asList(
new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY, cfOpts)
);
db = RocksDB.open(options, final List<ColumnFamilyHandle> readOnlyColumnFamilyHandleList =
dbFolder.getRoot().getAbsolutePath()); new ArrayList<>();
db.close();
rDb = RocksDB.openReadOnly(
dbFolder.getRoot().getAbsolutePath(), cfDescriptors,
readOnlyColumnFamilyHandleList);
rDb.remove("key".getBytes()); try (final RocksDB rDb = RocksDB.openReadOnly(
} finally { dbFolder.getRoot().getAbsolutePath(), cfDescriptors,
for (ColumnFamilyHandle columnFamilyHandle : readOnlyColumnFamilyHandleList) { readOnlyColumnFamilyHandleList)) {
columnFamilyHandle.dispose(); try {
} rDb.remove("key".getBytes());
if (db != null) { } finally {
db.close(); for (final ColumnFamilyHandle columnFamilyHandle :
} readOnlyColumnFamilyHandleList) {
if (rDb != null) { columnFamilyHandle.close();
rDb.close(); }
} }
if (options != null) {
options.dispose();
} }
} }
} }
@Test(expected = RocksDBException.class) @Test(expected = RocksDBException.class)
public void failToCFRemoveInReadOnly() throws RocksDBException { public void failToCFRemoveInReadOnly() throws RocksDBException {
RocksDB db = null; try (final Options options = new Options().setCreateIfMissing(true);
RocksDB rDb = null; final RocksDB db = RocksDB.open(options,
Options options = null; dbFolder.getRoot().getAbsolutePath())) {
List<ColumnFamilyDescriptor> cfDescriptors = new ArrayList<>(); //no-op
List<ColumnFamilyHandle> readOnlyColumnFamilyHandleList = }
new ArrayList<>();
try {
cfDescriptors.add(
new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY,
new ColumnFamilyOptions()));
options = new Options();
options.setCreateIfMissing(true);
db = RocksDB.open(options, try (final ColumnFamilyOptions cfOpts = new ColumnFamilyOptions()) {
dbFolder.getRoot().getAbsolutePath()); final List<ColumnFamilyDescriptor> cfDescriptors = Arrays.asList(
db.close(); new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY, cfOpts)
);
rDb = RocksDB.openReadOnly( final List<ColumnFamilyHandle> readOnlyColumnFamilyHandleList =
new ArrayList<>();
try (final RocksDB rDb = RocksDB.openReadOnly(
dbFolder.getRoot().getAbsolutePath(), cfDescriptors, dbFolder.getRoot().getAbsolutePath(), cfDescriptors,
readOnlyColumnFamilyHandleList); readOnlyColumnFamilyHandleList)) {
try {
rDb.remove(readOnlyColumnFamilyHandleList.get(0), rDb.remove(readOnlyColumnFamilyHandleList.get(0),
"key".getBytes()); "key".getBytes());
} finally { } finally {
for (ColumnFamilyHandle columnFamilyHandle : readOnlyColumnFamilyHandleList) { for (final ColumnFamilyHandle columnFamilyHandle :
columnFamilyHandle.dispose(); readOnlyColumnFamilyHandleList) {
} columnFamilyHandle.close();
if (db != null) { }
db.close(); }
}
if (rDb != null) {
rDb.close();
}
if (options != null) {
options.dispose();
} }
} }
} }
@Test(expected = RocksDBException.class) @Test(expected = RocksDBException.class)
public void failToWriteBatchReadOnly() throws RocksDBException { public void failToWriteBatchReadOnly() throws RocksDBException {
RocksDB db = null; try (final Options options = new Options().setCreateIfMissing(true);
RocksDB rDb = null; final RocksDB db = RocksDB.open(options,
Options options = null; dbFolder.getRoot().getAbsolutePath())) {
List<ColumnFamilyDescriptor> cfDescriptors = new ArrayList<>(); //no-op
List<ColumnFamilyHandle> readOnlyColumnFamilyHandleList = }
new ArrayList<>();
try {
cfDescriptors.add(
new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY,
new ColumnFamilyOptions()));
options = new Options();
options.setCreateIfMissing(true);
db = RocksDB.open(options, try (final ColumnFamilyOptions cfOpts = new ColumnFamilyOptions()) {
dbFolder.getRoot().getAbsolutePath()); final List<ColumnFamilyDescriptor> cfDescriptors = Arrays.asList(
db.close(); new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY, cfOpts)
);
rDb = RocksDB.openReadOnly( final List<ColumnFamilyHandle> readOnlyColumnFamilyHandleList =
new ArrayList<>();
try (final RocksDB rDb = RocksDB.openReadOnly(
dbFolder.getRoot().getAbsolutePath(), cfDescriptors, dbFolder.getRoot().getAbsolutePath(), cfDescriptors,
readOnlyColumnFamilyHandleList); readOnlyColumnFamilyHandleList);
final WriteBatch wb = new WriteBatch();
WriteBatch wb = new WriteBatch(); final WriteOptions wOpts = new WriteOptions()) {
wb.put("key".getBytes(), "value".getBytes()); try {
rDb.write(new WriteOptions(), wb); wb.put("key".getBytes(), "value".getBytes());
} finally { rDb.write(wOpts, wb);
for (ColumnFamilyHandle columnFamilyHandle : readOnlyColumnFamilyHandleList) { } finally {
columnFamilyHandle.dispose(); for (final ColumnFamilyHandle columnFamilyHandle :
} readOnlyColumnFamilyHandleList) {
if (db != null) { columnFamilyHandle.close();
db.close(); }
} }
if (rDb != null) {
rDb.close();
}
if (options != null) {
options.dispose();
} }
} }
} }
@Test(expected = RocksDBException.class) @Test(expected = RocksDBException.class)
public void failToCFWriteBatchReadOnly() throws RocksDBException { public void failToCFWriteBatchReadOnly() throws RocksDBException {
RocksDB db = null; try (final Options options = new Options().setCreateIfMissing(true);
RocksDB rDb = null; final RocksDB db = RocksDB.open(options,
Options options = null; dbFolder.getRoot().getAbsolutePath())) {
WriteBatch wb = null; //no-op
List<ColumnFamilyDescriptor> cfDescriptors = new ArrayList<>(); }
List<ColumnFamilyHandle> readOnlyColumnFamilyHandleList =
new ArrayList<>();
try {
cfDescriptors.add(
new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY,
new ColumnFamilyOptions()));
options = new Options();
options.setCreateIfMissing(true);
db = RocksDB.open(options, try (final ColumnFamilyOptions cfOpts = new ColumnFamilyOptions()) {
dbFolder.getRoot().getAbsolutePath()); final List<ColumnFamilyDescriptor> cfDescriptors = Arrays.asList(
db.close(); new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY, cfOpts)
);
rDb = RocksDB.openReadOnly( final List<ColumnFamilyHandle> readOnlyColumnFamilyHandleList =
new ArrayList<>();
try (final RocksDB rDb = RocksDB.openReadOnly(
dbFolder.getRoot().getAbsolutePath(), cfDescriptors, dbFolder.getRoot().getAbsolutePath(), cfDescriptors,
readOnlyColumnFamilyHandleList); readOnlyColumnFamilyHandleList);
final WriteBatch wb = new WriteBatch();
wb = new WriteBatch(); final WriteOptions wOpts = new WriteOptions()) {
wb.put(readOnlyColumnFamilyHandleList.get(0), try {
"key".getBytes(), "value".getBytes()); wb.put(readOnlyColumnFamilyHandleList.get(0), "key".getBytes(),
rDb.write(new WriteOptions(), wb); "value".getBytes());
} finally { rDb.write(wOpts, wb);
for (ColumnFamilyHandle columnFamilyHandle : readOnlyColumnFamilyHandleList) { } finally {
columnFamilyHandle.dispose(); for (final ColumnFamilyHandle columnFamilyHandle :
} readOnlyColumnFamilyHandleList) {
if (db != null) { columnFamilyHandle.close();
db.close(); }
} }
if (rDb != null) {
rDb.close();
}
if (options != null) {
options.dispose();
}
if (wb != null) {
wb.dispose();
} }
} }
} }

@ -24,127 +24,111 @@ public class ReadOptionsTest {
public ExpectedException exception = ExpectedException.none(); public ExpectedException exception = ExpectedException.none();
@Test @Test
public void verifyChecksum(){ public void verifyChecksum() {
ReadOptions opt = null; try (final ReadOptions opt = new ReadOptions()) {
try { final Random rand = new Random();
opt = new ReadOptions(); final boolean boolValue = rand.nextBoolean();
Random rand = new Random();
boolean boolValue = rand.nextBoolean();
opt.setVerifyChecksums(boolValue); opt.setVerifyChecksums(boolValue);
assertThat(opt.verifyChecksums()).isEqualTo(boolValue); assertThat(opt.verifyChecksums()).isEqualTo(boolValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
} }
@Test @Test
public void fillCache(){ public void fillCache() {
ReadOptions opt = null; try (final ReadOptions opt = new ReadOptions()) {
try { final Random rand = new Random();
opt = new ReadOptions(); final boolean boolValue = rand.nextBoolean();
Random rand = new Random();
boolean boolValue = rand.nextBoolean();
opt.setFillCache(boolValue); opt.setFillCache(boolValue);
assertThat(opt.fillCache()).isEqualTo(boolValue); assertThat(opt.fillCache()).isEqualTo(boolValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
} }
@Test @Test
public void tailing(){ public void tailing() {
ReadOptions opt = null; try (final ReadOptions opt = new ReadOptions()) {
try { final Random rand = new Random();
opt = new ReadOptions(); final boolean boolValue = rand.nextBoolean();
Random rand = new Random();
boolean boolValue = rand.nextBoolean();
opt.setTailing(boolValue); opt.setTailing(boolValue);
assertThat(opt.tailing()).isEqualTo(boolValue); assertThat(opt.tailing()).isEqualTo(boolValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
} }
@Test @Test
public void snapshot(){ public void snapshot() {
ReadOptions opt = null; try (final ReadOptions opt = new ReadOptions()) {
try {
opt = new ReadOptions();
opt.setSnapshot(null); opt.setSnapshot(null);
assertThat(opt.snapshot()).isNull(); assertThat(opt.snapshot()).isNull();
} finally {
if (opt != null) {
opt.dispose();
}
} }
} }
@Test @Test
public void failSetVerifyChecksumUninitialized(){ public void failSetVerifyChecksumUninitialized() {
ReadOptions readOptions = setupUninitializedReadOptions( try (final ReadOptions readOptions =
exception); setupUninitializedReadOptions(exception)) {
readOptions.setVerifyChecksums(true); readOptions.setVerifyChecksums(true);
}
} }
@Test @Test
public void failVerifyChecksumUninitialized(){ public void failVerifyChecksumUninitialized() {
ReadOptions readOptions = setupUninitializedReadOptions( try (final ReadOptions readOptions =
exception); setupUninitializedReadOptions(exception)) {
readOptions.verifyChecksums(); readOptions.verifyChecksums();
}
} }
@Test @Test
public void failSetFillCacheUninitialized(){ public void failSetFillCacheUninitialized() {
ReadOptions readOptions = setupUninitializedReadOptions( try (final ReadOptions readOptions =
exception); setupUninitializedReadOptions(exception)) {
readOptions.setFillCache(true); readOptions.setFillCache(true);
}
} }
@Test @Test
public void failFillCacheUninitialized(){ public void failFillCacheUninitialized() {
ReadOptions readOptions = setupUninitializedReadOptions( try (final ReadOptions readOptions =
exception); setupUninitializedReadOptions(exception)) {
readOptions.fillCache(); readOptions.fillCache();
}
} }
@Test @Test
public void failSetTailingUninitialized(){ public void failSetTailingUninitialized() {
ReadOptions readOptions = setupUninitializedReadOptions( try (final ReadOptions readOptions =
exception); setupUninitializedReadOptions(exception)) {
readOptions.setTailing(true); readOptions.setTailing(true);
}
} }
@Test @Test
public void failTailingUninitialized(){ public void failTailingUninitialized() {
ReadOptions readOptions = setupUninitializedReadOptions( try (final ReadOptions readOptions =
exception); setupUninitializedReadOptions(exception)) {
readOptions.tailing(); readOptions.tailing();
}
} }
@Test @Test
public void failSetSnapshotUninitialized(){ public void failSetSnapshotUninitialized() {
ReadOptions readOptions = setupUninitializedReadOptions( try (final ReadOptions readOptions =
exception); setupUninitializedReadOptions(exception)) {
readOptions.setSnapshot(null); readOptions.setSnapshot(null);
}
} }
@Test @Test
public void failSnapshotUninitialized(){ public void failSnapshotUninitialized() {
ReadOptions readOptions = setupUninitializedReadOptions( try (final ReadOptions readOptions =
exception); setupUninitializedReadOptions(exception)) {
readOptions.snapshot(); readOptions.snapshot();
}
} }
private ReadOptions setupUninitializedReadOptions( private ReadOptions setupUninitializedReadOptions(
ExpectedException exception) { ExpectedException exception) {
ReadOptions readOptions = new ReadOptions(); final ReadOptions readOptions = new ReadOptions();
readOptions.dispose(); readOptions.close();
exception.expect(AssertionError.class); exception.expect(AssertionError.class);
return readOptions; return readOptions;
} }

File diff suppressed because it is too large Load Diff

@ -17,22 +17,23 @@ public class RocksEnvTest {
new RocksMemoryResource(); new RocksMemoryResource();
@Test @Test
public void rocksEnv(){ public void rocksEnv() {
Env rocksEnv = RocksEnv.getDefault(); try (final Env rocksEnv = RocksEnv.getDefault()) {
rocksEnv.setBackgroundThreads(5); rocksEnv.setBackgroundThreads(5);
// default rocksenv will always return zero for flush pool // default rocksenv will always return zero for flush pool
// no matter what was set via setBackgroundThreads // no matter what was set via setBackgroundThreads
assertThat(rocksEnv.getThreadPoolQueueLen(RocksEnv.FLUSH_POOL)). assertThat(rocksEnv.getThreadPoolQueueLen(RocksEnv.FLUSH_POOL)).
isEqualTo(0); isEqualTo(0);
rocksEnv.setBackgroundThreads(5, RocksEnv.FLUSH_POOL); rocksEnv.setBackgroundThreads(5, RocksEnv.FLUSH_POOL);
// default rocksenv will always return zero for flush pool // default rocksenv will always return zero for flush pool
// no matter what was set via setBackgroundThreads // no matter what was set via setBackgroundThreads
assertThat(rocksEnv.getThreadPoolQueueLen(RocksEnv.FLUSH_POOL)). assertThat(rocksEnv.getThreadPoolQueueLen(RocksEnv.FLUSH_POOL)).
isEqualTo(0); isEqualTo(0);
rocksEnv.setBackgroundThreads(5, RocksEnv.COMPACTION_POOL); rocksEnv.setBackgroundThreads(5, RocksEnv.COMPACTION_POOL);
// default rocksenv will always return zero for compaction pool // default rocksenv will always return zero for compaction pool
// no matter what was set via setBackgroundThreads // no matter what was set via setBackgroundThreads
assertThat(rocksEnv.getThreadPoolQueueLen(RocksEnv.COMPACTION_POOL)). assertThat(rocksEnv.getThreadPoolQueueLen(RocksEnv.COMPACTION_POOL)).
isEqualTo(0); isEqualTo(0);
}
} }
} }

@ -22,50 +22,36 @@ public class RocksIteratorTest {
@Test @Test
public void rocksIterator() throws RocksDBException { public void rocksIterator() throws RocksDBException {
RocksDB db = null; try (final Options options = new Options()
Options options = null; .setCreateIfMissing(true)
RocksIterator iterator = null; .setCreateMissingColumnFamilies(true);
try { final RocksDB db = RocksDB.open(options,
options = new Options(); dbFolder.getRoot().getAbsolutePath())) {
options.setCreateIfMissing(true)
.setCreateMissingColumnFamilies(true);
db = RocksDB.open(options,
dbFolder.getRoot().getAbsolutePath());
db.put("key1".getBytes(), "value1".getBytes()); db.put("key1".getBytes(), "value1".getBytes());
db.put("key2".getBytes(), "value2".getBytes()); db.put("key2".getBytes(), "value2".getBytes());
iterator = db.newIterator(); try (final RocksIterator iterator = db.newIterator()) {
iterator.seekToFirst();
iterator.seekToFirst(); assertThat(iterator.isValid()).isTrue();
assertThat(iterator.isValid()).isTrue(); assertThat(iterator.key()).isEqualTo("key1".getBytes());
assertThat(iterator.key()).isEqualTo("key1".getBytes()); assertThat(iterator.value()).isEqualTo("value1".getBytes());
assertThat(iterator.value()).isEqualTo("value1".getBytes()); iterator.next();
iterator.next(); assertThat(iterator.isValid()).isTrue();
assertThat(iterator.isValid()).isTrue(); assertThat(iterator.key()).isEqualTo("key2".getBytes());
assertThat(iterator.key()).isEqualTo("key2".getBytes()); assertThat(iterator.value()).isEqualTo("value2".getBytes());
assertThat(iterator.value()).isEqualTo("value2".getBytes()); iterator.next();
iterator.next(); assertThat(iterator.isValid()).isFalse();
assertThat(iterator.isValid()).isFalse(); iterator.seekToLast();
iterator.seekToLast(); iterator.prev();
iterator.prev(); assertThat(iterator.isValid()).isTrue();
assertThat(iterator.isValid()).isTrue(); assertThat(iterator.key()).isEqualTo("key1".getBytes());
assertThat(iterator.key()).isEqualTo("key1".getBytes()); assertThat(iterator.value()).isEqualTo("value1".getBytes());
assertThat(iterator.value()).isEqualTo("value1".getBytes()); iterator.seekToFirst();
iterator.seekToFirst(); iterator.seekToLast();
iterator.seekToLast(); assertThat(iterator.isValid()).isTrue();
assertThat(iterator.isValid()).isTrue(); assertThat(iterator.key()).isEqualTo("key2".getBytes());
assertThat(iterator.key()).isEqualTo("key2".getBytes()); assertThat(iterator.value()).isEqualTo("value2".getBytes());
assertThat(iterator.value()).isEqualTo("value2".getBytes()); iterator.status();
iterator.status();
} finally {
if (iterator != null) {
iterator.dispose();
}
if (db != null) {
db.close();
}
if (options != null) {
options.dispose();
} }
} }
} }

@ -33,73 +33,55 @@ public class RocksMemEnvTest {
"baz".getBytes() "baz".getBytes()
}; };
Env env = null; try (final Env env = new RocksMemEnv();
Options options = null; final Options options = new Options()
RocksDB db = null; .setCreateIfMissing(true)
FlushOptions flushOptions = null; .setEnv(env);
try { final FlushOptions flushOptions = new FlushOptions()
env = new RocksMemEnv(); .setWaitForFlush(true);
options = new Options(). ) {
setCreateIfMissing(true). try (final RocksDB db = RocksDB.open(options, "dir/db")) {
setEnv(env); // write key/value pairs using MemEnv
flushOptions = new FlushOptions(). for (int i = 0; i < keys.length; i++) {
setWaitForFlush(true); db.put(keys[i], values[i]);
db = RocksDB.open(options, "dir/db"); }
// write key/value pairs using MemEnv // read key/value pairs using MemEnv
for (int i=0; i < keys.length; i++) { for (int i = 0; i < keys.length; i++) {
db.put(keys[i], values[i]); assertThat(db.get(keys[i])).isEqualTo(values[i]);
}
// Check iterator access
try (final RocksIterator iterator = db.newIterator()) {
iterator.seekToFirst();
for (int i = 0; i < keys.length; i++) {
assertThat(iterator.isValid()).isTrue();
assertThat(iterator.key()).isEqualTo(keys[i]);
assertThat(iterator.value()).isEqualTo(values[i]);
iterator.next();
}
// reached end of database
assertThat(iterator.isValid()).isFalse();
}
// flush
db.flush(flushOptions);
// read key/value pairs after flush using MemEnv
for (int i = 0; i < keys.length; i++) {
assertThat(db.get(keys[i])).isEqualTo(values[i]);
}
} }
// read key/value pairs using MemEnv
for (int i=0; i < keys.length; i++) {
assertThat(db.get(keys[i])).isEqualTo(values[i]);
}
// Check iterator access
RocksIterator iterator = db.newIterator();
iterator.seekToFirst();
for (int i=0; i < keys.length; i++) {
assertThat(iterator.isValid()).isTrue();
assertThat(iterator.key()).isEqualTo(keys[i]);
assertThat(iterator.value()).isEqualTo(values[i]);
iterator.next();
}
// reached end of database
assertThat(iterator.isValid()).isFalse();
iterator.dispose();
// flush
db.flush(flushOptions);
// read key/value pairs after flush using MemEnv
for (int i=0; i < keys.length; i++) {
assertThat(db.get(keys[i])).isEqualTo(values[i]);
}
db.close();
options.setCreateIfMissing(false); options.setCreateIfMissing(false);
// After reopen the values shall still be in the mem env. // After reopen the values shall still be in the mem env.
// as long as the env is not freed. // as long as the env is not freed.
db = RocksDB.open(options, "dir/db"); try (final RocksDB db = RocksDB.open(options, "dir/db")) {
// read key/value pairs using MemEnv // read key/value pairs using MemEnv
for (int i=0; i < keys.length; i++) { for (int i = 0; i < keys.length; i++) {
assertThat(db.get(keys[i])).isEqualTo(values[i]); assertThat(db.get(keys[i])).isEqualTo(values[i]);
} }
} finally {
if (db != null) {
db.close();
}
if (options != null) {
options.dispose();
}
if (flushOptions != null) {
flushOptions.dispose();
}
if (env != null) {
env.dispose();
} }
} }
} }
@ -125,27 +107,22 @@ public class RocksMemEnvTest {
"baz".getBytes() "baz".getBytes()
}; };
Env env = null; try (final Env env = new RocksMemEnv();
Options options = null; final Options options = new Options()
RocksDB db = null, otherDb = null; .setCreateIfMissing(true)
.setEnv(env);
try { final RocksDB db = RocksDB.open(options, "dir/db");
env = new RocksMemEnv(); final RocksDB otherDb = RocksDB.open(options, "dir/otherDb")
options = new Options(). ) {
setCreateIfMissing(true).
setEnv(env);
db = RocksDB.open(options, "dir/db");
otherDb = RocksDB.open(options, "dir/otherDb");
// write key/value pairs using MemEnv // write key/value pairs using MemEnv
// to db and to otherDb. // to db and to otherDb.
for (int i=0; i < keys.length; i++) { for (int i = 0; i < keys.length; i++) {
db.put(keys[i], values[i]); db.put(keys[i], values[i]);
otherDb.put(otherKeys[i], values[i]); otherDb.put(otherKeys[i], values[i]);
} }
// verify key/value pairs after flush using MemEnv // verify key/value pairs after flush using MemEnv
for (int i=0; i < keys.length; i++) { for (int i = 0; i < keys.length; i++) {
// verify db // verify db
assertThat(db.get(otherKeys[i])).isNull(); assertThat(db.get(otherKeys[i])).isNull();
assertThat(db.get(keys[i])).isEqualTo(values[i]); assertThat(db.get(keys[i])).isEqualTo(values[i]);
@ -154,43 +131,18 @@ public class RocksMemEnvTest {
assertThat(otherDb.get(keys[i])).isNull(); assertThat(otherDb.get(keys[i])).isNull();
assertThat(otherDb.get(otherKeys[i])).isEqualTo(values[i]); assertThat(otherDb.get(otherKeys[i])).isEqualTo(values[i]);
} }
} finally {
if (db != null) {
db.close();
}
if (otherDb != null) {
otherDb.close();
}
if (options != null) {
options.dispose();
}
if (env != null) {
env.dispose();
}
} }
} }
@Test(expected = RocksDBException.class) @Test(expected = RocksDBException.class)
public void createIfMissingFalse() throws RocksDBException { public void createIfMissingFalse() throws RocksDBException {
Env env = null; try (final Env env = new RocksMemEnv();
Options options = null; final Options options = new Options()
RocksDB db = null; .setCreateIfMissing(false)
.setEnv(env);
try { final RocksDB db = RocksDB.open(options, "db/dir")) {
env = new RocksMemEnv();
options = new Options().
setCreateIfMissing(false).
setEnv(env);
// shall throw an exception because db dir does not // shall throw an exception because db dir does not
// exist. // exist.
db = RocksDB.open(options, "db/dir");
} finally {
if (options != null) {
options.dispose();
}
if (env != null) {
env.dispose();
}
} }
} }
} }

@ -5,7 +5,11 @@ import org.junit.rules.ExternalResource;
/** /**
* Resource to trigger garbage collection after each test * Resource to trigger garbage collection after each test
* run. * run.
*
* @deprecated Will be removed with the implementation of
* {@link RocksObject#finalize()}
*/ */
@Deprecated
public class RocksMemoryResource extends ExternalResource { public class RocksMemoryResource extends ExternalResource {
static { static {

@ -17,89 +17,45 @@ public class SliceTest {
@Test @Test
public void slice() { public void slice() {
Slice slice = null; try (final Slice slice = new Slice("testSlice")) {
Slice otherSlice = null;
Slice thirdSlice = null;
try {
slice = new Slice("testSlice");
assertThat(slice.empty()).isFalse(); assertThat(slice.empty()).isFalse();
assertThat(slice.size()).isEqualTo(9); assertThat(slice.size()).isEqualTo(9);
assertThat(slice.data()).isEqualTo("testSlice".getBytes()); assertThat(slice.data()).isEqualTo("testSlice".getBytes());
}
otherSlice = new Slice("otherSlice".getBytes()); try (final Slice otherSlice = new Slice("otherSlice".getBytes())) {
assertThat(otherSlice.data()).isEqualTo("otherSlice".getBytes()); assertThat(otherSlice.data()).isEqualTo("otherSlice".getBytes());
}
thirdSlice = new Slice("otherSlice".getBytes(), 5); try (final Slice thirdSlice = new Slice("otherSlice".getBytes(), 5)) {
assertThat(thirdSlice.data()).isEqualTo("Slice".getBytes()); assertThat(thirdSlice.data()).isEqualTo("Slice".getBytes());
} finally {
if (slice != null) {
slice.dispose();
}
if (otherSlice != null) {
otherSlice.dispose();
}
if (thirdSlice != null) {
thirdSlice.dispose();
}
} }
} }
@Test @Test
public void sliceEquals() { public void sliceEquals() {
Slice slice = null; try (final Slice slice = new Slice("abc");
Slice slice2 = null; final Slice slice2 = new Slice("abc")) {
try {
slice = new Slice("abc");
slice2 = new Slice("abc");
assertThat(slice.equals(slice2)).isTrue(); assertThat(slice.equals(slice2)).isTrue();
assertThat(slice.hashCode() == slice2.hashCode()).isTrue(); assertThat(slice.hashCode() == slice2.hashCode()).isTrue();
} finally {
if (slice != null) {
slice.dispose();
}
if (slice2 != null) {
slice2.dispose();
}
} }
} }
@Test @Test
public void sliceStartWith() { public void sliceStartWith() {
Slice slice = null; try (final Slice slice = new Slice("matchpoint");
Slice match = null; final Slice match = new Slice("mat");
Slice noMatch = null; final Slice noMatch = new Slice("nomatch")) {
try { assertThat(slice.startsWith(match)).isTrue();
slice = new Slice("matchpoint");
match = new Slice("mat");
noMatch = new Slice("nomatch");
//assertThat(slice.startsWith(match)).isTrue();
assertThat(slice.startsWith(noMatch)).isFalse(); assertThat(slice.startsWith(noMatch)).isFalse();
} finally {
if (slice != null) {
slice.dispose();
}
if (match != null) {
match.dispose();
}
if (noMatch != null) {
noMatch.dispose();
}
} }
} }
@Test @Test
public void sliceToString() { public void sliceToString() {
Slice slice = null; try (final Slice slice = new Slice("stringTest")) {
try {
slice = new Slice("stringTest");
assertThat(slice.toString()).isEqualTo("stringTest"); assertThat(slice.toString()).isEqualTo("stringTest");
assertThat(slice.toString(true)).isNotEqualTo(""); assertThat(slice.toString(true)).isNotEqualTo("");
} finally {
if (slice != null) {
slice.dispose();
}
} }
} }
} }

@ -22,195 +22,147 @@ public class SnapshotTest {
@Test @Test
public void snapshots() throws RocksDBException { public void snapshots() throws RocksDBException {
RocksDB db = null; try (final Options options = new Options().setCreateIfMissing(true);
Options options = null; final RocksDB db = RocksDB.open(options,
ReadOptions readOptions = null; dbFolder.getRoot().getAbsolutePath())) {
try {
options = new Options();
options.setCreateIfMissing(true);
db = RocksDB.open(options, dbFolder.getRoot().getAbsolutePath());
db.put("key".getBytes(), "value".getBytes()); db.put("key".getBytes(), "value".getBytes());
// Get new Snapshot of database // Get new Snapshot of database
Snapshot snapshot = db.getSnapshot(); try (final Snapshot snapshot = db.getSnapshot()) {
assertThat(snapshot.getSequenceNumber()).isGreaterThan(0); assertThat(snapshot.getSequenceNumber()).isGreaterThan(0);
assertThat(snapshot.getSequenceNumber()).isEqualTo(1); assertThat(snapshot.getSequenceNumber()).isEqualTo(1);
readOptions = new ReadOptions(); try (final ReadOptions readOptions = new ReadOptions()) {
// set snapshot in ReadOptions // set snapshot in ReadOptions
readOptions.setSnapshot(snapshot); readOptions.setSnapshot(snapshot);
// retrieve key value pair
assertThat(new String(db.get("key".getBytes()))). // retrieve key value pair
isEqualTo("value"); assertThat(new String(db.get("key".getBytes()))).
// retrieve key value pair created before isEqualTo("value");
// the snapshot was made // retrieve key value pair created before
assertThat(new String(db.get(readOptions, // the snapshot was made
"key".getBytes()))).isEqualTo("value"); assertThat(new String(db.get(readOptions,
// add new key/value pair "key".getBytes()))).isEqualTo("value");
db.put("newkey".getBytes(), "newvalue".getBytes()); // add new key/value pair
// using no snapshot the latest db entries db.put("newkey".getBytes(), "newvalue".getBytes());
// will be taken into account // using no snapshot the latest db entries
assertThat(new String(db.get("newkey".getBytes()))). // will be taken into account
isEqualTo("newvalue"); assertThat(new String(db.get("newkey".getBytes()))).
// snapshopot was created before newkey isEqualTo("newvalue");
assertThat(db.get(readOptions, "newkey".getBytes())). // snapshopot was created before newkey
isNull(); assertThat(db.get(readOptions, "newkey".getBytes())).
// Retrieve snapshot from read options isNull();
Snapshot sameSnapshot = readOptions.snapshot(); // Retrieve snapshot from read options
readOptions.setSnapshot(sameSnapshot); try (final Snapshot sameSnapshot = readOptions.snapshot()) {
// results must be the same with new Snapshot readOptions.setSnapshot(sameSnapshot);
// instance using the same native pointer // results must be the same with new Snapshot
assertThat(new String(db.get(readOptions, // instance using the same native pointer
"key".getBytes()))).isEqualTo("value"); assertThat(new String(db.get(readOptions,
// update key value pair to newvalue "key".getBytes()))).isEqualTo("value");
db.put("key".getBytes(), "newvalue".getBytes()); // update key value pair to newvalue
// read with previously created snapshot will db.put("key".getBytes(), "newvalue".getBytes());
// read previous version of key value pair // read with previously created snapshot will
assertThat(new String(db.get(readOptions, // read previous version of key value pair
"key".getBytes()))).isEqualTo("value"); assertThat(new String(db.get(readOptions,
// read for newkey using the snapshot must be "key".getBytes()))).isEqualTo("value");
// null // read for newkey using the snapshot must be
assertThat(db.get(readOptions, "newkey".getBytes())). // null
isNull(); assertThat(db.get(readOptions, "newkey".getBytes())).
// setting null to snapshot in ReadOptions leads isNull();
// to no Snapshot being used. // setting null to snapshot in ReadOptions leads
readOptions.setSnapshot(null); // to no Snapshot being used.
assertThat(new String(db.get(readOptions, readOptions.setSnapshot(null);
"newkey".getBytes()))).isEqualTo("newvalue"); assertThat(new String(db.get(readOptions,
// release Snapshot "newkey".getBytes()))).isEqualTo("newvalue");
db.releaseSnapshot(snapshot); // release Snapshot
} finally { db.releaseSnapshot(snapshot);
if (db != null) { }
db.close(); }
}
if (options != null) {
options.dispose();
}
if (readOptions != null) {
readOptions.dispose();
} }
} }
} }
@Test @Test
public void iteratorWithSnapshot() throws RocksDBException { public void iteratorWithSnapshot() throws RocksDBException {
RocksDB db = null; try (final Options options = new Options().setCreateIfMissing(true);
Options options = null; final RocksDB db = RocksDB.open(options,
ReadOptions readOptions = null; dbFolder.getRoot().getAbsolutePath())) {
RocksIterator iterator = null;
RocksIterator snapshotIterator = null;
try {
options = new Options();
options.setCreateIfMissing(true);
db = RocksDB.open(options, dbFolder.getRoot().getAbsolutePath());
db.put("key".getBytes(), "value".getBytes()); db.put("key".getBytes(), "value".getBytes());
// Get new Snapshot of database // Get new Snapshot of database
Snapshot snapshot = db.getSnapshot();
readOptions = new ReadOptions();
// set snapshot in ReadOptions // set snapshot in ReadOptions
readOptions.setSnapshot(snapshot); try (final Snapshot snapshot = db.getSnapshot();
db.put("key2".getBytes(), "value2".getBytes()); final ReadOptions readOptions =
new ReadOptions().setSnapshot(snapshot)) {
// iterate over current state of db db.put("key2".getBytes(), "value2".getBytes());
iterator = db.newIterator();
iterator.seekToFirst(); // iterate over current state of db
assertThat(iterator.isValid()).isTrue(); try (final RocksIterator iterator = db.newIterator()) {
assertThat(iterator.key()).isEqualTo("key".getBytes()); iterator.seekToFirst();
iterator.next(); assertThat(iterator.isValid()).isTrue();
assertThat(iterator.isValid()).isTrue(); assertThat(iterator.key()).isEqualTo("key".getBytes());
assertThat(iterator.key()).isEqualTo("key2".getBytes()); iterator.next();
iterator.next(); assertThat(iterator.isValid()).isTrue();
assertThat(iterator.isValid()).isFalse(); assertThat(iterator.key()).isEqualTo("key2".getBytes());
iterator.next();
// iterate using a snapshot assertThat(iterator.isValid()).isFalse();
snapshotIterator = db.newIterator(readOptions); }
snapshotIterator.seekToFirst();
assertThat(snapshotIterator.isValid()).isTrue(); // iterate using a snapshot
assertThat(snapshotIterator.key()).isEqualTo("key".getBytes()); try (final RocksIterator snapshotIterator =
snapshotIterator.next(); db.newIterator(readOptions)) {
assertThat(snapshotIterator.isValid()).isFalse(); snapshotIterator.seekToFirst();
assertThat(snapshotIterator.isValid()).isTrue();
// release Snapshot assertThat(snapshotIterator.key()).isEqualTo("key".getBytes());
db.releaseSnapshot(snapshot); snapshotIterator.next();
} finally { assertThat(snapshotIterator.isValid()).isFalse();
if (iterator != null) { }
iterator.dispose();
} // release Snapshot
if (snapshotIterator != null) { db.releaseSnapshot(snapshot);
snapshotIterator.dispose();
}
if (db != null) {
db.close();
}
if (options != null) {
options.dispose();
}
if (readOptions != null) {
readOptions.dispose();
} }
} }
} }
@Test @Test
public void iteratorWithSnapshotOnColumnFamily() throws RocksDBException { public void iteratorWithSnapshotOnColumnFamily() throws RocksDBException {
RocksDB db = null; try (final Options options = new Options()
Options options = null; .setCreateIfMissing(true);
ReadOptions readOptions = null; final RocksDB db = RocksDB.open(options,
RocksIterator iterator = null; dbFolder.getRoot().getAbsolutePath())) {
RocksIterator snapshotIterator = null;
try {
options = new Options();
options.setCreateIfMissing(true);
db = RocksDB.open(options, dbFolder.getRoot().getAbsolutePath());
db.put("key".getBytes(), "value".getBytes()); db.put("key".getBytes(), "value".getBytes());
// Get new Snapshot of database // Get new Snapshot of database
Snapshot snapshot = db.getSnapshot();
readOptions = new ReadOptions();
// set snapshot in ReadOptions // set snapshot in ReadOptions
readOptions.setSnapshot(snapshot); try (final Snapshot snapshot = db.getSnapshot();
db.put("key2".getBytes(), "value2".getBytes()); final ReadOptions readOptions = new ReadOptions()
.setSnapshot(snapshot)) {
// iterate over current state of column family db.put("key2".getBytes(), "value2".getBytes());
iterator = db.newIterator(db.getDefaultColumnFamily());
iterator.seekToFirst(); // iterate over current state of column family
assertThat(iterator.isValid()).isTrue(); try (final RocksIterator iterator = db.newIterator(
assertThat(iterator.key()).isEqualTo("key".getBytes()); db.getDefaultColumnFamily())) {
iterator.next(); iterator.seekToFirst();
assertThat(iterator.isValid()).isTrue(); assertThat(iterator.isValid()).isTrue();
assertThat(iterator.key()).isEqualTo("key2".getBytes()); assertThat(iterator.key()).isEqualTo("key".getBytes());
iterator.next(); iterator.next();
assertThat(iterator.isValid()).isFalse(); assertThat(iterator.isValid()).isTrue();
assertThat(iterator.key()).isEqualTo("key2".getBytes());
// iterate using a snapshot on default column family iterator.next();
snapshotIterator = db.newIterator(db.getDefaultColumnFamily(), assertThat(iterator.isValid()).isFalse();
readOptions); }
snapshotIterator.seekToFirst();
assertThat(snapshotIterator.isValid()).isTrue(); // iterate using a snapshot on default column family
assertThat(snapshotIterator.key()).isEqualTo("key".getBytes()); try (final RocksIterator snapshotIterator = db.newIterator(
snapshotIterator.next(); db.getDefaultColumnFamily(), readOptions)) {
assertThat(snapshotIterator.isValid()).isFalse(); snapshotIterator.seekToFirst();
assertThat(snapshotIterator.isValid()).isTrue();
// release Snapshot assertThat(snapshotIterator.key()).isEqualTo("key".getBytes());
db.releaseSnapshot(snapshot); snapshotIterator.next();
} finally { assertThat(snapshotIterator.isValid()).isFalse();
if (iterator != null) {
iterator.dispose(); // release Snapshot
} db.releaseSnapshot(snapshot);
if (snapshotIterator != null) { }
snapshotIterator.dispose();
}
if (db != null) {
db.close();
}
if (options != null) {
options.dispose();
}
if (readOptions != null) {
readOptions.dispose();
} }
} }
} }

@ -26,19 +26,18 @@ public class StatisticsCollectorTest {
@Test @Test
public void statisticsCollector() public void statisticsCollector()
throws InterruptedException, RocksDBException { throws InterruptedException, RocksDBException {
Options opt = null; try (final Options opt = new Options()
RocksDB db = null; .createStatistics()
try { .setCreateIfMissing(true);
opt = new Options().createStatistics().setCreateIfMissing(true); final RocksDB db = RocksDB.open(opt,
Statistics stats = opt.statisticsPtr(); dbFolder.getRoot().getAbsolutePath())) {
final Statistics stats = opt.statisticsPtr();
db = RocksDB.open(opt,
dbFolder.getRoot().getAbsolutePath()); final StatsCallbackMock callback = new StatsCallbackMock();
final StatsCollectorInput statsInput =
StatsCallbackMock callback = new StatsCallbackMock(); new StatsCollectorInput(stats, callback);
StatsCollectorInput statsInput = new StatsCollectorInput(stats, callback);
final StatisticsCollector statsCollector = new StatisticsCollector(
StatisticsCollector statsCollector = new StatisticsCollector(
Collections.singletonList(statsInput), 100); Collections.singletonList(statsInput), 100);
statsCollector.start(); statsCollector.start();
@ -48,13 +47,6 @@ public class StatisticsCollectorTest {
assertThat(callback.histCallbackCount).isGreaterThan(0); assertThat(callback.histCallbackCount).isGreaterThan(0);
statsCollector.shutDown(1000); statsCollector.shutDown(1000);
} finally {
if (db != null) {
db.close();
}
if (opt != null) {
opt.dispose();
}
} }
} }
} }

@ -17,43 +17,27 @@ public class TransactionLogIteratorTest {
@Test @Test
public void transactionLogIterator() throws RocksDBException { public void transactionLogIterator() throws RocksDBException {
RocksDB db = null; try (final Options options = new Options()
Options options = null; .setCreateIfMissing(true);
TransactionLogIterator transactionLogIterator = null; final RocksDB db = RocksDB.open(options,
try { dbFolder.getRoot().getAbsolutePath());
options = new Options(). final TransactionLogIterator transactionLogIterator =
setCreateIfMissing(true); db.getUpdatesSince(0)) {
db = RocksDB.open(options, dbFolder.getRoot().getAbsolutePath()); //no-op
transactionLogIterator = db.getUpdatesSince(0);
} finally {
if (transactionLogIterator != null) {
transactionLogIterator.dispose();
}
if (db != null) {
db.close();
}
if (options != null) {
options.dispose();
}
} }
} }
@Test @Test
public void getBatch() throws RocksDBException { public void getBatch() throws RocksDBException {
final int numberOfPuts = 5; final int numberOfPuts = 5;
RocksDB db = null; try (final Options options = new Options()
Options options = null; .setCreateIfMissing(true)
ColumnFamilyHandle cfHandle = null; .setWalTtlSeconds(1000)
TransactionLogIterator transactionLogIterator = null; .setWalSizeLimitMB(10);
try { final RocksDB db = RocksDB.open(options,
options = new Options(). dbFolder.getRoot().getAbsolutePath())) {
setCreateIfMissing(true).
setWalTtlSeconds(1000). for (int i = 0; i < numberOfPuts; i++) {
setWalSizeLimitMB(10);
db = RocksDB.open(options, dbFolder.getRoot().getAbsolutePath());
for (int i = 0; i < numberOfPuts; i++){
db.put(String.valueOf(i).getBytes(), db.put(String.valueOf(i).getBytes(),
String.valueOf(i).getBytes()); String.valueOf(i).getBytes());
} }
@ -65,117 +49,89 @@ public class TransactionLogIteratorTest {
isEqualTo(numberOfPuts); isEqualTo(numberOfPuts);
// insert 5 writes into a cf // insert 5 writes into a cf
cfHandle = db.createColumnFamily( try (final ColumnFamilyHandle cfHandle = db.createColumnFamily(
new ColumnFamilyDescriptor("new_cf".getBytes())); new ColumnFamilyDescriptor("new_cf".getBytes()))) {
for (int i = 0; i < numberOfPuts; i++) {
for (int i = 0; i < numberOfPuts; i++){ db.put(cfHandle, String.valueOf(i).getBytes(),
db.put(cfHandle, String.valueOf(i).getBytes(), String.valueOf(i).getBytes());
String.valueOf(i).getBytes()); }
} // the latest sequence number is 10 because
// the latest sequence number is 10 because // (5 + 5) puts were written beforehand
// (5 + 5) puts were written beforehand assertThat(db.getLatestSequenceNumber()).
assertThat(db.getLatestSequenceNumber()). isEqualTo(numberOfPuts + numberOfPuts);
isEqualTo(numberOfPuts + numberOfPuts);
// Get updates since the beginning
// Get updates since the beginning try (final TransactionLogIterator transactionLogIterator =
transactionLogIterator = db.getUpdatesSince(0); db.getUpdatesSince(0)) {
assertThat(transactionLogIterator.isValid()).isTrue(); assertThat(transactionLogIterator.isValid()).isTrue();
transactionLogIterator.status(); transactionLogIterator.status();
// The first sequence number is 1 // The first sequence number is 1
TransactionLogIterator.BatchResult batchResult = final TransactionLogIterator.BatchResult batchResult =
transactionLogIterator.getBatch(); transactionLogIterator.getBatch();
assertThat(batchResult.sequenceNumber()).isEqualTo(1); assertThat(batchResult.sequenceNumber()).isEqualTo(1);
} finally { }
if (transactionLogIterator != null) {
transactionLogIterator.dispose();
}
if (cfHandle != null) {
cfHandle.dispose();
}
if (db != null) {
db.close();
}
if (options != null) {
options.dispose();
} }
} }
} }
@Test @Test
public void transactionLogIteratorStallAtLastRecord() throws RocksDBException { public void transactionLogIteratorStallAtLastRecord()
RocksDB db = null; throws RocksDBException {
Options options = null; try (final Options options = new Options()
TransactionLogIterator transactionLogIterator = null; .setCreateIfMissing(true)
try { .setWalTtlSeconds(1000)
options = new Options(). .setWalSizeLimitMB(10);
setCreateIfMissing(true). final RocksDB db = RocksDB.open(options,
setWalTtlSeconds(1000). dbFolder.getRoot().getAbsolutePath())) {
setWalSizeLimitMB(10);
db = RocksDB.open(options, dbFolder.getRoot().getAbsolutePath());
db.put("key1".getBytes(), "value1".getBytes()); db.put("key1".getBytes(), "value1".getBytes());
// Get updates since the beginning // Get updates since the beginning
transactionLogIterator = db.getUpdatesSince(0); try (final TransactionLogIterator transactionLogIterator =
transactionLogIterator.status(); db.getUpdatesSince(0)) {
assertThat(transactionLogIterator.isValid()).isTrue(); transactionLogIterator.status();
transactionLogIterator.next(); assertThat(transactionLogIterator.isValid()).isTrue();
assertThat(transactionLogIterator.isValid()).isFalse(); transactionLogIterator.next();
transactionLogIterator.status(); assertThat(transactionLogIterator.isValid()).isFalse();
db.put("key2".getBytes(), "value2".getBytes()); transactionLogIterator.status();
transactionLogIterator.next(); db.put("key2".getBytes(), "value2".getBytes());
transactionLogIterator.status(); transactionLogIterator.next();
assertThat(transactionLogIterator.isValid()).isTrue(); transactionLogIterator.status();
assertThat(transactionLogIterator.isValid()).isTrue();
} finally {
if (transactionLogIterator != null) {
transactionLogIterator.dispose();
}
if (db != null) {
db.close();
}
if (options != null) {
options.dispose();
} }
} }
} }
@Test @Test
public void transactionLogIteratorCheckAfterRestart() throws RocksDBException { public void transactionLogIteratorCheckAfterRestart()
throws RocksDBException {
final int numberOfKeys = 2; final int numberOfKeys = 2;
RocksDB db = null; try (final Options options = new Options()
Options options = null; .setCreateIfMissing(true)
TransactionLogIterator transactionLogIterator = null; .setWalTtlSeconds(1000)
try { .setWalSizeLimitMB(10)) {
options = new Options().
setCreateIfMissing(true). try (final RocksDB db = RocksDB.open(options,
setWalTtlSeconds(1000). dbFolder.getRoot().getAbsolutePath())) {
setWalSizeLimitMB(10); db.put("key1".getBytes(), "value1".getBytes());
db.put("key2".getBytes(), "value2".getBytes());
db = RocksDB.open(options, dbFolder.getRoot().getAbsolutePath()); db.flush(new FlushOptions().setWaitForFlush(true));
db.put("key1".getBytes(), "value1".getBytes());
db.put("key2".getBytes(), "value2".getBytes());
db.flush(new FlushOptions().setWaitForFlush(true));
// reopen
db.close();
db = RocksDB.open(options, dbFolder.getRoot().getAbsolutePath());
assertThat(db.getLatestSequenceNumber()).isEqualTo(numberOfKeys);
transactionLogIterator = db.getUpdatesSince(0);
for (int i = 0; i < numberOfKeys; i++) {
transactionLogIterator.status();
assertThat(transactionLogIterator.isValid()).isTrue();
transactionLogIterator.next();
}
} finally {
if (transactionLogIterator != null) {
transactionLogIterator.dispose();
}
if (db != null) {
db.close();
} }
if (options != null) {
options.dispose(); // reopen
try (final RocksDB db = RocksDB.open(options,
dbFolder.getRoot().getAbsolutePath())) {
assertThat(db.getLatestSequenceNumber()).isEqualTo(numberOfKeys);
try (final TransactionLogIterator transactionLogIterator =
db.getUpdatesSince(0)) {
for (int i = 0; i < numberOfKeys; i++) {
transactionLogIterator.status();
assertThat(transactionLogIterator.isValid()).isTrue();
transactionLogIterator.next();
}
}
} }
} }
} }

@ -11,6 +11,7 @@ import org.junit.Test;
import org.junit.rules.TemporaryFolder; import org.junit.rules.TemporaryFolder;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
@ -26,108 +27,74 @@ public class TtlDBTest {
public TemporaryFolder dbFolder = new TemporaryFolder(); public TemporaryFolder dbFolder = new TemporaryFolder();
@Test @Test
public void ttlDBOpen() throws RocksDBException, public void ttlDBOpen() throws RocksDBException, InterruptedException {
InterruptedException { try (final Options options = new Options()
Options options = null; .setCreateIfMissing(true)
TtlDB ttlDB = null; .setMaxGrandparentOverlapFactor(0);
try { final TtlDB ttlDB = TtlDB.open(options,
options = new Options(). dbFolder.getRoot().getAbsolutePath())
setCreateIfMissing(true). ) {
setMaxGrandparentOverlapFactor(0);
ttlDB = TtlDB.open(options,
dbFolder.getRoot().getAbsolutePath());
ttlDB.put("key".getBytes(), "value".getBytes()); ttlDB.put("key".getBytes(), "value".getBytes());
assertThat(ttlDB.get("key".getBytes())). assertThat(ttlDB.get("key".getBytes())).
isEqualTo("value".getBytes()); isEqualTo("value".getBytes());
assertThat(ttlDB.get("key".getBytes())).isNotNull(); assertThat(ttlDB.get("key".getBytes())).isNotNull();
} finally {
if (ttlDB != null) {
ttlDB.close();
}
if (options != null) {
options.dispose();
}
} }
} }
@Test @Test
public void ttlDBOpenWithTtl() throws RocksDBException, public void ttlDBOpenWithTtl() throws RocksDBException, InterruptedException {
InterruptedException { try (final Options options = new Options()
Options options = null; .setCreateIfMissing(true)
TtlDB ttlDB = null; .setMaxGrandparentOverlapFactor(0);
try { final TtlDB ttlDB = TtlDB.open(options,
options = new Options(). dbFolder.getRoot().getAbsolutePath(), 1, false);
setCreateIfMissing(true). ) {
setMaxGrandparentOverlapFactor(0);
ttlDB = TtlDB.open(options, dbFolder.getRoot().getAbsolutePath(),
1, false);
ttlDB.put("key".getBytes(), "value".getBytes()); ttlDB.put("key".getBytes(), "value".getBytes());
assertThat(ttlDB.get("key".getBytes())). assertThat(ttlDB.get("key".getBytes())).
isEqualTo("value".getBytes()); isEqualTo("value".getBytes());
TimeUnit.SECONDS.sleep(2); TimeUnit.SECONDS.sleep(2);
ttlDB.compactRange(); ttlDB.compactRange();
assertThat(ttlDB.get("key".getBytes())).isNull(); assertThat(ttlDB.get("key".getBytes())).isNull();
} finally {
if (ttlDB != null) {
ttlDB.close();
}
if (options != null) {
options.dispose();
}
} }
} }
@Test @Test
public void ttlDbOpenWithColumnFamilies() throws RocksDBException, InterruptedException { public void ttlDbOpenWithColumnFamilies() throws RocksDBException,
DBOptions dbOptions = null; InterruptedException {
TtlDB ttlDB = null; final List<ColumnFamilyDescriptor> cfNames = Arrays.asList(
List<ColumnFamilyDescriptor> cfNames = new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY),
new ArrayList<>(); new ColumnFamilyDescriptor("new_cf".getBytes())
List<ColumnFamilyHandle> columnFamilyHandleList = );
new ArrayList<>(); final List<Integer> ttlValues = Arrays.asList(0, 1);
cfNames.add(new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY));
cfNames.add(new ColumnFamilyDescriptor("new_cf".getBytes())); final List<ColumnFamilyHandle> columnFamilyHandleList = new ArrayList<>();
List<Integer> ttlValues = new ArrayList<>(); try (final DBOptions dbOptions = new DBOptions()
// Default column family with infinite lifetime .setCreateMissingColumnFamilies(true)
ttlValues.add(0); .setCreateIfMissing(true);
// new column family with 1 second ttl final TtlDB ttlDB = TtlDB.open(dbOptions,
ttlValues.add(1); dbFolder.getRoot().getAbsolutePath(), cfNames,
columnFamilyHandleList, ttlValues, false)) {
try { try {
dbOptions = new DBOptions(). ttlDB.put("key".getBytes(), "value".getBytes());
setCreateMissingColumnFamilies(true). assertThat(ttlDB.get("key".getBytes())).
setCreateIfMissing(true); isEqualTo("value".getBytes());
ttlDB = TtlDB.open(dbOptions, dbFolder.getRoot().getAbsolutePath(), ttlDB.put(columnFamilyHandleList.get(1), "key".getBytes(),
cfNames, columnFamilyHandleList, ttlValues, false); "value".getBytes());
assertThat(ttlDB.get(columnFamilyHandleList.get(1),
ttlDB.put("key".getBytes(), "value".getBytes()); "key".getBytes())).isEqualTo("value".getBytes());
assertThat(ttlDB.get("key".getBytes())). TimeUnit.SECONDS.sleep(2);
isEqualTo("value".getBytes());
ttlDB.put(columnFamilyHandleList.get(1), "key".getBytes(), ttlDB.compactRange();
"value".getBytes()); ttlDB.compactRange(columnFamilyHandleList.get(1));
assertThat(ttlDB.get(columnFamilyHandleList.get(1),
"key".getBytes())).isEqualTo("value".getBytes()); assertThat(ttlDB.get("key".getBytes())).isNotNull();
TimeUnit.SECONDS.sleep(2); assertThat(ttlDB.get(columnFamilyHandleList.get(1),
"key".getBytes())).isNull();
ttlDB.compactRange(); } finally {
ttlDB.compactRange(columnFamilyHandleList.get(1)); for (final ColumnFamilyHandle columnFamilyHandle :
columnFamilyHandleList) {
assertThat(ttlDB.get("key".getBytes())).isNotNull(); columnFamilyHandle.close();
assertThat(ttlDB.get(columnFamilyHandleList.get(1), }
"key".getBytes())).isNull();
} finally {
for (ColumnFamilyHandle columnFamilyHandle :
columnFamilyHandleList) {
columnFamilyHandle.dispose();
}
if (ttlDB != null) {
ttlDB.close();
}
if (dbOptions != null) {
dbOptions.dispose();
} }
} }
} }
@ -135,15 +102,12 @@ public class TtlDBTest {
@Test @Test
public void createTtlColumnFamily() throws RocksDBException, public void createTtlColumnFamily() throws RocksDBException,
InterruptedException { InterruptedException {
Options options = null; try (final Options options = new Options().setCreateIfMissing(true);
TtlDB ttlDB = null; final TtlDB ttlDB = TtlDB.open(options,
ColumnFamilyHandle columnFamilyHandle = null; dbFolder.getRoot().getAbsolutePath());
try { final ColumnFamilyHandle columnFamilyHandle =
options = new Options().setCreateIfMissing(true); ttlDB.createColumnFamilyWithTtl(
ttlDB = TtlDB.open(options, new ColumnFamilyDescriptor("new_cf".getBytes()), 1)) {
dbFolder.getRoot().getAbsolutePath());
columnFamilyHandle = ttlDB.createColumnFamilyWithTtl(
new ColumnFamilyDescriptor("new_cf".getBytes()), 1);
ttlDB.put(columnFamilyHandle, "key".getBytes(), ttlDB.put(columnFamilyHandle, "key".getBytes(),
"value".getBytes()); "value".getBytes());
assertThat(ttlDB.get(columnFamilyHandle, "key".getBytes())). assertThat(ttlDB.get(columnFamilyHandle, "key".getBytes())).
@ -151,16 +115,6 @@ public class TtlDBTest {
TimeUnit.SECONDS.sleep(2); TimeUnit.SECONDS.sleep(2);
ttlDB.compactRange(columnFamilyHandle); ttlDB.compactRange(columnFamilyHandle);
assertThat(ttlDB.get(columnFamilyHandle, "key".getBytes())).isNull(); assertThat(ttlDB.get(columnFamilyHandle, "key".getBytes())).isNull();
} finally {
if (columnFamilyHandle != null) {
columnFamilyHandle.dispose();
}
if (ttlDB != null) {
ttlDB.close();
}
if (options != null) {
options.dispose();
}
} }
} }
} }

@ -23,28 +23,26 @@ public class WriteBatchHandlerTest {
@Test @Test
public void writeBatchHandler() throws IOException, RocksDBException { public void writeBatchHandler() throws IOException, RocksDBException {
WriteBatch batch = null; // setup test data
CapturingWriteBatchHandler handler = null; final List<Tuple<Action, Tuple<byte[], byte[]>>> testEvents = Arrays.asList(
try { new Tuple<>(Action.DELETE,
// setup test data new Tuple<byte[], byte[]>("k0".getBytes(), null)),
final List<Tuple<Action, Tuple<byte[], byte[]>>> testEvents = new ArrayList<>(); new Tuple<>(Action.PUT,
testEvents.add(new Tuple<>(Action.DELETE, new Tuple<>("k1".getBytes(), "v1".getBytes())),
new Tuple<byte[], byte[]>("k0".getBytes(), null))); new Tuple<>(Action.PUT,
testEvents.add(new Tuple<>(Action.PUT, new Tuple<>("k2".getBytes(), "v2".getBytes())),
new Tuple<>("k1".getBytes(), "v1".getBytes()))); new Tuple<>(Action.PUT,
testEvents.add(new Tuple<>(Action.PUT, new Tuple<>("k3".getBytes(), "v3".getBytes())),
new Tuple<>("k2".getBytes(), "v2".getBytes()))); new Tuple<>(Action.LOG,
testEvents.add(new Tuple<>(Action.PUT, new Tuple<byte[], byte[]>(null, "log1".getBytes())),
new Tuple<>("k3".getBytes(), "v3".getBytes()))); new Tuple<>(Action.MERGE,
testEvents.add(new Tuple<>(Action.LOG, new Tuple<>("k2".getBytes(), "v22".getBytes())),
new Tuple<byte[], byte[]>(null, "log1".getBytes()))); new Tuple<>(Action.DELETE,
testEvents.add(new Tuple<>(Action.MERGE, new Tuple<byte[], byte[]>("k3".getBytes(), null))
new Tuple<>("k2".getBytes(), "v22".getBytes()))); );
testEvents.add(new Tuple<>(Action.DELETE,
new Tuple<byte[], byte[]>("k3".getBytes(), null))); // load test data to the write batch
try (final WriteBatch batch = new WriteBatch()) {
// load test data to the write batch
batch = new WriteBatch();
for (final Tuple<Action, Tuple<byte[], byte[]>> testEvent : testEvents) { for (final Tuple<Action, Tuple<byte[], byte[]>> testEvent : testEvents) {
final Tuple<byte[], byte[]> data = testEvent.value; final Tuple<byte[], byte[]> data = testEvent.value;
switch (testEvent.key) { switch (testEvent.key) {
@ -67,29 +65,27 @@ public class WriteBatchHandlerTest {
} }
} }
// attempt to read test data back from the WriteBatch by iterating with a handler // attempt to read test data back from the WriteBatch by iterating
handler = new CapturingWriteBatchHandler(); // with a handler
batch.iterate(handler); try (final CapturingWriteBatchHandler handler =
new CapturingWriteBatchHandler()) {
batch.iterate(handler);
// compare the results to the test data // compare the results to the test data
final List<Tuple<Action, Tuple<byte[], byte[]>>> actualEvents = handler.getEvents(); final List<Tuple<Action, Tuple<byte[], byte[]>>> actualEvents =
assertThat(testEvents.size()).isSameAs(actualEvents.size()); handler.getEvents();
assertThat(testEvents.size()).isSameAs(actualEvents.size());
for (int i = 0; i < testEvents.size(); i++) { for (int i = 0; i < testEvents.size(); i++) {
assertThat(equals(testEvents.get(i), actualEvents.get(i))).isTrue(); assertThat(equals(testEvents.get(i), actualEvents.get(i))).isTrue();
} }
} finally {
if (handler != null) {
handler.dispose();
}
if (batch != null) {
batch.dispose();
} }
} }
} }
private static boolean equals(final Tuple<Action, Tuple<byte[], byte[]>> expected, private static boolean equals(
final Tuple<Action, Tuple<byte[], byte[]>> actual) { final Tuple<Action, Tuple<byte[], byte[]>> expected,
final Tuple<Action, Tuple<byte[], byte[]>> actual) {
if (!expected.key.equals(actual.key)) { if (!expected.key.equals(actual.key)) {
return false; return false;
} }
@ -136,7 +132,8 @@ public class WriteBatchHandlerTest {
*/ */
private static class CapturingWriteBatchHandler extends WriteBatch.Handler { private static class CapturingWriteBatchHandler extends WriteBatch.Handler {
private final List<Tuple<Action, Tuple<byte[], byte[]>>> events = new ArrayList<>(); private final List<Tuple<Action, Tuple<byte[], byte[]>>> events
= new ArrayList<>();
/** /**
* Returns a copy of the current events list * Returns a copy of the current events list
@ -159,12 +156,14 @@ public class WriteBatchHandlerTest {
@Override @Override
public void delete(final byte[] key) { public void delete(final byte[] key) {
events.add(new Tuple<>(Action.DELETE, new Tuple<byte[], byte[]>(key, null))); events.add(new Tuple<>(Action.DELETE,
new Tuple<byte[], byte[]>(key, null)));
} }
@Override @Override
public void logData(final byte[] blob) { public void logData(final byte[] blob) {
events.add(new Tuple<>(Action.LOG, new Tuple<byte[], byte[]>(null, blob))); events.add(new Tuple<>(Action.LOG,
new Tuple<byte[], byte[]>(null, blob)));
} }
} }
} }

@ -20,9 +20,9 @@ import static org.assertj.core.api.Assertions.assertThat;
/** /**
* This class mimics the db/write_batch_test.cc * This class mimics the db/write_batch_test.cc
* in the c++ rocksdb library. * in the c++ rocksdb library.
* * <p/>
* Not ported yet: * Not ported yet:
* * <p/>
* Continue(); * Continue();
* PutGatherSlices(); * PutGatherSlices();
*/ */
@ -36,77 +36,83 @@ public class WriteBatchTest {
@Test @Test
public void emptyWriteBatch() { public void emptyWriteBatch() {
WriteBatch batch = new WriteBatch(); try (final WriteBatch batch = new WriteBatch()) {
assertThat(batch.count()).isEqualTo(0); assertThat(batch.count()).isEqualTo(0);
}
} }
@Test @Test
public void multipleBatchOperations() public void multipleBatchOperations()
throws UnsupportedEncodingException { throws UnsupportedEncodingException {
WriteBatch batch = new WriteBatch(); try (WriteBatch batch = new WriteBatch()) {
batch.put("foo".getBytes("US-ASCII"), "bar".getBytes("US-ASCII")); batch.put("foo".getBytes("US-ASCII"), "bar".getBytes("US-ASCII"));
batch.remove("box".getBytes("US-ASCII")); batch.remove("box".getBytes("US-ASCII"));
batch.put("baz".getBytes("US-ASCII"), "boo".getBytes("US-ASCII")); batch.put("baz".getBytes("US-ASCII"), "boo".getBytes("US-ASCII"));
WriteBatchTestInternalHelper.setSequence(batch, 100);
assertThat(WriteBatchTestInternalHelper.sequence(batch)). WriteBatchTestInternalHelper.setSequence(batch, 100);
isNotNull(). assertThat(WriteBatchTestInternalHelper.sequence(batch)).
isEqualTo(100); isNotNull().
assertThat(batch.count()).isEqualTo(3); isEqualTo(100);
assertThat(new String(getContents(batch), "US-ASCII")). assertThat(batch.count()).isEqualTo(3);
isEqualTo("Put(baz, boo)@102" + assertThat(new String(getContents(batch), "US-ASCII")).
"Delete(box)@101" + isEqualTo("Put(baz, boo)@102" +
"Put(foo, bar)@100"); "Delete(box)@101" +
"Put(foo, bar)@100");
}
} }
@Test @Test
public void testAppendOperation() public void testAppendOperation()
throws UnsupportedEncodingException { throws UnsupportedEncodingException {
WriteBatch b1 = new WriteBatch(); try (final WriteBatch b1 = new WriteBatch();
WriteBatch b2 = new WriteBatch(); final WriteBatch b2 = new WriteBatch()) {
WriteBatchTestInternalHelper.setSequence(b1, 200); WriteBatchTestInternalHelper.setSequence(b1, 200);
WriteBatchTestInternalHelper.setSequence(b2, 300); WriteBatchTestInternalHelper.setSequence(b2, 300);
WriteBatchTestInternalHelper.append(b1, b2); WriteBatchTestInternalHelper.append(b1, b2);
assertThat(getContents(b1).length).isEqualTo(0); assertThat(getContents(b1).length).isEqualTo(0);
assertThat(b1.count()).isEqualTo(0); assertThat(b1.count()).isEqualTo(0);
b2.put("a".getBytes("US-ASCII"), "va".getBytes("US-ASCII")); b2.put("a".getBytes("US-ASCII"), "va".getBytes("US-ASCII"));
WriteBatchTestInternalHelper.append(b1, b2); WriteBatchTestInternalHelper.append(b1, b2);
assertThat("Put(a, va)@200".equals(new String(getContents(b1), "US-ASCII"))); assertThat("Put(a, va)@200".equals(new String(getContents(b1),
assertThat(b1.count()).isEqualTo(1); "US-ASCII")));
b2.clear(); assertThat(b1.count()).isEqualTo(1);
b2.put("b".getBytes("US-ASCII"), "vb".getBytes("US-ASCII")); b2.clear();
WriteBatchTestInternalHelper.append(b1, b2); b2.put("b".getBytes("US-ASCII"), "vb".getBytes("US-ASCII"));
assertThat(("Put(a, va)@200" + WriteBatchTestInternalHelper.append(b1, b2);
"Put(b, vb)@201") assertThat(("Put(a, va)@200" +
.equals(new String(getContents(b1), "US-ASCII"))); "Put(b, vb)@201")
assertThat(b1.count()).isEqualTo(2); .equals(new String(getContents(b1), "US-ASCII")));
b2.remove("foo".getBytes("US-ASCII")); assertThat(b1.count()).isEqualTo(2);
WriteBatchTestInternalHelper.append(b1, b2); b2.remove("foo".getBytes("US-ASCII"));
assertThat(("Put(a, va)@200" + WriteBatchTestInternalHelper.append(b1, b2);
"Put(b, vb)@202" + assertThat(("Put(a, va)@200" +
"Put(b, vb)@201" + "Put(b, vb)@202" +
"Delete(foo)@203") "Put(b, vb)@201" +
.equals(new String(getContents(b1), "US-ASCII"))); "Delete(foo)@203")
assertThat(b1.count()).isEqualTo(4); .equals(new String(getContents(b1), "US-ASCII")));
assertThat(b1.count()).isEqualTo(4);
}
} }
@Test @Test
public void blobOperation() public void blobOperation()
throws UnsupportedEncodingException { throws UnsupportedEncodingException {
WriteBatch batch = new WriteBatch(); try (final WriteBatch batch = new WriteBatch()) {
batch.put("k1".getBytes("US-ASCII"), "v1".getBytes("US-ASCII")); batch.put("k1".getBytes("US-ASCII"), "v1".getBytes("US-ASCII"));
batch.put("k2".getBytes("US-ASCII"), "v2".getBytes("US-ASCII")); batch.put("k2".getBytes("US-ASCII"), "v2".getBytes("US-ASCII"));
batch.put("k3".getBytes("US-ASCII"), "v3".getBytes("US-ASCII")); batch.put("k3".getBytes("US-ASCII"), "v3".getBytes("US-ASCII"));
batch.putLogData("blob1".getBytes("US-ASCII")); batch.putLogData("blob1".getBytes("US-ASCII"));
batch.remove("k2".getBytes("US-ASCII")); batch.remove("k2".getBytes("US-ASCII"));
batch.putLogData("blob2".getBytes("US-ASCII")); batch.putLogData("blob2".getBytes("US-ASCII"));
batch.merge("foo".getBytes("US-ASCII"), "bar".getBytes("US-ASCII")); batch.merge("foo".getBytes("US-ASCII"), "bar".getBytes("US-ASCII"));
assertThat(batch.count()).isEqualTo(5); assertThat(batch.count()).isEqualTo(5);
assertThat(("Merge(foo, bar)@4" + assertThat(("Merge(foo, bar)@4" +
"Put(k1, v1)@0" + "Put(k1, v1)@0" +
"Delete(k2)@3" + "Delete(k2)@3" +
"Put(k2, v2)@1" + "Put(k2, v2)@1" +
"Put(k3, v3)@2") "Put(k3, v3)@2")
.equals(new String(getContents(batch), "US-ASCII"))); .equals(new String(getContents(batch), "US-ASCII")));
}
} }
static byte[] getContents(final WriteBatch wb) { static byte[] getContents(final WriteBatch wb) {
@ -133,7 +139,11 @@ class WriteBatchTestInternalHelper {
append(wb1.nativeHandle_, wb2.nativeHandle_); append(wb1.nativeHandle_, wb2.nativeHandle_);
} }
private static native void setSequence(final long writeBatchHandle, final long sn); private static native void setSequence(final long writeBatchHandle,
final long sn);
private static native long sequence(final long writeBatchHandle); private static native long sequence(final long writeBatchHandle);
private static native void append(final long writeBatchHandle1, final long writeBatchHandle2);
private static native void append(final long writeBatchHandle1,
final long writeBatchHandle2);
} }

@ -32,13 +32,9 @@ public class WriteBatchWithIndexTest {
@Test @Test
public void readYourOwnWrites() throws RocksDBException { public void readYourOwnWrites() throws RocksDBException {
RocksDB db = null; try (final Options options = new Options().setCreateIfMissing(true);
Options options = null; final RocksDB db = RocksDB.open(options,
try { dbFolder.getRoot().getAbsolutePath())) {
options = new Options();
// Setup options
options.setCreateIfMissing(true);
db = RocksDB.open(options, dbFolder.getRoot().getAbsolutePath());
final byte[] k1 = "key1".getBytes(); final byte[] k1 = "key1".getBytes();
final byte[] v1 = "value1".getBytes(); final byte[] v1 = "value1".getBytes();
@ -48,13 +44,9 @@ public class WriteBatchWithIndexTest {
db.put(k1, v1); db.put(k1, v1);
db.put(k2, v2); db.put(k2, v2);
final WriteBatchWithIndex wbwi = new WriteBatchWithIndex(true); try (final WriteBatchWithIndex wbwi = new WriteBatchWithIndex(true);
final RocksIterator base = db.newIterator();
RocksIterator base = null; final RocksIterator it = wbwi.newIteratorWithBase(base)) {
RocksIterator it = null;
try {
base = db.newIterator();
it = wbwi.newIteratorWithBase(base);
it.seek(k1); it.seek(k1);
assertThat(it.isValid()).isTrue(); assertThat(it.isValid()).isTrue();
@ -95,169 +87,121 @@ public class WriteBatchWithIndexTest {
assertThat(it.isValid()).isTrue(); assertThat(it.isValid()).isTrue();
assertThat(it.key()).isEqualTo(k1); assertThat(it.key()).isEqualTo(k1);
assertThat(it.value()).isEqualTo(v1Other); assertThat(it.value()).isEqualTo(v1Other);
} finally {
if (it != null) {
it.dispose();
}
if (base != null) {
base.dispose();
}
}
} finally {
if (db != null) {
db.close();
}
if (options != null) {
options.dispose();
} }
} }
} }
@Test @Test
public void write_writeBatchWithIndex() throws RocksDBException { public void write_writeBatchWithIndex() throws RocksDBException {
RocksDB db = null; try (final Options options = new Options().setCreateIfMissing(true);
Options options = null; final RocksDB db = RocksDB.open(options,
try { dbFolder.getRoot().getAbsolutePath())) {
options = new Options();
// Setup options
options.setCreateIfMissing(true);
db = RocksDB.open(options, dbFolder.getRoot().getAbsolutePath());
final byte[] k1 = "key1".getBytes(); final byte[] k1 = "key1".getBytes();
final byte[] v1 = "value1".getBytes(); final byte[] v1 = "value1".getBytes();
final byte[] k2 = "key2".getBytes(); final byte[] k2 = "key2".getBytes();
final byte[] v2 = "value2".getBytes(); final byte[] v2 = "value2".getBytes();
WriteBatchWithIndex wbwi = null; try (final WriteBatchWithIndex wbwi = new WriteBatchWithIndex()) {
try {
wbwi = new WriteBatchWithIndex();
wbwi.put(k1, v1); wbwi.put(k1, v1);
wbwi.put(k2, v2); wbwi.put(k2, v2);
db.write(new WriteOptions(), wbwi); db.write(new WriteOptions(), wbwi);
} finally {
if(wbwi != null) {
wbwi.dispose();
}
} }
assertThat(db.get(k1)).isEqualTo(v1); assertThat(db.get(k1)).isEqualTo(v1);
assertThat(db.get(k2)).isEqualTo(v2); assertThat(db.get(k2)).isEqualTo(v2);
} finally {
if (db != null) {
db.close();
}
if (options != null) {
options.dispose();
}
} }
} }
@Test @Test
public void iterator() throws RocksDBException { public void iterator() throws RocksDBException {
final WriteBatchWithIndex wbwi = new WriteBatchWithIndex(true); try (final WriteBatchWithIndex wbwi = new WriteBatchWithIndex(true)) {
final String k1 = "key1"; final String k1 = "key1";
final String v1 = "value1"; final String v1 = "value1";
final String k2 = "key2"; final String k2 = "key2";
final String v2 = "value2"; final String v2 = "value2";
final String k3 = "key3"; final String k3 = "key3";
final String v3 = "value3"; final String v3 = "value3";
final byte[] k1b = k1.getBytes(); final byte[] k1b = k1.getBytes();
final byte[] v1b = v1.getBytes(); final byte[] v1b = v1.getBytes();
final byte[] k2b = k2.getBytes(); final byte[] k2b = k2.getBytes();
final byte[] v2b = v2.getBytes(); final byte[] v2b = v2.getBytes();
final byte[] k3b = k3.getBytes(); final byte[] k3b = k3.getBytes();
final byte[] v3b = v3.getBytes(); final byte[] v3b = v3.getBytes();
//add put records //add put records
wbwi.put(k1b, v1b); wbwi.put(k1b, v1b);
wbwi.put(k2b, v2b); wbwi.put(k2b, v2b);
wbwi.put(k3b, v3b); wbwi.put(k3b, v3b);
//add a deletion record //add a deletion record
final String k4 = "key4"; final String k4 = "key4";
final byte[] k4b = k4.getBytes(); final byte[] k4b = k4.getBytes();
wbwi.remove(k4b); wbwi.remove(k4b);
WBWIRocksIterator.WriteEntry[] expected = { final WBWIRocksIterator.WriteEntry[] expected = {
new WBWIRocksIterator.WriteEntry(WBWIRocksIterator.WriteType.PUT, new WBWIRocksIterator.WriteEntry(WBWIRocksIterator.WriteType.PUT,
new DirectSlice(k1), new DirectSlice(v1)), new DirectSlice(k1), new DirectSlice(v1)),
new WBWIRocksIterator.WriteEntry(WBWIRocksIterator.WriteType.PUT, new WBWIRocksIterator.WriteEntry(WBWIRocksIterator.WriteType.PUT,
new DirectSlice(k2), new DirectSlice(v2)), new DirectSlice(k2), new DirectSlice(v2)),
new WBWIRocksIterator.WriteEntry(WBWIRocksIterator.WriteType.PUT, new WBWIRocksIterator.WriteEntry(WBWIRocksIterator.WriteType.PUT,
new DirectSlice(k3), new DirectSlice(v3)), new DirectSlice(k3), new DirectSlice(v3)),
new WBWIRocksIterator.WriteEntry(WBWIRocksIterator.WriteType.DELETE, new WBWIRocksIterator.WriteEntry(WBWIRocksIterator.WriteType.DELETE,
new DirectSlice(k4), DirectSlice.NONE) new DirectSlice(k4), DirectSlice.NONE)
}; };
WBWIRocksIterator it = null; try (final WBWIRocksIterator it = wbwi.newIterator()) {
try { //direct access - seek to key offsets
it = wbwi.newIterator(); final int[] testOffsets = {2, 0, 1, 3};
//direct access - seek to key offsets for (int i = 0; i < testOffsets.length; i++) {
final int[] testOffsets = {2, 0, 1, 3}; final int testOffset = testOffsets[i];
final byte[] key = toArray(expected[testOffset].getKey().data());
for(int i = 0; i < testOffsets.length; i++) {
final int testOffset = testOffsets[i]; it.seek(key);
final byte[] key = toArray(expected[testOffset].getKey().data()); assertThat(it.isValid()).isTrue();
it.seek(key); final WBWIRocksIterator.WriteEntry entry = it.entry();
assertThat(it.isValid()).isTrue(); assertThat(entry.equals(expected[testOffset])).isTrue();
}
final WBWIRocksIterator.WriteEntry entry = it.entry();
assertThat(entry.equals(expected[testOffset])).isTrue();
}
//forward iterative access
int i = 0;
for(it.seekToFirst(); it.isValid(); it.next()) {
assertThat(it.entry().equals(expected[i++])).isTrue();
}
//reverse iterative access //forward iterative access
i = expected.length - 1; int i = 0;
for(it.seekToLast(); it.isValid(); it.prev()) { for (it.seekToFirst(); it.isValid(); it.next()) {
assertThat(it.entry().equals(expected[i--])).isTrue(); assertThat(it.entry().equals(expected[i++])).isTrue();
} }
} finally { //reverse iterative access
if(it != null) { i = expected.length - 1;
it.dispose(); for (it.seekToLast(); it.isValid(); it.prev()) {
assertThat(it.entry().equals(expected[i--])).isTrue();
}
} }
} }
} }
@Test @Test
public void zeroByteTests() { public void zeroByteTests() {
final WriteBatchWithIndex wbwi = new WriteBatchWithIndex(true); try (final WriteBatchWithIndex wbwi = new WriteBatchWithIndex(true)) {
byte[] zeroByteValue = new byte[] { 0, 0 }; final byte[] zeroByteValue = new byte[]{0, 0};
//add zero byte value
//add zero byte value wbwi.put(zeroByteValue, zeroByteValue);
wbwi.put(zeroByteValue, zeroByteValue);
final ByteBuffer buffer = ByteBuffer.allocateDirect(zeroByteValue.length);
ByteBuffer buffer = ByteBuffer.allocateDirect(zeroByteValue.length); buffer.put(zeroByteValue);
buffer.put(zeroByteValue);
WBWIRocksIterator.WriteEntry[] expected = {
WBWIRocksIterator.WriteEntry[] expected = { new WBWIRocksIterator.WriteEntry(WBWIRocksIterator.WriteType.PUT,
new WBWIRocksIterator.WriteEntry(WBWIRocksIterator.WriteType.PUT, new DirectSlice(buffer, zeroByteValue.length),
new DirectSlice(buffer, zeroByteValue.length), new DirectSlice(buffer, zeroByteValue.length))
new DirectSlice(buffer, zeroByteValue.length)) };
};
WBWIRocksIterator it = null; try (final WBWIRocksIterator it = wbwi.newIterator()) {
try { it.seekToFirst();
it = wbwi.newIterator(); assertThat(it.entry().equals(expected[0])).isTrue();
it.seekToFirst(); assertThat(it.entry().hashCode() == expected[0].hashCode()).isTrue();
assertThat(it.entry().equals(expected[0])).isTrue();
assertThat(it.entry().hashCode() == expected[0].hashCode()).isTrue();
} finally {
if(it != null) {
it.dispose();
} }
} }
} }

@ -17,15 +17,16 @@ public class WriteOptionsTest {
new RocksMemoryResource(); new RocksMemoryResource();
@Test @Test
public void writeOptions(){ public void writeOptions() {
WriteOptions writeOptions = new WriteOptions(); try (final WriteOptions writeOptions = new WriteOptions()) {
writeOptions.setDisableWAL(true); writeOptions.setDisableWAL(true);
assertThat(writeOptions.disableWAL()).isTrue(); assertThat(writeOptions.disableWAL()).isTrue();
writeOptions.setDisableWAL(false); writeOptions.setDisableWAL(false);
assertThat(writeOptions.disableWAL()).isFalse(); assertThat(writeOptions.disableWAL()).isFalse();
writeOptions.setSync(true); writeOptions.setSync(true);
assertThat(writeOptions.sync()).isTrue(); assertThat(writeOptions.sync()).isTrue();
writeOptions.setSync(false); writeOptions.setSync(false);
assertThat(writeOptions.sync()).isFalse(); assertThat(writeOptions.sync()).isFalse();
}
} }
} }

Loading…
Cancel
Save