Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion jena-cmds/src/main/java/tdb2/cmdline/ModTDBDataset.java
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ public void processArgs(CmdArgModule cmdLine) {
public Dataset createDataset() {
if ( inMemFile != null ) {
Dataset ds = TDB2Factory.createDataset();
RDFDataMgr.read(ds, inMemFile);
ds.executeWrite(()->RDFDataMgr.read(ds, inMemFile));
return ds;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
import static java.lang.String.format;

import java.util.Arrays;
import java.util.Objects;

import org.apache.jena.atlas.lib.Bytes;
import org.apache.jena.dboe.sys.SystemIndex;
Expand Down Expand Up @@ -167,4 +168,58 @@ static boolean compatible(Record record1, Record record2, boolean checkValue) {
}
return true;
}

/**
* Return a new record with the key increased by 1.
* In case of overflow, the result is null.
*/
public static Record incrementKeyOrNull(Record record) {
Objects.requireNonNull(record);
byte[] keyBytes = incrementByteArray(record.getKey().clone());
return keyBytes == null ? null : new Record(keyBytes, record.getValue());
}

private static byte[] incrementByteArray(byte[] array) {
// Loop from the rightmost (least significant) byte to the left
for (int i = array.length - 1; i >= 0; i--) {
array[i]++;
// If it didn't roll over to 0, no carry is needed; we are done
if (array[i] != 0) {
return array;
}
}
// If we reach here, the entire array overflowed (e.g., [255, 255] -> [0, 0])
return null;
}

/**
* Pad {@code record} with zeros such that the lengths of its
* key and value arrays match those of the {@code prototype} record.
*
* If no padding is needed then {@code record} is returned.
* Otherwise, a new record is created.
*/
public static Record padRight(Record record, Record prototype, byte padValue) {
byte[] rkey = record.getKey();
byte[] rval = record.getValue();

byte[] pkey = prototype.getKey();
byte[] pval = prototype.getValue();

byte[] key = pkey == null ? rkey : padRight(rkey, pkey.length, padValue);
byte[] val = pval == null ? rval : padRight(rval, pval.length, padValue);
return (key == rkey && val == rval) ? record : new Record(key, val);
}

private static byte[] padRight(byte[] arr, int length, byte padValue) {
if (length <= arr.length) {
return arr;
}
byte[] r = Arrays.copyOf(arr, length); // Implicitly pads with 0 bytes
if (padValue != 0) {
// Pad with non-zero bytes.
Arrays.fill(r, arr.length, length, padValue);
}
return r;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -37,39 +37,71 @@ class BPTreeDistinctKeyPrefixIterator implements Iterator<Record> {
static Logger log = LoggerFactory.getLogger(BPTreeDistinctKeyPrefixIterator.class);

public static Iterator<Record> create(BPTreeNode node, int keyPrefixLength) {
if (keyPrefixLength < 1) {
throw new IllegalArgumentException("keyPrefixLength must be >= 1");
} else if (keyPrefixLength > node.params.recordFactory.keyLength()) {
throw new IllegalArgumentException(
"Maximum keyPrefixLength for this B+Tree is " + node.params.recordFactory.keyLength());
}
Record minRecord = node.minRecord();
Record maxRecord = node.maxRecord();
// If there's no records just return a null iterator
if (minRecord == null) {
return create(node, keyPrefixLength, null, null);
}

/**
* Iterate distinct key prefixes in the half-open range [min, max).
* Only the first keyPrefixLength bytes of either bound are significant; each
* bound must contain at least that many bytes. Null denotes an unbounded end.
* A zero-length prefix represents a single distinct value on a non-empty tree.
*/
public static Iterator<Record> create(BPTreeNode node, int keyPrefixLength, Record minRecordInclusive, Record maxRecordExclusive) {
int keyLength = node.params.recordFactory.keyLength();
if (keyPrefixLength < 0 || keyPrefixLength > keyLength) {
throw new IllegalArgumentException("keyPrefixLength must be between 0 and " + keyLength);
}

// Tree traversal and record-buffer scans compare whole keys. Map prefix
// bounds to the first full key of each prefix, including the exclusive max.
Record min = normalizeBound(minRecordInclusive, keyPrefixLength, keyLength);
Record max = normalizeBound(maxRecordExclusive, keyPrefixLength, keyLength);
if (min != null && max != null && Record.keyGE(min, max)) {
return Iter.nullIter();
}
// If there's only a single distinct prefix then just return a singleton
if (Arrays.compare(minRecord.getKey(), 0, keyPrefixLength, maxRecord.getKey(), 0, keyPrefixLength) == 0) {
return Iter.singletonIterator(minRecord);

Record nodeMinRecord = node.minRecord();
Record nodeMaxRecord = node.maxRecord();
if (nodeMinRecord == null) {
return Iter.nullIter();
}

if (haveSamePrefix(nodeMinRecord, nodeMaxRecord, keyPrefixLength)) {
return isPrefixInRequestRange(nodeMinRecord, keyPrefixLength, min, max)
? Iter.singletonIterator(nodeMinRecord) : Iter.nullIter();
}

// The downstream search requires a non-null lower bound.
return new BPTreeDistinctKeyPrefixIterator(node, keyPrefixLength,
min == null ? nodeMinRecord : min, max);
}

private static Record normalizeBound(Record bound, int keyPrefixLength, int keyLength) {
if (bound == null) {
return null;
}
if (bound.getKey().length < keyPrefixLength) {
throw new IllegalArgumentException("Range bound is shorter than keyPrefixLength");
}
// Otherwise need the full iterator
return new BPTreeDistinctKeyPrefixIterator(node, keyPrefixLength, minRecord, maxRecord);
byte[] key = new byte[keyLength];
System.arraycopy(bound.getKey(), 0, key, 0, keyPrefixLength);
return new Record(key, null);
}

// Convert path to a stack of iterators
private final Deque<Iterator<BPTreePage>> stack = new ArrayDeque<>();
private Iterator<Record> current;
private Record slot = null, minRecord, maxRecord;
private Record slot = null;
private final Record minRecordInclusive, maxRecordExclusive;
private byte[] lastPrefix = null;
private boolean finished = false;

private final int keyPrefixLength;

BPTreeDistinctKeyPrefixIterator(BPTreeNode node, int keyPrefixLength, Record minRecord, Record maxRecord) {
BPTreeDistinctKeyPrefixIterator(BPTreeNode node, int keyPrefixLength, Record minRecordInclusive, Record maxRecordExclusive) {
this.keyPrefixLength = keyPrefixLength;
this.minRecord = minRecord;
this.maxRecord = maxRecord;
this.minRecordInclusive = Objects.requireNonNull(minRecordInclusive);
this.maxRecordExclusive = maxRecordExclusive;

BPTreeRecords r = loadStack(node);
current = getRecordsIterator(r);
Expand Down Expand Up @@ -133,8 +165,16 @@ private Iterator<Record> moveOnCurrent() {
// iterator for this entire subtree and skip further recursion
Record subtreeMin = n.minRecord();
Record subtreeMax = n.maxRecord();
if (haveSamePrefix(subtreeMin, subtreeMax)) {
return Iter.singletonIterator(subtreeMin);
if (haveSamePrefix(subtreeMin, subtreeMax, keyPrefixLength)) {
Iterator<Record> recordIter;
// Check that the prefix is in range
if (isPrefixInRequestRange(subtreeMin, keyPrefixLength, minRecordInclusive, maxRecordExclusive)) {
// If the low and high keys for this page have the same prefix then just return a singleton iterator
recordIter = Iter.singletonIterator(subtreeMin);
} else {
recordIter = Iter.nullIterator();
}
return recordIter;
}
r = loadStack(n);
} else {
Expand All @@ -143,8 +183,20 @@ private Iterator<Record> moveOnCurrent() {
return getRecordsIterator(r);
}

protected final boolean haveSamePrefix(Record a, Record b) {
return Arrays.compare(a.getKey(), 0, this.keyPrefixLength, b.getKey(), 0, this.keyPrefixLength) == 0;
private static int comparePrefix(Record a, Record b, int keyPrefixLength) {
// Need to compare unsigned in general:
// E.g. [0, 5] is less than [0, -1] because the latter must be treated as [0, 255].
return Arrays.compareUnsigned(a.getKey(), 0, keyPrefixLength, b.getKey(), 0, keyPrefixLength);
}

private static boolean haveSamePrefix(Record a, Record b, int keyPrefixLength) {
return comparePrefix(a, b, keyPrefixLength) == 0;
}

protected static boolean isPrefixInRequestRange(Record record, int keyPrefixLength, Record minRecordInclusive, Record maxRecordExclusive) {
return
(minRecordInclusive == null || comparePrefix(record, minRecordInclusive, keyPrefixLength) >= 0) &&
(maxRecordExclusive == null || comparePrefix(record, maxRecordExclusive, keyPrefixLength) < 0);
}

// ---- Places we touch blocks.
Expand All @@ -157,12 +209,19 @@ protected Iterator<Record> getRecordsIterator(BPTreeRecords records) {
} else {
// Check whether we need to scan the whole page or can process it by skipping or singleton yield
Record lowRecord = records.getLowRecord();
if (haveSamePrefix(lowRecord, records.getHighRecord())) {
// If the low and high keys for this page have the same prefix then just return a singleton iterator
iter = Iter.singletonIterator(lowRecord);
Record highRecord = records.getHighRecord();
if (haveSamePrefix(lowRecord, highRecord, keyPrefixLength)) {
// Check that the prefix is in range
if (isPrefixInRequestRange(lowRecord, keyPrefixLength, minRecordInclusive, maxRecordExclusive)) {
// If the low and high keys for this page have the same prefix then just return a singleton iterator
iter = Iter.singletonIterator(lowRecord);
} else {
iter = Iter.nullIterator();
}
} else {
// Otherwise need to scan the whole page
iter = records.getRecordBuffer().iterator();
// Note: Adjacent records with the same prefix are filtered out in this class's hasNext() method
iter = records.getRecordBuffer().iterator(minRecordInclusive, maxRecordExclusive);
}
}
records.bpTree.finishReadBlkMgr();
Expand All @@ -173,11 +232,11 @@ private BPTreeRecords loadStack(BPTreeNode node) {
AccessPath path = new AccessPath(null);
node.bpTree.startReadBlkMgr();

node.internalMinRecord(path);
node.internalSearch(path, minRecordInclusive);
List<AccessStep> steps = path.getPath();
for (AccessStep step : steps) {
BPTreeNode n = step.node;
Iterator<BPTreePage> it = n.iterator(this.minRecord, this.maxRecord);
Iterator<BPTreePage> it = n.iterator(minRecordInclusive, maxRecordExclusive);
if (it == null || !it.hasNext()) {
continue;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,10 +34,10 @@
class BPTreeRangeIterator implements Iterator<Record> {
static Logger log = LoggerFactory.getLogger(BPTreeRangeIterator.class);

public static Iterator<Record> create(BPTreeNode node, Record minRec, Record maxRec) {
if ( minRec != null && maxRec != null && Record.keyGE(minRec, maxRec) )
public static Iterator<Record> create(BPTreeNode node, Record minRecInclusive, Record maxRecExclusive) {
if ( minRecInclusive != null && maxRecExclusive != null && Record.keyGE(minRecInclusive, maxRecExclusive) )
return Iter.nullIter();
return new BPTreeRangeIterator(node, minRec, maxRec);
return new BPTreeRangeIterator(node, minRecInclusive, maxRecExclusive);
}

// Convert path to a stack of iterators
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -312,21 +312,31 @@ public Iterator<Record> iterator() {
}

@Override
public Iterator<Record> iterator(Record fromRec, Record toRec) {
public Iterator<Record> iterator(Record fromRecInclusive, Record toRecExclusive) {
startReadBlkMgr();
BPTreeNode root = getRootRead();
releaseRootRead(root);
finishReadBlkMgr();
return BPTreeRangeIterator.create(root, fromRec, toRec);
return BPTreeRangeIterator.create(root, fromRecInclusive, toRecExclusive);
//return iterator(fromRec, toRec, RecordFactory.mapperRecord);
}

public Iterator<Record> distinctByKeyPrefix(int keyPrefixLength) {
return distinctByKeyPrefix(keyPrefixLength, null, null);
}

/**
* Return one record per distinct prefix in [fromRecInclusive, toRecExclusive).
* Only the first keyPrefixLength bytes of each bound are significant; bounds
* must contain at least that many bytes. Null bounds are unbounded. Prefix
* lengths from zero through the full key length are supported.
*/
public Iterator<Record> distinctByKeyPrefix(int keyPrefixLength, Record fromRecInclusive, Record toRecExclusive) {
startReadBlkMgr();
BPTreeNode root = getRootRead();
releaseRootRead(root);
finishReadBlkMgr();
return BPTreeDistinctKeyPrefixIterator.create(root, keyPrefixLength);
return BPTreeDistinctKeyPrefixIterator.create(root, keyPrefixLength, fromRecInclusive, toRecExclusive);
}

/*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
import java.util.*;
import java.util.stream.Stream;

import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedClass;
import org.junit.jupiter.params.provider.Arguments;
Expand Down Expand Up @@ -128,6 +129,7 @@ private static List<Integer> populateKeys(BPlusTree bpt, byte[] keys, int keyPos
}

@Test
@Disabled("SELECT DISTINCT ?zz { ?s ?p ?o } can result in 0 length prefixes")
public void bptree_distinct_by_key_bad_01() {
BPlusTree bpt = makeRangeIndex(this.treeOrder, 0);
assertThrows(IllegalArgumentException.class, ()->bpt.distinctByKeyPrefix(0));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ public interface TaskListener<T extends BasicTask> {
/**
* Whether the task has terminated.
*
* @implNote The original name {@code isTerminated} collided with the package−private method in {@link Thread}.
* @implNote The original name {@code isTerminated} collided with the package-private method in {@link Thread}.
*/
default boolean hasTerminated() {
TaskState state = getTaskState();
Expand Down
9 changes: 7 additions & 2 deletions jena-tdb2/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.

SPDX-License-Identifier: Apache-2.0
-->

Expand All @@ -32,7 +32,7 @@
<groupId>org.apache.jena</groupId>
<artifactId>jena</artifactId>
<version>6.3.0-SNAPSHOT</version>
</parent>
</parent>

<properties>
<build.time.xsd>${maven.build.timestamp}</build.time.xsd>
Expand Down Expand Up @@ -73,6 +73,11 @@
<scope>test</scope>
</dependency>

<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-math4-legacy</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

<build>
Expand Down
Loading