Merge pull request #380 from fyrz/RocksJava-Junit-Framework

[RocksJava] Test framework support
main
Yueh-Hsuan Chiang 10 years ago
commit 353303a765
  1. 85
      java/Makefile
  2. 8
      java/org/rocksdb/ColumnFamilyHandle.java
  3. 1
      java/org/rocksdb/Options.java
  4. 1
      java/org/rocksdb/ReadOptions.java
  5. 9
      java/org/rocksdb/RocksDB.java
  6. 3
      java/org/rocksdb/RocksEnv.java
  7. 8
      java/org/rocksdb/RocksIterator.java
  8. 10
      java/org/rocksdb/WriteBatch.java
  9. 124
      java/org/rocksdb/WriteBatchTest.java
  10. 5
      java/org/rocksdb/test/AbstractComparatorTest.java
  11. 146
      java/org/rocksdb/test/BackupableDBTest.java
  12. 157
      java/org/rocksdb/test/BlockBasedTableConfigTest.java
  13. 545
      java/org/rocksdb/test/ColumnFamilyOptionsTest.java
  14. 627
      java/org/rocksdb/test/ColumnFamilyTest.java
  15. 22
      java/org/rocksdb/test/ComparatorOptionsTest.java
  16. 168
      java/org/rocksdb/test/ComparatorTest.java
  17. 503
      java/org/rocksdb/test/DBOptionsTest.java
  18. 21
      java/org/rocksdb/test/DirectComparatorTest.java
  19. 143
      java/org/rocksdb/test/EnvironmentTest.java
  20. 66
      java/org/rocksdb/test/FilterTest.java
  21. 58
      java/org/rocksdb/test/FlushTest.java
  22. 108
      java/org/rocksdb/test/KeyMayExistTest.java
  23. 197
      java/org/rocksdb/test/MemTableTest.java
  24. 391
      java/org/rocksdb/test/MergeTest.java
  25. 23
      java/org/rocksdb/test/MixedOptionsTest.java
  26. 1115
      java/org/rocksdb/test/OptionsTest.java
  27. 86
      java/org/rocksdb/test/PlainTableConfigTest.java
  28. 4
      java/org/rocksdb/test/PlatformRandomHelper.java
  29. 375
      java/org/rocksdb/test/ReadOnlyTest.java
  30. 142
      java/org/rocksdb/test/ReadOptionsTest.java
  31. 282
      java/org/rocksdb/test/RocksDBTest.java
  32. 39
      java/org/rocksdb/test/RocksEnvTest.java
  33. 100
      java/org/rocksdb/test/RocksIteratorTest.java
  34. 65
      java/org/rocksdb/test/RocksJunitRunner.java
  35. 21
      java/org/rocksdb/test/RocksMemoryResource.java
  36. 28
      java/org/rocksdb/test/SizeUnitTest.java
  37. 88
      java/org/rocksdb/test/SnapshotTest.java
  38. 72
      java/org/rocksdb/test/StatisticsCollectorTest.java
  39. 19
      java/org/rocksdb/test/WriteBatchHandlerTest.java
  40. 124
      java/org/rocksdb/test/WriteBatchTest.java
  41. 32
      java/org/rocksdb/test/WriteOptionsTest.java
  42. 195
      java/rocksjni.pom
  43. 2
      java/rocksjni/backupablejni.cc
  44. 11
      java/rocksjni/options.cc
  45. 20
      java/rocksjni/write_batch.cc

@ -32,9 +32,9 @@ NATIVE_JAVA_CLASSES = org.rocksdb.AbstractComparator\
org.rocksdb.StringAppendOperator\ org.rocksdb.StringAppendOperator\
org.rocksdb.WriteBatch\ org.rocksdb.WriteBatch\
org.rocksdb.WriteBatch.Handler\ org.rocksdb.WriteBatch.Handler\
org.rocksdb.WriteBatchInternal\ org.rocksdb.test.WriteBatchInternal\
org.rocksdb.WriteBatchTest\ org.rocksdb.test.WriteBatchTest\
org.rocksdb.WriteOptions\ org.rocksdb.WriteOptions\
ROCKSDB_MAJOR = $(shell egrep "ROCKSDB_MAJOR.[0-9]" ../include/rocksdb/version.h | cut -d ' ' -f 3) ROCKSDB_MAJOR = $(shell egrep "ROCKSDB_MAJOR.[0-9]" ../include/rocksdb/version.h | cut -d ' ' -f 3)
ROCKSDB_MINOR = $(shell egrep "ROCKSDB_MINOR.[0-9]" ../include/rocksdb/version.h | cut -d ' ' -f 3) ROCKSDB_MINOR = $(shell egrep "ROCKSDB_MINOR.[0-9]" ../include/rocksdb/version.h | cut -d ' ' -f 3)
@ -43,21 +43,57 @@ ROCKSDB_PATCH = $(shell egrep "ROCKSDB_PATCH.[0-9]" ../include/rocksdb/version.h
NATIVE_INCLUDE = ./include NATIVE_INCLUDE = ./include
ARCH := $(shell getconf LONG_BIT) ARCH := $(shell getconf LONG_BIT)
ROCKSDB_JAR = rocksdbjni-$(ROCKSDB_MAJOR).$(ROCKSDB_MINOR).$(ROCKSDB_PATCH)-linux$(ARCH).jar ROCKSDB_JAR = rocksdbjni-$(ROCKSDB_MAJOR).$(ROCKSDB_MINOR).$(ROCKSDB_PATCH)-linux$(ARCH).jar
ifeq ($(PLATFORM), OS_MACOSX) ifeq ($(PLATFORM), OS_MACOSX)
ROCKSDB_JAR = rocksdbjni-$(ROCKSDB_MAJOR).$(ROCKSDB_MINOR).$(ROCKSDB_PATCH)-osx.jar ROCKSDB_JAR = rocksdbjni-$(ROCKSDB_MAJOR).$(ROCKSDB_MINOR).$(ROCKSDB_PATCH)-osx.jar
endif endif
JAVA_TESTS = org.rocksdb.test.BackupableDBTest\
org.rocksdb.test.BlockBasedTableConfigTest\
org.rocksdb.test.ColumnFamilyOptionsTest\
org.rocksdb.test.ColumnFamilyTest\
org.rocksdb.test.ComparatorOptionsTest\
org.rocksdb.test.ComparatorTest\
org.rocksdb.test.DBOptionsTest\
org.rocksdb.test.DirectComparatorTest\
org.rocksdb.test.FilterTest\
org.rocksdb.test.FlushTest\
org.rocksdb.test.KeyMayExistTest\
org.rocksdb.test.MemTableTest\
org.rocksdb.test.MergeTest\
org.rocksdb.test.MixedOptionsTest\
org.rocksdb.test.OptionsTest\
org.rocksdb.test.PlainTableConfigTest\
org.rocksdb.test.ReadOnlyTest\
org.rocksdb.test.ReadOptionsTest\
org.rocksdb.test.RocksDBTest\
org.rocksdb.test.RocksEnvTest\
org.rocksdb.test.RocksIteratorTest\
org.rocksdb.test.SnapshotTest\
org.rocksdb.test.StatisticsCollectorTest\
org.rocksdb.test.WriteBatchHandlerTest\
org.rocksdb.test.WriteBatchTest\
org.rocksdb.test.WriteOptionsTest\
JAVA_TEST_LIBDIR = ./test-libs/
JAVA_JUNIT_JAR = $(JAVA_TEST_LIBDIR)junit-4.12-beta-2.jar
JAVA_HAMCR_JAR = $(JAVA_TEST_LIBDIR)hamcrest-core-1.3.jar
JAVA_MOCKITO_JAR = $(JAVA_TEST_LIBDIR)mockito-all-1.9.5.jar
JAVA_CGLIB_JAR = $(JAVA_TEST_LIBDIR)cglib-2.2.2.jar
JAVA_ASSERTJ_JAR = $(JAVA_TEST_LIBDIR)assertj-core-1.7.0.jar
JAVA_TESTCLASSPATH = $(ROCKSDB_JAR):$(JAVA_JUNIT_JAR):$(JAVA_HAMCR_JAR):$(JAVA_MOCKITO_JAR):$(JAVA_CGLIB_JAR):$(JAVA_ASSERTJ_JAR):.:./*
clean: clean:
-find . -name "*.class" -exec rm {} \; -find . -name "*.class" -exec rm {} \;
-find . -name "hs*.log" -exec rm {} \; -find . -name "hs*.log" -exec rm {} \;
rm -rf javadoc/* rm -rf javadoc/*
rm -rf test-libs/
javadocs: javadocs:
mkdir -p javadoc; javadoc -d javadoc -sourcepath . -subpackages org mkdir -p javadoc; javadoc -d javadoc -sourcepath . -subpackages org -exclude org.rocksdb.test
java: javadocs java: javadocs resolve_test_deps
javac org/rocksdb/util/*.java org/rocksdb/*.java javac org/rocksdb/util/*.java org/rocksdb/*.java
javac -cp $(JAVA_TESTCLASSPATH) org/rocksdb/test/*.java
@cp ../HISTORY.md ./HISTORY-CPP.md @cp ../HISTORY.md ./HISTORY-CPP.md
@rm -f ./HISTORY-CPP.md @rm -f ./HISTORY-CPP.md
javah -d $(NATIVE_INCLUDE) -jni $(NATIVE_JAVA_CLASSES) javah -d $(NATIVE_INCLUDE) -jni $(NATIVE_JAVA_CLASSES)
@ -76,33 +112,16 @@ column_family_sample: java
java -ea -Djava.library.path=.:../ -cp ".:./*" -Xcheck:jni RocksDBColumnFamilySample /tmp/rocksdbjni java -ea -Djava.library.path=.:../ -cp ".:./*" -Xcheck:jni RocksDBColumnFamilySample /tmp/rocksdbjni
@rm -rf /tmp/rocksdbjni @rm -rf /tmp/rocksdbjni
test: java resolve_test_deps:
@rm -rf /tmp/rocksdbjni_* mkdir -p "$(JAVA_TEST_LIBDIR)"
javac org/rocksdb/test/*.java test -s "$(JAVA_JUNIT_JAR)" || curl -k -L -o $(JAVA_JUNIT_JAR) http://search.maven.org/remotecontent?filepath=junit/junit/4.12-beta-2/junit-4.12-beta-2.jar
java -ea -Djava.library.path=.:../ -cp "$(ROCKSDB_JAR):.:./*" org.rocksdb.WriteBatchTest test -s "$(JAVA_HAMCR_JAR)" || curl -k -L -o $(JAVA_HAMCR_JAR) http://search.maven.org/remotecontent?filepath=org/hamcrest/hamcrest-core/1.3/hamcrest-core-1.3.jar
java -ea -Djava.library.path=.:../ -cp "$(ROCKSDB_JAR):.:./*" org.rocksdb.test.BackupableDBTest test -s "$(JAVA_MOCKITO_JAR)" || curl -k -L -o "$(JAVA_MOCKITO_JAR)" http://search.maven.org/remotecontent?filepath=org/mockito/mockito-all/1.9.5/mockito-all-1.9.5.jar
java -ea -Djava.library.path=.:../ -cp "$(ROCKSDB_JAR):.:./*" org.rocksdb.test.BlockBasedTableConfigTest test -s "$(JAVA_CGLIB_JAR)" || curl -k -L -o "$(JAVA_CGLIB_JAR)" http://search.maven.org/remotecontent?filepath=cglib/cglib/2.2.2/cglib-2.2.2.jar
java -ea -Djava.library.path=.:../ -cp "$(ROCKSDB_JAR):.:./*" org.rocksdb.test.DBOptionsTest test -s "$(JAVA_ASSERTJ_JAR)" || curl -k -L -o "$(JAVA_ASSERTJ_JAR)" http://central.maven.org/maven2/org/assertj/assertj-core/1.7.0/assertj-core-1.7.0.jar
java -ea -Djava.library.path=.:../ -cp "$(ROCKSDB_JAR):.:./*" org.rocksdb.test.ColumnFamilyTest
java -ea -Djava.library.path=.:../ -cp "$(ROCKSDB_JAR):.:./*" org.rocksdb.test.ColumnFamilyOptionsTest test: java resolve_test_deps
java -ea -Djava.library.path=.:../ -cp "$(ROCKSDB_JAR):.:./*" org.rocksdb.test.FilterTest java -ea -Djava.library.path=.:../ -cp "$(JAVA_TESTCLASSPATH)" org.rocksdb.test.RocksJunitRunner $(JAVA_TESTS)
java -ea -Djava.library.path=.:../ -cp "$(ROCKSDB_JAR):.:./*" org.rocksdb.test.FlushTest
java -ea -Djava.library.path=.:../ -cp "$(ROCKSDB_JAR):.:./*" org.rocksdb.test.KeyMayExistTest
java -ea -Djava.library.path=.:../ -cp "$(ROCKSDB_JAR):.:./*" org.rocksdb.test.MemTableTest
java -ea -Djava.library.path=.:../ -cp "$(ROCKSDB_JAR):.:./*" org.rocksdb.test.MergeTest
java -ea -Djava.library.path=.:../ -cp "$(ROCKSDB_JAR):.:./*" org.rocksdb.test.MixedOptionsTest
java -ea -Djava.library.path=.:../ -cp "$(ROCKSDB_JAR):.:./*" org.rocksdb.test.OptionsTest
java -ea -Djava.library.path=.:../ -cp "$(ROCKSDB_JAR):.:./*" org.rocksdb.test.PlainTableConfigTest
java -ea -Djava.library.path=.:../ -cp "$(ROCKSDB_JAR):.:./*" org.rocksdb.test.ReadOnlyTest
java -ea -Djava.library.path=.:../ -cp "$(ROCKSDB_JAR):.:./*" org.rocksdb.test.ReadOptionsTest
java -ea -Djava.library.path=.:../ -cp "$(ROCKSDB_JAR):.:./*" org.rocksdb.test.RocksIteratorTest
java -ea -Djava.library.path=.:../ -cp "$(ROCKSDB_JAR):.:./*" org.rocksdb.test.SnapshotTest
java -ea -Djava.library.path=.:../ -cp "$(ROCKSDB_JAR):.:./*" org.rocksdb.test.StatisticsCollectorTest
java -ea -Djava.library.path=.:../ -cp "$(ROCKSDB_JAR):.:./*" org.rocksdb.test.ComparatorOptionsTest
java -ea -Djava.library.path=.:../ -cp "$(ROCKSDB_JAR):.:./*" org.rocksdb.test.ComparatorTest
java -ea -Djava.library.path=.:../ -cp "$(ROCKSDB_JAR):.:./*" org.rocksdb.test.DirectComparatorTest
java -ea -Djava.library.path=.:../ -cp "$(ROCKSDB_JAR):.:./*" org.rocksdb.test.WriteBatchHandlerTest
@rm -rf /tmp/rocksdbjni_*
db_bench: java db_bench: java
javac org/rocksdb/benchmark/*.java javac org/rocksdb/benchmark/*.java

@ -30,9 +30,11 @@ public class ColumnFamilyHandle extends RocksObject {
* before freeing the native handle.</p> * before freeing the native handle.</p>
*/ */
@Override protected void disposeInternal() { @Override protected void disposeInternal() {
assert(isInitialized()); synchronized (rocksDB_) {
if (rocksDB_.isInitialized()) { assert (isInitialized());
disposeInternal(nativeHandle_); if (rocksDB_.isInitialized()) {
disposeInternal(nativeHandle_);
}
} }
} }

@ -1010,7 +1010,6 @@ public class Options extends RocksObject
long cfOptHandle); long cfOptHandle);
private native void disposeInternal(long handle); private native void disposeInternal(long handle);
private native void setEnv(long optHandle, long envHandle); private native void setEnv(long optHandle, long envHandle);
private native long getEnvHandle(long handle);
private native void prepareForBulkLoad(long handle); private native void prepareForBulkLoad(long handle);
// DB native handles // DB native handles

@ -155,7 +155,6 @@ public class ReadOptions extends RocksObject {
@Override protected void disposeInternal() { @Override protected void disposeInternal() {
assert(isInitialized());
disposeInternal(nativeHandle_); disposeInternal(nativeHandle_);
} }
private native void disposeInternal(long handle); private native void disposeInternal(long handle);

@ -103,6 +103,7 @@ public class RocksDB extends RocksObject {
// This allows to use the rocksjni default Options instead of // This allows to use the rocksjni default Options instead of
// the c++ one. // the c++ one.
Options options = new Options(); Options options = new Options();
options.setCreateIfMissing(true);
return open(options, path); return open(options, path);
} }
@ -363,8 +364,10 @@ public class RocksDB extends RocksObject {
} }
@Override protected void disposeInternal() { @Override protected void disposeInternal() {
assert(isInitialized()); synchronized (this) {
disposeInternal(nativeHandle_); assert (isInitialized());
disposeInternal(nativeHandle_);
}
} }
/** /**
@ -1150,6 +1153,8 @@ public class RocksDB extends RocksObject {
throws RocksDBException, IllegalArgumentException { throws RocksDBException, IllegalArgumentException {
// throws RocksDBException if something goes wrong // throws RocksDBException if something goes wrong
dropColumnFamily(nativeHandle_, columnFamilyHandle.nativeHandle_); dropColumnFamily(nativeHandle_, columnFamilyHandle.nativeHandle_);
// After the drop the native handle is not valid anymore
columnFamilyHandle.nativeHandle_ = 0;
} }
/** /**

@ -18,6 +18,7 @@ public class RocksEnv extends RocksObject {
static { static {
default_env_ = new RocksEnv(getDefaultEnvInternal()); default_env_ = new RocksEnv(getDefaultEnvInternal());
} }
private static native long getDefaultEnvInternal(); private static native long getDefaultEnvInternal();
@ -101,7 +102,7 @@ public class RocksEnv extends RocksObject {
* {@link RocksObject} must implement to release their associated C++ * {@link RocksObject} must implement to release their associated C++
* resource. * resource.
*/ */
protected void disposeInternal() { @Override protected void disposeInternal() {
disposeInternal(nativeHandle_); disposeInternal(nativeHandle_);
} }
private native void disposeInternal(long handle); private native void disposeInternal(long handle);

@ -143,9 +143,11 @@ public class RocksIterator extends RocksObject {
* before freeing the native handle.</p> * before freeing the native handle.</p>
*/ */
@Override protected void disposeInternal() { @Override protected void disposeInternal() {
assert(isInitialized()); synchronized (rocksDB_) {
if (rocksDB_.isInitialized()) { assert (isInitialized());
disposeInternal(nativeHandle_); if (rocksDB_.isInitialized()) {
disposeInternal(nativeHandle_);
}
} }
} }

@ -221,13 +221,3 @@ public class WriteBatch extends RocksObject {
private native void disposeInternal(long handle); private native void disposeInternal(long handle);
} }
} }
/**
* Package-private class which provides java api to access
* c++ WriteBatchInternal.
*/
class WriteBatchInternal {
static native void setSequence(WriteBatch batch, long sn);
static native long sequence(WriteBatch batch);
static native void append(WriteBatch b1, WriteBatch b2);
}

@ -1,124 +0,0 @@
// Copyright (c) 2014, Facebook, Inc. All rights reserved.
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree. An additional grant
// of patent rights can be found in the PATENTS file in the same directory.
//
// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.
package org.rocksdb;
import java.util.*;
import java.io.UnsupportedEncodingException;
/**
* This class mimics the db/write_batch_test.cc in the c++ rocksdb library.
*/
public class WriteBatchTest {
static {
RocksDB.loadLibrary();
}
public static void main(String args[]) {
System.out.println("Testing WriteBatchTest.Empty ===");
Empty();
System.out.println("Testing WriteBatchTest.Multiple ===");
Multiple();
System.out.println("Testing WriteBatchTest.Append ===");
Append();
System.out.println("Testing WriteBatchTest.Blob ===");
Blob();
// The following tests have not yet ported.
// Continue();
// PutGatherSlices();
System.out.println("Passed all WriteBatchTest!");
}
static void Empty() {
WriteBatch batch = new WriteBatch();
assert(batch.count() == 0);
}
static void Multiple() {
try {
WriteBatch batch = new WriteBatch();
batch.put("foo".getBytes("US-ASCII"), "bar".getBytes("US-ASCII"));
batch.remove("box".getBytes("US-ASCII"));
batch.put("baz".getBytes("US-ASCII"), "boo".getBytes("US-ASCII"));
WriteBatchInternal.setSequence(batch, 100);
assert(100 == WriteBatchInternal.sequence(batch));
assert(3 == batch.count());
assert(("Put(baz, boo)@102" +
"Delete(box)@101" +
"Put(foo, bar)@100")
.equals(new String(getContents(batch), "US-ASCII")));
} catch (UnsupportedEncodingException e) {
System.err.println(e);
assert(false);
}
}
static void Append() {
WriteBatch b1 = new WriteBatch();
WriteBatch b2 = new WriteBatch();
WriteBatchInternal.setSequence(b1, 200);
WriteBatchInternal.setSequence(b2, 300);
WriteBatchInternal.append(b1, b2);
assert(getContents(b1).length == 0);
assert(b1.count() == 0);
try {
b2.put("a".getBytes("US-ASCII"), "va".getBytes("US-ASCII"));
WriteBatchInternal.append(b1, b2);
assert("Put(a, va)@200".equals(new String(getContents(b1), "US-ASCII")));
assert(1 == b1.count());
b2.clear();
b2.put("b".getBytes("US-ASCII"), "vb".getBytes("US-ASCII"));
WriteBatchInternal.append(b1, b2);
assert(("Put(a, va)@200" +
"Put(b, vb)@201")
.equals(new String(getContents(b1), "US-ASCII")));
assert(2 == b1.count());
b2.remove("foo".getBytes("US-ASCII"));
WriteBatchInternal.append(b1, b2);
assert(("Put(a, va)@200" +
"Put(b, vb)@202" +
"Put(b, vb)@201" +
"Delete(foo)@203")
.equals(new String(getContents(b1), "US-ASCII")));
assert(4 == b1.count());
} catch (UnsupportedEncodingException e) {
System.err.println(e);
assert(false);
}
}
static void Blob() {
WriteBatch batch = new WriteBatch();
try {
batch.put("k1".getBytes("US-ASCII"), "v1".getBytes("US-ASCII"));
batch.put("k2".getBytes("US-ASCII"), "v2".getBytes("US-ASCII"));
batch.put("k3".getBytes("US-ASCII"), "v3".getBytes("US-ASCII"));
batch.putLogData("blob1".getBytes("US-ASCII"));
batch.remove("k2".getBytes("US-ASCII"));
batch.putLogData("blob2".getBytes("US-ASCII"));
batch.merge("foo".getBytes("US-ASCII"), "bar".getBytes("US-ASCII"));
assert(5 == batch.count());
assert(("Merge(foo, bar)@4" +
"Put(k1, v1)@0" +
"Delete(k2)@3" +
"Put(k2, v2)@1" +
"Put(k3, v3)@2")
.equals(new String(getContents(batch), "US-ASCII")));
} catch (UnsupportedEncodingException e) {
System.err.println(e);
assert(false);
}
}
static native byte[] getContents(WriteBatch batch);
}

@ -12,6 +12,7 @@ import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes; import java.nio.file.attribute.BasicFileAttributes;
import java.util.Random; import java.util.Random;
import static org.assertj.core.api.Assertions.assertThat;
import static org.rocksdb.test.Types.byteToInt; import static org.rocksdb.test.Types.byteToInt;
import static org.rocksdb.test.Types.intToByte; import static org.rocksdb.test.Types.intToByte;
@ -75,13 +76,13 @@ public abstract class AbstractComparatorTest {
int count = 0; int count = 0;
for (it.seekToFirst(); it.isValid(); it.next()) { for (it.seekToFirst(); it.isValid(); it.next()) {
final int thisKey = byteToInt(it.key()); final int thisKey = byteToInt(it.key());
assert(thisKey > lastKey); assertThat(thisKey).isGreaterThan(lastKey);
lastKey = thisKey; lastKey = thisKey;
count++; count++;
} }
db.close(); db.close();
assert(count == ITERATIONS); assertThat(count).isEqualTo(ITERATIONS);
} catch (final RocksDBException e) { } catch (final RocksDBException e) {
System.err.format("[ERROR]: %s%n", e); System.err.format("[ERROR]: %s%n", e);

@ -5,121 +5,161 @@
package org.rocksdb.test; package org.rocksdb.test;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.rocksdb.*; import org.rocksdb.*;
import java.util.List; import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
public class BackupableDBTest { public class BackupableDBTest {
static final String db_path = "/tmp/rocksdbjni_backupable_db_test";
static final String backup_path = "/tmp/rocksdbjni_backupable_db_backup_test";
static {
RocksDB.loadLibrary();
}
public static void main(String[] args) {
Options opt = new Options(); @ClassRule
opt.setCreateIfMissing(true); public static final RocksMemoryResource rocksMemoryResource =
new RocksMemoryResource();
@Rule
public TemporaryFolder dbFolder = new TemporaryFolder();
BackupableDBOptions bopt = new BackupableDBOptions(backup_path, false, @Rule
true, false, true, 0, 0); public TemporaryFolder backupFolder = new TemporaryFolder();
@Test
public void backupableDb() throws RocksDBException {
Options opt = null;
BackupableDBOptions bopt = null;
BackupableDB bdb = null; BackupableDB bdb = null;
List<BackupInfo> backupInfos; RestoreOptions ropt = null;
List<BackupInfo> restoreInfos; RestoreBackupableDB rdb = null;
try { try {
bdb = BackupableDB.open(opt, bopt, db_path); opt = new Options();
opt.setCreateIfMissing(true);
bopt = new BackupableDBOptions(
backupFolder.getRoot().getAbsolutePath(), false,
true, false, true, 0, 0);
assertThat(bopt.backupDir()).isEqualTo(
backupFolder.getRoot().getAbsolutePath());
List<BackupInfo> backupInfos;
List<BackupInfo> restoreInfos;
bdb = BackupableDB.open(opt, bopt,
dbFolder.getRoot().getAbsolutePath());
bdb.put("abc".getBytes(), "def".getBytes()); bdb.put("abc".getBytes(), "def".getBytes());
bdb.put("ghi".getBytes(), "jkl".getBytes()); bdb.put("ghi".getBytes(), "jkl".getBytes());
backupInfos = bdb.getBackupInfos(); backupInfos = bdb.getBackupInfos();
assert(backupInfos.size() == 0); assertThat(backupInfos.size()).
isEqualTo(0);
bdb.createNewBackup(true); bdb.createNewBackup(true);
backupInfos = bdb.getBackupInfos(); backupInfos = bdb.getBackupInfos();
assert(backupInfos.size() == 1); assertThat(backupInfos.size()).
isEqualTo(1);
// Retrieving backup infos twice shall not // Retrieving backup infos twice shall not
// lead to different results // lead to different results
List<BackupInfo> tmpBackupInfo = bdb.getBackupInfos(); List<BackupInfo> tmpBackupInfo = bdb.getBackupInfos();
assert(tmpBackupInfo.get(0).backupId() == assertThat(tmpBackupInfo.get(0).backupId()).
backupInfos.get(0).backupId()); isEqualTo(backupInfos.get(0).backupId());
assert(tmpBackupInfo.get(0).timestamp() == assertThat(tmpBackupInfo.get(0).timestamp()).
backupInfos.get(0).timestamp()); isEqualTo(backupInfos.get(0).timestamp());
assert(tmpBackupInfo.get(0).size() == assertThat(tmpBackupInfo.get(0).size()).
backupInfos.get(0).size()); isEqualTo(backupInfos.get(0).size());
assert(tmpBackupInfo.get(0).numberFiles() == assertThat(tmpBackupInfo.get(0).numberFiles()).
backupInfos.get(0).numberFiles()); isEqualTo(backupInfos.get(0).numberFiles());
// delete record after backup // delete record after backup
bdb.remove("abc".getBytes()); bdb.remove("abc".getBytes());
byte[] value = bdb.get("abc".getBytes()); byte[] value = bdb.get("abc".getBytes());
assert(value == null); assertThat(value).isNull();
bdb.close(); bdb.close();
// restore from backup // restore from backup
RestoreOptions ropt = new RestoreOptions(false); ropt = new RestoreOptions(false);
RestoreBackupableDB rdb = new RestoreBackupableDB(bopt); rdb = new RestoreBackupableDB(bopt);
// getting backup infos from restorable db should // getting backup infos from restorable db should
// lead to the same infos as from backupable db // lead to the same infos as from backupable db
restoreInfos = rdb.getBackupInfos(); restoreInfos = rdb.getBackupInfos();
assert(restoreInfos.size() == backupInfos.size()); assertThat(restoreInfos.size()).
assert(restoreInfos.get(0).backupId() == isEqualTo(backupInfos.size());
backupInfos.get(0).backupId()); assertThat(restoreInfos.get(0).backupId()).
assert(restoreInfos.get(0).timestamp() == isEqualTo(backupInfos.get(0).backupId());
backupInfos.get(0).timestamp()); assertThat(restoreInfos.get(0).timestamp()).
assert(restoreInfos.get(0).size() == isEqualTo(backupInfos.get(0).timestamp());
backupInfos.get(0).size()); assertThat(restoreInfos.get(0).size()).
assert(restoreInfos.get(0).numberFiles() == isEqualTo(backupInfos.get(0).size());
backupInfos.get(0).numberFiles()); assertThat(restoreInfos.get(0).numberFiles()).
isEqualTo(backupInfos.get(0).numberFiles());
rdb.restoreDBFromLatestBackup(db_path, db_path,
rdb.restoreDBFromLatestBackup(
dbFolder.getRoot().getAbsolutePath(),
dbFolder.getRoot().getAbsolutePath(),
ropt); ropt);
// do nothing because there is only one backup // do nothing because there is only one backup
rdb.purgeOldBackups(1); rdb.purgeOldBackups(1);
restoreInfos = rdb.getBackupInfos(); restoreInfos = rdb.getBackupInfos();
assert(restoreInfos.size() == 1); assertThat(restoreInfos.size()).
isEqualTo(1);
rdb.dispose(); rdb.dispose();
ropt.dispose(); ropt.dispose();
// verify that backed up data contains deleted record // verify that backed up data contains deleted record
bdb = BackupableDB.open(opt, bopt, db_path); bdb = BackupableDB.open(opt, bopt,
dbFolder.getRoot().getAbsolutePath());
value = bdb.get("abc".getBytes()); value = bdb.get("abc".getBytes());
assert(new String(value).equals("def")); assertThat(new String(value)).
isEqualTo("def");
bdb.createNewBackup(false); bdb.createNewBackup(false);
// after new backup there must be two backup infos // after new backup there must be two backup infos
backupInfos = bdb.getBackupInfos(); backupInfos = bdb.getBackupInfos();
assert(backupInfos.size() == 2); assertThat(backupInfos.size()).
isEqualTo(2);
// deleting the backup must be possible using the // deleting the backup must be possible using the
// id provided by backup infos // id provided by backup infos
bdb.deleteBackup(backupInfos.get(1).backupId()); bdb.deleteBackup(backupInfos.get(1).backupId());
// after deletion there should only be one info // after deletion there should only be one info
backupInfos = bdb.getBackupInfos(); backupInfos = bdb.getBackupInfos();
assert(backupInfos.size() == 1); assertThat(backupInfos.size()).
isEqualTo(1);
bdb.createNewBackup(false); bdb.createNewBackup(false);
bdb.createNewBackup(false); bdb.createNewBackup(false);
bdb.createNewBackup(false); bdb.createNewBackup(false);
backupInfos = bdb.getBackupInfos(); backupInfos = bdb.getBackupInfos();
assert(backupInfos.size() == 4); assertThat(backupInfos.size()).
isEqualTo(4);
// purge everything and keep two // purge everything and keep two
bdb.purgeOldBackups(2); bdb.purgeOldBackups(2);
// backup infos need to be two // backup infos need to be two
backupInfos = bdb.getBackupInfos(); backupInfos = bdb.getBackupInfos();
assert(backupInfos.size() == 2); assertThat(backupInfos.size()).
assert(backupInfos.get(0).backupId() == 4); isEqualTo(2);
assert(backupInfos.get(1).backupId() == 5); assertThat(backupInfos.get(0).backupId()).
System.out.println("Backup and restore test passed"); isEqualTo(4);
} catch (RocksDBException e) { assertThat(backupInfos.get(1).backupId()).
System.err.format("[ERROR]: %s%n", e); isEqualTo(5);
e.printStackTrace();
} finally { } finally {
opt.dispose(); if (opt != null) {
bopt.dispose(); opt.dispose();
}
if (bopt != null) {
bopt.dispose();
}
if (bdb != null) { if (bdb != null) {
bdb.close(); bdb.close();
} }
if (ropt != null) {
ropt.dispose();
}
if (rdb != null) {
rdb.dispose();
}
} }
} }
} }

@ -5,43 +5,158 @@
package org.rocksdb.test; package org.rocksdb.test;
import org.rocksdb.BlockBasedTableConfig; import org.junit.ClassRule;
import org.rocksdb.ChecksumType; import org.junit.Test;
import org.rocksdb.IndexType; import org.rocksdb.*;
import static org.assertj.core.api.Assertions.assertThat;
public class BlockBasedTableConfigTest { public class BlockBasedTableConfigTest {
public static void main(String[] args) { @ClassRule
BlockBasedTableConfig blockBasedTableConfig = public static final RocksMemoryResource rocksMemoryResource =
new BlockBasedTableConfig(); new RocksMemoryResource();
@Test
public void noBlockCache() {
BlockBasedTableConfig blockBasedTableConfig = new BlockBasedTableConfig();
blockBasedTableConfig.setNoBlockCache(true); blockBasedTableConfig.setNoBlockCache(true);
assert(blockBasedTableConfig.noBlockCache()); assertThat(blockBasedTableConfig.noBlockCache()).isTrue();
blockBasedTableConfig.setBlockCacheSize(8*1024); }
assert(blockBasedTableConfig.blockCacheSize() == (8*1024));
@Test
public void blockCacheSize() {
BlockBasedTableConfig blockBasedTableConfig = new BlockBasedTableConfig();
blockBasedTableConfig.setBlockCacheSize(8 * 1024);
assertThat(blockBasedTableConfig.blockCacheSize()).
isEqualTo(8 * 1024);
}
@Test
public void blockSizeDeviation() {
BlockBasedTableConfig blockBasedTableConfig = new BlockBasedTableConfig();
blockBasedTableConfig.setBlockSizeDeviation(12); blockBasedTableConfig.setBlockSizeDeviation(12);
assert(blockBasedTableConfig.blockSizeDeviation() == 12); assertThat(blockBasedTableConfig.blockSizeDeviation()).
isEqualTo(12);
}
@Test
public void blockRestartInterval() {
BlockBasedTableConfig blockBasedTableConfig = new BlockBasedTableConfig();
blockBasedTableConfig.setBlockRestartInterval(15); blockBasedTableConfig.setBlockRestartInterval(15);
assert(blockBasedTableConfig.blockRestartInterval() == 15); assertThat(blockBasedTableConfig.blockRestartInterval()).
isEqualTo(15);
}
@Test
public void wholeKeyFiltering() {
BlockBasedTableConfig blockBasedTableConfig = new BlockBasedTableConfig();
blockBasedTableConfig.setWholeKeyFiltering(false); blockBasedTableConfig.setWholeKeyFiltering(false);
assert(!blockBasedTableConfig.wholeKeyFiltering()); assertThat(blockBasedTableConfig.wholeKeyFiltering()).
isFalse();
}
@Test
public void cacheIndexAndFilterBlocks() {
BlockBasedTableConfig blockBasedTableConfig = new BlockBasedTableConfig();
blockBasedTableConfig.setCacheIndexAndFilterBlocks(true); blockBasedTableConfig.setCacheIndexAndFilterBlocks(true);
assert(blockBasedTableConfig.cacheIndexAndFilterBlocks()); assertThat(blockBasedTableConfig.cacheIndexAndFilterBlocks()).
isTrue();
}
@Test
public void hashIndexAllowCollision() {
BlockBasedTableConfig blockBasedTableConfig = new BlockBasedTableConfig();
blockBasedTableConfig.setHashIndexAllowCollision(false); blockBasedTableConfig.setHashIndexAllowCollision(false);
assert(!blockBasedTableConfig.hashIndexAllowCollision()); assertThat(blockBasedTableConfig.hashIndexAllowCollision()).
isFalse();
}
@Test
public void blockCacheCompressedSize() {
BlockBasedTableConfig blockBasedTableConfig = new BlockBasedTableConfig();
blockBasedTableConfig.setBlockCacheCompressedSize(40); blockBasedTableConfig.setBlockCacheCompressedSize(40);
assert(blockBasedTableConfig.blockCacheCompressedSize() == 40); assertThat(blockBasedTableConfig.blockCacheCompressedSize()).
isEqualTo(40);
}
@Test
public void checksumType() {
BlockBasedTableConfig blockBasedTableConfig = new BlockBasedTableConfig();
blockBasedTableConfig.setChecksumType(ChecksumType.kNoChecksum); blockBasedTableConfig.setChecksumType(ChecksumType.kNoChecksum);
blockBasedTableConfig.setChecksumType(ChecksumType.kxxHash); blockBasedTableConfig.setChecksumType(ChecksumType.kxxHash);
assert(blockBasedTableConfig.checksumType().equals( assertThat(blockBasedTableConfig.checksumType().equals(
ChecksumType.kxxHash)); ChecksumType.kxxHash));
}
@Test
public void indexType() {
BlockBasedTableConfig blockBasedTableConfig = new BlockBasedTableConfig();
assertThat(IndexType.values().length).isEqualTo(2);
blockBasedTableConfig.setIndexType(IndexType.kHashSearch); blockBasedTableConfig.setIndexType(IndexType.kHashSearch);
assert(blockBasedTableConfig.indexType().equals( assertThat(blockBasedTableConfig.indexType().equals(
IndexType.kHashSearch)); IndexType.kHashSearch));
assertThat(IndexType.valueOf("kBinarySearch")).isNotNull();
blockBasedTableConfig.setIndexType(IndexType.valueOf("kBinarySearch"));
assertThat(blockBasedTableConfig.indexType().equals(
IndexType.kBinarySearch));
}
@Test
public void blockCacheCompressedNumShardBits() {
BlockBasedTableConfig blockBasedTableConfig = new BlockBasedTableConfig();
blockBasedTableConfig.setBlockCacheCompressedNumShardBits(4); blockBasedTableConfig.setBlockCacheCompressedNumShardBits(4);
assert(blockBasedTableConfig.blockCacheCompressedNumShardBits() assertThat(blockBasedTableConfig.blockCacheCompressedNumShardBits()).
== 4); isEqualTo(4);
}
@Test
public void cacheNumShardBits() {
BlockBasedTableConfig blockBasedTableConfig = new BlockBasedTableConfig();
blockBasedTableConfig.setCacheNumShardBits(5); blockBasedTableConfig.setCacheNumShardBits(5);
assert(blockBasedTableConfig.cacheNumShardBits() == 5); assertThat(blockBasedTableConfig.cacheNumShardBits()).
System.out.println("BlockBasedTableConfig test passed"); isEqualTo(5);
}
@Test
public void blockSize() {
BlockBasedTableConfig blockBasedTableConfig = new BlockBasedTableConfig();
blockBasedTableConfig.setBlockSize(10);
assertThat(blockBasedTableConfig.blockSize()).isEqualTo(10);
}
@Test
public void blockBasedTableWithFilter() {
Options options = null;
try {
options = new Options();
options.setTableFormatConfig(
new BlockBasedTableConfig().setFilter(
new BloomFilter(10)));
assertThat(options.tableFactoryName()).
isEqualTo("BlockBasedTable");
} finally {
if (options != null) {
options.dispose();
}
}
}
@Test
public void blockBasedTableWithoutFilter() {
Options options = null;
try {
options = new Options();
options.setTableFormatConfig(
new BlockBasedTableConfig().setFilter(null));
assertThat(options.tableFactoryName()).
isEqualTo("BlockBasedTable");
} finally {
if (options != null) {
options.dispose();
}
}
} }
} }

@ -5,225 +5,584 @@
package org.rocksdb.test; package org.rocksdb.test;
import org.junit.ClassRule;
import org.junit.Test;
import org.rocksdb.*; import org.rocksdb.*;
import java.util.Random; import java.util.Random;
import static org.assertj.core.api.Assertions.assertThat;
public class ColumnFamilyOptionsTest { public class ColumnFamilyOptionsTest {
static {
RocksDB.loadLibrary();
}
public static void testCFOptions(ColumnFamilyOptionsInterface opt) { @ClassRule
Random rand = PlatformRandomHelper. public static final RocksMemoryResource rocksMemoryResource =
getPlatformSpecificRandomFactory(); new RocksMemoryResource();
{ // WriteBufferSize test
try { public static final Random rand = PlatformRandomHelper.
long longValue = rand.nextLong(); getPlatformSpecificRandomFactory();
opt.setWriteBufferSize(longValue);
assert(opt.writeBufferSize() == longValue); @Test
} catch (RocksDBException e) { public void writeBufferSize() throws RocksDBException {
assert(false); ColumnFamilyOptions opt = null;
try {
opt = new ColumnFamilyOptions();
long longValue = rand.nextLong();
opt.setWriteBufferSize(longValue);
assertThat(opt.writeBufferSize()).isEqualTo(longValue);
} finally {
if (opt != null) {
opt.dispose();
} }
} }
}
{ // MaxWriteBufferNumber test @Test
public void maxWriteBufferNumber() {
ColumnFamilyOptions opt = null;
try {
opt = new ColumnFamilyOptions();
int intValue = rand.nextInt(); int intValue = rand.nextInt();
opt.setMaxWriteBufferNumber(intValue); opt.setMaxWriteBufferNumber(intValue);
assert(opt.maxWriteBufferNumber() == intValue); assertThat(opt.maxWriteBufferNumber()).isEqualTo(intValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
}
{ // MinWriteBufferNumberToMerge test @Test
public void minWriteBufferNumberToMerge() {
ColumnFamilyOptions opt = null;
try {
opt = new ColumnFamilyOptions();
int intValue = rand.nextInt(); int intValue = rand.nextInt();
opt.setMinWriteBufferNumberToMerge(intValue); opt.setMinWriteBufferNumberToMerge(intValue);
assert(opt.minWriteBufferNumberToMerge() == intValue); assertThat(opt.minWriteBufferNumberToMerge()).isEqualTo(intValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
}
{ // NumLevels test @Test
public void numLevels() {
ColumnFamilyOptions opt = null;
try {
opt = new ColumnFamilyOptions();
int intValue = rand.nextInt(); int intValue = rand.nextInt();
opt.setNumLevels(intValue); opt.setNumLevels(intValue);
assert(opt.numLevels() == intValue); assertThat(opt.numLevels()).isEqualTo(intValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
}
{ // LevelFileNumCompactionTrigger test @Test
public void levelZeroFileNumCompactionTrigger() {
ColumnFamilyOptions opt = null;
try {
opt = new ColumnFamilyOptions();
int intValue = rand.nextInt(); int intValue = rand.nextInt();
opt.setLevelZeroFileNumCompactionTrigger(intValue); opt.setLevelZeroFileNumCompactionTrigger(intValue);
assert(opt.levelZeroFileNumCompactionTrigger() == intValue); assertThat(opt.levelZeroFileNumCompactionTrigger()).isEqualTo(intValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
}
{ // LevelSlowdownWritesTrigger test @Test
public void levelZeroSlowdownWritesTrigger() {
ColumnFamilyOptions opt = null;
try {
opt = new ColumnFamilyOptions();
int intValue = rand.nextInt(); int intValue = rand.nextInt();
opt.setLevelZeroSlowdownWritesTrigger(intValue); opt.setLevelZeroSlowdownWritesTrigger(intValue);
assert(opt.levelZeroSlowdownWritesTrigger() == intValue); assertThat(opt.levelZeroSlowdownWritesTrigger()).isEqualTo(intValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
}
{ // LevelStopWritesTrigger test @Test
public void levelZeroStopWritesTrigger() {
ColumnFamilyOptions opt = null;
try {
opt = new ColumnFamilyOptions();
int intValue = rand.nextInt(); int intValue = rand.nextInt();
opt.setLevelZeroStopWritesTrigger(intValue); opt.setLevelZeroStopWritesTrigger(intValue);
assert(opt.levelZeroStopWritesTrigger() == intValue); assertThat(opt.levelZeroStopWritesTrigger()).isEqualTo(intValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
}
{ // MaxMemCompactionLevel test @Test
public void maxMemCompactionLevel() {
ColumnFamilyOptions opt = null;
try {
opt = new ColumnFamilyOptions();
int intValue = rand.nextInt(); int intValue = rand.nextInt();
opt.setMaxMemCompactionLevel(intValue); opt.setMaxMemCompactionLevel(intValue);
assert(opt.maxMemCompactionLevel() == intValue); assertThat(opt.maxMemCompactionLevel()).isEqualTo(intValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
}
{ // TargetFileSizeBase test @Test
public void targetFileSizeBase() {
ColumnFamilyOptions opt = null;
try {
opt = new ColumnFamilyOptions();
long longValue = rand.nextLong(); long longValue = rand.nextLong();
opt.setTargetFileSizeBase(longValue); opt.setTargetFileSizeBase(longValue);
assert(opt.targetFileSizeBase() == longValue); assertThat(opt.targetFileSizeBase()).isEqualTo(longValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
}
{ // TargetFileSizeMultiplier test @Test
public void targetFileSizeMultiplier() {
ColumnFamilyOptions opt = null;
try {
opt = new ColumnFamilyOptions();
int intValue = rand.nextInt(); int intValue = rand.nextInt();
opt.setTargetFileSizeMultiplier(intValue); opt.setTargetFileSizeMultiplier(intValue);
assert(opt.targetFileSizeMultiplier() == intValue); assertThat(opt.targetFileSizeMultiplier()).isEqualTo(intValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
}
{ // MaxBytesForLevelBase test @Test
public void maxBytesForLevelBase() {
ColumnFamilyOptions opt = null;
try {
opt = new ColumnFamilyOptions();
long longValue = rand.nextLong(); long longValue = rand.nextLong();
opt.setMaxBytesForLevelBase(longValue); opt.setMaxBytesForLevelBase(longValue);
assert(opt.maxBytesForLevelBase() == longValue); assertThat(opt.maxBytesForLevelBase()).isEqualTo(longValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
}
{ // MaxBytesForLevelMultiplier test @Test
public void maxBytesForLevelMultiplier() {
ColumnFamilyOptions opt = null;
try {
opt = new ColumnFamilyOptions();
int intValue = rand.nextInt(); int intValue = rand.nextInt();
opt.setMaxBytesForLevelMultiplier(intValue); opt.setMaxBytesForLevelMultiplier(intValue);
assert(opt.maxBytesForLevelMultiplier() == intValue); assertThat(opt.maxBytesForLevelMultiplier()).isEqualTo(intValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
}
{ // ExpandedCompactionFactor test @Test
public void expandedCompactionFactor() {
ColumnFamilyOptions opt = null;
try {
opt = new ColumnFamilyOptions();
int intValue = rand.nextInt(); int intValue = rand.nextInt();
opt.setExpandedCompactionFactor(intValue); opt.setExpandedCompactionFactor(intValue);
assert(opt.expandedCompactionFactor() == intValue); assertThat(opt.expandedCompactionFactor()).isEqualTo(intValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
}
{ // SourceCompactionFactor test @Test
public void sourceCompactionFactor() {
ColumnFamilyOptions opt = null;
try {
opt = new ColumnFamilyOptions();
int intValue = rand.nextInt(); int intValue = rand.nextInt();
opt.setSourceCompactionFactor(intValue); opt.setSourceCompactionFactor(intValue);
assert(opt.sourceCompactionFactor() == intValue); assertThat(opt.sourceCompactionFactor()).isEqualTo(intValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
}
{ // MaxGrandparentOverlapFactor test @Test
public void maxGrandparentOverlapFactor() {
ColumnFamilyOptions opt = null;
try {
opt = new ColumnFamilyOptions();
int intValue = rand.nextInt(); int intValue = rand.nextInt();
opt.setMaxGrandparentOverlapFactor(intValue); opt.setMaxGrandparentOverlapFactor(intValue);
assert(opt.maxGrandparentOverlapFactor() == intValue); assertThat(opt.maxGrandparentOverlapFactor()).isEqualTo(intValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
}
{ // SoftRateLimit test @Test
public void softRateLimit() {
ColumnFamilyOptions opt = null;
try {
opt = new ColumnFamilyOptions();
double doubleValue = rand.nextDouble(); double doubleValue = rand.nextDouble();
opt.setSoftRateLimit(doubleValue); opt.setSoftRateLimit(doubleValue);
assert(opt.softRateLimit() == doubleValue); assertThat(opt.softRateLimit()).isEqualTo(doubleValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
}
{ // HardRateLimit test @Test
public void hardRateLimit() {
ColumnFamilyOptions opt = null;
try {
opt = new ColumnFamilyOptions();
double doubleValue = rand.nextDouble(); double doubleValue = rand.nextDouble();
opt.setHardRateLimit(doubleValue); opt.setHardRateLimit(doubleValue);
assert(opt.hardRateLimit() == doubleValue); assertThat(opt.hardRateLimit()).isEqualTo(doubleValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
}
{ // RateLimitDelayMaxMilliseconds test @Test
public void rateLimitDelayMaxMilliseconds() {
ColumnFamilyOptions opt = null;
try {
opt = new ColumnFamilyOptions();
int intValue = rand.nextInt(); int intValue = rand.nextInt();
opt.setRateLimitDelayMaxMilliseconds(intValue); opt.setRateLimitDelayMaxMilliseconds(intValue);
assert(opt.rateLimitDelayMaxMilliseconds() == intValue); assertThat(opt.rateLimitDelayMaxMilliseconds()).isEqualTo(intValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
}
{ // ArenaBlockSize test @Test
try { public void arenaBlockSize() throws RocksDBException {
long longValue = rand.nextLong(); ColumnFamilyOptions opt = null;
opt.setArenaBlockSize(longValue); try {
assert(opt.arenaBlockSize() == longValue); opt = new ColumnFamilyOptions();
} catch (RocksDBException e) { long longValue = rand.nextLong();
assert(false); opt.setArenaBlockSize(longValue);
assertThat(opt.arenaBlockSize()).isEqualTo(longValue);
} finally {
if (opt != null) {
opt.dispose();
} }
} }
}
{ // DisableAutoCompactions test @Test
public void disableAutoCompactions() {
ColumnFamilyOptions opt = null;
try {
opt = new ColumnFamilyOptions();
boolean boolValue = rand.nextBoolean(); boolean boolValue = rand.nextBoolean();
opt.setDisableAutoCompactions(boolValue); opt.setDisableAutoCompactions(boolValue);
assert(opt.disableAutoCompactions() == boolValue); assertThat(opt.disableAutoCompactions()).isEqualTo(boolValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
}
{ // PurgeRedundantKvsWhileFlush test @Test
public void purgeRedundantKvsWhileFlush() {
ColumnFamilyOptions opt = null;
try {
opt = new ColumnFamilyOptions();
boolean boolValue = rand.nextBoolean(); boolean boolValue = rand.nextBoolean();
opt.setPurgeRedundantKvsWhileFlush(boolValue); opt.setPurgeRedundantKvsWhileFlush(boolValue);
assert(opt.purgeRedundantKvsWhileFlush() == boolValue); assertThat(opt.purgeRedundantKvsWhileFlush()).isEqualTo(boolValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
}
{ // VerifyChecksumsInCompaction test @Test
public void verifyChecksumsInCompaction() {
ColumnFamilyOptions opt = null;
try {
opt = new ColumnFamilyOptions();
boolean boolValue = rand.nextBoolean(); boolean boolValue = rand.nextBoolean();
opt.setVerifyChecksumsInCompaction(boolValue); opt.setVerifyChecksumsInCompaction(boolValue);
assert(opt.verifyChecksumsInCompaction() == boolValue); assertThat(opt.verifyChecksumsInCompaction()).isEqualTo(boolValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
}
{ // FilterDeletes test @Test
public void filterDeletes() {
ColumnFamilyOptions opt = null;
try {
opt = new ColumnFamilyOptions();
boolean boolValue = rand.nextBoolean(); boolean boolValue = rand.nextBoolean();
opt.setFilterDeletes(boolValue); opt.setFilterDeletes(boolValue);
assert(opt.filterDeletes() == boolValue); assertThat(opt.filterDeletes()).isEqualTo(boolValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
}
{ // MaxSequentialSkipInIterations test @Test
public void maxSequentialSkipInIterations() {
ColumnFamilyOptions opt = null;
try {
opt = new ColumnFamilyOptions();
long longValue = rand.nextLong(); long longValue = rand.nextLong();
opt.setMaxSequentialSkipInIterations(longValue); opt.setMaxSequentialSkipInIterations(longValue);
assert(opt.maxSequentialSkipInIterations() == longValue); assertThat(opt.maxSequentialSkipInIterations()).isEqualTo(longValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
}
{ // InplaceUpdateSupport test @Test
public void inplaceUpdateSupport() {
ColumnFamilyOptions opt = null;
try {
opt = new ColumnFamilyOptions();
boolean boolValue = rand.nextBoolean(); boolean boolValue = rand.nextBoolean();
opt.setInplaceUpdateSupport(boolValue); opt.setInplaceUpdateSupport(boolValue);
assert(opt.inplaceUpdateSupport() == boolValue); assertThat(opt.inplaceUpdateSupport()).isEqualTo(boolValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
}
{ // InplaceUpdateNumLocks test @Test
try { public void inplaceUpdateNumLocks() throws RocksDBException {
long longValue = rand.nextLong(); ColumnFamilyOptions opt = null;
opt.setInplaceUpdateNumLocks(longValue); try {
assert(opt.inplaceUpdateNumLocks() == longValue); opt = new ColumnFamilyOptions();
} catch (RocksDBException e) { long longValue = rand.nextLong();
assert(false); opt.setInplaceUpdateNumLocks(longValue);
assertThat(opt.inplaceUpdateNumLocks()).isEqualTo(longValue);
} finally {
if (opt != null) {
opt.dispose();
} }
} }
}
{ // MemtablePrefixBloomBits test @Test
public void memtablePrefixBloomBits() {
ColumnFamilyOptions opt = null;
try {
opt = new ColumnFamilyOptions();
int intValue = rand.nextInt(); int intValue = rand.nextInt();
opt.setMemtablePrefixBloomBits(intValue); opt.setMemtablePrefixBloomBits(intValue);
assert(opt.memtablePrefixBloomBits() == intValue); assertThat(opt.memtablePrefixBloomBits()).isEqualTo(intValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
}
{ // MemtablePrefixBloomProbes test @Test
public void memtablePrefixBloomProbes() {
ColumnFamilyOptions opt = null;
try {
int intValue = rand.nextInt(); int intValue = rand.nextInt();
opt = new ColumnFamilyOptions();
opt.setMemtablePrefixBloomProbes(intValue); opt.setMemtablePrefixBloomProbes(intValue);
assert(opt.memtablePrefixBloomProbes() == intValue); assertThat(opt.memtablePrefixBloomProbes()).isEqualTo(intValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
}
{ // BloomLocality test @Test
public void bloomLocality() {
ColumnFamilyOptions opt = null;
try {
int intValue = rand.nextInt(); int intValue = rand.nextInt();
opt = new ColumnFamilyOptions();
opt.setBloomLocality(intValue); opt.setBloomLocality(intValue);
assert(opt.bloomLocality() == intValue); assertThat(opt.bloomLocality()).isEqualTo(intValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
}
{ // MaxSuccessiveMerges test @Test
try { public void maxSuccessiveMerges() throws RocksDBException {
long longValue = rand.nextLong(); ColumnFamilyOptions opt = null;
opt.setMaxSuccessiveMerges(longValue); try {
assert(opt.maxSuccessiveMerges() == longValue); long longValue = rand.nextLong();
} catch (RocksDBException e){ opt = new ColumnFamilyOptions();
assert(false); opt.setMaxSuccessiveMerges(longValue);
assertThat(opt.maxSuccessiveMerges()).isEqualTo(longValue);
} finally {
if (opt != null) {
opt.dispose();
} }
} }
}
{ // MinPartialMergeOperands test @Test
public void minPartialMergeOperands() {
ColumnFamilyOptions opt = null;
try {
int intValue = rand.nextInt(); int intValue = rand.nextInt();
opt = new ColumnFamilyOptions();
opt.setMinPartialMergeOperands(intValue); opt.setMinPartialMergeOperands(intValue);
assert(opt.minPartialMergeOperands() == intValue); assertThat(opt.minPartialMergeOperands()).isEqualTo(intValue);
} finally {
if (opt != null) {
opt.dispose();
}
}
}
@Test
public void memTable() throws RocksDBException {
ColumnFamilyOptions opt = null;
try {
opt = new ColumnFamilyOptions();
opt.setMemTableConfig(new HashLinkedListMemTableConfig());
assertThat(opt.memTableFactoryName()).
isEqualTo("HashLinkedListRepFactory");
} finally {
if (opt != null) {
opt.dispose();
}
}
}
@Test
public void comparator() throws RocksDBException {
ColumnFamilyOptions opt = null;
try {
opt = new ColumnFamilyOptions();
opt.setComparator(BuiltinComparator.BYTEWISE_COMPARATOR);
} finally {
if (opt != null) {
opt.dispose();
}
}
}
@Test
public void linkageOfPrepMethods() {
ColumnFamilyOptions options = null;
try {
options = new ColumnFamilyOptions();
options.optimizeUniversalStyleCompaction();
options.optimizeUniversalStyleCompaction(4000);
options.optimizeLevelStyleCompaction();
options.optimizeLevelStyleCompaction(3000);
options.optimizeForPointLookup(10);
} finally {
if (options != null) {
options.dispose();
}
}
}
@Test
public void shouldSetTestPrefixExtractor() {
ColumnFamilyOptions options = null;
try {
options = new ColumnFamilyOptions();
options.useFixedLengthPrefixExtractor(100);
options.useFixedLengthPrefixExtractor(10);
} finally {
if (options != null) {
options.dispose();
}
} }
} }
public static void main(String[] args) { @Test
ColumnFamilyOptions opt = new ColumnFamilyOptions(); public void compressionTypes() {
testCFOptions(opt); ColumnFamilyOptions ColumnFamilyOptions = null;
opt.dispose(); try {
System.out.println("Passed DBOptionsTest"); ColumnFamilyOptions = new ColumnFamilyOptions();
for (CompressionType compressionType :
CompressionType.values()) {
ColumnFamilyOptions.setCompressionType(compressionType);
assertThat(ColumnFamilyOptions.compressionType()).
isEqualTo(compressionType);
assertThat(CompressionType.valueOf("NO_COMPRESSION")).
isEqualTo(CompressionType.NO_COMPRESSION);
}
} finally {
if (ColumnFamilyOptions != null) {
ColumnFamilyOptions.dispose();
}
}
}
@Test
public void compactionStyles() {
ColumnFamilyOptions ColumnFamilyOptions = null;
try {
ColumnFamilyOptions = new ColumnFamilyOptions();
for (CompactionStyle compactionStyle :
CompactionStyle.values()) {
ColumnFamilyOptions.setCompactionStyle(compactionStyle);
assertThat(ColumnFamilyOptions.compactionStyle()).
isEqualTo(compactionStyle);
assertThat(CompactionStyle.valueOf("FIFO")).
isEqualTo(CompactionStyle.FIFO);
}
} finally {
if (ColumnFamilyOptions != null) {
ColumnFamilyOptions.dispose();
}
}
} }
} }

@ -9,79 +9,104 @@ import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Map; import java.util.Map;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.rocksdb.*; import org.rocksdb.*;
import static org.assertj.core.api.Assertions.assertThat;
public class ColumnFamilyTest { public class ColumnFamilyTest {
static final String db_path = "/tmp/rocksdbjni_columnfamily_test";
static {
RocksDB.loadLibrary();
}
public static void main(String[] args) { @ClassRule
public static final RocksMemoryResource rocksMemoryResource =
new RocksMemoryResource();
@Rule
public TemporaryFolder dbFolder = new TemporaryFolder();
@Test
public void listColumnFamilies() throws RocksDBException {
RocksDB db = null; RocksDB db = null;
Options options = new Options(); Options options = null;
options.setCreateIfMissing(true); try {
options = new Options();
options.setCreateIfMissing(true);
DBOptions dbOptions = new DBOptions(); DBOptions dbOptions = new DBOptions();
dbOptions.setCreateIfMissing(true); dbOptions.setCreateIfMissing(true);
try { db = RocksDB.open(options, dbFolder.getRoot().getAbsolutePath());
db = RocksDB.open(options, db_path); // Test listColumnFamilies
} catch (RocksDBException e) { List<byte[]> columnFamilyNames;
assert(false); columnFamilyNames = RocksDB.listColumnFamilies(options, dbFolder.getRoot().getAbsolutePath());
} assertThat(columnFamilyNames).isNotNull();
// Test listColumnFamilies assertThat(columnFamilyNames.size()).isGreaterThan(0);
List<byte[]> columnFamilyNames; assertThat(columnFamilyNames.size()).isEqualTo(1);
try { assertThat(new String(columnFamilyNames.get(0))).isEqualTo("default");
columnFamilyNames = RocksDB.listColumnFamilies(options, db_path); } finally {
if (columnFamilyNames != null && columnFamilyNames.size() > 0) { if (db != null) {
assert(columnFamilyNames.size() == 1); db.close();
assert(new String(columnFamilyNames.get(0)).equals("default")); }
} else { if (options != null) {
assert(false); options.dispose();
} }
} catch (RocksDBException e) {
assert(false);
} }
}
// Test createColumnFamily @Test
public void createColumnFamily() throws RocksDBException {
RocksDB db = null;
Options options = null;
try { try {
options = new Options();
options.setCreateIfMissing(true);
DBOptions dbOptions = new DBOptions();
dbOptions.setCreateIfMissing(true);
db = RocksDB.open(options, dbFolder.getRoot().getAbsolutePath());
db.createColumnFamily(new ColumnFamilyDescriptor("new_cf", db.createColumnFamily(new ColumnFamilyDescriptor("new_cf",
new ColumnFamilyOptions())); new ColumnFamilyOptions()));
} catch (RocksDBException e) {
assert(false);
}
if (db != null) {
db.close(); db.close();
List<byte[]> columnFamilyNames;
columnFamilyNames = RocksDB.listColumnFamilies(options, dbFolder.getRoot().getAbsolutePath());
assertThat(columnFamilyNames).isNotNull();
assertThat(columnFamilyNames.size()).isGreaterThan(0);
assertThat(columnFamilyNames.size()).isEqualTo(2);
assertThat(new String(columnFamilyNames.get(0))).isEqualTo("default");
assertThat(new String(columnFamilyNames.get(1))).isEqualTo("new_cf");
} finally {
if (db != null) {
db.close();
}
if (options != null) {
options.dispose();
}
} }
}
// Test listColumnFamilies after create "new_cf" @Test
public void openWithColumnFamilies() throws RocksDBException {
RocksDB db = null;
DBOptions options = null;
try { try {
columnFamilyNames = RocksDB.listColumnFamilies(options, db_path); options = new DBOptions();
if (columnFamilyNames != null && columnFamilyNames.size() > 0) { options.setCreateIfMissing(true);
assert(columnFamilyNames.size() == 2); options.setCreateMissingColumnFamilies(true);
assert(new String(columnFamilyNames.get(0)).equals("default")); // Test open database with column family names
assert(new String(columnFamilyNames.get(1)).equals("new_cf")); List<ColumnFamilyDescriptor> cfNames =
} else { new ArrayList<>();
assert(false); List<ColumnFamilyHandle> columnFamilyHandleList =
} new ArrayList<>();
} catch (RocksDBException e) { cfNames.add(new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY));
assert(false); cfNames.add(new ColumnFamilyDescriptor("new_cf"));
}
// Test open database with column family names
List<ColumnFamilyDescriptor> cfNames =
new ArrayList<>();
List<ColumnFamilyHandle> columnFamilyHandleList =
new ArrayList<>();
cfNames.add(new ColumnFamilyDescriptor("default"));
cfNames.add(new ColumnFamilyDescriptor("new_cf"));
try { db = RocksDB.open(options, dbFolder.getRoot().getAbsolutePath(),
db = RocksDB.open(dbOptions, db_path, cfNames, columnFamilyHandleList); cfNames, columnFamilyHandleList);
assert(columnFamilyHandleList.size() == 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(),
"dfvalue".getBytes()); "dfvalue".getBytes());
@ -90,57 +115,119 @@ public class ColumnFamilyTest {
String retVal = new String(db.get(columnFamilyHandleList.get(1), String retVal = new String(db.get(columnFamilyHandleList.get(1),
"newcfkey1".getBytes())); "newcfkey1".getBytes()));
assert(retVal.equals("newcfvalue")); assertThat(retVal).isEqualTo("newcfvalue");
assert( (db.get(columnFamilyHandleList.get(1), assertThat((db.get(columnFamilyHandleList.get(1),
"dfkey1".getBytes())) == null); "dfkey1".getBytes()))).isNull();
db.remove(columnFamilyHandleList.get(1), "newcfkey1".getBytes()); db.remove(columnFamilyHandleList.get(1), "newcfkey1".getBytes());
assert( (db.get(columnFamilyHandleList.get(1), assertThat((db.get(columnFamilyHandleList.get(1),
"newcfkey1".getBytes())) == null); "newcfkey1".getBytes()))).isNull();
db.remove("dfkey2".getBytes()); db.remove(columnFamilyHandleList.get(0), new WriteOptions(),
assert( (db.get(columnFamilyHandleList.get(0), "dfkey2".getBytes());
"dfkey2".getBytes())) == null); assertThat(db.get(columnFamilyHandleList.get(0), new ReadOptions(),
} catch (RocksDBException e) { "dfkey2".getBytes())).isNull();
assert(false); } finally {
if (db != null) {
db.close();
}
if (options != null) {
options.dispose();
}
} }
}
// Test create write to and drop ColumnFamily @Test
public void getWithOutValueAndCf() throws RocksDBException {
RocksDB db = null;
DBOptions options = null;
try {
options = new DBOptions();
options.setCreateIfMissing(true);
options.setCreateMissingColumnFamilies(true);
// Test open database with column family names
List<ColumnFamilyDescriptor> cfDescriptors =
new ArrayList<>();
List<ColumnFamilyHandle> columnFamilyHandleList =
new ArrayList<>();
cfDescriptors.add(new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY));
db = RocksDB.open(options, dbFolder.getRoot().getAbsolutePath(),
cfDescriptors, columnFamilyHandleList);
db.put(columnFamilyHandleList.get(0), new WriteOptions(),
"key1".getBytes(), "value".getBytes());
db.put("key2".getBytes(), "12345678".getBytes());
byte[] outValue = new byte[5];
// not found value
int getResult = db.get("keyNotFound".getBytes(), outValue);
assertThat(getResult).isEqualTo(RocksDB.NOT_FOUND);
// found value which fits in outValue
getResult = db.get(columnFamilyHandleList.get(0), "key1".getBytes(), outValue);
assertThat(getResult).isNotEqualTo(RocksDB.NOT_FOUND);
assertThat(outValue).isEqualTo("value".getBytes());
// found value which fits partially
getResult = db.get(columnFamilyHandleList.get(0), new ReadOptions(),
"key2".getBytes(), outValue);
assertThat(getResult).isNotEqualTo(RocksDB.NOT_FOUND);
assertThat(outValue).isEqualTo("12345".getBytes());
} finally {
if (db != null) {
db.close();
}
}
}
@Test
public void createWriteDropColumnFamily() throws RocksDBException {
RocksDB db = null;
DBOptions opt = null;
ColumnFamilyHandle tmpColumnFamilyHandle = null; ColumnFamilyHandle tmpColumnFamilyHandle = null;
try { try {
opt = new DBOptions();
opt.setCreateIfMissing(true);
opt.setCreateMissingColumnFamilies(true);
List<ColumnFamilyDescriptor> cfNames =
new ArrayList<>();
List<ColumnFamilyHandle> columnFamilyHandleList =
new ArrayList<>();
cfNames.add(new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY));
cfNames.add(new ColumnFamilyDescriptor("new_cf"));
db = RocksDB.open(opt, dbFolder.getRoot().getAbsolutePath(),
cfNames, columnFamilyHandleList);
tmpColumnFamilyHandle = db.createColumnFamily( tmpColumnFamilyHandle = db.createColumnFamily(
new ColumnFamilyDescriptor("tmpCF", new ColumnFamilyOptions())); new ColumnFamilyDescriptor("tmpCF", new ColumnFamilyOptions()));
db.put(tmpColumnFamilyHandle, "key".getBytes(), "value".getBytes()); db.put(tmpColumnFamilyHandle, "key".getBytes(), "value".getBytes());
db.dropColumnFamily(tmpColumnFamilyHandle); db.dropColumnFamily(tmpColumnFamilyHandle);
tmpColumnFamilyHandle.dispose(); tmpColumnFamilyHandle.dispose();
} catch (Exception e) { } finally {
assert(false); if (tmpColumnFamilyHandle != null) {
} tmpColumnFamilyHandle.dispose();
}
// Put to disposed column family tmpColumnFamilyHandle must fail if (db != null) {
try { db.close();
db.put(tmpColumnFamilyHandle, "key".getBytes(), "value".getBytes()); }
assert(false); if (opt != null) {
} catch (RocksDBException e) { opt.dispose();
assert(true); }
} }
}
// Remove to disposed column family tmpColumnFamilyHandle must fail @Test
public void writeBatch() throws RocksDBException {
RocksDB db = null;
DBOptions opt = null;
try { try {
db.remove(tmpColumnFamilyHandle, "key".getBytes()); opt = new DBOptions();
assert(false); opt.setCreateIfMissing(true);
} catch (RocksDBException e) { opt.setCreateMissingColumnFamilies(true);
assert(true); List<ColumnFamilyDescriptor> cfNames =
} new ArrayList<>();
List<ColumnFamilyHandle> columnFamilyHandleList =
new ArrayList<>();
cfNames.add(new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY));
cfNames.add(new ColumnFamilyDescriptor("new_cf"));
// Get on a disposed column family tmpColumnFamilyHandle must fail db = RocksDB.open(opt, dbFolder.getRoot().getAbsolutePath(),
try { cfNames, columnFamilyHandleList);
db.get(tmpColumnFamilyHandle, "key".getBytes());
assert(false);
} catch (RocksDBException e) {
assert(true);
}
// Test WriteBatch
try {
WriteBatch writeBatch = new WriteBatch(); WriteBatch writeBatch = new WriteBatch();
WriteOptions writeOpt = new WriteOptions(); WriteOptions writeOpt = new WriteOptions();
writeBatch.put("key".getBytes(), "value".getBytes()); writeBatch.put("key".getBytes(), "value".getBytes());
@ -152,136 +239,324 @@ public class ColumnFamilyTest {
writeBatch.remove(columnFamilyHandleList.get(1), "xyz".getBytes()); writeBatch.remove(columnFamilyHandleList.get(1), "xyz".getBytes());
db.write(writeOpt, writeBatch); db.write(writeOpt, writeBatch);
writeBatch.dispose(); writeBatch.dispose();
assert(db.get(columnFamilyHandleList.get(1), assertThat(db.get(columnFamilyHandleList.get(1),
"xyz".getBytes()) == null); "xyz".getBytes()) == null);
assert(new String(db.get(columnFamilyHandleList.get(1), assertThat(new String(db.get(columnFamilyHandleList.get(1),
"newcfkey".getBytes())).equals("value")); "newcfkey".getBytes()))).isEqualTo("value");
assert(new String(db.get(columnFamilyHandleList.get(1), assertThat(new String(db.get(columnFamilyHandleList.get(1),
"newcfkey2".getBytes())).equals("value2")); "newcfkey2".getBytes()))).isEqualTo("value2");
assert(new String(db.get("key".getBytes())).equals("value")); assertThat(new String(db.get("key".getBytes()))).isEqualTo("value");
} catch (Exception e) { } finally {
e.printStackTrace(); if (db != null) {
assert(false); db.close();
}
if (opt != null) {
opt.dispose();
}
} }
}
// Test iterator on column family @Test
public void iteratorOnColumnFamily() throws RocksDBException {
RocksDB db = null;
DBOptions options = null;
RocksIterator rocksIterator = null;
try { try {
RocksIterator rocksIterator = db.newIterator( options = new DBOptions();
options.setCreateIfMissing(true);
options.setCreateMissingColumnFamilies(true);
List<ColumnFamilyDescriptor> cfNames =
new ArrayList<>();
List<ColumnFamilyHandle> columnFamilyHandleList =
new ArrayList<>();
cfNames.add(new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY));
cfNames.add(new ColumnFamilyDescriptor("new_cf"));
db = RocksDB.open(options, dbFolder.getRoot().getAbsolutePath(),
cfNames, columnFamilyHandleList);
db.put(columnFamilyHandleList.get(1), "newcfkey".getBytes(),
"value".getBytes());
db.put(columnFamilyHandleList.get(1), "newcfkey2".getBytes(),
"value2".getBytes());
rocksIterator = db.newIterator(
columnFamilyHandleList.get(1)); columnFamilyHandleList.get(1));
rocksIterator.seekToFirst(); rocksIterator.seekToFirst();
Map<String, String> refMap = new HashMap<String, String>(); Map<String, String> refMap = new HashMap<>();
refMap.put("newcfkey", "value"); refMap.put("newcfkey", "value");
refMap.put("newcfkey2", "value2"); refMap.put("newcfkey2", "value2");
int i = 0; int i = 0;
while(rocksIterator.isValid()) { while (rocksIterator.isValid()) {
i++; i++;
refMap.get(new String(rocksIterator.key())).equals( assertThat(refMap.get(new String(rocksIterator.key()))).
new String(rocksIterator.value())); isEqualTo(new String(rocksIterator.value()));
rocksIterator.next(); rocksIterator.next();
} }
assert(i == 2); assertThat(i).isEqualTo(2);
rocksIterator.dispose(); rocksIterator.dispose();
} catch(Exception e) { } finally {
assert(false); if (rocksIterator != null) {
rocksIterator.dispose();
}
if (db != null) {
db.close();
}
if (options != null) {
options.dispose();
}
} }
}
// Test property handling on column families @Test
public void multiGet() throws RocksDBException {
RocksDB db = null;
DBOptions options = null;
try { try {
assert(db.getProperty("rocksdb.estimate-num-keys") != null); options = new DBOptions();
assert(db.getProperty("rocksdb.stats") != null); options.setCreateIfMissing(true);
assert(db.getProperty(columnFamilyHandleList.get(0), options.setCreateMissingColumnFamilies(true);
"rocksdb.sstables") != null); List<ColumnFamilyDescriptor> cfDescriptors =
assert(db.getProperty(columnFamilyHandleList.get(1), new ArrayList<>();
"rocksdb.estimate-num-keys") != null); List<ColumnFamilyHandle> columnFamilyHandleList =
assert(db.getProperty(columnFamilyHandleList.get(1), new ArrayList<>();
"rocksdb.stats") != null); cfDescriptors.add(new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY));
assert(db.getProperty(columnFamilyHandleList.get(1), cfDescriptors.add(new ColumnFamilyDescriptor("new_cf"));
"rocksdb.sstables") != null);
} catch(Exception e) {
assert(false);
}
// MultiGet test db = RocksDB.open(options, dbFolder.getRoot().getAbsolutePath(),
List<ColumnFamilyHandle> cfCustomList = new ArrayList<ColumnFamilyHandle>(); cfDescriptors, columnFamilyHandleList);
try { db.put(columnFamilyHandleList.get(0), "key".getBytes(), "value".getBytes());
List<byte[]> keys = new ArrayList<byte[]>(); db.put(columnFamilyHandleList.get(1), "newcfkey".getBytes(), "value".getBytes());
List<byte[]> keys = new ArrayList<>();
keys.add("key".getBytes()); keys.add("key".getBytes());
keys.add("newcfkey".getBytes()); keys.add("newcfkey".getBytes());
Map<byte[], byte[]> retValues = db.multiGet(columnFamilyHandleList,keys); Map<byte[], byte[]> retValues = db.multiGet(columnFamilyHandleList, keys);
assert(retValues.size() == 2); assertThat(retValues.size()).isEqualTo(2);
assert(new String(retValues.get(keys.get(0))) assertThat(new String(retValues.get(keys.get(0))))
.equals("value")); .isEqualTo("value");
assert(new String(retValues.get(keys.get(1))) assertThat(new String(retValues.get(keys.get(1))))
.equals("value")); .isEqualTo("value");
retValues = db.multiGet(new ReadOptions(), columnFamilyHandleList, keys);
cfCustomList.add(columnFamilyHandleList.get(0)); assertThat(retValues.size()).isEqualTo(2);
cfCustomList.add(columnFamilyHandleList.get(0)); assertThat(new String(retValues.get(keys.get(0))))
retValues = db.multiGet(cfCustomList, keys); .isEqualTo("value");
assert(retValues.size() == 1); assertThat(new String(retValues.get(keys.get(1))))
assert(new String(retValues.get(keys.get(0))) .isEqualTo("value");
.equals("value")); } finally {
} catch (RocksDBException e) { if (db != null) {
assert(false); db.close();
}
if (options != null) {
options.dispose();
}
} }
}
// Test multiget without correct number of column
// families @Test
public void properties() throws RocksDBException {
RocksDB db = null;
DBOptions options = null;
try { try {
List<byte[]> keys = new ArrayList<byte[]>(); options = new DBOptions();
keys.add("key".getBytes()); options.setCreateIfMissing(true);
keys.add("newcfkey".getBytes()); options.setCreateMissingColumnFamilies(true);
cfCustomList.remove(1); List<ColumnFamilyDescriptor> cfNames =
db.multiGet(cfCustomList, keys); new ArrayList<>();
assert(false); List<ColumnFamilyHandle> columnFamilyHandleList =
} catch (RocksDBException e) { new ArrayList<>();
assert(false); cfNames.add(new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY));
} catch (IllegalArgumentException e) { cfNames.add(new ColumnFamilyDescriptor("new_cf"));
assert(true);
db = RocksDB.open(options, dbFolder.getRoot().getAbsolutePath(),
cfNames, columnFamilyHandleList);
assertThat(db.getProperty("rocksdb.estimate-num-keys")).
isNotNull();
assertThat(db.getProperty("rocksdb.stats")).isNotNull();
assertThat(db.getProperty(columnFamilyHandleList.get(0),
"rocksdb.sstables")).isNotNull();
assertThat(db.getProperty(columnFamilyHandleList.get(1),
"rocksdb.estimate-num-keys")).isNotNull();
assertThat(db.getProperty(columnFamilyHandleList.get(1),
"rocksdb.stats")).isNotNull();
assertThat(db.getProperty(columnFamilyHandleList.get(1),
"rocksdb.sstables")).isNotNull();
} finally {
if (db != null) {
db.close();
}
if (options != null) {
options.dispose();
}
} }
}
@Test
public void iterators() throws RocksDBException {
RocksDB db = null;
DBOptions options = null;
try { try {
// iterate over default key/value pairs options = new DBOptions();
options.setCreateIfMissing(true);
options.setCreateMissingColumnFamilies(true);
List<ColumnFamilyDescriptor> cfNames =
new ArrayList<>();
List<ColumnFamilyHandle> columnFamilyHandleList =
new ArrayList<>();
cfNames.add(new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY));
cfNames.add(new ColumnFamilyDescriptor("new_cf"));
db = RocksDB.open(options, dbFolder.getRoot().getAbsolutePath(),
cfNames, columnFamilyHandleList);
List<RocksIterator> iterators = List<RocksIterator> iterators =
db.newIterators(columnFamilyHandleList); db.newIterators(columnFamilyHandleList);
assert(iterators.size() == 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<String, String>(); 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()) {
defRefMap.get(new String(iter.key())).equals( assertThat(defRefMap.get(new String(iter.key()))).
new String(iter.value())); isEqualTo(new String(iter.value()));
iter.next(); iter.next();
} }
// iterate over new_cf key/value pairs // iterate over new_cf key/value pairs
Map<String,String> cfRefMap = new HashMap<String, String>(); 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);
iter.seekToFirst(); iter.seekToFirst();
while (iter.isValid()) { while (iter.isValid()) {
cfRefMap.get(new String(iter.key())).equals( assertThat(cfRefMap.get(new String(iter.key()))).
new String(iter.value())); isEqualTo(new String(iter.value()));
iter.next(); iter.next();
} }
// free iterators } finally {
for (RocksIterator iterator : iterators) { if (db != null) {
iterator.dispose(); db.close();
}
if (options != null) {
options.dispose();
} }
assert(true);
} catch (RocksDBException e) {
assert(false);
} }
}
@Test(expected = RocksDBException.class)
public void failPutDisposedCF() throws RocksDBException {
RocksDB db = null;
DBOptions options = null;
try {
options = new DBOptions();
options.setCreateIfMissing(true);
List<ColumnFamilyDescriptor> cfNames =
new ArrayList<>();
List<ColumnFamilyHandle> columnFamilyHandleList =
new ArrayList<>();
cfNames.add(new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY));
cfNames.add(new ColumnFamilyDescriptor("new_cf"));
System.out.println("Passed ColumnFamilyTest"); db = RocksDB.open(options, dbFolder.getRoot().getAbsolutePath(),
// free cf handles before database close cfNames, columnFamilyHandleList);
for (ColumnFamilyHandle columnFamilyHandle : columnFamilyHandleList) { db.dropColumnFamily(columnFamilyHandleList.get(1));
columnFamilyHandle.dispose(); db.put(columnFamilyHandleList.get(1), "key".getBytes(), "value".getBytes());
} finally {
if (db != null) {
db.close();
}
if (options != null) {
options.dispose();
}
} }
// close database
db.close();
// be sure to dispose c++ pointers
options.dispose();
} }
@Test(expected = RocksDBException.class)
public void failRemoveDisposedCF() throws RocksDBException {
RocksDB db = null;
DBOptions options = null;
try {
options = new DBOptions();
options.setCreateIfMissing(true);
List<ColumnFamilyDescriptor> cfNames =
new ArrayList<>();
List<ColumnFamilyHandle> columnFamilyHandleList =
new ArrayList<>();
cfNames.add(new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY));
cfNames.add(new ColumnFamilyDescriptor("new_cf"));
db = RocksDB.open(options, dbFolder.getRoot().getAbsolutePath(),
cfNames, columnFamilyHandleList);
db.dropColumnFamily(columnFamilyHandleList.get(1));
db.remove(columnFamilyHandleList.get(1), "key".getBytes());
} finally {
if (db != null) {
db.close();
}
if (options != null) {
options.dispose();
}
}
}
@Test(expected = RocksDBException.class)
public void failGetDisposedCF() throws RocksDBException {
RocksDB db = null;
DBOptions options = null;
try {
options = new DBOptions();
options.setCreateIfMissing(true);
List<ColumnFamilyDescriptor> cfNames =
new ArrayList<>();
List<ColumnFamilyHandle> columnFamilyHandleList =
new ArrayList<>();
cfNames.add(new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY));
cfNames.add(new ColumnFamilyDescriptor("new_cf"));
db = RocksDB.open(options, dbFolder.getRoot().getAbsolutePath(),
cfNames, columnFamilyHandleList);
db.dropColumnFamily(columnFamilyHandleList.get(1));
db.get(columnFamilyHandleList.get(1), "key".getBytes());
} finally {
if (db != null) {
db.close();
}
if (options != null) {
options.dispose();
}
}
}
@Test(expected = RocksDBException.class)
public void failMultiGetWithoutCorrectNumberOfCF() throws RocksDBException {
RocksDB db = null;
DBOptions options = null;
try {
options = new DBOptions();
options.setCreateIfMissing(true);
List<ColumnFamilyDescriptor> cfNames =
new ArrayList<>();
List<ColumnFamilyHandle> columnFamilyHandleList =
new ArrayList<>();
cfNames.add(new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY));
cfNames.add(new ColumnFamilyDescriptor("new_cf"));
db = RocksDB.open(options, dbFolder.getRoot().getAbsolutePath(),
cfNames, columnFamilyHandleList);
List<byte[]> keys = new ArrayList<>();
keys.add("key".getBytes());
keys.add("newcfkey".getBytes());
List<ColumnFamilyHandle> cfCustomList = new ArrayList<>();
db.multiGet(cfCustomList, keys);
} finally {
if (db != null) {
db.close();
}
if (options != null) {
options.dispose();
}
}
}
} }

@ -5,30 +5,32 @@
package org.rocksdb.test; package org.rocksdb.test;
import org.junit.ClassRule;
import org.junit.Test;
import org.rocksdb.ComparatorOptions; import org.rocksdb.ComparatorOptions;
import org.rocksdb.RocksDB;
import java.util.Random; import static org.assertj.core.api.Assertions.assertThat;
public class ComparatorOptionsTest { public class ComparatorOptionsTest {
static { @ClassRule
RocksDB.loadLibrary(); public static final RocksMemoryResource rocksMemoryResource =
} new RocksMemoryResource();
public static void main(String[] args) { @Test
public void comparatorOptions() {
final ComparatorOptions copt = new ComparatorOptions(); final ComparatorOptions copt = new ComparatorOptions();
Random rand = new Random();
assertThat(copt).isNotNull();
{ // UseAdaptiveMutex test { // UseAdaptiveMutex test
copt.setUseAdaptiveMutex(true); copt.setUseAdaptiveMutex(true);
assert(copt.useAdaptiveMutex() == true); assertThat(copt.useAdaptiveMutex()).isTrue();
copt.setUseAdaptiveMutex(false); copt.setUseAdaptiveMutex(false);
assert(copt.useAdaptiveMutex() == false); assertThat(copt.useAdaptiveMutex()).isFalse();
} }
copt.dispose(); copt.dispose();
System.out.println("Passed ComparatorOptionsTest");
} }
} }

@ -5,19 +5,28 @@
package org.rocksdb.test; package org.rocksdb.test;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.rocksdb.*; import org.rocksdb.*;
import java.io.IOException; import java.io.IOException;
import java.nio.file.FileSystems; import java.nio.file.FileSystems;
import static org.assertj.core.api.Assertions.assertThat;
public class ComparatorTest { public class ComparatorTest {
private static final String db_path = "/tmp/comparator_db";
static { @ClassRule
RocksDB.loadLibrary(); public static final RocksMemoryResource rocksMemoryResource =
} new RocksMemoryResource();
@Rule
public TemporaryFolder dbFolder = new TemporaryFolder();
public static void main(String[] args) throws IOException { @Test
public void javaComparator() throws IOException {
final AbstractComparatorTest comparatorTest = new AbstractComparatorTest() { final AbstractComparatorTest comparatorTest = new AbstractComparatorTest() {
@Override @Override
@ -38,8 +47,153 @@ public class ComparatorTest {
}; };
// test the round-tripability of keys written and read with the Comparator // test the round-tripability of keys written and read with the Comparator
comparatorTest.testRoundtrip(FileSystems.getDefault().getPath(db_path)); comparatorTest.testRoundtrip(FileSystems.getDefault().getPath(
dbFolder.getRoot().getAbsolutePath()));
}
@Test
public void builtinForwardComparator()
throws RocksDBException {
Options options = null;
RocksDB rocksDB = null;
RocksIterator rocksIterator = null;
try {
options = new Options();
options.setCreateIfMissing(true);
options.setComparator(BuiltinComparator.BYTEWISE_COMPARATOR);
rocksDB = RocksDB.open(options,
dbFolder.getRoot().getAbsolutePath());
rocksDB.put("abc1".getBytes(), "abc1".getBytes());
rocksDB.put("abc2".getBytes(), "abc2".getBytes());
rocksDB.put("abc3".getBytes(), "abc3".getBytes());
rocksIterator = rocksDB.newIterator();
// Iterate over keys using a iterator
rocksIterator.seekToFirst();
assertThat(rocksIterator.isValid()).isTrue();
assertThat(rocksIterator.key()).isEqualTo(
"abc1".getBytes());
assertThat(rocksIterator.value()).isEqualTo(
"abc1".getBytes());
rocksIterator.next();
assertThat(rocksIterator.isValid()).isTrue();
assertThat(rocksIterator.key()).isEqualTo(
"abc2".getBytes());
assertThat(rocksIterator.value()).isEqualTo(
"abc2".getBytes());
rocksIterator.next();
assertThat(rocksIterator.isValid()).isTrue();
assertThat(rocksIterator.key()).isEqualTo(
"abc3".getBytes());
assertThat(rocksIterator.value()).isEqualTo(
"abc3".getBytes());
rocksIterator.next();
assertThat(rocksIterator.isValid()).isFalse();
// Get last one
rocksIterator.seekToLast();
assertThat(rocksIterator.isValid()).isTrue();
assertThat(rocksIterator.key()).isEqualTo(
"abc3".getBytes());
assertThat(rocksIterator.value()).isEqualTo(
"abc3".getBytes());
// Seek for abc
rocksIterator.seek("abc".getBytes());
assertThat(rocksIterator.isValid()).isTrue();
assertThat(rocksIterator.key()).isEqualTo(
"abc1".getBytes());
assertThat(rocksIterator.value()).isEqualTo(
"abc1".getBytes());
} finally {
if (rocksIterator != null) {
rocksIterator.dispose();
}
if (rocksDB != null) {
rocksDB.close();
}
if (options != null) {
options.dispose();
}
}
}
@Test
public void builtinReverseComparator()
throws RocksDBException {
Options options = null;
RocksDB rocksDB = null;
RocksIterator rocksIterator = null;
try {
options = new Options();
options.setCreateIfMissing(true);
options.setComparator(
BuiltinComparator.REVERSE_BYTEWISE_COMPARATOR);
rocksDB = RocksDB.open(options,
dbFolder.getRoot().getAbsolutePath());
rocksDB.put("abc1".getBytes(), "abc1".getBytes());
rocksDB.put("abc2".getBytes(), "abc2".getBytes());
rocksDB.put("abc3".getBytes(), "abc3".getBytes());
rocksIterator = rocksDB.newIterator();
// Iterate over keys using a iterator
rocksIterator.seekToFirst();
assertThat(rocksIterator.isValid()).isTrue();
assertThat(rocksIterator.key()).isEqualTo(
"abc3".getBytes());
assertThat(rocksIterator.value()).isEqualTo(
"abc3".getBytes());
rocksIterator.next();
assertThat(rocksIterator.isValid()).isTrue();
assertThat(rocksIterator.key()).isEqualTo(
"abc2".getBytes());
assertThat(rocksIterator.value()).isEqualTo(
"abc2".getBytes());
rocksIterator.next();
assertThat(rocksIterator.isValid()).isTrue();
assertThat(rocksIterator.key()).isEqualTo(
"abc1".getBytes());
assertThat(rocksIterator.value()).isEqualTo(
"abc1".getBytes());
rocksIterator.next();
assertThat(rocksIterator.isValid()).isFalse();
// Get last one
rocksIterator.seekToLast();
assertThat(rocksIterator.isValid()).isTrue();
assertThat(rocksIterator.key()).isEqualTo(
"abc1".getBytes());
assertThat(rocksIterator.value()).isEqualTo(
"abc1".getBytes());
// Will be invalid because abc is after abc1
rocksIterator.seek("abc".getBytes());
assertThat(rocksIterator.isValid()).isFalse();
// Will be abc3 because the next one after abc999
// is abc3
rocksIterator.seek("abc999".getBytes());
assertThat(rocksIterator.key()).isEqualTo(
"abc3".getBytes());
assertThat(rocksIterator.value()).isEqualTo(
"abc3".getBytes());
} finally {
if (rocksIterator != null) {
rocksIterator.dispose();
}
if (rocksDB != null) {
rocksDB.close();
}
if (options != null) {
options.dispose();
}
}
}
System.out.println("Passed ComparatorTest"); @Test
public void builtinComparatorEnum(){
assertThat(BuiltinComparator.BYTEWISE_COMPARATOR.ordinal())
.isEqualTo(0);
assertThat(
BuiltinComparator.REVERSE_BYTEWISE_COMPARATOR.ordinal())
.isEqualTo(1);
} }
} }

@ -5,224 +5,533 @@
package org.rocksdb.test; package org.rocksdb.test;
import org.rocksdb.DBOptions; import org.junit.ClassRule;
import org.rocksdb.DBOptionsInterface; import org.junit.Test;
import org.rocksdb.RocksDB; import org.rocksdb.*;
import org.rocksdb.RocksDBException;
import java.util.Random; import java.util.Random;
import static org.assertj.core.api.Assertions.assertThat;
public class DBOptionsTest { public class DBOptionsTest {
static {
RocksDB.loadLibrary();
}
public static void testDBOptions(DBOptionsInterface opt) { @ClassRule
Random rand = PlatformRandomHelper. public static final RocksMemoryResource rocksMemoryResource =
getPlatformSpecificRandomFactory(); new RocksMemoryResource();
{ // CreateIfMissing test
public static final Random rand = PlatformRandomHelper.
getPlatformSpecificRandomFactory();
@Test
public void createIfMissing() {
DBOptions opt = null;
try {
opt = new DBOptions();
boolean boolValue = rand.nextBoolean(); boolean boolValue = rand.nextBoolean();
opt.setCreateIfMissing(boolValue); opt.setCreateIfMissing(boolValue);
assert(opt.createIfMissing() == boolValue); assertThat(opt.createIfMissing()).
isEqualTo(boolValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
}
{ // CreateMissingColumnFamilies test @Test
public void createMissingColumnFamilies() {
DBOptions opt = null;
try {
opt = new DBOptions();
boolean boolValue = rand.nextBoolean(); boolean boolValue = rand.nextBoolean();
opt.setCreateMissingColumnFamilies(boolValue); opt.setCreateMissingColumnFamilies(boolValue);
assert(opt.createMissingColumnFamilies() == boolValue); assertThat(opt.createMissingColumnFamilies()).
isEqualTo(boolValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
}
{ // ErrorIfExists test @Test
public void errorIfExists() {
DBOptions opt = null;
try {
opt = new DBOptions();
boolean boolValue = rand.nextBoolean(); boolean boolValue = rand.nextBoolean();
opt.setErrorIfExists(boolValue); opt.setErrorIfExists(boolValue);
assert(opt.errorIfExists() == boolValue); assertThat(opt.errorIfExists()).isEqualTo(boolValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
}
{ // ParanoidChecks test @Test
public void paranoidChecks() {
DBOptions opt = null;
try {
opt = new DBOptions();
boolean boolValue = rand.nextBoolean(); boolean boolValue = rand.nextBoolean();
opt.setParanoidChecks(boolValue); opt.setParanoidChecks(boolValue);
assert(opt.paranoidChecks() == boolValue); assertThat(opt.paranoidChecks()).
isEqualTo(boolValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
}
{ @Test
// MaxTotalWalSize test public void maxTotalWalSize() {
DBOptions opt = null;
try {
opt = new DBOptions();
long longValue = rand.nextLong(); long longValue = rand.nextLong();
opt.setMaxTotalWalSize(longValue); opt.setMaxTotalWalSize(longValue);
assert(opt.maxTotalWalSize() == longValue); assertThat(opt.maxTotalWalSize()).
isEqualTo(longValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
}
{ // MaxOpenFiles test @Test
public void maxOpenFiles() {
DBOptions opt = null;
try {
opt = new DBOptions();
int intValue = rand.nextInt(); int intValue = rand.nextInt();
opt.setMaxOpenFiles(intValue); opt.setMaxOpenFiles(intValue);
assert(opt.maxOpenFiles() == intValue); assertThat(opt.maxOpenFiles()).isEqualTo(intValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
}
{ // DisableDataSync test @Test
public void disableDataSync() {
DBOptions opt = null;
try {
opt = new DBOptions();
boolean boolValue = rand.nextBoolean(); boolean boolValue = rand.nextBoolean();
opt.setDisableDataSync(boolValue); opt.setDisableDataSync(boolValue);
assert(opt.disableDataSync() == boolValue); assertThat(opt.disableDataSync()).
isEqualTo(boolValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
}
{ // UseFsync test @Test
public void useFsync() {
DBOptions opt = null;
try {
opt = new DBOptions();
boolean boolValue = rand.nextBoolean(); boolean boolValue = rand.nextBoolean();
opt.setUseFsync(boolValue); opt.setUseFsync(boolValue);
assert(opt.useFsync() == boolValue); assertThat(opt.useFsync()).isEqualTo(boolValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
}
{ // DbLogDir test @Test
public void dbLogDir() {
DBOptions opt = null;
try {
opt = new DBOptions();
String str = "path/to/DbLogDir"; String str = "path/to/DbLogDir";
opt.setDbLogDir(str); opt.setDbLogDir(str);
assert(opt.dbLogDir().equals(str)); assertThat(opt.dbLogDir()).isEqualTo(str);
} finally {
if (opt != null) {
opt.dispose();
}
} }
}
{ // WalDir test @Test
public void walDir() {
DBOptions opt = null;
try {
opt = new DBOptions();
String str = "path/to/WalDir"; String str = "path/to/WalDir";
opt.setWalDir(str); opt.setWalDir(str);
assert(opt.walDir().equals(str)); assertThat(opt.walDir()).isEqualTo(str);
} finally {
if (opt != null) {
opt.dispose();
}
} }
}
{ // DeleteObsoleteFilesPeriodMicros test @Test
public void deleteObsoleteFilesPeriodMicros() {
DBOptions opt = null;
try {
opt = new DBOptions();
long longValue = rand.nextLong(); long longValue = rand.nextLong();
opt.setDeleteObsoleteFilesPeriodMicros(longValue); opt.setDeleteObsoleteFilesPeriodMicros(longValue);
assert(opt.deleteObsoleteFilesPeriodMicros() == longValue); assertThat(opt.deleteObsoleteFilesPeriodMicros()).
isEqualTo(longValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
}
{ // MaxBackgroundCompactions test @Test
public void maxBackgroundCompactions() {
DBOptions opt = null;
try {
opt = new DBOptions();
int intValue = rand.nextInt(); int intValue = rand.nextInt();
opt.setMaxBackgroundCompactions(intValue); opt.setMaxBackgroundCompactions(intValue);
assert(opt.maxBackgroundCompactions() == intValue); assertThat(opt.maxBackgroundCompactions()).
isEqualTo(intValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
}
{ // MaxBackgroundFlushes test @Test
public void maxBackgroundFlushes() {
DBOptions opt = null;
try {
opt = new DBOptions();
int intValue = rand.nextInt(); int intValue = rand.nextInt();
opt.setMaxBackgroundFlushes(intValue); opt.setMaxBackgroundFlushes(intValue);
assert(opt.maxBackgroundFlushes() == intValue); assertThat(opt.maxBackgroundFlushes()).
isEqualTo(intValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
}
{ // MaxLogFileSize test @Test
try { public void maxLogFileSize() throws RocksDBException {
long longValue = rand.nextLong(); DBOptions opt = null;
opt.setMaxLogFileSize(longValue); try {
assert(opt.maxLogFileSize() == longValue); opt = new DBOptions();
} catch (RocksDBException e) { long longValue = rand.nextLong();
System.out.println(e.getMessage()); opt.setMaxLogFileSize(longValue);
assert(false); assertThat(opt.maxLogFileSize()).isEqualTo(longValue);
} finally {
if (opt != null) {
opt.dispose();
} }
} }
}
{ // LogFileTimeToRoll test @Test
try { public void logFileTimeToRoll() throws RocksDBException {
long longValue = rand.nextLong(); DBOptions opt = null;
opt.setLogFileTimeToRoll(longValue); try {
assert(opt.logFileTimeToRoll() == longValue); opt = new DBOptions();
} catch (RocksDBException e) { long longValue = rand.nextLong();
assert(false); opt.setLogFileTimeToRoll(longValue);
assertThat(opt.logFileTimeToRoll()).
isEqualTo(longValue);
} finally {
if (opt != null) {
opt.dispose();
} }
} }
}
{ // KeepLogFileNum test @Test
try { public void keepLogFileNum() throws RocksDBException {
long longValue = rand.nextLong(); DBOptions opt = null;
opt.setKeepLogFileNum(longValue); try {
assert(opt.keepLogFileNum() == longValue); opt = new DBOptions();
} catch (RocksDBException e) { long longValue = rand.nextLong();
assert(false); opt.setKeepLogFileNum(longValue);
assertThat(opt.keepLogFileNum()).isEqualTo(longValue);
} finally {
if (opt != null) {
opt.dispose();
} }
} }
}
{ // MaxManifestFileSize test @Test
public void maxManifestFileSize() {
DBOptions opt = null;
try {
opt = new DBOptions();
long longValue = rand.nextLong(); long longValue = rand.nextLong();
opt.setMaxManifestFileSize(longValue); opt.setMaxManifestFileSize(longValue);
assert(opt.maxManifestFileSize() == longValue); assertThat(opt.maxManifestFileSize()).
isEqualTo(longValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
}
{ // TableCacheNumshardbits test @Test
public void tableCacheNumshardbits() {
DBOptions opt = null;
try {
opt = new DBOptions();
int intValue = rand.nextInt(); int intValue = rand.nextInt();
opt.setTableCacheNumshardbits(intValue); opt.setTableCacheNumshardbits(intValue);
assert(opt.tableCacheNumshardbits() == intValue); assertThat(opt.tableCacheNumshardbits()).
isEqualTo(intValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
}
{ // TableCacheRemoveScanCountLimit test @Test
public void tableCacheRemoveScanCountLimit() {
DBOptions opt = null;
try {
opt = new DBOptions();
int intValue = rand.nextInt(); int intValue = rand.nextInt();
opt.setTableCacheRemoveScanCountLimit(intValue); opt.setTableCacheRemoveScanCountLimit(intValue);
assert(opt.tableCacheRemoveScanCountLimit() == intValue); assertThat(opt.tableCacheRemoveScanCountLimit()).
isEqualTo(intValue);
} finally {
if (opt != null) {
opt.dispose();
}
}
}
@Test
public void walSizeLimitMB() {
DBOptions opt = null;
try {
opt = new DBOptions();
long longValue = rand.nextLong();
opt.setWalSizeLimitMB(longValue);
assertThat(opt.walSizeLimitMB()).isEqualTo(longValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
}
{ // WalTtlSeconds test @Test
public void walTtlSeconds() {
DBOptions opt = null;
try {
opt = new DBOptions();
long longValue = rand.nextLong(); long longValue = rand.nextLong();
opt.setWalTtlSeconds(longValue); opt.setWalTtlSeconds(longValue);
assert(opt.walTtlSeconds() == longValue); assertThat(opt.walTtlSeconds()).isEqualTo(longValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
}
{ // ManifestPreallocationSize test @Test
try { public void manifestPreallocationSize() throws RocksDBException {
long longValue = rand.nextLong(); DBOptions opt = null;
opt.setManifestPreallocationSize(longValue); try {
assert(opt.manifestPreallocationSize() == longValue); opt = new DBOptions();
} catch (RocksDBException e) { long longValue = rand.nextLong();
assert(false); opt.setManifestPreallocationSize(longValue);
assertThat(opt.manifestPreallocationSize()).
isEqualTo(longValue);
} finally {
if (opt != null) {
opt.dispose();
} }
} }
}
{ // AllowOsBuffer test @Test
public void allowOsBuffer() {
DBOptions opt = null;
try {
opt = new DBOptions();
boolean boolValue = rand.nextBoolean(); boolean boolValue = rand.nextBoolean();
opt.setAllowOsBuffer(boolValue); opt.setAllowOsBuffer(boolValue);
assert(opt.allowOsBuffer() == boolValue); assertThat(opt.allowOsBuffer()).isEqualTo(boolValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
}
{ // AllowMmapReads test @Test
public void allowMmapReads() {
DBOptions opt = null;
try {
opt = new DBOptions();
boolean boolValue = rand.nextBoolean(); boolean boolValue = rand.nextBoolean();
opt.setAllowMmapReads(boolValue); opt.setAllowMmapReads(boolValue);
assert(opt.allowMmapReads() == boolValue); assertThat(opt.allowMmapReads()).isEqualTo(boolValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
}
{ // AllowMmapWrites test @Test
public void allowMmapWrites() {
DBOptions opt = null;
try {
opt = new DBOptions();
boolean boolValue = rand.nextBoolean(); boolean boolValue = rand.nextBoolean();
opt.setAllowMmapWrites(boolValue); opt.setAllowMmapWrites(boolValue);
assert(opt.allowMmapWrites() == boolValue); assertThat(opt.allowMmapWrites()).isEqualTo(boolValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
}
{ // IsFdCloseOnExec test @Test
public void isFdCloseOnExec() {
DBOptions opt = null;
try {
opt = new DBOptions();
boolean boolValue = rand.nextBoolean(); boolean boolValue = rand.nextBoolean();
opt.setIsFdCloseOnExec(boolValue); opt.setIsFdCloseOnExec(boolValue);
assert(opt.isFdCloseOnExec() == boolValue); assertThat(opt.isFdCloseOnExec()).isEqualTo(boolValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
}
{ // SkipLogErrorOnRecovery test @Test
public void skipLogErrorOnRecovery() {
DBOptions opt = null;
try {
opt = new DBOptions();
boolean boolValue = rand.nextBoolean(); boolean boolValue = rand.nextBoolean();
opt.setSkipLogErrorOnRecovery(boolValue); opt.setSkipLogErrorOnRecovery(boolValue);
assert(opt.skipLogErrorOnRecovery() == boolValue); assertThat(opt.skipLogErrorOnRecovery()).isEqualTo(boolValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
}
{ // StatsDumpPeriodSec test @Test
public void statsDumpPeriodSec() {
DBOptions opt = null;
try {
opt = new DBOptions();
int intValue = rand.nextInt(); int intValue = rand.nextInt();
opt.setStatsDumpPeriodSec(intValue); opt.setStatsDumpPeriodSec(intValue);
assert(opt.statsDumpPeriodSec() == intValue); assertThat(opt.statsDumpPeriodSec()).isEqualTo(intValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
}
{ // AdviseRandomOnOpen test @Test
public void adviseRandomOnOpen() {
DBOptions opt = null;
try {
opt = new DBOptions();
boolean boolValue = rand.nextBoolean(); boolean boolValue = rand.nextBoolean();
opt.setAdviseRandomOnOpen(boolValue); opt.setAdviseRandomOnOpen(boolValue);
assert(opt.adviseRandomOnOpen() == boolValue); assertThat(opt.adviseRandomOnOpen()).isEqualTo(boolValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
}
{ // UseAdaptiveMutex test @Test
public void useAdaptiveMutex() {
DBOptions opt = null;
try {
opt = new DBOptions();
boolean boolValue = rand.nextBoolean(); boolean boolValue = rand.nextBoolean();
opt.setUseAdaptiveMutex(boolValue); opt.setUseAdaptiveMutex(boolValue);
assert(opt.useAdaptiveMutex() == boolValue); assertThat(opt.useAdaptiveMutex()).isEqualTo(boolValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
}
{ // BytesPerSync test @Test
public void bytesPerSync() {
DBOptions opt = null;
try {
opt = new DBOptions();
long longValue = rand.nextLong(); long longValue = rand.nextLong();
opt.setBytesPerSync(longValue); opt.setBytesPerSync(longValue);
assert(opt.bytesPerSync() == longValue); assertThat(opt.bytesPerSync()).isEqualTo(longValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
} }
public static void main(String[] args) { @Test
DBOptions opt = new DBOptions(); public void rateLimiterConfig() {
testDBOptions(opt); DBOptions options = null;
opt.dispose(); DBOptions anotherOptions = null;
System.out.println("Passed DBOptionsTest"); try {
options = new DBOptions();
RateLimiterConfig rateLimiterConfig =
new GenericRateLimiterConfig(1000, 0, 1);
options.setRateLimiterConfig(rateLimiterConfig);
// Test with parameter initialization
anotherOptions = new DBOptions();
anotherOptions.setRateLimiterConfig(
new GenericRateLimiterConfig(1000));
} finally {
if (options != null) {
options.dispose();
}
if (anotherOptions != null) {
anotherOptions.dispose();
}
}
}
@Test
public void statistics() {
DBOptions options = new DBOptions();
Statistics statistics = options.createStatistics().
statisticsPtr();
assertThat(statistics).isNotNull();
DBOptions anotherOptions = new DBOptions();
statistics = anotherOptions.statisticsPtr();
assertThat(statistics).isNotNull();
} }
} }

@ -5,19 +5,25 @@
package org.rocksdb.test; package org.rocksdb.test;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.rocksdb.*; import org.rocksdb.*;
import java.io.IOException; import java.io.IOException;
import java.nio.file.FileSystems; import java.nio.file.FileSystems;
public class DirectComparatorTest { public class DirectComparatorTest {
private static final String db_path = "/tmp/direct_comparator_db"; @ClassRule
public static final RocksMemoryResource rocksMemoryResource =
new RocksMemoryResource();
static { @Rule
RocksDB.loadLibrary(); public TemporaryFolder dbFolder = new TemporaryFolder();
}
public static void main(String[] args) throws IOException { @Test
public void directComparator() throws IOException {
final AbstractComparatorTest comparatorTest = new AbstractComparatorTest() { final AbstractComparatorTest comparatorTest = new AbstractComparatorTest() {
@Override @Override
@ -41,8 +47,7 @@ public class DirectComparatorTest {
}; };
// test the round-tripability of keys written and read with the DirectComparator // test the round-tripability of keys written and read with the DirectComparator
comparatorTest.testRoundtrip(FileSystems.getDefault().getPath(db_path)); comparatorTest.testRoundtrip(FileSystems.getDefault().getPath(
dbFolder.getRoot().getAbsolutePath()));
System.out.println("Passed DirectComparatorTest");
} }
} }

@ -0,0 +1,143 @@
// Copyright (c) 2014, Facebook, Inc. All rights reserved.
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree. An additional grant
// of patent rights can be found in the PATENTS file in the same directory.
package org.rocksdb.test;
import org.junit.Test;
import org.rocksdb.util.Environment;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import static org.assertj.core.api.Assertions.assertThat;
public class EnvironmentTest {
// Init static context
private static Environment environment =
new Environment();
@Test
public void mac32() {
setEnvironmentClassFields("mac", "32");
assertThat(Environment.isWindows()).isFalse();
assertThat(Environment.getJniLibraryExtension()).
isEqualTo(".jnilib");
assertThat(Environment.getJniLibraryName("rocksdb")).
isEqualTo("librocksdbjni-osx.jnilib");
assertThat(Environment.getSharedLibraryName("rocksdb")).
isEqualTo("librocksdbjni.dylib");
}
@Test
public void mac64() {
setEnvironmentClassFields("mac", "64");
assertThat(Environment.isWindows()).isFalse();
assertThat(Environment.getJniLibraryExtension()).
isEqualTo(".jnilib");
assertThat(Environment.getJniLibraryName("rocksdb")).
isEqualTo("librocksdbjni-osx.jnilib");
assertThat(Environment.getSharedLibraryName("rocksdb")).
isEqualTo("librocksdbjni.dylib");
}
@Test
public void nix32() {
// Linux
setEnvironmentClassFields("Linux", "32");
assertThat(Environment.isWindows()).isFalse();
assertThat(Environment.getJniLibraryExtension()).
isEqualTo(".so");
assertThat(Environment.getJniLibraryName("rocksdb")).
isEqualTo("librocksdbjni-linux32.so");
assertThat(Environment.getSharedLibraryName("rocksdb")).
isEqualTo("librocksdbjni.so");
// UNIX
setEnvironmentClassFields("Unix", "32");
assertThat(Environment.isWindows()).isFalse();
assertThat(Environment.getJniLibraryExtension()).
isEqualTo(".so");
assertThat(Environment.getJniLibraryName("rocksdb")).
isEqualTo("librocksdbjni-linux32.so");
assertThat(Environment.getSharedLibraryName("rocksdb")).
isEqualTo("librocksdbjni.so");
// AIX
setEnvironmentClassFields("aix", "32");
assertThat(Environment.isWindows()).isFalse();
assertThat(Environment.getJniLibraryExtension()).
isEqualTo(".so");
assertThat(Environment.getJniLibraryName("rocksdb")).
isEqualTo("librocksdbjni-linux32.so");
assertThat(Environment.getSharedLibraryName("rocksdb")).
isEqualTo("librocksdbjni.so");
}
@Test
public void nix64() {
setEnvironmentClassFields("Linux", "x64");
assertThat(Environment.isWindows()).isFalse();
assertThat(Environment.getJniLibraryExtension()).
isEqualTo(".so");
assertThat(Environment.getJniLibraryName("rocksdb")).
isEqualTo("librocksdbjni-linux64.so");
assertThat(Environment.getSharedLibraryName("rocksdb")).
isEqualTo("librocksdbjni.so");
// UNIX
setEnvironmentClassFields("Unix", "x64");
assertThat(Environment.isWindows()).isFalse();
assertThat(Environment.getJniLibraryExtension()).
isEqualTo(".so");
assertThat(Environment.getJniLibraryName("rocksdb")).
isEqualTo("librocksdbjni-linux64.so");
assertThat(Environment.getSharedLibraryName("rocksdb")).
isEqualTo("librocksdbjni.so");
// AIX
setEnvironmentClassFields("aix", "x64");
assertThat(Environment.isWindows()).isFalse();
assertThat(Environment.getJniLibraryExtension()).
isEqualTo(".so");
assertThat(Environment.getJniLibraryName("rocksdb")).
isEqualTo("librocksdbjni-linux64.so");
assertThat(Environment.getSharedLibraryName("rocksdb")).
isEqualTo("librocksdbjni.so");
}
@Test
public void detectWindows(){
setEnvironmentClassFields("win", "x64");
assertThat(Environment.isWindows()).isTrue();
}
@Test(expected = UnsupportedOperationException.class)
public void failWinJniLibraryName(){
setEnvironmentClassFields("win", "x64");
Environment.getJniLibraryName("rocksdb");
}
@Test(expected = UnsupportedOperationException.class)
public void failWinSharedLibrary(){
setEnvironmentClassFields("win", "x64");
Environment.getSharedLibraryName("rocksdb");
}
private void setEnvironmentClassFields(String osName,
String osArch) {
setEnvironmentClassField("OS", osName);
setEnvironmentClassField("ARCH", osArch);
}
private void setEnvironmentClassField(String fieldName, String value) {
final Field field;
try {
field = Environment.class.getDeclaredField(fieldName);
field.setAccessible(true);
final Field modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
field.set(null, value);
} catch (NoSuchFieldException | IllegalAccessException e) {
throw new RuntimeException(e);
}
}
}

@ -5,38 +5,44 @@
package org.rocksdb.test; package org.rocksdb.test;
import org.junit.ClassRule;
import org.junit.Test;
import org.rocksdb.*; import org.rocksdb.*;
public class FilterTest { public class FilterTest {
static {
RocksDB.loadLibrary(); @ClassRule
} public static final RocksMemoryResource rocksMemoryResource =
public static void main(String[] args) { new RocksMemoryResource();
Options options = new Options();
// test table config @Test
BlockBasedTableConfig blockConfig = new BlockBasedTableConfig(); public void filter() {
options.setTableFormatConfig(new BlockBasedTableConfig(). Options options = null;
setFilter(new BloomFilter())); try {
options.dispose(); options = new Options();
System.gc(); // test table config
System.runFinalization(); options.setTableFormatConfig(new BlockBasedTableConfig().
// new Bloom filter setFilter(new BloomFilter()));
options = new Options(); options.dispose();
blockConfig = new BlockBasedTableConfig(); System.gc();
blockConfig.setFilter(new BloomFilter()); System.runFinalization();
options.setTableFormatConfig(blockConfig); // new Bloom filter
BloomFilter bloomFilter = new BloomFilter(10); options = new Options();
blockConfig.setFilter(bloomFilter); BlockBasedTableConfig blockConfig = new BlockBasedTableConfig();
options.setTableFormatConfig(blockConfig); blockConfig.setFilter(new BloomFilter());
System.gc(); options.setTableFormatConfig(blockConfig);
System.runFinalization(); BloomFilter bloomFilter = new BloomFilter(10);
blockConfig.setFilter(new BloomFilter(10, false)); blockConfig.setFilter(bloomFilter);
options.setTableFormatConfig(blockConfig); options.setTableFormatConfig(blockConfig);
options.dispose(); System.gc();
options = null; System.runFinalization();
blockConfig = null; blockConfig.setFilter(new BloomFilter(10, false));
System.gc(); options.setTableFormatConfig(blockConfig);
System.runFinalization();
System.out.println("Filter test passed"); } finally {
if (options != null) {
options.dispose();
}
}
} }
} }

@ -4,44 +4,62 @@
// of patent rights can be found in the PATENTS file in the same directory. // of patent rights can be found in the PATENTS file in the same directory.
package org.rocksdb.test; package org.rocksdb.test;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.rocksdb.*; import org.rocksdb.*;
import static org.assertj.core.api.Assertions.assertThat;
public class FlushTest { public class FlushTest {
static final String db_path = "/tmp/rocksdbjni_flush_test"; @ClassRule
static { public static final RocksMemoryResource rocksMemoryResource =
RocksDB.loadLibrary(); new RocksMemoryResource();
}
public static void main(String[] args) { @Rule
RocksDB db = null; public TemporaryFolder dbFolder = new TemporaryFolder();
Options options = new Options();
WriteOptions wOpt = new WriteOptions();
FlushOptions flushOptions = new FlushOptions();
@Test
public void flush() throws RocksDBException {
RocksDB db = null;
Options options = null;
WriteOptions wOpt = null;
FlushOptions flushOptions = null;
try { try {
options = new Options();
// Setup options // Setup options
options.setCreateIfMissing(true); options.setCreateIfMissing(true);
options.setMaxWriteBufferNumber(10); options.setMaxWriteBufferNumber(10);
options.setMinWriteBufferNumberToMerge(10); options.setMinWriteBufferNumberToMerge(10);
wOpt = new WriteOptions();
flushOptions = new FlushOptions();
flushOptions.setWaitForFlush(true); flushOptions.setWaitForFlush(true);
wOpt.setDisableWAL(true); wOpt.setDisableWAL(true);
db = RocksDB.open(options, db_path); 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());
assert(db.getProperty("rocksdb.num-entries-active-mem-table").equals("4")); assertThat(db.getProperty("rocksdb.num-entries-active-mem-table")).isEqualTo("4");
db.flush(flushOptions); db.flush(flushOptions);
assert(db.getProperty("rocksdb.num-entries-active-mem-table").equals("0")); assertThat(db.getProperty("rocksdb.num-entries-active-mem-table")).
} catch (RocksDBException e) { isEqualTo("0");
assert(false); } finally {
} if (flushOptions != null) {
flushOptions.dispose();
}
if (db != null) {
db.close();
}
if (options != null) {
options.dispose();
}
if (wOpt != null) {
wOpt.dispose();
}
db.close(); }
options.dispose();
wOpt.dispose();
flushOptions.dispose();
} }
} }

@ -4,73 +4,89 @@
// of patent rights can be found in the PATENTS file in the same directory. // of patent rights can be found in the PATENTS file in the same directory.
package org.rocksdb.test; package org.rocksdb.test;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.rocksdb.*; import org.rocksdb.*;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
public class KeyMayExistTest { public class KeyMayExistTest {
static final String DB_PATH = "/tmp/rocksdbjni_keymayexit_test";
static {
RocksDB.loadLibrary();
}
public static void main(String[] args){ @ClassRule
RocksDB db; public static final RocksMemoryResource rocksMemoryResource =
DBOptions options = new DBOptions(); new RocksMemoryResource();
options.setCreateIfMissing(true)
.setCreateMissingColumnFamilies(true); @Rule
public TemporaryFolder dbFolder = new TemporaryFolder();
@Test
public void keyMayExist() throws RocksDBException {
RocksDB db = null;
DBOptions options = null;
try { try {
options = new DBOptions();
options.setCreateIfMissing(true)
.setCreateMissingColumnFamilies(true);
// open database using cf names // open database using cf names
List<ColumnFamilyDescriptor> cfNames = List<ColumnFamilyDescriptor> cfDescriptors =
new ArrayList<ColumnFamilyDescriptor>(); new ArrayList<>();
List<ColumnFamilyHandle> columnFamilyHandleList = List<ColumnFamilyHandle> columnFamilyHandleList =
new ArrayList<ColumnFamilyHandle>(); new ArrayList<>();
cfNames.add(new ColumnFamilyDescriptor("default")); cfDescriptors.add(new ColumnFamilyDescriptor("default"));
cfNames.add(new ColumnFamilyDescriptor("new_cf")); cfDescriptors.add(new ColumnFamilyDescriptor("new_cf"));
db = RocksDB.open(options, DB_PATH, cfNames, columnFamilyHandleList); db = RocksDB.open(options,
assert(columnFamilyHandleList.size()==2); dbFolder.getRoot().getAbsolutePath(),
cfDescriptors, columnFamilyHandleList);
assertThat(columnFamilyHandleList.size()).
isEqualTo(2);
db.put("key".getBytes(), "value".getBytes()); db.put("key".getBytes(), "value".getBytes());
// Test without column family // Test without column family
StringBuffer retValue = new StringBuffer(); StringBuffer retValue = new StringBuffer();
if (db.keyMayExist("key".getBytes(), retValue)) { boolean exists = db.keyMayExist("key".getBytes(), retValue);
assert(retValue.toString().equals("value")); assertThat(exists).isTrue();
} else { assertThat(retValue.toString()).
assert(false); isEqualTo("value");
}
// Test without column family but with readOptions // Test without column family but with readOptions
retValue = new StringBuffer(); retValue = new StringBuffer();
if (db.keyMayExist(new ReadOptions(), "key".getBytes(), exists = db.keyMayExist(new ReadOptions(), "key".getBytes(),
retValue)) { retValue);
assert(retValue.toString().equals("value")); assertThat(exists).isTrue();
} else { assertThat(retValue.toString()).
assert(false); isEqualTo("value");
}
// Test with column family // Test with column family
retValue = new StringBuffer(); retValue = new StringBuffer();
if (db.keyMayExist(columnFamilyHandleList.get(0), "key".getBytes(), exists = db.keyMayExist(columnFamilyHandleList.get(0), "key".getBytes(),
retValue)) { retValue);
assert(retValue.toString().equals("value")); assertThat(exists).isTrue();
} else { assertThat(retValue.toString()).
assert(false); isEqualTo("value");
}
// Test with column family and readOptions // Test with column family and readOptions
retValue = new StringBuffer(); retValue = new StringBuffer();
if (db.keyMayExist(new ReadOptions(), exists = db.keyMayExist(new ReadOptions(),
columnFamilyHandleList.get(0), "key".getBytes(), columnFamilyHandleList.get(0), "key".getBytes(),
retValue)) { retValue);
assert(retValue.toString().equals("value")); assertThat(exists).isTrue();
} else { assertThat(retValue.toString()).
assert(false); isEqualTo("value");
}
// KeyMayExist in CF1 must return false // KeyMayExist in CF1 must return false
assert(db.keyMayExist(columnFamilyHandleList.get(1), "key".getBytes(), assertThat(db.keyMayExist(columnFamilyHandleList.get(1),
retValue) == false); "key".getBytes(), retValue)).isFalse();
System.out.println("Passed KeyMayExistTest"); } finally {
}catch (RocksDBException e){ if (db != null) {
e.printStackTrace(); db.close();
assert(false); }
if (options != null) {
options.dispose();
}
} }
} }
} }

@ -5,103 +5,134 @@
package org.rocksdb.test; package org.rocksdb.test;
import org.junit.ClassRule;
import org.junit.Test;
import org.rocksdb.*; import org.rocksdb.*;
import static org.assertj.core.api.Assertions.assertThat;
public class MemTableTest { public class MemTableTest {
static {
RocksDB.loadLibrary(); @ClassRule
} public static final RocksMemoryResource rocksMemoryResource =
public static void main(String[] args) { new RocksMemoryResource();
Options options = new Options();
// Test HashSkipListMemTableConfig @Test
HashSkipListMemTableConfig memTableConfig = public void hashSkipListMemTable() throws RocksDBException {
new HashSkipListMemTableConfig(); Options options = null;
assert(memTableConfig.bucketCount() == 1000000);
memTableConfig.setBucketCount(2000000);
assert(memTableConfig.bucketCount() == 2000000);
assert(memTableConfig.height() == 4);
memTableConfig.setHeight(5);
assert(memTableConfig.height() == 5);
assert(memTableConfig.branchingFactor() == 4);
memTableConfig.setBranchingFactor(6);
assert(memTableConfig.branchingFactor() == 6);
try { try {
options = new Options();
// Test HashSkipListMemTableConfig
HashSkipListMemTableConfig memTableConfig =
new HashSkipListMemTableConfig();
assertThat(memTableConfig.bucketCount()).
isEqualTo(1000000);
memTableConfig.setBucketCount(2000000);
assertThat(memTableConfig.bucketCount()).
isEqualTo(2000000);
assertThat(memTableConfig.height()).
isEqualTo(4);
memTableConfig.setHeight(5);
assertThat(memTableConfig.height()).
isEqualTo(5);
assertThat(memTableConfig.branchingFactor()).
isEqualTo(4);
memTableConfig.setBranchingFactor(6);
assertThat(memTableConfig.branchingFactor()).
isEqualTo(6);
options.setMemTableConfig(memTableConfig); options.setMemTableConfig(memTableConfig);
} catch (RocksDBException e) { } finally {
assert(false); if (options != null) {
options.dispose();
}
} }
memTableConfig = null; }
options.dispose();
System.gc(); @Test
System.runFinalization(); public void skipListMemTable() throws RocksDBException {
// Test SkipList Options options = null;
options = new Options();
SkipListMemTableConfig skipMemTableConfig =
new SkipListMemTableConfig();
assert(skipMemTableConfig.lookahead() == 0);
skipMemTableConfig.setLookahead(20);
assert(skipMemTableConfig.lookahead() == 20);
try { try {
options = new Options();
SkipListMemTableConfig skipMemTableConfig =
new SkipListMemTableConfig();
assertThat(skipMemTableConfig.lookahead()).
isEqualTo(0);
skipMemTableConfig.setLookahead(20);
assertThat(skipMemTableConfig.lookahead()).
isEqualTo(20);
options.setMemTableConfig(skipMemTableConfig); options.setMemTableConfig(skipMemTableConfig);
} catch (RocksDBException e) { options.dispose();
assert(false); } finally {
if (options != null) {
options.dispose();
}
} }
skipMemTableConfig = null; }
options.dispose();
System.gc(); @Test
System.runFinalization(); public void hashLinkedListMemTable() throws RocksDBException {
// Test HashLinkedListMemTableConfig Options options = null;
options = new Options();
HashLinkedListMemTableConfig hashLinkedListMemTableConfig =
new HashLinkedListMemTableConfig();
assert(hashLinkedListMemTableConfig.bucketCount() == 50000);
hashLinkedListMemTableConfig.setBucketCount(100000);
assert(hashLinkedListMemTableConfig.bucketCount() == 100000);
assert(hashLinkedListMemTableConfig.hugePageTlbSize() == 0);
hashLinkedListMemTableConfig.setHugePageTlbSize(1);
assert(hashLinkedListMemTableConfig.hugePageTlbSize() == 1);
assert(hashLinkedListMemTableConfig.
bucketEntriesLoggingThreshold() == 4096);
hashLinkedListMemTableConfig.
setBucketEntriesLoggingThreshold(200);
assert(hashLinkedListMemTableConfig.
bucketEntriesLoggingThreshold() == 200);
assert(hashLinkedListMemTableConfig.
ifLogBucketDistWhenFlush() == true);
hashLinkedListMemTableConfig.
setIfLogBucketDistWhenFlush(false);
assert(hashLinkedListMemTableConfig.
ifLogBucketDistWhenFlush() == false);
assert(hashLinkedListMemTableConfig.
thresholdUseSkiplist() == 256);
hashLinkedListMemTableConfig.setThresholdUseSkiplist(29);
assert(hashLinkedListMemTableConfig.
thresholdUseSkiplist() == 29);
try { try {
options = new Options();
HashLinkedListMemTableConfig hashLinkedListMemTableConfig =
new HashLinkedListMemTableConfig();
assertThat(hashLinkedListMemTableConfig.bucketCount()).
isEqualTo(50000);
hashLinkedListMemTableConfig.setBucketCount(100000);
assertThat(hashLinkedListMemTableConfig.bucketCount()).
isEqualTo(100000);
assertThat(hashLinkedListMemTableConfig.hugePageTlbSize()).
isEqualTo(0);
hashLinkedListMemTableConfig.setHugePageTlbSize(1);
assertThat(hashLinkedListMemTableConfig.hugePageTlbSize()).
isEqualTo(1);
assertThat(hashLinkedListMemTableConfig.
bucketEntriesLoggingThreshold()).
isEqualTo(4096);
hashLinkedListMemTableConfig.
setBucketEntriesLoggingThreshold(200);
assertThat(hashLinkedListMemTableConfig.
bucketEntriesLoggingThreshold()).
isEqualTo(200);
assertThat(hashLinkedListMemTableConfig.
ifLogBucketDistWhenFlush()).isTrue();
hashLinkedListMemTableConfig.
setIfLogBucketDistWhenFlush(false);
assertThat(hashLinkedListMemTableConfig.
ifLogBucketDistWhenFlush()).isFalse();
assertThat(hashLinkedListMemTableConfig.
thresholdUseSkiplist()).
isEqualTo(256);
hashLinkedListMemTableConfig.setThresholdUseSkiplist(29);
assertThat(hashLinkedListMemTableConfig.
thresholdUseSkiplist()).
isEqualTo(29);
options.setMemTableConfig(hashLinkedListMemTableConfig); options.setMemTableConfig(hashLinkedListMemTableConfig);
} catch (RocksDBException e) { } finally {
assert(false); if (options != null) {
options.dispose();
}
} }
hashLinkedListMemTableConfig = null; }
options.dispose();
System.gc(); @Test
System.runFinalization(); public void vectorMemTable() throws RocksDBException {
// test VectorMemTableConfig Options options = null;
options = new Options();
VectorMemTableConfig vectorMemTableConfig =
new VectorMemTableConfig();
assert(vectorMemTableConfig.reservedSize() == 0);
vectorMemTableConfig.setReservedSize(123);
assert(vectorMemTableConfig.reservedSize() == 123);
try { try {
options = new Options();
VectorMemTableConfig vectorMemTableConfig =
new VectorMemTableConfig();
assertThat(vectorMemTableConfig.reservedSize()).
isEqualTo(0);
vectorMemTableConfig.setReservedSize(123);
assertThat(vectorMemTableConfig.reservedSize()).
isEqualTo(123);
options.setMemTableConfig(vectorMemTableConfig); options.setMemTableConfig(vectorMemTableConfig);
} catch (RocksDBException e) { options.dispose();
assert(false); } finally {
if (options != null) {
options.dispose();
}
} }
vectorMemTableConfig = null;
options.dispose();
System.gc();
System.runFinalization();
System.out.println("Mem-table test passed");
} }
} }

@ -7,192 +7,249 @@ package org.rocksdb.test;
import java.util.List; import java.util.List;
import java.util.ArrayList; import java.util.ArrayList;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.rocksdb.*; import org.rocksdb.*;
import static org.assertj.core.api.Assertions.assertThat;
public class MergeTest { public class MergeTest {
static final String db_path_string = "/tmp/rocksdbjni_mergestring_db";
static final String db_cf_path_string = "/tmp/rocksdbjni_mergecfstring_db";
static final String db_path_operator = "/tmp/rocksdbjni_mergeoperator_db";
static { @ClassRule
RocksDB.loadLibrary(); public static final RocksMemoryResource rocksMemoryResource =
} new RocksMemoryResource();
public static void testStringOption() @Rule
public TemporaryFolder dbFolder = new TemporaryFolder();
@Test
public void stringOption()
throws InterruptedException, RocksDBException { throws InterruptedException, RocksDBException {
Options opt = new Options(); RocksDB db = null;
opt.setCreateIfMissing(true); Options opt = null;
opt.setMergeOperatorName("stringappend"); try {
String db_path_string =
RocksDB db = RocksDB.open(opt, db_path_string); dbFolder.getRoot().getAbsolutePath();
// writing aa under key opt = new Options();
db.put("key".getBytes(), "aa".getBytes()); opt.setCreateIfMissing(true);
// merge bb under key opt.setMergeOperatorName("stringappend");
db.merge("key".getBytes(), "bb".getBytes());
db = RocksDB.open(opt, db_path_string);
byte[] value = db.get("key".getBytes()); // writing aa under key
String strValue = new String(value); db.put("key".getBytes(), "aa".getBytes());
// merge bb under key
db.close(); db.merge("key".getBytes(), "bb".getBytes());
opt.dispose();
assert(strValue.equals("aa,bb")); byte[] value = db.get("key".getBytes());
String strValue = new String(value);
assertThat(strValue).isEqualTo("aa,bb");
} finally {
if (db != null) {
db.close();
}
if (opt != null) {
opt.dispose();
}
}
} }
public static void testCFStringOption() @Test
public void cFStringOption()
throws InterruptedException, RocksDBException { throws InterruptedException, RocksDBException {
DBOptions opt = new DBOptions(); RocksDB db = null;
opt.setCreateIfMissing(true); DBOptions opt = null;
opt.setCreateMissingColumnFamilies(true);
List<ColumnFamilyDescriptor> cfDescr =
new ArrayList<ColumnFamilyDescriptor>();
List<ColumnFamilyHandle> columnFamilyHandleList = List<ColumnFamilyHandle> columnFamilyHandleList =
new ArrayList<ColumnFamilyHandle>(); new ArrayList<>();
cfDescr.add(new ColumnFamilyDescriptor("default", try {
new ColumnFamilyOptions().setMergeOperatorName( String db_path_string =
"stringappend"))); dbFolder.getRoot().getAbsolutePath();
cfDescr.add(new ColumnFamilyDescriptor("default", opt = new DBOptions();
new ColumnFamilyOptions().setMergeOperatorName( opt.setCreateIfMissing(true);
"stringappend"))); opt.setCreateMissingColumnFamilies(true);
RocksDB db = RocksDB.open(opt, db_cf_path_string,
cfDescr, columnFamilyHandleList); List<ColumnFamilyDescriptor> cfDescriptors =
new ArrayList<>();
// writing aa under key cfDescriptors.add(new ColumnFamilyDescriptor("default",
db.put(columnFamilyHandleList.get(1), new ColumnFamilyOptions().setMergeOperatorName(
"cfkey".getBytes(), "aa".getBytes()); "stringappend")));
// merge bb under key cfDescriptors.add(new ColumnFamilyDescriptor("default",
db.merge(columnFamilyHandleList.get(1), new ColumnFamilyOptions().setMergeOperatorName(
"cfkey".getBytes(), "bb".getBytes()); "stringappend")));
db = RocksDB.open(opt, db_path_string,
byte[] value = db.get(columnFamilyHandleList.get(1), "cfkey".getBytes()); cfDescriptors, columnFamilyHandleList);
String strValue = new String(value);
// writing aa under key
for (ColumnFamilyHandle handle : columnFamilyHandleList) { db.put(columnFamilyHandleList.get(1),
handle.dispose(); "cfkey".getBytes(), "aa".getBytes());
// merge bb under key
db.merge(columnFamilyHandleList.get(1),
"cfkey".getBytes(), "bb".getBytes());
byte[] value = db.get(columnFamilyHandleList.get(1), "cfkey".getBytes());
String strValue = new String(value);
assertThat(strValue).isEqualTo("aa,bb");
} finally {
for (ColumnFamilyHandle handle : columnFamilyHandleList) {
handle.dispose();
}
if (db != null) {
db.close();
}
if (opt != null) {
opt.dispose();
}
} }
db.close();
opt.dispose();
assert(strValue.equals("aa,bb"));
} }
public static void testOperatorOption() @Test
public void operatorOption()
throws InterruptedException, RocksDBException { throws InterruptedException, RocksDBException {
Options opt = new Options(); RocksDB db = null;
opt.setCreateIfMissing(true); Options opt = null;
try {
StringAppendOperator stringAppendOperator = new StringAppendOperator(); String db_path_string =
opt.setMergeOperator(stringAppendOperator); dbFolder.getRoot().getAbsolutePath();
opt = new Options();
RocksDB db = RocksDB.open(opt, db_path_string); opt.setCreateIfMissing(true);
// Writing aa under key
db.put("key".getBytes(), "aa".getBytes()); StringAppendOperator stringAppendOperator = new StringAppendOperator();
opt.setMergeOperator(stringAppendOperator);
// Writing bb under key
db.merge("key".getBytes(), "bb".getBytes()); db = RocksDB.open(opt, db_path_string);
// Writing aa under key
byte[] value = db.get("key".getBytes()); db.put("key".getBytes(), "aa".getBytes());
String strValue = new String(value);
// Writing bb under key
db.close(); db.merge("key".getBytes(), "bb".getBytes());
opt.dispose();
assert(strValue.equals("aa,bb")); byte[] value = db.get("key".getBytes());
String strValue = new String(value);
assertThat(strValue).isEqualTo("aa,bb");
} finally {
if (db != null) {
db.close();
}
if (opt != null) {
opt.dispose();
}
}
} }
public static void testCFOperatorOption() @Test
public void cFOperatorOption()
throws InterruptedException, RocksDBException { throws InterruptedException, RocksDBException {
DBOptions opt = new DBOptions(); RocksDB db = null;
opt.setCreateIfMissing(true); DBOptions opt = null;
opt.setCreateMissingColumnFamilies(true); ColumnFamilyHandle columnFamilyHandle = null;
StringAppendOperator stringAppendOperator = new StringAppendOperator(); try {
String db_path_string =
List<ColumnFamilyDescriptor> cfDescr = dbFolder.getRoot().getAbsolutePath();
new ArrayList<ColumnFamilyDescriptor>(); opt = new DBOptions();
List<ColumnFamilyHandle> columnFamilyHandleList = opt.setCreateIfMissing(true);
new ArrayList<ColumnFamilyHandle>(); opt.setCreateMissingColumnFamilies(true);
cfDescr.add(new ColumnFamilyDescriptor("default", StringAppendOperator stringAppendOperator = new StringAppendOperator();
new ColumnFamilyOptions().setMergeOperator(
stringAppendOperator))); List<ColumnFamilyDescriptor> cfDescriptors =
cfDescr.add(new ColumnFamilyDescriptor("new_cf", new ArrayList<>();
new ColumnFamilyOptions().setMergeOperator( List<ColumnFamilyHandle> columnFamilyHandleList =
stringAppendOperator))); new ArrayList<>();
RocksDB db = RocksDB.open(opt, db_path_operator, cfDescriptors.add(new ColumnFamilyDescriptor("default",
cfDescr, columnFamilyHandleList); new ColumnFamilyOptions().setMergeOperator(
stringAppendOperator)));
// writing aa under key cfDescriptors.add(new ColumnFamilyDescriptor("new_cf",
db.put(columnFamilyHandleList.get(1), new ColumnFamilyOptions().setMergeOperator(
"cfkey".getBytes(), "aa".getBytes()); stringAppendOperator)));
// merge bb under key db = RocksDB.open(opt, db_path_string,
db.merge(columnFamilyHandleList.get(1), cfDescriptors, columnFamilyHandleList);
"cfkey".getBytes(), "bb".getBytes());
byte[] value = db.get(columnFamilyHandleList.get(1), "cfkey".getBytes()); // writing aa under key
String strValue = new String(value); db.put(columnFamilyHandleList.get(1),
"cfkey".getBytes(), "aa".getBytes());
// Test also with createColumnFamily // merge bb under key
ColumnFamilyHandle columnFamilyHandle = db.createColumnFamily( db.merge(columnFamilyHandleList.get(1),
new ColumnFamilyDescriptor("new_cf2", "cfkey".getBytes(), "bb".getBytes());
new ColumnFamilyOptions().setMergeOperator( byte[] value = db.get(columnFamilyHandleList.get(1), "cfkey".getBytes());
new StringAppendOperator()))); String strValue = new String(value);
// writing xx under cfkey2
db.put(columnFamilyHandle, "cfkey2".getBytes(), "xx".getBytes()); // Test also with createColumnFamily
// merge yy under cfkey2 columnFamilyHandle = db.createColumnFamily(
db.merge(columnFamilyHandle, "cfkey2".getBytes(), "yy".getBytes()); new ColumnFamilyDescriptor("new_cf2",
value = db.get(columnFamilyHandle, "cfkey2".getBytes()); new ColumnFamilyOptions().setMergeOperator(stringAppendOperator)));
String strValueTmpCf = new String(value); // writing xx under cfkey2
db.put(columnFamilyHandle, "cfkey2".getBytes(), "xx".getBytes());
db.close(); // merge yy under cfkey2
opt.dispose(); db.merge(columnFamilyHandle, new WriteOptions(), "cfkey2".getBytes(), "yy".getBytes());
assert(strValue.equals("aa,bb")); value = db.get(columnFamilyHandle, "cfkey2".getBytes());
assert(strValueTmpCf.equals("xx,yy")); String strValueTmpCf = new String(value);
columnFamilyHandle.dispose();
assertThat(strValue).isEqualTo("aa,bb");
assertThat(strValueTmpCf).isEqualTo("xx,yy");
} finally {
if (columnFamilyHandle != null) {
columnFamilyHandle.dispose();
}
if (db != null) {
db.close();
}
if (opt != null) {
opt.dispose();
}
}
} }
public static void testOperatorGcBehaviour() @Test
public void operatorGcBehaviour()
throws RocksDBException { throws RocksDBException {
Options opt = new Options(); Options opt = null;
opt.setCreateIfMissing(true); RocksDB db = null;
StringAppendOperator stringAppendOperator = new StringAppendOperator(); try {
opt.setMergeOperator(stringAppendOperator); String db_path_string =
RocksDB db = RocksDB.open(opt, db_path_string); dbFolder.getRoot().getAbsolutePath();
db.close(); opt = new Options();
opt.dispose(); opt.setCreateIfMissing(true);
System.gc(); StringAppendOperator stringAppendOperator = new StringAppendOperator();
System.runFinalization(); opt.setMergeOperator(stringAppendOperator);
// test reuse db = RocksDB.open(opt, db_path_string);
opt = new Options(); db.close();
opt.setMergeOperator(stringAppendOperator); opt.dispose();
db = RocksDB.open(opt, db_path_string); System.gc();
db.close(); System.runFinalization();
opt.dispose(); // test reuse
System.gc(); opt = new Options();
System.runFinalization(); opt.setMergeOperator(stringAppendOperator);
// test param init db = RocksDB.open(opt, db_path_string);
opt = new Options(); db.close();
opt.setMergeOperator(new StringAppendOperator()); opt.dispose();
db = RocksDB.open(opt, db_path_string); System.gc();
db.close(); System.runFinalization();
opt.dispose(); // test param init
System.gc(); opt = new Options();
System.runFinalization(); opt.setMergeOperator(new StringAppendOperator());
// test replace one with another merge operator instance db = RocksDB.open(opt, db_path_string);
opt = new Options(); db.close();
opt.setMergeOperator(stringAppendOperator); opt.dispose();
StringAppendOperator newStringAppendOperator = new StringAppendOperator(); System.gc();
opt.setMergeOperator(newStringAppendOperator); System.runFinalization();
db = RocksDB.open(opt, db_path_string); // test replace one with another merge operator instance
db.close(); opt = new Options();
opt.dispose(); opt.setMergeOperator(stringAppendOperator);
stringAppendOperator = null; StringAppendOperator newStringAppendOperator = new StringAppendOperator();
newStringAppendOperator = null; opt.setMergeOperator(newStringAppendOperator);
System.gc(); db = RocksDB.open(opt, db_path_string);
System.runFinalization(); db.close();
} opt.dispose();
} finally {
public static void main(String[] args) if (db != null) {
throws InterruptedException, RocksDBException { db.close();
testStringOption(); }
testCFStringOption(); if (opt != null) {
testOperatorOption(); opt.dispose();
testCFOperatorOption(); }
testOperatorGcBehaviour(); }
System.out.println("Passed MergeTest.");
} }
} }

@ -5,26 +5,33 @@
package org.rocksdb.test; package org.rocksdb.test;
import org.junit.ClassRule;
import org.junit.Test;
import org.rocksdb.*; import org.rocksdb.*;
import static org.assertj.core.api.Assertions.assertThat;
public class MixedOptionsTest { public class MixedOptionsTest {
static {
RocksDB.loadLibrary(); @ClassRule
} public static final RocksMemoryResource rocksMemoryResource =
public static void main(String[] args) { new RocksMemoryResource();
@Test
public void mixedOptionsTest(){
// Set a table factory and check the names // Set a table factory and check the names
ColumnFamilyOptions cfOptions = new ColumnFamilyOptions(); ColumnFamilyOptions cfOptions = new ColumnFamilyOptions();
cfOptions.setTableFormatConfig(new BlockBasedTableConfig(). cfOptions.setTableFormatConfig(new BlockBasedTableConfig().
setFilter(new BloomFilter())); setFilter(new BloomFilter()));
assert(cfOptions.tableFactoryName().equals( assertThat(cfOptions.tableFactoryName()).isEqualTo(
"BlockBasedTable")); "BlockBasedTable");
cfOptions.setTableFormatConfig(new PlainTableConfig()); cfOptions.setTableFormatConfig(new PlainTableConfig());
assert(cfOptions.tableFactoryName().equals("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(); DBOptions dbOptions = new DBOptions();
Options options = new Options(dbOptions, cfOptions); Options options = new Options(dbOptions, cfOptions);
assert(options.tableFactoryName().equals("PlainTable")); assertThat(options.tableFactoryName()).isEqualTo("PlainTable");
// Free instances // Free instances
options.dispose(); options.dispose();
options = null; options = null;

File diff suppressed because it is too large Load Diff

@ -5,30 +5,94 @@
package org.rocksdb.test; package org.rocksdb.test;
import org.junit.ClassRule;
import org.junit.Test;
import org.rocksdb.EncodingType; import org.rocksdb.EncodingType;
import org.rocksdb.Options;
import org.rocksdb.PlainTableConfig; import org.rocksdb.PlainTableConfig;
import static org.assertj.core.api.Assertions.assertThat;
public class PlainTableConfigTest { public class PlainTableConfigTest {
public static void main(String[] args) { @ClassRule
public static final RocksMemoryResource rocksMemoryResource =
new RocksMemoryResource();
@Test
public void keySize() {
PlainTableConfig plainTableConfig = new PlainTableConfig(); PlainTableConfig plainTableConfig = new PlainTableConfig();
plainTableConfig.setKeySize(5); plainTableConfig.setKeySize(5);
assert(plainTableConfig.keySize() == 5); assertThat(plainTableConfig.keySize()).
isEqualTo(5);
}
@Test
public void bloomBitsPerKey() {
PlainTableConfig plainTableConfig = new PlainTableConfig();
plainTableConfig.setBloomBitsPerKey(11); plainTableConfig.setBloomBitsPerKey(11);
assert(plainTableConfig.bloomBitsPerKey() == 11); assertThat(plainTableConfig.bloomBitsPerKey()).
isEqualTo(11);
}
@Test
public void hashTableRatio() {
PlainTableConfig plainTableConfig = new PlainTableConfig();
plainTableConfig.setHashTableRatio(0.95); plainTableConfig.setHashTableRatio(0.95);
assert(plainTableConfig.hashTableRatio() == 0.95); assertThat(plainTableConfig.hashTableRatio()).
isEqualTo(0.95);
}
@Test
public void indexSparseness() {
PlainTableConfig plainTableConfig = new PlainTableConfig();
plainTableConfig.setIndexSparseness(18); plainTableConfig.setIndexSparseness(18);
assert(plainTableConfig.indexSparseness() == 18); assertThat(plainTableConfig.indexSparseness()).
isEqualTo(18);
}
@Test
public void hugePageTlbSize() {
PlainTableConfig plainTableConfig = new PlainTableConfig();
plainTableConfig.setHugePageTlbSize(1); plainTableConfig.setHugePageTlbSize(1);
assert(plainTableConfig.hugePageTlbSize() == 1); assertThat(plainTableConfig.hugePageTlbSize()).
isEqualTo(1);
}
@Test
public void encodingType() {
PlainTableConfig plainTableConfig = new PlainTableConfig();
plainTableConfig.setEncodingType(EncodingType.kPrefix); plainTableConfig.setEncodingType(EncodingType.kPrefix);
assert(plainTableConfig.encodingType().equals( assertThat(plainTableConfig.encodingType()).isEqualTo(
EncodingType.kPrefix)); EncodingType.kPrefix);
}
@Test
public void fullScanMode() {
PlainTableConfig plainTableConfig = new PlainTableConfig();
plainTableConfig.setFullScanMode(true); plainTableConfig.setFullScanMode(true);
assert(plainTableConfig.fullScanMode()); assertThat(plainTableConfig.fullScanMode()).isTrue(); }
@Test
public void storeIndexInFile() {
PlainTableConfig plainTableConfig = new PlainTableConfig();
plainTableConfig.setStoreIndexInFile(true); plainTableConfig.setStoreIndexInFile(true);
assert(plainTableConfig.storeIndexInFile()); assertThat(plainTableConfig.storeIndexInFile()).
System.out.println("PlainTableConfig test passed"); isTrue();
}
@Test
public void plainTableConfig() {
Options opt = null;
try {
opt = new Options();
PlainTableConfig plainTableConfig = new PlainTableConfig();
opt.setTableFormatConfig(plainTableConfig);
assertThat(opt.tableFactoryName()).isEqualTo("PlainTable");
} finally {
if (opt != null) {
opt.dispose();
}
}
} }
} }

@ -18,11 +18,11 @@ 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 = false; 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 {
is64Bit = (System.getProperty("os.arch").indexOf("64") != -1); is64Bit = (System.getProperty("os.arch").contains("64"));
} }
return is64Bit; return is64Bit;
} }

@ -4,41 +4,59 @@
// of patent rights can be found in the PATENTS file in the same directory. // of patent rights can be found in the PATENTS file in the same directory.
package org.rocksdb.test; package org.rocksdb.test;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.rocksdb.*; import org.rocksdb.*;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
public class ReadOnlyTest { public class ReadOnlyTest {
static final String DB_PATH = "/tmp/rocksdbjni_readonly_test";
static {
RocksDB.loadLibrary();
}
public static void main(String[] args){ @ClassRule
RocksDB db = null, db2 = null, db3 = null; public static final RocksMemoryResource rocksMemoryResource =
new RocksMemoryResource();
@Rule
public TemporaryFolder dbFolder = new TemporaryFolder();
@Test
public void readOnlyOpen() throws RocksDBException {
RocksDB db = null;
RocksDB db2 = null;
RocksDB db3 = null;
Options options = null;
List<ColumnFamilyHandle> columnFamilyHandleList = List<ColumnFamilyHandle> columnFamilyHandleList =
new ArrayList<ColumnFamilyHandle>(); new ArrayList<>();
List<ColumnFamilyHandle> db2ColumnFamilyHandleList = List<ColumnFamilyHandle> readOnlyColumnFamilyHandleList =
new ArrayList<ColumnFamilyHandle>(); new ArrayList<>();
List<ColumnFamilyHandle> db3ColumnFamilyHandleList = List<ColumnFamilyHandle> readOnlyColumnFamilyHandleList2 =
new ArrayList<ColumnFamilyHandle>(); new ArrayList<>();
Options options = new Options();
options.setCreateIfMissing(true);
try { try {
db = RocksDB.open(options, DB_PATH); 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(DB_PATH); db2 = RocksDB.openReadOnly(
assert("value".equals(new String(db2.get("key".getBytes())))); dbFolder.getRoot().getAbsolutePath());
assertThat("value").
isEqualTo(new String(db2.get("key".getBytes())));
db.close(); db.close();
db2.close(); db2.close();
List<ColumnFamilyDescriptor> cfDescriptors = new ArrayList<>();
cfDescriptors.add(
new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY,
new ColumnFamilyOptions()));
List<ColumnFamilyDescriptor> cfNames = db = RocksDB.open(
new ArrayList<ColumnFamilyDescriptor>(); dbFolder.getRoot().getAbsolutePath(), cfDescriptors, columnFamilyHandleList);
cfNames.add(new ColumnFamilyDescriptor("default"));
db = RocksDB.open(DB_PATH, cfNames, columnFamilyHandleList);
columnFamilyHandleList.add(db.createColumnFamily( columnFamilyHandleList.add(db.createColumnFamily(
new ColumnFamilyDescriptor("new_cf", new ColumnFamilyOptions()))); new ColumnFamilyDescriptor("new_cf", new ColumnFamilyOptions())));
columnFamilyHandleList.add(db.createColumnFamily( columnFamilyHandleList.add(db.createColumnFamily(
@ -46,85 +64,270 @@ public class ReadOnlyTest {
db.put(columnFamilyHandleList.get(2), "key2".getBytes(), db.put(columnFamilyHandleList.get(2), "key2".getBytes(),
"value2".getBytes()); "value2".getBytes());
db2 = RocksDB.openReadOnly(DB_PATH, cfNames, db2ColumnFamilyHandleList); db2 = RocksDB.openReadOnly(
assert(db2.get("key2".getBytes())==null); dbFolder.getRoot().getAbsolutePath(), cfDescriptors,
assert(db2.get(columnFamilyHandleList.get(0), "key2".getBytes())==null); readOnlyColumnFamilyHandleList);
assertThat(db2.get("key2".getBytes())).isNull();
List<ColumnFamilyDescriptor> cfNewName = assertThat(db2.get(readOnlyColumnFamilyHandleList.get(0), "key2".getBytes())).
new ArrayList<ColumnFamilyDescriptor>(); isNull();
cfNewName.add(new ColumnFamilyDescriptor("default")); cfDescriptors.clear();
cfNewName.add(new ColumnFamilyDescriptor("new_cf2")); cfDescriptors.add(
db3 = RocksDB.openReadOnly(DB_PATH, cfNewName, db3ColumnFamilyHandleList); new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY,
assert(new String(db3.get(db3ColumnFamilyHandleList.get(1), new ColumnFamilyOptions()));
"key2".getBytes())).equals("value2")); cfDescriptors.add(
}catch (RocksDBException e){ new ColumnFamilyDescriptor("new_cf2", new ColumnFamilyOptions()));
e.printStackTrace(); db3 = RocksDB.openReadOnly(
assert(false); dbFolder.getRoot().getAbsolutePath(), cfDescriptors, readOnlyColumnFamilyHandleList2);
assertThat(new String(db3.get(readOnlyColumnFamilyHandleList2.get(1),
"key2".getBytes()))).isEqualTo("value2");
} finally {
if (db != null) {
db.close();
}
if (db2 != null) {
db2.close();
}
if (db3 != null) {
db3.close();
}
if (options != null) {
options.dispose();
}
} }
// test that put fails in readonly mode }
@Test(expected = RocksDBException.class)
public void failToWriteInReadOnly() throws RocksDBException {
RocksDB db = null;
RocksDB rDb = null;
Options options = null;
try { try {
db2.put("key".getBytes(), "value".getBytes()); List<ColumnFamilyDescriptor> cfDescriptors = new ArrayList<>();
assert(false); cfDescriptors.add(
} catch (RocksDBException e) { new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY,
assert(true); new ColumnFamilyOptions()));
List<ColumnFamilyHandle> readOnlyColumnFamilyHandleList =
new ArrayList<>();
options = new Options();
options.setCreateIfMissing(true);
db = RocksDB.open(options,
dbFolder.getRoot().getAbsolutePath());
db.close();
rDb = RocksDB.openReadOnly(
dbFolder.getRoot().getAbsolutePath(), cfDescriptors,
readOnlyColumnFamilyHandleList);
// test that put fails in readonly mode
rDb.put("key".getBytes(), "value".getBytes());
} finally {
if (db != null) {
db.close();
}
if (rDb != null) {
rDb.close();
}
if (options != null) {
options.dispose();
}
} }
}
@Test(expected = RocksDBException.class)
public void failToCFWriteInReadOnly() throws RocksDBException {
RocksDB db = null;
RocksDB rDb = null;
Options options = null;
try { try {
db3.put(db3ColumnFamilyHandleList.get(1), List<ColumnFamilyDescriptor> cfDescriptors = new ArrayList<>();
cfDescriptors.add(
new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY,
new ColumnFamilyOptions()));
List<ColumnFamilyHandle> readOnlyColumnFamilyHandleList =
new ArrayList<>();
options = new Options();
options.setCreateIfMissing(true);
db = RocksDB.open(options,
dbFolder.getRoot().getAbsolutePath());
db.close();
rDb = RocksDB.openReadOnly(
dbFolder.getRoot().getAbsolutePath(), cfDescriptors,
readOnlyColumnFamilyHandleList);
rDb.put(readOnlyColumnFamilyHandleList.get(0),
"key".getBytes(), "value".getBytes()); "key".getBytes(), "value".getBytes());
assert(false); } finally {
} catch (RocksDBException e) { if (db != null) {
assert(true); db.close();
}
if (rDb != null) {
rDb.close();
}
if (options != null) {
options.dispose();
}
} }
// test that remove fails in readonly mode }
@Test(expected = RocksDBException.class)
public void failToRemoveInReadOnly() throws RocksDBException {
RocksDB db = null;
RocksDB rDb = null;
Options options = null;
try { try {
db2.remove("key".getBytes()); List<ColumnFamilyDescriptor> cfDescriptors = new ArrayList<>();
assert(false); cfDescriptors.add(
} catch (RocksDBException e) { new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY,
assert(true); new ColumnFamilyOptions()));
List<ColumnFamilyHandle> readOnlyColumnFamilyHandleList =
new ArrayList<>();
options = new Options();
options.setCreateIfMissing(true);
db = RocksDB.open(options,
dbFolder.getRoot().getAbsolutePath());
db.close();
rDb = RocksDB.openReadOnly(
dbFolder.getRoot().getAbsolutePath(), cfDescriptors,
readOnlyColumnFamilyHandleList);
rDb.remove("key".getBytes());
} finally {
if (db != null) {
db.close();
}
if (rDb != null) {
rDb.close();
}
if (options != null) {
options.dispose();
}
} }
}
@Test(expected = RocksDBException.class)
public void failToCFRemoveInReadOnly() throws RocksDBException {
RocksDB db = null;
RocksDB rDb = null;
Options options = null;
try { try {
db3.remove(db3ColumnFamilyHandleList.get(1), List<ColumnFamilyDescriptor> cfDescriptors = new ArrayList<>();
cfDescriptors.add(
new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY,
new ColumnFamilyOptions()));
List<ColumnFamilyHandle> readOnlyColumnFamilyHandleList =
new ArrayList<>();
options = new Options();
options.setCreateIfMissing(true);
db = RocksDB.open(options,
dbFolder.getRoot().getAbsolutePath());
db.close();
rDb = RocksDB.openReadOnly(
dbFolder.getRoot().getAbsolutePath(), cfDescriptors,
readOnlyColumnFamilyHandleList);
rDb.remove(readOnlyColumnFamilyHandleList.get(0),
"key".getBytes()); "key".getBytes());
assert(false); } finally {
} catch (RocksDBException e) { if (db != null) {
assert(true); db.close();
}
if (rDb != null) {
rDb.close();
}
if (options != null) {
options.dispose();
}
} }
// test that write fails in readonly mode }
WriteBatch wb = new WriteBatch();
wb.put("key".getBytes(), "value".getBytes()); @Test(expected = RocksDBException.class)
public void failToWriteBatchReadOnly() throws RocksDBException {
RocksDB db = null;
RocksDB rDb = null;
Options options = null;
try { try {
db2.write(new WriteOptions(), wb); List<ColumnFamilyDescriptor> cfDescriptors = new ArrayList<>();
assert(false); cfDescriptors.add(
} catch (RocksDBException e) { new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY,
assert(true); new ColumnFamilyOptions()));
List<ColumnFamilyHandle> readOnlyColumnFamilyHandleList =
new ArrayList<>();
options = new Options();
options.setCreateIfMissing(true);
db = RocksDB.open(options,
dbFolder.getRoot().getAbsolutePath());
db.close();
rDb = RocksDB.openReadOnly(
dbFolder.getRoot().getAbsolutePath(), cfDescriptors,
readOnlyColumnFamilyHandleList);
WriteBatch wb = new WriteBatch();
wb.put("key".getBytes(), "value".getBytes());
rDb.write(new WriteOptions(), wb);
} finally {
if (db != null) {
db.close();
}
if (rDb != null) {
rDb.close();
}
if (options != null) {
options.dispose();
}
} }
wb.dispose(); }
wb = new WriteBatch();
wb.put(db3ColumnFamilyHandleList.get(1), @Test(expected = RocksDBException.class)
"key".getBytes(), "value".getBytes()); public void failToCFWriteBatchReadOnly() throws RocksDBException {
RocksDB db = null;
RocksDB rDb = null;
Options options = null;
WriteBatch wb = null;
try { try {
db3.write(new WriteOptions(), wb); List<ColumnFamilyDescriptor> cfDescriptors = new ArrayList<>();
assert(false); cfDescriptors.add(
} catch (RocksDBException e) { new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY,
assert(true); new ColumnFamilyOptions()));
} List<ColumnFamilyHandle> readOnlyColumnFamilyHandleList =
wb.dispose(); new ArrayList<>();
// cleanup c++ pointers
for (ColumnFamilyHandle columnFamilyHandle : options = new Options();
columnFamilyHandleList) { options.setCreateIfMissing(true);
columnFamilyHandle.dispose();
} db = RocksDB.open(options,
db.close(); dbFolder.getRoot().getAbsolutePath());
for (ColumnFamilyHandle columnFamilyHandle : db.close();
db2ColumnFamilyHandleList) {
columnFamilyHandle.dispose(); rDb = RocksDB.openReadOnly(
} dbFolder.getRoot().getAbsolutePath(), cfDescriptors,
db2.close(); readOnlyColumnFamilyHandleList);
for (ColumnFamilyHandle columnFamilyHandle :
db3ColumnFamilyHandleList) { wb = new WriteBatch();
columnFamilyHandle.dispose(); wb.put(readOnlyColumnFamilyHandleList.get(0),
"key".getBytes(), "value".getBytes());
rDb.write(new WriteOptions(), wb);
} finally {
if (db != null) {
db.close();
}
if (rDb != null) {
rDb.close();
}
if (options != null) {
options.dispose();
}
if (wb != null) {
wb.dispose();
}
} }
db3.close();
System.out.println("Passed ReadOnlyTest");
} }
} }

@ -6,35 +6,147 @@
package org.rocksdb.test; package org.rocksdb.test;
import java.util.Random; import java.util.Random;
import org.rocksdb.RocksDB;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.rocksdb.ReadOptions; import org.rocksdb.ReadOptions;
import static org.assertj.core.api.Assertions.assertThat;
public class ReadOptionsTest { public class ReadOptionsTest {
static {
RocksDB.loadLibrary(); @ClassRule
} public static final RocksMemoryResource rocksMemoryResource =
public static void main(String[] args) { new RocksMemoryResource();
ReadOptions opt = new ReadOptions();
Random rand = new Random(); @Rule
{ // VerifyChecksums test public ExpectedException exception = ExpectedException.none();
@Test
public void verifyChecksum(){
ReadOptions opt = null;
try {
opt = new ReadOptions();
Random rand = new Random();
boolean boolValue = rand.nextBoolean(); boolean boolValue = rand.nextBoolean();
opt.setVerifyChecksums(boolValue); opt.setVerifyChecksums(boolValue);
assert(opt.verifyChecksums() == boolValue); assertThat(opt.verifyChecksums()).isEqualTo(boolValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
}
{ // FillCache test @Test
public void fillCache(){
ReadOptions opt = null;
try {
opt = new ReadOptions();
Random rand = new Random();
boolean boolValue = rand.nextBoolean(); boolean boolValue = rand.nextBoolean();
opt.setFillCache(boolValue); opt.setFillCache(boolValue);
assert(opt.fillCache() == boolValue); assertThat(opt.fillCache()).isEqualTo(boolValue);
} finally {
if (opt != null) {
opt.dispose();
}
} }
}
{ // Tailing test @Test
public void tailing(){
ReadOptions opt = null;
try {
opt = new ReadOptions();
Random rand = new Random();
boolean boolValue = rand.nextBoolean(); boolean boolValue = rand.nextBoolean();
opt.setTailing(boolValue); opt.setTailing(boolValue);
assert(opt.tailing() == boolValue); assertThat(opt.tailing()).isEqualTo(boolValue);
} finally {
if (opt != null) {
opt.dispose();
}
}
}
@Test
public void snapshot(){
ReadOptions opt = null;
try {
opt = new ReadOptions();
opt.setSnapshot(null);
assertThat(opt.snapshot()).isNull();
} finally {
if (opt != null) {
opt.dispose();
}
} }
}
@Test
public void failSetVerifyChecksumUninitialized(){
ReadOptions readOptions = setupUninitializedReadOptions(
exception);
readOptions.setVerifyChecksums(true);
}
@Test
public void failVerifyChecksumUninitialized(){
ReadOptions readOptions = setupUninitializedReadOptions(
exception);
readOptions.verifyChecksums();
}
@Test
public void failSetFillCacheUninitialized(){
ReadOptions readOptions = setupUninitializedReadOptions(
exception);
readOptions.setFillCache(true);
}
@Test
public void failFillCacheUninitialized(){
ReadOptions readOptions = setupUninitializedReadOptions(
exception);
readOptions.fillCache();
}
@Test
public void failSetTailingUninitialized(){
ReadOptions readOptions = setupUninitializedReadOptions(
exception);
readOptions.setTailing(true);
}
@Test
public void failTailingUninitialized(){
ReadOptions readOptions = setupUninitializedReadOptions(
exception);
readOptions.tailing();
}
@Test
public void failSetSnapshotUninitialized(){
ReadOptions readOptions = setupUninitializedReadOptions(
exception);
readOptions.setSnapshot(null);
}
@Test
public void failSnapshotUninitialized(){
ReadOptions readOptions = setupUninitializedReadOptions(
exception);
readOptions.snapshot();
}
opt.dispose(); private ReadOptions setupUninitializedReadOptions(
System.out.println("Passed ReadOptionsTest"); ExpectedException exception) {
ReadOptions readOptions = new ReadOptions();
readOptions.dispose();
exception.expect(AssertionError.class);
return readOptions;
} }
} }

@ -0,0 +1,282 @@
// Copyright (c) 2014, Facebook, Inc. All rights reserved.
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree. An additional grant
// of patent rights can be found in the PATENTS file in the same directory.
package org.rocksdb.test;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.rocksdb.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
public class RocksDBTest {
@ClassRule
public static final RocksMemoryResource rocksMemoryResource =
new RocksMemoryResource();
@Rule
public TemporaryFolder dbFolder = new TemporaryFolder();
@Test
public void open() throws RocksDBException {
RocksDB db = null;
Options opt = null;
try {
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 put() throws RocksDBException {
RocksDB db = null;
WriteOptions opt = null;
try {
db = RocksDB.open(dbFolder.getRoot().getAbsolutePath());
db.put("key1".getBytes(), "value".getBytes());
opt = new WriteOptions();
db.put(opt, "key2".getBytes(), "12345678".getBytes());
assertThat(db.get("key1".getBytes())).isEqualTo(
"value".getBytes());
assertThat(db.get("key2".getBytes())).isEqualTo(
"12345678".getBytes());
} finally {
if (db != null) {
db.close();
}
if (opt != null) {
opt.dispose();
}
}
}
@Test
public void write() throws RocksDBException {
RocksDB db = null;
Options options = null;
WriteBatch wb1 = null;
WriteBatch wb2 = null;
WriteOptions opts = null;
try {
options = new Options().
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.merge("key1".getBytes(), "bb".getBytes());
wb2 = new WriteBatch();
wb2.put("key2".getBytes(), "xx".getBytes());
wb2.merge("key2".getBytes(), "yy".getBytes());
db.write(opts, wb1);
db.write(opts, wb2);
assertThat(db.get("key1".getBytes())).isEqualTo(
"aa,bb".getBytes());
assertThat(db.get("key2".getBytes())).isEqualTo(
"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
public void getWithOutValue() throws RocksDBException {
RocksDB db = null;
try {
db = RocksDB.open(dbFolder.getRoot().getAbsolutePath());
db.put("key1".getBytes(), "value".getBytes());
db.put("key2".getBytes(), "12345678".getBytes());
byte[] outValue = new byte[5];
// not found value
int getResult = db.get("keyNotFound".getBytes(), outValue);
assertThat(getResult).isEqualTo(RocksDB.NOT_FOUND);
// found value which fits in outValue
getResult = db.get("key1".getBytes(), outValue);
assertThat(getResult).isNotEqualTo(RocksDB.NOT_FOUND);
assertThat(outValue).isEqualTo("value".getBytes());
// found value which fits partially
getResult = db.get("key2".getBytes(), outValue);
assertThat(getResult).isNotEqualTo(RocksDB.NOT_FOUND);
assertThat(outValue).isEqualTo("12345".getBytes());
} finally {
if (db != null) {
db.close();
}
}
}
@Test
public void getWithOutValueReadOptions() throws RocksDBException {
RocksDB db = null;
ReadOptions rOpt = null;
try {
db = RocksDB.open(dbFolder.getRoot().getAbsolutePath());
rOpt = new ReadOptions();
db.put("key1".getBytes(), "value".getBytes());
db.put("key2".getBytes(), "12345678".getBytes());
byte[] outValue = new byte[5];
// not found value
int getResult = db.get(rOpt, "keyNotFound".getBytes(),
outValue);
assertThat(getResult).isEqualTo(RocksDB.NOT_FOUND);
// found value which fits in outValue
getResult = db.get(rOpt, "key1".getBytes(), outValue);
assertThat(getResult).isNotEqualTo(RocksDB.NOT_FOUND);
assertThat(outValue).isEqualTo("value".getBytes());
// found value which fits partially
getResult = db.get(rOpt, "key2".getBytes(), outValue);
assertThat(getResult).isNotEqualTo(RocksDB.NOT_FOUND);
assertThat(outValue).isEqualTo("12345".getBytes());
} finally {
if (db != null) {
db.close();
}
if (rOpt != null) {
rOpt.dispose();
}
}
}
@Test
public void multiGet() throws RocksDBException {
RocksDB db = null;
ReadOptions rOpt = null;
try {
db = RocksDB.open(dbFolder.getRoot().getAbsolutePath());
rOpt = new ReadOptions();
db.put("key1".getBytes(), "value".getBytes());
db.put("key2".getBytes(), "12345678".getBytes());
List<byte[]> lookupKeys = new ArrayList<byte[]>() {{
add("key1".getBytes());
add("key2".getBytes());
}};
Map<byte[], byte[]> results = db.multiGet(lookupKeys);
assertThat(results).isNotNull();
assertThat(results.values()).isNotNull();
assertThat(results.values()).
contains("value".getBytes(), "12345678".getBytes());
// test same method with ReadOptions
results = db.multiGet(rOpt, lookupKeys);
assertThat(results).isNotNull();
assertThat(results.values()).isNotNull();
assertThat(results.values()).
contains("value".getBytes(), "12345678".getBytes());
// remove existing key
lookupKeys.remove("key2".getBytes());
// add non existing key
lookupKeys.add("key3".getBytes());
results = db.multiGet(lookupKeys);
assertThat(results).isNotNull();
assertThat(results.values()).isNotNull();
assertThat(results.values()).
contains("value".getBytes());
// test same call with readOptions
results = db.multiGet(rOpt, lookupKeys);
assertThat(results).isNotNull();
assertThat(results.values()).isNotNull();
assertThat(results.values()).
contains("value".getBytes());
} finally {
if (db != null) {
db.close();
}
if (rOpt != null) {
rOpt.dispose();
}
}
}
@Test
public void merge() throws RocksDBException {
RocksDB db = null;
Options opt = null;
WriteOptions wOpt;
try {
opt = new Options().
setCreateIfMissing(true).
setMergeOperator(new StringAppendOperator());
wOpt = new WriteOptions();
db = RocksDB.open(opt, dbFolder.getRoot().getAbsolutePath());
db.put("key1".getBytes(), "value".getBytes());
assertThat(db.get("key1".getBytes())).isEqualTo(
"value".getBytes());
// merge key1 with another value portion
db.merge("key1".getBytes(), "value2".getBytes());
assertThat(db.get("key1".getBytes())).isEqualTo(
"value,value2".getBytes());
// merge key1 with another value portion
db.merge(wOpt, "key1".getBytes(), "value3".getBytes());
assertThat(db.get("key1".getBytes())).isEqualTo(
"value,value2,value3".getBytes());
// merge on non existent key shall insert the value
db.merge(wOpt, "key2".getBytes(), "xxxx".getBytes());
assertThat(db.get("key2".getBytes())).isEqualTo(
"xxxx".getBytes());
} finally {
if (db != null) {
db.close();
}
if (opt != null) {
opt.dispose();
}
}
}
@Test
public void remove() throws RocksDBException {
RocksDB db = null;
WriteOptions wOpt;
try {
wOpt = new WriteOptions();
db = RocksDB.open(dbFolder.getRoot().getAbsolutePath());
db.put("key1".getBytes(), "value".getBytes());
db.put("key2".getBytes(), "12345678".getBytes());
assertThat(db.get("key1".getBytes())).isEqualTo(
"value".getBytes());
assertThat(db.get("key2".getBytes())).isEqualTo(
"12345678".getBytes());
db.remove("key1".getBytes());
db.remove(wOpt, "key2".getBytes());
assertThat(db.get("key1".getBytes())).isNull();
assertThat(db.get("key2".getBytes())).isNull();
} finally {
if (db != null) {
db.close();
}
}
}
}

@ -0,0 +1,39 @@
// Copyright (c) 2014, Facebook, Inc. All rights reserved.
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree. An additional grant
// of patent rights can be found in the PATENTS file in the same directory.
package org.rocksdb.test;
import org.junit.ClassRule;
import org.junit.Test;
import org.rocksdb.RocksEnv;
import static org.assertj.core.api.Assertions.assertThat;
public class RocksEnvTest {
@ClassRule
public static final RocksMemoryResource rocksMemoryResource =
new RocksMemoryResource();
@Test
public void rocksEnv(){
RocksEnv rocksEnv = RocksEnv.getDefault();
rocksEnv.setBackgroundThreads(5);
// default rocksenv will always return zero for flush pool
// no matter what was set via setBackgroundThreads
assertThat(rocksEnv.getThreadPoolQueueLen(RocksEnv.FLUSH_POOL)).
isEqualTo(0);
rocksEnv.setBackgroundThreads(5, RocksEnv.FLUSH_POOL);
// default rocksenv will always return zero for flush pool
// no matter what was set via setBackgroundThreads
assertThat(rocksEnv.getThreadPoolQueueLen(RocksEnv.FLUSH_POOL)).
isEqualTo(0);
rocksEnv.setBackgroundThreads(5, RocksEnv.COMPACTION_POOL);
// default rocksenv will always return zero for compaction pool
// no matter what was set via setBackgroundThreads
assertThat(rocksEnv.getThreadPoolQueueLen(RocksEnv.COMPACTION_POOL)).
isEqualTo(0);
}
}

@ -4,45 +4,105 @@
// of patent rights can be found in the PATENTS file in the same directory. // of patent rights can be found in the PATENTS file in the same directory.
package org.rocksdb.test; package org.rocksdb.test;
import org.rocksdb.ColumnFamilyHandle; import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.rocksdb.Options; import org.rocksdb.Options;
import org.rocksdb.RocksDB; import org.rocksdb.RocksDB;
import org.rocksdb.RocksDBException; import org.rocksdb.RocksDBException;
import org.rocksdb.RocksIterator; import org.rocksdb.RocksIterator;
import java.util.ArrayList; import static org.assertj.core.api.Assertions.assertThat;
import java.util.List;
public class RocksIteratorTest { public class RocksIteratorTest {
static final String DB_PATH = "/tmp/rocksdbjni_iterator_test";
static { @ClassRule
RocksDB.loadLibrary(); public static final RocksMemoryResource rocksMemoryResource =
new RocksMemoryResource();
@Rule
public TemporaryFolder dbFolder = new TemporaryFolder();
@Test
public void rocksIterator() throws RocksDBException {
RocksDB db = null;
Options options = null;
RocksIterator iterator = null;
try {
options = new Options();
options.setCreateIfMissing(true)
.setCreateMissingColumnFamilies(true);
db = RocksDB.open(options,
dbFolder.getRoot().getAbsolutePath());
db.put("key1".getBytes(), "value1".getBytes());
db.put("key2".getBytes(), "value2".getBytes());
iterator = db.newIterator();
iterator.seekToFirst();
assertThat(iterator.isValid()).isTrue();
assertThat(iterator.key()).isEqualTo("key1".getBytes());
assertThat(iterator.value()).isEqualTo("value1".getBytes());
iterator.next();
assertThat(iterator.isValid()).isTrue();
assertThat(iterator.key()).isEqualTo("key2".getBytes());
assertThat(iterator.value()).isEqualTo("value2".getBytes());
iterator.next();
assertThat(iterator.isValid()).isFalse();
iterator.seekToLast();
iterator.prev();
assertThat(iterator.isValid()).isTrue();
assertThat(iterator.key()).isEqualTo("key1".getBytes());
assertThat(iterator.value()).isEqualTo("value1".getBytes());
iterator.seekToFirst();
iterator.seekToLast();
assertThat(iterator.isValid()).isTrue();
assertThat(iterator.key()).isEqualTo("key2".getBytes());
assertThat(iterator.value()).isEqualTo("value2".getBytes());
iterator.status();
} finally {
if (db != null) {
db.close();
}
if (options != null) {
options.dispose();
}
if (iterator != null) {
iterator.dispose();
}
}
} }
public static void main(String[] args){ @Test
RocksDB db; public void rocksIteratorGc()
Options options = new Options(); throws RocksDBException {
options.setCreateIfMissing(true) RocksDB db = null;
.setCreateMissingColumnFamilies(true); Options options = null;
try { try {
db = RocksDB.open(options, DB_PATH); options = new Options();
options.setCreateIfMissing(true)
.setCreateMissingColumnFamilies(true);
db = RocksDB.open(options,
dbFolder.getRoot().getAbsolutePath());
db.put("key".getBytes(), "value".getBytes()); db.put("key".getBytes(), "value".getBytes());
RocksIterator iter = db.newIterator(); db.newIterator();
RocksIterator iter2 = db.newIterator(); db.newIterator();
RocksIterator iter3 = db.newIterator(); RocksIterator iter3 = db.newIterator();
iter = null;
db.close(); db.close();
db = null; db = null;
iter2 = null;
System.gc(); System.gc();
System.runFinalization(); System.runFinalization();
System.out.println("Passed RocksIterator Test");
iter3.dispose(); iter3.dispose();
System.gc(); System.gc();
System.runFinalization(); System.runFinalization();
}catch (RocksDBException e){ } finally {
e.printStackTrace(); if (db != null) {
assert(false); db.close();
}
if (options != null) {
options.dispose();
}
} }
} }
} }

@ -0,0 +1,65 @@
// Copyright (c) 2014, Facebook, Inc. All rights reserved.
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree. An additional grant
// of patent rights can be found in the PATENTS file in the same directory.
package org.rocksdb.test;
import org.junit.internal.JUnitSystem;
import org.junit.internal.RealSystem;
import org.junit.internal.TextListener;
import org.junit.runner.Description;
import org.junit.runner.JUnitCore;
import java.util.ArrayList;
import java.util.List;
/**
* Custom Junit Runner to print also Test classes
* and executed methods to command prompt.
*/
public class RocksJunitRunner {
/**
* Listener which overrides default functionality
* to print class and method to system out.
*/
static class RocksJunitListener extends TextListener {
/**
* RocksJunitListener constructor
*
* @param system JUnitSystem
*/
public RocksJunitListener(JUnitSystem system) {
super(system);
}
@Override
public void testStarted(Description description) {
System.out.format("Run: %s testing now -> %s \n",
description.getClassName(),
description.getMethodName());
}
}
/**
* Main method to execute tests
*
* @param args Test classes as String names
*/
public static void main(String[] args){
JUnitCore runner = new JUnitCore();
final JUnitSystem system = new RealSystem();
runner.addListener(new RocksJunitListener(system));
try {
List<Class<?>> classes = new ArrayList<>();
for (String arg : args) {
classes.add(Class.forName(arg));
}
runner.run(classes.toArray(new Class[1]));
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}

@ -0,0 +1,21 @@
package org.rocksdb.test;
import org.junit.rules.ExternalResource;
import org.rocksdb.RocksDB;
/**
* Resource to trigger garbage collection after each test
* run.
*/
public class RocksMemoryResource extends ExternalResource {
static {
RocksDB.loadLibrary();
}
@Override
protected void after() {
System.gc();
System.runFinalization();
}
}

@ -0,0 +1,28 @@
// Copyright (c) 2014, Facebook, Inc. All rights reserved.
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree. An additional grant
// of patent rights can be found in the PATENTS file in the same directory.
package org.rocksdb.test;
import org.junit.Test;
import org.rocksdb.util.SizeUnit;
import static org.assertj.core.api.Assertions.assertThat;
public class SizeUnitTest {
public static final long COMPUTATION_UNIT = 1024L;
@Test
public void sizeUnit() {
assertThat(SizeUnit.KB).isEqualTo(COMPUTATION_UNIT);
assertThat(SizeUnit.MB).isEqualTo(
SizeUnit.KB * COMPUTATION_UNIT);
assertThat(SizeUnit.GB).isEqualTo(
SizeUnit.MB * COMPUTATION_UNIT);
assertThat(SizeUnit.TB).isEqualTo(
SizeUnit.GB * COMPUTATION_UNIT);
assertThat(SizeUnit.PB).isEqualTo(
SizeUnit.TB * COMPUTATION_UNIT);
}
}

@ -4,84 +4,94 @@
// of patent rights can be found in the PATENTS file in the same directory. // of patent rights can be found in the PATENTS file in the same directory.
package org.rocksdb.test; package org.rocksdb.test;
import java.util.ArrayList; import org.junit.ClassRule;
import java.util.List; import org.junit.Rule;
import org.junit.Test;
import org.rocksdb.ColumnFamilyHandle; import org.junit.rules.TemporaryFolder;
import org.rocksdb.Options; import org.rocksdb.Options;
import org.rocksdb.ReadOptions; import org.rocksdb.ReadOptions;
import org.rocksdb.RocksDB; import org.rocksdb.RocksDB;
import org.rocksdb.RocksDBException; import org.rocksdb.RocksDBException;
import org.rocksdb.Snapshot; import org.rocksdb.Snapshot;
import org.rocksdb.WriteBatch;
import org.rocksdb.WriteOptions;
import static org.assertj.core.api.Assertions.assertThat;
public class SnapshotTest public class SnapshotTest {
{
static final String DB_PATH = "/tmp/rocksdbjni_snapshot_test"; @ClassRule
static { public static final RocksMemoryResource rocksMemoryResource =
RocksDB.loadLibrary(); new RocksMemoryResource();
}
public static void main(String[] args){ @Rule
public TemporaryFolder dbFolder = new TemporaryFolder();
@Test
public void snapshots() throws RocksDBException {
RocksDB db = null; RocksDB db = null;
Options options = new Options(); Options options = null;
options.setCreateIfMissing(true); ReadOptions readOptions = null;
try { try {
db = RocksDB.open(options, DB_PATH);
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(); Snapshot snapshot = db.getSnapshot();
ReadOptions readOptions = new 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
assert(new String(db.get("key".getBytes())) assertThat(new String(db.get("key".getBytes()))).
.equals("value")); isEqualTo("value");
// retrieve key value pair created before // retrieve key value pair created before
// the snapshot was made // the snapshot was made
assert(new String(db.get(readOptions, assertThat(new String(db.get(readOptions,
"key".getBytes())).equals("value")); "key".getBytes()))).isEqualTo("value");
// add new key/value pair // add new key/value pair
db.put("newkey".getBytes(), "newvalue".getBytes()); db.put("newkey".getBytes(), "newvalue".getBytes());
// using no snapshot the latest db entries // using no snapshot the latest db entries
// will be taken into account // will be taken into account
assert(new String(db.get("newkey".getBytes())) assertThat(new String(db.get("newkey".getBytes()))).
.equals("newvalue")); isEqualTo("newvalue");
// snapshopot was created before newkey // snapshopot was created before newkey
assert(db.get(readOptions, "newkey".getBytes()) assertThat(db.get(readOptions, "newkey".getBytes())).
== null); isNull();
// Retrieve snapshot from read options // Retrieve snapshot from read options
Snapshot sameSnapshot = readOptions.snapshot(); 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
assert(new String(db.get(readOptions, assertThat(new String(db.get(readOptions,
"key".getBytes())).equals("value")); "key".getBytes()))).isEqualTo("value");
// update key value pair to newvalue // update key value pair to newvalue
db.put("key".getBytes(), "newvalue".getBytes()); db.put("key".getBytes(), "newvalue".getBytes());
// read with previously created snapshot will // read with previously created snapshot will
// read previous version of key value pair // read previous version of key value pair
assert(new String(db.get(readOptions, assertThat(new String(db.get(readOptions,
"key".getBytes())).equals("value")); "key".getBytes()))).isEqualTo("value");
// read for newkey using the snapshot must be // read for newkey using the snapshot must be
// null // null
assert(db.get(readOptions, "newkey".getBytes()) assertThat(db.get(readOptions, "newkey".getBytes())).
== null); isNull();
// setting null to snapshot in ReadOptions leads // setting null to snapshot in ReadOptions leads
// to no Snapshot being used. // to no Snapshot being used.
readOptions.setSnapshot(null); readOptions.setSnapshot(null);
assert(new String(db.get(readOptions, assertThat(new String(db.get(readOptions,
"newkey".getBytes())).equals("newvalue")); "newkey".getBytes()))).isEqualTo("newvalue");
// release Snapshot // release Snapshot
db.releaseSnapshot(snapshot); db.releaseSnapshot(snapshot);
// Close database } finally {
db.close(); if (db != null) {
}catch (RocksDBException e){ db.close();
e.printStackTrace(); }
assert(false); if (options != null) {
options.dispose();
}
if (readOptions != null) {
readOptions.dispose();
}
} }
System.out.println("Passed SnapshotTest");
} }
} }

@ -6,38 +6,56 @@
package org.rocksdb.test; package org.rocksdb.test;
import java.util.Collections; import java.util.Collections;
import org.rocksdb.*;
public class StatisticsCollectorTest {
static final String db_path = "/tmp/rocksdbjni_statistics_collector_test";
static {
RocksDB.loadLibrary();
}
public static void main(String[] args)
throws InterruptedException, RocksDBException {
Options opt = new Options().createStatistics().setCreateIfMissing(true);
Statistics stats = opt.statisticsPtr();
RocksDB db = RocksDB.open(opt, db_path); import org.junit.ClassRule;
import org.junit.Rule;
StatsCallbackMock callback = new StatsCallbackMock(); import org.junit.Test;
StatsCollectorInput statsInput = new StatsCollectorInput(stats, callback); import org.junit.rules.TemporaryFolder;
import org.rocksdb.*;
StatisticsCollector statsCollector = new StatisticsCollector(
Collections.singletonList(statsInput), 100);
statsCollector.start();
Thread.sleep(1000); import static org.assertj.core.api.Assertions.assertThat;
assert(callback.tickerCallbackCount > 0); public class StatisticsCollectorTest {
assert(callback.histCallbackCount > 0);
statsCollector.shutDown(1000); @ClassRule
public static final RocksMemoryResource rocksMemoryResource =
new RocksMemoryResource();
db.close(); @Rule
opt.dispose(); public TemporaryFolder dbFolder = new TemporaryFolder();
System.out.println("Stats collector test passed.!"); @Test
public void statisticsCollector()
throws InterruptedException, RocksDBException {
Options opt = null;
RocksDB db = null;
try {
opt = new Options().createStatistics().setCreateIfMissing(true);
Statistics stats = opt.statisticsPtr();
db = RocksDB.open(opt,
dbFolder.getRoot().getAbsolutePath());
StatsCallbackMock callback = new StatsCallbackMock();
StatsCollectorInput statsInput = new StatsCollectorInput(stats, callback);
StatisticsCollector statsCollector = new StatisticsCollector(
Collections.singletonList(statsInput), 100);
statsCollector.start();
Thread.sleep(1000);
assertThat(callback.tickerCallbackCount).isGreaterThan(0);
assertThat(callback.histCallbackCount).isGreaterThan(0);
statsCollector.shutDown(1000);
} finally {
if (db != null) {
db.close();
}
if (opt != null) {
opt.dispose();
}
}
} }
} }

@ -13,13 +13,20 @@ import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
import org.junit.ClassRule;
import org.junit.Test;
import org.rocksdb.WriteOptions;
import static org.assertj.core.api.Assertions.assertThat;
public class WriteBatchHandlerTest { public class WriteBatchHandlerTest {
static { @ClassRule
RocksDB.loadLibrary(); public static final RocksMemoryResource rocksMemoryResource =
} new RocksMemoryResource();
public static void main(final String[] args) throws IOException, RocksDBException { @Test
public void writeBatchHandler() throws IOException, RocksDBException {
// setup test data // setup test data
final List<Tuple<Action, Tuple<byte[], byte[]>>> testEvents = new ArrayList<>(); final List<Tuple<Action, Tuple<byte[], byte[]>>> testEvents = new ArrayList<>();
@ -68,10 +75,10 @@ public class WriteBatchHandlerTest {
// 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();
assert(testEvents.size() == actualEvents.size()); assertThat(testEvents.size()).isSameAs(actualEvents.size());
for(int i = 0; i < testEvents.size(); i++) { for(int i = 0; i < testEvents.size(); i++) {
assert(equals(testEvents.get(i), actualEvents.get(i))); assertThat(equals(testEvents.get(i), actualEvents.get(i))).isTrue();
} }
System.out.println("Passed WriteBatchHandler Test"); System.out.println("Passed WriteBatchHandler Test");

@ -0,0 +1,124 @@
// Copyright (c) 2014, Facebook, Inc. All rights reserved.
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree. An additional grant
// of patent rights can be found in the PATENTS file in the same directory.
//
// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.
package org.rocksdb.test;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.rocksdb.WriteBatch;
import java.io.UnsupportedEncodingException;
import static org.assertj.core.api.Assertions.assertThat;
/**
* This class mimics the db/write_batch_test.cc
* in the c++ rocksdb library.
*
* Not ported yet:
*
* Continue();
* PutGatherSlices();
*/
public class WriteBatchTest {
@ClassRule
public static final RocksMemoryResource rocksMemoryResource =
new RocksMemoryResource();
@Rule
public TemporaryFolder dbFolder = new TemporaryFolder();
@Test
public void emptyWriteBatch() {
WriteBatch batch = new WriteBatch();
assertThat(batch.count()).isEqualTo(0);
}
@Test
public void multipleBatchOperations()
throws UnsupportedEncodingException {
WriteBatch batch = new WriteBatch();
batch.put("foo".getBytes("US-ASCII"), "bar".getBytes("US-ASCII"));
batch.remove("box".getBytes("US-ASCII"));
batch.put("baz".getBytes("US-ASCII"), "boo".getBytes("US-ASCII"));
WriteBatchInternal.setSequence(batch, 100);
assertThat(WriteBatchInternal.sequence(batch)).
isNotNull().
isEqualTo(100);
assertThat(batch.count()).isEqualTo(3);
assertThat(new String(getContents(batch), "US-ASCII")).
isEqualTo("Put(baz, boo)@102" +
"Delete(box)@101" +
"Put(foo, bar)@100");
}
@Test
public void testAppendOperation()
throws UnsupportedEncodingException {
WriteBatch b1 = new WriteBatch();
WriteBatch b2 = new WriteBatch();
WriteBatchInternal.setSequence(b1, 200);
WriteBatchInternal.setSequence(b2, 300);
WriteBatchInternal.append(b1, b2);
assertThat(getContents(b1).length).isEqualTo(0);
assertThat(b1.count()).isEqualTo(0);
b2.put("a".getBytes("US-ASCII"), "va".getBytes("US-ASCII"));
WriteBatchInternal.append(b1, b2);
assertThat("Put(a, va)@200".equals(new String(getContents(b1), "US-ASCII")));
assertThat(b1.count()).isEqualTo(1);
b2.clear();
b2.put("b".getBytes("US-ASCII"), "vb".getBytes("US-ASCII"));
WriteBatchInternal.append(b1, b2);
assertThat(("Put(a, va)@200" +
"Put(b, vb)@201")
.equals(new String(getContents(b1), "US-ASCII")));
assertThat(b1.count()).isEqualTo(2);
b2.remove("foo".getBytes("US-ASCII"));
WriteBatchInternal.append(b1, b2);
assertThat(("Put(a, va)@200" +
"Put(b, vb)@202" +
"Put(b, vb)@201" +
"Delete(foo)@203")
.equals(new String(getContents(b1), "US-ASCII")));
assertThat(b1.count()).isEqualTo(4);
}
@Test
public void blobOperation()
throws UnsupportedEncodingException {
WriteBatch batch = new WriteBatch();
batch.put("k1".getBytes("US-ASCII"), "v1".getBytes("US-ASCII"));
batch.put("k2".getBytes("US-ASCII"), "v2".getBytes("US-ASCII"));
batch.put("k3".getBytes("US-ASCII"), "v3".getBytes("US-ASCII"));
batch.putLogData("blob1".getBytes("US-ASCII"));
batch.remove("k2".getBytes("US-ASCII"));
batch.putLogData("blob2".getBytes("US-ASCII"));
batch.merge("foo".getBytes("US-ASCII"), "bar".getBytes("US-ASCII"));
assertThat(batch.count()).isEqualTo(5);
assertThat(("Merge(foo, bar)@4" +
"Put(k1, v1)@0" +
"Delete(k2)@3" +
"Put(k2, v2)@1" +
"Put(k3, v3)@2")
.equals(new String(getContents(batch), "US-ASCII")));
}
static native byte[] getContents(WriteBatch batch);
}
/**
* Package-private class which provides java api to access
* c++ WriteBatchInternal.
*/
class WriteBatchInternal {
static native void setSequence(WriteBatch batch, long sn);
static native long sequence(WriteBatch batch);
static native void append(WriteBatch b1, WriteBatch b2);
}

@ -0,0 +1,32 @@
// Copyright (c) 2014, Facebook, Inc. All rights reserved.
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree. An additional grant
// of patent rights can be found in the PATENTS file in the same directory.
package org.rocksdb.test;
import org.junit.ClassRule;
import org.junit.Test;
import org.rocksdb.WriteOptions;
import static org.assertj.core.api.Assertions.assertThat;
public class WriteOptionsTest {
@ClassRule
public static final RocksMemoryResource rocksMemoryResource =
new RocksMemoryResource();
@Test
public void writeOptions(){
WriteOptions writeOptions = new WriteOptions();
writeOptions.setDisableWAL(true);
assertThat(writeOptions.disableWAL()).isTrue();
writeOptions.setDisableWAL(false);
assertThat(writeOptions.disableWAL()).isFalse();
writeOptions.setSync(true);
assertThat(writeOptions.sync()).isTrue();
writeOptions.setSync(false);
assertThat(writeOptions.sync()).isFalse();
}
}

@ -1,34 +1,165 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0" <project
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
<modelVersion>4.0.0</modelVersion> xmlns="http://maven.apache.org/POM/4.0.0"
<name>RocksDB JNI</name> xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<url>http://rocksdb.org/</url> <modelVersion>4.0.0</modelVersion>
<groupId>org.rocksdb</groupId> <name>RocksDB JNI</name>
<artifactId>rocksdbjni</artifactId> <url>http://rocksdb.org/</url>
<version>3.6.0</version> <groupId>org.rocksdb</groupId>
<description>RocksDB fat jar that contains .so files for linux32 and linux64, and jnilib files for Mac OSX.</description> <artifactId>rocksdbjni</artifactId>
<licenses> <version>3.6.0</version>
<license> <description>RocksDB fat jar that contains .so files for linux32 and linux64, and jnilib files
<name>Apache License 2.0</name> for Mac OSX.
<url>http://www.apache.org/licenses/LICENSE-2.0.html</url> </description>
<distribution>repo</distribution> <licenses>
</license> <license>
</licenses> <name>Apache License 2.0</name>
<scm> <url>http://www.apache.org/licenses/LICENSE-2.0.html</url>
<connection>scm:git:git://github.com/dropwizard/metrics.git</connection> <distribution>repo</distribution>
<developerConnection>scm:git:git@github.com:dropwizard/metrics.git</developerConnection> </license>
<url>http://github.com/dropwizard/metrics/</url> </licenses>
<tag>HEAD</tag> <scm>
</scm> <connection>scm:git:git://github.com/dropwizard/metrics.git</connection>
<developers> <developerConnection>scm:git:git@github.com:dropwizard/metrics.git</developerConnection>
<developer> <url>http://github.com/dropwizard/metrics/</url>
<name>Facebook</name> <tag>HEAD</tag>
<email>help@facebook.com</email> </scm>
<timezone>America/New_York</timezone> <developers>
<roles> <developer>
<role>architect</role> <name>Facebook</name>
</roles> <email>help@facebook.com</email>
</developer> <timezone>America/New_York</timezone>
</developers> <roles>
<role>architect</role>
</roles>
</developer>
</developers>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<build>
<!-- Use custom maven folder layout -->
<!-- Set folder for src root -->
<sourceDirectory>${project.basedir}</sourceDirectory>
<!-- main resources, nothing shall be excluded -->
<resources>
<resource>
<directory>${project.basedir}</directory>
<excludes>
<exclude>**/*</exclude>
</excludes>
</resource>
</resources>
<!-- Set folder for test root -->
<testSourceDirectory>${project.basedir}</testSourceDirectory>
<!-- Bring libraries on classpath -->
<testResources>
<testResource>
<directory>${project.basedir}</directory>
<includes>
<include>*.so</include>
<include>*.jar</include>
<include>*.jnilib</include>
</includes>
</testResource>
</testResources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.0.2</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
<!-- Exclude all tests from classes -->
<excludes>
<!-- Exclude Sample -->
<exclude>*.java</exclude>
<!-- Exclude Benchmark -->
<exclude>org/rocksdb/benchmark/*.java</exclude>
<!-- Exclude Tests -->
<exclude>org/rocksdb/test/*.java</exclude>
<exclude>org/rocksdb/WriteBatchTest.java</exclude>
</excludes>
</configuration>
<executions>
<execution>
<id>default-testCompile</id>
<phase>test-compile</phase>
<configuration>
<!-- Include only tests in test-classes -->
<testExcludes>
<!-- Exclude everything but WriteBatchTest -->
<exclude>%regex[org/rocksdb/[^WriteBatchTest].*java]</exclude>
<!-- Exclude WriteBatchTest -->
<exclude>*.java</exclude>
<!-- Exclude Benchmark -->
<exclude>org/rocksdb/benchmark/*.java</exclude>
<!-- Exclude Utilities -->
<exclude>org/rocksdb/util/*.java</exclude>
</testExcludes>
<testIncludes>
<!-- Include Tests -->
<include>org/rocksdb/test/*.java</include>
</testIncludes>
</configuration>
<goals>
<goal>testCompile</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.17</version>
<configuration>
<argLine>${argLine}</argLine>
</configuration>
</plugin>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.7.2.201409121644</version>
<executions>
<execution>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
<execution>
<id>report</id>
<phase>prepare-package</phase>
<goals>
<goal>report</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12-beta-2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>1.7.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>1.9.5</version>
<scope>test</scope>
</dependency>
</dependencies>
</project> </project>

@ -124,7 +124,7 @@ void Java_org_rocksdb_BackupableDBOptions_newBackupableDBOptions(
* Signature: (J)Ljava/lang/String; * Signature: (J)Ljava/lang/String;
*/ */
jstring Java_org_rocksdb_BackupableDBOptions_backupDir( jstring Java_org_rocksdb_BackupableDBOptions_backupDir(
JNIEnv* env, jobject jopt, jlong jhandle, jstring jpath) { JNIEnv* env, jobject jopt, jlong jhandle) {
auto bopt = reinterpret_cast<rocksdb::BackupableDBOptions*>(jhandle); auto bopt = reinterpret_cast<rocksdb::BackupableDBOptions*>(jhandle);
return env->NewStringUTF(bopt->backup_dir.c_str()); return env->NewStringUTF(bopt->backup_dir.c_str());
} }

@ -274,6 +274,17 @@ void Java_org_rocksdb_Options_setParanoidChecks(
static_cast<bool>(paranoid_checks); static_cast<bool>(paranoid_checks);
} }
/*
* Class: org_rocksdb_Options
* Method: setEnv
* Signature: (JJ)V
*/
void Java_org_rocksdb_Options_setEnv(
JNIEnv* env, jobject jobj, jlong jhandle, jlong jenv) {
reinterpret_cast<rocksdb::Options*>(jhandle)->env =
reinterpret_cast<rocksdb::Env*>(jenv);
}
/* /*
* Class: org_rocksdb_Options * Class: org_rocksdb_Options
* Method: setMaxTotalWalSize * Method: setMaxTotalWalSize

@ -9,8 +9,8 @@
#include "include/org_rocksdb_WriteBatch.h" #include "include/org_rocksdb_WriteBatch.h"
#include "include/org_rocksdb_WriteBatch_Handler.h" #include "include/org_rocksdb_WriteBatch_Handler.h"
#include "include/org_rocksdb_WriteBatchInternal.h" #include "include/org_rocksdb_test_WriteBatchInternal.h"
#include "include/org_rocksdb_WriteBatchTest.h" #include "include/org_rocksdb_test_WriteBatchTest.h"
#include "rocksjni/portal.h" #include "rocksjni/portal.h"
#include "rocksjni/writebatchhandlerjnicallback.h" #include "rocksjni/writebatchhandlerjnicallback.h"
#include "rocksdb/db.h" #include "rocksdb/db.h"
@ -257,11 +257,11 @@ void Java_org_rocksdb_WriteBatch_disposeInternal(
} }
/* /*
* Class: org_rocksdb_WriteBatchInternal * Class: org_rocksdb_test_WriteBatchInternal
* Method: setSequence * Method: setSequence
* Signature: (Lorg/rocksdb/WriteBatch;J)V * Signature: (Lorg/rocksdb/WriteBatch;J)V
*/ */
void Java_org_rocksdb_WriteBatchInternal_setSequence( void Java_org_rocksdb_test_WriteBatchInternal_setSequence(
JNIEnv* env, jclass jclazz, jobject jobj, jlong jsn) { JNIEnv* env, jclass jclazz, jobject jobj, jlong jsn) {
rocksdb::WriteBatch* wb = rocksdb::WriteBatchJni::getHandle(env, jobj); rocksdb::WriteBatch* wb = rocksdb::WriteBatchJni::getHandle(env, jobj);
assert(wb != nullptr); assert(wb != nullptr);
@ -271,11 +271,11 @@ void Java_org_rocksdb_WriteBatchInternal_setSequence(
} }
/* /*
* Class: org_rocksdb_WriteBatchInternal * Class: org_rocksdb_test_WriteBatchInternal
* Method: sequence * Method: sequence
* Signature: (Lorg/rocksdb/WriteBatch;)J * Signature: (Lorg/rocksdb/WriteBatch;)J
*/ */
jlong Java_org_rocksdb_WriteBatchInternal_sequence( jlong Java_org_rocksdb_test_WriteBatchInternal_sequence(
JNIEnv* env, jclass jclazz, jobject jobj) { JNIEnv* env, jclass jclazz, jobject jobj) {
rocksdb::WriteBatch* wb = rocksdb::WriteBatchJni::getHandle(env, jobj); rocksdb::WriteBatch* wb = rocksdb::WriteBatchJni::getHandle(env, jobj);
assert(wb != nullptr); assert(wb != nullptr);
@ -284,11 +284,11 @@ jlong Java_org_rocksdb_WriteBatchInternal_sequence(
} }
/* /*
* Class: org_rocksdb_WriteBatchInternal * Class: org_rocksdb_test_WriteBatchInternal
* Method: append * Method: append
* Signature: (Lorg/rocksdb/WriteBatch;Lorg/rocksdb/WriteBatch;)V * Signature: (Lorg/rocksdb/WriteBatch;Lorg/rocksdb/WriteBatch;)V
*/ */
void Java_org_rocksdb_WriteBatchInternal_append( void Java_org_rocksdb_test_WriteBatchInternal_append(
JNIEnv* env, jclass jclazz, jobject jwb1, jobject jwb2) { JNIEnv* env, jclass jclazz, jobject jwb1, jobject jwb2) {
rocksdb::WriteBatch* wb1 = rocksdb::WriteBatchJni::getHandle(env, jwb1); rocksdb::WriteBatch* wb1 = rocksdb::WriteBatchJni::getHandle(env, jwb1);
assert(wb1 != nullptr); assert(wb1 != nullptr);
@ -321,11 +321,11 @@ void Java_org_rocksdb_WriteBatch_00024Handler_disposeInternal(
} }
/* /*
* Class: org_rocksdb_WriteBatchTest * Class: org_rocksdb_test_WriteBatchTest
* Method: getContents * Method: getContents
* Signature: (Lorg/rocksdb/WriteBatch;)[B * Signature: (Lorg/rocksdb/WriteBatch;)[B
*/ */
jbyteArray Java_org_rocksdb_WriteBatchTest_getContents( jbyteArray Java_org_rocksdb_test_WriteBatchTest_getContents(
JNIEnv* env, jclass jclazz, jobject jobj) { JNIEnv* env, jclass jclazz, jobject jobj) {
rocksdb::WriteBatch* b = rocksdb::WriteBatchJni::getHandle(env, jobj); rocksdb::WriteBatch* b = rocksdb::WriteBatchJni::getHandle(env, jobj);
assert(b != nullptr); assert(b != nullptr);

Loading…
Cancel
Save