Refactored tests to use try-with-resources

main
Adam Retter 9 years ago
parent f8e02c7825
commit 0f2d2fcff6
  1. 58
      java/samples/src/main/java/RocksDBColumnFamilySample.java
  2. 180
      java/samples/src/main/java/RocksDBSample.java
  3. 100
      java/src/test/java/org/rocksdb/AbstractComparatorTest.java
  4. 139
      java/src/test/java/org/rocksdb/BackupEngineTest.java
  5. 200
      java/src/test/java/org/rocksdb/BackupableDBOptionsTest.java
  6. 219
      java/src/test/java/org/rocksdb/BackupableDBTest.java
  7. 24
      java/src/test/java/org/rocksdb/BlockBasedTableConfigTest.java
  8. 63
      java/src/test/java/org/rocksdb/CheckPointTest.java
  9. 447
      java/src/test/java/org/rocksdb/ColumnFamilyOptionsTest.java
  10. 617
      java/src/test/java/org/rocksdb/ColumnFamilyTest.java
  11. 7
      java/src/test/java/org/rocksdb/ComparatorOptionsTest.java
  12. 73
      java/src/test/java/org/rocksdb/ComparatorTest.java
  13. 5
      java/src/test/java/org/rocksdb/CompressionOptionsTest.java
  14. 388
      java/src/test/java/org/rocksdb/DBOptionsTest.java
  15. 64
      java/src/test/java/org/rocksdb/DirectSliceTest.java
  16. 32
      java/src/test/java/org/rocksdb/FilterTest.java
  17. 46
      java/src/test/java/org/rocksdb/FlushTest.java
  18. 54
      java/src/test/java/org/rocksdb/InfoLogLevelTest.java
  19. 58
      java/src/test/java/org/rocksdb/KeyMayExistTest.java
  20. 126
      java/src/test/java/org/rocksdb/LoggerTest.java
  21. 34
      java/src/test/java/org/rocksdb/MemTableTest.java
  22. 283
      java/src/test/java/org/rocksdb/MergeTest.java
  23. 29
      java/src/test/java/org/rocksdb/MixedOptionsTest.java
  24. 2
      java/src/test/java/org/rocksdb/NativeLibraryLoaderTest.java
  25. 739
      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. 396
      java/src/test/java/org/rocksdb/ReadOnlyTest.java
  29. 112
      java/src/test/java/org/rocksdb/ReadOptionsTest.java
  30. 435
      java/src/test/java/org/rocksdb/RocksDBTest.java
  31. 5
      java/src/test/java/org/rocksdb/RocksEnvTest.java
  32. 24
      java/src/test/java/org/rocksdb/RocksIteratorTest.java
  33. 110
      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. 112
      java/src/test/java/org/rocksdb/SnapshotTest.java
  37. 32
      java/src/test/java/org/rocksdb/StatisticsCollectorTest.java
  38. 140
      java/src/test/java/org/rocksdb/TransactionLogIteratorTest.java
  39. 120
      java/src/test/java/org/rocksdb/TtlDBTest.java
  40. 63
      java/src/test/java/org/rocksdb/WriteBatchHandlerTest.java
  41. 30
      java/src/test/java/org/rocksdb/WriteBatchTest.java
  42. 98
      java/src/test/java/org/rocksdb/WriteBatchWithIndexTest.java
  43. 5
      java/src/test/java/org/rocksdb/WriteOptionsTest.java

@ -22,48 +22,35 @@ 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);
try {
// put and get from non-default column family // put and get from non-default column family
db.put(columnFamilyHandles.get(0), new WriteOptions(), db.put(columnFamilyHandles.get(0), new WriteOptions(),
"key".getBytes(), "value".getBytes()); "key".getBytes(), "value".getBytes());
@ -71,24 +58,21 @@ public class RocksDBColumnFamilySample {
"key".getBytes())); "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.put(columnFamilyHandles.get(1), "key3".getBytes(),
"value3".getBytes());
wb.remove(columnFamilyHandles.get(0), "key".getBytes()); wb.remove(columnFamilyHandles.get(0), "key".getBytes());
db.write(new WriteOptions(), wb); db.write(new WriteOptions(), wb);
}
// drop column family // drop column family
db.dropColumnFamily(columnFamilyHandles.get(1)); db.dropColumnFamily(columnFamilyHandles.get(1));
} finally { } finally {
for (ColumnFamilyHandle handle : columnFamilyHandles){ for (final ColumnFamilyHandle handle : columnFamilyHandles) {
handle.dispose(); handle.close();
}
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,14 +28,15 @@ 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);
try (final RocksDB db = RocksDB.open(options, db_path_not_found)) {
assert (false);
} catch (RocksDBException e) { } catch (RocksDBException e) {
System.out.format("caught the expceted exception -- %s\n", e); System.out.format("caught the expected exception -- %s\n", e);
assert(db == null);
} }
try { try {
@ -45,50 +48,48 @@ public class RocksDBSample {
.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);
BlockBasedTableConfig table_options = new BlockBasedTableConfig();
table_options.setBlockCacheSize(64 * SizeUnit.KB) table_options.setBlockCacheSize(64 * SizeUnit.KB)
.setFilter(bloomFilter) .setFilter(bloomFilter)
.setCacheNumShardBits(6) .setCacheNumShardBits(6)
@ -99,38 +100,30 @@ public class RocksDBSample {
.setBlockCacheCompressedSize(64 * SizeUnit.KB) .setBlockCacheCompressedSize(64 * SizeUnit.KB)
.setBlockCacheCompressedNumShardBits(10); .setBlockCacheCompressedNumShardBits(10);
assert(table_options.blockCacheSize() == 64 * SizeUnit.KB); assert (table_options.blockCacheSize() == 64 * SizeUnit.KB);
assert(table_options.cacheNumShardBits() == 6); assert (table_options.cacheNumShardBits() == 6);
assert(table_options.blockSizeDeviation() == 5); assert (table_options.blockSizeDeviation() == 5);
assert(table_options.blockRestartInterval() == 10); assert (table_options.blockRestartInterval() == 10);
assert(table_options.cacheIndexAndFilterBlocks() == true); assert (table_options.cacheIndexAndFilterBlocks() == true);
assert(table_options.hashIndexAllowCollision() == false); assert (table_options.hashIndexAllowCollision() == false);
assert(table_options.blockCacheCompressedSize() == 64 * SizeUnit.KB); assert (table_options.blockCacheCompressedSize() == 64 * SizeUnit.KB);
assert(table_options.blockCacheCompressedNumShardBits() == 10); assert (table_options.blockCacheCompressedNumShardBits() == 10);
options.setTableFormatConfig(table_options); options.setTableFormatConfig(table_options);
assert(options.tableFactoryName().equals("BlockBasedTable")); assert (options.tableFactoryName().equals("BlockBasedTable"));
try { try (final RocksDB db = RocksDB.open(options, db_path)) {
db = RocksDB.open(options, db_path);
db.put("hello".getBytes(), "world".getBytes()); db.put("hello".getBytes(), "world".getBytes());
byte[] value = db.get("hello".getBytes()); byte[] value = db.get("hello".getBytes());
assert("world".equals(new String(value))); assert ("world".equals(new String(value)));
String str = db.getProperty("rocksdb.stats"); String str = db.getProperty("rocksdb.stats");
assert(str != null && !str.equals("")); assert (str != null && !str.equals(""));
} catch (RocksDBException e) { } catch (RocksDBException e) {
System.out.format("[ERROR] caught the unexpceted exception -- %s\n", e); System.out.format("[ERROR] caught the unexpceted exception -- %s\n", e);
assert(db == null); assert (false);
assert(false);
} }
// be sure to release the c++ pointer
db.close();
ReadOptions readOptions = new ReadOptions();
readOptions.setFillCache(false);
try { try (final RocksDB db = RocksDB.open(options, db_path)) {
db = RocksDB.open(options, db_path);
db.put("hello".getBytes(), "world".getBytes()); db.put("hello".getBytes(), "world".getBytes());
byte[] value = db.get("hello".getBytes()); byte[] value = db.get("hello".getBytes());
System.out.format("Get('hello') = %s\n", System.out.format("Get('hello') = %s\n",
@ -152,19 +145,20 @@ public class RocksDBSample {
} }
// 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);
batch.dispose(); }
}
} }
for (int i = 10; i <= 19; ++i) { for (int i = 10; i <= 19; ++i) {
for (int j = 10; j <= 19; ++j) { for (int j = 10; j <= 19; ++j) {
assert(new String( assert (new String(
db.get(String.format("%dx%d", i, j).getBytes())).equals( db.get(String.format("%dx%d", i, j).getBytes())).equals(
String.format("%d", i * j))); String.format("%d", i * j)));
System.out.format("%s ", new String(db.get( System.out.format("%s ", new String(db.get(
@ -172,59 +166,58 @@ public class RocksDBSample {
} }
System.out.println(""); System.out.println("");
} }
writeOpt.dispose();
value = db.get("1x1".getBytes()); value = db.get("1x1".getBytes());
assert(value != null); assert (value != null);
value = db.get("world".getBytes()); value = db.get("world".getBytes());
assert(value == null); assert (value == null);
value = db.get(readOptions, "world".getBytes()); value = db.get(readOptions, "world".getBytes());
assert(value == null); assert (value == null);
byte[] testKey = "asdf".getBytes(); byte[] testKey = "asdf".getBytes();
byte[] testValue = byte[] testValue =
"asdfghjkl;'?><MNBVCXZQWERTYUIOP{+_)(*&^%$#@".getBytes(); "asdfghjkl;'?><MNBVCXZQWERTYUIOP{+_)(*&^%$#@".getBytes();
db.put(testKey, testValue); db.put(testKey, testValue);
byte[] testResult = db.get(testKey); byte[] testResult = db.get(testKey);
assert(testResult != null); assert (testResult != null);
assert(Arrays.equals(testValue, testResult)); assert (Arrays.equals(testValue, testResult));
assert(new String(testValue).equals(new String(testResult))); assert (new String(testValue).equals(new String(testResult)));
testResult = db.get(readOptions, testKey); testResult = db.get(readOptions, testKey);
assert(testResult != null); assert (testResult != null);
assert(Arrays.equals(testValue, testResult)); assert (Arrays.equals(testValue, testResult));
assert(new String(testValue).equals(new String(testResult))); assert (new String(testValue).equals(new String(testResult)));
byte[] insufficientArray = new byte[10]; byte[] insufficientArray = new byte[10];
byte[] enoughArray = new byte[50]; byte[] enoughArray = new byte[50];
int len; int len;
len = db.get(testKey, insufficientArray); len = db.get(testKey, insufficientArray);
assert(len > insufficientArray.length); assert (len > insufficientArray.length);
len = db.get("asdfjkl;".getBytes(), enoughArray); len = db.get("asdfjkl;".getBytes(), enoughArray);
assert(len == RocksDB.NOT_FOUND); assert (len == RocksDB.NOT_FOUND);
len = db.get(testKey, enoughArray); len = db.get(testKey, enoughArray);
assert(len == testValue.length); assert (len == testValue.length);
len = db.get(readOptions, testKey, insufficientArray); len = db.get(readOptions, testKey, insufficientArray);
assert(len > insufficientArray.length); assert (len > insufficientArray.length);
len = db.get(readOptions, "asdfjkl;".getBytes(), enoughArray); len = db.get(readOptions, "asdfjkl;".getBytes(), enoughArray);
assert(len == RocksDB.NOT_FOUND); assert (len == RocksDB.NOT_FOUND);
len = db.get(readOptions, testKey, enoughArray); len = db.get(readOptions, testKey, enoughArray);
assert(len == testValue.length); assert (len == testValue.length);
db.remove(testKey); db.remove(testKey);
len = db.get(testKey, enoughArray); len = db.get(testKey, enoughArray);
assert(len == RocksDB.NOT_FOUND); assert (len == RocksDB.NOT_FOUND);
// repeat the test with WriteOptions // repeat the test with WriteOptions
WriteOptions writeOpts = new WriteOptions(); try (final WriteOptions writeOpts = new WriteOptions()) {
writeOpts.setSync(true); writeOpts.setSync(true);
writeOpts.setDisableWAL(true); writeOpts.setDisableWAL(true);
db.put(writeOpts, testKey, testValue); db.put(writeOpts, testKey, testValue);
len = db.get(testKey, enoughArray); len = db.get(testKey, enoughArray);
assert(len == testValue.length); assert (len == testValue.length);
assert(new String(testValue).equals( assert (new String(testValue).equals(
new String(enoughArray, 0, len))); new String(enoughArray, 0, len)));
writeOpts.dispose(); }
try { try {
for (TickerType statsType : TickerType.values()) { for (TickerType statsType : TickerType.values()) {
@ -233,7 +226,7 @@ public class RocksDBSample {
System.out.println("getTickerCount() passed."); System.out.println("getTickerCount() passed.");
} catch (Exception e) { } catch (Exception e) {
System.out.println("Failed in call to getTickerCount()"); System.out.println("Failed in call to getTickerCount()");
assert(false); //Should never reach here. assert (false); //Should never reach here.
} }
try { try {
@ -243,70 +236,65 @@ public class RocksDBSample {
System.out.println("geHistogramData() passed."); System.out.println("geHistogramData() passed.");
} catch (Exception e) { } catch (Exception e) {
System.out.println("Failed in call to geHistogramData()"); System.out.println("Failed in call to geHistogramData()");
assert(false); //Should never reach here. assert (false); //Should never reach here.
} }
RocksIterator iterator = db.newIterator(); try (final RocksIterator iterator = db.newIterator()) {
boolean seekToFirstPassed = false; boolean seekToFirstPassed = false;
for (iterator.seekToFirst(); iterator.isValid(); iterator.next()) { for (iterator.seekToFirst(); iterator.isValid(); iterator.next()) {
iterator.status(); iterator.status();
assert(iterator.key() != null); assert (iterator.key() != null);
assert(iterator.value() != null); assert (iterator.value() != null);
seekToFirstPassed = true; seekToFirstPassed = true;
} }
if(seekToFirstPassed) { if (seekToFirstPassed) {
System.out.println("iterator seekToFirst tests passed."); System.out.println("iterator seekToFirst tests passed.");
} }
boolean seekToLastPassed = false; boolean seekToLastPassed = false;
for (iterator.seekToLast(); iterator.isValid(); iterator.prev()) { for (iterator.seekToLast(); iterator.isValid(); iterator.prev()) {
iterator.status(); iterator.status();
assert(iterator.key() != null); assert (iterator.key() != null);
assert(iterator.value() != null); assert (iterator.value() != null);
seekToLastPassed = true; seekToLastPassed = true;
} }
if(seekToLastPassed) { if (seekToLastPassed) {
System.out.println("iterator seekToLastPassed tests passed."); System.out.println("iterator seekToLastPassed tests passed.");
} }
iterator.seekToFirst(); iterator.seekToFirst();
iterator.seek(iterator.key()); iterator.seek(iterator.key());
assert(iterator.key() != null); assert (iterator.key() != null);
assert(iterator.value() != null); assert (iterator.value() != null);
System.out.println("iterator seek test passed."); 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) { } catch (RocksDBException e) {
System.err.println(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,36 +40,33 @@ 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());
if (i > 0 && db.get(key) != null) { // does key already exist (avoid duplicates) // 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;
@ -78,18 +76,7 @@ public abstract class AbstractComparatorTest {
lastKey = thisKey; lastKey = thisKey;
count++; count++;
} }
it.dispose();
db.close();
assertThat(count).isEqualTo(ITERATIONS); assertThat(count).isEqualTo(ITERATIONS);
} finally {
if (db != null) {
db.close();
}
if (opt != null) {
opt.dispose();
} }
} }
} }
@ -109,25 +96,25 @@ 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( final List<ColumnFamilyHandle> cfHandles = new ArrayList<>();
getAscendingIntKeyComparator())));
List<ColumnFamilyHandle> cfHandles = new ArrayList<>(); try (final DBOptions opt = new DBOptions().
try {
opt = new DBOptions().
setCreateIfMissing(true). setCreateIfMissing(true).
setCreateMissingColumnFamilies(true); setCreateMissingColumnFamilies(true)) {
// store 10,000 random integer keys // store 10,000 random integer keys
final int ITERATIONS = 10000; final int ITERATIONS = 10000;
db = RocksDB.open(opt, db_path.toString(), cfDescriptors, cfHandles); try (final RocksDB db = RocksDB.open(opt, db_path.toString(),
cfDescriptors, cfHandles)) {
try {
assertThat(cfDescriptors.size()).isEqualTo(2); assertThat(cfDescriptors.size()).isEqualTo(2);
assertThat(cfHandles.size()).isEqualTo(2); assertThat(cfHandles.size()).isEqualTo(2);
@ -141,19 +128,24 @@ public abstract class AbstractComparatorTest {
db.put(cfHandles.get(1), key, "value".getBytes()); db.put(cfHandles.get(1), key, "value".getBytes());
} }
} }
for (ColumnFamilyHandle handle : cfHandles) { } finally {
handle.dispose(); for (final ColumnFamilyHandle handle : cfHandles) {
handle.close();
}
} }
cfHandles.clear(); cfHandles.clear();
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(), cfDescriptors, cfHandles); try (final RocksDB db = RocksDB.open(opt, db_path.toString(),
cfDescriptors, cfHandles);
final RocksIterator it = db.newIterator(cfHandles.get(1))) {
try {
assertThat(cfDescriptors.size()).isEqualTo(2); assertThat(cfDescriptors.size()).isEqualTo(2);
assertThat(cfHandles.size()).isEqualTo(2); assertThat(cfHandles.size()).isEqualTo(2);
final RocksIterator it = db.newIterator(cfHandles.get(1));
it.seekToFirst(); it.seekToFirst();
int lastKey = Integer.MIN_VALUE; int lastKey = Integer.MIN_VALUE;
int count = 0; int count = 0;
@ -164,25 +156,15 @@ public abstract class AbstractComparatorTest {
count++; count++;
} }
it.dispose();
for (ColumnFamilyHandle handle : cfHandles) {
handle.dispose();
}
cfHandles.clear();
db.close();
assertThat(count).isEqualTo(ITERATIONS); assertThat(count).isEqualTo(ITERATIONS);
} finally { } finally {
for (ColumnFamilyHandle handle : cfHandles) { for (final ColumnFamilyHandle handle : cfHandles) {
handle.dispose(); handle.close();
} }
if (db != null) {
db.close();
} }
cfHandles.clear();
if (opt != null) { }
opt.dispose();
} }
} }
} }

@ -28,57 +28,37 @@ public class BackupEngineTest {
@Test @Test
public void backupDb() throws RocksDBException { public void backupDb() throws RocksDBException {
Options opt = null;
RocksDB db = null;
try {
opt = new Options().setCreateIfMissing(true);
// Open empty database. // Open empty database.
db = RocksDB.open(opt, try(final Options opt = new Options().setCreateIfMissing(true);
dbFolder.getRoot().getAbsolutePath()); final RocksDB 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;
RocksDB db = null;
try {
opt = new Options().setCreateIfMissing(true);
// Open empty database. // Open empty database.
db = RocksDB.open(opt, try(final Options opt = new Options().setCreateIfMissing(true);
dbFolder.getRoot().getAbsolutePath()); final RocksDB 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);
final List<BackupInfo> backupInfo = final List<BackupInfo> backupInfo =
@ -92,38 +72,21 @@ public class BackupEngineTest {
assertThat(newBackupInfo.get(0).backupId()). assertThat(newBackupInfo.get(0).backupId()).
isEqualTo(backupInfo.get(1).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;
RocksDB db = null;
try {
opt = new Options().setCreateIfMissing(true);
// Open empty database. // Open empty database.
db = RocksDB.open(opt, try(final Options opt = new Options().setCreateIfMissing(true);
dbFolder.getRoot().getAbsolutePath()); final RocksDB 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 {
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);
be.createNewBackup(db, true); be.createNewBackup(db, true);
@ -138,38 +101,23 @@ public class BackupEngineTest {
assertThat(newBackupInfo.get(0).backupId()). assertThat(newBackupInfo.get(0).backupId()).
isEqualTo(backupInfo.get(3).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; // Open empty database.
RocksDB db = null; RocksDB db = null;
try { try {
opt = new Options().setCreateIfMissing(true);
// Open empty database.
db = RocksDB.open(opt, db = RocksDB.open(opt,
dbFolder.getRoot().getAbsolutePath()); dbFolder.getRoot().getAbsolutePath());
// Fill database with some test values // Fill database with some test values
prepareDatabase(db); prepareDatabase(db);
BackupableDBOptions bopt = null;
try { try (final BackupableDBOptions bopt = new 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,30 +130,26 @@ 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
try(final RestoreOptions ropts = new RestoreOptions(false)) {
be.restoreDbFromLatestBackup(dbFolder.getRoot().getAbsolutePath(), be.restoreDbFromLatestBackup(dbFolder.getRoot().getAbsolutePath(),
dbFolder.getRoot().getAbsolutePath(), dbFolder.getRoot().getAbsolutePath(), ropts);
new RestoreOptions(false)); }
// 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();
}
}
} finally {
if (db != null) {
db.close(); db.close();
} }
if (opt != null) {
opt.dispose();
} }
} }
} }
@ -213,20 +157,17 @@ public class BackupEngineTest {
@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 { try {
opt = new Options().setCreateIfMissing(true);
// Open empty database. // Open empty database.
db = RocksDB.open(opt, db = RocksDB.open(opt,
dbFolder.getRoot().getAbsolutePath()); dbFolder.getRoot().getAbsolutePath());
// Fill database with some test values // Fill database with some test values
prepareDatabase(db); prepareDatabase(db);
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, 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,16 +198,9 @@ 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();
}
}
} finally {
if (db != null) {
db.close(); 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,51 +28,34 @@ 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
@ -82,20 +65,11 @@ public class BackupableDBTest {
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,28 +77,23 @@ 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
@ -132,36 +101,21 @@ public class BackupableDBTest {
// 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
@ -169,24 +123,15 @@ public class BackupableDBTest {
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,19 +139,15 @@ 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
@ -226,7 +167,7 @@ public class BackupableDBTest {
} }
} }
// init RestoreBackupableDB // init RestoreBackupableDB
rdb = new RestoreBackupableDB(bopt); try (final RestoreBackupableDB rdb = new RestoreBackupableDB(bopt)) {
// the same number of backups must // the same number of backups must
// exist using RestoreBackupableDB. // exist using RestoreBackupableDB.
verifyNumberOfValidBackups(rdb, 4); verifyNumberOfValidBackups(rdb, 4);
@ -234,18 +175,7 @@ public class BackupableDBTest {
infos = verifyNumberOfValidBackups(rdb, 1); infos = verifyNumberOfValidBackups(rdb, 1);
assertThat(infos.get(0).timestamp()). assertThat(infos.get(0).timestamp()).
isEqualTo(maxTimeBeforePurge); isEqualTo(maxTimeBeforePurge);
} finally {
if (bdb != null) {
bdb.close();
}
if (rdb != null) {
rdb.dispose();
} }
if (bopt != null) {
bopt.dispose();
}
if (opt != null) {
opt.dispose();
} }
} }
} }
@ -253,19 +183,15 @@ 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);
@ -278,33 +204,23 @@ public class BackupableDBTest {
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. // Open database again.
bdb = BackupableDB.open(opt, bopt, try (final BackupableDB bdb = BackupableDB.open(opt, bopt,
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(bdb.get("key1".getBytes()))).endsWith("V2"); assertThat(new String(bdb.get("key1".getBytes()))).endsWith("V2");
assertThat(new String(bdb.get("key2".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();
} }
} }
} }
@ -312,19 +228,14 @@ 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);
@ -337,34 +248,24 @@ public class BackupableDBTest {
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. // Open database again.
bdb = BackupableDB.open(opt, bopt, try (final BackupableDB bdb = BackupableDB.open(opt, bopt,
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(bdb.get("key1".getBytes()))).endsWith("V1"); assertThat(new String(bdb.get("key1".getBytes()))).endsWith("V1");
assertThat(new String(bdb.get("key2".getBytes()))).endsWith("V1"); assertThat(new String(bdb.get("key2".getBytes()))).endsWith("V1");
} finally {
if (bdb != null) {
bdb.close();
}
if (rdb != null) {
rdb.dispose();
}
if (bopt != null) {
bopt.dispose();
}
if (opt != null) {
opt.dispose();
} }
} }
} }
@ -377,8 +278,8 @@ public class BackupableDBTest {
* @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);
@ -398,7 +299,7 @@ public class BackupableDBTest {
* 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).
@ -417,7 +318,7 @@ public class BackupableDBTest {
* @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 = RocksDB.open(options,
dbFolder.getRoot().getAbsolutePath());
db.put("key".getBytes(), "value".getBytes()); db.put("key".getBytes(), "value".getBytes());
checkpoint = Checkpoint.create(db); try (final Checkpoint checkpoint = Checkpoint.create(db)) {
checkpoint.createCheckpoint(checkpointFolder. checkpoint.createCheckpoint(checkpointFolder.
getRoot().getAbsolutePath() + "/snapshot1"); getRoot().getAbsolutePath() + "/snapshot1");
db.put("key2".getBytes(), "value2".getBytes()); db.put("key2".getBytes(), "value2".getBytes());
checkpoint.createCheckpoint(checkpointFolder. checkpoint.createCheckpoint(checkpointFolder.
getRoot().getAbsolutePath() + "/snapshot2"); getRoot().getAbsolutePath() + "/snapshot2");
db.close(); }
db = RocksDB.open(options, }
try (final RocksDB db = RocksDB.open(options,
checkpointFolder.getRoot().getAbsolutePath() + checkpointFolder.getRoot().getAbsolutePath() +
"/snapshot1"); "/snapshot1")) {
assertThat(new String(db.get("key".getBytes()))). assertThat(new String(db.get("key".getBytes()))).
isEqualTo("value"); isEqualTo("value");
assertThat(db.get("key2".getBytes())).isNull(); assertThat(db.get("key2".getBytes())).isNull();
db.close(); }
db = RocksDB.open(options,
try (final RocksDB db = RocksDB.open(options,
checkpointFolder.getRoot().getAbsolutePath() + checkpointFolder.getRoot().getAbsolutePath() +
"/snapshot2"); "/snapshot2")) {
assertThat(new String(db.get("key".getBytes()))). assertThat(new String(db.get("key".getBytes()))).
isEqualTo("value"); isEqualTo("value");
assertThat(new String(db.get("key2".getBytes()))). assertThat(new String(db.get("key2".getBytes()))).
isEqualTo("value2"); isEqualTo("value2");
} finally {
if (db != null) {
db.close();
}
if (options != null) {
options.dispose();
}
if (checkpoint != null) {
checkpoint.dispose();
} }
} }
} }
@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())) {
db.close();
Checkpoint.create(db); 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;
try {
// setup sample properties
Properties properties = new Properties(); Properties properties = new Properties();
properties.put("write_buffer_size", "112"); properties.put("write_buffer_size", "112");
properties.put("max_write_buffer_number", "13"); properties.put("max_write_buffer_number", "13");
opt = ColumnFamilyOptions.
getColumnFamilyOptionsFromProps(properties); try (final ColumnFamilyOptions opt = ColumnFamilyOptions.
getColumnFamilyOptionsFromProps(properties)) {
// setup sample 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;
try {
// setup sample properties // setup sample properties
Properties properties = new Properties(); final Properties properties = new Properties();
properties.put("tomato", "1024"); properties.put("tomato", "1024");
properties.put("burger", "2"); properties.put("burger", "2");
opt = ColumnFamilyOptions.
getColumnFamilyOptionsFromProps(properties); try (final ColumnFamilyOptions opt =
ColumnFamilyOptions.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() {
try (final ColumnFamilyOptions opt =
ColumnFamilyOptions.getColumnFamilyOptionsFromProps( ColumnFamilyOptions.getColumnFamilyOptionsFromProps(
new Properties()); 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();
}
} }
} }
} }

@ -25,43 +25,26 @@ public class ColumnFamilyTest {
@Test @Test
public void listColumnFamilies() throws RocksDBException { public void listColumnFamilies() 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();
options.setCreateIfMissing(true);
DBOptions dbOptions = new DBOptions();
dbOptions.setCreateIfMissing(true);
db = RocksDB.open(options, dbFolder.getRoot().getAbsolutePath());
// Test listColumnFamilies // Test listColumnFamilies
List<byte[]> columnFamilyNames; final List<byte[]> columnFamilyNames = RocksDB.listColumnFamilies(options,
columnFamilyNames = RocksDB.listColumnFamilies(options, dbFolder.getRoot().getAbsolutePath()); dbFolder.getRoot().getAbsolutePath());
assertThat(columnFamilyNames).isNotNull(); assertThat(columnFamilyNames).isNotNull();
assertThat(columnFamilyNames.size()).isGreaterThan(0); assertThat(columnFamilyNames.size()).isGreaterThan(0);
assertThat(columnFamilyNames.size()).isEqualTo(1); assertThat(columnFamilyNames.size()).isEqualTo(1);
assertThat(new String(columnFamilyNames.get(0))).isEqualTo("default"); assertThat(new String(columnFamilyNames.get(0))).isEqualTo("default");
} finally {
if (db != null) {
db.close();
}
if (options != null) {
options.dispose();
}
} }
} }
@Test @Test
public void defaultColumnFamily() throws RocksDBException { public void defaultColumnFamily() throws RocksDBException {
RocksDB db = null; try (final Options options = new Options().setCreateIfMissing(true);
Options options = null; final RocksDB db = RocksDB.open(options,
ColumnFamilyHandle cfh; dbFolder.getRoot().getAbsolutePath())) {
final ColumnFamilyHandle cfh = db.getDefaultColumnFamily();
try { try {
options = new Options().setCreateIfMissing(true);
db = RocksDB.open(options, dbFolder.getRoot().getAbsolutePath());
cfh = db.getDefaultColumnFamily();
assertThat(cfh).isNotNull(); assertThat(cfh).isNotNull();
final byte[] key = "key".getBytes(); final byte[] key = "key".getBytes();
@ -74,66 +57,52 @@ public class ColumnFamilyTest {
assertThat(cfh).isNotNull(); assertThat(cfh).isNotNull();
assertThat(actualValue).isEqualTo(value); assertThat(actualValue).isEqualTo(value);
} finally { } finally {
if (db != null) { cfh.close();
db.close();
}
if (options != null) {
options.dispose();
} }
} }
} }
@Test @Test
public void createColumnFamily() throws RocksDBException { public void createColumnFamily() throws RocksDBException {
RocksDB db = null; try (final Options options = new Options().setCreateIfMissing(true);
Options options = null; final RocksDB db = RocksDB.open(options,
ColumnFamilyHandle columnFamilyHandle = null; dbFolder.getRoot().getAbsolutePath())) {
final ColumnFamilyHandle columnFamilyHandle = db.createColumnFamily(
new ColumnFamilyDescriptor("new_cf".getBytes(),
new ColumnFamilyOptions()));
try { try {
options = new Options(); final List<byte[]> columnFamilyNames = RocksDB.listColumnFamilies(
options.setCreateIfMissing(true); options, dbFolder.getRoot().getAbsolutePath());
db = RocksDB.open(options, dbFolder.getRoot().getAbsolutePath());
columnFamilyHandle = db.createColumnFamily(
new ColumnFamilyDescriptor("new_cf".getBytes(), new ColumnFamilyOptions()));
List<byte[]> columnFamilyNames;
columnFamilyNames = RocksDB.listColumnFamilies(options, dbFolder.getRoot().getAbsolutePath());
assertThat(columnFamilyNames).isNotNull(); assertThat(columnFamilyNames).isNotNull();
assertThat(columnFamilyNames.size()).isGreaterThan(0); assertThat(columnFamilyNames.size()).isGreaterThan(0);
assertThat(columnFamilyNames.size()).isEqualTo(2); assertThat(columnFamilyNames.size()).isEqualTo(2);
assertThat(new String(columnFamilyNames.get(0))).isEqualTo("default"); assertThat(new String(columnFamilyNames.get(0))).isEqualTo("default");
assertThat(new String(columnFamilyNames.get(1))).isEqualTo("new_cf"); assertThat(new String(columnFamilyNames.get(1))).isEqualTo("new_cf");
} finally { } finally {
if (columnFamilyHandle != null) { columnFamilyHandle.close();
columnFamilyHandle.dispose();
}
if (db != null) {
db.close();
}
if (options != null) {
options.dispose();
} }
} }
} }
@Test @Test
public void openWithColumnFamilies() throws RocksDBException { public void openWithColumnFamilies() throws RocksDBException {
RocksDB db = null; final List<ColumnFamilyDescriptor> cfNames = Arrays.asList(
DBOptions options = null; new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY),
List<ColumnFamilyDescriptor> cfNames = new ColumnFamilyDescriptor("new_cf".getBytes())
new ArrayList<>(); );
List<ColumnFamilyHandle> columnFamilyHandleList =
final List<ColumnFamilyHandle> columnFamilyHandleList =
new ArrayList<>(); new ArrayList<>();
try {
options = new DBOptions();
options.setCreateIfMissing(true);
options.setCreateMissingColumnFamilies(true);
// Test open database with column family names // Test open database with column family names
cfNames.add(new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY)); try (final DBOptions options = new DBOptions()
cfNames.add(new ColumnFamilyDescriptor("new_cf".getBytes())); .setCreateIfMissing(true)
.setCreateMissingColumnFamilies(true);
final RocksDB db = RocksDB.open(options,
dbFolder.getRoot().getAbsolutePath(), cfNames,
columnFamilyHandleList)) {
db = RocksDB.open(options, dbFolder.getRoot().getAbsolutePath(), try {
cfNames, columnFamilyHandleList);
assertThat(columnFamilyHandleList.size()).isEqualTo(2); assertThat(columnFamilyHandleList.size()).isEqualTo(2);
db.put("dfkey1".getBytes(), "dfvalue".getBytes()); db.put("dfkey1".getBytes(), "dfvalue".getBytes());
db.put(columnFamilyHandleList.get(0), "dfkey2".getBytes(), db.put(columnFamilyHandleList.get(0), "dfkey2".getBytes(),
@ -154,43 +123,38 @@ public class ColumnFamilyTest {
assertThat(db.get(columnFamilyHandleList.get(0), new ReadOptions(), assertThat(db.get(columnFamilyHandleList.get(0), new ReadOptions(),
"dfkey2".getBytes())).isNull(); "dfkey2".getBytes())).isNull();
} 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();
} }
} }
} }
@Test @Test
public void getWithOutValueAndCf() throws RocksDBException { public void getWithOutValueAndCf() throws RocksDBException {
RocksDB db = null; final List<ColumnFamilyDescriptor> cfDescriptors = Arrays.asList(
DBOptions options = null; new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY));
List<ColumnFamilyDescriptor> cfDescriptors = final List<ColumnFamilyHandle> columnFamilyHandleList = new ArrayList<>();
new ArrayList<>();
List<ColumnFamilyHandle> columnFamilyHandleList =
new ArrayList<>();
try {
options = new DBOptions();
options.setCreateIfMissing(true);
options.setCreateMissingColumnFamilies(true);
// Test open database with column family names // Test open database with column family names
cfDescriptors.add(new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY)); try (final DBOptions options = new DBOptions()
db = RocksDB.open(options, dbFolder.getRoot().getAbsolutePath(), .setCreateIfMissing(true)
cfDescriptors, columnFamilyHandleList); .setCreateMissingColumnFamilies(true);
final RocksDB db = RocksDB.open(options,
dbFolder.getRoot().getAbsolutePath(), cfDescriptors,
columnFamilyHandleList)) {
try {
db.put(columnFamilyHandleList.get(0), new WriteOptions(), db.put(columnFamilyHandleList.get(0), new WriteOptions(),
"key1".getBytes(), "value".getBytes()); "key1".getBytes(), "value".getBytes());
db.put("key2".getBytes(), "12345678".getBytes()); db.put("key2".getBytes(), "12345678".getBytes());
byte[] outValue = new byte[5]; final byte[] outValue = new byte[5];
// not found value // not found value
int getResult = db.get("keyNotFound".getBytes(), outValue); int getResult = db.get("keyNotFound".getBytes(), outValue);
assertThat(getResult).isEqualTo(RocksDB.NOT_FOUND); assertThat(getResult).isEqualTo(RocksDB.NOT_FOUND);
// found value which fits in outValue // found value which fits in outValue
getResult = db.get(columnFamilyHandleList.get(0), "key1".getBytes(), outValue); getResult = db.get(columnFamilyHandleList.get(0), "key1".getBytes(),
outValue);
assertThat(getResult).isNotEqualTo(RocksDB.NOT_FOUND); assertThat(getResult).isNotEqualTo(RocksDB.NOT_FOUND);
assertThat(outValue).isEqualTo("value".getBytes()); assertThat(outValue).isEqualTo("value".getBytes());
// found value which fits partially // found value which fits partially
@ -199,79 +163,62 @@ public class ColumnFamilyTest {
assertThat(getResult).isNotEqualTo(RocksDB.NOT_FOUND); assertThat(getResult).isNotEqualTo(RocksDB.NOT_FOUND);
assertThat(outValue).isEqualTo("12345".getBytes()); assertThat(outValue).isEqualTo("12345".getBytes());
} 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();
} }
} }
} }
@Test @Test
public void createWriteDropColumnFamily() throws RocksDBException { public void createWriteDropColumnFamily() throws RocksDBException {
RocksDB db = null; final List<ColumnFamilyDescriptor> cfDescriptors = Arrays.asList(
DBOptions opt = null; new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY),
new ColumnFamilyDescriptor("new_cf".getBytes()));
final List<ColumnFamilyHandle> columnFamilyHandleList = new ArrayList<>();
try (final DBOptions options = new DBOptions()
.setCreateIfMissing(true)
.setCreateMissingColumnFamilies(true);
final RocksDB db = RocksDB.open(options,
dbFolder.getRoot().getAbsolutePath(), cfDescriptors,
columnFamilyHandleList)) {
ColumnFamilyHandle tmpColumnFamilyHandle = null; ColumnFamilyHandle tmpColumnFamilyHandle = null;
List<ColumnFamilyDescriptor> cfNames =
new ArrayList<>();
List<ColumnFamilyHandle> columnFamilyHandleList =
new ArrayList<>();
try { try {
opt = new DBOptions();
opt.setCreateIfMissing(true);
opt.setCreateMissingColumnFamilies(true);
cfNames.add(new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY));
cfNames.add(new ColumnFamilyDescriptor("new_cf".getBytes()));
db = RocksDB.open(opt, dbFolder.getRoot().getAbsolutePath(),
cfNames, columnFamilyHandleList);
tmpColumnFamilyHandle = db.createColumnFamily( tmpColumnFamilyHandle = db.createColumnFamily(
new ColumnFamilyDescriptor("tmpCF".getBytes(), new ColumnFamilyOptions())); new ColumnFamilyDescriptor("tmpCF".getBytes(),
new ColumnFamilyOptions()));
db.put(tmpColumnFamilyHandle, "key".getBytes(), "value".getBytes()); db.put(tmpColumnFamilyHandle, "key".getBytes(), "value".getBytes());
db.dropColumnFamily(tmpColumnFamilyHandle); db.dropColumnFamily(tmpColumnFamilyHandle);
tmpColumnFamilyHandle.dispose();
} finally { } finally {
for (ColumnFamilyHandle columnFamilyHandle : columnFamilyHandleList) {
columnFamilyHandle.dispose();
}
if (tmpColumnFamilyHandle != null) { if (tmpColumnFamilyHandle != null) {
tmpColumnFamilyHandle.dispose(); tmpColumnFamilyHandle.close();
} }
if (db != null) { for (ColumnFamilyHandle columnFamilyHandle : columnFamilyHandleList) {
db.close(); columnFamilyHandle.close();
} }
if (opt != null) {
opt.dispose();
} }
} }
} }
@Test @Test
public void writeBatch() throws RocksDBException { public void writeBatch() throws RocksDBException {
RocksDB db = null; try (final ColumnFamilyOptions defaultCfOptions = new ColumnFamilyOptions()
DBOptions opt = null; .setMergeOperator(new StringAppendOperator())) {
List<ColumnFamilyDescriptor> cfNames = final List<ColumnFamilyDescriptor> cfDescriptors = Arrays.asList(
new ArrayList<>(); new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY,
List<ColumnFamilyHandle> columnFamilyHandleList = defaultCfOptions),
new ArrayList<>(); new ColumnFamilyDescriptor("new_cf".getBytes()));
final List<ColumnFamilyHandle> columnFamilyHandleList = new ArrayList<>();
try (final DBOptions options = new DBOptions()
.setCreateIfMissing(true)
.setCreateMissingColumnFamilies(true);
final RocksDB db = RocksDB.open(options,
dbFolder.getRoot().getAbsolutePath(),
cfDescriptors, columnFamilyHandleList);
final WriteBatch writeBatch = new WriteBatch();
final WriteOptions writeOpt = new WriteOptions()) {
try { try {
opt = new DBOptions();
opt.setCreateIfMissing(true);
opt.setCreateMissingColumnFamilies(true);
cfNames.add(new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY,
new ColumnFamilyOptions().setMergeOperator(new StringAppendOperator())));
cfNames.add(new ColumnFamilyDescriptor("new_cf".getBytes()));
db = RocksDB.open(opt, dbFolder.getRoot().getAbsolutePath(),
cfNames, columnFamilyHandleList);
WriteBatch writeBatch = new WriteBatch();
WriteOptions writeOpt = new WriteOptions();
writeBatch.put("key".getBytes(), "value".getBytes()); writeBatch.put("key".getBytes(), "value".getBytes());
writeBatch.put(db.getDefaultColumnFamily(), writeBatch.put(db.getDefaultColumnFamily(),
"mergeKey".getBytes(), "merge".getBytes()); "mergeKey".getBytes(), "merge".getBytes());
@ -284,7 +231,7 @@ public class ColumnFamilyTest {
writeBatch.remove("xyz".getBytes()); writeBatch.remove("xyz".getBytes());
writeBatch.remove(columnFamilyHandleList.get(1), "xyz".getBytes()); writeBatch.remove(columnFamilyHandleList.get(1), "xyz".getBytes());
db.write(writeOpt, writeBatch); db.write(writeOpt, writeBatch);
writeBatch.dispose();
assertThat(db.get(columnFamilyHandleList.get(1), assertThat(db.get(columnFamilyHandleList.get(1),
"xyz".getBytes()) == null); "xyz".getBytes()) == null);
assertThat(new String(db.get(columnFamilyHandleList.get(1), assertThat(new String(db.get(columnFamilyHandleList.get(1),
@ -296,43 +243,35 @@ public class ColumnFamilyTest {
assertThat(new String(db.get(db.getDefaultColumnFamily(), assertThat(new String(db.get(db.getDefaultColumnFamily(),
"mergeKey".getBytes()))).isEqualTo("merge,merge"); "mergeKey".getBytes()))).isEqualTo("merge,merge");
} finally { } finally {
for (ColumnFamilyHandle columnFamilyHandle : columnFamilyHandleList) { for (final ColumnFamilyHandle columnFamilyHandle :
columnFamilyHandle.dispose(); columnFamilyHandleList) {
columnFamilyHandle.close();
} }
if (db != null) {
db.close();
} }
if (opt != null) {
opt.dispose();
} }
} }
} }
@Test @Test
public void iteratorOnColumnFamily() throws RocksDBException { public void iteratorOnColumnFamily() throws RocksDBException {
RocksDB db = null; final List<ColumnFamilyDescriptor> cfDescriptors = Arrays.asList(
DBOptions options = null; new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY),
RocksIterator rocksIterator = null; new ColumnFamilyDescriptor("new_cf".getBytes()));
List<ColumnFamilyDescriptor> cfNames = final List<ColumnFamilyHandle> columnFamilyHandleList = new ArrayList<>();
new ArrayList<>(); try (final DBOptions options = new DBOptions()
List<ColumnFamilyHandle> columnFamilyHandleList = .setCreateIfMissing(true)
new ArrayList<>(); .setCreateMissingColumnFamilies(true);
final RocksDB db = RocksDB.open(options,
dbFolder.getRoot().getAbsolutePath(),
cfDescriptors, columnFamilyHandleList)) {
try { try {
options = new DBOptions();
options.setCreateIfMissing(true);
options.setCreateMissingColumnFamilies(true);
cfNames.add(new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY));
cfNames.add(new ColumnFamilyDescriptor("new_cf".getBytes()));
db = RocksDB.open(options, dbFolder.getRoot().getAbsolutePath(),
cfNames, columnFamilyHandleList);
db.put(columnFamilyHandleList.get(1), "newcfkey".getBytes(), db.put(columnFamilyHandleList.get(1), "newcfkey".getBytes(),
"value".getBytes()); "value".getBytes());
db.put(columnFamilyHandleList.get(1), "newcfkey2".getBytes(), db.put(columnFamilyHandleList.get(1), "newcfkey2".getBytes(),
"value2".getBytes()); "value2".getBytes());
rocksIterator = db.newIterator( try (final RocksIterator rocksIterator =
columnFamilyHandleList.get(1)); db.newIterator(columnFamilyHandleList.get(1))) {
rocksIterator.seekToFirst(); rocksIterator.seekToFirst();
Map<String, String> refMap = new HashMap<>(); Map<String, String> refMap = new HashMap<>();
refMap.put("newcfkey", "value"); refMap.put("newcfkey", "value");
@ -345,88 +284,73 @@ public class ColumnFamilyTest {
rocksIterator.next(); rocksIterator.next();
} }
assertThat(i).isEqualTo(2); assertThat(i).isEqualTo(2);
rocksIterator.dispose();
} finally {
if (rocksIterator != null) {
rocksIterator.dispose();
}
for (ColumnFamilyHandle columnFamilyHandle : columnFamilyHandleList) {
columnFamilyHandle.dispose();
} }
if (db != null) { } finally {
db.close(); for (final ColumnFamilyHandle columnFamilyHandle :
columnFamilyHandleList) {
columnFamilyHandle.close();
} }
if (options != null) {
options.dispose();
} }
} }
} }
@Test @Test
public void multiGet() throws RocksDBException { public void multiGet() 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<>(); final List<ColumnFamilyHandle> columnFamilyHandleList = new ArrayList<>();
List<ColumnFamilyHandle> columnFamilyHandleList = try (final DBOptions options = new DBOptions()
new ArrayList<>(); .setCreateIfMissing(true)
.setCreateMissingColumnFamilies(true);
final RocksDB db = RocksDB.open(options,
dbFolder.getRoot().getAbsolutePath(),
cfDescriptors, columnFamilyHandleList)) {
try { try {
options = new DBOptions(); db.put(columnFamilyHandleList.get(0), "key".getBytes(),
options.setCreateIfMissing(true); "value".getBytes());
options.setCreateMissingColumnFamilies(true); db.put(columnFamilyHandleList.get(1), "newcfkey".getBytes(),
"value".getBytes());
cfDescriptors.add(new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY));
cfDescriptors.add(new ColumnFamilyDescriptor("new_cf".getBytes()));
db = RocksDB.open(options, dbFolder.getRoot().getAbsolutePath(),
cfDescriptors, columnFamilyHandleList);
db.put(columnFamilyHandleList.get(0), "key".getBytes(), "value".getBytes());
db.put(columnFamilyHandleList.get(1), "newcfkey".getBytes(), "value".getBytes());
List<byte[]> keys = Arrays.asList(new byte[][]{"key".getBytes(), "newcfkey".getBytes()}); final List<byte[]> keys = Arrays.asList(new byte[][]{
Map<byte[], byte[]> retValues = db.multiGet(columnFamilyHandleList, keys); "key".getBytes(), "newcfkey".getBytes()
});
Map<byte[], byte[]> retValues = db.multiGet(columnFamilyHandleList,
keys);
assertThat(retValues.size()).isEqualTo(2); assertThat(retValues.size()).isEqualTo(2);
assertThat(new String(retValues.get(keys.get(0)))) assertThat(new String(retValues.get(keys.get(0))))
.isEqualTo("value"); .isEqualTo("value");
assertThat(new String(retValues.get(keys.get(1)))) assertThat(new String(retValues.get(keys.get(1))))
.isEqualTo("value"); .isEqualTo("value");
retValues = db.multiGet(new ReadOptions(), columnFamilyHandleList, keys); retValues = db.multiGet(new ReadOptions(), columnFamilyHandleList,
keys);
assertThat(retValues.size()).isEqualTo(2); assertThat(retValues.size()).isEqualTo(2);
assertThat(new String(retValues.get(keys.get(0)))) assertThat(new String(retValues.get(keys.get(0))))
.isEqualTo("value"); .isEqualTo("value");
assertThat(new String(retValues.get(keys.get(1)))) assertThat(new String(retValues.get(keys.get(1))))
.isEqualTo("value"); .isEqualTo("value");
} 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();
} }
} }
} }
@Test @Test
public void properties() throws RocksDBException { public void properties() throws RocksDBException {
RocksDB db = null; final List<ColumnFamilyDescriptor> cfDescriptors = Arrays.asList(
DBOptions options = null; new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY),
List<ColumnFamilyDescriptor> cfNames = new ColumnFamilyDescriptor("new_cf".getBytes()));
new ArrayList<>(); final List<ColumnFamilyHandle> columnFamilyHandleList = new ArrayList<>();
List<ColumnFamilyHandle> columnFamilyHandleList = try (final DBOptions options = new DBOptions()
new ArrayList<>(); .setCreateIfMissing(true)
.setCreateMissingColumnFamilies(true);
final RocksDB db = RocksDB.open(options,
dbFolder.getRoot().getAbsolutePath(),
cfDescriptors, columnFamilyHandleList)) {
try { try {
options = new DBOptions();
options.setCreateIfMissing(true);
options.setCreateMissingColumnFamilies(true);
cfNames.add(new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY));
cfNames.add(new ColumnFamilyDescriptor("new_cf".getBytes()));
db = RocksDB.open(options, dbFolder.getRoot().getAbsolutePath(),
cfNames, columnFamilyHandleList);
assertThat(db.getProperty("rocksdb.estimate-num-keys")). assertThat(db.getProperty("rocksdb.estimate-num-keys")).
isNotNull(); isNotNull();
assertThat(db.getLongProperty(columnFamilyHandleList.get(0), assertThat(db.getLongProperty(columnFamilyHandleList.get(0),
@ -441,14 +365,10 @@ public class ColumnFamilyTest {
assertThat(db.getProperty(columnFamilyHandleList.get(1), assertThat(db.getProperty(columnFamilyHandleList.get(1),
"rocksdb.sstables")).isNotNull(); "rocksdb.sstables")).isNotNull();
} 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();
} }
} }
} }
@ -456,28 +376,23 @@ public class ColumnFamilyTest {
@Test @Test
public void iterators() throws RocksDBException { public void iterators() throws RocksDBException {
RocksDB db = null; final List<ColumnFamilyDescriptor> cfDescriptors = Arrays.asList(
DBOptions options = null; new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY),
List<ColumnFamilyDescriptor> cfNames = new ColumnFamilyDescriptor("new_cf".getBytes()));
new ArrayList<>(); final List<ColumnFamilyHandle> columnFamilyHandleList = new ArrayList<>();
List<ColumnFamilyHandle> columnFamilyHandleList = try (final DBOptions options = new DBOptions()
new ArrayList<>(); .setCreateIfMissing(true)
.setCreateMissingColumnFamilies(true);
final RocksDB db = RocksDB.open(options,
dbFolder.getRoot().getAbsolutePath(), cfDescriptors,
columnFamilyHandleList)) {
List<RocksIterator> iterators = null; List<RocksIterator> iterators = null;
try { try {
options = new DBOptions();
options.setCreateIfMissing(true);
options.setCreateMissingColumnFamilies(true);
cfNames.add(new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY));
cfNames.add(new ColumnFamilyDescriptor("new_cf".getBytes()));
db = RocksDB.open(options, dbFolder.getRoot().getAbsolutePath(),
cfNames, columnFamilyHandleList);
iterators = db.newIterators(columnFamilyHandleList); iterators = db.newIterators(columnFamilyHandleList);
assertThat(iterators.size()).isEqualTo(2); assertThat(iterators.size()).isEqualTo(2);
RocksIterator iter = iterators.get(0); RocksIterator iter = iterators.get(0);
iter.seekToFirst(); iter.seekToFirst();
Map<String, String> defRefMap = new HashMap<>(); final Map<String, String> defRefMap = new HashMap<>();
defRefMap.put("dfkey1", "dfvalue"); defRefMap.put("dfkey1", "dfvalue");
defRefMap.put("key", "value"); defRefMap.put("key", "value");
while (iter.isValid()) { while (iter.isValid()) {
@ -486,7 +401,7 @@ public class ColumnFamilyTest {
iter.next(); iter.next();
} }
// iterate over new_cf key/value pairs // iterate over new_cf key/value pairs
Map<String, String> cfRefMap = new HashMap<>(); final Map<String, String> cfRefMap = new HashMap<>();
cfRefMap.put("newcfkey", "value"); cfRefMap.put("newcfkey", "value");
cfRefMap.put("newcfkey2", "value2"); cfRefMap.put("newcfkey2", "value2");
iter = iterators.get(1); iter = iterators.get(1);
@ -498,247 +413,193 @@ public class ColumnFamilyTest {
} }
} finally { } finally {
if (iterators != null) { if (iterators != null) {
for (RocksIterator rocksIterator : iterators) { for (final RocksIterator rocksIterator : iterators) {
rocksIterator.dispose(); rocksIterator.close();
}
} }
for (ColumnFamilyHandle columnFamilyHandle : columnFamilyHandleList) {
columnFamilyHandle.dispose();
} }
if (db != null) { for (final ColumnFamilyHandle columnFamilyHandle :
db.close(); columnFamilyHandleList) {
columnFamilyHandle.close();
} }
if (options != null) {
options.dispose();
} }
} }
} }
@Test(expected = RocksDBException.class) @Test(expected = RocksDBException.class)
public void failPutDisposedCF() throws RocksDBException { public void failPutDisposedCF() throws RocksDBException {
RocksDB db = null; final List<ColumnFamilyDescriptor> cfDescriptors = Arrays.asList(
DBOptions options = null; new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY),
List<ColumnFamilyDescriptor> cfNames = new ColumnFamilyDescriptor("new_cf".getBytes()));
new ArrayList<>(); final List<ColumnFamilyHandle> columnFamilyHandleList = new ArrayList<>();
List<ColumnFamilyHandle> columnFamilyHandleList = try (final DBOptions options = new DBOptions()
new ArrayList<>(); .setCreateIfMissing(true);
final RocksDB db = RocksDB.open(options,
dbFolder.getRoot().getAbsolutePath(),
cfDescriptors, columnFamilyHandleList)) {
try { try {
options = new DBOptions();
options.setCreateIfMissing(true);
cfNames.add(new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY));
cfNames.add(new ColumnFamilyDescriptor("new_cf".getBytes()));
db = RocksDB.open(options, dbFolder.getRoot().getAbsolutePath(),
cfNames, columnFamilyHandleList);
db.dropColumnFamily(columnFamilyHandleList.get(1)); db.dropColumnFamily(columnFamilyHandleList.get(1));
db.put(columnFamilyHandleList.get(1), "key".getBytes(), "value".getBytes()); db.put(columnFamilyHandleList.get(1), "key".getBytes(),
"value".getBytes());
} finally { } finally {
for (ColumnFamilyHandle columnFamilyHandle : columnFamilyHandleList) { for (ColumnFamilyHandle columnFamilyHandle : columnFamilyHandleList) {
columnFamilyHandle.dispose(); columnFamilyHandle.close();
}
if (db != null) {
db.close();
} }
if (options != null) {
options.dispose();
} }
} }
} }
@Test(expected = RocksDBException.class) @Test(expected = RocksDBException.class)
public void failRemoveDisposedCF() throws RocksDBException { public void failRemoveDisposedCF() throws RocksDBException {
RocksDB db = null; final List<ColumnFamilyDescriptor> cfDescriptors = Arrays.asList(
DBOptions options = null; new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY),
List<ColumnFamilyDescriptor> cfNames = new ColumnFamilyDescriptor("new_cf".getBytes()));
new ArrayList<>(); final List<ColumnFamilyHandle> columnFamilyHandleList = new ArrayList<>();
List<ColumnFamilyHandle> columnFamilyHandleList = try (final DBOptions options = new DBOptions()
new ArrayList<>(); .setCreateIfMissing(true);
final RocksDB db = RocksDB.open(options,
dbFolder.getRoot().getAbsolutePath(),
cfDescriptors, columnFamilyHandleList)) {
try { try {
options = new DBOptions();
options.setCreateIfMissing(true);
cfNames.add(new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY));
cfNames.add(new ColumnFamilyDescriptor("new_cf".getBytes()));
db = RocksDB.open(options, dbFolder.getRoot().getAbsolutePath(),
cfNames, columnFamilyHandleList);
db.dropColumnFamily(columnFamilyHandleList.get(1)); db.dropColumnFamily(columnFamilyHandleList.get(1));
db.remove(columnFamilyHandleList.get(1), "key".getBytes()); db.remove(columnFamilyHandleList.get(1), "key".getBytes());
} 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();
} }
} }
} }
@Test(expected = RocksDBException.class) @Test(expected = RocksDBException.class)
public void failGetDisposedCF() throws RocksDBException { public void failGetDisposedCF() throws RocksDBException {
RocksDB db = null; final List<ColumnFamilyDescriptor> cfDescriptors = Arrays.asList(
DBOptions options = null; new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY),
List<ColumnFamilyDescriptor> cfNames = new ColumnFamilyDescriptor("new_cf".getBytes()));
new ArrayList<>(); final List<ColumnFamilyHandle> columnFamilyHandleList = new ArrayList<>();
List<ColumnFamilyHandle> columnFamilyHandleList = try (final DBOptions options = new DBOptions()
new ArrayList<>(); .setCreateIfMissing(true);
final RocksDB db = RocksDB.open(options,
dbFolder.getRoot().getAbsolutePath(), cfDescriptors,
columnFamilyHandleList)) {
try { try {
options = new DBOptions();
options.setCreateIfMissing(true);
cfNames.add(new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY));
cfNames.add(new ColumnFamilyDescriptor("new_cf".getBytes()));
db = RocksDB.open(options, dbFolder.getRoot().getAbsolutePath(),
cfNames, columnFamilyHandleList);
db.dropColumnFamily(columnFamilyHandleList.get(1)); db.dropColumnFamily(columnFamilyHandleList.get(1));
db.get(columnFamilyHandleList.get(1), "key".getBytes()); db.get(columnFamilyHandleList.get(1), "key".getBytes());
} 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();
} }
} }
} }
@Test(expected = RocksDBException.class) @Test(expected = RocksDBException.class)
public void failMultiGetWithoutCorrectNumberOfCF() throws RocksDBException { public void failMultiGetWithoutCorrectNumberOfCF() throws RocksDBException {
RocksDB db = null; final List<ColumnFamilyDescriptor> cfDescriptors = Arrays.asList(
DBOptions options = null; new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY),
List<ColumnFamilyDescriptor> cfNames = new ColumnFamilyDescriptor("new_cf".getBytes()));
new ArrayList<>(); final List<ColumnFamilyHandle> columnFamilyHandleList = new ArrayList<>();
List<ColumnFamilyHandle> columnFamilyHandleList = try (final DBOptions options = new DBOptions()
new ArrayList<>(); .setCreateIfMissing(true);
final RocksDB db = RocksDB.open(options,
dbFolder.getRoot().getAbsolutePath(), cfDescriptors,
columnFamilyHandleList)) {
try { try {
options = new DBOptions(); final List<byte[]> keys = new ArrayList<>();
options.setCreateIfMissing(true);
cfNames.add(new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY));
cfNames.add(new ColumnFamilyDescriptor("new_cf".getBytes()));
db = RocksDB.open(options, dbFolder.getRoot().getAbsolutePath(),
cfNames, columnFamilyHandleList);
List<byte[]> keys = new ArrayList<>();
keys.add("key".getBytes()); keys.add("key".getBytes());
keys.add("newcfkey".getBytes()); keys.add("newcfkey".getBytes());
List<ColumnFamilyHandle> cfCustomList = new ArrayList<>(); final List<ColumnFamilyHandle> cfCustomList = new ArrayList<>();
db.multiGet(cfCustomList, keys); db.multiGet(cfCustomList, keys);
} 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();
} }
} }
} }
@Test @Test
public void testByteCreateFolumnFamily() throws RocksDBException { public void testByteCreateFolumnFamily() throws RocksDBException {
RocksDB db = null;
Options options = null; try (final Options options = new Options().setCreateIfMissing(true);
final RocksDB db = RocksDB.open(options,
dbFolder.getRoot().getAbsolutePath())
) {
final byte[] b0 = new byte[]{(byte) 0x00};
final byte[] b1 = new byte[]{(byte) 0x01};
final byte[] b2 = new byte[]{(byte) 0x02};
ColumnFamilyHandle cf1 = null, cf2 = null, cf3 = null; ColumnFamilyHandle cf1 = null, cf2 = null, cf3 = null;
try { try {
options = new Options().setCreateIfMissing(true);
db = RocksDB.open(options, dbFolder.getRoot().getAbsolutePath());
byte[] b0 = new byte[] { (byte)0x00 };
byte[] b1 = new byte[] { (byte)0x01 };
byte[] b2 = new byte[] { (byte)0x02 };
cf1 = db.createColumnFamily(new ColumnFamilyDescriptor(b0)); cf1 = db.createColumnFamily(new ColumnFamilyDescriptor(b0));
cf2 = db.createColumnFamily(new ColumnFamilyDescriptor(b1)); cf2 = db.createColumnFamily(new ColumnFamilyDescriptor(b1));
List<byte[]> families = RocksDB.listColumnFamilies(options, dbFolder.getRoot().getAbsolutePath()); final List<byte[]> families = RocksDB.listColumnFamilies(options,
dbFolder.getRoot().getAbsolutePath());
assertThat(families).contains("default".getBytes(), b0, b1); assertThat(families).contains("default".getBytes(), b0, b1);
cf3 = db.createColumnFamily(new ColumnFamilyDescriptor(b2)); cf3 = db.createColumnFamily(new ColumnFamilyDescriptor(b2));
} finally { } finally {
if (cf1 != null) { if (cf1 != null) {
cf1.dispose(); cf1.close();
} }
if (cf2 != null) { if (cf2 != null) {
cf2.dispose(); cf2.close();
} }
if (cf3 != null) { if (cf3 != null) {
cf3.dispose(); cf3.close();
} }
if (db != null) {
db.close();
}
if (options != null) {
options.dispose();
} }
} }
} }
@Test @Test
public void testCFNamesWithZeroBytes() throws RocksDBException { public void testCFNamesWithZeroBytes() throws RocksDBException {
RocksDB db = null;
Options options = null;
ColumnFamilyHandle cf1 = null, cf2 = null; ColumnFamilyHandle cf1 = null, cf2 = null;
try (final Options options = new Options().setCreateIfMissing(true);
final RocksDB db = RocksDB.open(options,
dbFolder.getRoot().getAbsolutePath());
) {
try { try {
options = new Options().setCreateIfMissing(true); final byte[] b0 = new byte[]{0, 0};
db = RocksDB.open(options, dbFolder.getRoot().getAbsolutePath()); final byte[] b1 = new byte[]{0, 1};
byte[] b0 = new byte[] { 0, 0 };
byte[] b1 = new byte[] { 0, 1 };
cf1 = db.createColumnFamily(new ColumnFamilyDescriptor(b0)); cf1 = db.createColumnFamily(new ColumnFamilyDescriptor(b0));
cf2 = db.createColumnFamily(new ColumnFamilyDescriptor(b1)); cf2 = db.createColumnFamily(new ColumnFamilyDescriptor(b1));
List<byte[]> families = RocksDB.listColumnFamilies(options, dbFolder.getRoot().getAbsolutePath()); final List<byte[]> families = RocksDB.listColumnFamilies(options,
dbFolder.getRoot().getAbsolutePath());
assertThat(families).contains("default".getBytes(), b0, b1); assertThat(families).contains("default".getBytes(), b0, b1);
} finally { } finally {
if (cf1 != null) { if (cf1 != null) {
cf1.dispose(); cf1.close();
} }
if (cf2 != null) { if (cf2 != null) {
cf2.dispose(); cf2.close();
}
if (db != null) {
db.close();
} }
if (options != null) {
options.dispose();
} }
} }
} }
@Test @Test
public void testCFNameSimplifiedChinese() throws RocksDBException { public void testCFNameSimplifiedChinese() throws RocksDBException {
RocksDB db = null;
Options options = null;
ColumnFamilyHandle columnFamilyHandle = null; ColumnFamilyHandle columnFamilyHandle = null;
try (final Options options = new Options().setCreateIfMissing(true);
final RocksDB db = RocksDB.open(options,
dbFolder.getRoot().getAbsolutePath());
) {
try { try {
options = new Options().setCreateIfMissing(true);
db = RocksDB.open(options, dbFolder.getRoot().getAbsolutePath());
final String simplifiedChinese = "\u7b80\u4f53\u5b57"; final String simplifiedChinese = "\u7b80\u4f53\u5b57";
columnFamilyHandle = db.createColumnFamily( columnFamilyHandle = db.createColumnFamily(
new ColumnFamilyDescriptor(simplifiedChinese.getBytes())); new ColumnFamilyDescriptor(simplifiedChinese.getBytes()));
List<byte[]> families = RocksDB.listColumnFamilies(options, dbFolder.getRoot().getAbsolutePath()); final List<byte[]> families = RocksDB.listColumnFamilies(options,
assertThat(families).contains("default".getBytes(), simplifiedChinese.getBytes()); dbFolder.getRoot().getAbsolutePath());
assertThat(families).contains("default".getBytes(),
simplifiedChinese.getBytes());
} finally { } finally {
if (columnFamilyHandle != null) { if (columnFamilyHandle != null) {
columnFamilyHandle.dispose(); columnFamilyHandle.close();
} }
if (db != null) {
db.close();
} }
if (options != null) {
options.dispose();
} }
} }
}
} }

@ -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,21 +79,17 @@ 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());
rocksDB.put("abc3".getBytes(), "abc3".getBytes());
rocksIterator = rocksDB.newIterator();
// Iterate over keys using a iterator // Iterate over keys using a iterator
rocksIterator.seekToFirst(); rocksIterator.seekToFirst();
assertThat(rocksIterator.isValid()).isTrue(); assertThat(rocksIterator.isValid()).isTrue();
@ -129,16 +125,6 @@ public class ComparatorTest {
"abc1".getBytes()); "abc1".getBytes());
assertThat(rocksIterator.value()).isEqualTo( assertThat(rocksIterator.value()).isEqualTo(
"abc1".getBytes()); "abc1".getBytes());
} finally {
if (rocksIterator != null) {
rocksIterator.dispose();
}
if (rocksDB != null) {
rocksDB.close();
}
if (options != null) {
options.dispose();
} }
} }
} }
@ -146,22 +132,18 @@ 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());
rocksDB.put("abc3".getBytes(), "abc3".getBytes());
rocksIterator = rocksDB.newIterator();
// Iterate over keys using a iterator // Iterate over keys using a iterator
rocksIterator.seekToFirst(); rocksIterator.seekToFirst();
assertThat(rocksIterator.isValid()).isTrue(); assertThat(rocksIterator.isValid()).isTrue();
@ -200,15 +182,6 @@ public class ComparatorTest {
"abc3".getBytes()); "abc3".getBytes());
assertThat(rocksIterator.value()).isEqualTo( assertThat(rocksIterator.value()).isEqualTo(
"abc3".getBytes()); "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;
try {
// setup sample properties // setup sample properties
Properties properties = new Properties(); final Properties properties = new Properties();
properties.put("allow_mmap_reads", "true"); properties.put("allow_mmap_reads", "true");
properties.put("bytes_per_sync", "13"); properties.put("bytes_per_sync", "13");
opt = DBOptions.getDBOptionsFromProps(properties); try(final DBOptions 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;
try {
// setup sample properties // setup sample properties
Properties properties = new Properties(); final Properties properties = new Properties();
properties.put("tomato", "1024"); properties.put("tomato", "1024");
properties.put("burger", "2"); properties.put("burger", "2");
opt = DBOptions. try(final DBOptions opt = DBOptions.getDBOptionsFromProps(properties)) {
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();
ByteBuffer buffer = ByteBuffer.allocateDirect(data.length + 1);
buffer.put(data); buffer.put(data);
buffer.put(data.length, (byte)0); 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();
ByteBuffer buffer = ByteBuffer.allocateDirect(data.length);
buffer.put(data); buffer.put(data);
directSlice = new DirectSlice(buffer, 4); try(final DirectSlice 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;
try {
options = new Options();
// test table config
options.setTableFormatConfig(new BlockBasedTableConfig().
setFilter(new BloomFilter()));
options.dispose();
System.gc();
System.runFinalization();
// new Bloom filter // new Bloom filter
options = new Options(); final BlockBasedTableConfig blockConfig = new BlockBasedTableConfig();
BlockBasedTableConfig blockConfig = new BlockBasedTableConfig(); try(final Options options = new Options()) {
blockConfig.setFilter(new BloomFilter());
options.setTableFormatConfig(blockConfig); try(final Filter bloomFilter = new BloomFilter()) {
BloomFilter bloomFilter = new BloomFilter(10);
blockConfig.setFilter(bloomFilter); blockConfig.setFilter(bloomFilter);
options.setTableFormatConfig(blockConfig); options.setTableFormatConfig(blockConfig);
System.gc(); }
System.runFinalization();
blockConfig.setFilter(new BloomFilter(10, false)); try(final Filter bloomFilter = new BloomFilter(10)) {
blockConfig.setFilter(bloomFilter);
options.setTableFormatConfig(blockConfig); options.setTableFormatConfig(blockConfig);
}
} finally { try(final Filter bloomFilter = new BloomFilter(10, false)) {
if (options != null) { blockConfig.setFilter(bloomFilter);
options.dispose(); options.setTableFormatConfig(blockConfig);
} }
} }
} }

@ -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()); try(final RocksDB db = RocksDB.open(options,
dbFolder.getRoot().getAbsolutePath())) {
db.put(wOpt, "key1".getBytes(), "value1".getBytes()); db.put(wOpt, "key1".getBytes(), "value1".getBytes());
db.put(wOpt, "key2".getBytes(), "value2".getBytes()); db.put(wOpt, "key2".getBytes(), "value2".getBytes());
db.put(wOpt, "key3".getBytes(), "value3".getBytes()); db.put(wOpt, "key3".getBytes(), "value3".getBytes());
db.put(wOpt, "key4".getBytes(), "value4".getBytes()); db.put(wOpt, "key4".getBytes(), "value4".getBytes());
assertThat(db.getProperty("rocksdb.num-entries-active-mem-table")).isEqualTo("4"); assertThat(db.getProperty("rocksdb.num-entries-active-mem-table"))
.isEqualTo("4");
db.flush(flushOptions); db.flush(flushOptions);
assertThat(db.getProperty("rocksdb.num-entries-active-mem-table")). assertThat(db.getProperty("rocksdb.num-entries-active-mem-table"))
isEqualTo("0"); .isEqualTo("0");
} finally {
if (flushOptions != null) {
flushOptions.dispose();
}
if (db != null) {
db.close();
}
if (options != null) {
options.dispose();
} }
if (wOpt != null) {
wOpt.dispose();
}
} }
} }
} }

@ -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;
try {
options = new Options().
setCreateIfMissing(true). setCreateIfMissing(true).
setInfoLogLevel(InfoLogLevel.FATAL_LEVEL); setInfoLogLevel(InfoLogLevel.FATAL_LEVEL);
final RocksDB db = RocksDB.open(options,
dbFolder.getRoot().getAbsolutePath())) {
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;
DBOptions dbOptions = null;
try {
dbOptions = new DBOptions().
setInfoLogLevel(InfoLogLevel.FATAL_LEVEL); setInfoLogLevel(InfoLogLevel.FATAL_LEVEL);
options = new Options(dbOptions, final Options options = new Options(dbOptions,
new ColumnFamilyOptions()). new ColumnFamilyOptions()).
setCreateIfMissing(true); setCreateIfMissing(true);
final RocksDB db =
RocksDB.open(options, dbFolder.getRoot().getAbsolutePath())) {
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,23 +26,19 @@ 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)
.setCreateMissingColumnFamilies(true);
final RocksDB db = RocksDB.open(options,
dbFolder.getRoot().getAbsolutePath(), dbFolder.getRoot().getAbsolutePath(),
cfDescriptors, columnFamilyHandleList); cfDescriptors, columnFamilyHandleList)) {
try {
assertThat(columnFamilyHandleList.size()). assertThat(columnFamilyHandleList.size()).
isEqualTo(2); isEqualTo(2);
db.put("key".getBytes(), "value".getBytes()); db.put("key".getBytes(), "value".getBytes());
@ -49,46 +46,41 @@ public class KeyMayExistTest {
StringBuffer retValue = new StringBuffer(); StringBuffer retValue = new StringBuffer();
boolean exists = db.keyMayExist("key".getBytes(), retValue); boolean exists = db.keyMayExist("key".getBytes(), retValue);
assertThat(exists).isTrue(); assertThat(exists).isTrue();
assertThat(retValue.toString()). assertThat(retValue.toString()).isEqualTo("value");
isEqualTo("value");
// Test without column family but with readOptions // Test without column family but with readOptions
try (final ReadOptions readOptions = new ReadOptions()) {
retValue = new StringBuffer(); retValue = new StringBuffer();
exists = db.keyMayExist(new ReadOptions(), "key".getBytes(), exists = db.keyMayExist(readOptions, "key".getBytes(), retValue);
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
try (final ReadOptions readOptions = new ReadOptions()) {
retValue = new StringBuffer(); retValue = new StringBuffer();
exists = db.keyMayExist(new ReadOptions(), exists = db.keyMayExist(readOptions,
columnFamilyHandleList.get(0), "key".getBytes(), columnFamilyHandleList.get(0), "key".getBytes(),
retValue); retValue);
assertThat(exists).isTrue(); assertThat(exists).isTrue();
assertThat(retValue.toString()). assertThat(retValue.toString()).isEqualTo("value");
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,183 +20,151 @@ 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 {
// Setup options
final Options options = new Options().
setInfoLogLevel(InfoLogLevel.DEBUG_LEVEL). setInfoLogLevel(InfoLogLevel.DEBUG_LEVEL).
setCreateIfMissing(true); setCreateIfMissing(true);
final Logger logger = new Logger(options) {
// Create new logger with max log level passed by options // Create new logger with max log level passed by options
Logger logger = new Logger(options) {
@Override @Override
protected void log(InfoLogLevel infoLogLevel, String logMsg) { protected void log(InfoLogLevel infoLogLevel, String logMsg) {
assertThat(logMsg).isNotNull(); assertThat(logMsg).isNotNull();
assertThat(logMsg.length()).isGreaterThan(0); assertThat(logMsg.length()).isGreaterThan(0);
logMessageCounter.incrementAndGet(); 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().
try {
// Setup options
final Options options = new Options().
setInfoLogLevel(InfoLogLevel.FATAL_LEVEL). setInfoLogLevel(InfoLogLevel.FATAL_LEVEL).
setCreateIfMissing(true); setCreateIfMissing(true);
final Logger logger = new Logger(options) {
// Create new logger with max log level passed by options // Create new logger with max log level passed by options
Logger logger = new Logger(options) {
@Override @Override
protected void log(InfoLogLevel infoLogLevel, String logMsg) { protected void log(InfoLogLevel infoLogLevel, String logMsg) {
assertThat(logMsg).isNotNull(); assertThat(logMsg).isNotNull();
assertThat(logMsg.length()).isGreaterThan(0); assertThat(logMsg.length()).isGreaterThan(0);
logMessageCounter.incrementAndGet(); 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<>();
List<ColumnFamilyDescriptor> cfDescriptors = new ArrayList<>();
cfDescriptors.add(new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY));
logMessageCounter.set(0);
try {
// Setup options
final DBOptions options = new DBOptions().
setInfoLogLevel(InfoLogLevel.FATAL_LEVEL). setInfoLogLevel(InfoLogLevel.FATAL_LEVEL).
setCreateIfMissing(true); setCreateIfMissing(true);
final Logger logger = new Logger(options) {
// Create new logger with max log level passed by options // Create new logger with max log level passed by options
logger = new Logger(options) {
@Override @Override
protected void log(InfoLogLevel infoLogLevel, String logMsg) { protected void log(InfoLogLevel infoLogLevel, String logMsg) {
assertThat(logMsg).isNotNull(); assertThat(logMsg).isNotNull();
assertThat(logMsg.length()).isGreaterThan(0); assertThat(logMsg.length()).isGreaterThan(0);
logMessageCounter.incrementAndGet(); 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 =
Arrays.asList(
new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY));
final List<ColumnFamilyHandle> cfHandles = new ArrayList<>();
try (final RocksDB db = RocksDB.open(options,
dbFolder.getRoot().getAbsolutePath(),
cfDescriptors, cfHandles)) {
try {
// 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);
logMessageCounter.set(0);
} finally { } finally {
for (ColumnFamilyHandle columnFamilyHandle : cfHandles) { for (final ColumnFamilyHandle columnFamilyHandle : cfHandles) {
columnFamilyHandle.dispose(); columnFamilyHandle.close();
} }
if (db != null) {
db.close();
} }
if (logger != null) {
logger.dispose();
} }
} }
} }
@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
final Options options = new Options().
setInfoLogLevel(InfoLogLevel.FATAL_LEVEL). setInfoLogLevel(InfoLogLevel.FATAL_LEVEL).
setCreateIfMissing(true); setCreateIfMissing(true);
final Logger logger = new Logger(options) {
// Create new logger with max log level passed by options // Create new logger with max log level passed by options
logger = new Logger(options) {
@Override @Override
protected void log(InfoLogLevel infoLogLevel, String logMsg) { protected void log(InfoLogLevel infoLogLevel, String logMsg) {
assertThat(logMsg).isNotNull(); assertThat(logMsg).isNotNull();
assertThat(logMsg.length()).isGreaterThan(0); assertThat(logMsg.length()).isGreaterThan(0);
logMessageCounter.incrementAndGet(); 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().
try {
// Setup options
final Options options = new Options().
setInfoLogLevel(InfoLogLevel.FATAL_LEVEL). setInfoLogLevel(InfoLogLevel.FATAL_LEVEL).
setCreateIfMissing(true); setCreateIfMissing(true);
// Create new logger with max log level passed by options // Create new logger with max log level passed by options
Logger logger = new Logger(options) { final Logger logger = new Logger(options) {
@Override @Override
protected void log(InfoLogLevel infoLogLevel, String logMsg) { protected void log(InfoLogLevel infoLogLevel, String logMsg) {
assertThat(logMsg).isNotNull(); assertThat(logMsg).isNotNull();
assertThat(logMsg.length()).isGreaterThan(0); assertThat(logMsg.length()).isGreaterThan(0);
logMessageCounter.incrementAndGet(); 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.
@ -209,12 +178,7 @@ public class LoggerTest {
// messages shall be received due to previous actions. // messages shall be received due to previous actions.
assertThat(logMessageCounter.get()).isNotEqualTo(0); assertThat(logMessageCounter.get()).isNotEqualTo(0);
} finally {
if (db != null) {
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,59 +28,44 @@ 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 =
new ArrayList<>();
cfDescriptors.add(new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY,
new ColumnFamilyOptions().setMergeOperatorName(
"stringappend")));
cfDescriptors.add(new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY,
new ColumnFamilyOptions().setMergeOperatorName(
"stringappend")));
db = RocksDB.open(opt, db_path_string,
cfDescriptors, columnFamilyHandleList);
try (final ColumnFamilyOptions cfOpt1 = new ColumnFamilyOptions()
.setMergeOperatorName("stringappend");
final ColumnFamilyOptions cfOpt2 = new ColumnFamilyOptions()
.setMergeOperatorName("stringappend")
) {
final List<ColumnFamilyDescriptor> cfDescriptors = Arrays.asList(
new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY, cfOpt1),
new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY, cfOpt2)
);
final List<ColumnFamilyHandle> columnFamilyHandleList = new ArrayList<>();
try (final DBOptions opt = new DBOptions()
.setCreateIfMissing(true)
.setCreateMissingColumnFamilies(true);
final RocksDB db = RocksDB.open(opt,
dbFolder.getRoot().getAbsolutePath(), cfDescriptors,
columnFamilyHandleList)) {
try {
// writing aa under key // writing aa under key
db.put(columnFamilyHandleList.get(1), db.put(columnFamilyHandleList.get(1),
"cfkey".getBytes(), "aa".getBytes()); "cfkey".getBytes(), "aa".getBytes());
@ -87,18 +73,15 @@ public class MergeTest {
db.merge(columnFamilyHandleList.get(1), db.merge(columnFamilyHandleList.get(1),
"cfkey".getBytes(), "bb".getBytes()); "cfkey".getBytes(), "bb".getBytes());
byte[] value = db.get(columnFamilyHandleList.get(1), "cfkey".getBytes()); byte[] value = db.get(columnFamilyHandleList.get(1),
"cfkey".getBytes());
String strValue = new String(value); String strValue = new String(value);
assertThat(strValue).isEqualTo("aa,bb"); assertThat(strValue).isEqualTo("aa,bb");
} finally { } finally {
for (ColumnFamilyHandle handle : columnFamilyHandleList) { for (final ColumnFamilyHandle handle : columnFamilyHandleList) {
handle.dispose(); handle.close();
} }
if (db != null) {
db.close();
} }
if (opt != null) {
opt.dispose();
} }
} }
} }
@ -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<>(); ) {
final List<ColumnFamilyDescriptor> cfDescriptors = Arrays.asList(
new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY, cfOpt1),
new ColumnFamilyDescriptor("new_cf".getBytes(), cfOpt2)
);
final List<ColumnFamilyHandle> columnFamilyHandleList = new ArrayList<>();
try (final DBOptions opt = new DBOptions()
.setCreateIfMissing(true)
.setCreateMissingColumnFamilies(true);
final RocksDB db = RocksDB.open(opt,
dbFolder.getRoot().getAbsolutePath(), cfDescriptors,
columnFamilyHandleList)
) {
try { try {
String db_path_string =
dbFolder.getRoot().getAbsolutePath();
opt = new DBOptions();
opt.setCreateIfMissing(true);
opt.setCreateMissingColumnFamilies(true);
StringAppendOperator stringAppendOperator = new StringAppendOperator();
cfDescriptors.add(new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY,
new ColumnFamilyOptions().setMergeOperator(
stringAppendOperator)));
cfDescriptors.add(new ColumnFamilyDescriptor("new_cf".getBytes(),
new ColumnFamilyOptions().setMergeOperator(
stringAppendOperator)));
db = RocksDB.open(opt, db_path_string,
cfDescriptors, columnFamilyHandleList);
// writing aa under key // writing aa under key
db.put(columnFamilyHandleList.get(1), db.put(columnFamilyHandleList.get(1),
"cfkey".getBytes(), "aa".getBytes()); "cfkey".getBytes(), "aa".getBytes());
// merge bb under key // merge bb under key
db.merge(columnFamilyHandleList.get(1), db.merge(columnFamilyHandleList.get(1),
"cfkey".getBytes(), "bb".getBytes()); "cfkey".getBytes(), "bb".getBytes());
byte[] value = db.get(columnFamilyHandleList.get(1), "cfkey".getBytes()); byte[] value = db.get(columnFamilyHandleList.get(1),
"cfkey".getBytes());
String strValue = new String(value); String strValue = new String(value);
// Test also with createColumnFamily // Test also with createColumnFamily
cfHandle = db.createColumnFamily( try (final ColumnFamilyOptions cfHandleOpts =
new ColumnFamilyOptions()
.setMergeOperator(stringAppendOperator);
final ColumnFamilyHandle cfHandle =
db.createColumnFamily(
new ColumnFamilyDescriptor("new_cf2".getBytes(), new ColumnFamilyDescriptor("new_cf2".getBytes(),
new ColumnFamilyOptions().setMergeOperator(stringAppendOperator))); cfHandleOpts))
) {
// writing xx under cfkey2 // writing xx under cfkey2
db.put(cfHandle, "cfkey2".getBytes(), "xx".getBytes()); db.put(cfHandle, "cfkey2".getBytes(), "xx".getBytes());
// merge yy under cfkey2 // merge yy under cfkey2
db.merge(cfHandle, new WriteOptions(), "cfkey2".getBytes(), "yy".getBytes()); db.merge(cfHandle, new WriteOptions(), "cfkey2".getBytes(),
"yy".getBytes());
value = db.get(cfHandle, "cfkey2".getBytes()); value = db.get(cfHandle, "cfkey2".getBytes());
String strValueTmpCf = new String(value); String strValueTmpCf = new String(value);
assertThat(strValue).isEqualTo("aa,bb"); assertThat(strValue).isEqualTo("aa,bb");
assertThat(strValueTmpCf).isEqualTo("xx,yy"); assertThat(strValueTmpCf).isEqualTo("xx,yy");
} finally {
for (ColumnFamilyHandle columnFamilyHandle : columnFamilyHandleList) {
columnFamilyHandle.dispose();
} }
if (cfHandle != null) { } finally {
cfHandle.dispose(); for (final ColumnFamilyHandle columnFamilyHandle :
columnFamilyHandleList) {
columnFamilyHandle.close();
} }
if (db != null) {
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();
opt.dispose();
System.gc();
System.runFinalization();
// test reuse // test reuse
opt = new Options(); try (final Options opt = new Options()
opt.setMergeOperator(stringAppendOperator); .setMergeOperator(stringAppendOperator);
db = RocksDB.open(opt, db_path_string); final RocksDB db = RocksDB.open(opt,
db.close(); dbFolder.getRoot().getAbsolutePath())) {
opt.dispose(); //no-op
System.gc(); }
System.runFinalization();
// test param init // test param init
opt = new Options(); try (final Options opt = new Options()
opt.setMergeOperator(new StringAppendOperator()); .setMergeOperator(new StringAppendOperator());
db = RocksDB.open(opt, db_path_string); final RocksDB db = RocksDB.open(opt,
db.close(); dbFolder.getRoot().getAbsolutePath())) {
opt.dispose(); //no-op
System.gc(); }
System.runFinalization();
// test replace one with another merge operator instance // test replace one with another merge operator instance
opt = new Options(); try (final Options opt = new Options()
opt.setMergeOperator(stringAppendOperator); .setMergeOperator(stringAppendOperator)) {
StringAppendOperator newStringAppendOperator = new StringAppendOperator(); final 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,33 +19,30 @@ 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(
new BlockBasedTableConfig().setFilter(bloomFilter))
) {
assertThat(cfOptions.tableFactoryName()).isEqualTo( assertThat(cfOptions.tableFactoryName()).isEqualTo(
"BlockBasedTable"); "BlockBasedTable");
cfOptions.setTableFormatConfig(new PlainTableConfig()); cfOptions.setTableFormatConfig(new PlainTableConfig());
assertThat(cfOptions.tableFactoryName()).isEqualTo("PlainTable"); assertThat(cfOptions.tableFactoryName()).isEqualTo("PlainTable");
// Initialize a dbOptions object from cf options and // Initialize a dbOptions object from cf options and
// db options // db options
DBOptions dbOptions = new DBOptions(); try (final DBOptions dbOptions = new DBOptions();
Options options = new Options(dbOptions, cfOptions); final Options options = new Options(dbOptions, cfOptions)) {
assertThat(options.tableFactoryName()).isEqualTo("PlainTable"); assertThat(options.tableFactoryName()).isEqualTo("PlainTable");
// Free instances // Free instances
options.dispose(); }
options = null; }
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();
@ -53,4 +50,6 @@ public class MixedOptionsTest {
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<>(); try (final ColumnFamilyOptions cfOpts = new ColumnFamilyOptions()) {
cfDescriptors.add( final List<ColumnFamilyDescriptor> cfDescriptors = new ArrayList<>();
new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY, cfDescriptors.add(new ColumnFamilyDescriptor(
new ColumnFamilyOptions())); RocksDB.DEFAULT_COLUMN_FAMILY, cfOpts));
db = RocksDB.open( final List<ColumnFamilyHandle> columnFamilyHandleList = new ArrayList<>();
dbFolder.getRoot().getAbsolutePath(), cfDescriptors, columnFamilyHandleList); try (final RocksDB db = RocksDB.open(dbFolder.getRoot().getAbsolutePath(),
cfDescriptors, columnFamilyHandleList)) {
try (final ColumnFamilyOptions newCfOpts = new ColumnFamilyOptions();
final ColumnFamilyOptions newCf2Opts = new ColumnFamilyOptions()
) {
columnFamilyHandleList.add(db.createColumnFamily( columnFamilyHandleList.add(db.createColumnFamily(
new ColumnFamilyDescriptor("new_cf".getBytes(), new ColumnFamilyOptions()))); new ColumnFamilyDescriptor("new_cf".getBytes(), newCfOpts)));
columnFamilyHandleList.add(db.createColumnFamily( columnFamilyHandleList.add(db.createColumnFamily(
new ColumnFamilyDescriptor("new_cf2".getBytes(), new ColumnFamilyOptions()))); new ColumnFamilyDescriptor("new_cf2".getBytes(), newCf2Opts)));
db.put(columnFamilyHandleList.get(2), "key2".getBytes(), db.put(columnFamilyHandleList.get(2), "key2".getBytes(),
"value2".getBytes()); "value2".getBytes());
db2 = RocksDB.openReadOnly( final List<ColumnFamilyHandle> readOnlyColumnFamilyHandleList =
new ArrayList<>();
try (final RocksDB db2 = RocksDB.openReadOnly(
dbFolder.getRoot().getAbsolutePath(), cfDescriptors, dbFolder.getRoot().getAbsolutePath(), cfDescriptors,
readOnlyColumnFamilyHandleList); readOnlyColumnFamilyHandleList)) {
try (final ColumnFamilyOptions newCfOpts2 =
new ColumnFamilyOptions();
final ColumnFamilyOptions newCf2Opts2 =
new ColumnFamilyOptions()
) {
assertThat(db2.get("key2".getBytes())).isNull(); assertThat(db2.get("key2".getBytes())).isNull();
assertThat(db2.get(readOnlyColumnFamilyHandleList.get(0), "key2".getBytes())). assertThat(db2.get(readOnlyColumnFamilyHandleList.get(0),
"key2".getBytes())).
isNull(); isNull();
cfDescriptors.clear(); cfDescriptors.clear();
cfDescriptors.add( cfDescriptors.add(
new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY, new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY,
new ColumnFamilyOptions())); newCfOpts2));
cfDescriptors.add( cfDescriptors.add(new ColumnFamilyDescriptor("new_cf2".getBytes(),
new ColumnFamilyDescriptor("new_cf2".getBytes(), new ColumnFamilyOptions())); newCf2Opts2));
db3 = RocksDB.openReadOnly(
dbFolder.getRoot().getAbsolutePath(), cfDescriptors, readOnlyColumnFamilyHandleList2); final List<ColumnFamilyHandle> readOnlyColumnFamilyHandleList2
assertThat(new String(db3.get(readOnlyColumnFamilyHandleList2.get(1), = 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"); "key2".getBytes()))).isEqualTo("value2");
} finally { } finally {
for (ColumnFamilyHandle columnFamilyHandle : columnFamilyHandleList) { for (final ColumnFamilyHandle columnFamilyHandle :
columnFamilyHandle.dispose(); readOnlyColumnFamilyHandleList2) {
columnFamilyHandle.close();
} }
if (db != null) {
db.close();
} }
for (ColumnFamilyHandle columnFamilyHandle : readOnlyColumnFamilyHandleList) {
columnFamilyHandle.dispose();
} }
if (db2 != null) { } finally {
db2.close(); for (final ColumnFamilyHandle columnFamilyHandle :
readOnlyColumnFamilyHandleList) {
columnFamilyHandle.close();
} }
for (ColumnFamilyHandle columnFamilyHandle : readOnlyColumnFamilyHandleList2) {
columnFamilyHandle.dispose();
} }
if (db3 != null) {
db3.close();
} }
if (options != null) { } finally {
options.dispose(); 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);
try (final RocksDB rDb = RocksDB.openReadOnly(
dbFolder.getRoot().getAbsolutePath(), cfDescriptors,
readOnlyColumnFamilyHandleList)) {
try {
rDb.remove("key".getBytes()); rDb.remove("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 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()) {
try {
wb.put("key".getBytes(), "value".getBytes()); wb.put("key".getBytes(), "value".getBytes());
rDb.write(new WriteOptions(), wb); rDb.write(wOpts, wb);
} 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 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());
rDb.write(wOpts, wb);
} 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();
} }
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;
} }

@ -27,96 +27,65 @@ public class RocksDBTest {
@Test @Test
public void open() throws RocksDBException { public void open() throws RocksDBException {
RocksDB db = null; try (final RocksDB db =
Options opt = null; RocksDB.open(dbFolder.getRoot().getAbsolutePath())) {
try { assertThat(db).isNotNull();
db = RocksDB.open(dbFolder.getRoot().getAbsolutePath());
db.close();
opt = new Options();
opt.setCreateIfMissing(true);
db = RocksDB.open(opt, dbFolder.getRoot().getAbsolutePath());
} finally {
if (db != null) {
db.close();
} }
if (opt != null) {
opt.dispose();
} }
@Test
public void open_opt() throws RocksDBException {
try (final Options opt = new Options().setCreateIfMissing(true);
final RocksDB db = RocksDB.open(opt,
dbFolder.getRoot().getAbsolutePath())) {
assertThat(db).isNotNull();
} }
} }
@Test @Test
public void put() throws RocksDBException { public void put() throws RocksDBException {
RocksDB db = null; try (final RocksDB db = RocksDB.open(dbFolder.getRoot().getAbsolutePath());
WriteOptions opt = null; final WriteOptions opt = new WriteOptions()) {
try {
db = RocksDB.open(dbFolder.getRoot().getAbsolutePath());
db.put("key1".getBytes(), "value".getBytes()); db.put("key1".getBytes(), "value".getBytes());
opt = new WriteOptions();
db.put(opt, "key2".getBytes(), "12345678".getBytes()); db.put(opt, "key2".getBytes(), "12345678".getBytes());
assertThat(db.get("key1".getBytes())).isEqualTo( assertThat(db.get("key1".getBytes())).isEqualTo(
"value".getBytes()); "value".getBytes());
assertThat(db.get("key2".getBytes())).isEqualTo( assertThat(db.get("key2".getBytes())).isEqualTo(
"12345678".getBytes()); "12345678".getBytes());
} finally {
if (db != null) {
db.close();
}
if (opt != null) {
opt.dispose();
}
} }
} }
@Test @Test
public void write() throws RocksDBException { public void write() throws RocksDBException {
RocksDB db = null; try (final Options options = new Options().setMergeOperator(
Options options = null; new StringAppendOperator()).setCreateIfMissing(true);
WriteBatch wb1 = null; final RocksDB db = RocksDB.open(options,
WriteBatch wb2 = null; dbFolder.getRoot().getAbsolutePath());
WriteOptions opts = null; final WriteOptions opts = new WriteOptions()) {
try {
options = new Options(). try (final WriteBatch wb1 = new WriteBatch()) {
setMergeOperator(new StringAppendOperator()).
setCreateIfMissing(true);
db = RocksDB.open(options, dbFolder.getRoot().getAbsolutePath());
opts = new WriteOptions();
wb1 = new WriteBatch();
wb1.put("key1".getBytes(), "aa".getBytes()); wb1.put("key1".getBytes(), "aa".getBytes());
wb1.merge("key1".getBytes(), "bb".getBytes()); wb1.merge("key1".getBytes(), "bb".getBytes());
wb2 = new WriteBatch();
try (final WriteBatch wb2 = new WriteBatch()) {
wb2.put("key2".getBytes(), "xx".getBytes()); wb2.put("key2".getBytes(), "xx".getBytes());
wb2.merge("key2".getBytes(), "yy".getBytes()); wb2.merge("key2".getBytes(), "yy".getBytes());
db.write(opts, wb1); db.write(opts, wb1);
db.write(opts, wb2); db.write(opts, wb2);
}
}
assertThat(db.get("key1".getBytes())).isEqualTo( assertThat(db.get("key1".getBytes())).isEqualTo(
"aa,bb".getBytes()); "aa,bb".getBytes());
assertThat(db.get("key2".getBytes())).isEqualTo( assertThat(db.get("key2".getBytes())).isEqualTo(
"xx,yy".getBytes()); "xx,yy".getBytes());
} finally {
if (db != null) {
db.close();
}
if (wb1 != null) {
wb1.dispose();
}
if (wb2 != null) {
wb2.dispose();
}
if (options != null) {
options.dispose();
}
if (opts != null) {
opts.dispose();
}
} }
} }
@Test @Test
public void getWithOutValue() throws RocksDBException { public void getWithOutValue() throws RocksDBException {
RocksDB db = null; try (final RocksDB db =
try { RocksDB.open(dbFolder.getRoot().getAbsolutePath())) {
db = RocksDB.open(dbFolder.getRoot().getAbsolutePath());
db.put("key1".getBytes(), "value".getBytes()); db.put("key1".getBytes(), "value".getBytes());
db.put("key2".getBytes(), "12345678".getBytes()); db.put("key2".getBytes(), "12345678".getBytes());
byte[] outValue = new byte[5]; byte[] outValue = new byte[5];
@ -131,20 +100,13 @@ public class RocksDBTest {
getResult = db.get("key2".getBytes(), outValue); getResult = db.get("key2".getBytes(), outValue);
assertThat(getResult).isNotEqualTo(RocksDB.NOT_FOUND); assertThat(getResult).isNotEqualTo(RocksDB.NOT_FOUND);
assertThat(outValue).isEqualTo("12345".getBytes()); assertThat(outValue).isEqualTo("12345".getBytes());
} finally {
if (db != null) {
db.close();
}
} }
} }
@Test @Test
public void getWithOutValueReadOptions() throws RocksDBException { public void getWithOutValueReadOptions() throws RocksDBException {
RocksDB db = null; try (final RocksDB db = RocksDB.open(dbFolder.getRoot().getAbsolutePath());
ReadOptions rOpt = null; final ReadOptions rOpt = new ReadOptions()) {
try {
db = RocksDB.open(dbFolder.getRoot().getAbsolutePath());
rOpt = new ReadOptions();
db.put("key1".getBytes(), "value".getBytes()); db.put("key1".getBytes(), "value".getBytes());
db.put("key2".getBytes(), "12345678".getBytes()); db.put("key2".getBytes(), "12345678".getBytes());
byte[] outValue = new byte[5]; byte[] outValue = new byte[5];
@ -160,23 +122,13 @@ public class RocksDBTest {
getResult = db.get(rOpt, "key2".getBytes(), outValue); getResult = db.get(rOpt, "key2".getBytes(), outValue);
assertThat(getResult).isNotEqualTo(RocksDB.NOT_FOUND); assertThat(getResult).isNotEqualTo(RocksDB.NOT_FOUND);
assertThat(outValue).isEqualTo("12345".getBytes()); assertThat(outValue).isEqualTo("12345".getBytes());
} finally {
if (db != null) {
db.close();
}
if (rOpt != null) {
rOpt.dispose();
}
} }
} }
@Test @Test
public void multiGet() throws RocksDBException, InterruptedException { public void multiGet() throws RocksDBException, InterruptedException {
RocksDB db = null; try (final RocksDB db = RocksDB.open(dbFolder.getRoot().getAbsolutePath());
ReadOptions rOpt = null; final ReadOptions rOpt = new ReadOptions()) {
try {
db = RocksDB.open(dbFolder.getRoot().getAbsolutePath());
rOpt = new ReadOptions();
db.put("key1".getBytes(), "value".getBytes()); db.put("key1".getBytes(), "value".getBytes());
db.put("key2".getBytes(), "12345678".getBytes()); db.put("key2".getBytes(), "12345678".getBytes());
List<byte[]> lookupKeys = new ArrayList<>(); List<byte[]> lookupKeys = new ArrayList<>();
@ -209,27 +161,18 @@ public class RocksDBTest {
assertThat(results.values()).isNotNull(); assertThat(results.values()).isNotNull();
assertThat(results.values()). assertThat(results.values()).
contains("value".getBytes()); contains("value".getBytes());
} finally {
if (db != null) {
db.close();
}
if (rOpt != null) {
rOpt.dispose();
}
} }
} }
@Test @Test
public void merge() throws RocksDBException { public void merge() throws RocksDBException {
RocksDB db = null; try (final Options opt = new Options()
Options opt = null; .setCreateIfMissing(true)
WriteOptions wOpt; .setMergeOperator(new StringAppendOperator());
try { final WriteOptions wOpt = new WriteOptions();
opt = new Options(). final RocksDB db = RocksDB.open(opt,
setCreateIfMissing(true). dbFolder.getRoot().getAbsolutePath())
setMergeOperator(new StringAppendOperator()); ) {
wOpt = new WriteOptions();
db = RocksDB.open(opt, dbFolder.getRoot().getAbsolutePath());
db.put("key1".getBytes(), "value".getBytes()); db.put("key1".getBytes(), "value".getBytes());
assertThat(db.get("key1".getBytes())).isEqualTo( assertThat(db.get("key1".getBytes())).isEqualTo(
"value".getBytes()); "value".getBytes());
@ -245,23 +188,13 @@ public class RocksDBTest {
db.merge(wOpt, "key2".getBytes(), "xxxx".getBytes()); db.merge(wOpt, "key2".getBytes(), "xxxx".getBytes());
assertThat(db.get("key2".getBytes())).isEqualTo( assertThat(db.get("key2".getBytes())).isEqualTo(
"xxxx".getBytes()); "xxxx".getBytes());
} finally {
if (db != null) {
db.close();
}
if (opt != null) {
opt.dispose();
}
} }
} }
@Test @Test
public void remove() throws RocksDBException { public void remove() throws RocksDBException {
RocksDB db = null; try (final RocksDB db = RocksDB.open(dbFolder.getRoot().getAbsolutePath());
WriteOptions wOpt; final WriteOptions wOpt = new WriteOptions()) {
try {
wOpt = new WriteOptions();
db = RocksDB.open(dbFolder.getRoot().getAbsolutePath());
db.put("key1".getBytes(), "value".getBytes()); db.put("key1".getBytes(), "value".getBytes());
db.put("key2".getBytes(), "12345678".getBytes()); db.put("key2".getBytes(), "12345678".getBytes());
assertThat(db.get("key1".getBytes())).isEqualTo( assertThat(db.get("key1".getBytes())).isEqualTo(
@ -272,66 +205,47 @@ public class RocksDBTest {
db.remove(wOpt, "key2".getBytes()); db.remove(wOpt, "key2".getBytes());
assertThat(db.get("key1".getBytes())).isNull(); assertThat(db.get("key1".getBytes())).isNull();
assertThat(db.get("key2".getBytes())).isNull(); assertThat(db.get("key2".getBytes())).isNull();
} finally {
if (db != null) {
db.close();
}
} }
} }
@Test @Test
public void getIntProperty() throws RocksDBException { public void getIntProperty() throws RocksDBException {
RocksDB db = null; try (
Options options = null; final Options options = new Options()
WriteOptions wOpt = null; .setCreateIfMissing(true)
try { .setMaxWriteBufferNumber(10)
options = new Options(); .setMinWriteBufferNumberToMerge(10);
wOpt = new WriteOptions(); final RocksDB db = RocksDB.open(options,
// Setup options dbFolder.getRoot().getAbsolutePath());
options.setCreateIfMissing(true); final WriteOptions wOpt = new WriteOptions().setDisableWAL(true)
options.setMaxWriteBufferNumber(10); ) {
options.setMinWriteBufferNumberToMerge(10);
wOpt.setDisableWAL(true);
db = RocksDB.open(options, dbFolder.getRoot().getAbsolutePath());
db.put(wOpt, "key1".getBytes(), "value1".getBytes()); db.put(wOpt, "key1".getBytes(), "value1".getBytes());
db.put(wOpt, "key2".getBytes(), "value2".getBytes()); db.put(wOpt, "key2".getBytes(), "value2".getBytes());
db.put(wOpt, "key3".getBytes(), "value3".getBytes()); db.put(wOpt, "key3".getBytes(), "value3".getBytes());
db.put(wOpt, "key4".getBytes(), "value4".getBytes()); db.put(wOpt, "key4".getBytes(), "value4".getBytes());
assertThat(db.getLongProperty("rocksdb.num-entries-active-mem-table")).isGreaterThan(0); assertThat(db.getLongProperty("rocksdb.num-entries-active-mem-table"))
assertThat(db.getLongProperty("rocksdb.cur-size-active-mem-table")).isGreaterThan(0); .isGreaterThan(0);
} finally { assertThat(db.getLongProperty("rocksdb.cur-size-active-mem-table"))
if (db != null) { .isGreaterThan(0);
db.close();
}
if (options != null) {
options.dispose();
}
if (wOpt != null) {
wOpt.dispose();
}
} }
} }
@Test @Test
public void fullCompactRange() throws RocksDBException { public void fullCompactRange() throws RocksDBException {
RocksDB db = null; try (final Options opt = new Options().
Options opt = null;
try {
opt = new Options().
setCreateIfMissing(true). setCreateIfMissing(true).
setDisableAutoCompactions(true). setDisableAutoCompactions(true).
setCompactionStyle(CompactionStyle.LEVEL). setCompactionStyle(CompactionStyle.LEVEL).
setNumLevels(4). setNumLevels(4).
setWriteBufferSize(100<<10). setWriteBufferSize(100 << 10).
setLevelZeroFileNumCompactionTrigger(3). setLevelZeroFileNumCompactionTrigger(3).
setTargetFileSizeBase(200 << 10). setTargetFileSizeBase(200 << 10).
setTargetFileSizeMultiplier(1). setTargetFileSizeMultiplier(1).
setMaxBytesForLevelBase(500 << 10). setMaxBytesForLevelBase(500 << 10).
setMaxBytesForLevelMultiplier(1). setMaxBytesForLevelMultiplier(1).
setDisableAutoCompactions(false); setDisableAutoCompactions(false);
// open database final RocksDB db = RocksDB.open(opt,
db = RocksDB.open(opt, dbFolder.getRoot().getAbsolutePath())) {
dbFolder.getRoot().getAbsolutePath());
// fill database with key/value pairs // fill database with key/value pairs
byte[] b = new byte[10000]; byte[] b = new byte[10000];
for (int i = 0; i < 200; i++) { for (int i = 0; i < 200; i++) {
@ -339,34 +253,17 @@ public class RocksDBTest {
db.put((String.valueOf(i)).getBytes(), b); db.put((String.valueOf(i)).getBytes(), b);
} }
db.compactRange(); db.compactRange();
} finally {
if (db != null) {
db.close();
}
if (opt != null) {
opt.dispose();
}
} }
} }
@Test @Test
public void fullCompactRangeColumnFamily() public void fullCompactRangeColumnFamily()
throws RocksDBException { throws RocksDBException {
RocksDB db = null; try (
DBOptions opt = null; final DBOptions opt = new DBOptions().
List<ColumnFamilyHandle> columnFamilyHandles =
new ArrayList<>();
try {
opt = new DBOptions().
setCreateIfMissing(true). setCreateIfMissing(true).
setCreateMissingColumnFamilies(true); setCreateMissingColumnFamilies(true);
List<ColumnFamilyDescriptor> columnFamilyDescriptors = final ColumnFamilyOptions new_cf_opts = new ColumnFamilyOptions().
new ArrayList<>();
columnFamilyDescriptors.add(new ColumnFamilyDescriptor(
RocksDB.DEFAULT_COLUMN_FAMILY));
columnFamilyDescriptors.add(new ColumnFamilyDescriptor(
"new_cf".getBytes(),
new ColumnFamilyOptions().
setDisableAutoCompactions(true). setDisableAutoCompactions(true).
setCompactionStyle(CompactionStyle.LEVEL). setCompactionStyle(CompactionStyle.LEVEL).
setNumLevels(4). setNumLevels(4).
@ -376,12 +273,20 @@ public class RocksDBTest {
setTargetFileSizeMultiplier(1). setTargetFileSizeMultiplier(1).
setMaxBytesForLevelBase(500 << 10). setMaxBytesForLevelBase(500 << 10).
setMaxBytesForLevelMultiplier(1). setMaxBytesForLevelMultiplier(1).
setDisableAutoCompactions(false))); setDisableAutoCompactions(false)
) {
final List<ColumnFamilyDescriptor> columnFamilyDescriptors =
Arrays.asList(
new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY),
new ColumnFamilyDescriptor("new_cf".getBytes(), new_cf_opts));
// open database // open database
db = RocksDB.open(opt, final List<ColumnFamilyHandle> columnFamilyHandles = new ArrayList<>();
try (final RocksDB db = RocksDB.open(opt,
dbFolder.getRoot().getAbsolutePath(), dbFolder.getRoot().getAbsolutePath(),
columnFamilyDescriptors, columnFamilyDescriptors,
columnFamilyHandles); columnFamilyHandles)) {
try {
// fill database with key/value pairs // fill database with key/value pairs
byte[] b = new byte[10000]; byte[] b = new byte[10000];
for (int i = 0; i < 200; i++) { for (int i = 0; i < 200; i++) {
@ -391,14 +296,10 @@ public class RocksDBTest {
} }
db.compactRange(columnFamilyHandles.get(1)); db.compactRange(columnFamilyHandles.get(1));
} finally { } finally {
for (ColumnFamilyHandle handle : columnFamilyHandles) { for (final ColumnFamilyHandle handle : columnFamilyHandles) {
handle.dispose(); handle.close();
} }
if (db != null) {
db.close();
} }
if (opt != null) {
opt.dispose();
} }
} }
} }
@ -406,24 +307,20 @@ public class RocksDBTest {
@Test @Test
public void compactRangeWithKeys() public void compactRangeWithKeys()
throws RocksDBException { throws RocksDBException {
RocksDB db = null; try (final Options opt = new Options().
Options opt = null;
try {
opt = new Options().
setCreateIfMissing(true). setCreateIfMissing(true).
setDisableAutoCompactions(true). setDisableAutoCompactions(true).
setCompactionStyle(CompactionStyle.LEVEL). setCompactionStyle(CompactionStyle.LEVEL).
setNumLevels(4). setNumLevels(4).
setWriteBufferSize(100<<10). setWriteBufferSize(100 << 10).
setLevelZeroFileNumCompactionTrigger(3). setLevelZeroFileNumCompactionTrigger(3).
setTargetFileSizeBase(200 << 10). setTargetFileSizeBase(200 << 10).
setTargetFileSizeMultiplier(1). setTargetFileSizeMultiplier(1).
setMaxBytesForLevelBase(500 << 10). setMaxBytesForLevelBase(500 << 10).
setMaxBytesForLevelMultiplier(1). setMaxBytesForLevelMultiplier(1).
setDisableAutoCompactions(false); setDisableAutoCompactions(false);
// open database final RocksDB db = RocksDB.open(opt,
db = RocksDB.open(opt, dbFolder.getRoot().getAbsolutePath())) {
dbFolder.getRoot().getAbsolutePath());
// fill database with key/value pairs // fill database with key/value pairs
byte[] b = new byte[10000]; byte[] b = new byte[10000];
for (int i = 0; i < 200; i++) { for (int i = 0; i < 200; i++) {
@ -431,37 +328,27 @@ public class RocksDBTest {
db.put((String.valueOf(i)).getBytes(), b); db.put((String.valueOf(i)).getBytes(), b);
} }
db.compactRange("0".getBytes(), "201".getBytes()); db.compactRange("0".getBytes(), "201".getBytes());
} finally {
if (db != null) {
db.close();
}
if (opt != null) {
opt.dispose();
}
} }
} }
@Test @Test
public void compactRangeWithKeysReduce() public void compactRangeWithKeysReduce()
throws RocksDBException { throws RocksDBException {
RocksDB db = null; try (
Options opt = null; final Options opt = new Options().
try {
opt = new Options().
setCreateIfMissing(true). setCreateIfMissing(true).
setDisableAutoCompactions(true). setDisableAutoCompactions(true).
setCompactionStyle(CompactionStyle.LEVEL). setCompactionStyle(CompactionStyle.LEVEL).
setNumLevels(4). setNumLevels(4).
setWriteBufferSize(100<<10). setWriteBufferSize(100 << 10).
setLevelZeroFileNumCompactionTrigger(3). setLevelZeroFileNumCompactionTrigger(3).
setTargetFileSizeBase(200 << 10). setTargetFileSizeBase(200 << 10).
setTargetFileSizeMultiplier(1). setTargetFileSizeMultiplier(1).
setMaxBytesForLevelBase(500 << 10). setMaxBytesForLevelBase(500 << 10).
setMaxBytesForLevelMultiplier(1). setMaxBytesForLevelMultiplier(1).
setDisableAutoCompactions(false); setDisableAutoCompactions(false);
// open database final RocksDB db = RocksDB.open(opt,
db = RocksDB.open(opt, dbFolder.getRoot().getAbsolutePath())) {
dbFolder.getRoot().getAbsolutePath());
// fill database with key/value pairs // fill database with key/value pairs
byte[] b = new byte[10000]; byte[] b = new byte[10000];
for (int i = 0; i < 200; i++) { for (int i = 0; i < 200; i++) {
@ -471,49 +358,41 @@ public class RocksDBTest {
db.flush(new FlushOptions().setWaitForFlush(true)); db.flush(new FlushOptions().setWaitForFlush(true));
db.compactRange("0".getBytes(), "201".getBytes(), db.compactRange("0".getBytes(), "201".getBytes(),
true, -1, 0); true, -1, 0);
} finally {
if (db != null) {
db.close();
}
if (opt != null) {
opt.dispose();
}
} }
} }
@Test @Test
public void compactRangeWithKeysColumnFamily() public void compactRangeWithKeysColumnFamily()
throws RocksDBException { throws RocksDBException {
RocksDB db = null; try (final DBOptions opt = new DBOptions().
DBOptions opt = null;
List<ColumnFamilyHandle> columnFamilyHandles =
new ArrayList<>();
try {
opt = new DBOptions().
setCreateIfMissing(true). setCreateIfMissing(true).
setCreateMissingColumnFamilies(true); setCreateMissingColumnFamilies(true);
List<ColumnFamilyDescriptor> columnFamilyDescriptors = final ColumnFamilyOptions new_cf_opts = new ColumnFamilyOptions().
new ArrayList<>();
columnFamilyDescriptors.add(new ColumnFamilyDescriptor(
RocksDB.DEFAULT_COLUMN_FAMILY));
columnFamilyDescriptors.add(new ColumnFamilyDescriptor(
"new_cf".getBytes(),
new ColumnFamilyOptions().
setDisableAutoCompactions(true). setDisableAutoCompactions(true).
setCompactionStyle(CompactionStyle.LEVEL). setCompactionStyle(CompactionStyle.LEVEL).
setNumLevels(4). setNumLevels(4).
setWriteBufferSize(100<<10). setWriteBufferSize(100 << 10).
setLevelZeroFileNumCompactionTrigger(3). setLevelZeroFileNumCompactionTrigger(3).
setTargetFileSizeBase(200 << 10). setTargetFileSizeBase(200 << 10).
setTargetFileSizeMultiplier(1). setTargetFileSizeMultiplier(1).
setMaxBytesForLevelBase(500 << 10). setMaxBytesForLevelBase(500 << 10).
setMaxBytesForLevelMultiplier(1). setMaxBytesForLevelMultiplier(1).
setDisableAutoCompactions(false))); setDisableAutoCompactions(false)
) {
final List<ColumnFamilyDescriptor> columnFamilyDescriptors =
Arrays.asList(
new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY),
new ColumnFamilyDescriptor("new_cf".getBytes(), new_cf_opts)
);
// open database // open database
db = RocksDB.open(opt, final List<ColumnFamilyHandle> columnFamilyHandles =
new ArrayList<>();
try (final RocksDB db = RocksDB.open(opt,
dbFolder.getRoot().getAbsolutePath(), dbFolder.getRoot().getAbsolutePath(),
columnFamilyDescriptors, columnFamilyDescriptors,
columnFamilyHandles); columnFamilyHandles)) {
try {
// fill database with key/value pairs // fill database with key/value pairs
byte[] b = new byte[10000]; byte[] b = new byte[10000];
for (int i = 0; i < 200; i++) { for (int i = 0; i < 200; i++) {
@ -524,14 +403,10 @@ public class RocksDBTest {
db.compactRange(columnFamilyHandles.get(1), db.compactRange(columnFamilyHandles.get(1),
"0".getBytes(), "201".getBytes()); "0".getBytes(), "201".getBytes());
} finally { } finally {
for (ColumnFamilyHandle handle : columnFamilyHandles) { for (final ColumnFamilyHandle handle : columnFamilyHandles) {
handle.dispose(); handle.close();
} }
if (db != null) {
db.close();
} }
if (opt != null) {
opt.dispose();
} }
} }
} }
@ -539,36 +414,34 @@ public class RocksDBTest {
@Test @Test
public void compactRangeWithKeysReduceColumnFamily() public void compactRangeWithKeysReduceColumnFamily()
throws RocksDBException { throws RocksDBException {
RocksDB db = null; try (final DBOptions opt = new DBOptions().
DBOptions opt = null;
List<ColumnFamilyHandle> columnFamilyHandles =
new ArrayList<>();
try {
opt = new DBOptions().
setCreateIfMissing(true). setCreateIfMissing(true).
setCreateMissingColumnFamilies(true); setCreateMissingColumnFamilies(true);
List<ColumnFamilyDescriptor> columnFamilyDescriptors = final ColumnFamilyOptions new_cf_opts = new ColumnFamilyOptions().
new ArrayList<>();
columnFamilyDescriptors.add(new ColumnFamilyDescriptor(
RocksDB.DEFAULT_COLUMN_FAMILY));
columnFamilyDescriptors.add(new ColumnFamilyDescriptor(
"new_cf".getBytes(),
new ColumnFamilyOptions().
setDisableAutoCompactions(true). setDisableAutoCompactions(true).
setCompactionStyle(CompactionStyle.LEVEL). setCompactionStyle(CompactionStyle.LEVEL).
setNumLevels(4). setNumLevels(4).
setWriteBufferSize(100<<10). setWriteBufferSize(100 << 10).
setLevelZeroFileNumCompactionTrigger(3). setLevelZeroFileNumCompactionTrigger(3).
setTargetFileSizeBase(200 << 10). setTargetFileSizeBase(200 << 10).
setTargetFileSizeMultiplier(1). setTargetFileSizeMultiplier(1).
setMaxBytesForLevelBase(500 << 10). setMaxBytesForLevelBase(500 << 10).
setMaxBytesForLevelMultiplier(1). setMaxBytesForLevelMultiplier(1).
setDisableAutoCompactions(false))); setDisableAutoCompactions(false)
) {
final List<ColumnFamilyDescriptor> columnFamilyDescriptors =
Arrays.asList(
new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY),
new ColumnFamilyDescriptor("new_cf".getBytes(), new_cf_opts)
);
final List<ColumnFamilyHandle> columnFamilyHandles = new ArrayList<>();
// open database // open database
db = RocksDB.open(opt, try (final RocksDB db = RocksDB.open(opt,
dbFolder.getRoot().getAbsolutePath(), dbFolder.getRoot().getAbsolutePath(),
columnFamilyDescriptors, columnFamilyDescriptors,
columnFamilyHandles); columnFamilyHandles)) {
try {
// fill database with key/value pairs // fill database with key/value pairs
byte[] b = new byte[10000]; byte[] b = new byte[10000];
for (int i = 0; i < 200; i++) { for (int i = 0; i < 200; i++) {
@ -579,14 +452,10 @@ public class RocksDBTest {
db.compactRange(columnFamilyHandles.get(1), "0".getBytes(), db.compactRange(columnFamilyHandles.get(1), "0".getBytes(),
"201".getBytes(), true, -1, 0); "201".getBytes(), true, -1, 0);
} finally { } finally {
for (ColumnFamilyHandle handle : columnFamilyHandles) { for (final ColumnFamilyHandle handle : columnFamilyHandles) {
handle.dispose(); handle.close();
} }
if (db != null) {
db.close();
} }
if (opt != null) {
opt.dispose();
} }
} }
} }
@ -594,9 +463,6 @@ public class RocksDBTest {
@Test @Test
public void compactRangeToLevel() public void compactRangeToLevel()
throws RocksDBException, InterruptedException { throws RocksDBException, InterruptedException {
RocksDB db = null;
Options opt = null;
try {
final int NUM_KEYS_PER_L0_FILE = 100; final int NUM_KEYS_PER_L0_FILE = 100;
final int KEY_SIZE = 20; final int KEY_SIZE = 20;
final int VALUE_SIZE = 300; final int VALUE_SIZE = 300;
@ -605,7 +471,7 @@ public class RocksDBTest {
final int NUM_L0_FILES = 10; final int NUM_L0_FILES = 10;
final int TEST_SCALE = 5; final int TEST_SCALE = 5;
final int KEY_INTERVAL = 100; final int KEY_INTERVAL = 100;
opt = new Options(). try (final Options opt = new Options().
setCreateIfMissing(true). setCreateIfMissing(true).
setCompactionStyle(CompactionStyle.LEVEL). setCompactionStyle(CompactionStyle.LEVEL).
setNumLevels(5). setNumLevels(5).
@ -621,8 +487,9 @@ public class RocksDBTest {
setMaxBytesForLevelBase(NUM_L0_FILES * L0_FILE_SIZE * 100). setMaxBytesForLevelBase(NUM_L0_FILES * L0_FILE_SIZE * 100).
setMaxBytesForLevelMultiplier(2). setMaxBytesForLevelMultiplier(2).
setDisableAutoCompactions(true); setDisableAutoCompactions(true);
db = RocksDB.open(opt, final RocksDB db = RocksDB.open(opt,
dbFolder.getRoot().getAbsolutePath()); dbFolder.getRoot().getAbsolutePath())
) {
// fill database with key/value pairs // fill database with key/value pairs
byte[] value = new byte[VALUE_SIZE]; byte[] value = new byte[VALUE_SIZE];
int int_key = 0; int int_key = 0;
@ -665,24 +532,12 @@ public class RocksDBTest {
db.getProperty("rocksdb.num-files-at-level2")). db.getProperty("rocksdb.num-files-at-level2")).
isEqualTo("0"); isEqualTo("0");
} }
} finally {
if (db != null) {
db.close();
}
if (opt != null) {
opt.dispose();
}
} }
} }
@Test @Test
public void compactRangeToLevelColumnFamily() public void compactRangeToLevelColumnFamily()
throws RocksDBException { throws RocksDBException {
RocksDB db = null;
DBOptions opt = null;
List<ColumnFamilyHandle> columnFamilyHandles =
new ArrayList<>();
try {
final int NUM_KEYS_PER_L0_FILE = 100; final int NUM_KEYS_PER_L0_FILE = 100;
final int KEY_SIZE = 20; final int KEY_SIZE = 20;
final int VALUE_SIZE = 300; final int VALUE_SIZE = 300;
@ -691,16 +546,11 @@ public class RocksDBTest {
final int NUM_L0_FILES = 10; final int NUM_L0_FILES = 10;
final int TEST_SCALE = 5; final int TEST_SCALE = 5;
final int KEY_INTERVAL = 100; final int KEY_INTERVAL = 100;
opt = new DBOptions().
try (final DBOptions opt = new DBOptions().
setCreateIfMissing(true). setCreateIfMissing(true).
setCreateMissingColumnFamilies(true); setCreateMissingColumnFamilies(true);
List<ColumnFamilyDescriptor> columnFamilyDescriptors = final ColumnFamilyOptions new_cf_opts = new ColumnFamilyOptions().
new ArrayList<>();
columnFamilyDescriptors.add(new ColumnFamilyDescriptor(
RocksDB.DEFAULT_COLUMN_FAMILY));
columnFamilyDescriptors.add(new ColumnFamilyDescriptor(
"new_cf".getBytes(),
new ColumnFamilyOptions().
setCompactionStyle(CompactionStyle.LEVEL). setCompactionStyle(CompactionStyle.LEVEL).
setNumLevels(5). setNumLevels(5).
// a slightly bigger write buffer than L0 file // a slightly bigger write buffer than L0 file
@ -714,12 +564,21 @@ public class RocksDBTest {
// To disable auto compaction // To disable auto compaction
setMaxBytesForLevelBase(NUM_L0_FILES * L0_FILE_SIZE * 100). setMaxBytesForLevelBase(NUM_L0_FILES * L0_FILE_SIZE * 100).
setMaxBytesForLevelMultiplier(2). setMaxBytesForLevelMultiplier(2).
setDisableAutoCompactions(true))); setDisableAutoCompactions(true)
) {
final List<ColumnFamilyDescriptor> columnFamilyDescriptors =
Arrays.asList(
new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY),
new ColumnFamilyDescriptor("new_cf".getBytes(), new_cf_opts)
);
final List<ColumnFamilyHandle> columnFamilyHandles = new ArrayList<>();
// open database // open database
db = RocksDB.open(opt, try (final RocksDB db = RocksDB.open(opt,
dbFolder.getRoot().getAbsolutePath(), dbFolder.getRoot().getAbsolutePath(),
columnFamilyDescriptors, columnFamilyDescriptors,
columnFamilyHandles); columnFamilyHandles)) {
try {
// fill database with key/value pairs // fill database with key/value pairs
byte[] value = new byte[VALUE_SIZE]; byte[] value = new byte[VALUE_SIZE];
int int_key = 0; int int_key = 0;
@ -770,36 +629,24 @@ public class RocksDBTest {
isEqualTo("0"); isEqualTo("0");
} }
} finally { } finally {
for (ColumnFamilyHandle handle : columnFamilyHandles) { for (final ColumnFamilyHandle handle : columnFamilyHandles) {
handle.dispose(); handle.close();
} }
if (db != null) {
db.close();
} }
if (opt != null) {
opt.dispose();
} }
} }
} }
@Test @Test
public void enableDisableFileDeletions() throws RocksDBException { public void enableDisableFileDeletions() 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().setCreateIfMissing(true); ) {
db = RocksDB.open(options, dbFolder.getRoot().getAbsolutePath());
db.disableFileDeletions(); db.disableFileDeletions();
db.enableFileDeletions(false); db.enableFileDeletions(false);
db.disableFileDeletions(); db.disableFileDeletions();
db.enableFileDeletions(true); db.enableFileDeletions(true);
} finally {
if (db != null) {
db.close();
}
if (options != null) {
options.dispose();
}
} }
} }
} }

@ -17,8 +17,8 @@ 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
@ -35,4 +35,5 @@ public class RocksEnvTest {
assertThat(rocksEnv.getThreadPoolQueueLen(RocksEnv.COMPACTION_POOL)). assertThat(rocksEnv.getThreadPoolQueueLen(RocksEnv.COMPACTION_POOL)).
isEqualTo(0); isEqualTo(0);
} }
}
} }

@ -22,20 +22,15 @@ 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;
try {
options = new Options();
options.setCreateIfMissing(true)
.setCreateMissingColumnFamilies(true); .setCreateMissingColumnFamilies(true);
db = RocksDB.open(options, final RocksDB db = RocksDB.open(options,
dbFolder.getRoot().getAbsolutePath()); 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());
@ -57,15 +52,6 @@ public class RocksIteratorTest {
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,33 +33,28 @@ 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);
flushOptions = new FlushOptions().
setWaitForFlush(true);
db = RocksDB.open(options, "dir/db");
// write key/value pairs using MemEnv // write 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]); db.put(keys[i], values[i]);
} }
// 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]);
} }
// Check iterator access // Check iterator access
RocksIterator iterator = db.newIterator(); try (final RocksIterator iterator = db.newIterator()) {
iterator.seekToFirst(); iterator.seekToFirst();
for (int i=0; i < keys.length; i++) { for (int i = 0; i < keys.length; i++) {
assertThat(iterator.isValid()).isTrue(); assertThat(iterator.isValid()).isTrue();
assertThat(iterator.key()).isEqualTo(keys[i]); assertThat(iterator.key()).isEqualTo(keys[i]);
assertThat(iterator.value()).isEqualTo(values[i]); assertThat(iterator.value()).isEqualTo(values[i]);
@ -67,39 +62,26 @@ public class RocksMemEnvTest {
} }
// reached end of database // reached end of database
assertThat(iterator.isValid()).isFalse(); assertThat(iterator.isValid()).isFalse();
iterator.dispose(); }
// flush // flush
db.flush(flushOptions); db.flush(flushOptions);
// read key/value pairs after flush using MemEnv // read key/value pairs after flush 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]);
} }
}
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,23 +22,18 @@ 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 // retrieve key value pair
assertThat(new String(db.get("key".getBytes()))). assertThat(new String(db.get("key".getBytes()))).
isEqualTo("value"); isEqualTo("value");
@ -56,7 +51,7 @@ public class SnapshotTest {
assertThat(db.get(readOptions, "newkey".getBytes())). assertThat(db.get(readOptions, "newkey".getBytes())).
isNull(); isNull();
// Retrieve snapshot from read options // Retrieve snapshot from read options
Snapshot sameSnapshot = readOptions.snapshot(); try (final Snapshot sameSnapshot = readOptions.snapshot()) {
readOptions.setSnapshot(sameSnapshot); readOptions.setSnapshot(sameSnapshot);
// results must be the same with new Snapshot // results must be the same with new Snapshot
// instance using the same native pointer // instance using the same native pointer
@ -79,42 +74,28 @@ public class SnapshotTest {
"newkey".getBytes()))).isEqualTo("newvalue"); "newkey".getBytes()))).isEqualTo("newvalue");
// release Snapshot // release Snapshot
db.releaseSnapshot(snapshot); db.releaseSnapshot(snapshot);
} finally {
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();
final ReadOptions readOptions =
new ReadOptions().setSnapshot(snapshot)) {
db.put("key2".getBytes(), "value2".getBytes()); db.put("key2".getBytes(), "value2".getBytes());
// iterate over current state of db // iterate over current state of db
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("key".getBytes()); assertThat(iterator.key()).isEqualTo("key".getBytes());
@ -123,59 +104,43 @@ public class SnapshotTest {
assertThat(iterator.key()).isEqualTo("key2".getBytes()); assertThat(iterator.key()).isEqualTo("key2".getBytes());
iterator.next(); iterator.next();
assertThat(iterator.isValid()).isFalse(); assertThat(iterator.isValid()).isFalse();
}
// iterate using a snapshot // iterate using a snapshot
snapshotIterator = db.newIterator(readOptions); try (final RocksIterator snapshotIterator =
db.newIterator(readOptions)) {
snapshotIterator.seekToFirst(); snapshotIterator.seekToFirst();
assertThat(snapshotIterator.isValid()).isTrue(); assertThat(snapshotIterator.isValid()).isTrue();
assertThat(snapshotIterator.key()).isEqualTo("key".getBytes()); assertThat(snapshotIterator.key()).isEqualTo("key".getBytes());
snapshotIterator.next(); snapshotIterator.next();
assertThat(snapshotIterator.isValid()).isFalse(); assertThat(snapshotIterator.isValid()).isFalse();
}
// release Snapshot // release Snapshot
db.releaseSnapshot(snapshot); db.releaseSnapshot(snapshot);
} finally {
if (iterator != null) {
iterator.dispose();
}
if (snapshotIterator != null) {
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();
final ReadOptions readOptions = new ReadOptions()
.setSnapshot(snapshot)) {
db.put("key2".getBytes(), "value2".getBytes()); db.put("key2".getBytes(), "value2".getBytes());
// iterate over current state of column family // iterate over current state of column family
iterator = db.newIterator(db.getDefaultColumnFamily()); try (final RocksIterator iterator = db.newIterator(
db.getDefaultColumnFamily())) {
iterator.seekToFirst(); iterator.seekToFirst();
assertThat(iterator.isValid()).isTrue(); assertThat(iterator.isValid()).isTrue();
assertThat(iterator.key()).isEqualTo("key".getBytes()); assertThat(iterator.key()).isEqualTo("key".getBytes());
@ -184,10 +149,11 @@ public class SnapshotTest {
assertThat(iterator.key()).isEqualTo("key2".getBytes()); assertThat(iterator.key()).isEqualTo("key2".getBytes());
iterator.next(); iterator.next();
assertThat(iterator.isValid()).isFalse(); assertThat(iterator.isValid()).isFalse();
}
// iterate using a snapshot on default column family // iterate using a snapshot on default column family
snapshotIterator = db.newIterator(db.getDefaultColumnFamily(), try (final RocksIterator snapshotIterator = db.newIterator(
readOptions); db.getDefaultColumnFamily(), readOptions)) {
snapshotIterator.seekToFirst(); snapshotIterator.seekToFirst();
assertThat(snapshotIterator.isValid()).isTrue(); assertThat(snapshotIterator.isValid()).isTrue();
assertThat(snapshotIterator.key()).isEqualTo("key".getBytes()); assertThat(snapshotIterator.key()).isEqualTo("key".getBytes());
@ -196,21 +162,7 @@ public class SnapshotTest {
// release Snapshot // release Snapshot
db.releaseSnapshot(snapshot); db.releaseSnapshot(snapshot);
} finally {
if (iterator != null) {
iterator.dispose();
}
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,10 +49,9 @@ 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());
} }
@ -78,45 +61,34 @@ public class TransactionLogIteratorTest {
isEqualTo(numberOfPuts + numberOfPuts); isEqualTo(numberOfPuts + numberOfPuts);
// Get updates since the beginning // Get updates since the beginning
transactionLogIterator = db.getUpdatesSince(0); try (final TransactionLogIterator transactionLogIterator =
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 =
db.getUpdatesSince(0)) {
transactionLogIterator.status(); transactionLogIterator.status();
assertThat(transactionLogIterator.isValid()).isTrue(); assertThat(transactionLogIterator.isValid()).isTrue();
transactionLogIterator.next(); transactionLogIterator.next();
@ -126,56 +98,40 @@ public class TransactionLogIteratorTest {
transactionLogIterator.next(); transactionLogIterator.next();
transactionLogIterator.status(); transactionLogIterator.status();
assertThat(transactionLogIterator.isValid()).isTrue(); 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 = 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());
db.flush(new FlushOptions().setWaitForFlush(true)); db.flush(new FlushOptions().setWaitForFlush(true));
}
// reopen // reopen
db.close(); try (final RocksDB db = RocksDB.open(options,
db = RocksDB.open(options, dbFolder.getRoot().getAbsolutePath()); dbFolder.getRoot().getAbsolutePath())) {
assertThat(db.getLatestSequenceNumber()).isEqualTo(numberOfKeys); assertThat(db.getLatestSequenceNumber()).isEqualTo(numberOfKeys);
transactionLogIterator = db.getUpdatesSince(0); try (final TransactionLogIterator transactionLogIterator =
db.getUpdatesSince(0)) {
for (int i = 0; i < numberOfKeys; i++) { for (int i = 0; i < numberOfKeys; i++) {
transactionLogIterator.status(); transactionLogIterator.status();
assertThat(transactionLogIterator.isValid()).isTrue(); assertThat(transactionLogIterator.isValid()).isTrue();
transactionLogIterator.next(); transactionLogIterator.next();
} }
} finally {
if (transactionLogIterator != null) {
transactionLogIterator.dispose();
}
if (db != null) {
db.close();
} }
if (options != null) {
options.dispose();
} }
} }
} }

@ -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,81 +27,54 @@ 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().
setCreateMissingColumnFamilies(true).
setCreateIfMissing(true);
ttlDB = TtlDB.open(dbOptions, dbFolder.getRoot().getAbsolutePath(),
cfNames, columnFamilyHandleList, ttlValues, 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());
@ -116,18 +90,11 @@ public class TtlDBTest {
assertThat(ttlDB.get("key".getBytes())).isNotNull(); assertThat(ttlDB.get("key".getBytes())).isNotNull();
assertThat(ttlDB.get(columnFamilyHandleList.get(1), assertThat(ttlDB.get(columnFamilyHandleList.get(1),
"key".getBytes())).isNull(); "key".getBytes())).isNull();
} finally { } finally {
for (ColumnFamilyHandle columnFamilyHandle : for (final ColumnFamilyHandle columnFamilyHandle :
columnFamilyHandleList) { columnFamilyHandleList) {
columnFamilyHandle.dispose(); columnFamilyHandle.close();
}
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;
try {
options = new Options().setCreateIfMissing(true);
ttlDB = TtlDB.open(options,
dbFolder.getRoot().getAbsolutePath()); dbFolder.getRoot().getAbsolutePath());
columnFamilyHandle = ttlDB.createColumnFamilyWithTtl( final ColumnFamilyHandle columnFamilyHandle =
new ColumnFamilyDescriptor("new_cf".getBytes()), 1); 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;
CapturingWriteBatchHandler handler = null;
try {
// setup test data // setup test data
final List<Tuple<Action, Tuple<byte[], byte[]>>> testEvents = new ArrayList<>(); final List<Tuple<Action, Tuple<byte[], byte[]>>> testEvents = Arrays.asList(
testEvents.add(new Tuple<>(Action.DELETE, new Tuple<>(Action.DELETE,
new Tuple<byte[], byte[]>("k0".getBytes(), null))); new Tuple<byte[], byte[]>("k0".getBytes(), null)),
testEvents.add(new Tuple<>(Action.PUT, new Tuple<>(Action.PUT,
new Tuple<>("k1".getBytes(), "v1".getBytes()))); new Tuple<>("k1".getBytes(), "v1".getBytes())),
testEvents.add(new Tuple<>(Action.PUT, new Tuple<>(Action.PUT,
new Tuple<>("k2".getBytes(), "v2".getBytes()))); new Tuple<>("k2".getBytes(), "v2".getBytes())),
testEvents.add(new Tuple<>(Action.PUT, new Tuple<>(Action.PUT,
new Tuple<>("k3".getBytes(), "v3".getBytes()))); new Tuple<>("k3".getBytes(), "v3".getBytes())),
testEvents.add(new Tuple<>(Action.LOG, new Tuple<>(Action.LOG,
new Tuple<byte[], byte[]>(null, "log1".getBytes()))); new Tuple<byte[], byte[]>(null, "log1".getBytes())),
testEvents.add(new Tuple<>(Action.MERGE, new Tuple<>(Action.MERGE,
new Tuple<>("k2".getBytes(), "v22".getBytes()))); new Tuple<>("k2".getBytes(), "v22".getBytes())),
testEvents.add(new Tuple<>(Action.DELETE, new Tuple<>(Action.DELETE,
new Tuple<byte[], byte[]>("k3".getBytes(), null))); new Tuple<byte[], byte[]>("k3".getBytes(), null))
);
// load test data to the write batch // load test data to the write batch
batch = new WriteBatch(); try (final WriteBatch 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,28 +65,26 @@ 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
try (final CapturingWriteBatchHandler handler =
new CapturingWriteBatchHandler()) {
batch.iterate(handler); 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 =
handler.getEvents();
assertThat(testEvents.size()).isSameAs(actualEvents.size()); 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[]>> expected,
final Tuple<Action, Tuple<byte[], byte[]>> actual) { 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,17 +36,19 @@ 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); WriteBatchTestInternalHelper.setSequence(batch, 100);
assertThat(WriteBatchTestInternalHelper.sequence(batch)). assertThat(WriteBatchTestInternalHelper.sequence(batch)).
isNotNull(). isNotNull().
@ -57,12 +59,13 @@ public class WriteBatchTest {
"Delete(box)@101" + "Delete(box)@101" +
"Put(foo, bar)@100"); "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);
@ -70,7 +73,8 @@ public class WriteBatchTest {
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),
"US-ASCII")));
assertThat(b1.count()).isEqualTo(1); assertThat(b1.count()).isEqualTo(1);
b2.clear(); b2.clear();
b2.put("b".getBytes("US-ASCII"), "vb".getBytes("US-ASCII")); b2.put("b".getBytes("US-ASCII"), "vb".getBytes("US-ASCII"));
@ -88,11 +92,12 @@ public class WriteBatchTest {
.equals(new String(getContents(b1), "US-ASCII"))); .equals(new String(getContents(b1), "US-ASCII")));
assertThat(b1.count()).isEqualTo(4); 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"));
@ -108,6 +113,7 @@ public class WriteBatchTest {
"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) {
return getContents(wb.nativeHandle_); return getContents(wb.nativeHandle_);
@ -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,72 +87,36 @@ 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";
@ -185,7 +141,7 @@ public class WriteBatchWithIndexTest {
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,
@ -196,14 +152,11 @@ public class WriteBatchWithIndexTest {
new DirectSlice(k4), DirectSlice.NONE) new DirectSlice(k4), DirectSlice.NONE)
}; };
WBWIRocksIterator it = null; try (final WBWIRocksIterator it = wbwi.newIterator()) {
try {
it = wbwi.newIterator();
//direct access - seek to key offsets //direct access - seek to key offsets
final int[] testOffsets = {2, 0, 1, 3}; final int[] testOffsets = {2, 0, 1, 3};
for(int i = 0; i < testOffsets.length; i++) { for (int i = 0; i < testOffsets.length; i++) {
final int testOffset = testOffsets[i]; final int testOffset = testOffsets[i];
final byte[] key = toArray(expected[testOffset].getKey().data()); final byte[] key = toArray(expected[testOffset].getKey().data());
@ -216,32 +169,27 @@ public class WriteBatchWithIndexTest {
//forward iterative access //forward iterative access
int i = 0; int i = 0;
for(it.seekToFirst(); it.isValid(); it.next()) { for (it.seekToFirst(); it.isValid(); it.next()) {
assertThat(it.entry().equals(expected[i++])).isTrue(); assertThat(it.entry().equals(expected[i++])).isTrue();
} }
//reverse iterative access //reverse iterative access
i = expected.length - 1; i = expected.length - 1;
for(it.seekToLast(); it.isValid(); it.prev()) { for (it.seekToLast(); it.isValid(); it.prev()) {
assertThat(it.entry().equals(expected[i--])).isTrue(); assertThat(it.entry().equals(expected[i--])).isTrue();
} }
} finally {
if(it != null) {
it.dispose();
} }
} }
} }
@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);
ByteBuffer buffer = ByteBuffer.allocateDirect(zeroByteValue.length); final ByteBuffer buffer = ByteBuffer.allocateDirect(zeroByteValue.length);
buffer.put(zeroByteValue); buffer.put(zeroByteValue);
WBWIRocksIterator.WriteEntry[] expected = { WBWIRocksIterator.WriteEntry[] expected = {
@ -249,15 +197,11 @@ public class WriteBatchWithIndexTest {
new DirectSlice(buffer, zeroByteValue.length), new DirectSlice(buffer, zeroByteValue.length),
new DirectSlice(buffer, zeroByteValue.length)) new DirectSlice(buffer, zeroByteValue.length))
}; };
WBWIRocksIterator it = null;
try { try (final WBWIRocksIterator it = wbwi.newIterator()) {
it = wbwi.newIterator();
it.seekToFirst(); it.seekToFirst();
assertThat(it.entry().equals(expected[0])).isTrue(); assertThat(it.entry().equals(expected[0])).isTrue();
assertThat(it.entry().hashCode() == expected[0].hashCode()).isTrue(); assertThat(it.entry().hashCode() == expected[0].hashCode()).isTrue();
} finally {
if(it != null) {
it.dispose();
} }
} }
} }

@ -17,8 +17,8 @@ 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);
@ -28,4 +28,5 @@ public class WriteOptionsTest {
writeOptions.setSync(false); writeOptions.setSync(false);
assertThat(writeOptions.sync()).isFalse(); assertThat(writeOptions.sync()).isFalse();
} }
}
} }

Loading…
Cancel
Save