You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@phoenix.apache.org by vj...@apache.org on 2024/02/09 05:41:59 UTC
(phoenix) branch master updated: PHOENIX-7106 Data Integrity issues due to invalid rowkeys returned by various coprocessors (#1736)
This is an automated email from the ASF dual-hosted git repository.
vjasani pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/phoenix.git
The following commit(s) were added to refs/heads/master by this push:
new 87e3361e1f PHOENIX-7106 Data Integrity issues due to invalid rowkeys returned by various coprocessors (#1736)
87e3361e1f is described below
commit 87e3361e1f4cba6bb8f45355214067a8e9f8adcb
Author: Viraj Jasani <vj...@apache.org>
AuthorDate: Thu Feb 8 20:41:53 2024 -0900
PHOENIX-7106 Data Integrity issues due to invalid rowkeys returned by various coprocessors (#1736)
---
.../BaseScannerRegionObserverConstants.java | 30 +
.../ResultSetOutOfScanRangeException.java | 33 +-
.../apache/phoenix/exception/SQLExceptionCode.java | 1 +
.../org/apache/phoenix/filter/PagingFilter.java | 24 +-
.../phoenix/iterate/BaseResultIterators.java | 5 +-
.../phoenix/iterate/OffsetResultIterator.java | 47 +-
.../phoenix/iterate/OrderedResultIterator.java | 212 ++-
.../phoenix/iterate/ScanningResultIterator.java | 31 +
.../ScanningResultPostDummyResultCaller.java | 30 +
.../ScanningResultPostValidResultCaller.java | 30 +
.../phoenix/iterate/TableResultIterator.java | 36 +-
.../org/apache/phoenix/query/QueryConstants.java | 3 +-
.../org/apache/phoenix/query/QueryServices.java | 29 +
.../java/org/apache/phoenix/util/ByteUtil.java | 124 ++
.../java/org/apache/phoenix/util/QueryUtil.java | 17 +-
.../java/org/apache/phoenix/util/ScanUtil.java | 126 +-
.../java/org/apache/phoenix/util/TupleUtil.java | 44 +-
.../cache/aggcache/SpillableGroupByCache.java | 66 +-
.../coprocessor/BaseScannerRegionObserver.java | 42 +-
.../apache/phoenix/coprocessor/GroupByCache.java | 1 +
.../GroupedAggregateRegionObserver.java | 501 ++++-
.../coprocessor/IndexRebuildRegionScanner.java | 56 +-
.../coprocessor/IndexRepairRegionScanner.java | 27 +-
.../phoenix/coprocessor/IndexerRegionScanner.java | 31 +-
.../phoenix/coprocessor/PagingRegionScanner.java | 35 +-
.../coprocessor/UncoveredIndexRegionScanner.java | 76 +-
.../UngroupedAggregateRegionObserver.java | 50 +-
.../UngroupedAggregateRegionScanner.java | 13 +-
.../apache/phoenix/index/GlobalIndexChecker.java | 47 +-
.../iterate/NonAggregateRegionScannerFactory.java | 176 +-
.../java/org/apache/phoenix/util/ServerUtil.java | 16 +
.../end2end/AggregateQueryWithRegionMoves2IT.java | 136 ++
.../end2end/AggregateQueryWithRegionMovesIT.java | 279 +++
.../end2end/AggregateWithRegionMoves2IT.java | 124 ++
.../end2end/AggregateWithRegionMovesIT.java | 537 ++++++
.../phoenix/end2end/BackwardCompatibilityIT.java | 90 +
.../end2end/BackwardCompatibilityTestUtil.java | 12 +
.../end2end/BaseAggregateWithRegionMoves2IT.java | 633 +++++++
.../end2end/BaseAggregateWithRegionMoves3IT.java | 124 ++
.../end2end/BaseAggregateWithRegionMoves4IT.java | 136 ++
.../end2end/BaseAggregateWithRegionMovesIT.java | 998 ++++++++++
.../end2end/BaseOrderByWithRegionMovesIT.java | 1406 ++++++++++++++
.../end2end/BaseQueryWithRegionMovesIT.java | 165 ++
.../java/org/apache/phoenix/end2end/GroupByIT.java | 51 +
.../phoenix/end2end/OrderByWithRegionMovesIT.java | 21 +-
.../end2end/OrderByWithServerMemoryLimitIT.java | 10 +-
.../ParallelStatsDisabledWithRegionMovesIT.java | 310 +++
.../end2end/ScanUncommittedWithRegionMovesIT.java | 551 ++++++
.../org/apache/phoenix/end2end/ServerPagingIT.java | 9 +-
.../end2end/ServerPagingWithRegionMovesIT.java | 840 ++++++++
.../org/apache/phoenix/end2end/SortOrderIT.java | 60 +-
.../end2end/SortOrderWithRegionMoves2IT.java | 200 ++
.../end2end/SortOrderWithRegionMovesIT.java | 210 ++
.../end2end/UncoveredIndexWithRegionMovesIT.java | 391 ++++
.../end2end/UpsertSelectWithRegionMovesIT.java | 1996 ++++++++++++++++++++
.../end2end/index/BaseIndexWithRegionMovesIT.java | 1847 ++++++++++++++++++
...GlobalImmutableNonTxIndexWithRegionMovesIT.java | 35 +-
.../GlobalImmutableTxIndexWithRegionMovesIT.java | 44 +
.../index/GlobalIndexCheckerWithRegionMovesIT.java | 1715 +++++++++++++++++
.../GlobalMutableNonTxIndexWithRegionMovesIT.java | 40 +
.../UncoveredGlobalImmutableNonTxIndex2IT.java | 42 +
.../UncoveredGlobalIndexRegionScanner2IT.java | 1116 +++++++++++
.../phoenix/iterate/PhoenixQueryTimeoutIT.java | 116 +-
.../it/resources/compatible_client_versions.json | 2 +-
.../it/resources/gold_files/gold_query_offset.txt | 36 +-
.../gold_files/gold_query_orderby_nonpk.txt | 43 +-
.../gold_files/gold_query_ordered_groupby.txt | 39 +-
.../gold_files/gold_query_unorder_groupby.txt | 28 +-
.../src/it/resources/sql_files/create_offset.sql | 48 +
.../resources/sql_files/create_orderby_nonpk.sql | 48 +
.../resources/sql_files/create_ordered_groupby.sql | 48 +
.../resources/sql_files/create_unorder_groupby.sql | 44 +
.../src/it/resources/sql_files/query_offset.sql | 21 +-
.../it/resources/sql_files/query_orderby_nonpk.sql | 21 +-
.../resources/sql_files/query_ordered_groupby.sql | 21 +-
.../resources/sql_files/query_unorder_groupby.sql | 21 +-
.../phoenix/iterate/OrderedResultIteratorTest.java | 3 +
.../java/org/apache/phoenix/query/BaseTest.java | 3 +-
78 files changed, 16189 insertions(+), 440 deletions(-)
diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/coprocessorclient/BaseScannerRegionObserverConstants.java b/phoenix-core-client/src/main/java/org/apache/phoenix/coprocessorclient/BaseScannerRegionObserverConstants.java
index e8061cc9f7..f0fac9c278 100644
--- a/phoenix-core-client/src/main/java/org/apache/phoenix/coprocessorclient/BaseScannerRegionObserverConstants.java
+++ b/phoenix-core-client/src/main/java/org/apache/phoenix/coprocessorclient/BaseScannerRegionObserverConstants.java
@@ -136,6 +136,36 @@ public class BaseScannerRegionObserverConstants {
public static final String INDEX_ROW_KEY = "_IndexRowKey";
public static final String READ_REPAIR_TRANSFORMING_TABLE = "_ReadRepairTransformingTable";
+ /**
+ * The scan attribute to provide the scan start rowkey for analyze table queries.
+ */
+ public static final String SCAN_ANALYZE_ACTUAL_START_ROW = "_ScanAnalyzeActualStartRow";
+
+ /**
+ * The scan attribute to provide the scan stop rowkey for analyze table queries.
+ */
+ public static final String SCAN_ANALYZE_ACTUAL_STOP_ROW = "_ScanAnalyzeActualStopRow";
+
+ /**
+ * The scan attribute to provide the scan start rowkey include boolean value for analyze table
+ * queries.
+ */
+ public static final String SCAN_ANALYZE_INCLUDE_START_ROW = "_ScanAnalyzeIncludeStartRow";
+
+ /**
+ * The scan attribute to provide the scan stop rowkey include boolean value for analyze table
+ * queries.
+ */
+ public static final String SCAN_ANALYZE_INCLUDE_STOP_ROW = "_ScanAnalyzeIncludeStopRow";
+
+ /**
+ * The scan attribute to determine whether client changes are compatible to consume
+ * new format changes sent by the server. This attribute is mainly used to address
+ * data integrity issues related to region moves (PHOENIX-7106).
+ */
+ public static final String SCAN_SERVER_RETURN_VALID_ROW_KEY = "_ScanServerValidRowKey";
+
+
public final static byte[] REPLAY_TABLE_AND_INDEX_WRITES = PUnsignedTinyint.INSTANCE.toBytes(1);
public final static byte[] REPLAY_ONLY_INDEX_WRITES = PUnsignedTinyint.INSTANCE.toBytes(2);
// In case of Index Write failure, we need to determine that Index mutation
diff --git a/phoenix-core-server/src/main/java/org/apache/phoenix/coprocessor/GroupByCache.java b/phoenix-core-client/src/main/java/org/apache/phoenix/exception/ResultSetOutOfScanRangeException.java
similarity index 52%
copy from phoenix-core-server/src/main/java/org/apache/phoenix/coprocessor/GroupByCache.java
copy to phoenix-core-client/src/main/java/org/apache/phoenix/exception/ResultSetOutOfScanRangeException.java
index 68d07a948a..3aa9347f56 100644
--- a/phoenix-core-server/src/main/java/org/apache/phoenix/coprocessor/GroupByCache.java
+++ b/phoenix-core-client/src/main/java/org/apache/phoenix/exception/ResultSetOutOfScanRangeException.java
@@ -15,24 +15,27 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.phoenix.coprocessor;
-import java.io.Closeable;
+package org.apache.phoenix.exception;
-import org.apache.hadoop.hbase.regionserver.RegionScanner;
-import org.apache.phoenix.expression.aggregator.Aggregator;
-import org.apache.phoenix.hbase.index.util.ImmutableBytesPtr;
+import java.sql.SQLException;
/**
- *
- * Interface to abstract the way in which distinct group by
- * elements are cached
- *
- *
- * @since 3.0.0
+ * The Exception is thrown when the returned row key by the given Scanner does not satisfy the
+ * Scan boundaries i.e. scan start and end keys.
*/
-public interface GroupByCache extends Closeable {
- long size();
- Aggregator[] cache(ImmutableBytesPtr key);
- RegionScanner getScanner(RegionScanner s);
+public class ResultSetOutOfScanRangeException extends SQLException {
+
+ private static final SQLExceptionCode EXCEPTION_CODE =
+ SQLExceptionCode.ROW_KEY_OUT_OF_SCAN_RANGE;
+
+ public ResultSetOutOfScanRangeException(String message) {
+ super(new SQLExceptionInfo
+ .Builder(EXCEPTION_CODE)
+ .setMessage(message)
+ .build()
+ .toString(),
+ EXCEPTION_CODE.getSQLState(),
+ EXCEPTION_CODE.getErrorCode());
+ }
}
diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/exception/SQLExceptionCode.java b/phoenix-core-client/src/main/java/org/apache/phoenix/exception/SQLExceptionCode.java
index 6f2dc5bc1a..c3596b4f11 100644
--- a/phoenix-core-client/src/main/java/org/apache/phoenix/exception/SQLExceptionCode.java
+++ b/phoenix-core-client/src/main/java/org/apache/phoenix/exception/SQLExceptionCode.java
@@ -98,6 +98,7 @@ public enum SQLExceptionCode {
AMBIGUOUS_JOIN_CONDITION(217, "22017", "Ambiguous or non-equi join condition specified. Consider using table list with where clause."),
CONSTRAINT_VIOLATION(218, "23018", "Constraint violation."),
SUBQUERY_SELECT_LIST_COLUMN_MUST_HAS_ALIAS(219,"23019","Every column in subquery select lists must has alias when used for join."),
+ ROW_KEY_OUT_OF_SCAN_RANGE(220, "23020", "Row key is out of scan start/stop key boundaries"),
CONCURRENT_TABLE_MUTATION(301, "23000", "Concurrent modification to table.", new Factory() {
@Override
diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/filter/PagingFilter.java b/phoenix-core-client/src/main/java/org/apache/phoenix/filter/PagingFilter.java
index a472086d36..988efddf6a 100644
--- a/phoenix-core-client/src/main/java/org/apache/phoenix/filter/PagingFilter.java
+++ b/phoenix-core-client/src/main/java/org/apache/phoenix/filter/PagingFilter.java
@@ -46,9 +46,6 @@ public class PagingFilter extends FilterBase implements Writable {
State state;
private long pageSizeMs;
private long startTime;
- // tracks the row which we will visit next. It is not always a full row key and maybe
- // just the row key prefix.
- private Cell nextHintCell;
// tracks the row we last visited
private Cell currentCell;
private Filter delegate = null;
@@ -71,22 +68,14 @@ public class PagingFilter extends FilterBase implements Writable {
this.delegate = delegate;
}
- public byte[] getRowKeyAtStop() {
+ public byte[] getCurrentRowKeyToBeExcluded() {
byte[] rowKeyAtStop = null;
- if (nextHintCell != null) {
- // if we have already seeked to the next cell use that when we resume the scan
- rowKeyAtStop = CellUtil.cloneRow(nextHintCell);
- } else if (currentCell != null) {
+ if (currentCell != null) {
rowKeyAtStop = CellUtil.cloneRow(currentCell);
}
return rowKeyAtStop;
}
- public boolean isNextRowInclusive() {
- // since this can be a key prefix we have to set inclusive to true when resuming scan
- return nextHintCell != null;
- }
-
public boolean isStopped() {
return state == State.STOPPED;
}
@@ -94,7 +83,6 @@ public class PagingFilter extends FilterBase implements Writable {
public void init() {
state = State.INITIAL;
currentCell = null;
- nextHintCell = null;
}
@Override
@@ -118,10 +106,7 @@ public class PagingFilter extends FilterBase implements Writable {
@Override
public Cell getNextCellHint(Cell currentKV) throws IOException {
if (delegate != null) {
- Cell ret = delegate.getNextCellHint(currentKV);
- // save the hint so that if the filter stops we know where to resume the scan
- nextHintCell = ret;
- return ret;
+ return delegate.getNextCellHint(currentKV);
}
return super.getNextCellHint(currentKV);
}
@@ -129,8 +114,6 @@ public class PagingFilter extends FilterBase implements Writable {
@Override
public boolean filterRowKey(Cell cell) throws IOException {
currentCell = cell;
- // now that we have visited the row we need to reset the hint
- nextHintCell = null;
if (delegate != null) {
return delegate.filterRowKey(cell);
}
@@ -228,7 +211,6 @@ public class PagingFilter extends FilterBase implements Writable {
@Override
public Filter.ReturnCode filterCell(Cell c) throws IOException {
currentCell = c;
- nextHintCell = null;
if (delegate != null) {
return delegate.filterCell(c);
}
diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/iterate/BaseResultIterators.java b/phoenix-core-client/src/main/java/org/apache/phoenix/iterate/BaseResultIterators.java
index 07918fc459..5fda525316 100644
--- a/phoenix-core-client/src/main/java/org/apache/phoenix/iterate/BaseResultIterators.java
+++ b/phoenix-core-client/src/main/java/org/apache/phoenix/iterate/BaseResultIterators.java
@@ -1403,6 +1403,8 @@ public abstract class BaseResultIterators extends ExplainTable implements Result
concatIterators.add(iterator);
previousScan.setScan(scanPair.getFirst());
} catch (ExecutionException e) {
+ LOGGER.warn("Getting iterators at BaseResultIterators encountered error "
+ + "for table {}", TableName.valueOf(physicalTableName), e);
try { // Rethrow as SQLException
throw ClientUtil.parseServerException(e);
} catch (StaleRegionBoundaryCacheException | HashJoinCacheNotFoundException e2){
@@ -1414,9 +1416,6 @@ public abstract class BaseResultIterators extends ExplainTable implements Result
// Resubmit just this portion of work again
Scan oldScan = scanPair.getFirst();
byte[] startKey = oldScan.getAttribute(SCAN_ACTUAL_START_ROW);
- if (e2 instanceof StaleRegionBoundaryCacheException) {
- LOGGER.warn("Found stale region boundary with the following stack trace ", e2);
- }
if (e2 instanceof HashJoinCacheNotFoundException) {
LOGGER.debug(
"Retrying when Hash Join cache is not found on the server ,by sending the cache again");
diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/iterate/OffsetResultIterator.java b/phoenix-core-client/src/main/java/org/apache/phoenix/iterate/OffsetResultIterator.java
index 61de07500b..af23429cca 100644
--- a/phoenix-core-client/src/main/java/org/apache/phoenix/iterate/OffsetResultIterator.java
+++ b/phoenix-core-client/src/main/java/org/apache/phoenix/iterate/OffsetResultIterator.java
@@ -20,10 +20,12 @@ package org.apache.phoenix.iterate;
import java.sql.SQLException;
import java.util.List;
+import static org.apache.phoenix.util.ScanUtil.getDummyTuple;
import static org.apache.phoenix.util.ScanUtil.isDummy;
import org.apache.phoenix.compile.ExplainPlanAttributes.ExplainPlanAttributesBuilder;
import org.apache.phoenix.schema.tuple.Tuple;
+import org.apache.phoenix.util.EnvironmentEdgeManager;
/**
* Iterates through tuples up to a limit
@@ -32,32 +34,53 @@ import org.apache.phoenix.schema.tuple.Tuple;
*/
public class OffsetResultIterator extends DelegateResultIterator {
private int rowCount;
- private int offset;
+ private final int offset;
+ private Tuple lastScannedTuple;
private long pageSizeMs = Long.MAX_VALUE;
+ private boolean isIncompatibleClient = false;
public OffsetResultIterator(ResultIterator delegate, Integer offset) {
super(delegate);
this.offset = offset == null ? -1 : offset;
+ this.lastScannedTuple = null;
}
- public OffsetResultIterator(ResultIterator delegate, Integer offset, long pageSizeMs) {
+ public OffsetResultIterator(ResultIterator delegate, Integer offset, long pageSizeMs,
+ boolean isIncompatibleClient) {
this(delegate, offset);
this.pageSizeMs = pageSizeMs;
+ this.isIncompatibleClient = isIncompatibleClient;
}
+
@Override
public Tuple next() throws SQLException {
+ long startTime = EnvironmentEdgeManager.currentTimeMillis();
while (rowCount < offset) {
Tuple tuple = super.next();
- if (tuple == null) { return null; }
+ if (tuple == null) {
+ return null;
+ }
if (tuple.size() == 0 || isDummy(tuple)) {
- // while rowCount < offset absorb the dummy and call next on the underlying scanner
+ if (!isIncompatibleClient) {
+ return tuple;
+ }
+ // While rowCount < offset absorb the dummy and call next on the underlying scanner.
+ // This is applicable to old client.
continue;
}
rowCount++;
- // no page timeout check at this level because we cannot correctly resume
- // scans for OFFSET queries until the offset is reached
+ lastScannedTuple = tuple;
+ if (!isIncompatibleClient) {
+ if (EnvironmentEdgeManager.currentTimeMillis() - startTime >= pageSizeMs) {
+ return getDummyTuple(lastScannedTuple);
+ }
+ }
+ }
+ Tuple result = super.next();
+ if (result != null) {
+ lastScannedTuple = result;
}
- return super.next();
+ return result;
}
@Override
@@ -80,6 +103,14 @@ public class OffsetResultIterator extends DelegateResultIterator {
}
public Integer getRemainingOffset() {
- return (offset - rowCount) > 0 ? (offset - rowCount) : 0;
+ return Math.max(offset - rowCount, 0);
+ }
+
+ public Tuple getLastScannedTuple() {
+ return lastScannedTuple;
+ }
+
+ public void setRowCountToOffset() {
+ this.rowCount = this.offset;
}
}
diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/iterate/OrderedResultIterator.java b/phoenix-core-client/src/main/java/org/apache/phoenix/iterate/OrderedResultIterator.java
index 8172d703dc..4e36ae1a2a 100644
--- a/phoenix-core-client/src/main/java/org/apache/phoenix/iterate/OrderedResultIterator.java
+++ b/phoenix-core-client/src/main/java/org/apache/phoenix/iterate/OrderedResultIterator.java
@@ -17,37 +17,43 @@
*/
package org.apache.phoenix.iterate;
-import static org.apache.phoenix.thirdparty.com.google.common.base.Preconditions.checkArgument;
-import static org.apache.phoenix.thirdparty.com.google.common.base.Preconditions.checkPositionIndex;
-import static org.apache.phoenix.util.ScanUtil.getDummyTuple;
-import static org.apache.phoenix.util.ScanUtil.isDummy;
-
-import java.io.IOException;
-import java.sql.SQLException;
-import java.util.ArrayList;
-import java.util.Comparator;
-import java.util.List;
-
import org.apache.hadoop.hbase.KeyValue;
+import org.apache.hadoop.hbase.client.RegionInfo;
import org.apache.hadoop.hbase.client.Result;
+import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
import org.apache.hadoop.hbase.util.Bytes;
-import org.apache.phoenix.compile.ExplainPlanAttributes
- .ExplainPlanAttributesBuilder;
+import org.apache.phoenix.compile.ExplainPlanAttributes.ExplainPlanAttributesBuilder;
+import org.apache.phoenix.coprocessorclient.BaseScannerRegionObserverConstants;
+import org.apache.phoenix.exception.PhoenixIOException;
import org.apache.phoenix.execute.DescVarLengthFastByteComparisons;
import org.apache.phoenix.expression.Expression;
import org.apache.phoenix.expression.OrderByExpression;
+import org.apache.phoenix.query.QueryServices;
import org.apache.phoenix.schema.SortOrder;
import org.apache.phoenix.schema.tuple.Tuple;
+import org.apache.phoenix.thirdparty.com.google.common.base.Function;
+import org.apache.phoenix.thirdparty.com.google.common.collect.Collections2;
+import org.apache.phoenix.thirdparty.com.google.common.collect.Lists;
+import org.apache.phoenix.thirdparty.com.google.common.collect.Ordering;
+import org.apache.phoenix.util.ByteUtil;
import org.apache.phoenix.util.ClientUtil;
import org.apache.phoenix.util.EnvironmentEdgeManager;
import org.apache.phoenix.util.PhoenixKeyValueUtil;
+import org.apache.phoenix.util.ScanUtil;
import org.apache.phoenix.util.SizedUtil;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
-import org.apache.phoenix.thirdparty.com.google.common.base.Function;
-import org.apache.phoenix.thirdparty.com.google.common.collect.Collections2;
-import org.apache.phoenix.thirdparty.com.google.common.collect.Lists;
-import org.apache.phoenix.thirdparty.com.google.common.collect.Ordering;
+import java.io.IOException;
+import java.sql.SQLException;
+import java.util.ArrayList;
+import java.util.Comparator;
+import java.util.List;
+
+import static org.apache.phoenix.thirdparty.com.google.common.base.Preconditions.checkArgument;
+import static org.apache.phoenix.thirdparty.com.google.common.base.Preconditions.checkPositionIndex;
+import static org.apache.phoenix.util.ScanUtil.isDummy;
/**
* Result scanner that sorts aggregated rows by columns specified in the ORDER BY clause.
@@ -59,6 +65,8 @@ import org.apache.phoenix.thirdparty.com.google.common.collect.Ordering;
*/
public class OrderedResultIterator implements PeekingResultIterator {
+ private static final Logger LOGGER = LoggerFactory.getLogger(OrderedResultIterator.class);
+
/** A container that holds pointers to a {@link Result} and its sort keys. */
protected static class ResultEntry {
protected final ImmutableBytesWritable[] sortKeys;
@@ -151,6 +159,15 @@ public class OrderedResultIterator implements PeekingResultIterator {
private Tuple dummyTuple = null;
private long byteSize;
private long pageSizeMs;
+ private Scan scan;
+ private byte[] scanStartRowKey;
+ private byte[] actualScanStartRowKey;
+ private Boolean actualScanIncludeStartRowKey;
+ private RegionInfo regionInfo = null;
+ private boolean includeStartRowKey;
+ private boolean serverSideIterator = false;
+ private boolean firstScan = true;
+ private boolean skipValidRowsSent = false;
protected ResultIterator getDelegate() {
return delegate;
@@ -172,6 +189,32 @@ public class OrderedResultIterator implements PeekingResultIterator {
this(delegate, orderByExpressions, spoolingEnabled, thresholdBytes, limit, offset, estimatedRowSize, Long.MAX_VALUE);
}
+ public OrderedResultIterator(ResultIterator delegate,
+ List<OrderByExpression> orderByExpressions,
+ boolean spoolingEnabled,
+ long thresholdBytes, Integer limit, Integer offset,
+ int estimatedRowSize, long pageSizeMs, Scan scan,
+ RegionInfo regionInfo) {
+ this(delegate, orderByExpressions, spoolingEnabled, thresholdBytes, limit, offset,
+ estimatedRowSize, pageSizeMs);
+ this.scan = scan;
+ // If scan start rowkey is empty, use region boundaries. Reverse region boundaries
+ // for reverse scan.
+ // Keep this same as ServerUtil#getScanStartRowKeyFromScanOrRegionBoundaries.
+ this.scanStartRowKey =
+ scan.getStartRow().length > 0 ? scan.getStartRow()
+ : (scan.isReversed() ? regionInfo.getEndKey()
+ : regionInfo.getStartKey());
+ // Retrieve start rowkey of the previous scan. This would be different than
+ // current scan start rowkey if the region has recently moved or split or merged.
+ this.actualScanStartRowKey =
+ scan.getAttribute(BaseScannerRegionObserverConstants.SCAN_ACTUAL_START_ROW);
+ this.actualScanIncludeStartRowKey = true;
+ this.includeStartRowKey = scan.includeStartRow();
+ this.serverSideIterator = true;
+ this.regionInfo = regionInfo;
+ }
+
public OrderedResultIterator(ResultIterator delegate,
List<OrderByExpression> orderByExpressions, boolean spoolingEnabled,
long thresholdBytes, Integer limit, Integer offset, int estimatedRowSize, long pageSizeMs) {
@@ -257,11 +300,106 @@ public class OrderedResultIterator implements PeekingResultIterator {
@Override
public Tuple next() throws SQLException {
- getResultIterator();
- if (!resultIteratorReady) {
- return dummyTuple;
+ try {
+ if (firstScan && serverSideIterator && actualScanStartRowKey != null
+ && actualScanIncludeStartRowKey != null) {
+ if (scanStartRowKey.length > 0 && !ScanUtil.isLocalIndex(scan)) {
+ if (Bytes.compareTo(actualScanStartRowKey, scanStartRowKey) != 0
+ || actualScanIncludeStartRowKey != includeStartRowKey) {
+ LOGGER.info("Region has moved. Actual scan start rowkey {} is not same as"
+ + " current scan start rowkey {}",
+ Bytes.toStringBinary(actualScanStartRowKey),
+ Bytes.toStringBinary(scanStartRowKey));
+ // If region has moved in the middle of the scan operation, after resetting
+ // the scanner, hbase client uses (latest received rowkey + \x00) as new
+ // start rowkey for resuming the scan operation on the new scanner.
+ if (Bytes.compareTo(
+ ByteUtil.concat(actualScanStartRowKey, ByteUtil.ZERO_BYTE),
+ scanStartRowKey) == 0) {
+ scan.setAttribute(QueryServices.PHOENIX_PAGING_NEW_SCAN_START_ROWKEY,
+ actualScanStartRowKey);
+ scan.setAttribute(
+ QueryServices.PHOENIX_PAGING_NEW_SCAN_START_ROWKEY_INCLUDE,
+ Bytes.toBytes(actualScanIncludeStartRowKey));
+ } else {
+ // This happens when the server side scanner has already sent some
+ // rows back to the client and region has moved, so now we need to
+ // use skipValidRowsSent flag and also reset the scanner
+ // at paging region scanner level to re-read the previously sent
+ // values in order to re-compute the aggregation and then return
+ // only the next rowkey that was not yet sent back to the client.
+ skipValidRowsSent = true;
+ scan.setAttribute(QueryServices.PHOENIX_PAGING_NEW_SCAN_START_ROWKEY,
+ actualScanStartRowKey);
+ scan.setAttribute(
+ QueryServices.PHOENIX_PAGING_NEW_SCAN_START_ROWKEY_INCLUDE,
+ Bytes.toBytes(actualScanIncludeStartRowKey));
+ }
+ }
+ }
+ }
+ if (firstScan) {
+ firstScan = false;
+ }
+ getResultIterator();
+ if (!resultIteratorReady) {
+ return dummyTuple;
+ }
+ Tuple result = resultIterator.next();
+ if (skipValidRowsSent) {
+ while (true) {
+ if (result == null) {
+ skipValidRowsSent = false;
+ return null;
+ }
+ ImmutableBytesWritable ptr = new ImmutableBytesWritable();
+ result.getKey(ptr);
+ byte[] resultRowKey = new byte[ptr.getLength()];
+ System.arraycopy(ptr.get(), ptr.getOffset(), resultRowKey, 0,
+ resultRowKey.length);
+ // In case of regular scans, if the region moves and scanner is reset,
+ // hbase client checks the last returned row by the server, gets the
+ // rowkey and appends "\x00" byte, before resuming the scan. With this,
+ // scan includeStartRowKey is set to true.
+ // However, same is not the case with reverse scans. For the reverse scan,
+ // hbase client checks the last returned row by the server, gets the
+ // rowkey and treats it as startRowKey for resuming the scan. With this,
+ // scan includeStartRowKey is set to false.
+ // Hence, we need to cover both cases here.
+ if (Bytes.compareTo(resultRowKey, scanStartRowKey) == 0) {
+ // This can be true for reverse scan case.
+ skipValidRowsSent = false;
+ if (includeStartRowKey) {
+ return result;
+ }
+ // If includeStartRowKey is false and the current rowkey is matching
+ // with scanStartRowKey, return the next row result.
+ return resultIterator.next();
+ } else if (
+ Bytes.compareTo(
+ ByteUtil.concat(resultRowKey, ByteUtil.ZERO_BYTE),
+ scanStartRowKey) == 0) {
+ // This can be true for regular scan case.
+ skipValidRowsSent = false;
+ if (includeStartRowKey) {
+ // If includeStartRowKey is true and the (current rowkey + "\0xx") is
+ // matching with scanStartRowKey, return the next row result.
+ return resultIterator.next();
+ }
+ }
+ result = resultIterator.next();
+ }
+ }
+ return result;
+ } catch (Exception e) {
+ LOGGER.error("Ordered result iterator next encountered error " + (regionInfo != null
+ ? " for region: " + regionInfo.getRegionNameAsString() : "."), e);
+ if (e instanceof SQLException) {
+ throw e;
+ } else {
+ throw new PhoenixIOException(e);
+ }
}
- return resultIterator.next();
}
private PeekingResultIterator getResultIterator() throws SQLException {
@@ -288,7 +426,7 @@ public class OrderedResultIterator implements PeekingResultIterator {
}
if (isDummy(result)) {
- dummyTuple = result;
+ getDummyResult();
return resultIterator;
}
int pos = 0;
@@ -301,14 +439,16 @@ public class OrderedResultIterator implements PeekingResultIterator {
}
queueEntries.add(new ResultEntry(sortKeys, result));
if (EnvironmentEdgeManager.currentTimeMillis() - startTime >= pageSizeMs) {
- dummyTuple = getDummyTuple(result);
+ getDummyResult();
return resultIterator;
}
}
resultIteratorReady = true;
this.byteSize = queueEntries.getByteSize();
} catch (IOException e) {
+ LOGGER.error("Error while getting result iterator from OrderedResultIterator.", e);
ClientUtil.createIOException(e.getMessage(), e);
+ throw new SQLException(e);
} finally {
delegate.close();
}
@@ -316,6 +456,32 @@ public class OrderedResultIterator implements PeekingResultIterator {
return resultIterator;
}
+ /**
+ * Retrieve dummy rowkey.
+ */
+ private void getDummyResult() {
+ if (scanStartRowKey.length > 0 && !ScanUtil.isLocalIndex(scan)) {
+ if (Bytes.compareTo(actualScanStartRowKey, scanStartRowKey) != 0
+ || actualScanIncludeStartRowKey != includeStartRowKey) {
+ byte[] lastByte =
+ new byte[]{scanStartRowKey[scanStartRowKey.length - 1]};
+ if (scanStartRowKey.length > 1 && Bytes.compareTo(lastByte,
+ ByteUtil.ZERO_BYTE) == 0) {
+ byte[] prevKey = new byte[scanStartRowKey.length - 1];
+ System.arraycopy(scanStartRowKey, 0, prevKey, 0,
+ prevKey.length);
+ dummyTuple = ScanUtil.getDummyTuple(prevKey);
+ } else {
+ dummyTuple = ScanUtil.getDummyTuple(scanStartRowKey);
+ }
+ } else {
+ dummyTuple = ScanUtil.getDummyTuple(scanStartRowKey);
+ }
+ } else {
+ dummyTuple = ScanUtil.getDummyTuple(scanStartRowKey);
+ }
+ }
+
@Override
public Tuple peek() throws SQLException {
return getResultIterator().peek();
diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/iterate/ScanningResultIterator.java b/phoenix-core-client/src/main/java/org/apache/phoenix/iterate/ScanningResultIterator.java
index a3f335a6d2..82081267bf 100644
--- a/phoenix-core-client/src/main/java/org/apache/phoenix/iterate/ScanningResultIterator.java
+++ b/phoenix-core-client/src/main/java/org/apache/phoenix/iterate/ScanningResultIterator.java
@@ -53,6 +53,7 @@ import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.client.metrics.ScanMetrics;
+import org.apache.hadoop.util.ReflectionUtils;
import org.apache.phoenix.compile.ExplainPlanAttributes.ExplainPlanAttributesBuilder;
import org.apache.phoenix.compile.StatementContext;
import org.apache.phoenix.exception.SQLExceptionCode;
@@ -60,6 +61,7 @@ import org.apache.phoenix.exception.SQLExceptionInfo;
import org.apache.phoenix.monitoring.CombinableMetric;
import org.apache.phoenix.monitoring.GlobalClientMetrics;
import org.apache.phoenix.monitoring.ScanMetricsHolder;
+import org.apache.phoenix.query.QueryServices;
import org.apache.phoenix.schema.tuple.ResultTuple;
import org.apache.phoenix.schema.tuple.Tuple;
import org.apache.phoenix.thirdparty.com.google.common.annotations.VisibleForTesting;
@@ -83,6 +85,9 @@ public class ScanningResultIterator implements ResultIterator {
private long dummyRowCounter = 0;
+ private final ScanningResultPostDummyResultCaller scanningResultPostDummyResultCaller;
+ private final ScanningResultPostValidResultCaller scanningResultPostValidResultCaller;
+
public ScanningResultIterator(ResultScanner scanner, Scan scan, ScanMetricsHolder scanMetricsHolder, StatementContext context, boolean isMapReduceContext, long maxQueryEndTime) {
this.scanner = scanner;
this.scanMetricsHolder = scanMetricsHolder;
@@ -91,6 +96,22 @@ public class ScanningResultIterator implements ResultIterator {
scanMetricsEnabled = scan.isScanMetricsEnabled();
this.isMapReduceContext = isMapReduceContext;
this.maxQueryEndTime = maxQueryEndTime;
+ Class<? extends ScanningResultPostDummyResultCaller> dummyResultCallerClazz =
+ context.getConnection().getQueryServices().getConfiguration().getClass(
+ QueryServices.PHOENIX_POST_DUMMY_PROCESS,
+ ScanningResultPostDummyResultCaller.class,
+ ScanningResultPostDummyResultCaller.class);
+ this.scanningResultPostDummyResultCaller =
+ ReflectionUtils.newInstance(dummyResultCallerClazz,
+ context.getConnection().getQueryServices().getConfiguration());
+ Class<? extends ScanningResultPostValidResultCaller> validResultCallerClazz =
+ context.getConnection().getQueryServices().getConfiguration().getClass(
+ QueryServices.PHOENIX_POST_VALID_PROCESS,
+ ScanningResultPostValidResultCaller.class,
+ ScanningResultPostValidResultCaller.class);
+ this.scanningResultPostValidResultCaller =
+ ReflectionUtils.newInstance(validResultCallerClazz,
+ context.getConnection().getQueryServices().getConfiguration());
}
@Override
@@ -197,6 +218,7 @@ public class ScanningResultIterator implements ResultIterator {
close();
return null;
}
+ processAfterRetrievingDummyResult();
result = scanner.next();
}
if (result == null) {
@@ -205,12 +227,21 @@ public class ScanningResultIterator implements ResultIterator {
}
// TODO: use ResultTuple.setResult(result)?
// Need to create a new one if holding on to it (i.e. OrderedResultIterator)
+ processAfterRetrievingValidResult();
return new ResultTuple(result);
} catch (IOException e) {
throw ClientUtil.parseServerException(e);
}
}
+ private void processAfterRetrievingDummyResult() {
+ scanningResultPostDummyResultCaller.postDummyProcess();
+ }
+
+ private void processAfterRetrievingValidResult() {
+ scanningResultPostValidResultCaller.postValidRowProcess();
+ }
+
@Override
public void explain(List<String> planSteps) {
}
diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/iterate/ScanningResultPostDummyResultCaller.java b/phoenix-core-client/src/main/java/org/apache/phoenix/iterate/ScanningResultPostDummyResultCaller.java
new file mode 100644
index 0000000000..6367a28e0c
--- /dev/null
+++ b/phoenix-core-client/src/main/java/org/apache/phoenix/iterate/ScanningResultPostDummyResultCaller.java
@@ -0,0 +1,30 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to you under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.phoenix.iterate;
+
+/**
+ * The class to perform any operation at {@link ScanningResultIterator} level once dummy cell is
+ * returned by the server.
+ */
+public class ScanningResultPostDummyResultCaller {
+
+ public void postDummyProcess() {
+ // no-op
+ }
+
+}
diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/iterate/ScanningResultPostValidResultCaller.java b/phoenix-core-client/src/main/java/org/apache/phoenix/iterate/ScanningResultPostValidResultCaller.java
new file mode 100644
index 0000000000..4a38f51218
--- /dev/null
+++ b/phoenix-core-client/src/main/java/org/apache/phoenix/iterate/ScanningResultPostValidResultCaller.java
@@ -0,0 +1,30 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to you under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.phoenix.iterate;
+
+/**
+ * The class to perform any operation at {@link ScanningResultIterator} level once valid row is
+ * returned by the server.
+ */
+public class ScanningResultPostValidResultCaller {
+
+ public void postValidRowProcess() {
+ // no-op
+ }
+
+}
diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/iterate/TableResultIterator.java b/phoenix-core-client/src/main/java/org/apache/phoenix/iterate/TableResultIterator.java
index 5a8283432d..d92e63867a 100644
--- a/phoenix-core-client/src/main/java/org/apache/phoenix/iterate/TableResultIterator.java
+++ b/phoenix-core-client/src/main/java/org/apache/phoenix/iterate/TableResultIterator.java
@@ -19,6 +19,7 @@ package org.apache.phoenix.iterate;
import static org.apache.phoenix.coprocessorclient.BaseScannerRegionObserverConstants.SCAN_ACTUAL_START_ROW;
import static org.apache.phoenix.coprocessorclient.BaseScannerRegionObserverConstants.SCAN_START_ROW_SUFFIX;
+import static org.apache.phoenix.coprocessorclient.BaseScannerRegionObserverConstants.SCAN_STOP_ROW_SUFFIX;
import static org.apache.phoenix.iterate.TableResultIterator.RenewLeaseStatus.CLOSED;
import static org.apache.phoenix.iterate.TableResultIterator.RenewLeaseStatus.LOCK_NOT_ACQUIRED;
import static org.apache.phoenix.iterate.TableResultIterator.RenewLeaseStatus.NOT_RENEWED;
@@ -46,6 +47,7 @@ import org.apache.phoenix.compile.ExplainPlanAttributes
.ExplainPlanAttributesBuilder;
import org.apache.phoenix.compile.QueryPlan;
import org.apache.phoenix.coprocessorclient.HashJoinCacheNotFoundException;
+import org.apache.phoenix.exception.ResultSetOutOfScanRangeException;
import org.apache.phoenix.execute.BaseQueryPlan;
import org.apache.phoenix.execute.MutationState;
import org.apache.phoenix.hbase.index.util.ImmutableBytesPtr;
@@ -59,6 +61,7 @@ import org.apache.phoenix.util.ClientUtil;
import org.apache.phoenix.util.Closeables;
import org.apache.phoenix.util.EnvironmentEdgeManager;
import org.apache.phoenix.util.ScanUtil;
+import org.apache.phoenix.util.TupleUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -209,8 +212,27 @@ public class TableResultIterator implements ResultIterator {
if (lastTuple != null) {
ImmutableBytesWritable ptr = new ImmutableBytesWritable();
lastTuple.getKey(ptr);
+ try {
+ ScanUtil.verifyKeyInScanRange(ptr, scan);
+ } catch (ResultSetOutOfScanRangeException e) {
+ LOGGER.error("Row key {} of table {} is out of scan range. Scan start "
+ + "key: {} , end key: {} , _ScanActualStartRow: {} , "
+ + "_ScanStartRowSuffix: {} , _ScanStopRowSuffix: {} , "
+ + "scan attributes: {}",
+ Bytes.toStringBinary(ptr.get()),
+ htable.getName(),
+ Bytes.toStringBinary(scan.getStartRow()),
+ Bytes.toStringBinary(scan.getStopRow()),
+ Bytes.toStringBinary(scan.getAttribute(SCAN_ACTUAL_START_ROW)),
+ Bytes.toStringBinary(scan.getAttribute(SCAN_START_ROW_SUFFIX)),
+ Bytes.toStringBinary(scan.getAttribute(SCAN_STOP_ROW_SUFFIX)),
+ scan.getAttributesMap(),
+ e);
+ throw e;
+ }
}
} catch (SQLException e) {
+ LOGGER.error("Error while scanning table {} , scan {}", htable, scan);
try {
throw ClientUtil.parseServerException(e);
} catch(HashJoinCacheNotFoundException e1) {
@@ -256,7 +278,7 @@ public class TableResultIterator implements ResultIterator {
}
}
}
- return lastTuple;
+ return TupleUtil.getAggregateGroupTuple(lastTuple);
} finally {
renewLeaseLock.unlock();
}
@@ -271,8 +293,18 @@ public class TableResultIterator implements ResultIterator {
ResultIterator delegate = this.scanIterator;
if (delegate == UNINITIALIZED_SCANNER) {
try {
+ // It is important to update the scan boundaries for the reverse scan
+ // and set the scan as reverse at the client side rather than update it
+ // at the server side. Updating reverse scan boundaries at the server side
+ // can lead to incorrect results if the region moves in the middle of the
+ // ongoing scans.
+ if (ScanUtil.isReversed(scan)) {
+ ScanUtil.setupReverseScan(scan);
+ }
this.scanIterator =
- new ScanningResultIterator(htable.getScanner(scan), scan, scanMetricsHolder, plan.getContext(), isMapReduceContext, maxQueryEndTime);
+ new ScanningResultIterator(htable.getScanner(scan), scan,
+ scanMetricsHolder, plan.getContext(), isMapReduceContext,
+ maxQueryEndTime);
} catch (IOException e) {
Closeables.closeQuietly(htable);
throw ClientUtil.parseServerException(e);
diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/query/QueryConstants.java b/phoenix-core-client/src/main/java/org/apache/phoenix/query/QueryConstants.java
index cd5a54f520..a75cc7e117 100644
--- a/phoenix-core-client/src/main/java/org/apache/phoenix/query/QueryConstants.java
+++ b/phoenix-core-client/src/main/java/org/apache/phoenix/query/QueryConstants.java
@@ -200,7 +200,8 @@ public interface QueryConstants {
byte[] SYSTEM_SCHEMA_NAME_BYTES = Bytes.toBytes(SYSTEM_SCHEMA_NAME);
String OFFSET_ROW_KEY = "_OFFSET_";
byte[] OFFSET_ROW_KEY_BYTES = Bytes.toBytes(OFFSET_ROW_KEY);
- ImmutableBytesPtr OFFSET_ROW_KEY_PTR = new ImmutableBytesPtr(OFFSET_ROW_KEY_BYTES);
+ String GROUPED_AGGREGATOR_VALUE = "_GA_";
+ byte[] GROUPED_AGGREGATOR_VALUE_BYTES = Bytes.toBytes(GROUPED_AGGREGATOR_VALUE);
long AGG_TIMESTAMP = HConstants.LATEST_TIMESTAMP;
/**
diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/query/QueryServices.java b/phoenix-core-client/src/main/java/org/apache/phoenix/query/QueryServices.java
index 8397bdc046..799bf8f7ce 100644
--- a/phoenix-core-client/src/main/java/org/apache/phoenix/query/QueryServices.java
+++ b/phoenix-core-client/src/main/java/org/apache/phoenix/query/QueryServices.java
@@ -448,6 +448,35 @@ public interface QueryServices extends SQLCloseable {
boolean DEFAULT_DISABLE_VIEW_SUBTREE_VALIDATION = false;
+ /**
+ * Only used by tests: parameter to determine num of regionservers to be created by
+ * MiniHBaseCluster.
+ */
+ String TESTS_MINI_CLUSTER_NUM_REGION_SERVERS = "phoenix.tests.minicluster.numregionservers";
+
+
+ /**
+ * Config to inject any processing after the client retrieves dummy result from the server.
+ */
+ String PHOENIX_POST_DUMMY_PROCESS = "phoenix.scanning.result.post.dummy.process";
+
+ /**
+ * Config to inject any processing after the client retrieves valid result from the server.
+ */
+ String PHOENIX_POST_VALID_PROCESS = "phoenix.scanning.result.post.valid.process";
+
+ /**
+ * New start rowkey to be used by paging region scanner for the scan.
+ */
+ String PHOENIX_PAGING_NEW_SCAN_START_ROWKEY = "phoenix.paging.start.newscan.startrow";
+
+ /**
+ * New start rowkey to be included by paging region scanner for the scan. The value of the
+ * attribute is expected to be boolean.
+ */
+ String PHOENIX_PAGING_NEW_SCAN_START_ROWKEY_INCLUDE =
+ "phoenix.paging.start.newscan.startrow.include";
+
/**
* Get executor service used for parallel scans
*/
diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/util/ByteUtil.java b/phoenix-core-client/src/main/java/org/apache/phoenix/util/ByteUtil.java
index a1bb50807e..56dbb88a46 100644
--- a/phoenix-core-client/src/main/java/org/apache/phoenix/util/ByteUtil.java
+++ b/phoenix-core-client/src/main/java/org/apache/phoenix/util/ByteUtil.java
@@ -41,6 +41,8 @@ import org.apache.phoenix.schema.SortOrder;
import org.apache.phoenix.schema.types.PDataType;
import org.apache.phoenix.thirdparty.com.google.common.base.Preconditions;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
@@ -51,6 +53,9 @@ import org.apache.phoenix.thirdparty.com.google.common.base.Preconditions;
* @since 0.1
*/
public class ByteUtil {
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(ByteUtil.class);
+
public static final byte[] EMPTY_BYTE_ARRAY = new byte[0];
public static final ImmutableBytesPtr EMPTY_BYTE_ARRAY_PTR = new ImmutableBytesPtr(
EMPTY_BYTE_ARRAY);
@@ -84,6 +89,8 @@ public class ByteUtil {
private static final int[] BITS = {BIT_7, BIT_6, BIT_5, BIT_4, BIT_3, BIT_2, BIT_1, BIT_0};
+ public static final byte[] ZERO_BYTE = Bytes.toBytesBinary("\\x00");
+
public static final Comparator<ImmutableBytesPtr> BYTES_PTR_COMPARATOR = new Comparator<ImmutableBytesPtr>() {
@Override
@@ -469,6 +476,116 @@ public class ByteUtil {
return previousKey;
}
+ /**
+ * Best attempt to generate largest rowkey smaller than endKey i.e. largest rowkey in the
+ * range of [startKey, endKey). If startKey and endKey are empty, the empty key is returned.
+ * This function is used to return valid rowkey for some ungrouped aggregation e.g. while
+ * returning count value after scanning the rows. If any error or validation issues (e.g.
+ * startKey > endKey) are encountered, null value is returned.
+ *
+ * @param startKey start rowkey for the range.
+ * @param endKey end rowkey for the range.
+ * @return best attempt of largest rowkey in the range of [startKey, endKey).
+ */
+ public static byte[] getLargestPossibleRowKeyInRange(byte[] startKey, byte[] endKey) {
+ if (startKey.length == 0 && endKey.length == 0) {
+ return HConstants.EMPTY_END_ROW;
+ }
+ byte[] rowKey;
+ try {
+ if (startKey.length > 0 && endKey.length > 0) {
+ int commonBytesIdx = 0;
+ while (commonBytesIdx < startKey.length && commonBytesIdx < endKey.length) {
+ if (startKey[commonBytesIdx] == endKey[commonBytesIdx]) {
+ commonBytesIdx++;
+ } else {
+ break;
+ }
+ }
+ if (commonBytesIdx == 0) {
+ rowKey = ByteUtil.previousKeyWithLength(ByteUtil.concat(endKey,
+ new byte[startKey.length + 1]),
+ Math.max(endKey.length, startKey.length) + 1);
+ } else {
+ byte[] newStartKey;
+ byte[] newEndKey;
+ if (commonBytesIdx < startKey.length) {
+ newStartKey = new byte[startKey.length - commonBytesIdx];
+ System.arraycopy(startKey, commonBytesIdx, newStartKey, 0,
+ newStartKey.length);
+ } else {
+ newStartKey = startKey;
+ }
+ if (commonBytesIdx < endKey.length) {
+ newEndKey = new byte[endKey.length - commonBytesIdx];
+ System.arraycopy(endKey, commonBytesIdx, newEndKey, 0, newEndKey.length);
+ } else {
+ newEndKey = endKey;
+ }
+ byte[] commonBytes = new byte[commonBytesIdx];
+ System.arraycopy(startKey, 0, commonBytes, 0, commonBytesIdx);
+ byte[] tmpRowKey = ByteUtil.previousKeyWithLength(ByteUtil.concat(newEndKey,
+ new byte[newStartKey.length + 1]),
+ Math.max(newEndKey.length, newStartKey.length) + 1);
+ // tmpRowKey can be null if newEndKey has only \x00 bytes
+ if (tmpRowKey == null) {
+ tmpRowKey = new byte[newEndKey.length - 1];
+ System.arraycopy(newEndKey, 0, tmpRowKey, 0, tmpRowKey.length);
+ rowKey = ByteUtil.concat(commonBytes, tmpRowKey);
+ } else {
+ rowKey = ByteUtil.concat(commonBytes, tmpRowKey);
+ }
+ }
+ } else if (endKey.length > 0) {
+ rowKey = ByteUtil.previousKeyWithLength(ByteUtil.concat(endKey,
+ new byte[1]), endKey.length + 1);
+ } else {
+ rowKey = ByteUtil.nextKeyWithLength(ByteUtil.concat(startKey,
+ new byte[1]), startKey.length + 1);
+ }
+ if (rowKey == null) {
+ LOGGER.error("Unexpected result while retrieving rowkey in range ({} , {})",
+ Bytes.toStringBinary(startKey), Bytes.toStringBinary(endKey));
+ return null;
+ }
+ if (Bytes.compareTo(startKey, rowKey) >= 0
+ || Bytes.compareTo(rowKey, endKey) >= 0) {
+ LOGGER.error("Unexpected result while comparing result rowkey in range "
+ + "({} , {}) , rowKey: {}",
+ Bytes.toStringBinary(startKey), Bytes.toStringBinary(endKey),
+ Bytes.toStringBinary(rowKey));
+ return null;
+ }
+ } catch (Exception e) {
+ LOGGER.error("Error while retrieving rowkey in range ({} , {})",
+ Bytes.toStringBinary(startKey), Bytes.toStringBinary(endKey));
+ return null;
+ }
+ return rowKey;
+ }
+
+ public static byte[] previousKeyWithLength(byte[] key, int length) {
+ Preconditions.checkArgument(key.length >= length, "Key length " + key.length + " is "
+ + "less than least expected length " + length);
+ byte[] previousKey = new byte[length];
+ System.arraycopy(key, 0, previousKey, 0, length);
+ if (!previousKey(previousKey, length)) {
+ return null;
+ }
+ return previousKey;
+ }
+
+ public static byte[] nextKeyWithLength(byte[] key, int length) {
+ Preconditions.checkArgument(key.length >= length, "Key length " + key.length + " is "
+ + "less than least expected length " + length);
+ byte[] nextStartRow = new byte[length];
+ System.arraycopy(key, 0, nextStartRow, 0, length);
+ if (!nextKey(nextStartRow, length)) {
+ return null;
+ }
+ return nextStartRow;
+ }
+
public static boolean previousKey(byte[] key, int length) {
return previousKey(key, 0, length);
}
@@ -698,4 +815,11 @@ public class ByteUtil {
}
return l_raw;
}
+
+ /**
+ * Create the closest row after the specified row
+ */
+ public static byte[] closestPossibleRowAfter(byte[] row) {
+ return Arrays.copyOf(row, row.length + 1);
+ }
}
diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/util/QueryUtil.java b/phoenix-core-client/src/main/java/org/apache/phoenix/util/QueryUtil.java
index fb2e3434bf..52e4f6aa0e 100644
--- a/phoenix-core-client/src/main/java/org/apache/phoenix/util/QueryUtil.java
+++ b/phoenix-core-client/src/main/java/org/apache/phoenix/util/QueryUtil.java
@@ -83,7 +83,6 @@ import org.apache.phoenix.expression.function.SQLTableTypeFunction;
import org.apache.phoenix.expression.function.SQLViewTypeFunction;
import org.apache.phoenix.expression.function.SqlTypeNameFunction;
import org.apache.phoenix.expression.function.TransactionProviderNameFunction;
-import org.apache.phoenix.hbase.index.util.ImmutableBytesPtr;
import org.apache.phoenix.iterate.ResultIterator;
import org.apache.phoenix.jdbc.ConnectionInfo;
import org.apache.phoenix.jdbc.PhoenixConnection;
@@ -514,11 +513,17 @@ public final class QueryUtil {
public static Integer getRemainingOffset(Tuple offsetTuple) {
if (offsetTuple != null) {
- ImmutableBytesPtr rowKeyPtr = new ImmutableBytesPtr();
- offsetTuple.getKey(rowKeyPtr);
- if (QueryConstants.OFFSET_ROW_KEY_PTR.compareTo(rowKeyPtr) == 0) {
- Cell cell = offsetTuple.getValue(QueryConstants.OFFSET_FAMILY, QueryConstants.OFFSET_COLUMN);
- return PInteger.INSTANCE.toObject(cell.getValueArray(), cell.getValueOffset(), cell.getValueLength(), PInteger.INSTANCE, SortOrder.ASC, null, null);
+ Cell cell = offsetTuple.getValue(QueryConstants.OFFSET_FAMILY,
+ QueryConstants.OFFSET_COLUMN);
+ if (cell != null) {
+ return PInteger.INSTANCE.toObject(
+ cell.getValueArray(),
+ cell.getValueOffset(),
+ cell.getValueLength(),
+ PInteger.INSTANCE,
+ SortOrder.ASC,
+ null,
+ null);
}
}
return null;
diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/util/ScanUtil.java b/phoenix-core-client/src/main/java/org/apache/phoenix/util/ScanUtil.java
index d4cb31d9e8..8ed9fce9a1 100644
--- a/phoenix-core-client/src/main/java/org/apache/phoenix/util/ScanUtil.java
+++ b/phoenix-core-client/src/main/java/org/apache/phoenix/util/ScanUtil.java
@@ -61,6 +61,7 @@ import org.apache.phoenix.compile.StatementContext;
import org.apache.phoenix.coprocessor.generated.PTableProtos;
import org.apache.phoenix.coprocessorclient.BaseScannerRegionObserverConstants;
import org.apache.phoenix.coprocessorclient.MetaDataProtocol;
+import org.apache.phoenix.exception.ResultSetOutOfScanRangeException;
import org.apache.phoenix.exception.SQLExceptionCode;
import org.apache.phoenix.exception.SQLExceptionInfo;
import org.apache.phoenix.execute.BaseQueryPlan;
@@ -121,6 +122,10 @@ public class ScanUtil {
public static final int UNKNOWN_CLIENT_VERSION = VersionUtil.encodeVersion(4, 4, 0);
private static final byte[] ZERO_BYTE_ARRAY = new byte[1024];
+ private static final String RESULT_IS_OUT_OF_SCAN_START_KEY =
+ "Row key of the result is out of scan start key range";
+ private static final String RESULT_IS_OUT_OF_SCAN_STOP_KEY =
+ "Row key of the result is out of scan stop key range";
private ScanUtil() {
}
@@ -975,6 +980,9 @@ public class ScanUtil {
byte[] clientVersionBytes = scan.getAttribute(BaseScannerRegionObserverConstants.CLIENT_VERSION);
if (clientVersionBytes != null) {
clientVersion = Bytes.toInt(clientVersionBytes);
+ } else {
+ LOGGER.warn("Scan attribute {} not found. Scan attributes: {}",
+ BaseScannerRegionObserverConstants.CLIENT_VERSION, scan.getAttributesMap());
}
return clientVersion;
}
@@ -1337,6 +1345,8 @@ public class ScanUtil {
}
setScanAttributeForPaging(scan, phoenixConnection);
+ scan.setAttribute(BaseScannerRegionObserverConstants.SCAN_SERVER_RETURN_VALID_ROW_KEY,
+ Bytes.toBytes(true));
}
public static void setScanAttributeForPaging(Scan scan, PhoenixConnection phoenixConnection) {
@@ -1365,22 +1375,12 @@ public class ScanUtil {
result.add(keyValue);
}
- public static void getDummyResult(List<Cell> result) {
- getDummyResult(EMPTY_BYTE_ARRAY, result);
- }
-
public static Tuple getDummyTuple(byte[] rowKey) {
List<Cell> result = new ArrayList<Cell>(1);
getDummyResult(rowKey, result);
return new ResultTuple(Result.create(result));
}
- public static Tuple getDummyTuple() {
- List<Cell> result = new ArrayList<Cell>(1);
- getDummyResult(result);
- return new ResultTuple(Result.create(result));
- }
-
public static Tuple getDummyTuple(Tuple tuple) {
ImmutableBytesWritable ptr = new ImmutableBytesWritable();
tuple.getKey(ptr);
@@ -1596,6 +1596,19 @@ public class ScanUtil {
return null;
}
+ /**
+ * Determine if the client is incompatible and therefore will not be able to parse the
+ * valid rowkey that server returns.
+ *
+ * @param scan Scan object.
+ * @return true if the client is incompatible and therefore will not be able to parse the
+ * valid rowkey that server returns.
+ */
+ public static boolean isIncompatibleClientForServerReturnValidRowKey(Scan scan) {
+ return scan.getAttribute(
+ BaseScannerRegionObserverConstants.SCAN_SERVER_RETURN_VALID_ROW_KEY) == null;
+ }
+
// This method assumes that there is at most one instance of PageFilter in a scan
public static PageFilter removePageFilter(Scan scan) {
Filter filter = scan.getFilter();
@@ -1615,4 +1628,97 @@ public class ScanUtil {
}
return null;
}
+
+ /**
+ * Verify whether the given row key is in the scan boundaries i.e. scan start and end keys.
+ *
+ * @param ptr row key.
+ * @param scan scan object used to retrieve the result set.
+ * @throws ResultSetOutOfScanRangeException if the row key is out of scan range.
+ */
+ public static void verifyKeyInScanRange(ImmutableBytesWritable ptr,
+ Scan scan)
+ throws ResultSetOutOfScanRangeException {
+ try {
+ if (scan.isReversed()) {
+ verifyScanRangesForReverseScan(ptr, scan, scan.getStartRow(), scan.getStopRow());
+ } else {
+ verifyScanRanges(ptr, scan, scan.getStartRow(), scan.getStopRow());
+ }
+ } catch (ResultSetOutOfScanRangeException e) {
+ if (isLocalIndex(scan)) {
+ verifyScanRanges(ptr, scan, scan.getAttribute(SCAN_START_ROW_SUFFIX),
+ scan.getAttribute(SCAN_STOP_ROW_SUFFIX));
+ return;
+ }
+ if (scan.getAttribute(SCAN_ACTUAL_START_ROW) == null) {
+ throw e;
+ }
+ verifyScanRanges(ptr, scan, scan.getAttribute(SCAN_ACTUAL_START_ROW),
+ scan.getStopRow());
+ }
+ }
+
+ private static void verifyScanRanges(ImmutableBytesWritable ptr,
+ Scan scan,
+ byte[] startRow,
+ byte[] stopRow)
+ throws ResultSetOutOfScanRangeException {
+ if (startRow != null
+ && Bytes.compareTo(startRow, HConstants.EMPTY_START_ROW) != 0) {
+ if (scan.includeStartRow()) {
+ if (Bytes.compareTo(startRow, ptr.get()) > 0) {
+ throw new ResultSetOutOfScanRangeException(RESULT_IS_OUT_OF_SCAN_START_KEY);
+ }
+ } else {
+ if (Bytes.compareTo(startRow, ptr.get()) >= 0) {
+ throw new ResultSetOutOfScanRangeException(RESULT_IS_OUT_OF_SCAN_START_KEY);
+ }
+ }
+ }
+ if (stopRow != null
+ && Bytes.compareTo(stopRow, HConstants.EMPTY_END_ROW) != 0) {
+ if (scan.includeStopRow()) {
+ if (Bytes.compareTo(stopRow, ptr.get()) < 0) {
+ throw new ResultSetOutOfScanRangeException(RESULT_IS_OUT_OF_SCAN_STOP_KEY);
+ }
+ } else {
+ if (Bytes.compareTo(stopRow, ptr.get()) <= 0) {
+ throw new ResultSetOutOfScanRangeException(RESULT_IS_OUT_OF_SCAN_STOP_KEY);
+ }
+ }
+ }
+ }
+
+ private static void verifyScanRangesForReverseScan(ImmutableBytesWritable ptr,
+ Scan scan,
+ byte[] startRow,
+ byte[] stopRow)
+ throws ResultSetOutOfScanRangeException {
+ if (stopRow != null
+ && Bytes.compareTo(stopRow, HConstants.EMPTY_START_ROW) != 0) {
+ if (scan.includeStopRow()) {
+ if (Bytes.compareTo(stopRow, ptr.get()) > 0) {
+ throw new ResultSetOutOfScanRangeException(RESULT_IS_OUT_OF_SCAN_START_KEY);
+ }
+ } else {
+ if (Bytes.compareTo(stopRow, ptr.get()) >= 0) {
+ throw new ResultSetOutOfScanRangeException(RESULT_IS_OUT_OF_SCAN_START_KEY);
+ }
+ }
+ }
+ if (startRow != null
+ && Bytes.compareTo(startRow, HConstants.EMPTY_END_ROW) != 0) {
+ if (scan.includeStartRow()) {
+ if (Bytes.compareTo(startRow, ptr.get()) < 0) {
+ throw new ResultSetOutOfScanRangeException(RESULT_IS_OUT_OF_SCAN_STOP_KEY);
+ }
+ } else {
+ if (Bytes.compareTo(startRow, ptr.get()) <= 0) {
+ throw new ResultSetOutOfScanRangeException(RESULT_IS_OUT_OF_SCAN_STOP_KEY);
+ }
+ }
+ }
+ }
+
}
diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/util/TupleUtil.java b/phoenix-core-client/src/main/java/org/apache/phoenix/util/TupleUtil.java
index ec9bf499c4..9ea187edf2 100644
--- a/phoenix-core-client/src/main/java/org/apache/phoenix/util/TupleUtil.java
+++ b/phoenix-core-client/src/main/java/org/apache/phoenix/util/TupleUtil.java
@@ -17,23 +17,30 @@
*/
package org.apache.phoenix.util;
+import static org.apache.phoenix.query.QueryConstants.AGG_TIMESTAMP;
+import static org.apache.phoenix.query.QueryConstants.GROUPED_AGGREGATOR_VALUE_BYTES;
import static org.apache.phoenix.query.QueryConstants.SINGLE_COLUMN;
import static org.apache.phoenix.query.QueryConstants.SINGLE_COLUMN_FAMILY;
import java.io.DataOutput;
import java.io.IOException;
+import java.util.Collections;
import java.util.List;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.DoNotRetryIOException;
import org.apache.hadoop.hbase.KeyValue;
+import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.io.WritableUtils;
import org.apache.phoenix.expression.Expression;
import org.apache.phoenix.hbase.index.util.ImmutableBytesPtr;
import org.apache.phoenix.query.QueryConstants;
+import org.apache.phoenix.schema.SortOrder;
+import org.apache.phoenix.schema.tuple.ResultTuple;
import org.apache.phoenix.schema.tuple.Tuple;
+import org.apache.phoenix.schema.types.PInteger;
/**
@@ -87,7 +94,42 @@ public class TupleUtil {
}
throw new IllegalStateException("Expected single, aggregated KeyValue from coprocessor, but instead received " + r + ". Ensure aggregating coprocessors are loaded correctly on server");
}
-
+
+ public static Tuple getAggregateGroupTuple(Tuple tuple) {
+ if (tuple == null) {
+ return null;
+ }
+ if (tuple.size() == 1) {
+ Cell kv = tuple.getValue(0);
+ if (Bytes.compareTo(GROUPED_AGGREGATOR_VALUE_BYTES, 0,
+ GROUPED_AGGREGATOR_VALUE_BYTES.length,
+ kv.getFamilyArray(), kv.getFamilyOffset(), kv.getFamilyLength()) == 0) {
+ if (Bytes.compareTo(GROUPED_AGGREGATOR_VALUE_BYTES, 0,
+ GROUPED_AGGREGATOR_VALUE_BYTES.length, kv.getQualifierArray(),
+ kv.getQualifierOffset(), kv.getQualifierLength()) == 0) {
+ byte[] kvValue = new byte[kv.getValueLength()];
+ System.arraycopy(kv.getValueArray(), kv.getValueOffset(), kvValue, 0,
+ kvValue.length);
+ int sizeOfAggregateGroupValue =
+ PInteger.INSTANCE.getCodec().decodeInt(kvValue, 0,
+ SortOrder.ASC);
+ Cell result = PhoenixKeyValueUtil.newKeyValue(
+ kvValue,
+ Bytes.SIZEOF_INT,
+ sizeOfAggregateGroupValue,
+ SINGLE_COLUMN_FAMILY,
+ SINGLE_COLUMN,
+ AGG_TIMESTAMP,
+ kvValue,
+ Bytes.SIZEOF_INT + sizeOfAggregateGroupValue,
+ kvValue.length - Bytes.SIZEOF_INT - sizeOfAggregateGroupValue);
+ return new ResultTuple(Result.create(Collections.singletonList(result)));
+ }
+ }
+ }
+ return tuple;
+ }
+
/** Concatenate results evaluated against a list of expressions
*
* @param result the tuple for expression evaluation
diff --git a/phoenix-core-server/src/main/java/org/apache/phoenix/cache/aggcache/SpillableGroupByCache.java b/phoenix-core-server/src/main/java/org/apache/phoenix/cache/aggcache/SpillableGroupByCache.java
index 8c54753b0e..a753365692 100644
--- a/phoenix-core-server/src/main/java/org/apache/phoenix/cache/aggcache/SpillableGroupByCache.java
+++ b/phoenix-core-server/src/main/java/org/apache/phoenix/cache/aggcache/SpillableGroupByCache.java
@@ -19,6 +19,7 @@
package org.apache.phoenix.cache.aggcache;
import static org.apache.phoenix.query.QueryConstants.AGG_TIMESTAMP;
+import static org.apache.phoenix.query.QueryConstants.GROUPED_AGGREGATOR_VALUE_BYTES;
import static org.apache.phoenix.query.QueryConstants.SINGLE_COLUMN;
import static org.apache.phoenix.query.QueryConstants.SINGLE_COLUMN_FAMILY;
import static org.apache.phoenix.query.QueryServices.GROUPBY_MAX_CACHE_SIZE_ATTRIB;
@@ -27,11 +28,13 @@ import static org.apache.phoenix.query.QueryServicesOptions.DEFAULT_GROUPBY_MAX_
import static org.apache.phoenix.query.QueryServicesOptions.DEFAULT_GROUPBY_SPILL_FILES;
import java.io.IOException;
+import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
+import java.util.concurrent.ConcurrentMap;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.Cell;
@@ -50,6 +53,9 @@ import org.apache.phoenix.expression.aggregator.ServerAggregators;
import org.apache.phoenix.hbase.index.util.ImmutableBytesPtr;
import org.apache.phoenix.memory.InsufficientMemoryException;
import org.apache.phoenix.memory.MemoryManager.MemoryChunk;
+import org.apache.phoenix.schema.types.PInteger;
+import org.apache.phoenix.thirdparty.com.google.common.collect.Maps;
+import org.apache.phoenix.util.ByteUtil;
import org.apache.phoenix.util.Closeables;
import org.apache.phoenix.util.PhoenixKeyValueUtil;
import org.slf4j.Logger;
@@ -101,6 +107,9 @@ public class SpillableGroupByCache implements GroupByCache {
// TODO Generally better to use Collection API with generics instead of
// array types
private final LinkedHashMap<ImmutableBytesWritable, Aggregator[]> cache;
+ private final ConcurrentMap<ImmutableBytesWritable, ImmutableBytesWritable>
+ aggregateValueToLastScannedRowKeys;
+ private final boolean isIncompatibleClient;
private SpillManager spillManager = null;
private long totalNumElements;
private final ServerAggregators aggregators;
@@ -124,9 +133,12 @@ public class SpillableGroupByCache implements GroupByCache {
* @param tenantId
* @param aggs
* @param estSizeNum
+ * @param isIncompatibleClient
*/
public SpillableGroupByCache(final RegionCoprocessorEnvironment env, ImmutableBytesPtr tenantId,
- ServerAggregators aggs, final int estSizeNum) {
+ ServerAggregators aggs, final int estSizeNum,
+ boolean isIncompatibleClient) {
+ this.isIncompatibleClient = isIncompatibleClient;
totalNumElements = 0;
this.aggregators = aggs;
this.env = env;
@@ -159,6 +171,7 @@ public class SpillableGroupByCache implements GroupByCache {
LOGGER.debug("Instantiating LRU groupby cache of element size: " + maxCacheSize);
}
+ aggregateValueToLastScannedRowKeys = Maps.newConcurrentMap();
// LRU cache implemented as LinkedHashMap with access order
cache = new LinkedHashMap<ImmutableBytesWritable, Aggregator[]>(maxCacheSize, 0.75f, true) {
boolean spill = false;
@@ -358,19 +371,56 @@ public class SpillableGroupByCache implements GroupByCache {
return false;
}
Map.Entry<ImmutableBytesWritable, Aggregator[]> ce = cacheIter.next();
- ImmutableBytesWritable key = ce.getKey();
+ ImmutableBytesWritable aggregateGroupValPtr = ce.getKey();
Aggregator[] aggs = ce.getValue();
- byte[] value = aggregators.toBytes(aggs);
+ byte[] aggregateArrayBytes = aggregators.toBytes(aggs);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Adding new distinct group: "
- + Bytes.toStringBinary(key.get(), key.getOffset(), key.getLength()) +
- " with aggregators " + aggs.toString() + " value = " +
- Bytes.toStringBinary(value));
+ + Bytes.toStringBinary(aggregateGroupValPtr.get(),
+ aggregateGroupValPtr.getOffset(), aggregateGroupValPtr.getLength())
+ + " with aggregators " + Arrays.toString(aggs) + " value = "
+ + Bytes.toStringBinary(aggregateArrayBytes));
+ }
+ if (!isIncompatibleClient) {
+ ImmutableBytesWritable lastScannedRowKey =
+ aggregateValueToLastScannedRowKeys.get(aggregateGroupValPtr);
+ byte[] aggregateGroupValueBytes = new byte[aggregateGroupValPtr.getLength()];
+ System.arraycopy(aggregateGroupValPtr.get(), aggregateGroupValPtr.getOffset(),
+ aggregateGroupValueBytes, 0,
+ aggregateGroupValueBytes.length);
+ byte[] finalValue =
+ ByteUtil.concat(
+ PInteger.INSTANCE.toBytes(aggregateGroupValueBytes.length),
+ aggregateGroupValueBytes, aggregateArrayBytes);
+ results.add(
+ PhoenixKeyValueUtil.newKeyValue(
+ lastScannedRowKey.get(),
+ lastScannedRowKey.getOffset(),
+ lastScannedRowKey.getLength(),
+ GROUPED_AGGREGATOR_VALUE_BYTES,
+ GROUPED_AGGREGATOR_VALUE_BYTES,
+ AGG_TIMESTAMP,
+ finalValue,
+ 0,
+ finalValue.length));
+ } else {
+ results.add(PhoenixKeyValueUtil.newKeyValue(
+ aggregateGroupValPtr.get(),
+ aggregateGroupValPtr.getOffset(),
+ aggregateGroupValPtr.getLength(),
+ SINGLE_COLUMN_FAMILY,
+ SINGLE_COLUMN,
+ AGG_TIMESTAMP,
+ aggregateArrayBytes, 0,
+ aggregateArrayBytes.length));
}
- results.add(PhoenixKeyValueUtil.newKeyValue(key.get(), key.getOffset(), key.getLength(), SINGLE_COLUMN_FAMILY,
- SINGLE_COLUMN, AGG_TIMESTAMP, value, 0, value.length));
return cacheIter.hasNext();
}
};
}
+
+ @Override
+ public void cacheAggregateRowKey(ImmutableBytesPtr value, ImmutableBytesPtr rowKey) {
+ aggregateValueToLastScannedRowKeys.put(value, rowKey);
+ }
}
\ No newline at end of file
diff --git a/phoenix-core-server/src/main/java/org/apache/phoenix/coprocessor/BaseScannerRegionObserver.java b/phoenix-core-server/src/main/java/org/apache/phoenix/coprocessor/BaseScannerRegionObserver.java
index 9b5c9fc413..ab52dd69d4 100644
--- a/phoenix-core-server/src/main/java/org/apache/phoenix/coprocessor/BaseScannerRegionObserver.java
+++ b/phoenix-core-server/src/main/java/org/apache/phoenix/coprocessor/BaseScannerRegionObserver.java
@@ -60,10 +60,15 @@ import org.apache.phoenix.query.QueryServicesOptions;
import org.apache.phoenix.schema.StaleRegionBoundaryCacheException;
import org.apache.phoenix.util.ClientUtil;
import org.apache.phoenix.util.ScanUtil;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import static org.apache.phoenix.util.ScanUtil.getPageSizeMsForFilter;
abstract public class BaseScannerRegionObserver implements RegionObserver {
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(BaseScannerRegionObserver.class);
+
/**
* Used by logger to identify coprocessor
*/
@@ -96,12 +101,35 @@ abstract public class BaseScannerRegionObserver implements RegionObserver {
Bytes.compareTo(upperExclusiveRegionKey, expectedUpperRegionKey) != 0) ||
(actualStartRow != null && Bytes.compareTo(actualStartRow, lowerInclusiveRegionKey) < 0);
} else {
- isStaleRegionBoundaries = Bytes.compareTo(lowerInclusiveScanKey, lowerInclusiveRegionKey) < 0 ||
- ( Bytes.compareTo(upperExclusiveScanKey, upperExclusiveRegionKey) > 0 && upperExclusiveRegionKey.length != 0) ||
- (upperExclusiveRegionKey.length != 0 && upperExclusiveScanKey.length == 0);
+ if (scan.isReversed()) {
+ isStaleRegionBoundaries =
+ Bytes.compareTo(upperExclusiveScanKey, lowerInclusiveRegionKey) < 0 ||
+ (Bytes.compareTo(lowerInclusiveScanKey, upperExclusiveRegionKey) >
+ 0 && upperExclusiveRegionKey.length != 0) ||
+ (upperExclusiveRegionKey.length != 0 &&
+ lowerInclusiveScanKey.length == 0);
+ } else {
+ isStaleRegionBoundaries =
+ Bytes.compareTo(lowerInclusiveScanKey, lowerInclusiveRegionKey) < 0 ||
+ (Bytes.compareTo(upperExclusiveScanKey, upperExclusiveRegionKey) >
+ 0 && upperExclusiveRegionKey.length != 0) ||
+ (upperExclusiveRegionKey.length != 0 &&
+ upperExclusiveScanKey.length == 0);
+ }
}
if (isStaleRegionBoundaries) {
- Exception cause = new StaleRegionBoundaryCacheException(region.getRegionInfo().getTable().getNameAsString());
+ LOGGER.error("Throwing StaleRegionBoundaryCacheException due to mismatched scan "
+ + "boundaries. Region: {} , lowerInclusiveScanKey: {} , "
+ + "upperExclusiveScanKey: {} , lowerInclusiveRegionKey: {} , "
+ + "upperExclusiveRegionKey: {} , scan reversed: {}",
+ region.getRegionInfo().getRegionNameAsString(),
+ Bytes.toStringBinary(lowerInclusiveScanKey),
+ Bytes.toStringBinary(upperExclusiveScanKey),
+ Bytes.toStringBinary(lowerInclusiveRegionKey),
+ Bytes.toStringBinary(upperExclusiveRegionKey),
+ scan.isReversed());
+ Exception cause = new StaleRegionBoundaryCacheException(
+ region.getRegionInfo().getTable().getNameAsString());
throw new DoNotRetryIOException(cause.getMessage(), cause);
}
if(isLocalIndex) {
@@ -282,8 +310,14 @@ abstract public class BaseScannerRegionObserver implements RegionObserver {
// StaleRegionBoundaryCacheException to handle it by phoenix client other wise hbase
// client may recreate scans with wrong region boundaries.
if(t instanceof NotServingRegionException) {
+ LOGGER.error("postScannerOpen error for region {} . "
+ + "Thorwing it as StaleRegionBoundaryCacheException",
+ s.getRegionInfo().getRegionNameAsString(), t);
Exception cause = new StaleRegionBoundaryCacheException(c.getEnvironment().getRegion().getRegionInfo().getTable().getNameAsString());
throw new DoNotRetryIOException(cause.getMessage(), cause);
+ } else {
+ LOGGER.error("postScannerOpen error for region {}",
+ s.getRegionInfo().getRegionNameAsString(), t);
}
ClientUtil.throwIOException(c.getEnvironment().getRegion().getRegionInfo().getRegionNameAsString(), t);
return null; // impossible
diff --git a/phoenix-core-server/src/main/java/org/apache/phoenix/coprocessor/GroupByCache.java b/phoenix-core-server/src/main/java/org/apache/phoenix/coprocessor/GroupByCache.java
index 68d07a948a..0633989d1a 100644
--- a/phoenix-core-server/src/main/java/org/apache/phoenix/coprocessor/GroupByCache.java
+++ b/phoenix-core-server/src/main/java/org/apache/phoenix/coprocessor/GroupByCache.java
@@ -35,4 +35,5 @@ public interface GroupByCache extends Closeable {
long size();
Aggregator[] cache(ImmutableBytesPtr key);
RegionScanner getScanner(RegionScanner s);
+ void cacheAggregateRowKey(ImmutableBytesPtr value, ImmutableBytesPtr rowKey);
}
diff --git a/phoenix-core-server/src/main/java/org/apache/phoenix/coprocessor/GroupedAggregateRegionObserver.java b/phoenix-core-server/src/main/java/org/apache/phoenix/coprocessor/GroupedAggregateRegionObserver.java
index dc4883cfd6..29e8c0a147 100644
--- a/phoenix-core-server/src/main/java/org/apache/phoenix/coprocessor/GroupedAggregateRegionObserver.java
+++ b/phoenix-core-server/src/main/java/org/apache/phoenix/coprocessor/GroupedAggregateRegionObserver.java
@@ -18,6 +18,7 @@
package org.apache.phoenix.coprocessor;
import static org.apache.phoenix.query.QueryConstants.AGG_TIMESTAMP;
+import static org.apache.phoenix.query.QueryConstants.GROUPED_AGGREGATOR_VALUE_BYTES;
import static org.apache.phoenix.query.QueryConstants.SINGLE_COLUMN;
import static org.apache.phoenix.query.QueryConstants.SINGLE_COLUMN_FAMILY;
import static org.apache.phoenix.query.QueryServices.GROUPBY_ESTIMATED_DISTINCT_VALUES_ATTRIB;
@@ -34,18 +35,22 @@ import java.io.EOFException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
-import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
+import java.util.concurrent.ConcurrentMap;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.Cell;
+import org.apache.hadoop.hbase.CellUtil;
+import org.apache.hadoop.hbase.HConstants;
+import org.apache.hadoop.hbase.client.RegionInfo;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.coprocessor.ObserverContext;
import org.apache.hadoop.hbase.coprocessor.RegionCoprocessor;
import org.apache.hadoop.hbase.coprocessor.RegionCoprocessorEnvironment;
import org.apache.hadoop.hbase.coprocessor.RegionObserver;
+import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
import org.apache.hadoop.hbase.regionserver.Region;
import org.apache.hadoop.hbase.regionserver.RegionScanner;
import org.apache.hadoop.hbase.util.Bytes;
@@ -65,6 +70,7 @@ import org.apache.phoenix.hbase.index.util.ImmutableBytesPtr;
import org.apache.phoenix.index.IndexMaintainer;
import org.apache.phoenix.join.HashJoinInfo;
import org.apache.phoenix.memory.MemoryManager.MemoryChunk;
+import org.apache.phoenix.query.QueryServices;
import org.apache.phoenix.schema.PTable;
import org.apache.phoenix.schema.SortOrder;
import org.apache.phoenix.schema.tuple.EncodedColumnQualiferCellsList;
@@ -72,6 +78,7 @@ import org.apache.phoenix.schema.tuple.MultiKeyValueTuple;
import org.apache.phoenix.schema.tuple.PositionBasedMultiKeyValueTuple;
import org.apache.phoenix.schema.tuple.Tuple;
import org.apache.phoenix.schema.types.PInteger;
+import org.apache.phoenix.util.ByteUtil;
import org.apache.phoenix.util.Closeables;
import org.apache.phoenix.util.EncodedColumnsUtil;
import org.apache.phoenix.util.EnvironmentEdgeManager;
@@ -79,6 +86,7 @@ import org.apache.phoenix.util.IndexUtil;
import org.apache.phoenix.util.LogUtil;
import org.apache.phoenix.util.PhoenixKeyValueUtil;
import org.apache.phoenix.util.ScanUtil;
+import org.apache.phoenix.util.ServerUtil;
import org.apache.phoenix.util.SizedUtil;
import org.apache.phoenix.util.TupleUtil;
import org.slf4j.Logger;
@@ -230,10 +238,17 @@ public class GroupedAggregateRegionObserver extends BaseScannerRegionObserver im
private final ServerAggregators aggregators;
private final RegionCoprocessorEnvironment env;
private final byte[] customAnnotations;
+ private final ConcurrentMap<ImmutableBytesWritable, ImmutableBytesWritable>
+ aggregateValueToLastScannedRowKeys;
+ private final boolean isIncompatibleClient;
private int estDistVals;
- InMemoryGroupByCache(RegionCoprocessorEnvironment env, ImmutableBytesPtr tenantId, byte[] customAnnotations, ServerAggregators aggregators, int estDistVals) {
+ InMemoryGroupByCache(RegionCoprocessorEnvironment env, ImmutableBytesPtr tenantId,
+ byte[] customAnnotations, ServerAggregators aggregators,
+ int estDistVals,
+ boolean isIncompatibleClient) {
+ this.isIncompatibleClient = isIncompatibleClient;
int estValueSize = aggregators.getEstimatedByteSize();
long estSize = sizeOfUnorderedGroupByMap(estDistVals, estValueSize);
TenantCache tenantCache = GlobalCache.getTenantCache(env, tenantId);
@@ -243,6 +258,7 @@ public class GroupedAggregateRegionObserver extends BaseScannerRegionObserver im
this.aggregateMap = Maps.newHashMapWithExpectedSize(estDistVals);
this.chunk = tenantCache.getMemoryManager().allocate(estSize);
this.customAnnotations = customAnnotations;
+ aggregateValueToLastScannedRowKeys = Maps.newConcurrentMap();
}
@Override
@@ -284,26 +300,53 @@ public class GroupedAggregateRegionObserver extends BaseScannerRegionObserver im
final List<Cell> aggResults = new ArrayList<Cell>(aggregateMap.size());
- final Iterator<Map.Entry<ImmutableBytesPtr, Aggregator[]>> cacheIter =
- aggregateMap.entrySet().iterator();
- while (cacheIter.hasNext()) {
- Map.Entry<ImmutableBytesPtr, Aggregator[]> entry = cacheIter.next();
- ImmutableBytesPtr key = entry.getKey();
+ for (Map.Entry<ImmutableBytesPtr, Aggregator[]> entry : aggregateMap.entrySet()) {
+ ImmutableBytesWritable aggregateGroupValPtr = entry.getKey();
Aggregator[] rowAggregators = entry.getValue();
// Generate byte array of Aggregators and set as value of row
- byte[] value = aggregators.toBytes(rowAggregators);
-
+ byte[] aggregateArrayBytes = aggregators.toBytes(rowAggregators);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(LogUtil.addCustomAnnotations("Adding new distinct group: "
- + Bytes.toStringBinary(key.get(), key.getOffset(), key.getLength())
- + " with aggregators " + Arrays.asList(rowAggregators).toString()
- + " value = " + Bytes.toStringBinary(value), customAnnotations));
+ + Bytes.toStringBinary(aggregateGroupValPtr.get(),
+ aggregateGroupValPtr.getOffset(), aggregateGroupValPtr.getLength())
+ + " with aggregators " + Arrays.asList(rowAggregators) + " value = "
+ + Bytes.toStringBinary(aggregateArrayBytes), customAnnotations));
+ }
+ if (!isIncompatibleClient) {
+ ImmutableBytesWritable lastScannedRowKey =
+ aggregateValueToLastScannedRowKeys.get(aggregateGroupValPtr);
+ byte[] aggregateGroupValueBytes = new byte[aggregateGroupValPtr.getLength()];
+ System.arraycopy(aggregateGroupValPtr.get(), aggregateGroupValPtr.getOffset(),
+ aggregateGroupValueBytes, 0,
+ aggregateGroupValueBytes.length);
+ byte[] finalValue =
+ ByteUtil.concat(
+ PInteger.INSTANCE.toBytes(aggregateGroupValueBytes.length),
+ aggregateGroupValueBytes, aggregateArrayBytes);
+ aggResults.add(
+ PhoenixKeyValueUtil.newKeyValue(
+ lastScannedRowKey.get(),
+ lastScannedRowKey.getOffset(),
+ lastScannedRowKey.getLength(),
+ GROUPED_AGGREGATOR_VALUE_BYTES,
+ GROUPED_AGGREGATOR_VALUE_BYTES,
+ AGG_TIMESTAMP,
+ finalValue,
+ 0,
+ finalValue.length));
+ } else {
+ aggResults.add(
+ PhoenixKeyValueUtil.newKeyValue(
+ aggregateGroupValPtr.get(),
+ aggregateGroupValPtr.getOffset(),
+ aggregateGroupValPtr.getLength(),
+ SINGLE_COLUMN_FAMILY,
+ SINGLE_COLUMN,
+ AGG_TIMESTAMP,
+ aggregateArrayBytes,
+ 0,
+ aggregateArrayBytes.length));
}
- Cell keyValue =
- PhoenixKeyValueUtil.newKeyValue(key.get(), key.getOffset(), key.getLength(),
- SINGLE_COLUMN_FAMILY, SINGLE_COLUMN, AGG_TIMESTAMP, value, 0,
- value.length);
- aggResults.add(keyValue);
}
// scanner using the non spillable, memory-only implementation
return new BaseRegionScanner(s) {
@@ -330,6 +373,11 @@ public class GroupedAggregateRegionObserver extends BaseScannerRegionObserver im
};
}
+ @Override
+ public void cacheAggregateRowKey(ImmutableBytesPtr value, ImmutableBytesPtr rowKey) {
+ aggregateValueToLastScannedRowKeys.put(value, rowKey);
+ }
+
@Override
public long size() {
return aggregateMap.size();
@@ -343,15 +391,21 @@ public class GroupedAggregateRegionObserver extends BaseScannerRegionObserver im
private GroupByCacheFactory() {
}
- GroupByCache newCache(RegionCoprocessorEnvironment env, ImmutableBytesPtr tenantId, byte[] customAnnotations, ServerAggregators aggregators, int estDistVals) {
+ GroupByCache newCache(RegionCoprocessorEnvironment env,
+ ImmutableBytesPtr tenantId,
+ byte[] customAnnotations,
+ ServerAggregators aggregators,
+ int estDistVals,
+ boolean isIncompatibleClient) {
Configuration conf = env.getConfiguration();
boolean spillableEnabled =
conf.getBoolean(GROUPBY_SPILLABLE_ATTRIB, DEFAULT_GROUPBY_SPILLABLE);
if (spillableEnabled) {
- return new SpillableGroupByCache(env, tenantId, aggregators, estDistVals);
+ return new SpillableGroupByCache(env, tenantId, aggregators, estDistVals,
+ isIncompatibleClient);
}
-
- return new InMemoryGroupByCache(env, tenantId, customAnnotations, aggregators, estDistVals);
+ return new InMemoryGroupByCache(env, tenantId, customAnnotations, aggregators,
+ estDistVals, isIncompatibleClient);
}
}
@@ -371,12 +425,29 @@ public class GroupedAggregateRegionObserver extends BaseScannerRegionObserver im
private final long pageSizeMs;
private RegionScanner regionScanner = null;
private final GroupByCache groupByCache;
+ private final Scan scan;
+ private final byte[] scanStartRowKey;
+ private final boolean includeStartRowKey;
+ private final byte[] actualScanStartRowKey;
+ private final boolean actualScanIncludeStartRowKey;
+ private boolean firstScan = true;
+ private boolean skipValidRowsSent = false;
+ private byte[] lastReturnedRowKey = null;
private UnorderedGroupByRegionScanner(final ObserverContext<RegionCoprocessorEnvironment> c,
final Scan scan, final RegionScanner scanner, final List<Expression> expressions,
final ServerAggregators aggregators, final long limit, final long pageSizeMs) {
super(scanner);
this.region = c.getEnvironment().getRegion();
+ this.scan = scan;
+ scanStartRowKey =
+ ServerUtil.getScanStartRowKeyFromScanOrRegionBoundaries(scan, region);
+ includeStartRowKey = scan.includeStartRow();
+ // Retrieve start rowkey of the previous scan. This would be different than
+ // current scan start rowkey if the region has recently moved or split or merged.
+ this.actualScanStartRowKey =
+ scan.getAttribute(BaseScannerRegionObserverConstants.SCAN_ACTUAL_START_ROW);
+ this.actualScanIncludeStartRowKey = true;
this.aggregators = aggregators;
this.limit = limit;
this.pageSizeMs = pageSizeMs;
@@ -395,9 +466,11 @@ public class GroupedAggregateRegionObserver extends BaseScannerRegionObserver im
useQualifierAsIndex = EncodedColumnsUtil.useQualifierAsIndex(EncodedColumnsUtil.getMinMaxQualifiersFromScan(scan));
final boolean spillableEnabled = conf.getBoolean(GROUPBY_SPILLABLE_ATTRIB, DEFAULT_GROUPBY_SPILLABLE);
encodingScheme = EncodedColumnsUtil.getQualifierEncodingScheme(scan);
-
+ final boolean isIncompatibleClient =
+ ScanUtil.isIncompatibleClientForServerReturnValidRowKey(scan);
groupByCache = GroupByCacheFactory.INSTANCE.newCache(
- env, ScanUtil.getTenantId(scan), ScanUtil.getCustomAnnotations(scan), aggregators, estDistVals);
+ env, ScanUtil.getTenantId(scan), ScanUtil.getCustomAnnotations(scan),
+ aggregators, estDistVals, isIncompatibleClient);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(LogUtil.addCustomAnnotations(
"Grouped aggregation over unordered rows with scan " + scan
@@ -411,6 +484,132 @@ public class GroupedAggregateRegionObserver extends BaseScannerRegionObserver im
@Override
public boolean next(List<Cell> resultsToReturn) throws IOException {
+ if (firstScan && actualScanStartRowKey != null) {
+ if (scanStartRowKey.length > 0 && !ScanUtil.isLocalIndex(scan)) {
+ if (hasRegionMoved()) {
+ LOGGER.info("Region has moved.. Actual scan start rowkey {} is not same "
+ + "as current scan start rowkey {}",
+ Bytes.toStringBinary(actualScanStartRowKey),
+ Bytes.toStringBinary(scanStartRowKey));
+ // If region has moved in the middle of the scan operation, after resetting
+ // the scanner, hbase client uses (latest received rowkey + \x00) as new
+ // start rowkey for resuming the scan operation on the new scanner.
+ if (Bytes.compareTo(
+ ByteUtil.concat(actualScanStartRowKey, ByteUtil.ZERO_BYTE),
+ scanStartRowKey) == 0) {
+ scan.setAttribute(QueryServices.PHOENIX_PAGING_NEW_SCAN_START_ROWKEY,
+ actualScanStartRowKey);
+ scan.setAttribute(
+ QueryServices.PHOENIX_PAGING_NEW_SCAN_START_ROWKEY_INCLUDE,
+ Bytes.toBytes(actualScanIncludeStartRowKey));
+ } else {
+ // This happens when the server side scanner has already sent some
+ // rows back to the client and region has moved, so now we need to
+ // use skipValidRowsSent flag and also reset the scanner
+ // at paging region scanner level to re-read the previously sent
+ // values in order to re-compute the aggregation and then return
+ // only the next rowkey that was not yet sent back to the client.
+ skipValidRowsSent = true;
+ scan.setAttribute(QueryServices.PHOENIX_PAGING_NEW_SCAN_START_ROWKEY,
+ actualScanStartRowKey);
+ scan.setAttribute(
+ QueryServices.PHOENIX_PAGING_NEW_SCAN_START_ROWKEY_INCLUDE,
+ Bytes.toBytes(actualScanIncludeStartRowKey));
+ }
+ }
+ }
+ }
+ if (firstScan) {
+ firstScan = false;
+ }
+ boolean moreRows = nextInternal(resultsToReturn);
+ if (ScanUtil.isDummy(resultsToReturn)) {
+ return true;
+ }
+ if (skipValidRowsSent) {
+ while (true) {
+ if (!moreRows) {
+ skipValidRowsSent = false;
+ if (resultsToReturn.size() > 0) {
+ lastReturnedRowKey = CellUtil.cloneRow(resultsToReturn.get(0));
+ }
+ return moreRows;
+ }
+ Cell firstCell = resultsToReturn.get(0);
+ byte[] resultRowKey = new byte[firstCell.getRowLength()];
+ System.arraycopy(firstCell.getRowArray(), firstCell.getRowOffset(),
+ resultRowKey, 0, resultRowKey.length);
+ // In case of regular scans, if the region moves and scanner is reset,
+ // hbase client checks the last returned row by the server, gets the
+ // rowkey and appends "\x00" byte, before resuming the scan. With this,
+ // scan includeStartRowKey is set to true.
+ // However, same is not the case with reverse scans. For the reverse scan,
+ // hbase client checks the last returned row by the server, gets the
+ // rowkey and treats it as startRowKey for resuming the scan. With this,
+ // scan includeStartRowKey is set to false.
+ // Hence, we need to cover both cases here.
+ if (Bytes.compareTo(resultRowKey, scanStartRowKey) == 0) {
+ // This can be true for reverse scan case.
+ skipValidRowsSent = false;
+ if (includeStartRowKey) {
+ if (resultsToReturn.size() > 0) {
+ lastReturnedRowKey = CellUtil.cloneRow(resultsToReturn.get(0));
+ }
+ return moreRows;
+ }
+ // If includeStartRowKey is false and the current rowkey is matching
+ // with scanStartRowKey, return the next row result.
+ resultsToReturn.clear();
+ moreRows = nextInternal(resultsToReturn);
+ if (ScanUtil.isDummy(resultsToReturn)) {
+ return true;
+ }
+ if (resultsToReturn.size() > 0) {
+ lastReturnedRowKey = CellUtil.cloneRow(resultsToReturn.get(0));
+ }
+ return moreRows;
+ } else if (
+ Bytes.compareTo(
+ ByteUtil.concat(resultRowKey, ByteUtil.ZERO_BYTE),
+ scanStartRowKey) == 0) {
+ // This can be true for regular scan case.
+ skipValidRowsSent = false;
+ if (includeStartRowKey) {
+ // If includeStartRowKey is true and the (current rowkey + "\0xx") is
+ // matching with scanStartRowKey, return the next row result.
+ resultsToReturn.clear();
+ moreRows = nextInternal(resultsToReturn);
+ if (ScanUtil.isDummy(resultsToReturn)) {
+ return true;
+ }
+ if (resultsToReturn.size() > 0) {
+ lastReturnedRowKey = CellUtil.cloneRow(resultsToReturn.get(0));
+ }
+ return moreRows;
+ }
+ }
+ // In the loop, keep iterating through rows.
+ resultsToReturn.clear();
+ moreRows = nextInternal(resultsToReturn);
+ if (ScanUtil.isDummy(resultsToReturn)) {
+ return true;
+ }
+ }
+ }
+ if (resultsToReturn.size() > 0) {
+ lastReturnedRowKey = CellUtil.cloneRow(resultsToReturn.get(0));
+ }
+ return moreRows;
+ }
+
+ /**
+ * Perform the next operation to grab the next row's worth of values.
+ *
+ * @param resultsToReturn output list of cells that are read as part of this operation.
+ * @return true if more rows exist after this one, false if scanner is done.
+ * @throws IOException if something goes wrong.
+ */
+ private boolean nextInternal(List<Cell> resultsToReturn) throws IOException {
boolean hasMore;
long startTime = EnvironmentEdgeManager.currentTimeMillis();
long now;
@@ -436,24 +635,24 @@ public class GroupedAggregateRegionObserver extends BaseScannerRegionObserver im
hasMore = delegate.nextRaw(results);
if (!results.isEmpty()) {
if (isDummy(results)) {
- getDummyResult(resultsToReturn);
- return true;
+ return getDummyResult(resultsToReturn);
}
result.setKeyValues(results);
ImmutableBytesPtr key =
TupleUtil.getConcatenatedValue(result, expressions);
+ ImmutableBytesPtr originalRowKey = new ImmutableBytesPtr();
+ result.getKey(originalRowKey);
Aggregator[] rowAggregators = groupByCache.cache(key);
+ groupByCache.cacheAggregateRowKey(key, originalRowKey);
// Aggregate values here
aggregators.aggregate(rowAggregators, result);
}
now = EnvironmentEdgeManager.currentTimeMillis();
- } while (hasMore && groupByCache.size() < limit && (now - startTime) < pageSizeMs);
- if (hasMore && groupByCache.size() < limit && (now - startTime) >= pageSizeMs) {
- // Return a dummy result as we have processed a page worth of rows
- // but we are not ready to aggregate
- getDummyResult(resultsToReturn);
- return true;
- }
+ if (hasMore && groupByCache.size() < limit
+ && (now - startTime) >= pageSizeMs) {
+ return getDummyResult(resultsToReturn);
+ }
+ } while (hasMore && groupByCache.size() < limit);
regionScanner = groupByCache.getScanner(delegate);
// Do not sort here, but sort back on the client instead
// The reason is that if the scan ever extends beyond a region
@@ -461,11 +660,68 @@ public class GroupedAggregateRegionObserver extends BaseScannerRegionObserver im
// points on old metadata), we'll get incorrect query results.
return regionScanner.next(resultsToReturn);
}
+ } catch (Exception e) {
+ LOGGER.error("Unordered group-by scanner next encountered error for region {}",
+ region.getRegionInfo().getRegionNameAsString(), e);
+ if (e instanceof IOException) {
+ throw e;
+ } else {
+ throw new IOException(e);
+ }
} finally {
if (acquiredLock) region.closeRegionOperation();
}
}
+ /**
+ * Retrieve dummy rowkey and return to the client.
+ *
+ * @param resultsToReturn dummy cell.
+ * @return always true, because some rows are likely to exist as we are returning
+ * dummy result to the client.
+ */
+ private boolean getDummyResult(List<Cell> resultsToReturn) {
+ if (lastReturnedRowKey != null) {
+ ScanUtil.getDummyResult(lastReturnedRowKey, resultsToReturn);
+ return true;
+ }
+ if (scanStartRowKey.length > 0 && !ScanUtil.isLocalIndex(scan)) {
+ if (hasRegionMoved()) {
+ byte[] lastByte =
+ new byte[]{scanStartRowKey[scanStartRowKey.length - 1]};
+ if (scanStartRowKey.length > 1 && Bytes.compareTo(lastByte,
+ ByteUtil.ZERO_BYTE) == 0) {
+ byte[] prevKey = new byte[scanStartRowKey.length - 1];
+ System.arraycopy(scanStartRowKey, 0, prevKey, 0,
+ prevKey.length);
+ ScanUtil.getDummyResult(prevKey, resultsToReturn);
+ } else {
+ ScanUtil.getDummyResult(scanStartRowKey,
+ resultsToReturn);
+ }
+ } else {
+ ScanUtil.getDummyResult(scanStartRowKey, resultsToReturn);
+ }
+ } else {
+ ScanUtil.getDummyResult(scanStartRowKey, resultsToReturn);
+ }
+ return true;
+ }
+
+ /**
+ * Return true if the region has moved in the middle of an ongoing scan operation,
+ * resulting in scanner reset. Based on the return value of this function, we need to
+ * either scan the region as if we are scanning for the first time or we need to scan
+ * the region considering that we have already returned some rows back to client and
+ * we need to resume from the last row that we returned to the client.
+ *
+ * @return true if the region has moved in the middle of an ongoing scan operation.
+ */
+ private boolean hasRegionMoved() {
+ return Bytes.compareTo(actualScanStartRowKey, scanStartRowKey) != 0
+ || actualScanIncludeStartRowKey != includeStartRowKey;
+ }
+
@Override
public void close() throws IOException {
if (regionScanner != null) {
@@ -492,12 +748,18 @@ public class GroupedAggregateRegionObserver extends BaseScannerRegionObserver im
private final long pageSizeMs;
private long rowCount = 0;
private ImmutableBytesPtr currentKey = null;
+ private final ImmutableBytesPtr currentKeyRowKey = new ImmutableBytesPtr();
+ private final boolean isIncompatibleClient;
+ private final byte[] initStartRowKey;
+ private final boolean includeInitStartRowKey;
+ private byte[] previousResultRowKey;
private OrderedGroupByRegionScanner(final ObserverContext<RegionCoprocessorEnvironment> c,
final Scan scan, final RegionScanner scanner, final List<Expression> expressions,
final ServerAggregators aggregators, final long limit, final long pageSizeMs) {
super(scanner);
this.scan = scan;
+ isIncompatibleClient = ScanUtil.isIncompatibleClientForServerReturnValidRowKey(scan);
this.aggregators = aggregators;
this.limit = limit;
this.pageSizeMs = pageSizeMs;
@@ -506,6 +768,9 @@ public class GroupedAggregateRegionObserver extends BaseScannerRegionObserver im
minMaxQualifiers = EncodedColumnsUtil.getMinMaxQualifiersFromScan(scan);
useQualifierAsIndex = EncodedColumnsUtil.useQualifierAsIndex(minMaxQualifiers);
encodingScheme = EncodedColumnsUtil.getQualifierEncodingScheme(scan);
+ initStartRowKey = ServerUtil.getScanStartRowKeyFromScanOrRegionBoundaries(scan,
+ region);
+ includeInitStartRowKey = scan.includeStartRow();
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(LogUtil.addCustomAnnotations(
"Grouped aggregation over ordered rows with scan " + scan + ", group by "
@@ -513,6 +778,7 @@ public class GroupedAggregateRegionObserver extends BaseScannerRegionObserver im
ScanUtil.getCustomAnnotations(scan)));
}
}
+
@Override
public boolean next(List<Cell> results) throws IOException {
boolean hasMore;
@@ -544,7 +810,8 @@ public class GroupedAggregateRegionObserver extends BaseScannerRegionObserver im
hasMore = delegate.nextRaw(kvs);
if (!kvs.isEmpty()) {
if (isDummy(kvs)) {
- getDummyResult(results);
+ updateDummyWithPrevRowKey(results, initStartRowKey,
+ includeInitStartRowKey, scan);
return true;
}
result.setKeyValues(kvs);
@@ -560,6 +827,9 @@ public class GroupedAggregateRegionObserver extends BaseScannerRegionObserver im
ScanUtil.getCustomAnnotations(scan)));
}
currentKey = key;
+ if (result.size() > 0) {
+ result.getKey(currentKeyRowKey);
+ }
}
}
atLimit = rowCount + countOffset >= limit;
@@ -568,41 +838,150 @@ public class GroupedAggregateRegionObserver extends BaseScannerRegionObserver im
now = EnvironmentEdgeManager.currentTimeMillis();
} while (hasMore && !aggBoundary && !atLimit && (now - startTime) < pageSizeMs);
}
+ } catch (Exception e) {
+ LOGGER.error("Ordered group-by scanner next encountered error for region {}",
+ region.getRegionInfo().getRegionNameAsString(), e);
+ if (e instanceof IOException) {
+ throw e;
+ } else {
+ throw new IOException(e);
+ }
} finally {
if (acquiredLock) region.closeRegionOperation();
}
- if (hasMore && !aggBoundary && !atLimit && (now - startTime) >= pageSizeMs) {
- // Return a dummy result as we have processed a page worth of rows
- // but we are not ready to aggregate
- getDummyResult(results);
- return true;
- }
- if (currentKey != null) {
- byte[] value = aggregators.toBytes(rowAggregators);
- Cell keyValue =
- PhoenixKeyValueUtil.newKeyValue(currentKey.get(), currentKey.getOffset(),
- currentKey.getLength(), SINGLE_COLUMN_FAMILY, SINGLE_COLUMN,
- AGG_TIMESTAMP, value, 0, value.length);
- results.add(keyValue);
- // If we're at an aggregation boundary, reset the
- // aggregators and
- // aggregate with the current result (which is not a part of
- // the returned result).
- if (aggBoundary) {
- aggregators.reset(rowAggregators);
- aggregators.aggregate(rowAggregators, result);
- currentKey = key;
- rowCount++;
- atLimit |= rowCount >= limit;
+ try {
+ if (hasMore && !aggBoundary && !atLimit && (now - startTime) >= pageSizeMs) {
+ updateDummyWithPrevRowKey(results, initStartRowKey,
+ includeInitStartRowKey, scan);
+ return true;
+ }
+ if (currentKey != null) {
+ if (!isIncompatibleClient) {
+ byte[] aggregateArrayBytes = aggregators.toBytes(rowAggregators);
+ byte[] aggregateGroupValueBytes = new byte[currentKey.getLength()];
+ System.arraycopy(currentKey.get(), currentKey.getOffset(),
+ aggregateGroupValueBytes, 0,
+ aggregateGroupValueBytes.length);
+ byte[] finalValue =
+ ByteUtil.concat(
+ PInteger.INSTANCE.toBytes(aggregateGroupValueBytes.length),
+ aggregateGroupValueBytes, aggregateArrayBytes);
+ Cell keyValue =
+ PhoenixKeyValueUtil.newKeyValue(
+ currentKeyRowKey.get(),
+ currentKeyRowKey.getOffset(),
+ currentKeyRowKey.getLength(),
+ GROUPED_AGGREGATOR_VALUE_BYTES,
+ GROUPED_AGGREGATOR_VALUE_BYTES,
+ AGG_TIMESTAMP,
+ finalValue,
+ 0,
+ finalValue.length);
+ results.add(keyValue);
+ } else {
+ byte[] value = aggregators.toBytes(rowAggregators);
+ Cell keyValue =
+ PhoenixKeyValueUtil.newKeyValue(
+ currentKey.get(),
+ currentKey.getOffset(),
+ currentKey.getLength(),
+ SINGLE_COLUMN_FAMILY,
+ SINGLE_COLUMN,
+ AGG_TIMESTAMP,
+ value,
+ 0,
+ value.length);
+ results.add(keyValue);
+ }
+ // If we're at an aggregation boundary, reset the
+ // aggregators and
+ // aggregate with the current result (which is not a part of
+ // the returned result).
+ if (aggBoundary) {
+ aggregators.reset(rowAggregators);
+ aggregators.aggregate(rowAggregators, result);
+ currentKey = key;
+ if (result.size() > 0) {
+ result.getKey(currentKeyRowKey);
+ }
+ rowCount++;
+ atLimit |= rowCount >= limit;
+ }
+ }
+ // Continue if there are more
+ if (!atLimit && (hasMore || aggBoundary)) {
+ if (!results.isEmpty()) {
+ previousResultRowKey = CellUtil.cloneRow(results.get(results.size() - 1));
+ }
+ return true;
+ }
+ currentKey = null;
+ return false;
+ } catch (Exception e) {
+ LOGGER.error("Ordered group-by scanner next encountered some issue for"
+ + " region {}", region.getRegionInfo().getRegionNameAsString(), e);
+ if (e instanceof IOException) {
+ throw e;
+ } else {
+ throw new IOException(e);
}
}
- // Continue if there are more
- if (!atLimit && (hasMore || aggBoundary)) {
- return true;
+ }
+
+ /**
+ * Add dummy cell to the result list based on either the previous rowkey returned to the
+ * client or the start rowkey and start rowkey include params.
+ *
+ * @param result result to add the dummy cell to.
+ * @param initStartRowKey scan start rowkey.
+ * @param includeInitStartRowKey scan start rowkey included.
+ * @param scan scan object.
+ */
+ private void updateDummyWithPrevRowKey(List<Cell> result, byte[] initStartRowKey,
+ boolean includeInitStartRowKey, Scan scan) {
+ result.clear();
+ if (previousResultRowKey != null) {
+ getDummyResult(previousResultRowKey, result);
+ } else {
+ if (includeInitStartRowKey && initStartRowKey.length > 0) {
+ byte[] prevKey;
+ // In order to generate largest possible rowkey that is less than
+ // initStartRowKey, we need to check size of the region name that can be
+ // used by hbase client for meta lookup, in case meta cache is expired at
+ // client.
+ // Once we know regionLookupInMetaLen, use it to generate largest possible
+ // rowkey that is lower than initStartRowKey by using
+ // ByteUtil#previousKeyWithLength function, which appends "\\xFF" bytes to
+ // prev rowkey upto the length provided. e.g. for the given key
+ // "\\x01\\xC1\\x06", the previous key with length 5 would be
+ // "\\x01\\xC1\\x05\\xFF\\xFF" by padding 2 bytes "\\xFF".
+ // The length of the largest scan start rowkey should not exceed
+ // HConstants#MAX_ROW_LENGTH.
+ int regionLookupInMetaLen =
+ RegionInfo.createRegionName(region.getTableDescriptor().getTableName(),
+ new byte[1], HConstants.NINES, false).length;
+ if (Bytes.compareTo(initStartRowKey, initStartRowKey.length - 1,
+ 1, ByteUtil.ZERO_BYTE, 0, 1) == 0) {
+ // If initStartRowKey has last byte as "\\x00", we can discard the last
+ // byte and send the key as dummy rowkey.
+ prevKey = new byte[initStartRowKey.length - 1];
+ System.arraycopy(initStartRowKey, 0, prevKey, 0, prevKey.length);
+ } else if (initStartRowKey.length < (HConstants.MAX_ROW_LENGTH - 1
+ - regionLookupInMetaLen)) {
+ prevKey = ByteUtil.previousKeyWithLength(ByteUtil.concat(initStartRowKey,
+ new byte[HConstants.MAX_ROW_LENGTH - initStartRowKey.length
+ - 1 - regionLookupInMetaLen]),
+ HConstants.MAX_ROW_LENGTH - 1 - regionLookupInMetaLen);
+ } else {
+ prevKey = initStartRowKey;
+ }
+ getDummyResult(prevKey, result);
+ } else {
+ getDummyResult(initStartRowKey, result);
+ }
}
- currentKey = null;
- return false;
}
+
}
@Override
diff --git a/phoenix-core-server/src/main/java/org/apache/phoenix/coprocessor/IndexRebuildRegionScanner.java b/phoenix-core-server/src/main/java/org/apache/phoenix/coprocessor/IndexRebuildRegionScanner.java
index ceee4533c8..9b7402149f 100644
--- a/phoenix-core-server/src/main/java/org/apache/phoenix/coprocessor/IndexRebuildRegionScanner.java
+++ b/phoenix-core-server/src/main/java/org/apache/phoenix/coprocessor/IndexRebuildRegionScanner.java
@@ -33,6 +33,7 @@ import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
+import org.apache.hadoop.hbase.HConstants;
import org.apache.phoenix.coprocessorclient.BaseScannerRegionObserverConstants;
import org.apache.phoenix.thirdparty.com.google.common.annotations.VisibleForTesting;
import org.apache.hadoop.hbase.Cell;
@@ -57,6 +58,7 @@ import org.apache.phoenix.mapreduce.index.IndexTool;
import org.apache.phoenix.schema.types.PLong;
import org.apache.phoenix.util.ClientUtil;
import org.apache.phoenix.util.PhoenixKeyValueUtil;
+import org.apache.phoenix.util.ScanUtil;
import org.apache.phoenix.thirdparty.com.google.common.collect.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -279,9 +281,30 @@ public class IndexRebuildRegionScanner extends GlobalIndexRegionScanner {
if (indexRowKeyforReadRepair != null &&
singleRowRebuildReturnCode == GlobalIndexChecker.RebuildReturnCode.NO_DATA_ROW.getValue()) {
byte[] rowCountBytes =
- PLong.INSTANCE.toBytes(Long.valueOf(singleRowRebuildReturnCode));
- final Cell aggKeyValue = PhoenixKeyValueUtil.newKeyValue(UNGROUPED_AGG_ROW_KEY,
- SINGLE_COLUMN_FAMILY,
+ PLong.INSTANCE.toBytes((long) singleRowRebuildReturnCode);
+ byte[] rowKey;
+ byte[] startKey = scan.getStartRow().length > 0 ? scan.getStartRow() :
+ region.getRegionInfo().getStartKey();
+ byte[] endKey = scan.getStopRow().length > 0 ? scan.getStopRow() :
+ region.getRegionInfo().getEndKey();
+ final boolean isIncompatibleClient =
+ ScanUtil.isIncompatibleClientForServerReturnValidRowKey(scan);
+ if (!isIncompatibleClient) {
+ rowKey = ByteUtil.getLargestPossibleRowKeyInRange(startKey, endKey);
+ if (rowKey == null) {
+ if (scan.includeStartRow()) {
+ rowKey = startKey;
+ } else if (scan.includeStopRow()) {
+ rowKey = endKey;
+ } else {
+ rowKey = HConstants.EMPTY_END_ROW;
+ }
+ }
+ } else {
+ rowKey = UNGROUPED_AGG_ROW_KEY;
+ }
+ final Cell aggKeyValue = PhoenixKeyValueUtil.newKeyValue(rowKey,
+ SINGLE_COLUMN_FAMILY,
SINGLE_COLUMN, AGG_TIMESTAMP, rowCountBytes, 0, rowCountBytes.length);
results.add(aggKeyValue);
return false;
@@ -371,11 +394,32 @@ public class IndexRebuildRegionScanner extends GlobalIndexRegionScanner {
if (minTimestamp != 0) {
nextStartKey = ByteUtil.calculateTheClosestNextRowKeyForPrefix(CellUtil.cloneRow(lastCell));
}
- byte[] rowCountBytes = PLong.INSTANCE.toBytes(Long.valueOf(dataRowCount));
+ byte[] rowCountBytes = PLong.INSTANCE.toBytes((long) dataRowCount);
final Cell aggKeyValue;
if (lastCell == null) {
- aggKeyValue = PhoenixKeyValueUtil.newKeyValue(UNGROUPED_AGG_ROW_KEY,
- SINGLE_COLUMN_FAMILY,
+ byte[] rowKey;
+ byte[] startKey = scan.getStartRow().length > 0 ? scan.getStartRow() :
+ region.getRegionInfo().getStartKey();
+ byte[] endKey = scan.getStopRow().length > 0 ? scan.getStopRow() :
+ region.getRegionInfo().getEndKey();
+ final boolean isIncompatibleClient =
+ ScanUtil.isIncompatibleClientForServerReturnValidRowKey(scan);
+ if (!isIncompatibleClient) {
+ rowKey = ByteUtil.getLargestPossibleRowKeyInRange(startKey, endKey);
+ if (rowKey == null) {
+ if (scan.includeStartRow()) {
+ rowKey = startKey;
+ } else if (scan.includeStopRow()) {
+ rowKey = endKey;
+ } else {
+ rowKey = HConstants.EMPTY_END_ROW;
+ }
+ }
+ } else {
+ rowKey = UNGROUPED_AGG_ROW_KEY;
+ }
+ aggKeyValue = PhoenixKeyValueUtil.newKeyValue(rowKey,
+ SINGLE_COLUMN_FAMILY,
SINGLE_COLUMN, AGG_TIMESTAMP, rowCountBytes, 0, rowCountBytes.length);
} else {
aggKeyValue = PhoenixKeyValueUtil.newKeyValue(CellUtil.cloneRow(lastCell),
diff --git a/phoenix-core-server/src/main/java/org/apache/phoenix/coprocessor/IndexRepairRegionScanner.java b/phoenix-core-server/src/main/java/org/apache/phoenix/coprocessor/IndexRepairRegionScanner.java
index 8ce273ceeb..74c8e2edf6 100644
--- a/phoenix-core-server/src/main/java/org/apache/phoenix/coprocessor/IndexRepairRegionScanner.java
+++ b/phoenix-core-server/src/main/java/org/apache/phoenix/coprocessor/IndexRepairRegionScanner.java
@@ -33,6 +33,7 @@ import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
+import org.apache.hadoop.hbase.HConstants;
import org.apache.phoenix.thirdparty.com.google.common.collect.Lists;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CellUtil;
@@ -62,6 +63,7 @@ import org.apache.phoenix.schema.types.PLong;
import org.apache.phoenix.schema.types.PVarbinary;
import org.apache.phoenix.util.ClientUtil;
import org.apache.phoenix.util.PhoenixKeyValueUtil;
+import org.apache.phoenix.util.ScanUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -442,10 +444,31 @@ public class IndexRepairRegionScanner extends GlobalIndexRegionScanner {
if (minTimestamp != 0) {
nextStartKey = ByteUtil.calculateTheClosestNextRowKeyForPrefix(CellUtil.cloneRow(lastCell));
}
- byte[] rowCountBytes = PLong.INSTANCE.toBytes(Long.valueOf(rowCount));
+ byte[] rowCountBytes = PLong.INSTANCE.toBytes((long) rowCount);
final Cell aggKeyValue;
if (lastCell == null) {
- aggKeyValue = PhoenixKeyValueUtil.newKeyValue(UNGROUPED_AGG_ROW_KEY,
+ byte[] rowKey;
+ byte[] startKey = scan.getStartRow().length > 0 ? scan.getStartRow() :
+ region.getRegionInfo().getStartKey();
+ byte[] endKey = scan.getStopRow().length > 0 ? scan.getStopRow() :
+ region.getRegionInfo().getEndKey();
+ final boolean isIncompatibleClient =
+ ScanUtil.isIncompatibleClientForServerReturnValidRowKey(scan);
+ if (!isIncompatibleClient) {
+ rowKey = ByteUtil.getLargestPossibleRowKeyInRange(startKey, endKey);
+ if (rowKey == null) {
+ if (scan.includeStartRow()) {
+ rowKey = startKey;
+ } else if (scan.includeStopRow()) {
+ rowKey = endKey;
+ } else {
+ rowKey = HConstants.EMPTY_END_ROW;
+ }
+ }
+ } else {
+ rowKey = UNGROUPED_AGG_ROW_KEY;
+ }
+ aggKeyValue = PhoenixKeyValueUtil.newKeyValue(rowKey,
SINGLE_COLUMN_FAMILY,
SINGLE_COLUMN, AGG_TIMESTAMP, rowCountBytes, 0, rowCountBytes.length);
} else {
diff --git a/phoenix-core-server/src/main/java/org/apache/phoenix/coprocessor/IndexerRegionScanner.java b/phoenix-core-server/src/main/java/org/apache/phoenix/coprocessor/IndexerRegionScanner.java
index 8714ef358e..42e51d6606 100644
--- a/phoenix-core-server/src/main/java/org/apache/phoenix/coprocessor/IndexerRegionScanner.java
+++ b/phoenix-core-server/src/main/java/org/apache/phoenix/coprocessor/IndexerRegionScanner.java
@@ -37,6 +37,7 @@ import java.util.concurrent.Future;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CellUtil;
+import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.client.Delete;
import org.apache.hadoop.hbase.client.Durability;
import org.apache.hadoop.hbase.client.Mutation;
@@ -73,6 +74,7 @@ import org.apache.phoenix.query.KeyRange;
import org.apache.phoenix.schema.SortOrder;
import org.apache.phoenix.schema.types.PLong;
import org.apache.phoenix.schema.types.PVarbinary;
+import org.apache.phoenix.util.ByteUtil;
import org.apache.phoenix.util.ClientUtil;
import org.apache.phoenix.util.IndexUtil;
import org.apache.phoenix.util.PhoenixKeyValueUtil;
@@ -435,12 +437,33 @@ public class IndexerRegionScanner extends GlobalIndexRegionScanner {
mutations.clear();
}
}
- byte[] rowCountBytes = PLong.INSTANCE.toBytes(Long.valueOf(rowCount));
+ byte[] rowCountBytes = PLong.INSTANCE.toBytes((long) rowCount);
final Cell aggKeyValue;
if (lastCell == null) {
- aggKeyValue = PhoenixKeyValueUtil.newKeyValue(UNGROUPED_AGG_ROW_KEY,
- SINGLE_COLUMN_FAMILY,
- SINGLE_COLUMN, AGG_TIMESTAMP, rowCountBytes,0, rowCountBytes.length);
+ byte[] rowKey;
+ byte[] startKey = scan.getStartRow().length > 0 ? scan.getStartRow() :
+ region.getRegionInfo().getStartKey();
+ byte[] endKey = scan.getStopRow().length > 0 ? scan.getStopRow() :
+ region.getRegionInfo().getEndKey();
+ final boolean isIncompatibleClient =
+ ScanUtil.isIncompatibleClientForServerReturnValidRowKey(scan);
+ if (!isIncompatibleClient) {
+ rowKey = ByteUtil.getLargestPossibleRowKeyInRange(startKey, endKey);
+ if (rowKey == null) {
+ if (scan.includeStartRow()) {
+ rowKey = startKey;
+ } else if (scan.includeStopRow()) {
+ rowKey = endKey;
+ } else {
+ rowKey = HConstants.EMPTY_END_ROW;
+ }
+ }
+ } else {
+ rowKey = UNGROUPED_AGG_ROW_KEY;
+ }
+ aggKeyValue = PhoenixKeyValueUtil.newKeyValue(rowKey,
+ SINGLE_COLUMN_FAMILY,
+ SINGLE_COLUMN, AGG_TIMESTAMP, rowCountBytes, 0, rowCountBytes.length);
} else {
aggKeyValue = PhoenixKeyValueUtil.newKeyValue(CellUtil.cloneRow(lastCell),
SINGLE_COLUMN_FAMILY,
diff --git a/phoenix-core-server/src/main/java/org/apache/phoenix/coprocessor/PagingRegionScanner.java b/phoenix-core-server/src/main/java/org/apache/phoenix/coprocessor/PagingRegionScanner.java
index 5787630072..965cd370c9 100644
--- a/phoenix-core-server/src/main/java/org/apache/phoenix/coprocessor/PagingRegionScanner.java
+++ b/phoenix-core-server/src/main/java/org/apache/phoenix/coprocessor/PagingRegionScanner.java
@@ -21,11 +21,13 @@ import java.io.IOException;
import java.util.List;
import org.apache.hadoop.hbase.Cell;
+import org.apache.hadoop.hbase.client.PackagePrivateFieldAccessor;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.regionserver.Region;
import org.apache.hadoop.hbase.regionserver.RegionScanner;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.phoenix.filter.PagingFilter;
+import org.apache.phoenix.query.QueryServices;
import org.apache.phoenix.util.ScanUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -61,6 +63,28 @@ public class PagingRegionScanner extends BaseRegionScanner {
private boolean next(List<Cell> results, boolean raw) throws IOException {
try {
+ byte[] adjustedStartRowKey =
+ scan.getAttribute(QueryServices.PHOENIX_PAGING_NEW_SCAN_START_ROWKEY);
+ byte[] adjustedStartRowKeyIncludeBytes =
+ scan.getAttribute(QueryServices.PHOENIX_PAGING_NEW_SCAN_START_ROWKEY_INCLUDE);
+ // If scanners at higher level needs to re-scan the data that were already scanned
+ // earlier, they can provide adjusted new start rowkey for the scan and whether to
+ // include it.
+ // If they are set as the scan attributes, close the scanner, reopen it with
+ // updated start rowkey and whether to include it. Update mvcc read point from the
+ // previous scanner and set it back to the new scanner to maintain the read
+ // consistency for the given region.
+ // Once done, continue the scan operation and reset the attributes.
+ if (adjustedStartRowKey != null && adjustedStartRowKeyIncludeBytes != null) {
+ long mvccReadPoint = delegate.getMvccReadPoint();
+ delegate.close();
+ scan.withStartRow(adjustedStartRowKey,
+ Bytes.toBoolean(adjustedStartRowKeyIncludeBytes));
+ PackagePrivateFieldAccessor.setMvccReadPoint(scan, mvccReadPoint);
+ delegate = region.getScanner(scan);
+ scan.setAttribute(QueryServices.PHOENIX_PAGING_NEW_SCAN_START_ROWKEY, null);
+ scan.setAttribute(QueryServices.PHOENIX_PAGING_NEW_SCAN_START_ROWKEY_INCLUDE, null);
+ }
if (pagingFilter != null) {
pagingFilter.init();
}
@@ -72,15 +96,10 @@ public class PagingRegionScanner extends BaseRegionScanner {
// There is no more row from the HBase region scanner. We need to check if PageFilter
// has stopped the region scanner
if (pagingFilter.isStopped()) {
- // Close the current region scanner, start a new one and return a dummy result
- delegate.close();
- byte[] rowKey = pagingFilter.getRowKeyAtStop();
- boolean isInclusive = pagingFilter.isNextRowInclusive();
- scan.withStartRow(rowKey, isInclusive);
- delegate = region.getScanner(scan);
if (results.isEmpty()) {
- LOGGER.info("Page filter stopped, generating dummy key {} inclusive={}",
- Bytes.toStringBinary(rowKey), isInclusive);
+ byte[] rowKey = pagingFilter.getCurrentRowKeyToBeExcluded();
+ LOGGER.info("Page filter stopped, generating dummy key {} ",
+ Bytes.toStringBinary(rowKey));
ScanUtil.getDummyResult(rowKey, results);
}
return true;
diff --git a/phoenix-core-server/src/main/java/org/apache/phoenix/coprocessor/UncoveredIndexRegionScanner.java b/phoenix-core-server/src/main/java/org/apache/phoenix/coprocessor/UncoveredIndexRegionScanner.java
index 18188f298c..a9dd460599 100644
--- a/phoenix-core-server/src/main/java/org/apache/phoenix/coprocessor/UncoveredIndexRegionScanner.java
+++ b/phoenix-core-server/src/main/java/org/apache/phoenix/coprocessor/UncoveredIndexRegionScanner.java
@@ -20,6 +20,7 @@ package org.apache.phoenix.coprocessor;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CellUtil;
+import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.client.Delete;
import org.apache.hadoop.hbase.client.Mutation;
import org.apache.hadoop.hbase.client.Put;
@@ -44,9 +45,11 @@ import org.apache.phoenix.schema.SortOrder;
import org.apache.phoenix.schema.tuple.ResultTuple;
import org.apache.phoenix.schema.types.PVarbinary;
import org.apache.phoenix.thirdparty.com.google.common.collect.Maps;
+import org.apache.phoenix.util.ByteUtil;
import org.apache.phoenix.util.EnvironmentEdgeManager;
import org.apache.phoenix.util.IndexUtil;
import org.apache.phoenix.util.ScanUtil;
+import org.apache.phoenix.util.ServerUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -95,6 +98,9 @@ public abstract class UncoveredIndexRegionScanner extends BaseRegionScanner {
protected int indexRowCount = 0;
protected final long pageSizeMs;
protected byte[] lastIndexRowKey = null;
+ private byte[] previousResultRowKey = null;
+ private final byte[] initStartRowKey;
+ private final boolean includeInitStartRowKey;
public UncoveredIndexRegionScanner(final RegionScanner innerScanner,
final Region region,
@@ -138,6 +144,11 @@ public abstract class UncoveredIndexRegionScanner extends BaseRegionScanner {
this.ptr = ptr;
this.tupleProjector = tupleProjector;
this.pageSizeMs = pageSizeMs;
+ // If scan start rowkey is empty, use region boundaries. Reverse region boundaries
+ // for reverse scan.
+ this.initStartRowKey =
+ ServerUtil.getScanStartRowKeyFromScanOrRegionBoundaries(scan, region);
+ this.includeInitStartRowKey = scan.includeStartRow();
}
@Override
@@ -381,6 +392,8 @@ public abstract class UncoveredIndexRegionScanner extends BaseRegionScanner {
if (state == State.SCANNING_INDEX) {
hasMore = scanIndexTableRows(result, startTime);
if (isDummy(result)) {
+ updateDummyWithPrevRowKey(result, initStartRowKey, includeInitStartRowKey,
+ scan);
return hasMore;
}
state = State.SCANNING_DATA;
@@ -390,9 +403,14 @@ public abstract class UncoveredIndexRegionScanner extends BaseRegionScanner {
indexRowIterator = indexRows.iterator();
}
if (state == State.READY) {
- return getNextCoveredIndexRow(result);
+ boolean moreRows = getNextCoveredIndexRow(result);
+ if (!result.isEmpty()) {
+ previousResultRowKey = CellUtil.cloneRow(result.get(0));
+ }
+ return moreRows;
} else {
- getDummyResult(lastIndexRowKey, result);
+ updateDummyWithPrevRowKey(result, initStartRowKey, includeInitStartRowKey,
+ scan);
return true;
}
}
@@ -404,4 +422,58 @@ public abstract class UncoveredIndexRegionScanner extends BaseRegionScanner {
region.closeRegionOperation();
}
}
+
+ /**
+ * Add dummy cell to the result list based on either the previous rowkey returned to the
+ * client or the start rowkey and start rowkey include params.
+ *
+ * @param result result to add the dummy cell to.
+ * @param initStartRowKey scan start rowkey.
+ * @param includeInitStartRowKey scan start rowkey included.
+ * @param scan scan object.
+ */
+ private void updateDummyWithPrevRowKey(List<Cell> result, byte[] initStartRowKey,
+ boolean includeInitStartRowKey, Scan scan) {
+ result.clear();
+ if (previousResultRowKey != null) {
+ getDummyResult(previousResultRowKey, result);
+ } else {
+ if (includeInitStartRowKey && initStartRowKey.length > 0) {
+ byte[] prevKey;
+ // In order to generate largest possible rowkey that is less than
+ // initStartRowKey, we need to check size of the region name that can be
+ // used by hbase client for meta lookup, in case meta cache is expired at client.
+ // Once we know regionLookupInMetaLen, use it to generate largest possible
+ // rowkey that is lower than initStartRowKey by using
+ // ByteUtil#previousKeyWithLength function, which appends "\\xFF" bytes to
+ // prev rowkey upto the length provided. e.g. for the given key
+ // "\\x01\\xC1\\x06", the previous key with length 5 would be
+ // "\\x01\\xC1\\x05\\xFF\\xFF" by padding 2 bytes "\\xFF".
+ // The length of the largest scan start rowkey should not exceed
+ // HConstants#MAX_ROW_LENGTH.
+ int regionLookupInMetaLen =
+ RegionInfo.createRegionName(region.getTableDescriptor().getTableName(),
+ new byte[1], HConstants.NINES, false).length;
+ if (Bytes.compareTo(initStartRowKey, initStartRowKey.length - 1,
+ 1, ByteUtil.ZERO_BYTE, 0, 1) == 0) {
+ // If initStartRowKey has last byte as "\\x00", we can discard the last
+ // byte and send the key as dummy rowkey.
+ prevKey = new byte[initStartRowKey.length - 1];
+ System.arraycopy(initStartRowKey, 0, prevKey, 0, prevKey.length);
+ } else if (initStartRowKey.length <
+ (HConstants.MAX_ROW_LENGTH - 1 - regionLookupInMetaLen)) {
+ prevKey = ByteUtil.previousKeyWithLength(ByteUtil.concat(initStartRowKey,
+ new byte[HConstants.MAX_ROW_LENGTH
+ - initStartRowKey.length - 1 - regionLookupInMetaLen]),
+ HConstants.MAX_ROW_LENGTH - 1 - regionLookupInMetaLen);
+ } else {
+ prevKey = initStartRowKey;
+ }
+ getDummyResult(prevKey, result);
+ } else {
+ getDummyResult(initStartRowKey, result);
+ }
+ }
+ }
+
}
diff --git a/phoenix-core-server/src/main/java/org/apache/phoenix/coprocessor/UngroupedAggregateRegionObserver.java b/phoenix-core-server/src/main/java/org/apache/phoenix/coprocessor/UngroupedAggregateRegionObserver.java
index b07d680355..ed415f7add 100644
--- a/phoenix-core-server/src/main/java/org/apache/phoenix/coprocessor/UngroupedAggregateRegionObserver.java
+++ b/phoenix-core-server/src/main/java/org/apache/phoenix/coprocessor/UngroupedAggregateRegionObserver.java
@@ -105,6 +105,7 @@ import org.apache.phoenix.schema.stats.StatisticsCollectorFactory;
import org.apache.phoenix.schema.stats.StatsCollectionDisabledOnServerException;
import org.apache.phoenix.schema.types.PDataType;
import org.apache.phoenix.schema.types.PLong;
+import org.apache.phoenix.util.ByteUtil;
import org.apache.phoenix.util.ClientUtil;
import org.apache.phoenix.util.EncodedColumnsUtil;
import org.apache.phoenix.util.EnvironmentEdgeManager;
@@ -331,6 +332,14 @@ public class UngroupedAggregateRegionObserver extends BaseScannerRegionObserver
throws IOException {
super.preScannerOpen(e, scan);
if (ScanUtil.isAnalyzeTable(scan)) {
+ scan.setAttribute(BaseScannerRegionObserverConstants.SCAN_ANALYZE_ACTUAL_START_ROW,
+ scan.getStartRow());
+ scan.setAttribute(BaseScannerRegionObserverConstants.SCAN_ANALYZE_ACTUAL_STOP_ROW,
+ scan.getStopRow());
+ scan.setAttribute(BaseScannerRegionObserverConstants.SCAN_ANALYZE_INCLUDE_START_ROW,
+ Bytes.toBytes(scan.includeStartRow()));
+ scan.setAttribute(BaseScannerRegionObserverConstants.SCAN_ANALYZE_INCLUDE_STOP_ROW,
+ Bytes.toBytes(scan.includeStopRow()));
// We are setting the start row and stop row such that it covers the entire region. As part
// of Phonenix-1263 we are storing the guideposts against the physical table rather than
// individual tenant specific tables.
@@ -748,9 +757,12 @@ public class UngroupedAggregateRegionObserver extends BaseScannerRegionObserver
LOGGER.info("UPDATE STATISTICS didn't run because another UPDATE STATISTICS command was already running on the region "
+ region.getRegionInfo().getRegionNameAsString());
}
- byte[] rowCountBytes = PLong.INSTANCE.toBytes(Long.valueOf(rowCount));
+ final boolean isIncompatibleClient =
+ ScanUtil.isIncompatibleClientForServerReturnValidRowKey(scan);
+ byte[] rowKey = getRowKeyForCollectStats(region, scan, isIncompatibleClient);
+ byte[] rowCountBytes = PLong.INSTANCE.toBytes(rowCount);
final Cell aggKeyValue =
- PhoenixKeyValueUtil.newKeyValue(UNGROUPED_AGG_ROW_KEY, SINGLE_COLUMN_FAMILY,
+ PhoenixKeyValueUtil.newKeyValue(rowKey, SINGLE_COLUMN_FAMILY,
SINGLE_COLUMN, AGG_TIMESTAMP, rowCountBytes, 0, rowCountBytes.length);
RegionScanner scanner = new BaseRegionScanner(innerScanner) {
@Override
@@ -786,6 +798,40 @@ public class UngroupedAggregateRegionObserver extends BaseScannerRegionObserver
return scanner;
}
+ private static byte[] getRowKeyForCollectStats(Region region, Scan scan,
+ boolean isIncompatibleClient) {
+ byte[] rowKey;
+ if (!isIncompatibleClient) {
+ byte[] startKey = scan.getAttribute(
+ BaseScannerRegionObserverConstants.SCAN_ANALYZE_ACTUAL_START_ROW) == null ?
+ region.getRegionInfo().getStartKey() : scan.getAttribute(
+ BaseScannerRegionObserverConstants.SCAN_ANALYZE_ACTUAL_START_ROW);
+ byte[] endKey = scan.getAttribute(
+ BaseScannerRegionObserverConstants.SCAN_ANALYZE_ACTUAL_STOP_ROW) == null ?
+ region.getRegionInfo().getEndKey() : scan.getAttribute(
+ BaseScannerRegionObserverConstants.SCAN_ANALYZE_ACTUAL_STOP_ROW);
+ rowKey = ByteUtil.getLargestPossibleRowKeyInRange(startKey, endKey);
+ if (rowKey == null) {
+ if (scan.getAttribute(
+ BaseScannerRegionObserverConstants.SCAN_ANALYZE_INCLUDE_START_ROW) !=
+ null && Bytes.toBoolean(scan.getAttribute(
+ BaseScannerRegionObserverConstants.SCAN_ANALYZE_INCLUDE_START_ROW))) {
+ rowKey = startKey;
+ } else if (scan.getAttribute(
+ BaseScannerRegionObserverConstants.SCAN_ANALYZE_INCLUDE_STOP_ROW) !=
+ null && Bytes.toBoolean(scan.getAttribute(
+ BaseScannerRegionObserverConstants.SCAN_ANALYZE_INCLUDE_STOP_ROW))) {
+ rowKey = endKey;
+ } else {
+ rowKey = HConstants.EMPTY_END_ROW;
+ }
+ }
+ } else {
+ rowKey = UNGROUPED_AGG_ROW_KEY;
+ }
+ return rowKey;
+ }
+
/**
*
* Callable to encapsulate the collection of stats triggered by
diff --git a/phoenix-core-server/src/main/java/org/apache/phoenix/coprocessor/UngroupedAggregateRegionScanner.java b/phoenix-core-server/src/main/java/org/apache/phoenix/coprocessor/UngroupedAggregateRegionScanner.java
index 2943d7b6e0..65f76c78e7 100644
--- a/phoenix-core-server/src/main/java/org/apache/phoenix/coprocessor/UngroupedAggregateRegionScanner.java
+++ b/phoenix-core-server/src/main/java/org/apache/phoenix/coprocessor/UngroupedAggregateRegionScanner.java
@@ -661,8 +661,17 @@ public class UngroupedAggregateRegionScanner extends BaseRegionScanner {
if (hasAny) {
byte[] value = aggregators.toBytes(rowAggregators);
if (pageSizeMs == Long.MAX_VALUE) {
- // Paging is not set. To be compatible with older clients, do not set the row key
- keyValue = PhoenixKeyValueUtil.newKeyValue(UNGROUPED_AGG_ROW_KEY, SINGLE_COLUMN_FAMILY, SINGLE_COLUMN,
+ byte[] rowKey;
+ final boolean isIncompatibleClient =
+ ScanUtil.isIncompatibleClientForServerReturnValidRowKey(scan);
+ if (!isIncompatibleClient) {
+ rowKey = CellUtil.cloneRow(lastCell);
+ } else {
+ // Paging is not set. To be compatible with older clients, do not set the row key
+ rowKey = UNGROUPED_AGG_ROW_KEY;
+ }
+ keyValue = PhoenixKeyValueUtil.newKeyValue(rowKey, SINGLE_COLUMN_FAMILY,
+ SINGLE_COLUMN,
AGG_TIMESTAMP, value, 0, value.length);
} else {
keyValue = PhoenixKeyValueUtil.newKeyValue(CellUtil.cloneRow(lastCell), SINGLE_COLUMN_FAMILY, SINGLE_COLUMN,
diff --git a/phoenix-core-server/src/main/java/org/apache/phoenix/index/GlobalIndexChecker.java b/phoenix-core-server/src/main/java/org/apache/phoenix/index/GlobalIndexChecker.java
index 2eec0c4e7d..4dbf5c1f6d 100644
--- a/phoenix-core-server/src/main/java/org/apache/phoenix/index/GlobalIndexChecker.java
+++ b/phoenix-core-server/src/main/java/org/apache/phoenix/index/GlobalIndexChecker.java
@@ -37,6 +37,7 @@ import org.apache.hadoop.hbase.CellUtil;
import org.apache.hadoop.hbase.CoprocessorEnvironment;
import org.apache.hadoop.hbase.DoNotRetryIOException;
import org.apache.hadoop.hbase.TableName;
+import org.apache.hadoop.hbase.client.PackagePrivateFieldAccessor;
import org.apache.hadoop.hbase.client.RegionInfo;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
@@ -136,7 +137,7 @@ public class GlobalIndexChecker extends BaseScannerRegionObserver implements Reg
private Scan scan;
private Scan indexScan;
private Scan singleRowIndexScan;
- private Scan buildIndexScan = null;
+ private Scan buildIndexScanForDataTable = null;
private Table dataHTable = null;
private byte[] emptyCF;
private byte[] emptyCQ;
@@ -274,7 +275,8 @@ public class GlobalIndexChecker extends BaseScannerRegionObserver implements Reg
if (verifyRowAndRepairIfNecessary(result)) {
break;
}
- if (hasMore && (EnvironmentEdgeManager.currentTimeMillis() - startTime) >= pageSizeMs) {
+ if (hasMore && (EnvironmentEdgeManager.currentTimeMillis() - startTime) >=
+ pageSizeMs) {
byte[] rowKey = CellUtil.cloneRow(cell);
result.clear();
getDummyResult(rowKey, result);
@@ -338,10 +340,21 @@ public class GlobalIndexChecker extends BaseScannerRegionObserver implements Reg
}
private void repairIndexRows(byte[] indexRowKey, long ts, List<Cell> row) throws IOException {
- if (buildIndexScan == null) {
- buildIndexScan = new Scan();
+ if (buildIndexScanForDataTable == null) {
+ buildIndexScanForDataTable = new Scan();
indexScan = new Scan(scan);
singleRowIndexScan = new Scan(scan);
+ // Scanners to be opened on index table using indexScan and singleRowIndexScan do
+ // require scanning the latest/newer version of cells i.e. new rows updated on the
+ // index table as part of the read-repair operation.
+ // Both scan objects copy mvcc read point from the original scan object used to
+ // open GlobalIndexScanner. Hence, we need to reset them to -1 so that if the
+ // region moves in the middle of the ongoing scan on the data table, the reset
+ // mvcc value of -1 will ensure that new scanners opened on index table using
+ // indexScan and singleRowIndexScan are able to read the latest snapshot of the
+ // index updates.
+ PackagePrivateFieldAccessor.setMvccReadPoint(indexScan, -1);
+ PackagePrivateFieldAccessor.setMvccReadPoint(singleRowIndexScan, -1);
byte[] dataTableName = scan.getAttribute(BaseScannerRegionObserverConstants.PHYSICAL_DATA_TABLE_NAME);
dataHTable =
ServerUtil.ConnectionFactory.
@@ -351,29 +364,29 @@ public class GlobalIndexChecker extends BaseScannerRegionObserver implements Reg
viewConstants = IndexUtil.deserializeViewConstantsFromScan(scan);
// The following attributes are set to instruct UngroupedAggregateRegionObserver to do partial index rebuild
// i.e., rebuild a subset of index rows.
- buildIndexScan.setAttribute(BaseScannerRegionObserverConstants.UNGROUPED_AGG, TRUE_BYTES);
- buildIndexScan.setAttribute(PhoenixIndexCodec.INDEX_PROTO_MD, scan.getAttribute(PhoenixIndexCodec.INDEX_PROTO_MD));
- ScanUtil.annotateScanWithMetadataAttributes(scan, buildIndexScan);
- buildIndexScan.setAttribute(BaseScannerRegionObserverConstants.REBUILD_INDEXES, TRUE_BYTES);
- buildIndexScan.setAttribute(BaseScannerRegionObserverConstants.SKIP_REGION_BOUNDARY_CHECK, Bytes.toBytes(true));
- buildIndexScan.setAttribute(BaseScannerRegionObserverConstants.EMPTY_COLUMN_QUALIFIER_NAME, emptyCQ);
+ buildIndexScanForDataTable.setAttribute(BaseScannerRegionObserverConstants.UNGROUPED_AGG, TRUE_BYTES);
+ buildIndexScanForDataTable.setAttribute(PhoenixIndexCodec.INDEX_PROTO_MD, scan.getAttribute(PhoenixIndexCodec.INDEX_PROTO_MD));
+ ScanUtil.annotateScanWithMetadataAttributes(scan, buildIndexScanForDataTable);
+ buildIndexScanForDataTable.setAttribute(BaseScannerRegionObserverConstants.REBUILD_INDEXES, TRUE_BYTES);
+ buildIndexScanForDataTable.setAttribute(BaseScannerRegionObserverConstants.SKIP_REGION_BOUNDARY_CHECK, Bytes.toBytes(true));
+ buildIndexScanForDataTable.setAttribute(BaseScannerRegionObserverConstants.EMPTY_COLUMN_QUALIFIER_NAME, emptyCQ);
// Scan only columns included in the index table plus the empty column
for (ColumnReference column : indexMaintainer.getAllColumnsForDataTable()) {
- buildIndexScan.addColumn(column.getFamily(), column.getQualifier());
+ buildIndexScanForDataTable.addColumn(column.getFamily(), column.getQualifier());
}
- buildIndexScan.addColumn(indexMaintainer.getDataEmptyKeyValueCF(), indexMaintainer.getEmptyKeyValueQualifierForDataTable());
+ buildIndexScanForDataTable.addColumn(indexMaintainer.getDataEmptyKeyValueCF(), indexMaintainer.getEmptyKeyValueQualifierForDataTable());
}
// Rebuild the index row from the corresponding the row in the the data table
// Get the data row key from the index row key
byte[] dataRowKey = indexMaintainer.buildDataRowKey(new ImmutableBytesWritable(indexRowKey), viewConstants);
- buildIndexScan.withStartRow(dataRowKey, true);
- buildIndexScan.withStopRow(dataRowKey, true);
- buildIndexScan.setTimeRange(0, maxTimestamp);
+ buildIndexScanForDataTable.withStartRow(dataRowKey, true);
+ buildIndexScanForDataTable.withStopRow(dataRowKey, true);
+ buildIndexScanForDataTable.setTimeRange(0, maxTimestamp);
// Pass the index row key to the partial index builder which will rebuild the index row and check if the
// row key of this rebuilt index row matches with the passed index row key
- buildIndexScan.setAttribute(BaseScannerRegionObserverConstants.INDEX_ROW_KEY, indexRowKey);
+ buildIndexScanForDataTable.setAttribute(BaseScannerRegionObserverConstants.INDEX_ROW_KEY, indexRowKey);
Result result = null;
- try (ResultScanner resultScanner = dataHTable.getScanner(buildIndexScan)){
+ try (ResultScanner resultScanner = dataHTable.getScanner(buildIndexScanForDataTable)){
result = resultScanner.next();
} catch (Throwable t) {
ClientUtil.throwIOException(dataHTable.getName().toString(), t);
diff --git a/phoenix-core-server/src/main/java/org/apache/phoenix/iterate/NonAggregateRegionScannerFactory.java b/phoenix-core-server/src/main/java/org/apache/phoenix/iterate/NonAggregateRegionScannerFactory.java
index b3c723201b..12873c9081 100644
--- a/phoenix-core-server/src/main/java/org/apache/phoenix/iterate/NonAggregateRegionScannerFactory.java
+++ b/phoenix-core-server/src/main/java/org/apache/phoenix/iterate/NonAggregateRegionScannerFactory.java
@@ -32,6 +32,8 @@ import java.util.List;
import java.util.Set;
import org.apache.hadoop.hbase.Cell;
+import org.apache.hadoop.hbase.CellUtil;
+import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.KeyValue;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.Scan;
@@ -39,6 +41,7 @@ import org.apache.hadoop.hbase.coprocessor.RegionCoprocessorEnvironment;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
import org.apache.hadoop.hbase.regionserver.Region;
import org.apache.hadoop.hbase.regionserver.RegionScanner;
+import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.io.WritableUtils;
import org.apache.phoenix.cache.GlobalCache;
import org.apache.phoenix.cache.TenantCache;
@@ -70,6 +73,7 @@ import org.apache.phoenix.schema.tuple.Tuple;
import org.apache.phoenix.schema.types.PInteger;
import org.apache.phoenix.transaction.PhoenixTransactionContext;
import org.apache.phoenix.transaction.TransactionFactory;
+import org.apache.phoenix.util.ByteUtil;
import org.apache.phoenix.util.ClientUtil;
import org.apache.phoenix.util.EncodedColumnsUtil;
import org.apache.phoenix.util.IndexUtil;
@@ -78,9 +82,14 @@ import org.apache.phoenix.util.ScanUtil;
import org.apache.phoenix.thirdparty.com.google.common.annotations.VisibleForTesting;
import org.apache.phoenix.thirdparty.com.google.common.collect.Lists;
import org.apache.phoenix.thirdparty.com.google.common.collect.Sets;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public class NonAggregateRegionScannerFactory extends RegionScannerFactory {
+ private static final Logger LOGGER =
+ LoggerFactory.getLogger(NonAggregateRegionScannerFactory.class);
+
public NonAggregateRegionScannerFactory(RegionCoprocessorEnvironment env) {
this.env = env;
}
@@ -161,10 +170,21 @@ public class NonAggregateRegionScannerFactory extends RegionScannerFactory {
useNewValueColumnQualifier);
}
if (scanOffset != null) {
- innerScanner = getOffsetScanner(innerScanner, new OffsetResultIterator(
- new RegionScannerResultIterator(innerScanner, getMinMaxQualifiersFromScan(scan), encodingScheme),
- scanOffset, getPageSizeMsForRegionScanner(scan)),
- scan.getAttribute(QueryConstants.LAST_SCAN) != null);
+ final boolean isIncompatibleClient =
+ ScanUtil.isIncompatibleClientForServerReturnValidRowKey(scan);
+ innerScanner = getOffsetScanner(
+ innerScanner,
+ new OffsetResultIterator(
+ new RegionScannerResultIterator(
+ innerScanner,
+ getMinMaxQualifiersFromScan(scan),
+ encodingScheme),
+ scanOffset,
+ getPageSizeMsForRegionScanner(scan),
+ isIncompatibleClient),
+ scan.getAttribute(QueryConstants.LAST_SCAN) != null,
+ isIncompatibleClient,
+ scan);
}
boolean spoolingEnabled =
env.getConfiguration().getBoolean(
@@ -217,10 +237,13 @@ public class NonAggregateRegionScannerFactory extends RegionScannerFactory {
orderByExpression.readFields(input);
orderByExpressions.add(orderByExpression);
}
- PTable.QualifierEncodingScheme encodingScheme = EncodedColumnsUtil.getQualifierEncodingScheme(scan);
- ResultIterator inner = new RegionScannerResultIterator(s, EncodedColumnsUtil.getMinMaxQualifiersFromScan(scan), encodingScheme);
+ PTable.QualifierEncodingScheme encodingScheme =
+ EncodedColumnsUtil.getQualifierEncodingScheme(scan);
+ ResultIterator inner = new RegionScannerResultIterator(s,
+ EncodedColumnsUtil.getMinMaxQualifiersFromScan(scan), encodingScheme);
return new OrderedResultIterator(inner, orderByExpressions, spoolingEnabled,
- thresholdBytes, limit >= 0 ? limit : null, null, estimatedRowSize, getPageSizeMsForRegionScanner(scan));
+ thresholdBytes, limit >= 0 ? limit : null, null, estimatedRowSize,
+ getPageSizeMsForRegionScanner(scan), scan, s.getRegionInfo());
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
@@ -268,18 +291,71 @@ public class NonAggregateRegionScannerFactory extends RegionScannerFactory {
}
}
-
private RegionScanner getOffsetScanner(final RegionScanner s,
- final OffsetResultIterator iterator, final boolean isLastScan) throws IOException {
+ final OffsetResultIterator iterator,
+ final boolean isLastScan,
+ final boolean incompatibleClient,
+ final Scan scan)
+ throws IOException {
final Tuple firstTuple;
final Region region = getRegion();
region.startRegionOperation();
+ final byte[] initStartRowKey = scan.getStartRow().length > 0 ? scan.getStartRow() :
+ (scan.isReversed() ? region.getRegionInfo().getEndKey() :
+ region.getRegionInfo().getStartKey());
+ byte[] prevScanStartRowKey =
+ scan.getAttribute(BaseScannerRegionObserverConstants.SCAN_ACTUAL_START_ROW);
+ // If the region has moved after server has returned dummy or valid row to client,
+ // prevScanStartRowKey would be different from actual scan start rowkey.
+ // If the region moves after dummy was returned, we do not need to set row count to
+ // offset. However, if the region moves after valid row was returned, we do need to
+ // set row count to offset because we return valid row only after offset num of rows
+ // are skipped.
+ if (Bytes.compareTo(prevScanStartRowKey, initStartRowKey) != 0 && Bytes.compareTo(
+ ByteUtil.concat(prevScanStartRowKey, ByteUtil.ZERO_BYTE),
+ initStartRowKey) != 0) {
+ iterator.setRowCountToOffset();
+ }
try {
Tuple tuple = iterator.next();
if (tuple == null && !isLastScan) {
- List<Cell> kvList = new ArrayList<Cell>(1);
- KeyValue kv = new KeyValue(QueryConstants.OFFSET_ROW_KEY_BYTES, QueryConstants.OFFSET_FAMILY,
- QueryConstants.OFFSET_COLUMN, PInteger.INSTANCE.toBytes(iterator.getRemainingOffset()));
+ List<Cell> kvList = new ArrayList<>(1);
+ KeyValue kv;
+ byte[] remainingOffset =
+ PInteger.INSTANCE.toBytes(iterator.getRemainingOffset());
+ if (incompatibleClient) {
+ kv = new KeyValue(
+ QueryConstants.OFFSET_ROW_KEY_BYTES,
+ QueryConstants.OFFSET_FAMILY,
+ QueryConstants.OFFSET_COLUMN,
+ remainingOffset);
+ } else {
+ Tuple lastScannedTuple = iterator.getLastScannedTuple();
+ if (lastScannedTuple != null) {
+ kv = getOffsetKvWithLastScannedRowKey(remainingOffset, lastScannedTuple);
+ } else {
+ byte[] rowKey;
+ byte[] startKey = scan.getStartRow().length > 0 ? scan.getStartRow() :
+ region.getRegionInfo().getStartKey();
+ byte[] endKey = scan.getStopRow().length > 0 ? scan.getStopRow() :
+ region.getRegionInfo().getEndKey();
+ rowKey = ByteUtil.getLargestPossibleRowKeyInRange(startKey, endKey);
+ if (rowKey == null) {
+ if (scan.includeStartRow()) {
+ rowKey = startKey;
+ } else if (scan.includeStopRow()) {
+ rowKey = endKey;
+ } else {
+ rowKey = HConstants.EMPTY_END_ROW;
+ }
+ }
+ kv = new KeyValue(
+ rowKey,
+ QueryConstants.OFFSET_FAMILY,
+ QueryConstants.OFFSET_COLUMN,
+ remainingOffset);
+ }
+ }
kvList.add(kv);
Result r = Result.create(kvList);
firstTuple = new ResultTuple(r);
@@ -292,8 +368,10 @@ public class NonAggregateRegionScannerFactory extends RegionScannerFactory {
} finally {
region.closeRegionOperation();
}
+
return new BaseRegionScanner(s) {
private Tuple tuple = firstTuple;
+ private byte[] previousResultRowKey;
@Override
public boolean isFilterDone() {
@@ -303,13 +381,41 @@ public class NonAggregateRegionScannerFactory extends RegionScannerFactory {
@Override
public boolean next(List<Cell> results) throws IOException {
try {
- if (isFilterDone()) { return false; }
- for (int i = 0; i < tuple.size(); i++) {
- results.add(tuple.getValue(i));
+ if (isFilterDone()) {
+ return false;
}
- tuple = iterator.next();
+ Tuple nextTuple = iterator.next();
+ if (tuple.size() > 0 && !isDummy(tuple)) {
+ for (int i = 0; i < tuple.size(); i++) {
+ results.add(tuple.getValue(i));
+ if (i == 0) {
+ previousResultRowKey = CellUtil.cloneRow(tuple.getValue(i));
+ }
+ }
+ } else {
+ if (nextTuple == null) {
+ byte[] remainingOffset =
+ PInteger.INSTANCE.toBytes(iterator.getRemainingOffset());
+ KeyValue kv;
+ if (incompatibleClient) {
+ kv = new KeyValue(
+ QueryConstants.OFFSET_ROW_KEY_BYTES,
+ QueryConstants.OFFSET_FAMILY,
+ QueryConstants.OFFSET_COLUMN,
+ remainingOffset);
+ } else {
+ kv = getOffsetKvWithLastScannedRowKey(remainingOffset, tuple);
+ }
+ results.add(kv);
+ } else {
+ updateDummyWithPrevRowKey(results, initStartRowKey,
+ previousResultRowKey);
+ }
+ }
+ tuple = nextTuple;
return !isFilterDone();
} catch (Throwable t) {
+ LOGGER.error("Error while iterating Offset scanner.", t);
ClientUtil.throwIOException(getRegion().getRegionInfo().getRegionNameAsString(), t);
return false;
}
@@ -321,9 +427,7 @@ public class NonAggregateRegionScannerFactory extends RegionScannerFactory {
s.close();
} finally {
try {
- if (iterator != null) {
- iterator.close();
- }
+ iterator.close();
} catch (SQLException e) {
ClientUtil.throwIOException(getRegion().getRegionInfo().getRegionNameAsString(), e);
}
@@ -332,6 +436,38 @@ public class NonAggregateRegionScannerFactory extends RegionScannerFactory {
};
}
+ /**
+ * Add dummy cell to the result list based on either the previous rowkey returned to the
+ * client or the start rowkey of the scan or region start key.
+ *
+ * @param result result row.
+ * @param initStartRowKey scan start rowkey.
+ * @param previousResultRowKey previous result rowkey returned to client.
+ */
+ private void updateDummyWithPrevRowKey(final List<Cell> result,
+ final byte[] initStartRowKey,
+ final byte[] previousResultRowKey) {
+ result.clear();
+ if (previousResultRowKey != null) {
+ getDummyResult(previousResultRowKey, result);
+ } else {
+ getDummyResult(initStartRowKey, result);
+ }
+ }
+
+ private static KeyValue getOffsetKvWithLastScannedRowKey(byte[] value, Tuple tuple) {
+ ImmutableBytesWritable ptr = new ImmutableBytesWritable();
+ tuple.getKey(ptr);
+ byte[] rowKey = new byte[ptr.getLength()];
+ System.arraycopy(ptr.get(), ptr.getOffset(), rowKey, 0,
+ rowKey.length);
+ return new KeyValue(
+ rowKey,
+ QueryConstants.OFFSET_FAMILY,
+ QueryConstants.OFFSET_COLUMN,
+ value);
+ }
+
/**
* Return region scanner that does TopN.
* We only need to call startRegionOperation and closeRegionOperation when
@@ -375,7 +511,7 @@ public class NonAggregateRegionScannerFactory extends RegionScannerFactory {
return false;
}
if (isDummy(tuple)) {
- getDummyResult(results);
+ ScanUtil.getDummyResult(CellUtil.cloneRow(tuple.getValue(0)), results);
} else {
for (int i = 0; i < tuple.size(); i++) {
results.add(tuple.getValue(i));
diff --git a/phoenix-core-server/src/main/java/org/apache/phoenix/util/ServerUtil.java b/phoenix-core-server/src/main/java/org/apache/phoenix/util/ServerUtil.java
index a620c595a7..2b364e2865 100644
--- a/phoenix-core-server/src/main/java/org/apache/phoenix/util/ServerUtil.java
+++ b/phoenix-core-server/src/main/java/org/apache/phoenix/util/ServerUtil.java
@@ -37,6 +37,7 @@ import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.CoprocessorDescriptor;
+import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.client.Table;
import org.apache.hadoop.hbase.coprocessor.RegionCoprocessorEnvironment;
import org.apache.hadoop.hbase.ipc.RpcControllerFactory;
@@ -156,6 +157,21 @@ public class ServerUtil {
}
}
+ /**
+ * If scan start rowkey is empty, use region boundaries. Reverse region boundaries
+ * for reverse scan.
+ *
+ * @param scan Scan object for which we need to find start rowkey.
+ * @param region Region object.
+ * @return Scan start rowkey based on scan's start rowkey or region boundaries.
+ */
+ public static byte[] getScanStartRowKeyFromScanOrRegionBoundaries(Scan scan,
+ Region region) {
+ return scan.getStartRow().length > 0 ? scan.getStartRow() :
+ (scan.isReversed() ? region.getRegionInfo().getEndKey() :
+ region.getRegionInfo().getStartKey());
+ }
+
public static enum ConnectionType {
COMPACTION_CONNECTION,
INDEX_WRITER_CONNECTION,
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/AggregateQueryWithRegionMoves2IT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/AggregateQueryWithRegionMoves2IT.java
new file mode 100644
index 0000000000..20066ab322
--- /dev/null
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/AggregateQueryWithRegionMoves2IT.java
@@ -0,0 +1,136 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.phoenix.end2end;
+
+import org.apache.hadoop.hbase.HConstants;
+import org.apache.phoenix.coprocessor.BaseScannerRegionObserver;
+import org.apache.phoenix.coprocessorclient.BaseScannerRegionObserverConstants;
+import org.apache.phoenix.iterate.ScanningResultPostDummyResultCaller;
+import org.apache.phoenix.iterate.ScanningResultPostValidResultCaller;
+import org.apache.phoenix.query.BaseTest;
+import org.apache.phoenix.query.QueryServices;
+import org.apache.phoenix.util.ReadOnlyProps;
+import org.junit.After;
+import org.junit.AfterClass;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.experimental.categories.Category;
+import org.junit.runners.Parameterized;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.Map;
+
+@Category(NeedsOwnMiniClusterTest.class)
+public class AggregateQueryWithRegionMoves2IT extends AggregateQueryWithRegionMovesIT {
+
+ private static final Logger LOGGER =
+ LoggerFactory.getLogger(AggregateQueryWithRegionMoves2IT.class);
+
+ private static int countOfValidResults = 0;
+
+ @Parameterized.Parameters(name = "AggregateQueryWithRegionMoves2IT_{index}")
+ public static synchronized Collection<Object> data() {
+ return BaseQueryWithRegionMovesIT.allIndexes();
+ }
+
+ public AggregateQueryWithRegionMoves2IT(String indexDDL, boolean columnEncoded,
+ boolean keepDeletedCells) {
+ super(indexDDL, columnEncoded, keepDeletedCells);
+ }
+
+ @Before
+ public void setUp() throws Exception {
+ hasTestStarted = true;
+ }
+
+ @After
+ public void tearDown() throws Exception {
+ countOfDummyResults = 0;
+ countOfValidResults = 0;
+ TABLE_NAMES.clear();
+ hasTestStarted = false;
+ }
+
+ private static class TestScanningResultPostDummyResultCaller extends
+ ScanningResultPostDummyResultCaller {
+
+ @Override
+ public void postDummyProcess() {
+ if (hasTestStarted && (countOfDummyResults++ % 3) == 0 &&
+ (countOfDummyResults < 17 ||
+ countOfDummyResults > 28 && countOfDummyResults < 40)) {
+ LOGGER.info("Moving regions of tables {}. current count of dummy results: {}",
+ TABLE_NAMES, countOfDummyResults);
+ TABLE_NAMES.forEach(table -> {
+ try {
+ moveRegionsOfTable(table);
+ } catch (Exception e) {
+ LOGGER.error("Unable to move regions of table: {}", table);
+ }
+ });
+ }
+ }
+ }
+
+ private static class TestScanningResultPostValidResultCaller extends
+ ScanningResultPostValidResultCaller {
+
+ @Override
+ public void postValidRowProcess() {
+ if (hasTestStarted &&
+ (countOfValidResults < 17 ||
+ countOfValidResults > 28 && countOfValidResults < 40)) {
+ LOGGER.info("Moving regions of tables {}. current count of valid results: {}",
+ TABLE_NAMES, countOfValidResults);
+ countOfValidResults++;
+ TABLE_NAMES.forEach(table -> {
+ try {
+ moveRegionsOfTable(table);
+ } catch (Exception e) {
+ LOGGER.error("Unable to move regions of table: {}", table);
+ }
+ });
+ }
+ }
+ }
+
+ @BeforeClass
+ public static synchronized void doSetup() throws Exception {
+ Map<String, String> props = new HashMap<>();
+ props.put(BaseScannerRegionObserverConstants.PHOENIX_MAX_LOOKBACK_AGE_CONF_KEY,
+ Integer.toString(60 * 60)); // An hour
+ props.put(QueryServices.USE_STATS_FOR_PARALLELIZATION, Boolean.toString(false));
+ props.put(QueryServices.PHOENIX_SERVER_PAGE_SIZE_MS, Long.toString(0));
+ props.put(QueryServices.TESTS_MINI_CLUSTER_NUM_REGION_SERVERS, String.valueOf(2));
+ props.put(HConstants.HBASE_CLIENT_SCANNER_MAX_RESULT_SIZE_KEY, String.valueOf(1));
+ props.put(QueryServices.PHOENIX_POST_DUMMY_PROCESS,
+ TestScanningResultPostDummyResultCaller.class.getName());
+ props.put(QueryServices.PHOENIX_POST_VALID_PROCESS,
+ TestScanningResultPostValidResultCaller.class.getName());
+ setUpTestDriver(new ReadOnlyProps(props.entrySet().iterator()));
+ }
+
+ @AfterClass
+ public static synchronized void freeResources() throws Exception {
+ BaseTest.freeResourcesIfBeyondThreshold();
+ }
+
+}
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/AggregateQueryWithRegionMovesIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/AggregateQueryWithRegionMovesIT.java
new file mode 100644
index 0000000000..2382d82849
--- /dev/null
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/AggregateQueryWithRegionMovesIT.java
@@ -0,0 +1,279 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.phoenix.end2end;
+
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.hbase.TableName;
+import org.apache.hadoop.hbase.client.Admin;
+import org.apache.hadoop.hbase.client.ClusterConnection;
+import org.apache.hadoop.hbase.client.ConnectionFactory;
+import org.apache.hadoop.hbase.client.RegionLocator;
+import org.apache.hadoop.hbase.util.Bytes;
+import org.apache.phoenix.jdbc.PhoenixConnection;
+import org.apache.phoenix.util.ByteUtil;
+import org.apache.phoenix.util.PropertiesUtil;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+import org.junit.runners.Parameterized.Parameters;
+
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.util.Collection;
+import java.util.Properties;
+
+import static org.apache.phoenix.util.TestUtil.A_VALUE;
+import static org.apache.phoenix.util.TestUtil.B_VALUE;
+import static org.apache.phoenix.util.TestUtil.C_VALUE;
+import static org.apache.phoenix.util.TestUtil.E_VALUE;
+import static org.apache.phoenix.util.TestUtil.ROW4;
+import static org.apache.phoenix.util.TestUtil.TEST_PROPERTIES;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotEquals;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+
+@Category(NeedsOwnMiniClusterTest.class)
+public class AggregateQueryWithRegionMovesIT extends BaseQueryWithRegionMovesIT {
+
+ @Parameters(name = "AggregateQueryWithRegionMovesIT_{index}")
+ public static synchronized Collection<Object> data() {
+ return BaseQueryWithRegionMovesIT.allIndexes();
+ }
+
+ public AggregateQueryWithRegionMovesIT(String indexDDL, boolean columnEncoded,
+ boolean keepDeletedCells) {
+ super(indexDDL, columnEncoded, keepDeletedCells);
+ }
+
+ @Before
+ public void setUp() throws Exception {
+ hasTestStarted = true;
+ }
+
+ @After
+ public void tearDown() throws Exception {
+ countOfDummyResults = 0;
+ TABLE_NAMES.clear();
+ hasTestStarted = false;
+ }
+
+ @Test
+ public void testGroupByPlusOne() throws Exception {
+ String query = "SELECT a_integer+1 FROM " + tableName +
+ " WHERE organization_id=? and a_integer = 5 GROUP BY a_integer+1";
+ TABLE_NAMES.add(tableName);
+ TABLE_NAMES.add(indexName);
+ Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
+ try (Connection conn = DriverManager.getConnection(getUrl(), props)) {
+ PreparedStatement statement = conn.prepareStatement(query);
+ statement.setString(1, tenantId);
+ ResultSet rs = statement.executeQuery();
+ assertTrue(rs.next());
+ moveRegionsOfTable(tableName);
+ moveRegionsOfTable(indexName);
+ assertEquals(6, rs.getInt(1));
+ assertFalse(rs.next());
+ }
+ }
+
+ @Test
+ public void testSplitWithCachedMeta() throws Exception {
+ TABLE_NAMES.add(tableName);
+ TABLE_NAMES.add(indexName);
+ // Tests that you don't get an ambiguous column exception when using the same alias as the column name
+ String query = "SELECT a_string, b_string, count(1) FROM " + tableName +
+ " WHERE organization_id=? and entity_id<=? GROUP BY a_string,b_string";
+ Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
+ Connection conn = DriverManager.getConnection(getUrl(), props);
+ Admin admin = null;
+ try {
+ PreparedStatement statement = conn.prepareStatement(query);
+ statement.setString(1, tenantId);
+ statement.setString(2, ROW4);
+ ResultSet rs = statement.executeQuery();
+ assertTrue(rs.next());
+ moveRegionsOfTable(tableName);
+ moveRegionsOfTable(indexName);
+ assertEquals(A_VALUE, rs.getString(1));
+ assertEquals(B_VALUE, rs.getString(2));
+ assertEquals(2, rs.getLong(3));
+ assertTrue(rs.next());
+ assertEquals(A_VALUE, rs.getString(1));
+ assertEquals(C_VALUE, rs.getString(2));
+ assertEquals(1, rs.getLong(3));
+ moveRegionsOfTable(tableName);
+ moveRegionsOfTable(indexName);
+ assertTrue(rs.next());
+ assertEquals(A_VALUE, rs.getString(1));
+ assertEquals(E_VALUE, rs.getString(2));
+ assertEquals(1, rs.getLong(3));
+ assertFalse(rs.next());
+
+ TableName tn = TableName.valueOf(tableName);
+ admin = conn.unwrap(PhoenixConnection.class).getQueryServices().getAdmin();
+ Configuration configuration =
+ conn.unwrap(PhoenixConnection.class).getQueryServices().getConfiguration();
+ org.apache.hadoop.hbase.client.Connection hbaseConn =
+ ConnectionFactory.createConnection(configuration);
+ ((ClusterConnection) hbaseConn).clearRegionCache(TableName.valueOf(tableName));
+ RegionLocator regionLocator = hbaseConn.getRegionLocator(TableName.valueOf(tableName));
+ int nRegions = regionLocator.getAllRegionLocations().size();
+ admin.split(tn, ByteUtil.concat(Bytes.toBytes(tenantId), Bytes.toBytes("00A3")));
+ int retryCount = 0;
+ do {
+ Thread.sleep(2000);
+ retryCount++;
+ //htable.clearRegionCache();
+ } while (retryCount < 10 && regionLocator.getAllRegionLocations().size() == nRegions);
+ assertNotEquals(nRegions, regionLocator.getAllRegionLocations().size());
+
+ statement.setString(1, tenantId);
+ rs = statement.executeQuery();
+ assertTrue(rs.next());
+ moveRegionsOfTable(tableName);
+ moveRegionsOfTable(indexName);
+ assertEquals(A_VALUE, rs.getString(1));
+ assertEquals(B_VALUE, rs.getString(2));
+ assertEquals(2, rs.getLong(3));
+ assertTrue(rs.next());
+ moveRegionsOfTable(tableName);
+ moveRegionsOfTable(indexName);
+ assertEquals(A_VALUE, rs.getString(1));
+ assertEquals(C_VALUE, rs.getString(2));
+ assertEquals(1, rs.getLong(3));
+ assertTrue(rs.next());
+ assertEquals(A_VALUE, rs.getString(1));
+ assertEquals(E_VALUE, rs.getString(2));
+ assertEquals(1, rs.getLong(3));
+ assertFalse(rs.next());
+ } finally {
+ if (admin != null) {
+ admin.close();
+ }
+ conn.close();
+ }
+ }
+
+ @Test
+ public void testCountIsNull() throws Exception {
+ TABLE_NAMES.add(tableName);
+ TABLE_NAMES.add(indexName);
+ String query = "SELECT count(1) FROM " + tableName + " WHERE X_DECIMAL is null";
+ Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
+ try (Connection conn = DriverManager.getConnection(getUrl(), props)) {
+ PreparedStatement statement = conn.prepareStatement(query);
+ ResultSet rs = statement.executeQuery();
+ assertTrue(rs.next());
+ moveRegionsOfTable(tableName);
+ moveRegionsOfTable(indexName);
+ assertEquals(6, rs.getLong(1));
+ assertFalse(rs.next());
+ }
+ }
+
+ @Test
+ public void testCountWithNoScanRanges() throws Exception {
+ TABLE_NAMES.add(tableName);
+ TABLE_NAMES.add(indexName);
+ String query = "SELECT count(1) FROM " + tableName +
+ " WHERE organization_id = 'not_existing_organization_id'";
+ Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
+ try (Connection conn = DriverManager.getConnection(getUrl(), props)) {
+ PreparedStatement statement = conn.prepareStatement(query);
+ ResultSet rs = statement.executeQuery();
+ assertTrue(rs.next());
+ moveRegionsOfTable(tableName);
+ moveRegionsOfTable(indexName);
+ assertEquals(0, rs.getLong(1));
+ assertFalse(rs.next());
+ query = "SELECT count(1) FROM " + tableName +
+ " WHERE organization_id = 'not_existing_organization_id' having count(*)>0";
+ rs = conn.prepareStatement(query).executeQuery();
+ assertFalse(rs.next());
+ query = "SELECT count(1) FROM " + tableName +
+ " WHERE organization_id = 'not_existing_organization_id' limit 1 offset 1";
+ rs = conn.prepareStatement(query).executeQuery();
+ assertFalse(rs.next());
+ query = "SELECT count(1),123 FROM " + tableName +
+ " WHERE organization_id = 'not_existing_organization_id'";
+ rs = conn.prepareStatement(query).executeQuery();
+ assertTrue(rs.next());
+ moveRegionsOfTable(tableName);
+ moveRegionsOfTable(indexName);
+ assertEquals(0, rs.getLong(1));
+ assertEquals("123", rs.getString(2));
+ assertFalse(rs.next());
+ query = "SELECT count(1),sum(x_decimal) FROM " + tableName +
+ " WHERE organization_id = 'not_existing_organization_id'";
+ rs = conn.prepareStatement(query).executeQuery();
+ assertTrue(rs.next());
+ moveRegionsOfTable(tableName);
+ moveRegionsOfTable(indexName);
+ assertEquals(0, rs.getLong(1));
+ assertNull(rs.getBigDecimal(2));
+ assertFalse(rs.next());
+ }
+ }
+
+ @Test
+ public void testCountIsNotNull() throws Exception {
+ TABLE_NAMES.add(tableName);
+ TABLE_NAMES.add(indexName);
+ String query = "SELECT count(1) FROM " + tableName + " WHERE X_DECIMAL is not null";
+ Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
+ try (Connection conn = DriverManager.getConnection(getUrl(), props)) {
+ PreparedStatement statement = conn.prepareStatement(query);
+ ResultSet rs = statement.executeQuery();
+ assertTrue(rs.next());
+ moveRegionsOfTable(tableName);
+ moveRegionsOfTable(indexName);
+ assertEquals(3, rs.getLong(1));
+ assertFalse(rs.next());
+ }
+ }
+
+ /**
+ * Test to repro Null Pointer Exception
+ */
+ @Test
+ public void testInFilterOnKey() throws Exception {
+ TABLE_NAMES.add(tableName);
+ TABLE_NAMES.add(indexName);
+ String query =
+ "SELECT count(entity_id) FROM " + tableName + " WHERE organization_id IN (?,?)";
+ String url = getUrl();
+ Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
+ try (Connection conn = DriverManager.getConnection(url, props)) {
+ PreparedStatement statement = conn.prepareStatement(query);
+ statement.setString(1, tenantId);
+ statement.setString(2, tenantId);
+ ResultSet rs = statement.executeQuery();
+ assertTrue(rs.next());
+ moveRegionsOfTable(tableName);
+ moveRegionsOfTable(indexName);
+ assertEquals(9, rs.getInt(1));
+ assertFalse(rs.next());
+ }
+ }
+
+}
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/AggregateWithRegionMoves2IT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/AggregateWithRegionMoves2IT.java
new file mode 100644
index 0000000000..6bd47b8f00
--- /dev/null
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/AggregateWithRegionMoves2IT.java
@@ -0,0 +1,124 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.phoenix.end2end;
+
+import org.apache.hadoop.hbase.HConstants;
+import org.apache.phoenix.coprocessor.BaseScannerRegionObserver;
+import org.apache.phoenix.coprocessorclient.BaseScannerRegionObserverConstants;
+import org.apache.phoenix.iterate.ScanningResultPostDummyResultCaller;
+import org.apache.phoenix.iterate.ScanningResultPostValidResultCaller;
+import org.apache.phoenix.query.BaseTest;
+import org.apache.phoenix.query.QueryServices;
+import org.apache.phoenix.util.ReadOnlyProps;
+import org.junit.After;
+import org.junit.AfterClass;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.experimental.categories.Category;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.HashMap;
+import java.util.Map;
+
+@Category(NeedsOwnMiniClusterTest.class)
+public class AggregateWithRegionMoves2IT extends AggregateWithRegionMovesIT {
+
+ private static final Logger LOGGER =
+ LoggerFactory.getLogger(AggregateWithRegionMoves2IT.class);
+
+ private static int countOfValidResults = 0;
+
+ @Before
+ public void setUp() throws Exception {
+ hasTestStarted = true;
+ }
+
+ @After
+ public void tearDown() throws Exception {
+ countOfDummyResults = 0;
+ countOfValidResults = 0;
+ TABLE_NAMES.clear();
+ hasTestStarted = false;
+ }
+
+ private static class TestScanningResultPostDummyResultCaller extends
+ ScanningResultPostDummyResultCaller {
+
+ @Override
+ public void postDummyProcess() {
+ if (hasTestStarted && (countOfDummyResults++ % 3) == 0 &&
+ (countOfDummyResults < 17 ||
+ countOfDummyResults > 28 && countOfDummyResults < 40)) {
+ LOGGER.info("Moving regions of tables {}. current count of dummy results: {}",
+ TABLE_NAMES, countOfDummyResults);
+ TABLE_NAMES.forEach(table -> {
+ try {
+ moveRegionsOfTable(table);
+ } catch (Exception e) {
+ LOGGER.error("Unable to move regions of table: {}", table);
+ }
+ });
+ }
+ }
+ }
+
+ private static class TestScanningResultPostValidResultCaller extends
+ ScanningResultPostValidResultCaller {
+
+ @Override
+ public void postValidRowProcess() {
+ if (hasTestStarted &&
+ (countOfValidResults < 17 ||
+ countOfValidResults > 28 && countOfValidResults < 40)) {
+ LOGGER.info("Moving regions of tables {}. current count of valid results: {}",
+ TABLE_NAMES, countOfValidResults);
+ countOfValidResults++;
+ TABLE_NAMES.forEach(table -> {
+ try {
+ moveRegionsOfTable(table);
+ } catch (Exception e) {
+ LOGGER.error("Unable to move regions of table: {}", table);
+ }
+ });
+ }
+ }
+ }
+
+ @BeforeClass
+ public static synchronized void doSetup() throws Exception {
+ Map<String, String> props = new HashMap<>();
+ props.put(BaseScannerRegionObserverConstants.PHOENIX_MAX_LOOKBACK_AGE_CONF_KEY,
+ Integer.toString(60 * 60)); // An hour
+ props.put(QueryServices.USE_STATS_FOR_PARALLELIZATION, Boolean.toString(false));
+ props.put(QueryServices.PHOENIX_SERVER_PAGE_SIZE_MS, Long.toString(0));
+ props.put(QueryServices.TESTS_MINI_CLUSTER_NUM_REGION_SERVERS, String.valueOf(2));
+ props.put(HConstants.HBASE_CLIENT_SCANNER_MAX_RESULT_SIZE_KEY, String.valueOf(1));
+ props.put(QueryServices.PHOENIX_POST_DUMMY_PROCESS,
+ TestScanningResultPostDummyResultCaller.class.getName());
+ props.put(QueryServices.PHOENIX_POST_VALID_PROCESS,
+ TestScanningResultPostValidResultCaller.class.getName());
+ setUpTestDriver(new ReadOnlyProps(props.entrySet().iterator()));
+ }
+
+ @AfterClass
+ public static synchronized void freeResources() throws Exception {
+ BaseTest.freeResourcesIfBeyondThreshold();
+ }
+
+}
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/AggregateWithRegionMovesIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/AggregateWithRegionMovesIT.java
new file mode 100644
index 0000000000..e07bcb0d11
--- /dev/null
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/AggregateWithRegionMovesIT.java
@@ -0,0 +1,537 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.phoenix.end2end;
+
+import org.apache.hadoop.hbase.TableName;
+import org.apache.phoenix.jdbc.PhoenixDatabaseMetaData;
+import org.apache.phoenix.schema.AmbiguousColumnException;
+import org.apache.phoenix.util.PropertiesUtil;
+import org.apache.phoenix.util.QueryBuilder;
+import org.apache.phoenix.util.TestUtil;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.util.Properties;
+
+import static org.apache.phoenix.util.TestUtil.TEST_PROPERTIES;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+@Category(NeedsOwnMiniClusterTest.class)
+public class AggregateWithRegionMovesIT extends BaseAggregateWithRegionMovesIT {
+
+ @Before
+ public void setUp() throws Exception {
+ hasTestStarted = true;
+ }
+
+ @After
+ public void tearDown() throws Exception {
+ countOfDummyResults = 0;
+ TABLE_NAMES.clear();
+ hasTestStarted = false;
+ }
+
+ @Test
+ public void testGroupByWithAliasWithSameColumnName() throws Exception {
+ hasTestStarted = true;
+ Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
+ Connection conn = DriverManager.getConnection(getUrl(), props);
+ String tableName1 = generateUniqueName();
+ String tableName2 = generateUniqueName();
+ String tableName3 = generateUniqueName();
+ String ddl = "create table " + tableName1 + " (pk integer primary key, col integer)";
+ conn.createStatement().execute(ddl);
+ ddl = "create table " + tableName2 + " (pk integer primary key, col integer)";
+ conn.createStatement().execute(ddl);
+ ddl = "create table " + tableName3 + " (notPk integer primary key, col integer)";
+ conn.createStatement().execute(ddl);
+ TABLE_NAMES.add(tableName1);
+ TABLE_NAMES.add(tableName2);
+ TABLE_NAMES.add(tableName3);
+ conn.createStatement().execute("UPSERT INTO " + tableName1 + " VALUES (1,2)");
+ conn.createStatement().execute("UPSERT INTO " + tableName2 + " VALUES (1,2)");
+ conn.createStatement().execute("UPSERT INTO " + tableName3 + " VALUES (1,2)");
+ conn.createStatement().executeQuery(
+ "select " + tableName1 + ".pk as pk from " + tableName1 + " group by pk");
+ conn.createStatement().executeQuery(
+ "select " + tableName1 + ".pk as pk from " + tableName1 + " group by " +
+ tableName1 + ".pk");
+ conn.createStatement().executeQuery(
+ "select " + tableName1 + ".pk as pk from " + tableName1 + " as t group by t.pk");
+ conn.createStatement()
+ .executeQuery("select " + tableName1 + ".col as pk from " + tableName1);
+ conn.createStatement()
+ .executeQuery("select " + tableName1 + ".pk as pk from " + tableName1 + " join " +
+ tableName3 + " on (" + tableName1 + ".pk=" + tableName3 +
+ ".notPk) group by pk");
+ try {
+ conn.createStatement().executeQuery(
+ "select " + tableName1 + ".col as pk from " + tableName1 + " group by pk");
+ fail();
+ } catch (AmbiguousColumnException ignored) {
+ }
+ moveRegionsOfTable(tableName1);
+ moveRegionsOfTable(tableName2);
+ moveRegionsOfTable(tableName3);
+ try {
+ conn.createStatement()
+ .executeQuery("select col as pk from " + tableName1 + " group by pk");
+ fail();
+ } catch (AmbiguousColumnException ignored) {
+ }
+ try {
+ conn.createStatement()
+ .executeQuery(
+ "select " + tableName1 + ".pk as pk from " + tableName1 + " join " +
+ tableName2 + " on (" + tableName1 + ".pk=" + tableName2 +
+ ".pk) group by pk");
+ fail();
+ } catch (AmbiguousColumnException ignored) {
+ }
+ conn.close();
+ }
+
+ @Test
+ public void testGroupByCoerceExpressionBug3453() throws Exception {
+ try (Connection conn = DriverManager.getConnection(getUrl())) {
+ //Type is INT
+ String intTableName = generateUniqueName();
+ String sql = "CREATE TABLE " + intTableName + "(" +
+ "ENTITY_ID INTEGER NOT NULL," +
+ "CONTAINER_ID INTEGER NOT NULL," +
+ "SCORE INTEGER NOT NULL," +
+ "CONSTRAINT TEST_PK PRIMARY KEY (ENTITY_ID DESC,CONTAINER_ID DESC,SCORE DESC))";
+ TABLE_NAMES.add(intTableName);
+
+ conn.createStatement().execute(sql);
+ conn.createStatement().execute("UPSERT INTO " + intTableName + " VALUES (1,1,1)");
+ conn.commit();
+
+ sql = "select DISTINCT entity_id, score from ( select entity_id, score from " +
+ intTableName + " limit 1)";
+ ResultSet rs = conn.prepareStatement(sql).executeQuery();
+ assertResultSet(rs, new Object[][]{{1, 1}}, intTableName);
+
+ conn.createStatement().execute("UPSERT INTO " + intTableName + " VALUES (2,2,2)");
+ conn.createStatement().execute("UPSERT INTO " + intTableName + " VALUES (3,3,3)");
+ conn.commit();
+
+ sql = "select DISTINCT entity_id, score from ( select entity_id, score from " +
+ intTableName + " limit 3) order by entity_id";
+ rs = conn.prepareStatement(sql).executeQuery();
+ assertResultSet(rs, new Object[][]{{1, 1}, {2, 2}, {3, 3}}, intTableName);
+
+ sql = "select DISTINCT entity_id, score from ( select entity_id, score from " +
+ intTableName + " limit 3) order by entity_id desc";
+ rs = conn.prepareStatement(sql).executeQuery();
+ assertResultSet(rs, new Object[][]{{3, 3}, {2, 2}, {1, 1}}, intTableName);
+
+ //Type is CHAR
+ String charTableName = generateUniqueName();
+ sql = "CREATE TABLE " + charTableName + "(" +
+ "ENTITY_ID CHAR(15) NOT NULL," +
+ "CONTAINER_ID INTEGER NOT NULL," +
+ "SCORE INTEGER NOT NULL," +
+ "CONSTRAINT TEST_PK PRIMARY KEY (ENTITY_ID DESC,CONTAINER_ID DESC,SCORE DESC))";
+ TABLE_NAMES.add(charTableName);
+
+ conn.createStatement().execute(sql);
+ conn.createStatement()
+ .execute("UPSERT INTO " + charTableName + " VALUES ('entity1',1,1)");
+ conn.createStatement()
+ .execute("UPSERT INTO " + charTableName + " VALUES ('entity2',2,2)");
+ conn.createStatement()
+ .execute("UPSERT INTO " + charTableName + " VALUES ('entity3',3,3)");
+ conn.commit();
+
+ sql = "select DISTINCT entity_id, score from ( select entity_id, score from " +
+ charTableName + " limit 3) order by entity_id";
+ rs = conn.prepareStatement(sql).executeQuery();
+ assertResultSet(rs, new Object[][]{{"entity1", 1}, {"entity2", 2}, {"entity3", 3}},
+ charTableName);
+
+ sql = "select DISTINCT entity_id, score from ( select entity_id, score from " +
+ charTableName + " limit 3) order by entity_id desc";
+ rs = conn.prepareStatement(sql).executeQuery();
+ assertResultSet(rs, new Object[][]{{"entity3", 3}, {"entity2", 2}, {"entity1", 1}},
+ charTableName);
+ }
+ }
+
+ @Test
+ public void testNestedGroupedAggregationWithBigInt() throws Exception {
+ Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
+ String tableName = generateUniqueName();
+ TABLE_NAMES.add(tableName);
+ try (Connection conn = DriverManager.getConnection(getUrl(), props);) {
+ String createQuery = "CREATE TABLE " + tableName +
+ " (a BIGINT NOT NULL,c BIGINT NOT NULL CONSTRAINT PK PRIMARY KEY (a, c))";
+ String updateQuery = "UPSERT INTO " + tableName +
+ "(a,c) VALUES(4444444444444444444, 5555555555555555555)";
+ String query = "SELECT a FROM (SELECT a, c FROM " + tableName +
+ " GROUP BY a, c) GROUP BY a, c";
+ conn.prepareStatement(createQuery).execute();
+ conn.prepareStatement(updateQuery).execute();
+ conn.commit();
+ PreparedStatement statement = conn.prepareStatement(query);
+ ResultSet rs = statement.executeQuery();
+ assertTrue(rs.next());
+ moveRegionsOfTable(tableName);
+ assertEquals(4444444444444444444L, rs.getLong(1));
+ assertFalse(rs.next());
+ }
+ }
+
+ @Test
+ public void testAvgGroupByOrderPreservingWithStats() throws Exception {
+ Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
+ Connection conn = DriverManager.getConnection(getUrl(), props);
+ String tableName = generateUniqueName();
+ QueryBuilder queryBuilder = new QueryBuilder()
+ .setSelectExpression("COUNT(*)")
+ .setFullTableName(PhoenixDatabaseMetaData.SYSTEM_STATS_NAME)
+ .setWhereClause(PhoenixDatabaseMetaData.PHYSICAL_NAME + " ='" + tableName + "'");
+ ResultSet rs = executeQuery(conn, queryBuilder);
+ assertTrue(rs.next());
+ assertEquals(0, rs.getInt(1));
+ initAvgGroupTable(conn, tableName, PhoenixDatabaseMetaData.GUIDE_POSTS_WIDTH + "=20 ");
+ TestUtil.dumpTable(conn, TableName.valueOf(tableName));
+ // When ParallelStats are disabled it is 4. When enabled it is 13
+ testAvgGroupByOrderPreserving(conn, tableName, 4);
+ rs = executeQuery(conn, queryBuilder);
+ assertTrue(rs.next());
+ assertEquals(13, rs.getInt(1));
+ conn.setAutoCommit(true);
+ conn.createStatement().execute("DELETE FROM " + "\"SYSTEM\".\"STATS\"");
+ rs = executeQuery(conn, queryBuilder);
+ assertTrue(rs.next());
+ assertEquals(0, rs.getInt(1));
+ TestUtil.doMajorCompaction(conn, tableName);
+ rs = executeQuery(conn, queryBuilder);
+ assertTrue(rs.next());
+ assertEquals(13, rs.getInt(1));
+ testAvgGroupByOrderPreserving(conn, tableName, 4);
+ conn.createStatement().execute(
+ "ALTER TABLE " + tableName + " SET " + PhoenixDatabaseMetaData.GUIDE_POSTS_WIDTH +
+ "=100");
+ testAvgGroupByOrderPreserving(conn, tableName, 6);
+ conn.createStatement().execute(
+ "ALTER TABLE " + tableName + " SET " + PhoenixDatabaseMetaData.GUIDE_POSTS_WIDTH +
+ "=null");
+ testAvgGroupByOrderPreserving(conn, tableName, 4);
+ }
+
+ @Test
+ public void testAvgGroupByDescOrderPreservingWithStats() throws Exception {
+ Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
+ Connection conn = DriverManager.getConnection(getUrl(), props);
+ String tableName = generateUniqueName();
+ QueryBuilder queryBuilder = new QueryBuilder()
+ .setSelectExpression("COUNT(*)")
+ .setFullTableName(PhoenixDatabaseMetaData.SYSTEM_STATS_NAME)
+ .setWhereClause(PhoenixDatabaseMetaData.PHYSICAL_NAME + " ='" + tableName + "'");
+ ResultSet rs = executeQuery(conn, queryBuilder);
+ assertTrue(rs.next());
+ assertEquals(0, rs.getInt(1));
+ initAvgGroupTable(conn, tableName, PhoenixDatabaseMetaData.GUIDE_POSTS_WIDTH + "=20 ");
+ TestUtil.dumpTable(conn, TableName.valueOf(tableName));
+ testAvgGroupByDescOrderPreserving(conn, tableName);
+ rs = executeQuery(conn, queryBuilder);
+ assertTrue(rs.next());
+ assertEquals(13, rs.getInt(1));
+ conn.setAutoCommit(true);
+ conn.createStatement().execute("DELETE FROM " + "\"SYSTEM\".\"STATS\"");
+ rs = executeQuery(conn, queryBuilder);
+ assertTrue(rs.next());
+ assertEquals(0, rs.getInt(1));
+ TestUtil.doMajorCompaction(conn, tableName);
+ rs = executeQuery(conn, queryBuilder);
+ assertTrue(rs.next());
+ assertEquals(13, rs.getInt(1));
+ testAvgGroupByDescOrderPreserving(conn, tableName);
+ conn.createStatement().execute(
+ "ALTER TABLE " + tableName + " SET " + PhoenixDatabaseMetaData.GUIDE_POSTS_WIDTH +
+ "=100");
+ testAvgGroupByDescOrderPreserving(conn, tableName);
+ conn.createStatement().execute(
+ "ALTER TABLE " + tableName + " SET " + PhoenixDatabaseMetaData.GUIDE_POSTS_WIDTH +
+ "=null");
+ testAvgGroupByDescOrderPreserving(conn, tableName);
+ }
+
+ @Override
+ protected void testCountNullInNonEmptyKeyValueCF(int columnEncodedBytes) throws Exception {
+ try (Connection conn = DriverManager.getConnection(getUrl())) {
+ //Type is INT
+ String intTableName = generateUniqueName();
+ TABLE_NAMES.add(intTableName);
+ String sql = "create table " + intTableName +
+ " (mykey integer not null primary key, A.COLA integer, B.COLB integer) "
+ +
+ "IMMUTABLE_ROWS=true, IMMUTABLE_STORAGE_SCHEME = ONE_CELL_PER_COLUMN, COLUMN_ENCODED_BYTES = " +
+ columnEncodedBytes + ", DISABLE_WAL=true";
+
+ conn.createStatement().execute(sql);
+ conn.createStatement().execute("UPSERT INTO " + intTableName + " VALUES (1,1)");
+ conn.createStatement().execute("UPSERT INTO " + intTableName + " VALUES (2,1)");
+ conn.createStatement().execute("UPSERT INTO " + intTableName + " VALUES (3,1,2)");
+ conn.createStatement().execute("UPSERT INTO " + intTableName + " VALUES (4,1)");
+ conn.createStatement().execute("UPSERT INTO " + intTableName + " VALUES (5,1)");
+ conn.commit();
+
+ sql = "select count(*) from " + intTableName;
+ QueryBuilder queryBuilder = new QueryBuilder()
+ .setSelectExpression("COUNT(*)")
+ .setFullTableName(intTableName);
+ ResultSet rs = executeQuery(conn, queryBuilder);
+ assertTrue(rs.next());
+ assertEquals(5, rs.getLong(1));
+
+ sql = "select count(*) from " + intTableName + " where b.colb is not null";
+ queryBuilder.setWhereClause("B.COLB IS NOT NULL");
+ rs = executeQuery(conn, queryBuilder);
+ assertTrue(rs.next());
+ assertEquals(1, rs.getLong(1));
+
+ sql = "select count(*) from " + intTableName + " where b.colb is null";
+ queryBuilder.setWhereClause("B.COLB IS NULL");
+ rs = executeQuery(conn, queryBuilder);
+ assertTrue(rs.next());
+ assertEquals(4, rs.getLong(1));
+ }
+ }
+
+ @Test
+ public void testOrderByOptimizeForClientAggregatePlanBug4820() throws Exception {
+ doTestOrderByOptimizeForClientAggregatePlanBug4820(false, false);
+ doTestOrderByOptimizeForClientAggregatePlanBug4820(false, true);
+ doTestOrderByOptimizeForClientAggregatePlanBug4820(true, false);
+ doTestOrderByOptimizeForClientAggregatePlanBug4820(true, true);
+ }
+
+ private void doTestOrderByOptimizeForClientAggregatePlanBug4820(boolean desc, boolean salted)
+ throws Exception {
+ Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
+ try (Connection conn = DriverManager.getConnection(getUrl(), props)) {
+ String tableName = generateUniqueName();
+ TABLE_NAMES.add(tableName);
+ String sql = "create table " + tableName + "( " +
+ " pk1 varchar not null , " +
+ " pk2 varchar not null, " +
+ " pk3 varchar not null," +
+ " v1 varchar, " +
+ " v2 varchar, " +
+ " CONSTRAINT TEST_PK PRIMARY KEY ( " +
+ "pk1 " + (desc ? "desc" : "") + ", " +
+ "pk2 " + (desc ? "desc" : "") + ", " +
+ "pk3 " + (desc ? "desc" : "") +
+ " )) " + (salted ? "SALT_BUCKETS =4" : "split on('b')");
+ conn.createStatement().execute(sql);
+
+ conn.createStatement().execute(
+ "UPSERT INTO " + tableName + " VALUES ('a11','a12','a13','a14','a15')");
+ conn.createStatement().execute(
+ "UPSERT INTO " + tableName + " VALUES ('a21','a22','a23','a24','a25')");
+ conn.createStatement().execute(
+ "UPSERT INTO " + tableName + " VALUES ('a31','a32','a33','a34','a35')");
+ conn.createStatement().execute(
+ "UPSERT INTO " + tableName + " VALUES ('b11','b12','b13','b14','b15')");
+ conn.createStatement().execute(
+ "UPSERT INTO " + tableName + " VALUES ('b21','b22','b23','b24','b25')");
+ conn.createStatement().execute(
+ "UPSERT INTO " + tableName + " VALUES ('b31','b32','b33','b34','b35')");
+ conn.commit();
+
+ sql = "select a.ak3 " +
+ "from (select pk1 ak1,pk2 ak2,pk3 ak3, substr(v1,1,1) av1,substr(v2,1,1) av2 from " +
+ tableName + " order by pk2,pk3 limit 10) a " +
+ "group by a.ak3,a.av1 order by a.ak3 desc,a.av1";
+ ResultSet rs = conn.prepareStatement(sql).executeQuery();
+ assertResultSet(rs,
+ new Object[][]{{"b33"}, {"b23"}, {"b13"}, {"a33"}, {"a23"}, {"a13"}},
+ tableName);
+
+ sql = "select a.ak3 " +
+ "from (select pk1 ak1,pk2 ak2,pk3 ak3, substr(v1,1,1) av1,substr(v2,1,1) av2 from " +
+ tableName + " order by pk2,pk3 limit 10) a " +
+ "group by a.ak3,a.av1 order by a.ak3,a.av1";
+ rs = conn.prepareStatement(sql).executeQuery();
+ assertResultSet(rs,
+ new Object[][]{{"a13"}, {"a23"}, {"a33"}, {"b13"}, {"b23"}, {"b33"}},
+ tableName);
+
+ sql = "select a.ak3 " +
+ "from (select pk1 ak1,pk2 ak2,pk3 ak3,substr(v1,1,1) av1,substr(v2,1,1) av2 from " +
+ tableName + " order by pk2,pk3 limit 10) a " +
+ "where a.av1 = 'a' group by a.av1,a.ak3 order by a.ak3 desc";
+ rs = conn.prepareStatement(sql).executeQuery();
+ assertResultSet(rs, new Object[][]{{"a33"}, {"a23"}, {"a13"}}, tableName);
+
+ sql = "select a.ak3 " +
+ "from (select pk1 ak1,pk2 ak2,pk3 ak3,substr(v1,1,1) av1,substr(v2,1,1) av2 from " +
+ tableName + " order by pk2,pk3 limit 10) a " +
+ "where a.av1 = 'a' group by a.av1,a.ak3 order by a.ak3";
+ rs = conn.prepareStatement(sql).executeQuery();
+ assertResultSet(rs, new Object[][]{{"a13"}, {"a23"}, {"a33"}}, tableName);
+
+ sql = "select a.ak3 " +
+ "from (select pk1 ak1,pk2 ak2,pk3 ak3,substr(v1,1,1) av1,substr(v2,1,1) av2 from " +
+ tableName + " order by pk2,pk3 limit 10) a " +
+ "where a.av1 = 'b' and a.av2= 'b' group by CASE WHEN a.av1 > a.av2 THEN a.av1 ELSE a.av2 END,a.ak3,a.ak2 order by a.ak3 desc,a.ak2 desc";
+ rs = conn.prepareStatement(sql).executeQuery();
+ assertResultSet(rs, new Object[][]{{"b33"}, {"b23"}, {"b13"}}, tableName);
+
+ sql = "select a.ak3 " +
+ "from (select pk1 ak1,pk2 ak2,pk3 ak3,substr(v1,1,1) av1,substr(v2,1,1) av2 from " +
+ tableName + " order by pk2,pk3 limit 10) a " +
+ "where a.av1 = 'b' and a.av2= 'b' group by CASE WHEN a.av1 > a.av2 THEN a.av1 ELSE a.av2 END,a.ak3,a.ak2 order by a.ak3,a.ak2 desc";
+ rs = conn.prepareStatement(sql).executeQuery();
+ assertResultSet(rs, new Object[][]{{"b13"}, {"b23"}, {"b33"}}, tableName);
+
+ tableName = generateUniqueName();
+ sql = "create table " + tableName + "( " +
+ " pk1 double not null , " +
+ " pk2 double not null, " +
+ " pk3 double not null," +
+ " v1 varchar, " +
+ " CONSTRAINT TEST_PK PRIMARY KEY ( " +
+ "pk1 " + (desc ? "desc" : "") + ", " +
+ "pk2 " + (desc ? "desc" : "") + ", " +
+ "pk3 " + (desc ? "desc" : "") +
+ " )) " + (salted ? "SALT_BUCKETS =4" : "split on(2.3)");
+ conn.createStatement().execute(sql);
+ conn.createStatement()
+ .execute("UPSERT INTO " + tableName + " VALUES (2.1,2.11,2.12,'e')");
+ conn.createStatement()
+ .execute("UPSERT INTO " + tableName + " VALUES (2.2,2.21,2.23,'d')");
+ conn.createStatement()
+ .execute("UPSERT INTO " + tableName + " VALUES (2.3,2.31,2.32,'c')");
+ conn.createStatement()
+ .execute("UPSERT INTO " + tableName + " VALUES (2.4,2.41,2.42,'b')");
+ conn.createStatement()
+ .execute("UPSERT INTO " + tableName + " VALUES (2.5,2.51,2.52,'a')");
+ conn.commit();
+
+ sql = "select a.av1 " +
+ "from (select pk1 ak1,pk2 ak2,pk3 ak3, substr(v1,1,1) av1 from " + tableName +
+ " order by pk1,pk2 limit 10) a " +
+ "where cast(a.ak1 as integer)=2 group by a.ak1,a.av1 order by a.av1";
+ rs = conn.prepareStatement(sql).executeQuery();
+ assertResultSet(rs, new Object[][]{{"a"}, {"b"}, {"c"}, {"d"}, {"e"}}, tableName);
+
+ }
+ }
+
+ @Test
+ public void testDistinctAggregatingResultIteratorBug6507() throws Exception {
+ doTestDistinctAggregatingResultIteratorBug6507(false, false);
+ doTestDistinctAggregatingResultIteratorBug6507(false, true);
+ doTestDistinctAggregatingResultIteratorBug6507(true, false);
+ doTestDistinctAggregatingResultIteratorBug6507(true, true);
+ }
+
+ private void doTestDistinctAggregatingResultIteratorBug6507(boolean desc, boolean salted)
+ throws Exception {
+ Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
+ Connection conn = null;
+ try {
+ conn = DriverManager.getConnection(getUrl(), props);
+ String tableName = generateUniqueName();
+ TABLE_NAMES.add(tableName);
+ String sql = "create table " + tableName + "( " +
+ " pk1 varchar not null , " +
+ " pk2 varchar not null, " +
+ " pk3 varchar not null," +
+ " v1 varchar, " +
+ " v2 varchar, " +
+ " CONSTRAINT TEST_PK PRIMARY KEY ( " +
+ "pk1 " + (desc ? "desc" : "") + ", " +
+ "pk2 " + (desc ? "desc" : "") + ", " +
+ "pk3 " + (desc ? "desc" : "") +
+ " )) " + (salted ? "SALT_BUCKETS =4" : "split on('b')");
+ conn.createStatement().execute(sql);
+
+ conn.createStatement().execute(
+ "UPSERT INTO " + tableName + " VALUES ('a11','a12','a13','a14','a15')");
+ conn.createStatement().execute(
+ "UPSERT INTO " + tableName + " VALUES ('a21','a22','a23','a24','a25')");
+ conn.createStatement().execute(
+ "UPSERT INTO " + tableName + " VALUES ('a31','a32','a33','a38','a35')");
+ conn.createStatement().execute(
+ "UPSERT INTO " + tableName + " VALUES ('b11','b12','b13','b14','b15')");
+ conn.createStatement().execute(
+ "UPSERT INTO " + tableName + " VALUES ('b21','b22','b23','b24','b25')");
+ conn.createStatement().execute(
+ "UPSERT INTO " + tableName + " VALUES ('b31','b32','b33','b34','b35')");
+ conn.createStatement().execute(
+ "UPSERT INTO " + tableName + " VALUES ('a31','c12','c13','a34','a35')");
+ conn.createStatement().execute(
+ "UPSERT INTO " + tableName + " VALUES ('a31','a32','c13','a34','a35')");
+ conn.createStatement().execute(
+ "UPSERT INTO " + tableName + " VALUES ('a31','a32','d13','a35','a35')");
+ conn.createStatement().execute(
+ "UPSERT INTO " + tableName + " VALUES ('d31','a32','c13','a35','a35')");
+ conn.commit();
+
+ sql = "select distinct pk1,max(v1) from " + tableName +
+ " group by pk1,pk2,pk3 order by pk1,pk2,pk3";
+
+ ResultSet rs = conn.prepareStatement(sql).executeQuery();
+ assertResultSet(rs, new Object[][]{
+ {"a11", "a14"},
+ {"a21", "a24"},
+ {"a31", "a38"},
+ {"a31", "a34"},
+ {"a31", "a35"},
+ {"b11", "b14"},
+ {"b21", "b24"},
+ {"b31", "b34"},
+ {"d31", "a35"}},
+ tableName);
+
+ sql = "select distinct pk2,max(v1) from " + tableName +
+ " group by pk2,pk3 order by pk2,pk3";
+
+ rs = conn.prepareStatement(sql).executeQuery();
+ assertResultSet(rs, new Object[][]{
+ {"a12", "a14"},
+ {"a22", "a24"},
+ {"a32", "a38"},
+ {"a32", "a35"},
+ {"b12", "b14"},
+ {"b22", "b24"},
+ {"b32", "b34"},
+ {"c12", "a34"}},
+ tableName);
+ } finally {
+ if (conn != null) {
+ conn.close();
+ }
+ }
+ }
+}
+
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/BackwardCompatibilityIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/BackwardCompatibilityIT.java
index 00ac01a689..3864292cbd 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/BackwardCompatibilityIT.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/BackwardCompatibilityIT.java
@@ -22,12 +22,20 @@ import static org.apache.phoenix.end2end.BackwardCompatibilityTestUtil.ADD_DELET
import static org.apache.phoenix.end2end.BackwardCompatibilityTestUtil.ADD_VIEW_INDEX;
import static org.apache.phoenix.end2end.BackwardCompatibilityTestUtil.CREATE_ADD;
import static org.apache.phoenix.end2end.BackwardCompatibilityTestUtil.CREATE_DIVERGED_VIEW;
+import static org.apache.phoenix.end2end.BackwardCompatibilityTestUtil.CREATE_OFFSET;
+import static org.apache.phoenix.end2end.BackwardCompatibilityTestUtil.CREATE_ORDERED_GROUP_BY;
+import static org.apache.phoenix.end2end.BackwardCompatibilityTestUtil.CREATE_ORDER_BY_NON_PK;
+import static org.apache.phoenix.end2end.BackwardCompatibilityTestUtil.CREATE_UNORDERED_GROUP_BY;
import static org.apache.phoenix.end2end.BackwardCompatibilityTestUtil.INDEX_REBUILD_ASYNC;
import static org.apache.phoenix.end2end.BackwardCompatibilityTestUtil.QUERY_ADD_DATA;
import static org.apache.phoenix.end2end.BackwardCompatibilityTestUtil.QUERY_ADD_DELETE;
import static org.apache.phoenix.end2end.BackwardCompatibilityTestUtil.QUERY_CREATE_ADD;
import static org.apache.phoenix.end2end.BackwardCompatibilityTestUtil.QUERY_CREATE_DIVERGED_VIEW;
import static org.apache.phoenix.end2end.BackwardCompatibilityTestUtil.QUERY_INDEX_REBUILD_ASYNC;
+import static org.apache.phoenix.end2end.BackwardCompatibilityTestUtil.QUERY_OFFSET;
+import static org.apache.phoenix.end2end.BackwardCompatibilityTestUtil.QUERY_ORDERED_GROUP_BY;
+import static org.apache.phoenix.end2end.BackwardCompatibilityTestUtil.QUERY_ORDER_BY_NON_PK;
+import static org.apache.phoenix.end2end.BackwardCompatibilityTestUtil.QUERY_UNORDERED_GROUP_BY;
import static org.apache.phoenix.end2end.BackwardCompatibilityTestUtil.QUERY_VIEW_INDEX;
import static org.apache.phoenix.end2end.BackwardCompatibilityTestUtil.assertExpectedOutput;
import static org.apache.phoenix.end2end.BackwardCompatibilityTestUtil.checkForPreConditions;
@@ -63,6 +71,7 @@ import org.apache.phoenix.schema.SystemTaskSplitPolicy;
import org.apache.phoenix.util.PhoenixRuntime;
import org.apache.phoenix.util.ServerUtil.ConnectionFactory;
import org.junit.After;
+import org.junit.Assume;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;
@@ -438,4 +447,85 @@ public class BackwardCompatibilityIT {
executeQueryWithClientVersion(compatibleClientVersion, QUERY_VIEW_INDEX, zkQuorum);
assertExpectedOutput(QUERY_VIEW_INDEX);
}
+
+ @Test
+ public void testUnorderedGroupByAddDataByOldClientReadByNewClient() throws Exception {
+ executeQueryWithClientVersion(compatibleClientVersion, CREATE_UNORDERED_GROUP_BY, zkQuorum);
+ executeQueriesWithCurrentVersion(QUERY_UNORDERED_GROUP_BY, url, NONE);
+ assertExpectedOutput(QUERY_UNORDERED_GROUP_BY);
+ }
+
+ @Test
+ public void testUnorderedGroupByAddDataByNewClientReadByOldClient() throws Exception {
+ executeQueriesWithCurrentVersion(CREATE_UNORDERED_GROUP_BY, url, NONE);
+ executeQueryWithClientVersion(compatibleClientVersion, QUERY_UNORDERED_GROUP_BY, zkQuorum);
+ assertExpectedOutput(QUERY_UNORDERED_GROUP_BY);
+ }
+
+ @Test
+ public void testOrderedGroupByAddDataByOldClientReadByNewClient() throws Exception {
+ executeQueryWithClientVersion(compatibleClientVersion, CREATE_ORDERED_GROUP_BY, zkQuorum);
+ executeQueriesWithCurrentVersion(QUERY_ORDERED_GROUP_BY, url, NONE);
+ assertExpectedOutput(QUERY_ORDERED_GROUP_BY);
+ }
+
+ @Test
+ public void testOrderedGroupByAddDataByNewClientReadByOldClient() throws Exception {
+ Assume.assumeTrue("compatible client version should be >= 5.1.3",
+ isClientCompatibleForOrderedGroupByQuery());
+ executeQueriesWithCurrentVersion(CREATE_ORDERED_GROUP_BY, url, NONE);
+ executeQueryWithClientVersion(compatibleClientVersion, QUERY_ORDERED_GROUP_BY, zkQuorum);
+ assertExpectedOutput(QUERY_ORDERED_GROUP_BY);
+ }
+
+ @Test
+ public void testOffsetAddDataByOldClientReadByNewClient() throws Exception {
+ executeQueryWithClientVersion(compatibleClientVersion, CREATE_OFFSET, zkQuorum);
+ executeQueriesWithCurrentVersion(QUERY_OFFSET, url, NONE);
+ assertExpectedOutput(QUERY_OFFSET);
+ }
+
+ @Test
+ public void testOffsetAddDataByNewClientReadByOldClient() throws Exception {
+ executeQueriesWithCurrentVersion(CREATE_OFFSET, url, NONE);
+ executeQueryWithClientVersion(compatibleClientVersion, QUERY_OFFSET, zkQuorum);
+ assertExpectedOutput(QUERY_OFFSET);
+ }
+
+ @Test
+ public void testOrderByNonPkAddDataByOldClientReadByNewClient() throws Exception {
+ executeQueryWithClientVersion(compatibleClientVersion, CREATE_ORDER_BY_NON_PK,
+ zkQuorum);
+ executeQueriesWithCurrentVersion(QUERY_ORDER_BY_NON_PK, url, NONE);
+ assertExpectedOutput(QUERY_ORDER_BY_NON_PK);
+ }
+
+ @Test
+ public void testOrderByNonPkAddDataByNewClientReadByOldClient() throws Exception {
+ executeQueriesWithCurrentVersion(CREATE_ORDER_BY_NON_PK, url, NONE);
+ executeQueryWithClientVersion(compatibleClientVersion, QUERY_ORDER_BY_NON_PK,
+ zkQuorum);
+ assertExpectedOutput(QUERY_ORDER_BY_NON_PK);
+ }
+
+ private boolean isClientCompatibleForOrderedGroupByQuery() {
+ String[] clientVersion = compatibleClientVersion.getVersion().split("\\.");
+ int majorVersion = Integer.parseInt(clientVersion[0]);
+ int minorVersion = Integer.parseInt(clientVersion[1]);
+ int patchVersion = Integer.parseInt(clientVersion[2]);
+ if (majorVersion > 5) {
+ return true;
+ }
+ if (majorVersion < 5) {
+ return false;
+ }
+ if (minorVersion > 1) {
+ return true;
+ }
+ if (minorVersion < 1) {
+ return false;
+ }
+ return patchVersion >= 3;
+ }
+
}
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/BackwardCompatibilityTestUtil.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/BackwardCompatibilityTestUtil.java
index fe02eed05b..6082967199 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/BackwardCompatibilityTestUtil.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/BackwardCompatibilityTestUtil.java
@@ -73,6 +73,14 @@ public final class BackwardCompatibilityTestUtil {
public static final String CREATE_ADD = "create_add";
public static final String CREATE_TMP_TABLE = "create_tmp_table";
public static final String CREATE_DIVERGED_VIEW = "create_diverged_view";
+ public static final String UNORDERED_GROUP_BY = "unorder_groupby";
+ public static final String ORDERED_GROUP_BY = "ordered_groupby";
+ public static final String ORDER_BY_NON_PK = "orderby_nonpk";
+ public static final String OFFSET = "offset";
+ public static final String CREATE_UNORDERED_GROUP_BY = "create_" + UNORDERED_GROUP_BY;
+ public static final String CREATE_ORDERED_GROUP_BY = "create_" + ORDERED_GROUP_BY;
+ public static final String CREATE_ORDER_BY_NON_PK = "create_" + ORDER_BY_NON_PK;
+ public static final String CREATE_OFFSET = "create_" + OFFSET;
public static final String ADD_DATA = "add_data";
public static final String ADD_DELETE = "add_delete";
public static final String ADD_VIEW_INDEX = "add_view_index";
@@ -80,6 +88,10 @@ public final class BackwardCompatibilityTestUtil {
public static final String DELETE_FOR_SPLITABLE_SYSCAT = "delete_for_splitable_syscat";
public static final String VIEW_INDEX = "view_index";
public static final String SELECT_AND_DROP_TABLE = "select_and_drop_table";
+ public static final String QUERY_UNORDERED_GROUP_BY = QUERY_PREFIX + UNORDERED_GROUP_BY;
+ public static final String QUERY_ORDERED_GROUP_BY = QUERY_PREFIX + ORDERED_GROUP_BY;
+ public static final String QUERY_OFFSET = QUERY_PREFIX + OFFSET;
+ public static final String QUERY_ORDER_BY_NON_PK = QUERY_PREFIX + ORDER_BY_NON_PK;
public static final String QUERY_CREATE_ADD = QUERY_PREFIX + CREATE_ADD;
public static final String QUERY_ADD_DATA = QUERY_PREFIX + ADD_DATA;
public static final String QUERY_ADD_DELETE = QUERY_PREFIX + ADD_DELETE;
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/BaseAggregateWithRegionMoves2IT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/BaseAggregateWithRegionMoves2IT.java
new file mode 100644
index 0000000000..2e6c15a651
--- /dev/null
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/BaseAggregateWithRegionMoves2IT.java
@@ -0,0 +1,633 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.phoenix.end2end;
+
+import org.apache.phoenix.compile.ExplainPlan;
+import org.apache.phoenix.compile.ExplainPlanAttributes;
+import org.apache.phoenix.jdbc.PhoenixPreparedStatement;
+import org.apache.phoenix.query.KeyRange;
+import org.apache.phoenix.query.QueryServices;
+import org.apache.phoenix.schema.types.PChar;
+import org.apache.phoenix.schema.types.PInteger;
+import org.apache.phoenix.thirdparty.com.google.common.collect.Lists;
+import org.apache.phoenix.util.ByteUtil;
+import org.apache.phoenix.util.PropertiesUtil;
+import org.apache.phoenix.util.QueryBuilder;
+import org.apache.phoenix.util.TestUtil;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+
+import java.io.IOException;
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.util.List;
+import java.util.Properties;
+
+import static org.apache.phoenix.util.TestUtil.TEST_PROPERTIES;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+
+@Category(NeedsOwnMiniClusterTest.class)
+public class BaseAggregateWithRegionMoves2IT extends ParallelStatsDisabledWithRegionMovesIT {
+
+ @Before
+ public void setUp() throws Exception {
+ hasTestStarted = true;
+ }
+
+ @After
+ public void tearDown() throws Exception {
+ countOfDummyResults = 0;
+ TABLE_NAMES.clear();
+ hasTestStarted = false;
+ }
+
+ @Test
+ public void testGroupByArray() throws Exception {
+ Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
+ Connection conn = DriverManager.getConnection(getUrl(), props);
+
+ String tableName = generateUniqueName();
+ TABLE_NAMES.add(tableName);
+ conn.createStatement().execute("CREATE TABLE " + tableName + "(\n" +
+ " a VARCHAR NOT NULL,\n" +
+ " b VARCHAR,\n" +
+ " c INTEGER,\n" +
+ " d VARCHAR,\n" +
+ " e VARCHAR ARRAY,\n" +
+ " f BIGINT,\n" +
+ " g BIGINT,\n" +
+ " CONSTRAINT pk PRIMARY KEY(a)\n" +
+ ")");
+ conn.createStatement().execute(
+ "UPSERT INTO " + tableName + " VALUES('1', 'val', 100, 'a', ARRAY ['b'], 1, 2)");
+ conn.createStatement().execute(
+ "UPSERT INTO " + tableName + " VALUES('2', 'val', 100, 'a', ARRAY ['b'], 3, 4)");
+ conn.createStatement().execute("UPSERT INTO " + tableName +
+ " VALUES('3', 'val', 100, 'a', ARRAY ['b','c'], 5, 6)");
+ conn.commit();
+
+ QueryBuilder queryBuilder = new QueryBuilder()
+ .setSelectExpression("C, SUM(F + G) AS SUMONE, D, E")
+ .setSelectExpressionColumns(Lists.newArrayList("A", "B", "C", "F", "G", "D", "E"))
+ .setWhereClause("B = 'val' AND A IN ('1','2','3')")
+ .setFullTableName(tableName)
+ .setGroupByClause("C, D, E")
+ .setOrderByClause("SUMONE desc");
+ ResultSet rs = executeQuery(conn, queryBuilder);
+ assertTrue(rs.next());
+ moveRegionsOfTable(tableName);
+ assertEquals(100, rs.getInt(1));
+ assertEquals(11, rs.getLong(2));
+ assertTrue(rs.next());
+ assertEquals(100, rs.getInt(1));
+ assertEquals(10, rs.getLong(2));
+ assertFalse(rs.next());
+ conn.close();
+ }
+
+ @Test
+ public void testGroupByOrderPreserving() throws Exception {
+ Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
+ props.put(QueryServices.FORCE_ROW_KEY_ORDER_ATTRIB, Boolean.FALSE.toString());
+ Connection conn = DriverManager.getConnection(getUrl(), props);
+ String tableName = generateUniqueName();
+ TABLE_NAMES.add(tableName);
+
+ conn.createStatement()
+ .execute("CREATE TABLE " + tableName + "(ORGANIZATION_ID char(15) not null, \n" +
+ "JOURNEY_ID char(15) not null, \n" +
+ "DATASOURCE SMALLINT not null, \n" +
+ "MATCH_STATUS TINYINT not null, \n" +
+ "EXTERNAL_DATASOURCE_KEY varchar(30), \n" +
+ "ENTITY_ID char(15) not null, \n" +
+ "CONSTRAINT PK PRIMARY KEY (\n" +
+ " ORGANIZATION_ID, \n" +
+ " JOURNEY_ID, \n" +
+ " DATASOURCE, \n" +
+ " MATCH_STATUS,\n" +
+ " EXTERNAL_DATASOURCE_KEY,\n" +
+ " ENTITY_ID))");
+ conn.createStatement().execute("UPSERT INTO " + tableName
+ + " VALUES('000001111122222', '333334444455555', 0, 0, 'abc', '666667777788888')");
+ conn.createStatement().execute("UPSERT INTO " + tableName
+ + " VALUES('000001111122222', '333334444455555', 0, 0, 'abcd', '666667777788889')");
+ conn.createStatement().execute("UPSERT INTO " + tableName
+ + " VALUES('000001111122222', '333334444455555', 0, 0, 'abc', '666667777788899')");
+ conn.commit();
+ QueryBuilder queryBuilder = new QueryBuilder()
+ .setSelectExpression("COUNT(1), EXTERNAL_DATASOURCE_KEY As DUP_COUNT")
+ .setSelectExpressionColumns(
+ Lists.newArrayList("EXTERNAL_DATASOURCE_KEY", "MATCH_STATUS",
+ "JOURNEY_ID", "DATASOURCE", "ORGANIZATION_ID"))
+ .setWhereClause(
+ "JOURNEY_ID='333334444455555' AND DATASOURCE=0 AND MATCH_STATUS <= 1 and ORGANIZATION_ID='000001111122222'")
+ .setFullTableName(tableName)
+ .setGroupByClause("MATCH_STATUS, EXTERNAL_DATASOURCE_KEY")
+ .setHavingClause("COUNT(1) > 1");
+ ResultSet rs = executeQuery(conn, queryBuilder);
+ assertTrue(rs.next());
+ moveRegionsOfTable(tableName);
+ assertEquals(2, rs.getLong(1));
+ assertEquals("abc", rs.getString(2));
+ assertFalse(rs.next());
+
+ ExplainPlan plan = conn.prepareStatement(queryBuilder.build())
+ .unwrap(PhoenixPreparedStatement.class).optimizeQuery()
+ .getExplainPlan();
+ ExplainPlanAttributes explainPlanAttributes =
+ plan.getPlanStepsAsAttributes();
+ assertEquals("PARALLEL 1-WAY",
+ explainPlanAttributes.getIteratorTypeAndScanSize());
+ assertEquals("RANGE SCAN ", explainPlanAttributes.getExplainScanType());
+ assertEquals(tableName, explainPlanAttributes.getTableName());
+ assertEquals(
+ " ['000001111122222','333334444455555',0,*] - ['000001111122222','333334444455555',0,1]",
+ explainPlanAttributes.getKeyRanges());
+ assertEquals("SERVER FILTER BY FIRST KEY ONLY",
+ explainPlanAttributes.getServerWhereFilter());
+ assertEquals(
+ "SERVER AGGREGATE INTO ORDERED DISTINCT ROWS BY [MATCH_STATUS, EXTERNAL_DATASOURCE_KEY]",
+ explainPlanAttributes.getServerAggregate());
+ assertEquals("COUNT(1) > 1", explainPlanAttributes.getClientFilterBy());
+ }
+
+ @Test
+ public void testGroupByOrderPreservingDescSort() throws Exception {
+ Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
+ Connection conn = DriverManager.getConnection(getUrl(), props);
+ String tableName = generateUniqueName();
+ TABLE_NAMES.add(tableName);
+ conn.createStatement().execute("DROP TABLE IF EXISTS " + tableName + " CASCADE");
+ conn.createStatement().execute(
+ "CREATE TABLE " + tableName + " (k1 char(1) not null, k2 char(1) not null," +
+ " constraint pk primary key (k1,k2)) split on ('ac','jc','nc')");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 'a')");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 'b')");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 'c')");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 'd')");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 'a')");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 'b')");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 'c')");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 'd')");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 'a')");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 'b')");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 'c')");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 'd')");
+ conn.commit();
+ QueryBuilder queryBuilder = new QueryBuilder()
+ .setSelectExpression("K1,COUNT(*)")
+ .setSelectColumns(Lists.newArrayList("K1"))
+ .setFullTableName(tableName)
+ .setGroupByClause("K1")
+ .setOrderByClause("K1 DESC");
+ ResultSet rs = executeQuery(conn, queryBuilder);
+ assertTrue(rs.next());
+ assertEquals("n", rs.getString(1));
+ assertEquals(4, rs.getLong(2));
+ assertTrue(rs.next());
+ assertEquals("j", rs.getString(1));
+ assertEquals(4, rs.getLong(2));
+ assertTrue(rs.next());
+ assertEquals("a", rs.getString(1));
+ assertEquals(4, rs.getLong(2));
+ assertFalse(rs.next());
+ ExplainPlan plan = conn.prepareStatement(queryBuilder.build())
+ .unwrap(PhoenixPreparedStatement.class).optimizeQuery()
+ .getExplainPlan();
+ ExplainPlanAttributes explainPlanAttributes =
+ plan.getPlanStepsAsAttributes();
+ assertEquals("PARALLEL 1-WAY",
+ explainPlanAttributes.getIteratorTypeAndScanSize());
+ assertEquals("REVERSE", explainPlanAttributes.getClientSortedBy());
+ assertEquals("FULL SCAN ", explainPlanAttributes.getExplainScanType());
+ assertEquals(tableName, explainPlanAttributes.getTableName());
+ assertEquals("SERVER FILTER BY FIRST KEY ONLY",
+ explainPlanAttributes.getServerWhereFilter());
+ assertEquals("SERVER AGGREGATE INTO ORDERED DISTINCT ROWS BY [K1]",
+ explainPlanAttributes.getServerAggregate());
+ }
+
+ @Test
+ public void testSumGroupByOrderPreservingDesc() throws Exception {
+ Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
+ Connection conn = DriverManager.getConnection(getUrl(), props);
+ String tableName = generateUniqueName();
+ TABLE_NAMES.add(tableName);
+
+ PreparedStatement stmt = conn.prepareStatement("CREATE TABLE " + tableName +
+ " (k1 char(1) not null, k2 integer not null, constraint pk primary key (k1,k2)) split on (?,?,?)");
+ stmt.setBytes(1,
+ ByteUtil.concat(PChar.INSTANCE.toBytes("a"), PInteger.INSTANCE.toBytes(3)));
+ stmt.setBytes(2,
+ ByteUtil.concat(PChar.INSTANCE.toBytes("j"), PInteger.INSTANCE.toBytes(3)));
+ stmt.setBytes(3,
+ ByteUtil.concat(PChar.INSTANCE.toBytes("n"), PInteger.INSTANCE.toBytes(3)));
+ stmt.execute();
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 1)");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 2)");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 3)");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 4)");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('b', 5)");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 1)");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 2)");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 3)");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 4)");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 1)");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 2)");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 3)");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 4)");
+ conn.commit();
+ QueryBuilder queryBuilder = new QueryBuilder()
+ .setSelectExpression("K1,SUM(K2)")
+ .setSelectExpressionColumns(Lists.newArrayList("K1", "K2"))
+ .setFullTableName(tableName)
+ .setGroupByClause("K1")
+ .setOrderByClause("K1 DESC");
+ ResultSet rs = executeQuery(conn, queryBuilder);
+ assertTrue(rs.next());
+ moveRegionsOfTable(tableName);
+ assertEquals("n", rs.getString(1));
+ assertEquals(10, rs.getLong(2));
+ assertTrue(rs.next());
+ assertEquals("j", rs.getString(1));
+ assertEquals(10, rs.getLong(2));
+ assertTrue(rs.next());
+ moveRegionsOfTable(tableName);
+ assertEquals("b", rs.getString(1));
+ assertEquals(5, rs.getLong(2));
+ assertTrue(rs.next());
+ moveRegionsOfTable(tableName);
+ assertEquals("a", rs.getString(1));
+ assertEquals(10, rs.getLong(2));
+ assertFalse(rs.next());
+ ExplainPlan plan = conn.prepareStatement(queryBuilder.build())
+ .unwrap(PhoenixPreparedStatement.class).optimizeQuery()
+ .getExplainPlan();
+ ExplainPlanAttributes explainPlanAttributes =
+ plan.getPlanStepsAsAttributes();
+ assertEquals("PARALLEL 1-WAY",
+ explainPlanAttributes.getIteratorTypeAndScanSize());
+ assertEquals("REVERSE", explainPlanAttributes.getClientSortedBy());
+ assertEquals("FULL SCAN ", explainPlanAttributes.getExplainScanType());
+ assertEquals(tableName, explainPlanAttributes.getTableName());
+ assertEquals("SERVER FILTER BY FIRST KEY ONLY",
+ explainPlanAttributes.getServerWhereFilter());
+ assertEquals("SERVER AGGREGATE INTO ORDERED DISTINCT ROWS BY [K1]",
+ explainPlanAttributes.getServerAggregate());
+ }
+
+ @Test
+ public void testSumGroupByOrderPreservingDescWithoutSplit() throws Exception {
+ Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
+ Connection conn = DriverManager.getConnection(getUrl(), props);
+ String tableName = generateUniqueName();
+ TABLE_NAMES.add(tableName);
+
+ PreparedStatement stmt = conn.prepareStatement("CREATE TABLE " + tableName +
+ " (k1 char(1) not null, k2 integer not null, constraint pk primary key (k1,k2))");
+ stmt.execute();
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 1)");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 2)");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 3)");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 4)");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('b', 5)");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 1)");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 2)");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 3)");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 4)");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 1)");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 2)");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 3)");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 4)");
+ conn.commit();
+ QueryBuilder queryBuilder = new QueryBuilder()
+ .setSelectExpression("K1,SUM(K2)")
+ .setSelectExpressionColumns(Lists.newArrayList("K1", "K2"))
+ .setFullTableName(tableName)
+ .setWhereClause("K1 >= 'a' AND K1 < 'o'")
+ .setGroupByClause("K1")
+ .setOrderByClause("K1 DESC");
+ ResultSet rs = executeQuery(conn, queryBuilder);
+ assertTrue(rs.next());
+ moveRegionsOfTable(tableName);
+ assertEquals("n", rs.getString(1));
+ assertEquals(10, rs.getLong(2));
+ assertTrue(rs.next());
+ moveRegionsOfTable(tableName);
+ assertEquals("j", rs.getString(1));
+ assertEquals(10, rs.getLong(2));
+ assertTrue(rs.next());
+ assertEquals("b", rs.getString(1));
+ assertEquals(5, rs.getLong(2));
+ assertTrue(rs.next());
+ assertEquals("a", rs.getString(1));
+ assertEquals(10, rs.getLong(2));
+ assertFalse(rs.next());
+ ExplainPlan plan = conn.prepareStatement(queryBuilder.build())
+ .unwrap(PhoenixPreparedStatement.class).optimizeQuery()
+ .getExplainPlan();
+ ExplainPlanAttributes explainPlanAttributes =
+ plan.getPlanStepsAsAttributes();
+ assertEquals("PARALLEL 1-WAY",
+ explainPlanAttributes.getIteratorTypeAndScanSize());
+ assertEquals("REVERSE", explainPlanAttributes.getClientSortedBy());
+ assertEquals("RANGE SCAN ", explainPlanAttributes.getExplainScanType());
+ assertEquals(tableName, explainPlanAttributes.getTableName());
+ }
+
+ @Test
+ public void testSumGroupByOrderPreservingAsc() throws Exception {
+ Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
+ Connection conn = DriverManager.getConnection(getUrl(), props);
+ String tableName = generateUniqueName();
+ TABLE_NAMES.add(tableName);
+
+ PreparedStatement stmt = conn.prepareStatement("CREATE TABLE " + tableName +
+ " (k1 char(1) not null, k2 integer not null, constraint pk primary key (k1,k2)) split on (?,?,?)");
+ stmt.setBytes(1,
+ ByteUtil.concat(PChar.INSTANCE.toBytes("a"), PInteger.INSTANCE.toBytes(3)));
+ stmt.setBytes(2,
+ ByteUtil.concat(PChar.INSTANCE.toBytes("j"), PInteger.INSTANCE.toBytes(3)));
+ stmt.setBytes(3,
+ ByteUtil.concat(PChar.INSTANCE.toBytes("n"), PInteger.INSTANCE.toBytes(3)));
+ stmt.execute();
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 1)");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 2)");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 3)");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 4)");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('b', 5)");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 1)");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 2)");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 3)");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 4)");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 1)");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 2)");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 3)");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 4)");
+ conn.commit();
+ QueryBuilder queryBuilder = new QueryBuilder()
+ .setSelectExpression("K1,SUM(K2)")
+ .setSelectExpressionColumns(Lists.newArrayList("K1", "K2"))
+ .setFullTableName(tableName)
+ .setGroupByClause("K1")
+ .setOrderByClause("K1 ASC");
+ ResultSet rs = executeQuery(conn, queryBuilder);
+ assertTrue(rs.next());
+ moveRegionsOfTable(tableName);
+ assertEquals("a", rs.getString(1));
+ assertEquals(10, rs.getLong(2));
+ assertTrue(rs.next());
+ assertEquals("b", rs.getString(1));
+ assertEquals(5, rs.getLong(2));
+ assertTrue(rs.next());
+ moveRegionsOfTable(tableName);
+ assertEquals("j", rs.getString(1));
+ assertEquals(10, rs.getLong(2));
+ assertTrue(rs.next());
+ assertEquals("n", rs.getString(1));
+ assertEquals(10, rs.getLong(2));
+ assertFalse(rs.next());
+ }
+
+ @Test
+ public void testSumGroupByOrderPreservingAscWithoutSplits() throws Exception {
+ Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
+ Connection conn = DriverManager.getConnection(getUrl(), props);
+ String tableName = generateUniqueName();
+ TABLE_NAMES.add(tableName);
+
+ PreparedStatement stmt = conn.prepareStatement("CREATE TABLE " + tableName +
+ " (k1 char(1) not null, k2 integer not null, constraint pk primary key (k1,k2))");
+ stmt.execute();
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 1)");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 2)");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 3)");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 4)");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('b', 5)");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 1)");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 2)");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 3)");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 4)");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 1)");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 2)");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 3)");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 4)");
+ conn.commit();
+ QueryBuilder queryBuilder = new QueryBuilder()
+ .setSelectExpression("K1,SUM(K2)")
+ .setSelectExpressionColumns(Lists.newArrayList("K1", "K2"))
+ .setFullTableName(tableName)
+ .setGroupByClause("K1")
+ .setOrderByClause("K1 ASC");
+ ResultSet rs = executeQuery(conn, queryBuilder);
+ assertTrue(rs.next());
+ moveRegionsOfTable(tableName);
+ assertEquals("a", rs.getString(1));
+ assertEquals(10, rs.getLong(2));
+ assertTrue(rs.next());
+ assertEquals("b", rs.getString(1));
+ assertEquals(5, rs.getLong(2));
+ assertTrue(rs.next());
+ moveRegionsOfTable(tableName);
+ assertEquals("j", rs.getString(1));
+ assertEquals(10, rs.getLong(2));
+ assertTrue(rs.next());
+ assertEquals("n", rs.getString(1));
+ assertEquals(10, rs.getLong(2));
+ assertFalse(rs.next());
+ }
+
+ @Test
+ public void testAvgGroupByOrderPreservingWithNoStats() throws Exception {
+ Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
+ Connection conn = DriverManager.getConnection(getUrl(), props);
+ String tableName = generateUniqueName();
+ initAvgGroupTable(conn, tableName, "");
+ testAvgGroupByOrderPreserving(conn, tableName, 4);
+ }
+
+ protected void initAvgGroupTable(Connection conn, String tableName, String tableProps)
+ throws SQLException {
+ PreparedStatement stmt = conn.prepareStatement("CREATE TABLE " + tableName +
+ " (k1 char(1) not null, k2 integer not null, constraint pk primary key (k1,k2)) " +
+ tableProps + " split on (?,?,?)");
+ TABLE_NAMES.add(tableName);
+ stmt.setBytes(1,
+ ByteUtil.concat(PChar.INSTANCE.toBytes("a"), PInteger.INSTANCE.toBytes(3)));
+ stmt.setBytes(2,
+ ByteUtil.concat(PChar.INSTANCE.toBytes("j"), PInteger.INSTANCE.toBytes(3)));
+ stmt.setBytes(3,
+ ByteUtil.concat(PChar.INSTANCE.toBytes("n"), PInteger.INSTANCE.toBytes(3)));
+ stmt.execute();
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 1)");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 2)");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 3)");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 6)");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('b', 5)");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 1)");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 2)");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 3)");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 10)");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 1)");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 2)");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 3)");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 2)");
+ conn.commit();
+ }
+
+ protected void testAvgGroupByOrderPreserving(Connection conn, String tableName, int splitSize)
+ throws SQLException, IOException {
+ TABLE_NAMES.add(tableName);
+ QueryBuilder queryBuilder = new QueryBuilder()
+ .setSelectExpression("K1, AVG(K2)")
+ .setSelectExpressionColumns(Lists.newArrayList("K1", "K2"))
+ .setFullTableName(tableName)
+ .setGroupByClause("K1")
+ .setOrderByClause("K1");
+ ResultSet rs = executeQuery(conn, queryBuilder);
+ assertTrue(rs.next());
+ assertEquals("a", rs.getString(1));
+ assertEquals(3, rs.getDouble(2), 1e-6);
+ assertTrue(rs.next());
+ moveRegionsOfTable(tableName);
+ assertEquals("b", rs.getString(1));
+ assertEquals(5, rs.getDouble(2), 1e-6);
+ assertTrue(rs.next());
+ assertEquals("j", rs.getString(1));
+ assertEquals(4, rs.getDouble(2), 1e-6);
+ assertTrue(rs.next());
+ moveRegionsOfTable(tableName);
+ assertEquals("n", rs.getString(1));
+ assertEquals(2, rs.getDouble(2), 1e-6);
+ assertFalse(rs.next());
+ ExplainPlan plan = conn.prepareStatement(queryBuilder.build())
+ .unwrap(PhoenixPreparedStatement.class).optimizeQuery()
+ .getExplainPlan();
+ ExplainPlanAttributes explainPlanAttributes =
+ plan.getPlanStepsAsAttributes();
+ assertEquals("PARALLEL 1-WAY",
+ explainPlanAttributes.getIteratorTypeAndScanSize());
+ assertEquals("FULL SCAN ", explainPlanAttributes.getExplainScanType());
+ assertEquals(tableName, explainPlanAttributes.getTableName());
+ assertEquals("SERVER FILTER BY FIRST KEY ONLY",
+ explainPlanAttributes.getServerWhereFilter());
+ assertEquals("SERVER AGGREGATE INTO ORDERED DISTINCT ROWS BY [K1]",
+ explainPlanAttributes.getServerAggregate());
+ TestUtil.analyzeTable(conn, tableName);
+ List<KeyRange> splits = TestUtil.getAllSplits(conn, tableName);
+ // nGuideposts when stats are enabled, 4 when disabled
+ assertEquals(splitSize, splits.size());
+ }
+
+ @Test
+ public void testGroupByOrderByDescBug3451() throws Exception {
+ Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
+ try (Connection conn = DriverManager.getConnection(getUrl(), props)) {
+ String tableName = generateUniqueName();
+ String sql = "CREATE TABLE " + tableName + " (\n" +
+ " ORGANIZATION_ID CHAR(15) NOT NULL,\n" +
+ " CONTAINER_ID CHAR(15) NOT NULL,\n" +
+ " ENTITY_ID CHAR(15) NOT NULL,\n" +
+ " SCORE DOUBLE,\n" +
+ " CONSTRAINT TEST_PK PRIMARY KEY (\n" +
+ " ORGANIZATION_ID,\n" +
+ " CONTAINER_ID,\n" +
+ " ENTITY_ID\n" +
+ " )\n" +
+ " )";
+ conn.createStatement().execute(sql);
+ String indexName = generateUniqueName();
+ TABLE_NAMES.add(tableName);
+ TABLE_NAMES.add(indexName);
+ conn.createStatement().execute("CREATE INDEX " + indexName + " ON " + tableName +
+ "(ORGANIZATION_ID,CONTAINER_ID, SCORE DESC, ENTITY_ID DESC)");
+ conn.createStatement().execute(
+ "UPSERT INTO " + tableName + " VALUES ('org2','container2','entityId6',1.1)");
+ conn.createStatement().execute(
+ "UPSERT INTO " + tableName + " VALUES ('org2','container1','entityId5',1.2)");
+ conn.createStatement().execute(
+ "UPSERT INTO " + tableName + " VALUES ('org2','container2','entityId4',1.3)");
+ conn.createStatement().execute(
+ "UPSERT INTO " + tableName + " VALUES ('org2','container1','entityId5',1.2)");
+ conn.createStatement().execute(
+ "UPSERT INTO " + tableName + " VALUES ('org2','container1','entityId3',1.4)");
+ conn.createStatement().execute(
+ "UPSERT INTO " + tableName + " VALUES ('org2','container3','entityId7',1.35)");
+ conn.createStatement().execute(
+ "UPSERT INTO " + tableName + " VALUES ('org2','container3','entityId8',1.45)");
+ conn.commit();
+ QueryBuilder queryBuilder = new QueryBuilder()
+ .setDistinct(true)
+ .setSelectColumns(Lists.newArrayList("ENTITY_ID", "SCORE", "ORGANIZATION_ID",
+ "CONTAINER_ID"))
+ .setFullTableName(tableName)
+ .setWhereClause(
+ "ORGANIZATION_ID = 'org2' AND CONTAINER_ID IN ('container1','container2','container3')")
+ .setOrderByClause("SCORE DESC")
+ .setLimit(2);
+ ResultSet rs = executeQuery(conn, queryBuilder);
+ assertTrue(rs.next());
+ moveRegionsOfTable(tableName);
+ assertEquals("entityId8", rs.getString(1));
+ assertEquals(1.45, rs.getDouble(2), 0.001);
+ assertTrue(rs.next());
+ assertEquals("entityId3", rs.getString(1));
+ assertEquals(1.4, rs.getDouble(2), 0.001);
+ assertFalse(rs.next());
+
+ String expectedPhoenixPlan = "";
+ validateQueryPlan(conn, queryBuilder, expectedPhoenixPlan, null);
+ }
+ }
+
+ protected static void assertResultSet(ResultSet rs, Object[][] rows, String tableName)
+ throws Exception {
+ boolean switchToRegionMove = true;
+ for (int rowIndex = 0; rowIndex < rows.length; rowIndex++) {
+ assertTrue("rowIndex:[" + rowIndex + "] rs.next error!", rs.next());
+ if (switchToRegionMove) {
+ moveRegionsOfTable(tableName);
+ switchToRegionMove = false;
+ } else {
+ switchToRegionMove = true;
+ }
+ for (int columnIndex = 1; columnIndex <= rows[rowIndex].length; columnIndex++) {
+ Object realValue = rs.getObject(columnIndex);
+ Object expectedValue = rows[rowIndex][columnIndex - 1];
+ if (realValue == null) {
+ assertNull("rowIndex:[" + rowIndex + "],columnIndex:[" + columnIndex + "]",
+ expectedValue);
+ } else {
+ assertEquals("rowIndex:[" + rowIndex + "],columnIndex:[" + columnIndex + "]",
+ expectedValue,
+ realValue
+ );
+ }
+ }
+ }
+ assertFalse(rs.next());
+ }
+}
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/BaseAggregateWithRegionMoves3IT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/BaseAggregateWithRegionMoves3IT.java
new file mode 100644
index 0000000000..7e8caf90c0
--- /dev/null
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/BaseAggregateWithRegionMoves3IT.java
@@ -0,0 +1,124 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.phoenix.end2end;
+
+import org.apache.hadoop.hbase.HConstants;
+import org.apache.phoenix.coprocessor.BaseScannerRegionObserver;
+import org.apache.phoenix.coprocessorclient.BaseScannerRegionObserverConstants;
+import org.apache.phoenix.iterate.ScanningResultPostDummyResultCaller;
+import org.apache.phoenix.iterate.ScanningResultPostValidResultCaller;
+import org.apache.phoenix.query.BaseTest;
+import org.apache.phoenix.query.QueryServices;
+import org.apache.phoenix.util.ReadOnlyProps;
+import org.junit.After;
+import org.junit.AfterClass;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.experimental.categories.Category;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.HashMap;
+import java.util.Map;
+
+@Category(NeedsOwnMiniClusterTest.class)
+public class BaseAggregateWithRegionMoves3IT extends BaseAggregateWithRegionMoves2IT {
+
+ private static final Logger LOGGER =
+ LoggerFactory.getLogger(BaseAggregateWithRegionMoves3IT.class);
+
+ private static int countOfValidResults = 0;
+
+ @Before
+ public void setUp() throws Exception {
+ hasTestStarted = true;
+ }
+
+ @After
+ public void tearDown() throws Exception {
+ countOfDummyResults = 0;
+ countOfValidResults = 0;
+ TABLE_NAMES.clear();
+ hasTestStarted = false;
+ }
+
+ private static class TestScanningResultPostDummyResultCaller extends
+ ScanningResultPostDummyResultCaller {
+
+ @Override
+ public void postDummyProcess() {
+ if (hasTestStarted && (countOfDummyResults++ % 3) == 0 &&
+ (countOfDummyResults < 17 ||
+ countOfDummyResults > 28 && countOfDummyResults < 40)) {
+ LOGGER.info("Moving regions of tables {}. current count of dummy results: {}",
+ TABLE_NAMES, countOfDummyResults);
+ TABLE_NAMES.forEach(table -> {
+ try {
+ moveRegionsOfTable(table);
+ } catch (Exception e) {
+ LOGGER.error("Unable to move regions of table: {}", table);
+ }
+ });
+ }
+ }
+ }
+
+ private static class TestScanningResultPostValidResultCaller extends
+ ScanningResultPostValidResultCaller {
+
+ @Override
+ public void postValidRowProcess() {
+ if (hasTestStarted &&
+ (countOfValidResults < 17 ||
+ countOfValidResults > 28 && countOfValidResults < 40)) {
+ LOGGER.info("Moving regions of tables {}. current count of valid results: {}",
+ TABLE_NAMES, countOfValidResults);
+ countOfValidResults++;
+ TABLE_NAMES.forEach(table -> {
+ try {
+ moveRegionsOfTable(table);
+ } catch (Exception e) {
+ LOGGER.error("Unable to move regions of table: {}", table);
+ }
+ });
+ }
+ }
+ }
+
+ @BeforeClass
+ public static synchronized void doSetup() throws Exception {
+ Map<String, String> props = new HashMap<>();
+ props.put(BaseScannerRegionObserverConstants.PHOENIX_MAX_LOOKBACK_AGE_CONF_KEY,
+ Integer.toString(60 * 60)); // An hour
+ props.put(QueryServices.USE_STATS_FOR_PARALLELIZATION, Boolean.toString(false));
+ props.put(QueryServices.PHOENIX_SERVER_PAGE_SIZE_MS, Long.toString(0));
+ props.put(QueryServices.TESTS_MINI_CLUSTER_NUM_REGION_SERVERS, String.valueOf(2));
+ props.put(HConstants.HBASE_CLIENT_SCANNER_MAX_RESULT_SIZE_KEY, String.valueOf(1));
+ props.put(QueryServices.PHOENIX_POST_DUMMY_PROCESS,
+ TestScanningResultPostDummyResultCaller.class.getName());
+ props.put(QueryServices.PHOENIX_POST_VALID_PROCESS,
+ TestScanningResultPostValidResultCaller.class.getName());
+ setUpTestDriver(new ReadOnlyProps(props.entrySet().iterator()));
+ }
+
+ @AfterClass
+ public static synchronized void freeResources() throws Exception {
+ BaseTest.freeResourcesIfBeyondThreshold();
+ }
+
+}
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/BaseAggregateWithRegionMoves4IT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/BaseAggregateWithRegionMoves4IT.java
new file mode 100644
index 0000000000..cab93de4e2
--- /dev/null
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/BaseAggregateWithRegionMoves4IT.java
@@ -0,0 +1,136 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.phoenix.end2end;
+
+import org.apache.hadoop.hbase.HConstants;
+import org.apache.phoenix.coprocessorclient.BaseScannerRegionObserverConstants;
+import org.apache.phoenix.iterate.ScanningResultPostValidResultCaller;
+import org.apache.phoenix.query.BaseTest;
+import org.apache.phoenix.query.QueryServices;
+import org.apache.phoenix.schema.StaleRegionBoundaryCacheException;
+import org.apache.phoenix.util.PropertiesUtil;
+import org.apache.phoenix.util.ReadOnlyProps;
+import org.junit.After;
+import org.junit.AfterClass;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Properties;
+
+import static org.apache.phoenix.util.TestUtil.TEST_PROPERTIES;
+
+@Category(NeedsOwnMiniClusterTest.class)
+public class BaseAggregateWithRegionMoves4IT extends BaseAggregateWithRegionMoves2IT {
+
+ private static final Logger LOGGER =
+ LoggerFactory.getLogger(BaseAggregateWithRegionMoves4IT.class);
+
+ private static int countOfValidResults = 0;
+
+ @Before
+ public void setUp() throws Exception {
+ hasTestStarted = true;
+ }
+
+ @After
+ public void tearDown() throws Exception {
+ countOfDummyResults = 0;
+ countOfValidResults = 0;
+ TABLE_NAMES.clear();
+ hasTestStarted = false;
+ }
+
+ private static class TestScanningResultPostValidResultCaller extends
+ ScanningResultPostValidResultCaller {
+
+ @Override
+ public void postValidRowProcess() {
+ if (hasTestStarted && countOfValidResults <= 1) {
+ LOGGER.info("Splitting regions of tables {}. current count of valid results: {}",
+ TABLE_NAMES, countOfValidResults);
+ countOfValidResults++;
+ TABLE_NAMES.forEach(table -> {
+ try {
+ splitAllRegionsOfTable(table, 2);
+ } catch (Exception e) {
+ LOGGER.error("Unable to move regions of table: {}", table);
+ }
+ });
+ }
+ }
+ }
+
+ @BeforeClass
+ public static synchronized void doSetup() throws Exception {
+ Map<String, String> props = new HashMap<>();
+ props.put(BaseScannerRegionObserverConstants.PHOENIX_MAX_LOOKBACK_AGE_CONF_KEY,
+ Integer.toString(60 * 60)); // An hour
+ props.put(QueryServices.USE_STATS_FOR_PARALLELIZATION, Boolean.toString(false));
+ props.put(QueryServices.PHOENIX_SERVER_PAGE_SIZE_MS, Long.toString(0));
+ props.put(QueryServices.TESTS_MINI_CLUSTER_NUM_REGION_SERVERS, String.valueOf(2));
+ props.put(HConstants.HBASE_CLIENT_SCANNER_MAX_RESULT_SIZE_KEY, String.valueOf(1));
+ props.put(QueryServices.PHOENIX_POST_VALID_PROCESS,
+ TestScanningResultPostValidResultCaller.class.getName());
+ setUpTestDriver(new ReadOnlyProps(props.entrySet().iterator()));
+ }
+
+ @AfterClass
+ public static synchronized void freeResources() throws Exception {
+ BaseTest.freeResourcesIfBeyondThreshold();
+ }
+
+ @Test
+ public void testAvgGroupByOrderPreservingWithNoStats() throws Exception {
+ Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
+ Connection conn = DriverManager.getConnection(getUrl(), props);
+ String tableName = generateUniqueName();
+ initAvgGroupTable(conn, tableName, "");
+ testAvgGroupByOrderPreserving(conn, tableName, 5);
+ }
+
+ @Test
+ public void testSumGroupByOrderPreservingDescWithoutSplit() throws Exception {
+ try {
+ super.testSumGroupByOrderPreservingDescWithoutSplit();
+ } catch (StaleRegionBoundaryCacheException e) {
+ hasTestStarted = false;
+ LOGGER.error("Rows could not be scanned because of stale region boundary. Try again.");
+ super.testSumGroupByOrderPreservingDescWithoutSplit();
+ }
+ }
+
+ @Test
+ public void testGroupByOrderByDescBug3451() throws Exception {
+ try {
+ super.testGroupByOrderByDescBug3451();
+ } catch (StaleRegionBoundaryCacheException e) {
+ hasTestStarted = false;
+ LOGGER.error("Rows could not be scanned because of stale region boundary. Try again.");
+ super.testGroupByOrderByDescBug3451();
+ }
+ }
+
+}
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/BaseAggregateWithRegionMovesIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/BaseAggregateWithRegionMovesIT.java
new file mode 100644
index 0000000000..a0dca2651e
--- /dev/null
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/BaseAggregateWithRegionMovesIT.java
@@ -0,0 +1,998 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.phoenix.end2end;
+
+import org.apache.phoenix.compile.ExplainPlan;
+import org.apache.phoenix.compile.ExplainPlanAttributes;
+import org.apache.phoenix.jdbc.PhoenixPreparedStatement;
+import org.apache.phoenix.query.KeyRange;
+import org.apache.phoenix.query.QueryServices;
+import org.apache.phoenix.schema.types.PChar;
+import org.apache.phoenix.schema.types.PInteger;
+import org.apache.phoenix.thirdparty.com.google.common.collect.Lists;
+import org.apache.phoenix.util.ByteUtil;
+import org.apache.phoenix.util.PropertiesUtil;
+import org.apache.phoenix.util.QueryBuilder;
+import org.apache.phoenix.util.TestUtil;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+import java.io.IOException;
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.List;
+import java.util.Properties;
+
+import static org.apache.phoenix.util.TestUtil.TEST_PROPERTIES;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+
+public abstract class BaseAggregateWithRegionMovesIT
+ extends ParallelStatsDisabledWithRegionMovesIT {
+
+ private static void initData(Connection conn, String tableName) throws SQLException {
+ conn.createStatement().execute("create table " + tableName +
+ " (id varchar not null primary key,\n" +
+ " uri varchar, appcpu integer)");
+ TABLE_NAMES.add(tableName);
+ insertRow(conn, tableName, "Report1", 10, 1);
+ insertRow(conn, tableName, "Report2", 10, 2);
+ insertRow(conn, tableName, "Report3", 30, 3);
+ insertRow(conn, tableName, "Report4", 30, 4);
+ insertRow(conn, tableName, "SOQL1", 10, 5);
+ insertRow(conn, tableName, "SOQL2", 10, 6);
+ insertRow(conn, tableName, "SOQL3", 30, 7);
+ insertRow(conn, tableName, "SOQL4", 30, 8);
+ conn.commit();
+ }
+
+ @Before
+ public void setUp() throws Exception {
+ hasTestStarted = true;
+ }
+
+ @After
+ public void tearDown() throws Exception {
+ countOfDummyResults = 0;
+ TABLE_NAMES.clear();
+ hasTestStarted = false;
+ }
+
+ private static void insertRow(Connection conn, String tableName, String uri, int appcpu, int id)
+ throws SQLException {
+ PreparedStatement statement = conn.prepareStatement(
+ "UPSERT INTO " + tableName + "(id, uri, appcpu) values (?,?,?)");
+ statement.setString(1, "id" + id);
+ statement.setString(2, uri);
+ statement.setInt(3, appcpu);
+ statement.executeUpdate();
+ }
+
+ @Test
+ public void testDuplicateTrailingAggExpr() throws Exception {
+ Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
+ props.put(QueryServices.FORCE_ROW_KEY_ORDER_ATTRIB, Boolean.FALSE.toString());
+ Connection conn = DriverManager.getConnection(getUrl(), props);
+ String tableName = generateUniqueName();
+ TABLE_NAMES.add(tableName);
+
+ conn.createStatement().execute("create table " + tableName +
+ " (nam VARCHAR(20), address VARCHAR(20), id BIGINT "
+ + "constraint my_pk primary key (id))");
+ PreparedStatement statement = conn.prepareStatement(
+ "UPSERT INTO " + tableName + "(nam, address, id) values (?,?,?)");
+ statement.setString(1, "pulkit");
+ statement.setString(2, "badaun");
+ statement.setInt(3, 1);
+ statement.executeUpdate();
+ conn.commit();
+
+ QueryBuilder queryBuilder = new QueryBuilder()
+ .setDistinct(true)
+ .setSelectExpression("'harshit' as TEST_COLUMN, trim(NAM), trim(NAM)")
+ .setSelectExpressionColumns(Lists.newArrayList("NAM"))
+ .setFullTableName(tableName);
+
+ ResultSet rs = executeQuery(conn, queryBuilder);
+ assertTrue(rs.next());
+ assertEquals("harshit", rs.getString(1));
+ assertEquals("pulkit", rs.getString(2));
+ assertEquals("pulkit", rs.getString(3));
+ conn.close();
+ }
+
+ @Test
+ public void testExpressionInGroupBy() throws Exception {
+ Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
+ Connection conn = DriverManager.getConnection(getUrl(), props);
+ String tableName = generateUniqueName();
+ TABLE_NAMES.add(tableName);
+ String ddl = "create table " + tableName +
+ "(tgb_id integer NOT NULL,utc_date_epoch integer NOT NULL,tgb_name varchar(40),ack_success_count integer" +
+ ",ack_success_one_ack_count integer, CONSTRAINT pk_tgb_counter PRIMARY KEY(tgb_id, utc_date_epoch))";
+
+ createTestTable(getUrl(), ddl);
+ String dml = "UPSERT INTO " + tableName + " VALUES(?,?,?,?,?)";
+ PreparedStatement stmt = conn.prepareStatement(dml);
+ stmt.setInt(1, 1);
+ stmt.setInt(2, 1000);
+ stmt.setString(3, "aaa");
+ stmt.setInt(4, 1);
+ stmt.setInt(5, 1);
+ stmt.execute();
+ stmt.setInt(1, 2);
+ stmt.setInt(2, 2000);
+ stmt.setString(3, "bbb");
+ stmt.setInt(4, 2);
+ stmt.setInt(5, 2);
+ stmt.execute();
+ conn.commit();
+
+ QueryBuilder queryBuilder = new QueryBuilder()
+ .setSelectExpression(
+ "TGB_ID, TGB_NAME, (UTC_DATE_EPOCH/10)*10 AS UTC_EPOCH_HOUR,SUM(ACK_SUCCESS_COUNT + " +
+ "ACK_SUCCESS_ONE_ACK_COUNT) AS ACK_TX_SUM")
+ .setSelectExpressionColumns(Lists.newArrayList("TGB_ID", "TGB_NAME",
+ "UTC_DATE_EPOCH", "ACK_SUCCESS_COUNT", "ACK_SUCCESS_ONE_ACK_COUNT"))
+ .setGroupByClause("TGB_ID, TGB_NAME, UTC_EPOCH_HOUR")
+ .setFullTableName(tableName)
+ .setOrderByClause("TGB_ID, UTC_EPOCH_HOUR");
+
+ ResultSet rs = executeQuery(conn, queryBuilder);
+ assertTrue(rs.next());
+ moveRegionsOfTable(tableName);
+ assertEquals(1, rs.getInt(1));
+ assertEquals("aaa", rs.getString(2));
+ assertEquals(1000, rs.getDouble(3), 1e-6);
+ assertEquals(2, rs.getLong(4));
+ assertTrue(rs.next());
+ assertEquals(2, rs.getInt(1));
+ assertEquals("bbb", rs.getString(2));
+ assertEquals(2000, rs.getDouble(3), 1e-6);
+ assertEquals(4, rs.getLong(4));
+ assertFalse(rs.next());
+ rs.close();
+ conn.close();
+ }
+
+ @Test
+ public void testBooleanInGroupBy() throws Exception {
+ Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
+ Connection conn = DriverManager.getConnection(getUrl(), props);
+ String tableName = generateUniqueName();
+ TABLE_NAMES.add(tableName);
+ String ddl = " create table " + tableName +
+ "(id varchar primary key,v1 boolean, v2 integer, v3 integer)";
+
+ createTestTable(getUrl(), ddl);
+ PreparedStatement stmt =
+ conn.prepareStatement("UPSERT INTO " + tableName + "(id,v2,v3) VALUES(?,?,?)");
+ stmt.setString(1, "a");
+ stmt.setInt(2, 1);
+ stmt.setInt(3, 1);
+ stmt.execute();
+ stmt.close();
+ stmt = conn.prepareStatement("UPSERT INTO " + tableName + " VALUES(?,?,?,?)");
+ stmt.setString(1, "b");
+ stmt.setBoolean(2, false);
+ stmt.setInt(3, 2);
+ stmt.setInt(4, 2);
+ stmt.execute();
+ stmt.setString(1, "c");
+ stmt.setBoolean(2, true);
+ stmt.setInt(3, 3);
+ stmt.setInt(4, 3);
+ stmt.execute();
+ conn.commit();
+
+ String[] gbs = {"V1,V2,V3", "V1,V3,V2", "V2,V1,V3"};
+ for (String gb : gbs) {
+ QueryBuilder queryBuilder = new QueryBuilder()
+ .setSelectColumns(Lists.newArrayList("V1", "V2", "V3"))
+ .setFullTableName(tableName)
+ .setGroupByClause(gb);
+
+ ResultSet rs = executeQuery(conn, queryBuilder);
+ assertTrue(rs.next());
+ moveRegionsOfTable(tableName);
+ assertEquals(false, rs.getBoolean("v1"));
+ assertTrue(rs.wasNull());
+ assertEquals(1, rs.getInt("v2"));
+ assertEquals(1, rs.getInt("v3"));
+ assertTrue(rs.next());
+ assertEquals(false, rs.getBoolean("v1"));
+ assertFalse(rs.wasNull());
+ assertEquals(2, rs.getInt("v2"));
+ assertEquals(2, rs.getInt("v3"));
+ assertTrue(rs.next());
+ assertEquals(true, rs.getBoolean("v1"));
+ assertEquals(3, rs.getInt("v2"));
+ assertEquals(3, rs.getInt("v3"));
+ assertFalse(rs.next());
+ rs.close();
+ }
+ conn.close();
+ }
+
+ @Test
+ public void testScanUri() throws Exception {
+ Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
+ Connection conn = DriverManager.getConnection(getUrl(), props);
+ String tableName = generateUniqueName();
+ TABLE_NAMES.add(tableName);
+ initData(conn, tableName);
+ Statement stmt = conn.createStatement();
+ QueryBuilder queryBuilder = new QueryBuilder()
+ .setSelectColumns(Lists.newArrayList("URI"))
+ .setFullTableName(tableName);
+
+ ResultSet rs = executeQuery(conn, queryBuilder);
+ assertTrue(rs.next());
+ moveRegionsOfTable(tableName);
+ assertEquals("Report1", rs.getString(1));
+ assertTrue(rs.next());
+ moveRegionsOfTable(tableName);
+ assertEquals("Report2", rs.getString(1));
+ assertTrue(rs.next());
+ assertEquals("Report3", rs.getString(1));
+ assertTrue(rs.next());
+ moveRegionsOfTable(tableName);
+ assertEquals("Report4", rs.getString(1));
+ assertTrue(rs.next());
+ assertEquals("SOQL1", rs.getString(1));
+ assertTrue(rs.next());
+ moveRegionsOfTable(tableName);
+ assertEquals("SOQL2", rs.getString(1));
+ assertTrue(rs.next());
+ assertEquals("SOQL3", rs.getString(1));
+ assertTrue(rs.next());
+ assertEquals("SOQL4", rs.getString(1));
+ assertFalse(rs.next());
+ conn.close();
+ }
+
+ @Test
+ public void testCount() throws Exception {
+ Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
+ Connection conn = DriverManager.getConnection(getUrl(), props);
+ String tableName = generateUniqueName();
+ TABLE_NAMES.add(tableName);
+ initData(conn, tableName);
+ Statement stmt = conn.createStatement();
+ QueryBuilder queryBuilder = new QueryBuilder()
+ .setSelectExpression("count(1)")
+ .setFullTableName(tableName);
+ ResultSet rs = executeQuery(conn, queryBuilder);
+ assertTrue(rs.next());
+ moveRegionsOfTable(tableName);
+ assertEquals(8, rs.getLong(1));
+ assertFalse(rs.next());
+ conn.close();
+ }
+
+ @Test
+ public void testGroupByCase() throws Exception {
+ Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
+ props.put(QueryServices.FORCE_ROW_KEY_ORDER_ATTRIB, Boolean.FALSE.toString());
+ Connection conn = DriverManager.getConnection(getUrl(), props);
+ String tableName = generateUniqueName();
+ TABLE_NAMES.add(tableName);
+ initData(conn, tableName);
+ QueryBuilder queryBuilder = new QueryBuilder()
+ .setSelectExpression(
+ "CASE WHEN URI LIKE 'REPORT%' THEN 'REPORTS' ELSE 'OTHER' END CATEGORY, AVG(APPCPU)")
+ .setSelectExpressionColumns(Lists.newArrayList("URI", "APPCPU"))
+ .setFullTableName(tableName)
+ .setGroupByClause("CATEGORY");
+ executeQuery(conn, queryBuilder);
+
+ queryBuilder.setSelectExpression(
+ "CASE URI WHEN 'REPORT%' THEN 'REPORTS' ELSE 'OTHER' END CATEGORY, AVG(APPCPU)")
+ .setSelectExpressionColumns(Lists.newArrayList("URI", "APPCPU"))
+ .setFullTableName(tableName)
+ .setGroupByClause("APPCPU, CATEGORY");
+ executeQuery(conn, queryBuilder);
+
+ queryBuilder.setSelectExpression(
+ "CASE URI WHEN 'Report%' THEN 'Reports' ELSE 'Other' END CATEGORY, AVG(APPCPU)")
+ .setSelectColumns(Lists.newArrayList("URI", "APPCPU"))
+ .setFullTableName(tableName)
+ .setGroupByClause("AVG(APPCPU), CATEGORY");
+ executeQueryThrowsException(conn, queryBuilder,
+ "Aggregate expressions may not be used in GROUP BY", "");
+ conn.close();
+ }
+
+ protected void initAvgGroupTable(Connection conn, String tableName, String tableProps)
+ throws SQLException {
+ PreparedStatement stmt = conn.prepareStatement("CREATE TABLE " + tableName +
+ " (k1 char(1) not null, k2 integer not null, constraint pk primary key (k1,k2)) " +
+ tableProps + " split on (?,?,?)");
+ TABLE_NAMES.add(tableName);
+ stmt.setBytes(1,
+ ByteUtil.concat(PChar.INSTANCE.toBytes("a"), PInteger.INSTANCE.toBytes(3)));
+ stmt.setBytes(2,
+ ByteUtil.concat(PChar.INSTANCE.toBytes("j"), PInteger.INSTANCE.toBytes(3)));
+ stmt.setBytes(3,
+ ByteUtil.concat(PChar.INSTANCE.toBytes("n"), PInteger.INSTANCE.toBytes(3)));
+ stmt.execute();
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 1)");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 2)");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 3)");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('a', 6)");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('b', 5)");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 1)");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 2)");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 3)");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('j', 10)");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 1)");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 2)");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 3)");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES('n', 2)");
+ conn.commit();
+ }
+
+ protected void testAvgGroupByOrderPreserving(Connection conn, String tableName, int nGuidePosts)
+ throws SQLException, IOException {
+ TABLE_NAMES.add(tableName);
+ QueryBuilder queryBuilder = new QueryBuilder()
+ .setSelectExpression("K1, AVG(K2)")
+ .setSelectExpressionColumns(Lists.newArrayList("K1", "K2"))
+ .setFullTableName(tableName)
+ .setGroupByClause("K1")
+ .setOrderByClause("K1");
+ ResultSet rs = executeQuery(conn, queryBuilder);
+ assertTrue(rs.next());
+ assertEquals("a", rs.getString(1));
+ assertEquals(3, rs.getDouble(2), 1e-6);
+ assertTrue(rs.next());
+ moveRegionsOfTable(tableName);
+ assertEquals("b", rs.getString(1));
+ assertEquals(5, rs.getDouble(2), 1e-6);
+ assertTrue(rs.next());
+ assertEquals("j", rs.getString(1));
+ assertEquals(4, rs.getDouble(2), 1e-6);
+ assertTrue(rs.next());
+ moveRegionsOfTable(tableName);
+ assertEquals("n", rs.getString(1));
+ assertEquals(2, rs.getDouble(2), 1e-6);
+ assertFalse(rs.next());
+ ExplainPlan plan = conn.prepareStatement(queryBuilder.build())
+ .unwrap(PhoenixPreparedStatement.class).optimizeQuery()
+ .getExplainPlan();
+ ExplainPlanAttributes explainPlanAttributes =
+ plan.getPlanStepsAsAttributes();
+ assertEquals("PARALLEL 1-WAY",
+ explainPlanAttributes.getIteratorTypeAndScanSize());
+ assertEquals("FULL SCAN ", explainPlanAttributes.getExplainScanType());
+ assertEquals(tableName, explainPlanAttributes.getTableName());
+ assertEquals("SERVER FILTER BY FIRST KEY ONLY",
+ explainPlanAttributes.getServerWhereFilter());
+ assertEquals("SERVER AGGREGATE INTO ORDERED DISTINCT ROWS BY [K1]",
+ explainPlanAttributes.getServerAggregate());
+ TestUtil.analyzeTable(conn, tableName);
+ List<KeyRange> splits = TestUtil.getAllSplits(conn, tableName);
+ // nGuideposts when stats are enabled, 4 when disabled
+ assertEquals(4, splits.size());
+ }
+
+ protected void testAvgGroupByDescOrderPreserving(Connection conn, String tableName)
+ throws SQLException, IOException {
+ TABLE_NAMES.add(tableName);
+ QueryBuilder queryBuilder = new QueryBuilder()
+ .setSelectExpression("K1, AVG(K2)")
+ .setSelectExpressionColumns(Lists.newArrayList("K1", "K2"))
+ .setFullTableName(tableName)
+ .setGroupByClause("K1")
+ .setOrderByClause("K1 DESC");
+ ResultSet rs = executeQuery(conn, queryBuilder);
+ assertTrue(rs.next());
+ assertEquals("n", rs.getString(1));
+ assertEquals(2, rs.getDouble(2), 1e-6);
+ moveRegionsOfTable(tableName);
+ assertTrue(rs.next());
+ assertEquals("j", rs.getString(1));
+ assertEquals(4, rs.getDouble(2), 1e-6);
+ assertTrue(rs.next());
+ assertEquals("b", rs.getString(1));
+ assertEquals(5, rs.getDouble(2), 1e-6);
+ moveRegionsOfTable(tableName);
+ assertTrue(rs.next());
+ assertEquals("a", rs.getString(1));
+ assertEquals(3, rs.getDouble(2), 1e-6);
+ assertFalse(rs.next());
+ ExplainPlan plan = conn.prepareStatement(queryBuilder.build())
+ .unwrap(PhoenixPreparedStatement.class).optimizeQuery()
+ .getExplainPlan();
+ ExplainPlanAttributes explainPlanAttributes =
+ plan.getPlanStepsAsAttributes();
+ assertEquals("PARALLEL 1-WAY",
+ explainPlanAttributes.getIteratorTypeAndScanSize());
+ assertEquals("FULL SCAN ", explainPlanAttributes.getExplainScanType());
+ assertEquals(tableName, explainPlanAttributes.getTableName());
+ assertEquals("SERVER FILTER BY FIRST KEY ONLY",
+ explainPlanAttributes.getServerWhereFilter());
+ assertEquals("SERVER AGGREGATE INTO ORDERED DISTINCT ROWS BY [K1]",
+ explainPlanAttributes.getServerAggregate());
+ TestUtil.analyzeTable(conn, tableName);
+ List<KeyRange> splits = TestUtil.getAllSplits(conn, tableName);
+ // nGuideposts when stats are enabled, 4 when disabled
+ assertEquals(4, splits.size());
+ }
+
+ @Test
+ public void testDistinctGroupByBug3452WithoutMultiTenant() throws Exception {
+ doTestDistinctGroupByBug3452("");
+ }
+
+ @Test
+ public void testDistinctGroupByBug3452WithMultiTenant() throws Exception {
+ doTestDistinctGroupByBug3452(
+ "VERSIONS=1, MULTI_TENANT=TRUE, REPLICATION_SCOPE=1, TTL=31536000");
+ }
+
+ private void doTestDistinctGroupByBug3452(String options) throws Exception {
+ Connection conn = null;
+ try {
+ Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
+ conn = DriverManager.getConnection(getUrl(), props);
+
+ String tableName = generateUniqueName();
+ TABLE_NAMES.add(tableName);
+ conn.createStatement().execute("DROP TABLE if exists " + tableName);
+ String sql = "CREATE TABLE " + tableName + " ( " +
+ "ORGANIZATION_ID CHAR(15) NOT NULL," +
+ "CONTAINER_ID CHAR(15) NOT NULL," +
+ "ENTITY_ID CHAR(15) NOT NULL," +
+ "SCORE DOUBLE," +
+ "CONSTRAINT TEST_PK PRIMARY KEY ( " +
+ "ORGANIZATION_ID," +
+ "CONTAINER_ID," +
+ "ENTITY_ID" +
+ ")) " + options;
+ conn.createStatement().execute(sql);
+
+ String indexTableName = generateUniqueName();
+ conn.createStatement()
+ .execute("DROP INDEX IF EXISTS " + indexTableName + " ON " + tableName);
+ conn.createStatement().execute("CREATE INDEX " + indexTableName + " ON " + tableName +
+ " (CONTAINER_ID, SCORE DESC, ENTITY_ID DESC)");
+
+ conn.createStatement().execute(
+ "UPSERT INTO " + tableName + " VALUES ('org1','container1','entityId6',1.1)");
+ conn.createStatement().execute(
+ "UPSERT INTO " + tableName + " VALUES ('org1','container1','entityId5',1.2)");
+ conn.createStatement().execute(
+ "UPSERT INTO " + tableName + " VALUES ('org1','container1','entityId4',1.3)");
+ conn.createStatement().execute(
+ "UPSERT INTO " + tableName + " VALUES ('org1','container1','entityId3',1.4)");
+ conn.createStatement().execute(
+ "UPSERT INTO " + tableName + " VALUES ('org1','container1','entityId2',1.5)");
+ conn.createStatement().execute(
+ "UPSERT INTO " + tableName + " VALUES ('org1','container1','entityId1',1.6)");
+ conn.commit();
+
+ QueryBuilder queryBuilder = new QueryBuilder()
+ .setDistinct(true)
+ .setSelectColumns(Lists.newArrayList("ENTITY_ID", "SCORE", "ORGANIZATION_ID",
+ "CONTAINER_ID"))
+ .setFullTableName(tableName)
+ .setWhereClause("ORGANIZATION_ID = 'org1' AND CONTAINER_ID = 'container1'")
+ .setOrderByClause("SCORE DESC");
+ ResultSet rs = executeQuery(conn, queryBuilder);
+ assertTrue(rs.next());
+ moveRegionsOfTable(tableName);
+ moveRegionsOfTable(indexTableName);
+ assertEquals("entityId1", rs.getString(1));
+ assertEquals(rs.getDouble(2), 1.6, 0.0001);
+
+ assertTrue(rs.next());
+ assertEquals("entityId2", rs.getString(1));
+ assertEquals(rs.getDouble(2), 1.5, 0.0001);
+
+ assertTrue(rs.next());
+ moveRegionsOfTable(tableName);
+ moveRegionsOfTable(indexTableName);
+ assertEquals("entityId3", rs.getString(1));
+ assertEquals(rs.getDouble(2), 1.4, 0.0001);
+
+ assertTrue(rs.next());
+ assertEquals("entityId4", rs.getString(1));
+ assertEquals(rs.getDouble(2), 1.3, 0.0001);
+
+ assertTrue(rs.next());
+ moveRegionsOfTable(tableName);
+ moveRegionsOfTable(indexTableName);
+ assertEquals("entityId5", rs.getString(1));
+ assertEquals(rs.getDouble(2), 1.2, 0.0001);
+
+ assertTrue(rs.next());
+ assertEquals("entityId6", rs.getString(1));
+ assertEquals(rs.getDouble(2), 1.1, 0.0001);
+ assertFalse(rs.next());
+ } finally {
+ if (conn != null) {
+ conn.close();
+ }
+ }
+ }
+
+ protected static void assertResultSet(ResultSet rs, Object[][] rows, String tableName)
+ throws Exception {
+ boolean switchToRegionMove = true;
+ for (int rowIndex = 0; rowIndex < rows.length; rowIndex++) {
+ assertTrue("rowIndex:[" + rowIndex + "] rs.next error!", rs.next());
+ if (switchToRegionMove) {
+ moveRegionsOfTable(tableName);
+ switchToRegionMove = false;
+ } else {
+ switchToRegionMove = true;
+ }
+ for (int columnIndex = 1; columnIndex <= rows[rowIndex].length; columnIndex++) {
+ Object realValue = rs.getObject(columnIndex);
+ Object expectedValue = rows[rowIndex][columnIndex - 1];
+ if (realValue == null) {
+ assertNull("rowIndex:[" + rowIndex + "],columnIndex:[" + columnIndex + "]",
+ expectedValue);
+ } else {
+ assertEquals("rowIndex:[" + rowIndex + "],columnIndex:[" + columnIndex + "]",
+ expectedValue,
+ realValue
+ );
+ }
+ }
+ }
+ assertFalse(rs.next());
+ }
+
+ @Test
+ public void testGroupByDescColumnWithNullsLastBug3452() throws Exception {
+
+ Connection conn = null;
+ try {
+ Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
+ conn = DriverManager.getConnection(getUrl(), props);
+
+ String tableName = generateUniqueName();
+ TABLE_NAMES.add(tableName);
+
+ String sql = "CREATE TABLE " + tableName + " ( " +
+ "ORGANIZATION_ID VARCHAR," +
+ "CONTAINER_ID VARCHAR," +
+ "ENTITY_ID VARCHAR NOT NULL," +
+ "CONSTRAINT TEST_PK PRIMARY KEY ( " +
+ "ORGANIZATION_ID DESC," +
+ "CONTAINER_ID DESC," +
+ "ENTITY_ID" +
+ "))";
+ conn.createStatement().execute(sql);
+
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES ('a',null,'11')");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES (null,'2','22')");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES ('c','3','33')");
+ conn.commit();
+
+ //-----ORGANIZATION_ID
+
+ QueryBuilder queryBuilder = new QueryBuilder()
+ .setSelectColumns(
+ Lists.newArrayList("CONTAINER_ID", "ORGANIZATION_ID"))
+ .setFullTableName(tableName)
+ .setGroupByClause("ORGANIZATION_ID, CONTAINER_ID")
+ .setOrderByClause("ORGANIZATION_ID ASC NULLS FIRST");
+ ResultSet rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs, new String[][]{{"2", null}, {null, "a"}, {"3", "c"},}, tableName);
+
+ queryBuilder.setOrderByClause("ORGANIZATION_ID ASC NULLS LAST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs, new String[][]{{null, "a"}, {"3", "c"}, {"2", null}}, tableName);
+
+ queryBuilder.setOrderByClause("ORGANIZATION_ID DESC NULLS FIRST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs, new String[][]{{"2", null}, {"3", "c"}, {null, "a"}}, tableName);
+
+ queryBuilder.setOrderByClause("ORGANIZATION_ID DESC NULLS LAST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs, new String[][]{{"3", "c"}, {null, "a"}, {"2", null}}, tableName);
+
+ //----CONTAINER_ID
+
+ queryBuilder.setOrderByClause("CONTAINER_ID ASC NULLS FIRST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs, new String[][]{{null, "a"}, {"2", null}, {"3", "c"}}, tableName);
+
+ queryBuilder.setOrderByClause("CONTAINER_ID ASC NULLS LAST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs, new String[][]{{"2", null}, {"3", "c"}, {null, "a"}}, tableName);
+
+ queryBuilder.setOrderByClause("CONTAINER_ID DESC NULLS FIRST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs, new String[][]{{null, "a"}, {"3", "c"}, {"2", null}}, tableName);
+
+ queryBuilder.setOrderByClause("CONTAINER_ID DESC NULLS LAST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs, new String[][]{{"3", "c"}, {"2", null}, {null, "a"}}, tableName);
+
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES (null,null,'44')");
+ conn.commit();
+
+ //-----ORGANIZATION_ID ASC CONTAINER_ID ASC
+
+ queryBuilder.setOrderByClause("ORGANIZATION_ID NULLS FIRST,CONTAINER_ID NULLS FIRST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs, new String[][]{{null, null}, {"2", null}, {null, "a"},
+ {"3", "c"}}, tableName);
+
+ queryBuilder.setOrderByClause("ORGANIZATION_ID NULLS FIRST,CONTAINER_ID NULLS LAST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs, new String[][]{{"2", null}, {null, null}, {null, "a"},
+ {"3", "c"}}, tableName);
+
+ queryBuilder.setOrderByClause("ORGANIZATION_ID NULLS LAST,CONTAINER_ID NULLS FIRST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs, new String[][]{{null, "a"}, {"3", "c"}, {null, null},
+ {"2", null}}, tableName);
+
+ queryBuilder.setOrderByClause("ORGANIZATION_ID NULLS LAST,CONTAINER_ID NULLS LAST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs, new String[][]{{null, "a"}, {"3", "c"}, {"2", null},
+ {null, null}}, tableName);
+
+ //-----ORGANIZATION_ID ASC CONTAINER_ID DESC
+
+ queryBuilder.setOrderByClause(
+ "ORGANIZATION_ID NULLS FIRST,CONTAINER_ID DESC NULLS FIRST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs, new String[][]{{null, null}, {"2", null}, {null, "a"},
+ {"3", "c"}}, tableName);
+
+ queryBuilder.setOrderByClause(
+ "ORGANIZATION_ID NULLS FIRST,CONTAINER_ID DESC NULLS LAST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs, new String[][]{{"2", null}, {null, null}, {null, "a"},
+ {"3", "c"}}, tableName);
+
+ queryBuilder.setOrderByClause(
+ "ORGANIZATION_ID NULLS LAST,CONTAINER_ID DESC NULLS FIRST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs, new String[][]{{null, "a"}, {"3", "c"}, {null, null},
+ {"2", null}}, tableName);
+
+ queryBuilder.setOrderByClause(
+ "ORGANIZATION_ID NULLS LAST,CONTAINER_ID DESC NULLS LAST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs, new String[][]{{null, "a"}, {"3", "c"}, {"2", null},
+ {null, null}}, tableName);
+
+ //-----ORGANIZATION_ID DESC CONTAINER_ID ASC
+
+ queryBuilder.setOrderByClause(
+ "ORGANIZATION_ID DESC NULLS FIRST,CONTAINER_ID NULLS FIRST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs, new String[][]{{null, null}, {"2", null}, {"3", "c"},
+ {null, "a"}}, tableName);
+
+ queryBuilder.setOrderByClause(
+ "ORGANIZATION_ID DESC NULLS FIRST,CONTAINER_ID NULLS LAST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs, new String[][]{{"2", null}, {null, null}, {"3", "c"},
+ {null, "a"}}, tableName);
+
+ queryBuilder.setOrderByClause(
+ "ORGANIZATION_ID DESC NULLS LAST,CONTAINER_ID NULLS FIRST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs, new String[][]{{"3", "c"}, {null, "a"}, {null, null},
+ {"2", null}}, tableName);
+
+ queryBuilder.setOrderByClause(
+ "ORGANIZATION_ID DESC NULLS LAST,CONTAINER_ID NULLS LAST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs, new String[][]{{"3", "c"}, {null, "a"}, {"2", null},
+ {null, null}}, tableName);
+
+ //-----ORGANIZATION_ID DESC CONTAINER_ID DESC
+
+ queryBuilder.setOrderByClause(
+ "ORGANIZATION_ID DESC NULLS FIRST,CONTAINER_ID DESC NULLS FIRST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs, new String[][]{{null, null}, {"2", null}, {"3", "c"},
+ {null, "a"}}, tableName);
+
+ queryBuilder.setOrderByClause(
+ "ORGANIZATION_ID DESC NULLS FIRST,CONTAINER_ID DESC NULLS LAST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs, new String[][]{{"2", null}, {null, null}, {"3", "c"},
+ {null, "a"}}, tableName);
+
+ queryBuilder.setOrderByClause(
+ "ORGANIZATION_ID DESC NULLS LAST,CONTAINER_ID DESC NULLS FIRST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs, new String[][]{{"3", "c"}, {null, "a"}, {null, null},
+ {"2", null}}, tableName);
+
+ queryBuilder.setOrderByClause(
+ "ORGANIZATION_ID DESC NULLS LAST,CONTAINER_ID DESC NULLS LAST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs, new String[][]{{"3", "c"}, {null, "a"}, {"2", null},
+ {null, null}}, tableName);
+
+ //-----CONTAINER_ID ASC ORGANIZATION_ID ASC
+
+ queryBuilder.setOrderByClause("CONTAINER_ID NULLS FIRST,ORGANIZATION_ID NULLS FIRST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs, new String[][]{{null, null}, {null, "a"}, {"2", null},
+ {"3", "c"}}, tableName);
+
+ queryBuilder.setOrderByClause("CONTAINER_ID NULLS FIRST,ORGANIZATION_ID NULLS LAST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs, new String[][]{{null, "a"}, {null, null}, {"2", null},
+ {"3", "c"}}, tableName);
+
+ queryBuilder.setOrderByClause("CONTAINER_ID NULLS LAST,ORGANIZATION_ID NULLS FIRST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs, new String[][]{{"2", null}, {"3", "c"}, {null, null},
+ {null, "a"}}, tableName);
+
+ queryBuilder.setOrderByClause("CONTAINER_ID NULLS LAST,ORGANIZATION_ID NULLS LAST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs, new String[][]{{"2", null}, {"3", "c"}, {null, "a"},
+ {null, null}}, tableName);
+
+ //-----CONTAINER_ID ASC ORGANIZATION_ID DESC
+
+ queryBuilder.setOrderByClause(
+ "CONTAINER_ID ASC NULLS FIRST,ORGANIZATION_ID DESC NULLS FIRST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs, new String[][]{{null, null}, {null, "a"}, {"2", null},
+ {"3", "c"}}, tableName);
+
+ queryBuilder.setOrderByClause(
+ "CONTAINER_ID ASC NULLS FIRST,ORGANIZATION_ID DESC NULLS LAST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs, new String[][]{{null, "a"}, {null, null}, {"2", null},
+ {"3", "c"}}, tableName);
+
+ queryBuilder.setOrderByClause(
+ "CONTAINER_ID ASC NULLS LAST,ORGANIZATION_ID DESC NULLS FIRST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs, new String[][]{{"2", null}, {"3", "c"}, {null, null},
+ {null, "a"}}, tableName);
+
+ queryBuilder.setOrderByClause(
+ "CONTAINER_ID ASC NULLS LAST,ORGANIZATION_ID DESC NULLS LAST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs, new String[][]{{"2", null}, {"3", "c"}, {null, "a"},
+ {null, null}}, tableName);
+
+ //-----CONTAINER_ID DESC ORGANIZATION_ID ASC
+
+ queryBuilder.setOrderByClause(
+ "CONTAINER_ID DESC NULLS FIRST,ORGANIZATION_ID ASC NULLS FIRST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs, new String[][]{{null, null}, {null, "a"}, {"3", "c"},
+ {"2", null}}, tableName);
+
+ queryBuilder.setOrderByClause(
+ "CONTAINER_ID DESC NULLS FIRST,ORGANIZATION_ID ASC NULLS LAST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs, new String[][]{{null, "a"}, {null, null}, {"3", "c"},
+ {"2", null}}, tableName);
+
+ queryBuilder.setOrderByClause(
+ "CONTAINER_ID DESC NULLS LAST,ORGANIZATION_ID ASC NULLS FIRST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs, new String[][]{{"3", "c"}, {"2", null}, {null, null},
+ {null, "a"}}, tableName);
+
+ queryBuilder.setOrderByClause(
+ "CONTAINER_ID DESC NULLS LAST,ORGANIZATION_ID ASC NULLS LAST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs, new String[][]{{"3", "c"}, {"2", null}, {null, "a"},
+ {null, null}}, tableName);
+
+ //-----CONTAINER_ID DESC ORGANIZATION_ID DESC
+
+ queryBuilder.setOrderByClause(
+ "CONTAINER_ID DESC NULLS FIRST,ORGANIZATION_ID DESC NULLS FIRST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs, new String[][]{{null, null}, {null, "a"}, {"3", "c"},
+ {"2", null}}, tableName);
+
+ queryBuilder.setOrderByClause(
+ "CONTAINER_ID DESC NULLS FIRST,ORGANIZATION_ID DESC NULLS LAST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs, new String[][]{{null, "a"}, {null, null}, {"3", "c"},
+ {"2", null}}, tableName);
+
+ queryBuilder.setOrderByClause(
+ "CONTAINER_ID DESC NULLS LAST,ORGANIZATION_ID DESC NULLS FIRST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs, new String[][]{{"3", "c"}, {"2", null}, {null, null},
+ {null, "a"}}, tableName);
+
+ queryBuilder.setOrderByClause(
+ "CONTAINER_ID DESC NULLS LAST,ORGANIZATION_ID DESC NULLS LAST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs, new String[][]{{"3", "c"}, {"2", null}, {null, "a"},
+ {null, null}}, tableName);
+ } finally {
+ if (conn != null) {
+ conn.close();
+ }
+ }
+ }
+
+ @Test
+ public void testCountNullInEncodedNonEmptyKeyValueCF() throws Exception {
+ testCountNullInNonEmptyKeyValueCF(1);
+ }
+
+ @Test
+ public void testCountNullInNonEncodedNonEmptyKeyValueCF() throws Exception {
+ testCountNullInNonEmptyKeyValueCF(0);
+ }
+
+ protected abstract void testCountNullInNonEmptyKeyValueCF(int columnEncodedBytes)
+ throws Exception;
+
+ @Test
+ public void testGroupByOrderMatchPkColumnOrderBug46901() throws Exception {
+ this.doTestGroupByOrderMatchPkColumnOrderBug4690(false, false);
+ this.doTestGroupByOrderMatchPkColumnOrderBug4690(false, true);
+ this.doTestGroupByOrderMatchPkColumnOrderBug4690(true, false);
+ this.doTestGroupByOrderMatchPkColumnOrderBug4690(true, true);
+ }
+
+ private void doTestGroupByOrderMatchPkColumnOrderBug4690(boolean desc, boolean salted)
+ throws Exception {
+ Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
+ try (Connection conn = DriverManager.getConnection(getUrl(), props)) {
+ String tableName = generateUniqueName();
+ String sql = "create table " + tableName + "( " +
+ " pk1 integer not null , " +
+ " pk2 integer not null, " +
+ " pk3 integer not null," +
+ " pk4 integer not null," +
+ " v integer, " +
+ " CONSTRAINT TEST_PK PRIMARY KEY ( " +
+ "pk1 " + (desc ? "desc" : "") + ", " +
+ "pk2 " + (desc ? "desc" : "") + ", " +
+ "pk3 " + (desc ? "desc" : "") + ", " +
+ "pk4 " + (desc ? "desc" : "") +
+ " )) " + (salted ? "SALT_BUCKETS =4" : "split on(2)");
+ conn.createStatement().execute(sql);
+
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES (1,8,10,20,30)");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES (1,8,11,21,31)");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES (1,9,5 ,22,32)");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES (1,9,6 ,12,33)");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES (1,9,6 ,13,34)");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES (1,9,7 ,8,35)");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES (2,3,15,25,35)");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES (2,7,16,26,36)");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES (2,7,17,27,37)");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES (3,2,18,28,38)");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES (3,2,19,29,39)");
+ conn.commit();
+
+ QueryBuilder queryBuilder = new QueryBuilder()
+ .setSelectExpression("PK2,PK1,COUNT(V)")
+ .setSelectExpressionColumns(Lists.newArrayList("PK1", "PK2", "V"))
+ .setFullTableName(tableName)
+ .setGroupByClause("PK2, PK1")
+ .setOrderByClause("PK2, PK1");
+ ResultSet rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs,
+ new Object[][]{{2, 3, 2L}, {3, 2, 1L}, {7, 2, 2L}, {8, 1, 2L}, {9, 1, 4L}},
+ tableName);
+
+ queryBuilder.setSelectExpression("PK1, PK2, COUNT(V)");
+ queryBuilder.setOrderByClause("PK1, PK2");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs,
+ new Object[][]{{1, 8, 2L}, {1, 9, 4L}, {2, 3, 1L}, {2, 7, 2L}, {3, 2, 2L}},
+ tableName);
+
+ queryBuilder.setSelectExpression("PK2,PK1,COUNT(V)");
+ queryBuilder.setOrderByClause("PK2 DESC,PK1 DESC");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs,
+ new Object[][]{{9, 1, 4L}, {8, 1, 2L}, {7, 2, 2L}, {3, 2, 1L}, {2, 3, 2L}},
+ tableName);
+
+ queryBuilder.setSelectExpression("PK1,PK2,COUNT(V)");
+ queryBuilder.setOrderByClause("PK1 DESC,PK2 DESC");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs,
+ new Object[][]{{3, 2, 2L}, {2, 7, 2L}, {2, 3, 1L}, {1, 9, 4L}, {1, 8, 2L}},
+ tableName);
+
+ queryBuilder.setSelectExpression("PK3,PK2,COUNT(V)");
+ queryBuilder.setSelectExpressionColumns(Lists.newArrayList("PK1", "PK2", "PK3", "V"));
+ queryBuilder.setFullTableName(tableName);
+ queryBuilder.setGroupByClause("PK3,PK2");
+ queryBuilder.setOrderByClause("PK3,PK2");
+ queryBuilder.setWhereClause("PK1=1");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs,
+ new Object[][]{{5, 9, 1L}, {6, 9, 2L}, {7, 9, 1L}, {10, 8, 1L}, {11, 8, 1L}},
+ tableName);
+
+ queryBuilder.setSelectExpression("PK2,PK3,COUNT(V)");
+ queryBuilder.setOrderByClause("PK2,PK3");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs,
+ new Object[][]{{8, 10, 1L}, {8, 11, 1L}, {9, 5, 1L}, {9, 6, 2L}, {9, 7, 1L}},
+ tableName);
+
+ queryBuilder.setSelectExpression("PK3,PK2,COUNT(V)");
+ queryBuilder.setOrderByClause("PK3 DESC,PK2 DESC");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs,
+ new Object[][]{{11, 8, 1L}, {10, 8, 1L}, {7, 9, 1L}, {6, 9, 2L}, {5, 9, 1L}},
+ tableName);
+
+ queryBuilder.setSelectExpression("PK2,PK3,COUNT(V)");
+ queryBuilder.setOrderByClause("PK2 DESC,PK3 DESC");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs,
+ new Object[][]{{9, 7, 1L}, {9, 6, 2L}, {9, 5, 1L}, {8, 11, 1L}, {8, 10, 1L}},
+ tableName);
+
+
+ queryBuilder.setSelectExpression("PK4,PK3,PK1,COUNT(V)");
+ queryBuilder.setSelectExpressionColumns(
+ Lists.newArrayList("PK1", "PK2", "PK3", "PK4", "V"));
+ queryBuilder.setFullTableName(tableName);
+ queryBuilder.setWhereClause("PK2=9 ");
+ queryBuilder.setGroupByClause("PK4,PK3,PK1");
+ queryBuilder.setOrderByClause("PK4,PK3,PK1");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs,
+ new Object[][]{{8, 7, 1, 1L}, {12, 6, 1, 1L}, {13, 6, 1, 1L}, {22, 5, 1, 1L}}
+ , tableName);
+
+ queryBuilder.setSelectExpression("PK1,PK3,PK4,COUNT(V)");
+ queryBuilder.setOrderByClause("PK1,PK3,PK4");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs,
+ new Object[][]{{1, 5, 22, 1L}, {1, 6, 12, 1L}, {1, 6, 13, 1L}, {1, 7, 8, 1L}},
+ tableName);
+
+ queryBuilder.setSelectExpression("PK4,PK3,PK1,COUNT(V)");
+ queryBuilder.setOrderByClause("PK4 DESC,PK3 DESC,PK1 DESC");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs,
+ new Object[][]{{22, 5, 1, 1L}, {13, 6, 1, 1L}, {12, 6, 1, 1L}, {8, 7, 1, 1L}},
+ tableName);
+
+ queryBuilder.setSelectExpression("PK1,PK3,PK4,COUNT(V)");
+ queryBuilder.setOrderByClause("PK1 DESC,PK3 DESC,PK4 DESC");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs, new Object[][]{{1, 7, 8, 1L}, {1, 6, 13, 1L}, {1, 6, 12, 1L}, {1,
+ 5, 22, 1L}}, tableName);
+ }
+ }
+}
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/BaseOrderByWithRegionMovesIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/BaseOrderByWithRegionMovesIT.java
new file mode 100644
index 0000000000..526d4f608d
--- /dev/null
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/BaseOrderByWithRegionMovesIT.java
@@ -0,0 +1,1406 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.phoenix.end2end;
+
+import org.apache.phoenix.compile.ExplainPlan;
+import org.apache.phoenix.compile.ExplainPlanAttributes;
+import org.apache.phoenix.jdbc.PhoenixPreparedStatement;
+import org.apache.phoenix.thirdparty.com.google.common.collect.Lists;
+import org.apache.phoenix.util.PropertiesUtil;
+import org.apache.phoenix.util.QueryBuilder;
+import org.apache.phoenix.util.SchemaUtil;
+import org.apache.phoenix.util.TestUtil;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.Properties;
+
+import static org.apache.phoenix.util.TestUtil.ROW1;
+import static org.apache.phoenix.util.TestUtil.ROW2;
+import static org.apache.phoenix.util.TestUtil.ROW3;
+import static org.apache.phoenix.util.TestUtil.ROW4;
+import static org.apache.phoenix.util.TestUtil.ROW5;
+import static org.apache.phoenix.util.TestUtil.ROW6;
+import static org.apache.phoenix.util.TestUtil.ROW7;
+import static org.apache.phoenix.util.TestUtil.ROW8;
+import static org.apache.phoenix.util.TestUtil.ROW9;
+import static org.apache.phoenix.util.TestUtil.TEST_PROPERTIES;
+import static org.apache.phoenix.util.TestUtil.assertResultSet;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+
+
+public abstract class BaseOrderByWithRegionMovesIT extends ParallelStatsDisabledWithRegionMovesIT {
+
+ @Before
+ public void setUp() throws Exception {
+ hasTestStarted = true;
+ }
+
+ @After
+ public void tearDown() throws Exception {
+ countOfDummyResults = 0;
+ TABLE_NAMES.clear();
+ hasTestStarted = false;
+ }
+
+ @Test
+ public void testMultiOrderByExpr() throws Exception {
+ Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
+ String tenantId = getOrganizationId();
+ String tableName = initATableValues(tenantId, getDefaultSplits(tenantId), getUrl());
+ TABLE_NAMES.add(tableName);
+ QueryBuilder queryBuilder = new QueryBuilder()
+ .setSelectColumns(
+ Lists.newArrayList("ENTITY_ID", "B_STRING"))
+ .setFullTableName(tableName)
+ .setOrderByClause("B_STRING, ENTITY_ID");
+
+ try (Connection conn = DriverManager.getConnection(getUrl(), props)) {
+ ResultSet rs = executeQuery(conn, queryBuilder);
+ assertTrue(rs.next());
+ moveRegionsOfTable(tableName);
+ assertEquals(ROW1, rs.getString(1));
+ assertTrue(rs.next());
+ assertEquals(ROW4, rs.getString(1));
+ assertTrue(rs.next());
+ assertEquals(ROW7, rs.getString(1));
+ assertTrue(rs.next());
+ moveRegionsOfTable(tableName);
+ assertEquals(ROW2, rs.getString(1));
+ assertTrue(rs.next());
+ assertEquals(ROW5, rs.getString(1));
+ assertTrue(rs.next());
+ moveRegionsOfTable(tableName);
+ assertEquals(ROW8, rs.getString(1));
+ assertTrue(rs.next());
+ assertEquals(ROW3, rs.getString(1));
+ assertTrue(rs.next());
+ moveRegionsOfTable(tableName);
+ assertEquals(ROW6, rs.getString(1));
+ assertTrue(rs.next());
+ assertEquals(ROW9, rs.getString(1));
+
+ assertFalse(rs.next());
+ }
+ }
+
+ @Test
+ public void testDescMultiOrderByExpr() throws Exception {
+ Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
+ String tenantId = getOrganizationId();
+ String tableName = initATableValues(tenantId, null, getUrl());
+ TABLE_NAMES.add(tableName);
+ QueryBuilder queryBuilder = new QueryBuilder()
+ .setSelectColumns(
+ Lists.newArrayList("ENTITY_ID", "B_STRING"))
+ .setFullTableName(tableName)
+ .setOrderByClause("B_STRING || ENTITY_ID DESC");
+ try (Connection conn = DriverManager.getConnection(getUrl(), props)) {
+ ResultSet rs = executeQuery(conn, queryBuilder);
+ assertTrue(rs.next());
+ moveRegionsOfTable(tableName);
+ assertEquals(ROW9, rs.getString(1));
+ assertTrue(rs.next());
+ moveRegionsOfTable(tableName);
+ assertEquals(ROW6, rs.getString(1));
+ assertTrue(rs.next());
+ assertEquals(ROW3, rs.getString(1));
+ assertTrue(rs.next());
+ assertEquals(ROW8, rs.getString(1));
+ assertTrue(rs.next());
+ assertEquals(ROW5, rs.getString(1));
+ assertTrue(rs.next());
+ moveRegionsOfTable(tableName);
+ assertEquals(ROW2, rs.getString(1));
+ assertTrue(rs.next());
+ assertEquals(ROW7, rs.getString(1));
+ assertTrue(rs.next());
+ assertEquals(ROW4, rs.getString(1));
+ assertTrue(rs.next());
+ moveRegionsOfTable(tableName);
+ assertEquals(ROW1, rs.getString(1));
+ assertFalse(rs.next());
+ }
+ }
+
+ @Test
+ public void testDescMultiOrderByExprWithSplits() throws Exception {
+ Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
+ String tenantId = getOrganizationId();
+ String tableName = initATableValues(tenantId, getDefaultSplits(tenantId), getUrl());
+ TABLE_NAMES.add(tableName);
+ QueryBuilder queryBuilder = new QueryBuilder()
+ .setSelectColumns(
+ Lists.newArrayList("ENTITY_ID", "B_STRING"))
+ .setFullTableName(tableName)
+ .setOrderByClause("B_STRING || ENTITY_ID DESC");
+ try (Connection conn = DriverManager.getConnection(getUrl(), props)) {
+ ResultSet rs = executeQuery(conn, queryBuilder);
+ assertTrue(rs.next());
+ moveRegionsOfTable(tableName);
+ assertEquals(ROW9, rs.getString(1));
+ assertTrue(rs.next());
+ moveRegionsOfTable(tableName);
+ assertEquals(ROW6, rs.getString(1));
+ assertTrue(rs.next());
+ assertEquals(ROW3, rs.getString(1));
+ assertTrue(rs.next());
+ assertEquals(ROW8, rs.getString(1));
+ assertTrue(rs.next());
+ assertEquals(ROW5, rs.getString(1));
+ assertTrue(rs.next());
+ moveRegionsOfTable(tableName);
+ assertEquals(ROW2, rs.getString(1));
+ assertTrue(rs.next());
+ assertEquals(ROW7, rs.getString(1));
+ assertTrue(rs.next());
+ assertEquals(ROW4, rs.getString(1));
+ assertTrue(rs.next());
+ moveRegionsOfTable(tableName);
+ assertEquals(ROW1, rs.getString(1));
+ assertFalse(rs.next());
+ }
+ }
+
+ @Test
+ public void testOrderByDifferentColumns() throws Exception {
+ Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
+ try (Connection conn = DriverManager.getConnection(getUrl(), props)) {
+ conn.setAutoCommit(false);
+ String tableName = generateUniqueName();
+ TABLE_NAMES.add(tableName);
+ String ddl = "CREATE TABLE " + tableName +
+ " (a_string varchar not null, col1 integer" +
+ " CONSTRAINT pk PRIMARY KEY (a_string))\n";
+ createTestTable(getUrl(), ddl);
+
+ String dml = "UPSERT INTO " + tableName + " VALUES(?, ?)";
+ PreparedStatement stmt = conn.prepareStatement(dml);
+ stmt.setString(1, "a");
+ stmt.setInt(2, 40);
+ stmt.execute();
+ stmt.setString(1, "b");
+ stmt.setInt(2, 20);
+ stmt.execute();
+ stmt.setString(1, "c");
+ stmt.setInt(2, 30);
+ stmt.execute();
+ conn.commit();
+
+ QueryBuilder queryBuilder = new QueryBuilder()
+ .setSelectColumns(
+ Lists.newArrayList("COL1"))
+ .setFullTableName(tableName)
+ .setSelectExpression("count(*)")
+ .setGroupByClause("COL1")
+ .setOrderByClause("COL1");
+ ResultSet rs = executeQuery(conn, queryBuilder);
+ assertTrue(rs.next());
+ moveRegionsOfTable(tableName);
+ assertEquals(1, rs.getLong(1));
+ assertTrue(rs.next());
+ moveRegionsOfTable(tableName);
+ assertEquals(1, rs.getLong(1));
+ assertTrue(rs.next());
+ moveRegionsOfTable(tableName);
+ assertEquals(1, rs.getLong(1));
+ assertFalse(rs.next());
+
+ queryBuilder = new QueryBuilder();
+ queryBuilder.setSelectColumns(
+ Lists.newArrayList("A_STRING", "COL1"));
+ queryBuilder.setFullTableName(tableName);
+ queryBuilder.setOrderByClause("A_STRING");
+ rs = executeQuery(conn, queryBuilder);
+ assertTrue(rs.next());
+ moveRegionsOfTable(tableName);
+ assertEquals("a", rs.getString(1));
+ assertEquals(40, rs.getInt(2));
+ assertTrue(rs.next());
+ moveRegionsOfTable(tableName);
+ assertEquals("b", rs.getString(1));
+ assertEquals(20, rs.getInt(2));
+ assertTrue(rs.next());
+ moveRegionsOfTable(tableName);
+ assertEquals("c", rs.getString(1));
+ assertEquals(30, rs.getInt(2));
+ assertFalse(rs.next());
+
+ queryBuilder.setSelectColumns(
+ Lists.newArrayList("A_STRING", "COL1"));
+ queryBuilder.setFullTableName(tableName);
+ queryBuilder.setOrderByClause("COL1");
+ rs = executeQuery(conn, queryBuilder);
+ assertTrue(rs.next());
+ moveRegionsOfTable(tableName);
+ assertEquals("b", rs.getString(1));
+ assertEquals(20, rs.getInt(2));
+ assertTrue(rs.next());
+ moveRegionsOfTable(tableName);
+ assertEquals("c", rs.getString(1));
+ assertEquals(30, rs.getInt(2));
+ assertTrue(rs.next());
+ moveRegionsOfTable(tableName);
+ assertEquals("a", rs.getString(1));
+ assertEquals(40, rs.getInt(2));
+ assertFalse(rs.next());
+ }
+ }
+
+ @Test
+ public void testAggregateOrderBy() throws Exception {
+ Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
+ Connection conn = DriverManager.getConnection(getUrl(), props);
+ String tableName = generateUniqueName();
+ TABLE_NAMES.add(tableName);
+ String ddl = "create table " + tableName +
+ " (ID VARCHAR NOT NULL PRIMARY KEY, VAL1 VARCHAR, VAL2 INTEGER)";
+ conn.createStatement().execute(ddl);
+
+ conn.createStatement().execute("upsert into " + tableName + " values ('ABC','aa123', 11)");
+ conn.createStatement().execute("upsert into " + tableName + " values ('ABD','ba124', 1)");
+ conn.createStatement().execute("upsert into " + tableName + " values ('ABE','cf125', 13)");
+ conn.createStatement().execute("upsert into " + tableName + " values ('ABF','dan126', 4)");
+ conn.createStatement().execute("upsert into " + tableName + " values ('ABG','elf127', 15)");
+ conn.createStatement().execute("upsert into " + tableName + " values ('ABH','fan128', 6)");
+ conn.createStatement()
+ .execute("upsert into " + tableName + " values ('AAA','get211', 100)");
+ conn.createStatement().execute("upsert into " + tableName + " values ('AAB','hat212', 7)");
+ conn.createStatement().execute("upsert into " + tableName + " values ('AAC','aap12', 2)");
+ conn.createStatement().execute("upsert into " + tableName + " values ('AAD','ball12', 3)");
+ conn.createStatement()
+ .execute("upsert into " + tableName + " values ('AAE','inn2110', 13)");
+ conn.createStatement()
+ .execute("upsert into " + tableName + " values ('AAF','key2112', 40)");
+ conn.commit();
+
+ QueryBuilder queryBuilder = new QueryBuilder()
+ .setSelectColumns(
+ Lists.newArrayList("VAL1", "VAL2"))
+ .setFullTableName(tableName)
+ .setOrderByClause("VAL1")
+ .setSelectExpression("DISTINCT(ID)")
+ .setSelectExpressionColumns(Lists.newArrayList("ID"))
+ .setWhereClause(
+ "ID in ('ABC','ABD','ABE','ABF','ABG','ABH','AAA', 'AAB', 'AAC','AAD','AAE','AAF')");
+ ResultSet rs = executeQuery(conn, queryBuilder);
+ assertTrue(rs.next());
+ moveRegionsOfTable(tableName);
+ assertEquals("ABC", rs.getString(1));
+ assertEquals("aa123", rs.getString(2));
+ assertTrue(rs.next());
+ moveRegionsOfTable(tableName);
+ assertEquals("aap12", rs.getString(2));
+ assertTrue(rs.next());
+ assertEquals("ba124", rs.getString(2));
+ assertTrue(rs.next());
+ assertEquals("ball12", rs.getString(2));
+ assertTrue(rs.next());
+ moveRegionsOfTable(tableName);
+ assertEquals("cf125", rs.getString(2));
+ assertTrue(rs.next());
+ assertEquals("dan126", rs.getString(2));
+ assertTrue(rs.next());
+ assertEquals("elf127", rs.getString(2));
+ assertTrue(rs.next());
+ moveRegionsOfTable(tableName);
+ assertEquals("fan128", rs.getString(2));
+ assertTrue(rs.next());
+ assertEquals("get211", rs.getString(2));
+ assertTrue(rs.next());
+ assertEquals("hat212", rs.getString(2));
+ assertTrue(rs.next());
+ assertEquals("inn2110", rs.getString(2));
+ assertTrue(rs.next());
+ moveRegionsOfTable(tableName);
+ assertEquals("AAF", rs.getString(1));
+ assertEquals("key2112", rs.getString(2));
+ assertFalse(rs.next());
+ }
+
+ @Test
+ public void testAggregateOptimizedOutOrderBy() throws Exception {
+ Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
+ Connection conn = DriverManager.getConnection(getUrl(), props);
+ String tableName = generateUniqueName();
+ TABLE_NAMES.add(tableName);
+ String ddl = "create table " + tableName +
+ " (K1 VARCHAR NOT NULL, K2 VARCHAR NOT NULL, VAL1 VARCHAR, VAL2 INTEGER, CONSTRAINT pk PRIMARY KEY(K1,K2))";
+ conn.createStatement().execute(ddl);
+
+ conn.createStatement()
+ .execute("upsert into " + tableName + " values ('ABC','ABC','aa123', 11)");
+ conn.createStatement()
+ .execute("upsert into " + tableName + " values ('ABD','ABC','ba124', 1)");
+ conn.createStatement()
+ .execute("upsert into " + tableName + " values ('ABE','ABC','cf125', 13)");
+ conn.createStatement()
+ .execute("upsert into " + tableName + " values ('ABF','ABC','dan126', 4)");
+ conn.createStatement()
+ .execute("upsert into " + tableName + " values ('ABG','ABC','elf127', 15)");
+ conn.createStatement()
+ .execute("upsert into " + tableName + " values ('ABH','ABC','fan128', 6)");
+ conn.createStatement()
+ .execute("upsert into " + tableName + " values ('AAA','ABC','get211', 100)");
+ conn.createStatement()
+ .execute("upsert into " + tableName + " values ('AAB','ABC','hat212', 7)");
+ conn.createStatement()
+ .execute("upsert into " + tableName + " values ('AAC','ABC','aap12', 2)");
+ conn.createStatement()
+ .execute("upsert into " + tableName + " values ('AAD','ABC','ball12', 3)");
+ conn.createStatement()
+ .execute("upsert into " + tableName + " values ('AAE','ABC','inn2110', 13)");
+ conn.createStatement()
+ .execute("upsert into " + tableName + " values ('AAF','ABC','key2112', 40)");
+ conn.commit();
+
+ QueryBuilder queryBuilder = new QueryBuilder()
+ .setSelectColumns(
+ Lists.newArrayList("VAL1", "VAL2"))
+ .setFullTableName(tableName)
+ .setOrderByClause("VAL1")
+ .setSelectExpressionColumns(Lists.newArrayList("K2"))
+ .setSelectExpression("DISTINCT(K2)")
+ .setWhereClause("K2 = 'ABC'");
+
+ // verify that the phoenix query plan doesn't contain an order by
+ ExplainPlan plan = conn.prepareStatement(queryBuilder.build())
+ .unwrap(PhoenixPreparedStatement.class).optimizeQuery()
+ .getExplainPlan();
+ ExplainPlanAttributes explainPlanAttributes =
+ plan.getPlanStepsAsAttributes();
+ assertEquals("PARALLEL 1-WAY",
+ explainPlanAttributes.getIteratorTypeAndScanSize());
+ assertEquals("FULL SCAN ", explainPlanAttributes.getExplainScanType());
+ assertEquals(tableName, explainPlanAttributes.getTableName());
+ assertEquals("SERVER FILTER BY K2 = 'ABC'",
+ explainPlanAttributes.getServerWhereFilter());
+ assertEquals("SERVER AGGREGATE INTO DISTINCT ROWS BY [K2, VAL1, VAL2]",
+ explainPlanAttributes.getServerAggregate());
+ assertEquals("CLIENT MERGE SORT",
+ explainPlanAttributes.getClientSortAlgo());
+ assertNull(explainPlanAttributes.getClientSortedBy());
+ assertNull(explainPlanAttributes.getServerSortedBy());
+
+ ResultSet rs = executeQuery(conn, queryBuilder);
+ assertTrue(rs.next());
+ moveRegionsOfTable(tableName);
+ assertEquals("ABC", rs.getString(1));
+ assertEquals("aa123", rs.getString(2));
+ assertTrue(rs.next());
+ moveRegionsOfTable(tableName);
+ assertEquals("aap12", rs.getString(2));
+ assertTrue(rs.next());
+ assertEquals("ba124", rs.getString(2));
+ assertTrue(rs.next());
+ assertEquals("ball12", rs.getString(2));
+ assertTrue(rs.next());
+ moveRegionsOfTable(tableName);
+ assertEquals("cf125", rs.getString(2));
+ assertTrue(rs.next());
+ assertEquals("dan126", rs.getString(2));
+ assertTrue(rs.next());
+ assertEquals("elf127", rs.getString(2));
+ assertTrue(rs.next());
+ moveRegionsOfTable(tableName);
+ assertEquals("fan128", rs.getString(2));
+ assertTrue(rs.next());
+ assertEquals("get211", rs.getString(2));
+ assertTrue(rs.next());
+ assertEquals("hat212", rs.getString(2));
+ assertTrue(rs.next());
+ moveRegionsOfTable(tableName);
+ assertEquals("inn2110", rs.getString(2));
+ assertTrue(rs.next());
+ moveRegionsOfTable(tableName);
+ assertEquals("ABC", rs.getString(1));
+ assertEquals("key2112", rs.getString(2));
+ assertFalse(rs.next());
+ }
+
+ @Test
+ public void testNullsLastWithDesc() throws Exception {
+ Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
+ try (Connection conn = DriverManager.getConnection(getUrl(), props)) {
+ String tableName = generateUniqueName();
+ TABLE_NAMES.add(tableName);
+ String sql = "CREATE TABLE " + tableName + " ( " +
+ "ORGANIZATION_ID VARCHAR," +
+ "CONTAINER_ID VARCHAR," +
+ "ENTITY_ID VARCHAR NOT NULL," +
+ "CONSTRAINT TEST_PK PRIMARY KEY ( " +
+ "ORGANIZATION_ID DESC," +
+ "CONTAINER_ID DESC," +
+ "ENTITY_ID" +
+ "))";
+ conn.createStatement().execute(sql);
+
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES ('a',null,'11')");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES (null,'2','22')");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES ('c','3','33')");
+ conn.commit();
+
+ //-----ORGANIZATION_ID
+
+// sql="SELECT CONTAINER_ID,ORGANIZATION_ID FROM "+tableName+" order by ORGANIZATION_ID ASC NULLS FIRST";
+ QueryBuilder queryBuilder = new QueryBuilder()
+ .setSelectColumns(
+ Lists.newArrayList("CONTAINER_ID", "ORGANIZATION_ID"))
+ .setFullTableName(tableName)
+ .setOrderByClause("ORGANIZATION_ID ASC NULLS FIRST");
+ ResultSet rs = executeQuery(conn, queryBuilder);
+ assertResultSetWithRegionMoves(rs,
+ new String[][]{{"2", null}, {null, "a"}, {"3", "c"},}, tableName);
+
+// sql="SELECT CONTAINER_ID,ORGANIZATION_ID FROM "+tableName+" order by ORGANIZATION_ID ASC NULLS LAST";
+ queryBuilder.setOrderByClause("ORGANIZATION_ID ASC NULLS LAST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSetWithRegionMoves(rs, new String[][]{{null, "a"}, {"3", "c"}, {"2", null}},
+ tableName);
+
+// sql="SELECT CONTAINER_ID,ORGANIZATION_ID FROM "+tableName+" order by ORGANIZATION_ID DESC NULLS FIRST";
+ queryBuilder.setOrderByClause("ORGANIZATION_ID DESC NULLS FIRST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSetWithRegionMoves(rs, new String[][]{{"2", null}, {"3", "c"}, {null, "a"}},
+ tableName);
+
+// sql="SELECT CONTAINER_ID,ORGANIZATION_ID FROM "+tableName+" order by ORGANIZATION_ID DESC NULLS LAST";
+ queryBuilder.setOrderByClause("ORGANIZATION_ID DESC NULLS LAST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSetWithRegionMoves(rs, new String[][]{{"3", "c"}, {null, "a"}, {"2", null}},
+ tableName);
+
+ //----CONTAINER_ID
+
+// sql="SELECT CONTAINER_ID,ORGANIZATION_ID FROM "+tableName+" order by CONTAINER_ID ASC NULLS FIRST";
+ queryBuilder.setOrderByClause("CONTAINER_ID ASC NULLS FIRST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs, new String[][]{{null, "a"}, {"2", null}, {"3", "c"}});
+
+// sql="SELECT CONTAINER_ID,ORGANIZATION_ID FROM "+tableName+" order by CONTAINER_ID ASC NULLS LAST";
+ queryBuilder.setOrderByClause("CONTAINER_ID ASC NULLS LAST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs, new String[][]{{"2", null}, {"3", "c"}, {null, "a"}});
+
+// sql="SELECT CONTAINER_ID,ORGANIZATION_ID FROM "+tableName+" order by CONTAINER_ID DESC NULLS FIRST";
+ queryBuilder.setOrderByClause("CONTAINER_ID DESC NULLS FIRST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSetWithRegionMoves(rs, new String[][]{{null, "a"}, {"3", "c"}, {"2", null}},
+ tableName);
+
+// sql="SELECT CONTAINER_ID,ORGANIZATION_ID FROM "+tableName+" order by CONTAINER_ID DESC NULLS LAST";
+ queryBuilder.setOrderByClause("CONTAINER_ID DESC NULLS LAST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs, new String[][]{{"3", "c"}, {"2", null}, {null, "a"}});
+
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES (null,null,'44')");
+ conn.commit();
+
+ //-----ORGANIZATION_ID ASC CONTAINER_ID ASC
+
+// sql="SELECT CONTAINER_ID,ORGANIZATION_ID FROM "+tableName+" order by ORGANIZATION_ID NULLS FIRST,CONTAINER_ID NULLS FIRST";
+ queryBuilder.setOrderByClause("ORGANIZATION_ID NULLS FIRST,CONTAINER_ID NULLS FIRST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSetWithRegionMoves(rs,
+ new String[][]{{null, null}, {"2", null}, {null, "a"},
+ {"3", "c"}}, tableName);
+
+// sql="SELECT CONTAINER_ID,ORGANIZATION_ID FROM "+tableName+" order by ORGANIZATION_ID NULLS FIRST,CONTAINER_ID NULLS LAST";
+ queryBuilder.setOrderByClause("ORGANIZATION_ID NULLS FIRST,CONTAINER_ID NULLS LAST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs, new String[][]{{"2", null}, {null, null}, {null, "a"},
+ {"3", "c"}});
+
+// sql="SELECT CONTAINER_ID,ORGANIZATION_ID FROM "+tableName+" order by ORGANIZATION_ID NULLS LAST,CONTAINER_ID NULLS FIRST";
+ queryBuilder.setOrderByClause("ORGANIZATION_ID NULLS LAST,CONTAINER_ID NULLS FIRST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs, new String[][]{{null, "a"}, {"3", "c"}, {null, null},
+ {"2", null}});
+
+// sql="SELECT CONTAINER_ID,ORGANIZATION_ID FROM "+tableName+" order by ORGANIZATION_ID NULLS LAST,CONTAINER_ID NULLS LAST";
+ queryBuilder.setOrderByClause("ORGANIZATION_ID NULLS LAST,CONTAINER_ID NULLS LAST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs, new String[][]{{null, "a"}, {"3", "c"}, {"2", null},
+ {null, null}});
+
+
+ //-----ORGANIZATION_ID ASC CONTAINER_ID DESC
+
+// sql="SELECT CONTAINER_ID,ORGANIZATION_ID FROM "+tableName+" order by ORGANIZATION_ID NULLS FIRST,CONTAINER_ID DESC NULLS FIRST";
+ queryBuilder.setOrderByClause(
+ "ORGANIZATION_ID NULLS FIRST,CONTAINER_ID DESC NULLS FIRST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs, new String[][]{{null, null}, {"2", null}, {null, "a"},
+ {"3", "c"}});
+
+// sql="SELECT CONTAINER_ID,ORGANIZATION_ID FROM "+tableName+" order by ORGANIZATION_ID NULLS FIRST,CONTAINER_ID DESC NULLS LAST";
+ queryBuilder.setOrderByClause(
+ "ORGANIZATION_ID NULLS FIRST,CONTAINER_ID DESC NULLS LAST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSetWithRegionMoves(rs,
+ new String[][]{{"2", null}, {null, null}, {null, "a"},
+ {"3", "c"}}, tableName);
+
+// sql="SELECT CONTAINER_ID,ORGANIZATION_ID FROM "+tableName+" order by ORGANIZATION_ID NULLS LAST,CONTAINER_ID DESC NULLS FIRST";
+ queryBuilder.setOrderByClause(
+ "ORGANIZATION_ID NULLS LAST,CONTAINER_ID DESC NULLS FIRST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSetWithRegionMoves(rs, new String[][]{{null, "a"}, {"3", "c"}, {null, null},
+ {"2", null}}, tableName);
+
+// sql="SELECT CONTAINER_ID,ORGANIZATION_ID FROM "+tableName+" order by ORGANIZATION_ID NULLS LAST,CONTAINER_ID DESC NULLS LAST";
+ queryBuilder.setOrderByClause(
+ "ORGANIZATION_ID NULLS LAST,CONTAINER_ID DESC NULLS LAST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs, new String[][]{{null, "a"}, {"3", "c"}, {"2", null},
+ {null, null}});
+
+ //-----ORGANIZATION_ID DESC CONTAINER_ID ASC
+
+// sql="SELECT CONTAINER_ID,ORGANIZATION_ID FROM "+tableName+" order by ORGANIZATION_ID DESC NULLS FIRST,CONTAINER_ID NULLS FIRST";
+ queryBuilder.setOrderByClause(
+ "ORGANIZATION_ID DESC NULLS FIRST,CONTAINER_ID NULLS FIRST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs, new String[][]{{null, null}, {"2", null}, {"3", "c"},
+ {null, "a"}});
+
+// sql="SELECT CONTAINER_ID,ORGANIZATION_ID FROM "+tableName+" order by ORGANIZATION_ID DESC NULLS FIRST,CONTAINER_ID NULLS LAST";
+ queryBuilder.setOrderByClause(
+ "ORGANIZATION_ID DESC NULLS FIRST,CONTAINER_ID NULLS LAST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs, new String[][]{{"2", null}, {null, null}, {"3", "c"},
+ {null, "a"}});
+
+// sql="SELECT CONTAINER_ID,ORGANIZATION_ID FROM "+tableName+" order by ORGANIZATION_ID DESC NULLS LAST,CONTAINER_ID NULLS FIRST";
+ queryBuilder.setOrderByClause(
+ "ORGANIZATION_ID DESC NULLS LAST,CONTAINER_ID NULLS FIRST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSetWithRegionMoves(rs, new String[][]{{"3", "c"}, {null, "a"}, {null, null},
+ {"2", null}}, tableName);
+
+// sql="SELECT CONTAINER_ID,ORGANIZATION_ID FROM "+tableName+" order by ORGANIZATION_ID DESC NULLS LAST,CONTAINER_ID NULLS LAST";
+ queryBuilder.setOrderByClause(
+ "ORGANIZATION_ID DESC NULLS LAST,CONTAINER_ID NULLS LAST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSetWithRegionMoves(rs, new String[][]{{"3", "c"}, {null, "a"}, {"2", null},
+ {null, null}}, tableName);
+
+ //-----ORGANIZATION_ID DESC CONTAINER_ID DESC
+
+// sql="SELECT CONTAINER_ID,ORGANIZATION_ID FROM "+tableName+" order by ORGANIZATION_ID DESC NULLS FIRST,CONTAINER_ID DESC NULLS FIRST";
+ queryBuilder.setOrderByClause(
+ "ORGANIZATION_ID DESC NULLS FIRST,CONTAINER_ID DESC NULLS FIRST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs, new String[][]{{null, null}, {"2", null}, {"3", "c"},
+ {null, "a"}});
+
+// sql="SELECT CONTAINER_ID,ORGANIZATION_ID FROM "+tableName+" order by ORGANIZATION_ID DESC NULLS FIRST,CONTAINER_ID DESC NULLS LAST";
+ queryBuilder.setOrderByClause(
+ "ORGANIZATION_ID DESC NULLS FIRST,CONTAINER_ID DESC NULLS LAST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs, new String[][]{{"2", null}, {null, null}, {"3", "c"},
+ {null, "a"}});
+
+// sql="SELECT CONTAINER_ID,ORGANIZATION_ID FROM "+tableName+" order by ORGANIZATION_ID DESC NULLS LAST,CONTAINER_ID DESC NULLS FIRST";
+ queryBuilder.setOrderByClause(
+ "ORGANIZATION_ID DESC NULLS LAST,CONTAINER_ID DESC NULLS FIRST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs, new String[][]{{"3", "c"}, {null, "a"}, {null, null},
+ {"2", null}});
+
+// sql="SELECT CONTAINER_ID,ORGANIZATION_ID FROM "+tableName+" order by ORGANIZATION_ID DESC NULLS LAST,CONTAINER_ID DESC NULLS LAST";
+ queryBuilder.setOrderByClause(
+ "ORGANIZATION_ID DESC NULLS LAST,CONTAINER_ID DESC NULLS LAST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs, new String[][]{{"3", "c"}, {null, "a"}, {"2", null}, {null, null}});
+
+ //-----CONTAINER_ID ASC ORGANIZATION_ID ASC
+
+// sql="SELECT CONTAINER_ID,ORGANIZATION_ID FROM "+tableName+" order by CONTAINER_ID NULLS FIRST,ORGANIZATION_ID NULLS FIRST";
+ queryBuilder.setOrderByClause("CONTAINER_ID NULLS FIRST,ORGANIZATION_ID NULLS FIRST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs, new String[][]{{null, null}, {null, "a"}, {"2", null}, {"3", "c"}});
+
+// sql="SELECT CONTAINER_ID,ORGANIZATION_ID FROM "+tableName+" order by CONTAINER_ID NULLS FIRST,ORGANIZATION_ID NULLS LAST";
+ queryBuilder.setOrderByClause("CONTAINER_ID NULLS FIRST,ORGANIZATION_ID NULLS LAST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs, new String[][]{{null, "a"}, {null, null}, {"2", null}, {"3", "c"}});
+
+// sql="SELECT CONTAINER_ID,ORGANIZATION_ID FROM "+tableName+" order by CONTAINER_ID NULLS LAST,ORGANIZATION_ID NULLS FIRST";
+ queryBuilder.setOrderByClause("CONTAINER_ID NULLS LAST,ORGANIZATION_ID NULLS FIRST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSetWithRegionMoves(rs,
+ new String[][]{{"2", null}, {"3", "c"}, {null, null}, {null,
+ "a"}}, tableName);
+
+// sql="SELECT CONTAINER_ID,ORGANIZATION_ID FROM "+tableName+" order by CONTAINER_ID NULLS LAST,ORGANIZATION_ID NULLS LAST";
+ queryBuilder.setOrderByClause("CONTAINER_ID NULLS LAST,ORGANIZATION_ID NULLS LAST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs, new String[][]{{"2", null}, {"3", "c"}, {null, "a"}, {null, null}});
+
+ //-----CONTAINER_ID ASC ORGANIZATION_ID DESC
+
+// sql="SELECT CONTAINER_ID,ORGANIZATION_ID FROM "+tableName+" order by CONTAINER_ID ASC NULLS FIRST,ORGANIZATION_ID DESC NULLS FIRST";
+ queryBuilder.setOrderByClause(
+ "CONTAINER_ID ASC NULLS FIRST,ORGANIZATION_ID DESC NULLS FIRST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs, new String[][]{{null, null}, {null, "a"}, {"2", null}, {"3", "c"}});
+
+// sql="SELECT CONTAINER_ID,ORGANIZATION_ID FROM "+tableName+" order by CONTAINER_ID ASC NULLS FIRST,ORGANIZATION_ID DESC NULLS LAST";
+ queryBuilder.setOrderByClause(
+ "CONTAINER_ID ASC NULLS FIRST,ORGANIZATION_ID DESC NULLS LAST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSetWithRegionMoves(rs,
+ new String[][]{{null, "a"}, {null, null}, {"2", null}, {"3",
+ "c"}}, tableName);
+
+// sql="SELECT CONTAINER_ID,ORGANIZATION_ID FROM "+tableName+" order by CONTAINER_ID ASC NULLS LAST,ORGANIZATION_ID DESC NULLS FIRST";
+ queryBuilder.setOrderByClause(
+ "CONTAINER_ID ASC NULLS LAST,ORGANIZATION_ID DESC NULLS FIRST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs, new String[][]{{"2", null}, {"3", "c"}, {null, null}, {null, "a"}});
+
+// sql="SELECT CONTAINER_ID,ORGANIZATION_ID FROM "+tableName+" order by CONTAINER_ID ASC NULLS LAST,ORGANIZATION_ID DESC NULLS LAST";
+ queryBuilder.setOrderByClause(
+ "CONTAINER_ID ASC NULLS LAST,ORGANIZATION_ID DESC NULLS LAST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs, new String[][]{{"2", null}, {"3", "c"}, {null, "a"}, {null, null}});
+
+ //-----CONTAINER_ID DESC ORGANIZATION_ID ASC
+
+// sql="SELECT CONTAINER_ID,ORGANIZATION_ID FROM "+tableName+" order by CONTAINER_ID DESC NULLS FIRST,ORGANIZATION_ID ASC NULLS FIRST";
+ queryBuilder.setOrderByClause(
+ "CONTAINER_ID DESC NULLS FIRST,ORGANIZATION_ID ASC NULLS FIRST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs, new String[][]{{null, null}, {null, "a"}, {"3", "c"}, {"2", null}});
+
+// sql="SELECT CONTAINER_ID,ORGANIZATION_ID FROM "+tableName+" order by CONTAINER_ID DESC NULLS FIRST,ORGANIZATION_ID ASC NULLS LAST";
+ queryBuilder.setOrderByClause(
+ "CONTAINER_ID DESC NULLS FIRST,ORGANIZATION_ID ASC NULLS LAST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs, new String[][]{{null, "a"}, {null, null}, {"3", "c"}, {"2", null}});
+
+// sql="SELECT CONTAINER_ID,ORGANIZATION_ID FROM "+tableName+" order by CONTAINER_ID DESC NULLS LAST,ORGANIZATION_ID ASC NULLS FIRST";
+ queryBuilder.setOrderByClause(
+ "CONTAINER_ID DESC NULLS LAST,ORGANIZATION_ID ASC NULLS FIRST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs, new String[][]{{"3", "c"}, {"2", null}, {null, null}, {null, "a"}});
+
+// sql="SELECT CONTAINER_ID,ORGANIZATION_ID FROM "+tableName+" order by CONTAINER_ID DESC NULLS LAST,ORGANIZATION_ID ASC NULLS LAST";
+ queryBuilder.setOrderByClause(
+ "CONTAINER_ID DESC NULLS LAST,ORGANIZATION_ID ASC NULLS LAST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs, new String[][]{{"3", "c"}, {"2", null}, {null, "a"}, {null, null}});
+
+ //-----CONTAINER_ID DESC ORGANIZATION_ID DESC
+
+// sql="SELECT CONTAINER_ID,ORGANIZATION_ID FROM "+tableName+" order by CONTAINER_ID DESC NULLS FIRST,ORGANIZATION_ID DESC NULLS FIRST";
+ queryBuilder.setOrderByClause(
+ "CONTAINER_ID DESC NULLS FIRST,ORGANIZATION_ID DESC NULLS FIRST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs, new String[][]{{null, null}, {null, "a"}, {"3", "c"}, {"2", null}});
+
+// sql="SELECT CONTAINER_ID,ORGANIZATION_ID FROM "+tableName+" order by CONTAINER_ID DESC NULLS FIRST,ORGANIZATION_ID DESC NULLS LAST";
+ queryBuilder.setOrderByClause(
+ "CONTAINER_ID DESC NULLS FIRST,ORGANIZATION_ID DESC NULLS LAST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs, new String[][]{{null, "a"}, {null, null}, {"3", "c"}, {"2", null}});
+
+// sql="SELECT CONTAINER_ID,ORGANIZATION_ID FROM "+tableName+" order by CONTAINER_ID DESC NULLS LAST,ORGANIZATION_ID DESC NULLS FIRST";
+ queryBuilder.setOrderByClause(
+ "CONTAINER_ID DESC NULLS LAST,ORGANIZATION_ID DESC NULLS FIRST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs, new String[][]{{"3", "c"}, {"2", null}, {null, null}, {null, "a"}});
+
+// sql="SELECT CONTAINER_ID,ORGANIZATION_ID FROM "+tableName+" order by CONTAINER_ID DESC NULLS LAST,ORGANIZATION_ID DESC NULLS LAST";
+ queryBuilder.setOrderByClause(
+ "CONTAINER_ID DESC NULLS LAST,ORGANIZATION_ID DESC NULLS LAST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSetWithRegionMoves(rs,
+ new String[][]{{"3", "c"}, {"2", null}, {null, "a"}, {null,
+ null}}, tableName);
+ }
+ }
+
+ @Test
+ public void testOrderByReverseOptimization1() throws Exception {
+ for (boolean salted : new boolean[]{true, false}) {
+ doTestOrderByReverseOptimization(salted, true, true, true);
+ doTestOrderByReverseOptimization(salted, true, true, false);
+ doTestOrderByReverseOptimization(salted, true, false, true);
+ doTestOrderByReverseOptimization(salted, true, false, false);
+ }
+ }
+
+ @Test
+ public void testOrderByReverseOptimization2() throws Exception {
+ for (boolean salted : new boolean[]{true, false}) {
+ doTestOrderByReverseOptimization(salted, false, true, true);
+ doTestOrderByReverseOptimization(salted, false, true, false);
+ doTestOrderByReverseOptimization(salted, false, false, true);
+ doTestOrderByReverseOptimization(salted, false, false, false);
+ }
+ }
+
+ private void doTestOrderByReverseOptimization(boolean salted, boolean desc1, boolean desc2,
+ boolean desc3) throws Exception {
+ Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
+ try (Connection conn = DriverManager.getConnection(getUrl(), props)) {
+ String tableName = generateUniqueName();
+ TABLE_NAMES.add(tableName);
+ String sql = "CREATE TABLE " + tableName + " ( " +
+ "ORGANIZATION_ID INTEGER NOT NULL," +
+ "CONTAINER_ID INTEGER NOT NULL," +
+ "SCORE INTEGER NOT NULL," +
+ "ENTITY_ID INTEGER NOT NULL," +
+ "CONSTRAINT TEST_PK PRIMARY KEY ( " +
+ "ORGANIZATION_ID" + (desc1 ? " DESC" : "") + "," +
+ "CONTAINER_ID" + (desc2 ? " DESC" : "") + "," +
+ "SCORE" + (desc3 ? " DESC" : "") + "," +
+ "ENTITY_ID" +
+ ")) " + (salted ? "SALT_BUCKETS =4" : "split on(4)");
+ conn.createStatement().execute(sql);
+
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES (1,1,1,1)");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES (2,2,2,2)");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES (3,3,3,3)");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES (4,4,4,4)");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES (5,5,5,5)");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES (6,6,6,6)");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES (1,1,1,11)");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES (2,2,2,22)");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES (3,3,3,33)");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES (4,4,4,44)");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES (5,5,5,55)");
+ conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES (6,6,6,66)");
+ conn.commit();
+
+ QueryBuilder queryBuilder = new QueryBuilder()
+ .setSelectColumns(
+ Lists.newArrayList("CONTAINER_ID", "ORGANIZATION_ID"))
+ .setFullTableName(tableName)
+ .setGroupByClause("ORGANIZATION_ID, CONTAINER_ID")
+ .setOrderByClause("ORGANIZATION_ID ASC, CONTAINER_ID ASC");
+ //groupBy orderPreserving orderBy asc asc
+// sql="SELECT ORGANIZATION_ID,CONTAINER_ID FROM "+tableName+" group by ORGANIZATION_ID, CONTAINER_ID ORDER BY ORGANIZATION_ID ASC, CONTAINER_ID ASC";
+ ResultSet rs = executeQuery(conn, queryBuilder);
+ assertResultSetWithRegionMoves(rs, new Object[][]{{1, 1}, {2, 2}, {3, 3}, {4, 4}, {5,
+ 5}, {6, 6}}, tableName);
+
+ //groupBy orderPreserving orderBy asc desc
+// sql="SELECT ORGANIZATION_ID,CONTAINER_ID FROM "+tableName+" group by ORGANIZATION_ID, CONTAINER_ID ORDER BY ORGANIZATION_ID ASC, CONTAINER_ID desc";
+ queryBuilder.setOrderByClause("ORGANIZATION_ID ASC, CONTAINER_ID DESC");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs, new Object[][]{{1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 5}, {6, 6}});
+
+ //groupBy orderPreserving orderBy desc asc
+// sql="SELECT ORGANIZATION_ID,CONTAINER_ID FROM "+tableName+" group by ORGANIZATION_ID, CONTAINER_ID ORDER BY ORGANIZATION_ID DESC, CONTAINER_ID ASC";
+ queryBuilder.setOrderByClause("ORGANIZATION_ID DESC, CONTAINER_ID ASC");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs, new Object[][]{{6, 6}, {5, 5}, {4, 4}, {3, 3}, {2, 2}, {1, 1}});
+
+ //groupBy orderPreserving orderBy desc desc
+// sql="SELECT ORGANIZATION_ID,CONTAINER_ID FROM "+tableName+" group by ORGANIZATION_ID, CONTAINER_ID ORDER BY ORGANIZATION_ID DESC, CONTAINER_ID DESC";
+ queryBuilder.setOrderByClause("ORGANIZATION_ID DESC, CONTAINER_ID DESC");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs, new Object[][]{{6, 6}, {5, 5}, {4, 4}, {3, 3}, {2,
+ 2}, {1, 1}});
+
+ //groupBy not orderPreserving orderBy asc asc
+// sql="SELECT ORGANIZATION_ID,SCORE FROM "+tableName+" group by ORGANIZATION_ID, SCORE ORDER BY ORGANIZATION_ID ASC, SCORE ASC";
+ queryBuilder.setSelectColumns(
+ Lists.newArrayList("ORGANIZATION_ID", "SCORE"));
+ queryBuilder.setGroupByClause("ORGANIZATION_ID, SCORE");
+ queryBuilder.setOrderByClause("ORGANIZATION_ID ASC, SCORE ASC");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs, new Object[][]{{1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 5}, {6, 6}});
+
+ //groupBy not orderPreserving orderBy asc desc
+// sql="SELECT ORGANIZATION_ID,SCORE FROM "+tableName+" group by ORGANIZATION_ID, SCORE ORDER BY ORGANIZATION_ID ASC, SCORE DESC";
+ queryBuilder.setGroupByClause("ORGANIZATION_ID, SCORE");
+ queryBuilder.setOrderByClause("ORGANIZATION_ID ASC, SCORE DESC");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs, new Object[][]{{1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 5}, {6, 6}});
+
+ //groupBy not orderPreserving orderBy desc asc
+// sql="SELECT ORGANIZATION_ID,SCORE FROM "+tableName+" group by ORGANIZATION_ID, SCORE ORDER BY ORGANIZATION_ID DESC, SCORE ASC";
+ queryBuilder.setGroupByClause("ORGANIZATION_ID, SCORE");
+ queryBuilder.setOrderByClause("ORGANIZATION_ID DESC, SCORE ASC");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSetWithRegionMoves(rs, new Object[][]{{6, 6}, {5, 5}, {4, 4}, {3, 3}, {2,
+ 2}, {1, 1}}, tableName);
+
+ //groupBy not orderPreserving orderBy desc desc
+// sql="SELECT ORGANIZATION_ID,SCORE FROM "+tableName+" group by ORGANIZATION_ID, SCORE ORDER BY ORGANIZATION_ID DESC, SCORE DESC";
+ queryBuilder.setGroupByClause("ORGANIZATION_ID, SCORE");
+ queryBuilder.setOrderByClause("ORGANIZATION_ID DESC, SCORE DESC");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs, new Object[][]{{6, 6}, {5, 5}, {4, 4}, {3, 3}, {2, 2}, {1, 1}});
+ }
+ }
+
+ @Test
+ public void testOrderByReverseOptimizationWithNullsLast1() throws Exception {
+ for (boolean salted : new boolean[]{true, false}) {
+ doTestOrderByReverseOptimizationWithNullsLast(salted, true, true, true);
+ doTestOrderByReverseOptimizationWithNullsLast(salted, true, true, false);
+ }
+ }
+
+ @Test
+ public void testOrderByReverseOptimizationWithNullsLast2() throws Exception {
+ for (boolean salted : new boolean[]{true, false}) {
+ doTestOrderByReverseOptimizationWithNullsLast(salted, true, false, true);
+ doTestOrderByReverseOptimizationWithNullsLast(salted, true, false, false);
+ }
+ }
+
+ @Test
+ public void testOrderByReverseOptimizationWithNullsLast3() throws Exception {
+ for (boolean salted : new boolean[]{true, false}) {
+ doTestOrderByReverseOptimizationWithNullsLast(salted, false, true, true);
+ doTestOrderByReverseOptimizationWithNullsLast(salted, false, true, false);
+ }
+ }
+
+ @Test
+ public void testOrderByReverseOptimizationWithNullsLast4() throws Exception {
+ for (boolean salted : new boolean[]{true, false}) {
+ doTestOrderByReverseOptimizationWithNullsLast(salted, false, false, true);
+ doTestOrderByReverseOptimizationWithNullsLast(salted, false, false, false);
+ }
+ }
+
+ private void doTestOrderByReverseOptimizationWithNullsLast(boolean salted, boolean desc1,
+ boolean desc2, boolean desc3)
+ throws Exception {
+ Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
+ try (Connection conn = DriverManager.getConnection(getUrl(), props)) {
+ String tableName = generateUniqueName();
+ TABLE_NAMES.add(tableName);
+ String sql = "CREATE TABLE " + tableName + " ( " +
+ "ORGANIZATION_ID VARCHAR," +
+ "CONTAINER_ID VARCHAR," +
+ "SCORE VARCHAR," +
+ "ENTITY_ID VARCHAR NOT NULL," +
+ "CONSTRAINT TEST_PK PRIMARY KEY ( " +
+ "ORGANIZATION_ID" + (desc1 ? " DESC" : "") + "," +
+ "CONTAINER_ID" + (desc2 ? " DESC" : "") + "," +
+ "SCORE" + (desc3 ? " DESC" : "") + "," +
+ "ENTITY_ID" +
+ ")) " + (salted ? "SALT_BUCKETS =4" : "split on('4')");
+ conn.createStatement().execute(sql);
+
+ for (int i = 1; i <= 6; i++) {
+ conn.createStatement().execute(
+ "UPSERT INTO " + tableName + " VALUES (null,'" + i + "','" + i + "','" + i +
+ "')");
+ conn.createStatement().execute(
+ "UPSERT INTO " + tableName + " VALUES (null,'" + i + "',null,'" + i + "')");
+ conn.createStatement().execute(
+ "UPSERT INTO " + tableName + " VALUES (null,null,'" + i + "','" + i + "')");
+ conn.createStatement().execute(
+ "UPSERT INTO " + tableName + " VALUES (null,null,null,'" + i + "')");
+ conn.createStatement().execute(
+ "UPSERT INTO " + tableName + " VALUES ('" + i + "','" + i + "','" + i +
+ "','" + i + "')");
+ conn.createStatement().execute(
+ "UPSERT INTO " + tableName + " VALUES ('" + i + "','" + i + "',null,'" + i +
+ "')");
+ conn.createStatement().execute(
+ "UPSERT INTO " + tableName + " VALUES ('" + i + "',null,'" + i + "','" + i +
+ "')");
+ conn.createStatement().execute(
+ "UPSERT INTO " + tableName + " VALUES ('" + i + "',null,null,'" + i + "')");
+ }
+ conn.createStatement()
+ .execute("UPSERT INTO " + tableName + " VALUES (null,null,null,'66')");
+ conn.commit();
+
+ //groupBy orderPreserving orderBy asc asc
+
+// sql="SELECT ORGANIZATION_ID,CONTAINER_ID FROM "+tableName+" group by ORGANIZATION_ID, CONTAINER_ID ORDER BY ORGANIZATION_ID ASC NULLS FIRST, CONTAINER_ID ASC NULLS FIRST";
+ QueryBuilder queryBuilder = new QueryBuilder()
+ .setSelectColumns(
+ Lists.newArrayList("ORGANIZATION_ID", "CONTAINER_ID"))
+ .setFullTableName(tableName)
+ .setGroupByClause("ORGANIZATION_ID, CONTAINER_ID")
+ .setOrderByClause(
+ "ORGANIZATION_ID ASC NULLS FIRST, CONTAINER_ID ASC NULLS FIRST");
+ ResultSet rs = executeQuery(conn, queryBuilder);
+ assertResultSetWithRegionMoves(rs,
+ new Object[][]{{null, null}, {null, "1"}, {null, "2"}, {null, "3"}, {null, "4"},
+ {null, "5"}, {null, "6"}, {"1", null}, {"1", "1"}, {"2", null},
+ {"2", "2"}, {"3", null}, {"3", "3"}, {"4", null}, {"4", "4"},
+ {"5", null}, {"5", "5"}, {"6", null}, {"6", "6"}}, tableName);
+
+// sql="SELECT ORGANIZATION_ID,CONTAINER_ID FROM "+tableName+" group by ORGANIZATION_ID, CONTAINER_ID ORDER BY ORGANIZATION_ID ASC NULLS FIRST, CONTAINER_ID ASC NULLS LAST";
+ queryBuilder.setOrderByClause(
+ "ORGANIZATION_ID ASC NULLS FIRST, CONTAINER_ID ASC NULLS LAST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs,
+ new Object[][]{{null, "1"}, {null, "2"}, {null, "3"}, {null, "4"}, {null, "5"},
+ {null, "6"}, {null, null}, {"1", "1"}, {"1", null}, {"2", "2"},
+ {"2", null}, {"3", "3"}, {"3", null}, {"4", "4"}, {"4", null},
+ {"5", "5"}, {"5", null}, {"6", "6"}, {"6", null}});
+
+// sql="SELECT ORGANIZATION_ID,CONTAINER_ID FROM "+tableName+" group by ORGANIZATION_ID, CONTAINER_ID ORDER BY ORDER BY ORGANIZATION_ID ASC NULLS FIRST, CONTAINER_ID ASC NULLS LAST";
+ queryBuilder.setOrderByClause(
+ "ORGANIZATION_ID ASC NULLS FIRST, CONTAINER_ID ASC NULLS LAST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs,
+ new Object[][]{{null, "1"}, {null, "2"}, {null, "3"}, {null, "4"}, {null, "5"},
+ {null, "6"}, {null, null}, {"1", "1"}, {"1", null}, {"2", "2"},
+ {"2", null}, {"3", "3"}, {"3", null}, {"4", "4"}, {"4", null},
+ {"5", "5"}, {"5", null}, {"6", "6"}, {"6", null}});
+
+// sql="SELECT ORGANIZATION_ID,CONTAINER_ID FROM "+tableName+" group by ORGANIZATION_ID, CONTAINER_ID ORDER BY ORGANIZATION_ID ASC NULLS LAST, CONTAINER_ID ASC NULLS LAST";
+ queryBuilder.setOrderByClause(
+ "ORGANIZATION_ID ASC NULLS LAST, CONTAINER_ID ASC NULLS LAST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs,
+ new Object[][]{{"1", "1"}, {"1", null}, {"2", "2"}, {"2", null}, {"3", "3"},
+ {"3", null}, {"4", "4"}, {"4", null}, {"5", "5"}, {"5", null},
+ {"6", "6"}, {"6", null}, {null, "1"}, {null, "2"}, {null, "3"},
+ {null, "4"}, {null, "5"}, {null, "6"}, {null, null}});
+
+ //groupBy orderPreserving orderBy asc desc
+
+// sql="SELECT ORGANIZATION_ID,CONTAINER_ID FROM "+tableName+" group by ORGANIZATION_ID, CONTAINER_ID ORDER BY ORGANIZATION_ID ASC NULLS FIRST, CONTAINER_ID DESC NULLS FIRST";
+ queryBuilder.setOrderByClause(
+ "ORGANIZATION_ID ASC NULLS FIRST, CONTAINER_ID DESC NULLS FIRST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs,
+ new Object[][]{{null, null}, {null, "6"}, {null, "5"}, {null, "4"}, {null, "3"},
+ {null, "2"}, {null, "1"}, {"1", null}, {"1", "1"}, {"2", null},
+ {"2", "2"}, {"3", null}, {"3", "3"}, {"4", null}, {"4", "4"},
+ {"5", null}, {"5", "5"}, {"6", null}, {"6", "6"}});
+
+// sql="SELECT ORGANIZATION_ID,CONTAINER_ID FROM "+tableName+" group by ORGANIZATION_ID, CONTAINER_ID ORDER BY ORGANIZATION_ID ASC NULLS FIRST, CONTAINER_ID DESC NULLS LAST";
+ queryBuilder.setOrderByClause(
+ "ORGANIZATION_ID ASC NULLS FIRST, CONTAINER_ID DESC NULLS LAST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSetWithRegionMoves(rs,
+ new Object[][]{{null, "6"}, {null, "5"}, {null, "4"}, {null, "3"}, {null, "2"},
+ {null, "1"}, {null, null}, {"1", "1"}, {"1", null}, {"2", "2"},
+ {"2", null}, {"3", "3"}, {"3", null}, {"4", "4"}, {"4", null},
+ {"5", "5"}, {"5", null}, {"6", "6"}, {"6", null}}, tableName);
+
+// sql="SELECT ORGANIZATION_ID,CONTAINER_ID FROM "+tableName+" group by ORGANIZATION_ID, CONTAINER_ID ORDER BY ORGANIZATION_ID ASC NULLS LAST, CONTAINER_ID DESC NULLS FIRST";
+ queryBuilder.setOrderByClause(
+ "ORGANIZATION_ID ASC NULLS LAST, CONTAINER_ID DESC NULLS FIRST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs,
+ new Object[][]{{"1", null}, {"1", "1"}, {"2", null}, {"2", "2"}, {"3", null},
+ {"3", "3"}, {"4", null}, {"4", "4"}, {"5", null}, {"5", "5"},
+ {"6", null}, {"6", "6"}, {null, null}, {null, "6"}, {null, "5"},
+ {null, "4"}, {null, "3"}, {null, "2"}, {null, "1"}});
+
+// sql="SELECT ORGANIZATION_ID,CONTAINER_ID FROM "+tableName+" group by ORGANIZATION_ID, CONTAINER_ID ORDER BY ORGANIZATION_ID ASC NULLS LAST, CONTAINER_ID DESC NULLS LAST";
+ queryBuilder.setOrderByClause(
+ "ORGANIZATION_ID ASC NULLS LAST, CONTAINER_ID DESC NULLS LAST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs,
+ new Object[][]{{"1", "1"}, {"1", null}, {"2", "2"}, {"2", null}, {"3", "3"},
+ {"3", null}, {"4", "4"}, {"4", null}, {"5", "5"}, {"5", null},
+ {"6", "6"}, {"6", null}, {null, "6"}, {null, "5"}, {null, "4"},
+ {null, "3"}, {null, "2"}, {null, "1"}, {null, null}});
+
+ //groupBy orderPreserving orderBy desc asc
+
+// sql="SELECT ORGANIZATION_ID,CONTAINER_ID FROM "+tableName+" group by ORGANIZATION_ID, CONTAINER_ID ORDER BY ORGANIZATION_ID DESC NULLS FIRST, CONTAINER_ID ASC NULLS FIRST";
+ queryBuilder.setOrderByClause(
+ "ORGANIZATION_ID DESC NULLS FIRST, CONTAINER_ID ASC NULLS FIRST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs,
+ new Object[][]{{null, null}, {null, "1"}, {null, "2"}, {null, "3"}, {null, "4"},
+ {null, "5"}, {null, "6"}, {"6", null}, {"6", "6"}, {"5", null},
+ {"5", "5"}, {"4", null}, {"4", "4"}, {"3", null}, {"3", "3"},
+ {"2", null}, {"2", "2"}, {"1", null}, {"1", "1"}});
+
+// sql="SELECT ORGANIZATION_ID,CONTAINER_ID FROM "+tableName+" group by ORGANIZATION_ID, CONTAINER_ID ORDER BY ORGANIZATION_ID DESC NULLS FIRST, CONTAINER_ID ASC NULLS LAST";
+ queryBuilder.setOrderByClause(
+ "ORGANIZATION_ID DESC NULLS FIRST, CONTAINER_ID ASC NULLS LAST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs,
+ new Object[][]{{null, "1"}, {null, "2"}, {null, "3"}, {null, "4"}, {null, "5"},
+ {null, "6"}, {null, null}, {"6", "6"}, {"6", null}, {"5", "5"},
+ {"5", null}, {"4", "4"}, {"4", null}, {"3", "3"}, {"3", null},
+ {"2", "2"}, {"2", null}, {"1", "1"}, {"1", null}});
+
+// sql="SELECT ORGANIZATION_ID,CONTAINER_ID FROM "+tableName+" group by ORGANIZATION_ID, CONTAINER_ID ORDER BY ORGANIZATION_ID DESC NULLS LAST, CONTAINER_ID ASC NULLS FIRST";
+ queryBuilder.setOrderByClause(
+ "ORGANIZATION_ID DESC NULLS LAST, CONTAINER_ID ASC NULLS FIRST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs,
+ new Object[][]{{"6", null}, {"6", "6"}, {"5", null}, {"5", "5"}, {"4", null},
+ {"4", "4"}, {"3", null}, {"3", "3"}, {"2", null}, {"2", "2"},
+ {"1", null}, {"1", "1"}, {null, null}, {null, "1"}, {null, "2"},
+ {null, "3"}, {null, "4"}, {null, "5"}, {null, "6"}});
+
+// sql="SELECT ORGANIZATION_ID,CONTAINER_ID FROM "+tableName+" group by ORGANIZATION_ID, CONTAINER_ID ORDER BY ORGANIZATION_ID DESC NULLS LAST, CONTAINER_ID ASC NULLS LAST";
+ queryBuilder.setOrderByClause(
+ "ORGANIZATION_ID DESC NULLS LAST, CONTAINER_ID ASC NULLS LAST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs,
+ new Object[][]{{"6", "6"}, {"6", null}, {"5", "5"}, {"5", null}, {"4", "4"},
+ {"4", null}, {"3", "3"}, {"3", null}, {"2", "2"}, {"2", null},
+ {"1", "1"}, {"1", null}, {null, "1"}, {null, "2"}, {null, "3"},
+ {null, "4"}, {null, "5"}, {null, "6"}, {null, null}});
+
+ //groupBy orderPreserving orderBy desc desc
+
+// sql="SELECT ORGANIZATION_ID,CONTAINER_ID FROM "+tableName+" group by ORGANIZATION_ID, CONTAINER_ID ORDER BY ORGANIZATION_ID DESC NULLS FIRST, CONTAINER_ID DESC NULLS FIRST";
+ queryBuilder.setOrderByClause(
+ "ORGANIZATION_ID DESC NULLS FIRST, CONTAINER_ID DESC NULLS FIRST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs,
+ new Object[][]{{null, null}, {null, "6"}, {null, "5"}, {null, "4"}, {null, "3"},
+ {null, "2"}, {null, "1"}, {"6", null}, {"6", "6"}, {"5", null},
+ {"5", "5"}, {"4", null}, {"4", "4"}, {"3", null}, {"3", "3"},
+ {"2", null}, {"2", "2"}, {"1", null}, {"1", "1"}});
+
+// sql="SELECT ORGANIZATION_ID,CONTAINER_ID FROM "+tableName+" group by ORGANIZATION_ID, CONTAINER_ID ORDER BY ORGANIZATION_ID DESC NULLS FIRST, CONTAINER_ID DESC NULLS LAST";
+ queryBuilder.setOrderByClause(
+ "ORGANIZATION_ID DESC NULLS FIRST, CONTAINER_ID DESC NULLS LAST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs,
+ new Object[][]{{null, "6"}, {null, "5"}, {null, "4"}, {null, "3"}, {null, "2"},
+ {null, "1"}, {null, null}, {"6", "6"}, {"6", null}, {"5", "5"},
+ {"5", null}, {"4", "4"}, {"4", null}, {"3", "3"}, {"3", null},
+ {"2", "2"}, {"2", null}, {"1", "1"}, {"1", null}});
+
+// sql="SELECT ORGANIZATION_ID,CONTAINER_ID FROM "+tableName+" group by ORGANIZATION_ID, CONTAINER_ID ORDER BY ORGANIZATION_ID DESC NULLS LAST, CONTAINER_ID DESC NULLS FIRST";
+ queryBuilder.setOrderByClause(
+ "ORGANIZATION_ID DESC NULLS LAST, CONTAINER_ID DESC NULLS FIRST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSetWithRegionMoves(rs,
+ new Object[][]{{"6", null}, {"6", "6"}, {"5", null}, {"5", "5"}, {"4", null},
+ {"4", "4"}, {"3", null}, {"3", "3"}, {"2", null}, {"2", "2"},
+ {"1", null}, {"1", "1"}, {null, null}, {null, "6"}, {null, "5"},
+ {null, "4"}, {null, "3"}, {null, "2"}, {null, "1"}}, tableName);
+
+// sql="SELECT ORGANIZATION_ID,CONTAINER_ID FROM "+tableName+" group by ORGANIZATION_ID, CONTAINER_ID ORDER BY ORGANIZATION_ID DESC NULLS LAST, CONTAINER_ID DESC NULLS LAST";
+ queryBuilder.setOrderByClause(
+ "ORGANIZATION_ID DESC NULLS LAST, CONTAINER_ID DESC NULLS LAST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs,
+ new Object[][]{{"6", "6"}, {"6", null}, {"5", "5"}, {"5", null}, {"4", "4"},
+ {"4", null}, {"3", "3"}, {"3", null}, {"2", "2"}, {"2", null},
+ {"1", "1"}, {"1", null}, {null, "6"}, {null, "5"}, {null, "4"},
+ {null, "3"}, {null, "2"}, {null, "1"}, {null, null}});
+
+ //-----groupBy not orderPreserving--
+
+ //groupBy not orderPreserving orderBy asc asc
+
+// sql="SELECT ORGANIZATION_ID,SCORE FROM "+tableName+" group by ORGANIZATION_ID, SCORE ORDER BY ORGANIZATION_ID ASC NULLS FIRST, SCORE ASC NULLS FIRST";
+ queryBuilder.setSelectColumns(
+ Lists.newArrayList("ORGANIZATION_ID", "SCORE"))
+ .setFullTableName(tableName)
+ .setGroupByClause("ORGANIZATION_ID, SCORE")
+ .setOrderByClause("ORGANIZATION_ID ASC NULLS FIRST, SCORE ASC NULLS FIRST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs,
+ new Object[][]{{null, null}, {null, "1"}, {null, "2"}, {null, "3"}, {null, "4"},
+ {null, "5"}, {null, "6"}, {"1", null}, {"1", "1"}, {"2", null},
+ {"2", "2"}, {"3", null}, {"3", "3"}, {"4", null}, {"4", "4"},
+ {"5", null}, {"5", "5"}, {"6", null}, {"6", "6"}});
+
+// sql="SELECT ORGANIZATION_ID,SCORE FROM "+tableName+" group by ORGANIZATION_ID, SCORE ORDER BY ORGANIZATION_ID ASC NULLS FIRST, SCORE ASC NULLS LAST";
+ queryBuilder.setOrderByClause("ORGANIZATION_ID ASC NULLS FIRST, SCORE ASC NULLS LAST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs,
+ new Object[][]{{null, "1"}, {null, "2"}, {null, "3"}, {null, "4"}, {null, "5"},
+ {null, "6"}, {null, null}, {"1", "1"}, {"1", null}, {"2", "2"},
+ {"2", null}, {"3", "3"}, {"3", null}, {"4", "4"}, {"4", null},
+ {"5", "5"}, {"5", null}, {"6", "6"}, {"6", null}});
+
+// sql="SELECT ORGANIZATION_ID,SCORE FROM "+tableName+" group by ORGANIZATION_ID, SCORE ORDER BY ORGANIZATION_ID ASC NULLS LAST, SCORE ASC NULLS FIRST";
+ queryBuilder.setOrderByClause("ORGANIZATION_ID ASC NULLS LAST, SCORE ASC NULLS FIRST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs,
+ new Object[][]{{"1", null}, {"1", "1"}, {"2", null}, {"2", "2"}, {"3", null},
+ {"3", "3"}, {"4", null}, {"4", "4"}, {"5", null}, {"5", "5"},
+ {"6", null}, {"6", "6"}, {null, null}, {null, "1"}, {null, "2"},
+ {null, "3"}, {null, "4"}, {null, "5"}, {null, "6"}});
+
+// sql="SELECT ORGANIZATION_ID,SCORE FROM "+tableName+" group by ORGANIZATION_ID, SCORE ORDER BY ORGANIZATION_ID ASC NULLS LAST, SCORE ASC NULLS LAST";
+ queryBuilder.setOrderByClause("ORGANIZATION_ID ASC NULLS LAST, SCORE ASC NULLS LAST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs,
+ new Object[][]{{"1", "1"}, {"1", null}, {"2", "2"}, {"2", null}, {"3", "3"},
+ {"3", null}, {"4", "4"}, {"4", null}, {"5", "5"}, {"5", null},
+ {"6", "6"}, {"6", null}, {null, "1"}, {null, "2"}, {null, "3"},
+ {null, "4"}, {null, "5"}, {null, "6"}, {null, null}});
+
+ //groupBy not orderPreserving orderBy asc desc
+
+// sql="SELECT ORGANIZATION_ID,SCORE FROM "+tableName+" group by ORGANIZATION_ID, SCORE ORDER BY ORGANIZATION_ID ASC NULLS FIRST, SCORE DESC NULLS FIRST";
+ queryBuilder.setOrderByClause(
+ "ORGANIZATION_ID ASC NULLS FIRST, SCORE DESC NULLS FIRST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs,
+ new Object[][]{{null, null}, {null, "6"}, {null, "5"}, {null, "4"}, {null, "3"},
+ {null, "2"}, {null, "1"}, {"1", null}, {"1", "1"}, {"2", null},
+ {"2", "2"}, {"3", null}, {"3", "3"}, {"4", null}, {"4", "4"},
+ {"5", null}, {"5", "5"}, {"6", null}, {"6", "6"}});
+
+// sql="SELECT ORGANIZATION_ID,SCORE FROM "+tableName+" group by ORGANIZATION_ID, SCORE ORDER BY ORGANIZATION_ID ASC NULLS FIRST, SCORE DESC NULLS LAST";
+ queryBuilder.setOrderByClause("ORGANIZATION_ID ASC NULLS FIRST, SCORE DESC NULLS LAST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs,
+ new Object[][]{{null, "6"}, {null, "5"}, {null, "4"}, {null, "3"}, {null, "2"},
+ {null, "1"}, {null, null}, {"1", "1"}, {"1", null}, {"2", "2"},
+ {"2", null}, {"3", "3"}, {"3", null}, {"4", "4"}, {"4", null},
+ {"5", "5"}, {"5", null}, {"6", "6"}, {"6", null}});
+
+// sql="SELECT ORGANIZATION_ID,SCORE FROM "+tableName+" group by ORGANIZATION_ID, SCORE ORDER BY ORGANIZATION_ID ASC NULLS LAST, SCORE DESC NULLS FIRST";
+ queryBuilder.setOrderByClause("ORGANIZATION_ID ASC NULLS LAST, SCORE DESC NULLS FIRST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs,
+ new Object[][]{{"1", null}, {"1", "1"}, {"2", null}, {"2", "2"}, {"3", null},
+ {"3", "3"}, {"4", null}, {"4", "4"}, {"5", null}, {"5", "5"},
+ {"6", null}, {"6", "6"}, {null, null}, {null, "6"}, {null, "5"},
+ {null, "4"}, {null, "3"}, {null, "2"}, {null, "1"}});
+
+// sql="SELECT ORGANIZATION_ID,SCORE FROM "+tableName+" group by ORGANIZATION_ID, SCORE ORDER BY ORGANIZATION_ID ASC NULLS LAST, SCORE DESC NULLS LAST";
+ queryBuilder.setOrderByClause("ORGANIZATION_ID ASC NULLS LAST, SCORE DESC NULLS LAST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs,
+ new Object[][]{{"1", "1"}, {"1", null}, {"2", "2"}, {"2", null}, {"3", "3"},
+ {"3", null}, {"4", "4"}, {"4", null}, {"5", "5"}, {"5", null},
+ {"6", "6"}, {"6", null}, {null, "6"}, {null, "5"}, {null, "4"},
+ {null, "3"}, {null, "2"}, {null, "1"}, {null, null}});
+
+ //groupBy not orderPreserving orderBy desc asc
+
+// sql="SELECT ORGANIZATION_ID,SCORE FROM "+tableName+" group by ORGANIZATION_ID, SCORE ORDER BY ORGANIZATION_ID DESC NULLS FIRST, SCORE ASC NULLS FIRST";
+ queryBuilder.setOrderByClause(
+ "ORGANIZATION_ID DESC NULLS FIRST, SCORE ASC NULLS FIRST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs,
+ new Object[][]{{null, null}, {null, "1"}, {null, "2"}, {null, "3"}, {null, "4"},
+ {null, "5"}, {null, "6"}, {"6", null}, {"6", "6"}, {"5", null},
+ {"5", "5"}, {"4", null}, {"4", "4"}, {"3", null}, {"3", "3"},
+ {"2", null}, {"2", "2"}, {"1", null}, {"1", "1"}});
+
+// sql="SELECT ORGANIZATION_ID,SCORE FROM "+tableName+" group by ORGANIZATION_ID, SCORE ORDER BY ORGANIZATION_ID DESC NULLS FIRST, SCORE ASC NULLS LAST";
+ queryBuilder.setOrderByClause("ORGANIZATION_ID DESC NULLS FIRST, SCORE ASC NULLS LAST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSetWithRegionMoves(rs,
+ new Object[][]{{null, "1"}, {null, "2"}, {null, "3"}, {null, "4"}, {null, "5"},
+ {null, "6"}, {null, null}, {"6", "6"}, {"6", null}, {"5", "5"},
+ {"5", null}, {"4", "4"}, {"4", null}, {"3", "3"}, {"3", null},
+ {"2", "2"}, {"2", null}, {"1", "1"}, {"1", null}}, tableName);
+
+// sql="SELECT ORGANIZATION_ID,SCORE FROM "+tableName+" group by ORGANIZATION_ID, SCORE ORDER BY ORGANIZATION_ID DESC NULLS LAST, SCORE ASC NULLS FIRST";
+ queryBuilder.setOrderByClause("ORGANIZATION_ID DESC NULLS LAST, SCORE ASC NULLS FIRST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs,
+ new Object[][]{{"6", null}, {"6", "6"}, {"5", null}, {"5", "5"}, {"4", null},
+ {"4", "4"}, {"3", null}, {"3", "3"}, {"2", null}, {"2", "2"},
+ {"1", null}, {"1", "1"}, {null, null}, {null, "1"}, {null, "2"},
+ {null, "3"}, {null, "4"}, {null, "5"}, {null, "6"}});
+
+// sql="SELECT ORGANIZATION_ID,SCORE FROM "+tableName+" group by ORGANIZATION_ID, SCORE ORDER BY ORGANIZATION_ID DESC NULLS LAST, SCORE ASC NULLS LAST";
+ queryBuilder.setOrderByClause("ORGANIZATION_ID DESC NULLS LAST, SCORE ASC NULLS LAST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs,
+ new Object[][]{{"6", "6"}, {"6", null}, {"5", "5"}, {"5", null}, {"4", "4"},
+ {"4", null}, {"3", "3"}, {"3", null}, {"2", "2"}, {"2", null},
+ {"1", "1"}, {"1", null}, {null, "1"}, {null, "2"}, {null, "3"},
+ {null, "4"}, {null, "5"}, {null, "6"}, {null, null}});
+
+ //groupBy not orderPreserving orderBy desc desc
+
+// sql="SELECT ORGANIZATION_ID,SCORE FROM "+tableName+" group by ORGANIZATION_ID, SCORE ORDER BY ORGANIZATION_ID DESC NULLS FIRST, SCORE DESC NULLS FIRST";
+ queryBuilder.setOrderByClause(
+ "ORGANIZATION_ID DESC NULLS FIRST, SCORE DESC NULLS FIRST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs,
+ new Object[][]{{null, null}, {null, "6"}, {null, "5"}, {null, "4"}, {null, "3"},
+ {null, "2"}, {null, "1"}, {"6", null}, {"6", "6"}, {"5", null},
+ {"5", "5"}, {"4", null}, {"4", "4"}, {"3", null}, {"3", "3"},
+ {"2", null}, {"2", "2"}, {"1", null}, {"1", "1"}});
+
+// sql="SELECT ORGANIZATION_ID,SCORE FROM "+tableName+" group by ORGANIZATION_ID, SCORE ORDER BY ORGANIZATION_ID DESC NULLS FIRST, SCORE DESC NULLS LAST";
+ queryBuilder.setOrderByClause(
+ "ORGANIZATION_ID DESC NULLS FIRST, SCORE DESC NULLS LAST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs,
+ new Object[][]{{null, "6"}, {null, "5"}, {null, "4"}, {null, "3"}, {null, "2"},
+ {null, "1"}, {null, null}, {"6", "6"}, {"6", null}, {"5", "5"},
+ {"5", null}, {"4", "4"}, {"4", null}, {"3", "3"}, {"3", null},
+ {"2", "2"}, {"2", null}, {"1", "1"}, {"1", null}});
+
+// sql="SELECT ORGANIZATION_ID,SCORE FROM "+tableName+" group by ORGANIZATION_ID, SCORE ORDER BY ORGANIZATION_ID DESC NULLS LAST, SCORE DESC NULLS FIRST";
+ queryBuilder.setOrderByClause(
+ "ORGANIZATION_ID DESC NULLS LAST, SCORE DESC NULLS FIRST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs,
+ new Object[][]{{"6", null}, {"6", "6"}, {"5", null}, {"5", "5"}, {"4", null},
+ {"4", "4"}, {"3", null}, {"3", "3"}, {"2", null}, {"2", "2"},
+ {"1", null}, {"1", "1"}, {null, null}, {null, "6"}, {null, "5"},
+ {null, "4"}, {null, "3"}, {null, "2"}, {null, "1"}});
+
+// sql="SELECT ORGANIZATION_ID,SCORE FROM "+tableName+" group by ORGANIZATION_ID, SCORE ORDER BY ORGANIZATION_ID DESC NULLS LAST, SCORE DESC NULLS LAST";
+ queryBuilder.setOrderByClause("ORGANIZATION_ID DESC NULLS LAST, SCORE DESC NULLS LAST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs,
+ new Object[][]{{"6", "6"}, {"6", null}, {"5", "5"}, {"5", null}, {"4", "4"},
+ {"4", null}, {"3", "3"}, {"3", null}, {"2", "2"}, {"2", null},
+ {"1", "1"}, {"1", null}, {null, "6"}, {null, "5"}, {null, "4"},
+ {null, "3"}, {null, "2"}, {null, "1"}, {null, null}});
+
+ //-------test only one return column----------------------------------
+
+// sql="SELECT SCORE FROM "+tableName+" group by SCORE ORDER BY SCORE ASC NULLS FIRST";
+ queryBuilder.setSelectColumns(
+ Lists.newArrayList("SCORE"))
+ .setFullTableName(tableName)
+ .setGroupByClause("SCORE")
+ .setOrderByClause("SCORE ASC NULLS FIRST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs, new Object[][]{{null}, {"1"}, {"2"}, {"3"}, {"4"}, {"5"}, {"6"}});
+
+// sql="SELECT SCORE FROM "+tableName+" group by SCORE ORDER BY SCORE ASC NULLS LAST";
+ queryBuilder.setOrderByClause("SCORE ASC NULLS LAST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSetWithRegionMoves(rs, new Object[][]{{"1"}, {"2"}, {"3"}, {"4"}, {"5"},
+ {"6"}, {null}}, tableName);
+
+// sql="SELECT SCORE FROM "+tableName+" group by SCORE ORDER BY SCORE DESC NULLS FIRST";
+ queryBuilder.setOrderByClause("SCORE DESC NULLS FIRST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs, new Object[][]{{null}, {"6"}, {"5"}, {"4"}, {"3"}, {"2"}, {"1"}});
+
+// sql="SELECT SCORE FROM "+tableName+" group by SCORE ORDER BY SCORE DESC NULLS LAST";
+ queryBuilder.setOrderByClause("SCORE DESC NULLS LAST");
+ rs = executeQuery(conn, queryBuilder);
+ assertResultSet(rs, new Object[][]{{"6"}, {"5"}, {"4"}, {"3"}, {"2"}, {"1"}, {null}});
+ }
+ }
+
+ @Test
+ public void testOrderByNullable() throws SQLException {
+ Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
+ try (Connection conn = DriverManager.getConnection(getUrl(), props)) {
+ String sql = "CREATE TABLE IF NOT EXISTS us_population (state CHAR(2) NOT NULL," +
+ "city VARCHAR NOT NULL, population BIGINT CONSTRAINT my_pk PRIMARY KEY" +
+ " (state, city))";
+ conn.createStatement().execute(sql);
+ TABLE_NAMES.add("US_POPULATION");
+
+ sql = "select ORDINAL_POSITION from SYSTEM.CATALOG where TABLE_NAME = 'US_POPULATION'";
+ ResultSet rs = conn.createStatement().executeQuery(sql);
+ int expected = 0;
+ while (rs.next()) {
+ expected += 1;
+ }
+
+ QueryBuilder queryBuilder = new QueryBuilder()
+ .setSelectColumns(Lists.newArrayList("*"))
+ .setFullTableName("SYSTEM.CATALOG")
+ .setWhereClause("TABLE_NAME = 'US_POPULATION'")
+ .setOrderByClause("ORDINAL_POSITION");
+ rs = executeQuery(conn, queryBuilder);
+ int linesCount = 0;
+ while (rs.next()) {
+ linesCount += 1;
+ }
+ assertEquals(expected, linesCount);
+
+ queryBuilder = new QueryBuilder()
+ .setSelectColumns(Lists.newArrayList("COLUMN_NAME"))
+ .setFullTableName("SYSTEM.CATALOG")
+ .setWhereClause("TABLE_NAME = 'US_POPULATION'")
+ .setOrderByClause("ORDINAL_POSITION");
+ rs = executeQuery(conn, queryBuilder);
+ linesCount = 0;
+ while (rs.next()) {
+ linesCount += 1;
+ }
+ assertEquals(expected, linesCount);
+ }
+ }
+
+ @Test
+ public void testPhoenix6999() throws Exception {
+ Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
+ String tableName = "TBL_" + generateUniqueName();
+ String descTableName = "TBL_" + generateUniqueName();
+
+ String fullTableName = SchemaUtil.getTableName(TestUtil.DEFAULT_SCHEMA_NAME, tableName);
+ String fullDescTableName =
+ SchemaUtil.getTableName(TestUtil.DEFAULT_SCHEMA_NAME, descTableName);
+ TABLE_NAMES.add(fullTableName);
+ TABLE_NAMES.add(fullDescTableName);
+
+ try (Connection conn = DriverManager.getConnection(getUrl(), props);
+ Statement stmt = conn.createStatement()) {
+ conn.setAutoCommit(false);
+ String ddl =
+ "CREATE TABLE " + fullTableName
+ + "(k1 varchar primary key, v1 varchar, v2 varchar)";
+ stmt.execute(ddl);
+ ddl =
+ "CREATE TABLE " + fullDescTableName
+ + "(k1 varchar primary key desc, v1 varchar, v2 varchar)";
+ stmt.execute(ddl);
+ stmt.execute("upsert into " + fullTableName + " values ('a','a','a')");
+ stmt.execute("upsert into " + fullTableName + " values ('b','b','b')");
+ stmt.execute("upsert into " + fullTableName + " values ('c','c','c')");
+ stmt.execute("upsert into " + fullDescTableName + " values ('a','a','a')");
+ stmt.execute("upsert into " + fullDescTableName + " values ('b','b','b')");
+ stmt.execute("upsert into " + fullDescTableName + " values ('c','c','c')");
+ conn.commit();
+
+ String query = "SELECT * from " + fullTableName + " where k1='b' order by k1 asc";
+ ResultSet rs = stmt.executeQuery(query);
+ assertTrue(rs.next());
+ assertEquals("b", rs.getString(1));
+
+ query = "SELECT * from " + fullTableName + " where k1='b' order by k1 desc";
+ rs = stmt.executeQuery(query);
+ assertTrue(rs.next());
+ assertEquals("b", rs.getString(1));
+
+ query = "SELECT * from " + fullDescTableName + " where k1='b' order by k1 asc";
+ rs = stmt.executeQuery(query);
+ assertTrue(rs.next());
+ assertEquals("b", rs.getString(1));
+
+ query = "SELECT * from " + fullDescTableName + " where k1='b' order by k1 desc";
+ rs = stmt.executeQuery(query);
+ assertTrue(rs.next());
+ assertEquals("b", rs.getString(1));
+ }
+ }
+
+}
\ No newline at end of file
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/BaseQueryWithRegionMovesIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/BaseQueryWithRegionMovesIT.java
new file mode 100644
index 0000000000..446ae58390
--- /dev/null
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/BaseQueryWithRegionMovesIT.java
@@ -0,0 +1,165 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.phoenix.end2end;
+
+import org.apache.phoenix.thirdparty.com.google.common.collect.Lists;
+import org.apache.phoenix.util.PropertiesUtil;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+import org.junit.runners.Parameterized.BeforeParam;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.sql.Connection;
+import java.sql.Date;
+import java.sql.DriverManager;
+import java.sql.SQLTimeoutException;
+import java.util.Collection;
+import java.util.List;
+import java.util.Properties;
+
+import static org.apache.phoenix.util.TestUtil.TEST_PROPERTIES;
+
+/**
+ * Basic tests that include region move hooks while scanning the rows.
+ * <p>
+ */
+@RunWith(Parameterized.class)
+public abstract class BaseQueryWithRegionMovesIT extends ParallelStatsDisabledWithRegionMovesIT {
+ protected static final String tenantId = getOrganizationId();
+ protected static final String NO_INDEX = "";
+ protected static final String[] GLOBAL_INDEX_DDLS =
+ new String[]{
+ "CREATE INDEX IF NOT EXISTS %s ON %s (a_integer DESC) INCLUDE (" +
+ " A_STRING, "
+ + " B_STRING, " + " A_DATE)",
+ "CREATE INDEX IF NOT EXISTS %s ON %s (a_integer, a_string) INCLUDE (" +
+ " B_STRING, "
+ + " A_DATE)",
+ "CREATE INDEX IF NOT EXISTS %s ON %s (a_integer) INCLUDE (" + " A_STRING, "
+ + " B_STRING, " + " A_DATE)",
+ NO_INDEX};
+ private static final String[] INDEX_DDLS;
+
+ static {
+ INDEX_DDLS = new String[GLOBAL_INDEX_DDLS.length];
+ int i = 0;
+ for (String s : GLOBAL_INDEX_DDLS) {
+ INDEX_DDLS[i++] = s;
+ }
+ }
+
+ protected static Date date;
+ protected static String tableName;
+ protected static String indexName;
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(BaseQueryWithRegionMovesIT.class);
+
+ @BeforeParam
+ public static synchronized void initTables(String idxDdl, boolean columnEncoded,
+ boolean keepDeletedCells) throws Exception {
+ StringBuilder optionBuilder = new StringBuilder();
+ if (!columnEncoded) {
+ optionBuilder.append("COLUMN_ENCODED_BYTES=0");
+ }
+ if (keepDeletedCells) {
+ if (optionBuilder.length() > 0) optionBuilder.append(",");
+ optionBuilder.append("KEEP_DELETED_CELLS=true");
+ }
+ String tableDDLOptions = optionBuilder.toString();
+ try {
+ tableName = initATableValues(generateUniqueName(), tenantId,
+ getDefaultSplits(tenantId),
+ date = new Date(System.currentTimeMillis()), null, getUrl(),
+ tableDDLOptions);
+ } catch (Exception e) {
+ LOGGER.error("Exception when creating aTable ", e);
+ throw e;
+ }
+ indexName = generateUniqueName();
+ if (idxDdl.length() > 0) {
+ String indexDDL =
+ String.format(idxDdl, indexName, tableName);
+ Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
+ props.setProperty("phoenix.query.timeoutMs", "30000");
+ try (Connection conn = DriverManager.getConnection(getUrl(), props)) {
+ conn.createStatement().execute(indexDDL);
+ } catch (SQLTimeoutException e) {
+ LOGGER.info("Query timed out. Retrying one more time.", e);
+ try (Connection conn = DriverManager.getConnection(getUrl(), props)) {
+ conn.createStatement().execute(indexDDL);
+ } catch (Exception ex) {
+ LOGGER.error("Exception while creating index during second retry: "
+ + indexDDL, ex);
+ throw ex;
+ }
+ } catch (Exception e) {
+ LOGGER.error("Exception while creating index: " + indexDDL, e);
+ throw e;
+ }
+ }
+ }
+
+ @Before
+ public void setUp() throws Exception {
+ hasTestStarted = true;
+ }
+
+ @After
+ public void tearDown() throws Exception {
+ countOfDummyResults = 0;
+ TABLE_NAMES.clear();
+ hasTestStarted = false;
+ }
+
+ public BaseQueryWithRegionMovesIT(String idxDdl, boolean columnEncoded,
+ boolean keepDeletedCells) {
+ }
+
+ public static Collection<Object> allIndexes() {
+ List<Object> testCases = Lists.newArrayList();
+ for (String indexDDL : INDEX_DDLS) {
+ for (boolean columnEncoded : new boolean[]{false}) {
+ testCases.add(new Object[]{indexDDL, columnEncoded, false});
+ }
+ }
+ return testCases;
+ }
+
+ public static Collection<Object> allIndexesWithEncoded() {
+ List<Object> testCases = Lists.newArrayList();
+ for (String indexDDL : INDEX_DDLS) {
+ for (boolean columnEncoded : new boolean[]{false, true}) {
+ testCases.add(new Object[]{indexDDL, columnEncoded, false});
+ }
+ }
+ return testCases;
+ }
+
+ public static Collection<Object> allIndexesWithEncodedAndKeepDeleted() {
+ List<Object> testCases = Lists.newArrayList();
+ for (String indexDDL : INDEX_DDLS) {
+ for (boolean columnEncoded : new boolean[]{false, true}) {
+ testCases.add(new Object[]{indexDDL, columnEncoded, true});
+ }
+ }
+ return testCases;
+ }
+}
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/GroupByIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/GroupByIT.java
index cde1e0fe50..7fa9329fad 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/GroupByIT.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/GroupByIT.java
@@ -378,4 +378,55 @@ public class GroupByIT extends BaseQueryIT {
conn.close();
}
}
+
+ @Test
+ public void testGroupByHavingWithAlias2() throws Exception {
+ Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
+ Connection conn = DriverManager.getConnection(getUrl(), props);
+ conn.setAutoCommit(false);
+ try {
+ conn = DriverManager.getConnection(getUrl(), props);
+ conn.setAutoCommit(false);
+ String tableName = generateUniqueName();
+ String ddl = "CREATE TABLE " + tableName + " (a_string varchar not null, col1 " +
+ "integer not null, col2 varchar, col3 integer"
+ + " CONSTRAINT pk PRIMARY KEY (a_string, col1))";
+ createTestTable(getUrl(), ddl);
+
+ String dml = "UPSERT INTO " + tableName + " VALUES(?, ?, ?, ?)";
+ PreparedStatement stmt = conn.prepareStatement(dml);
+ stmt.setString(1, "a1xyz");
+ stmt.setInt(2, 40);
+ stmt.setString(3, "col2xyz1");
+ stmt.setInt(4, 50);
+ stmt.execute();
+ stmt.setString(1, "b1xyz");
+ stmt.setInt(2, 20);
+ stmt.setString(3, "col2xyz2");
+ stmt.setInt(4, 60);
+ stmt.execute();
+ stmt.setString(1, "c1xyz");
+ stmt.setInt(2, 30);
+ stmt.setString(3, "col2xyz3");
+ stmt.setInt(4, 70);
+ stmt.execute();
+ conn.commit();
+
+ String query = "SELECT a_string, col1, sum(col1) as sumCol1 FROM " + tableName
+ + " GROUP BY a_string, col1 HAVING sumCol1 > 20 ORDER BY sumCol1";
+ ResultSet rs = conn.createStatement().executeQuery(query);
+ assertTrue(rs.next());
+ assertEquals("c1xyz", rs.getString(1));
+ assertEquals(30, rs.getInt(2));
+ assertEquals(30, rs.getInt(3));
+ assertTrue(rs.next());
+ assertEquals("a1xyz", rs.getString(1));
+ assertEquals(40, rs.getInt(2));
+ assertEquals(40, rs.getInt(3));
+ assertFalse(rs.next());
+ } finally {
+ conn.close();
+ }
+ }
+
}
diff --git a/phoenix-core-server/src/main/java/org/apache/phoenix/coprocessor/GroupByCache.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/OrderByWithRegionMovesIT.java
similarity index 60%
copy from phoenix-core-server/src/main/java/org/apache/phoenix/coprocessor/GroupByCache.java
copy to phoenix-core/src/it/java/org/apache/phoenix/end2end/OrderByWithRegionMovesIT.java
index 68d07a948a..f7a91f31c4 100644
--- a/phoenix-core-server/src/main/java/org/apache/phoenix/coprocessor/GroupByCache.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/OrderByWithRegionMovesIT.java
@@ -15,24 +15,11 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.phoenix.coprocessor;
+package org.apache.phoenix.end2end;
-import java.io.Closeable;
+import org.junit.experimental.categories.Category;
-import org.apache.hadoop.hbase.regionserver.RegionScanner;
-import org.apache.phoenix.expression.aggregator.Aggregator;
-import org.apache.phoenix.hbase.index.util.ImmutableBytesPtr;
+@Category(NeedsOwnMiniClusterTest.class)
+public class OrderByWithRegionMovesIT extends BaseOrderByWithRegionMovesIT {
-/**
- *
- * Interface to abstract the way in which distinct group by
- * elements are cached
- *
- *
- * @since 3.0.0
- */
-public interface GroupByCache extends Closeable {
- long size();
- Aggregator[] cache(ImmutableBytesPtr key);
- RegionScanner getScanner(RegionScanner s);
}
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/OrderByWithServerMemoryLimitIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/OrderByWithServerMemoryLimitIT.java
index 0a71e81bf0..edcf8848f1 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/OrderByWithServerMemoryLimitIT.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/OrderByWithServerMemoryLimitIT.java
@@ -19,10 +19,10 @@ import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
+import java.sql.SQLException;
import java.util.Map;
import java.util.Properties;
-import org.apache.phoenix.exception.PhoenixIOException;
import org.apache.phoenix.query.BaseTest;
import org.apache.phoenix.query.QueryServices;
import org.apache.phoenix.util.PropertiesUtil;
@@ -74,9 +74,11 @@ public class OrderByWithServerMemoryLimitIT extends BaseTest {
try {
rs.next();
fail("Expected PhoenixIOException due to IllegalStateException");
- } catch (PhoenixIOException e) {
- assertThat(e.getMessage(), containsString("java.lang.IllegalStateException: "
- + "Queue full. Consider increasing memory threshold or spooling to disk"));
+ } catch (SQLException e) {
+ assertThat(e.getMessage(), containsString(
+ "ERROR 101 (08000): Unexpected IO exception. ERROR 101 (08000): "
+ + "Queue full. Consider increasing memory threshold or "
+ + "spooling to disk"));
}
}
}
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/ParallelStatsDisabledWithRegionMovesIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/ParallelStatsDisabledWithRegionMovesIT.java
new file mode 100644
index 0000000000..383d5a2232
--- /dev/null
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/ParallelStatsDisabledWithRegionMovesIT.java
@@ -0,0 +1,310 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.phoenix.end2end;
+
+import org.apache.commons.lang3.StringUtils;
+import org.apache.hadoop.hbase.HConstants;
+import org.apache.hadoop.hbase.ServerName;
+import org.apache.hadoop.hbase.TableName;
+import org.apache.hadoop.hbase.client.AsyncAdmin;
+import org.apache.hadoop.hbase.client.AsyncConnection;
+import org.apache.hadoop.hbase.client.ConnectionFactory;
+import org.apache.hadoop.hbase.client.RegionInfo;
+import org.apache.hadoop.hbase.client.RegionStatesCount;
+import org.apache.hadoop.hbase.client.Result;
+import org.apache.hadoop.hbase.client.ResultScanner;
+import org.apache.hadoop.hbase.client.Scan;
+import org.apache.hadoop.hbase.client.Table;
+import org.apache.phoenix.coprocessorclient.BaseScannerRegionObserverConstants;
+import org.apache.phoenix.iterate.ScanningResultPostDummyResultCaller;
+import org.apache.phoenix.query.BaseTest;
+import org.apache.phoenix.query.QueryServices;
+import org.apache.phoenix.util.ByteUtil;
+import org.apache.phoenix.util.QueryBuilder;
+import org.apache.phoenix.util.QueryUtil;
+import org.apache.phoenix.util.ReadOnlyProps;
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.sql.Connection;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+
+/**
+ * Base class for tests whose methods run in parallel with
+ * 1. Statistics enabled on server side (QueryServices#STATS_COLLECTION_ENABLED is true)
+ * 2. Guide Post Width for all relevant tables is 0. Stats are disabled at table level.
+ * <p>
+ * See {@link org.apache.phoenix.schema.stats.NoOpStatsCollectorIT} for tests that disable
+ * stats collection from server side.
+ * <p>
+ * You must create unique names using {@link #generateUniqueName()} for each
+ * table and sequence used to prevent collisions.
+ * <p>
+ * Any class extending this would also observe multiple region moves while tests are running.
+ */
+public abstract class ParallelStatsDisabledWithRegionMovesIT extends BaseTest {
+
+ private static final Logger LOGGER =
+ LoggerFactory.getLogger(ParallelStatsDisabledWithRegionMovesIT.class);
+
+ protected static boolean hasTestStarted = false;
+ protected static int countOfDummyResults = 0;
+ protected static final Set<String> TABLE_NAMES = new HashSet<>();
+
+ protected static class TestScanningResultPostDummyResultCaller extends
+ ScanningResultPostDummyResultCaller {
+
+ @Override
+ public void postDummyProcess() {
+ if (hasTestStarted && (countOfDummyResults++ % 3) == 0 &&
+ (countOfDummyResults < 17 ||
+ countOfDummyResults > 28 && countOfDummyResults < 40)) {
+ LOGGER.info("Moving regions of tables {}. current count of dummy results: {}",
+ TABLE_NAMES, countOfDummyResults);
+ TABLE_NAMES.forEach(table -> {
+ try {
+ moveRegionsOfTable(table);
+ } catch (Exception e) {
+ LOGGER.error("Unable to move regions of table: {}", table);
+ }
+ });
+ }
+ }
+ }
+
+ @BeforeClass
+ public static synchronized void doSetup() throws Exception {
+ Map<String, String> props = new HashMap<>();
+ props.put(BaseScannerRegionObserverConstants.PHOENIX_MAX_LOOKBACK_AGE_CONF_KEY,
+ Integer.toString(60 * 60)); // An hour
+ props.put(QueryServices.USE_STATS_FOR_PARALLELIZATION, Boolean.toString(false));
+ props.put(QueryServices.PHOENIX_SERVER_PAGE_SIZE_MS, Long.toString(0));
+ props.put(QueryServices.TESTS_MINI_CLUSTER_NUM_REGION_SERVERS, String.valueOf(2));
+ props.put(HConstants.HBASE_CLIENT_SCANNER_MAX_RESULT_SIZE_KEY, String.valueOf(1));
+ props.put(QueryServices.PHOENIX_POST_DUMMY_PROCESS,
+ TestScanningResultPostDummyResultCaller.class.getName());
+ setUpTestDriver(new ReadOnlyProps(props.entrySet().iterator()));
+ }
+
+ @AfterClass
+ public static synchronized void freeResources() throws Exception {
+ BaseTest.freeResourcesIfBeyondThreshold();
+ }
+
+ protected static void moveRegionsOfTable(String tableName)
+ throws IOException {
+ try (AsyncConnection asyncConnection =
+ ConnectionFactory.createAsyncConnection(getUtility().getConfiguration())
+ .get()) {
+ AsyncAdmin admin = asyncConnection.getAdmin();
+ List<ServerName> servers =
+ new ArrayList<>(admin.getRegionServers().get());
+ ServerName server1 = servers.get(0);
+ ServerName server2 = servers.get(1);
+ List<RegionInfo> regionsOnServer1;
+ regionsOnServer1 = admin.getRegions(server1).get();
+ List<RegionInfo> regionsOnServer2;
+ regionsOnServer2 = admin.getRegions(server2).get();
+ regionsOnServer1.forEach(regionInfo -> {
+ if (regionInfo.getTable().equals(TableName.valueOf(tableName))) {
+ try {
+ for (int i = 0; i < 2; i++) {
+ RegionStatesCount regionStatesCount =
+ admin.getClusterMetrics().get().getTableRegionStatesCount()
+ .get(TableName.valueOf(tableName));
+ if (regionStatesCount.getRegionsInTransition() == 0 &&
+ regionStatesCount.getOpenRegions() ==
+ regionStatesCount.getTotalRegions()) {
+ LOGGER.info("Moving region {} to {}",
+ regionInfo.getRegionNameAsString(), server2);
+ admin.move(regionInfo.getEncodedNameAsBytes(), server2).get(3,
+ TimeUnit.SECONDS);
+ break;
+ } else {
+ LOGGER.info("Table {} has some region(s) in RIT or not online",
+ tableName);
+ }
+ }
+ } catch (InterruptedException | ExecutionException | TimeoutException e) {
+ LOGGER.error("Something went wrong", e);
+ throw new RuntimeException(e);
+ }
+ }
+ });
+ regionsOnServer2.forEach(regionInfo -> {
+ if (regionInfo.getTable().equals(TableName.valueOf(tableName))) {
+ try {
+ for (int i = 0; i < 2; i++) {
+ RegionStatesCount regionStatesCount =
+ admin.getClusterMetrics().get().getTableRegionStatesCount()
+ .get(TableName.valueOf(tableName));
+ if (regionStatesCount.getRegionsInTransition() == 0 &&
+ regionStatesCount.getOpenRegions() ==
+ regionStatesCount.getTotalRegions()) {
+ admin.move(regionInfo.getEncodedNameAsBytes(), server1)
+ .get(3, TimeUnit.SECONDS);
+ LOGGER.info("Moving region {} to {}",
+ regionInfo.getRegionNameAsString(), server1);
+ break;
+ } else {
+ LOGGER.info("Table {} has some region(s) in RIT or not online",
+ tableName);
+ }
+ }
+ } catch (InterruptedException | ExecutionException | TimeoutException e) {
+ LOGGER.error("Something went wrong", e);
+ throw new RuntimeException(e);
+ }
+ }
+ });
+ } catch (Exception e) {
+ LOGGER.error("Something went wrong..", e);
+ }
+ }
+
+ protected static void splitAllRegionsOfTable(String tableName, int splitAtRow) {
+ try (AsyncConnection asyncConnection =
+ ConnectionFactory.createAsyncConnection(getUtility().getConfiguration())
+ .get()) {
+ AsyncAdmin admin = asyncConnection.getAdmin();
+ List<RegionInfo> regionsOfTable =
+ admin.getRegions(TableName.valueOf(tableName)).get();
+ regionsOfTable.forEach(regionInfo -> {
+ if (regionInfo.getTable().equals(TableName.valueOf(tableName))) {
+ try {
+ for (int i = 0; i < 5; i++) {
+ RegionStatesCount regionStatesCount =
+ admin.getClusterMetrics().get().getTableRegionStatesCount()
+ .get(TableName.valueOf(tableName));
+ byte[] splitPoint;
+ if (regionStatesCount.getRegionsInTransition() == 0 &&
+ regionStatesCount.getOpenRegions() ==
+ regionStatesCount.getTotalRegions()) {
+ try (Table table =
+ utility.getConnection()
+ .getTable(TableName.valueOf(tableName))) {
+ try (ResultScanner resultScanner = table.getScanner(
+ new Scan())) {
+ Result result = null;
+ for (int rowCount = 0; rowCount < splitAtRow; rowCount++) {
+ result = resultScanner.next();
+ if (result == null) {
+ LOGGER.info("Table {} has only {} rows, splitting" +
+ " at row number {} not possible",
+ tableName, rowCount, splitAtRow);
+ return;
+ }
+ }
+ splitPoint = result == null ? null :
+ ByteUtil.closestPossibleRowAfter(result.getRow());
+ }
+ }
+ LOGGER.info("Splitting region {}",
+ regionInfo.getRegionNameAsString());
+ admin.flushRegion(regionInfo.getRegionName()).get(3,
+ TimeUnit.SECONDS);
+ admin.splitRegion(regionInfo.getRegionName(), splitPoint).get(4,
+ TimeUnit.SECONDS);
+ break;
+ } else {
+ LOGGER.info("Table {} has some region(s) in RIT or not online",
+ tableName);
+ Thread.sleep(1000);
+ }
+ }
+ } catch (InterruptedException | ExecutionException | TimeoutException |
+ IOException e) {
+ LOGGER.error("Something went wrong", e);
+ throw new RuntimeException(e);
+ }
+ }
+ });
+ } catch (Exception e) {
+ LOGGER.error("Something went wrong..", e);
+ }
+ }
+
+ protected ResultSet executeQueryThrowsException(Connection conn, QueryBuilder queryBuilder,
+ String expectedPhoenixExceptionMsg,
+ String expectedSparkExceptionMsg) {
+ ResultSet rs = null;
+ try {
+ rs = executeQuery(conn, queryBuilder);
+ fail();
+ } catch (Exception e) {
+ assertTrue(e.getMessage().contains(expectedPhoenixExceptionMsg));
+ }
+ return rs;
+ }
+
+ public static void validateQueryPlan(Connection conn, QueryBuilder queryBuilder,
+ String expectedPhoenixPlan, String expectedSparkPlan)
+ throws SQLException {
+ if (StringUtils.isNotBlank(expectedPhoenixPlan)) {
+ ResultSet rs = conn.createStatement().executeQuery("EXPLAIN " + queryBuilder.build());
+ assertEquals(expectedPhoenixPlan, QueryUtil.getExplainPlan(rs));
+ }
+ }
+
+ protected static void assertResultSetWithRegionMoves(ResultSet rs, Object[][] rows,
+ String tableName)
+ throws Exception {
+ for (int rowIndex = 0; rowIndex < rows.length; rowIndex++) {
+ assertTrue("rowIndex:[" + rowIndex + "] rs.next error!", rs.next());
+ if (rowIndex == 0) {
+ moveRegionsOfTable(tableName);
+ }
+ for (int columnIndex = 1; columnIndex <= rows[rowIndex].length; columnIndex++) {
+ Object realValue = rs.getObject(columnIndex);
+ Object expectedValue = rows[rowIndex][columnIndex - 1];
+ if (realValue == null) {
+ assertNull("rowIndex:[" + rowIndex + "],columnIndex:[" + columnIndex + "]",
+ expectedValue);
+ } else {
+ assertEquals("rowIndex:[" + rowIndex + "],columnIndex:[" + columnIndex + "]",
+ expectedValue,
+ realValue
+ );
+ }
+ }
+ }
+ assertFalse(rs.next());
+ }
+
+}
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/ScanUncommittedWithRegionMovesIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/ScanUncommittedWithRegionMovesIT.java
new file mode 100644
index 0000000000..cf4e69b429
--- /dev/null
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/ScanUncommittedWithRegionMovesIT.java
@@ -0,0 +1,551 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.phoenix.end2end;
+
+import org.apache.commons.lang3.StringUtils;
+import org.apache.hadoop.hbase.HConstants;
+import org.apache.hadoop.hbase.ServerName;
+import org.apache.hadoop.hbase.TableName;
+import org.apache.hadoop.hbase.client.Admin;
+import org.apache.hadoop.hbase.client.RegionInfo;
+import org.apache.phoenix.iterate.ScanningResultPostDummyResultCaller;
+import org.apache.phoenix.query.QueryServices;
+import org.apache.phoenix.thirdparty.com.google.common.collect.Maps;
+import org.apache.phoenix.util.ReadOnlyProps;
+import org.junit.After;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+/**
+ * Tests to ensure we perform READ_COMMITTED scan i.e. after the scanner is opened, any updated
+ * data should not be visible to the scanner until it is closed. The ongoing scanner should
+ * only be able to cover the region state that was present before the scanner was opened. HBase
+ * provides this guarantee by using region level MVCC.
+ */
+@Category(NeedsOwnMiniClusterTest.class)
+public class ScanUncommittedWithRegionMovesIT extends ParallelStatsDisabledIT {
+
+ private static final Logger LOGGER =
+ LoggerFactory.getLogger(ScanUncommittedWithRegionMovesIT.class);
+
+ private static boolean hasTestStarted = false;
+ private static int countOfDummyResults = 0;
+ private static final Set<String> TABLE_NAMES = new HashSet<>();
+
+ private static class TestScanningResultPostDummyResultCaller extends
+ ScanningResultPostDummyResultCaller {
+
+ @Override
+ public void postDummyProcess() {
+ if (hasTestStarted && (countOfDummyResults++ % 5) == 0 &&
+ (countOfDummyResults < 17 ||
+ countOfDummyResults > 28 && countOfDummyResults < 40)) {
+ LOGGER.info("Moving regions of tables {}. current count of dummy results: {}",
+ TABLE_NAMES, countOfDummyResults);
+ TABLE_NAMES.forEach(table -> {
+ try {
+ moveRegionsOfTable(table);
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ });
+ }
+ }
+ }
+
+ @BeforeClass
+ public static synchronized void doSetup() throws Exception {
+ Map<String, String> props = Maps.newHashMapWithExpectedSize(2);
+ props.put(QueryServices.PHOENIX_SERVER_PAGE_SIZE_MS, Long.toString(0));
+ props.put(QueryServices.COLLECT_REQUEST_LEVEL_METRICS, String.valueOf(true));
+ props.put(QueryServices.TESTS_MINI_CLUSTER_NUM_REGION_SERVERS, String.valueOf(2));
+ props.put(HConstants.HBASE_CLIENT_SCANNER_MAX_RESULT_SIZE_KEY, String.valueOf(1));
+ props.put(QueryServices.PHOENIX_POST_DUMMY_PROCESS,
+ TestScanningResultPostDummyResultCaller.class.getName());
+ setUpTestDriver(new ReadOnlyProps(props.entrySet().iterator()));
+ }
+
+ @After
+ public void tearDown() throws Exception {
+ TABLE_NAMES.clear();
+ hasTestStarted = false;
+ countOfDummyResults = 0;
+ }
+
+ private static void moveRegionsOfTable(String tableName)
+ throws IOException {
+ if (StringUtils.isEmpty(tableName)) {
+ return;
+ }
+ Admin admin = getUtility().getAdmin();
+ List<ServerName> servers =
+ new ArrayList<>(admin.getRegionServers());
+ ServerName server1 = servers.get(0);
+ ServerName server2 = servers.get(1);
+ List<RegionInfo> regionsOnServer1;
+ try {
+ regionsOnServer1 = admin.getRegions(server1);
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ List<RegionInfo> regionsOnServer2;
+ try {
+ regionsOnServer2 = admin.getRegions(server2);
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ regionsOnServer1.forEach(regionInfo -> {
+ if (regionInfo.getTable().equals(TableName.valueOf(tableName))) {
+ try {
+ admin.move(regionInfo.getEncodedNameAsBytes(), server2);
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ }
+ });
+ regionsOnServer2.forEach(regionInfo -> {
+ if (regionInfo.getTable().equals(TableName.valueOf(tableName))) {
+ try {
+ admin.move(regionInfo.getEncodedNameAsBytes(), server1);
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ }
+ });
+ }
+
+ @Test
+ public void testUncoveredIndex() throws Exception {
+ hasTestStarted = true;
+ String dataTableName = generateUniqueName();
+ populateTable(dataTableName);
+ try (Connection conn = DriverManager.getConnection(getUrl())) {
+ String indexTableName = generateUniqueName();
+ conn.createStatement().execute("CREATE UNCOVERED INDEX "
+ + indexTableName + " on " + dataTableName + " (val1) ");
+ populateTableWithAdditionalRows(dataTableName, conn);
+ conn.commit();
+ TABLE_NAMES.add(dataTableName);
+ TABLE_NAMES.add(indexTableName);
+ String selectSql;
+
+ // Verify that an index hint is not necessary for an uncovered index
+ selectSql = "SELECT val2, val3 from " + dataTableName +
+ " WHERE val1 IS NOT NULL";
+
+ try (ResultSet rs = conn.createStatement().executeQuery(selectSql)) {
+ assertTrue(rs.next());
+ assertEquals("abc", rs.getString(1));
+ assertEquals("abcd", rs.getString(2));
+ moveRegionsOfTable(dataTableName);
+ moveRegionsOfTable(indexTableName);
+ try (Connection newConn = DriverManager.getConnection(getUrl())) {
+ newConn.createStatement().execute("upsert into " + dataTableName
+ + " (id, val1, val2, val3) values ('c1', 'cd1','cde1', 'cdef1')");
+ newConn.createStatement().execute("upsert into " + dataTableName
+ + " (id, val1, val2, val3) values ('g1', 'gh1','gh11', 'gh111')");
+ newConn.createStatement().execute("upsert into " + dataTableName
+ + " (id, val1, val2, val3) values ('l', 'lm','lmn', 'lmno')");
+ newConn.createStatement().execute("upsert into " + dataTableName
+ + " (id, val1, val2, val3) values ('m', 'mn','mno', 'mnop')");
+ newConn.commit();
+ }
+ assertRowsWithOldScanner(dataTableName, indexTableName, rs, true);
+ }
+
+ try (ResultSet rs = conn.createStatement().executeQuery(selectSql)) {
+ assertRowsWithNewScanner(dataTableName, indexTableName, rs, true);
+ }
+ }
+ }
+
+ @Test
+ public void testCoveredIndex() throws Exception {
+ hasTestStarted = true;
+ String dataTableName = generateUniqueName();
+ populateTable(dataTableName);
+ try (Connection conn = DriverManager.getConnection(getUrl())) {
+ String indexTableName = generateUniqueName();
+ conn.createStatement().execute("CREATE INDEX "
+ + indexTableName + " on " + dataTableName + " (val1) INCLUDE (val2, val3)");
+ populateTableWithAdditionalRows(dataTableName, conn);
+ conn.commit();
+ TABLE_NAMES.add(dataTableName);
+ TABLE_NAMES.add(indexTableName);
+ String selectSql;
+
+ // Verify that an index hint is not necessary for an uncovered index
+ selectSql = "SELECT val2, val3 from " + dataTableName +
+ " WHERE val1 IS NOT NULL";
+
+ try (ResultSet rs = conn.createStatement().executeQuery(selectSql)) {
+ assertTrue(rs.next());
+ assertEquals("abc", rs.getString(1));
+ assertEquals("abcd", rs.getString(2));
+ moveRegionsOfTable(dataTableName);
+ moveRegionsOfTable(indexTableName);
+ try (Connection newConn = DriverManager.getConnection(getUrl())) {
+ newConn.createStatement().execute("upsert into " + dataTableName
+ + " (id, val1, val2, val3) values ('c1', 'cd1','cde1', 'cdef1')");
+ newConn.createStatement().execute("upsert into " + dataTableName
+ + " (id, val1, val2, val3) values ('g1', 'gh1','gh11', 'gh111')");
+ newConn.createStatement().execute("upsert into " + dataTableName
+ + " (id, val1, val2, val3) values ('l', 'lm','lmn', 'lmno')");
+ newConn.createStatement().execute("upsert into " + dataTableName
+ + " (id, val1, val2, val3) values ('m', 'mn','mno', 'mnop')");
+ newConn.commit();
+ }
+ assertRowsWithOldScanner(dataTableName, indexTableName, rs, true);
+ }
+
+ try (ResultSet rs = conn.createStatement().executeQuery(selectSql)) {
+ assertRowsWithNewScanner(dataTableName, indexTableName, rs, true);
+ }
+ }
+ }
+
+ @Test
+ public void testNoIndex() throws Exception {
+ hasTestStarted = true;
+ String dataTableName = generateUniqueName();
+ populateTable(dataTableName);
+ try (Connection conn = DriverManager.getConnection(getUrl())) {
+ populateTableWithAdditionalRows(dataTableName, conn);
+ conn.commit();
+ TABLE_NAMES.add(dataTableName);
+ String selectSql;
+
+ // Verify that an index hint is not necessary for an uncovered index
+ selectSql = "SELECT val2, val3 from " + dataTableName +
+ " WHERE val1 IS NOT NULL";
+
+ try (ResultSet rs = conn.createStatement().executeQuery(selectSql)) {
+ assertTrue(rs.next());
+ assertEquals("abc", rs.getString(1));
+ assertEquals("abcd", rs.getString(2));
+ moveRegionsOfTable(dataTableName);
+ try (Connection newConn = DriverManager.getConnection(getUrl())) {
+ newConn.createStatement().execute("upsert into " + dataTableName
+ + " (id, val1, val2, val3) values ('c1', 'cd1','cde1', 'cdef1')");
+ newConn.createStatement().execute("upsert into " + dataTableName
+ + " (id, val1, val2, val3) values ('g1', 'gh1','gh11', 'gh111')");
+ newConn.createStatement().execute("upsert into " + dataTableName
+ + " (id, val1, val2, val3) values ('l', 'lm','lmn', 'lmno')");
+ newConn.createStatement().execute("upsert into " + dataTableName
+ + " (id, val1, val2, val3) values ('m', 'mn','mno', 'mnop')");
+ newConn.commit();
+ }
+ assertRowsWithOldScanner(dataTableName, "", rs, true);
+ }
+
+ try (ResultSet rs = conn.createStatement().executeQuery(selectSql)) {
+ assertRowsWithNewScanner(dataTableName, "", rs, true);
+ }
+ }
+ }
+
+ @Test
+ public void testUncoveredIndex2() throws Exception {
+ hasTestStarted = true;
+ String dataTableName = generateUniqueName();
+ populateTable(dataTableName);
+ try (Connection conn = DriverManager.getConnection(getUrl())) {
+ String indexTableName = generateUniqueName();
+ conn.createStatement().execute("CREATE UNCOVERED INDEX "
+ + indexTableName + " on " + dataTableName + " (val1) ");
+ populateTableWithAdditionalRows(dataTableName, conn);
+ conn.commit();
+ String selectSql;
+
+ // Verify that an index hint is not necessary for an uncovered index
+ selectSql = "SELECT val2, val3 from " + dataTableName +
+ " WHERE val1 IS NOT NULL";
+
+ try (ResultSet rs = conn.createStatement().executeQuery(selectSql)) {
+ assertTrue(rs.next());
+ assertEquals("abc", rs.getString(1));
+ assertEquals("abcd", rs.getString(2));
+ try (Connection newConn = DriverManager.getConnection(getUrl())) {
+ newConn.createStatement().execute("upsert into " + dataTableName
+ + " (id, val1, val2, val3) values ('c1', 'cd1','cde1', 'cdef1')");
+ newConn.createStatement().execute("upsert into " + dataTableName
+ + " (id, val1, val2, val3) values ('g1', 'gh1','gh11', 'gh111')");
+ newConn.createStatement().execute("upsert into " + dataTableName
+ + " (id, val1, val2, val3) values ('l', 'lm','lmn', 'lmno')");
+ newConn.createStatement().execute("upsert into " + dataTableName
+ + " (id, val1, val2, val3) values ('m', 'mn','mno', 'mnop')");
+ newConn.commit();
+ }
+ assertRowsWithOldScanner(dataTableName, indexTableName, rs, false);
+ }
+
+ try (ResultSet rs = conn.createStatement().executeQuery(selectSql)) {
+ assertRowsWithNewScanner(dataTableName, indexTableName, rs, false);
+ }
+ }
+ }
+
+ @Test
+ public void testCoveredIndex2() throws Exception {
+ hasTestStarted = true;
+ String dataTableName = generateUniqueName();
+ populateTable(dataTableName);
+ try (Connection conn = DriverManager.getConnection(getUrl())) {
+ String indexTableName = generateUniqueName();
+ conn.createStatement().execute("CREATE INDEX "
+ + indexTableName + " on " + dataTableName + " (val1) INCLUDE (val2, val3)");
+ populateTableWithAdditionalRows(dataTableName, conn);
+ conn.commit();
+ String selectSql;
+
+ // Verify that an index hint is not necessary for an uncovered index
+ selectSql = "SELECT val2, val3 from " + dataTableName +
+ " WHERE val1 IS NOT NULL";
+
+ try (ResultSet rs = conn.createStatement().executeQuery(selectSql)) {
+ assertTrue(rs.next());
+ assertEquals("abc", rs.getString(1));
+ assertEquals("abcd", rs.getString(2));
+ try (Connection newConn = DriverManager.getConnection(getUrl())) {
+ newConn.createStatement().execute("upsert into " + dataTableName
+ + " (id, val1, val2, val3) values ('c1', 'cd1','cde1', 'cdef1')");
+ newConn.createStatement().execute("upsert into " + dataTableName
+ + " (id, val1, val2, val3) values ('g1', 'gh1','gh11', 'gh111')");
+ newConn.createStatement().execute("upsert into " + dataTableName
+ + " (id, val1, val2, val3) values ('l', 'lm','lmn', 'lmno')");
+ newConn.createStatement().execute("upsert into " + dataTableName
+ + " (id, val1, val2, val3) values ('m', 'mn','mno', 'mnop')");
+ newConn.commit();
+ }
+ assertRowsWithOldScanner(dataTableName, indexTableName, rs, false);
+ }
+
+ try (ResultSet rs = conn.createStatement().executeQuery(selectSql)) {
+ assertRowsWithNewScanner(dataTableName, indexTableName, rs, false);
+ }
+ }
+ }
+
+ @Test
+ public void testNoIndex2() throws Exception {
+ hasTestStarted = true;
+ String dataTableName = generateUniqueName();
+ populateTable(dataTableName);
+ try (Connection conn = DriverManager.getConnection(getUrl())) {
+ populateTableWithAdditionalRows(dataTableName, conn);
+ conn.commit();
+ TABLE_NAMES.add(dataTableName);
+ String selectSql;
+
+ // Verify that an index hint is not necessary for an uncovered index
+ selectSql = "SELECT val2, val3 from " + dataTableName +
+ " WHERE val1 IS NOT NULL";
+
+ try (ResultSet rs = conn.createStatement().executeQuery(selectSql)) {
+ assertTrue(rs.next());
+ assertEquals("abc", rs.getString(1));
+ assertEquals("abcd", rs.getString(2));
+ try (Connection newConn = DriverManager.getConnection(getUrl())) {
+ newConn.createStatement().execute("upsert into " + dataTableName
+ + " (id, val1, val2, val3) values ('c1', 'cd1','cde1', 'cdef1')");
+ newConn.createStatement().execute("upsert into " + dataTableName
+ + " (id, val1, val2, val3) values ('g1', 'gh1','gh11', 'gh111')");
+ newConn.createStatement().execute("upsert into " + dataTableName
+ + " (id, val1, val2, val3) values ('l', 'lm','lmn', 'lmno')");
+ newConn.createStatement().execute("upsert into " + dataTableName
+ + " (id, val1, val2, val3) values ('m', 'mn','mno', 'mnop')");
+ newConn.commit();
+ }
+ assertRowsWithOldScanner(dataTableName, "", rs, false);
+ }
+
+ try (ResultSet rs = conn.createStatement().executeQuery(selectSql)) {
+ assertRowsWithNewScanner(dataTableName, "", rs, false);
+ }
+ }
+ }
+
+ private static void populateTableWithAdditionalRows(String dataTableName, Connection conn)
+ throws SQLException {
+ conn.createStatement().execute("upsert into " + dataTableName
+ + " (id, val1, val2, val3) values ('c', 'cd','cde', 'cdef')");
+ conn.createStatement().execute("upsert into " + dataTableName
+ + " (id, val1, val2, val3) values ('d', 'de','de1', 'de11')");
+ conn.createStatement().execute("upsert into " + dataTableName
+ + " (id, val1, val2, val3) values ('e', 'ef','ef1', 'ef11')");
+ conn.createStatement().execute("upsert into " + dataTableName
+ + " (id, val1, val2, val3) values ('f', 'fg','fg1', 'fg11')");
+ conn.createStatement().execute("upsert into " + dataTableName
+ + " (id, val1, val2, val3) values ('g', 'gh','gh1', 'gh11')");
+ conn.createStatement().execute("upsert into " + dataTableName
+ + " (id, val1, val2, val3) values ('h', 'hi','hi1', 'hi11')");
+ conn.createStatement().execute("upsert into " + dataTableName
+ + " (id, val1, val2, val3) values ('i', 'ij','ij1', 'ij11')");
+ conn.createStatement().execute("upsert into " + dataTableName
+ + " (id, val1, val2, val3) values ('j', 'jk','jk1', 'jk11')");
+ conn.createStatement().execute("upsert into " + dataTableName
+ + " (id, val1, val2, val3) values ('k', 'kl','kl1', 'kl11')");
+ }
+
+ private static void assertRowsWithNewScanner(String dataTableName, String indexTableName,
+ ResultSet rs, boolean moveRegions)
+ throws SQLException, IOException {
+ assertTrue(rs.next());
+ assertEquals("abc", rs.getString(1));
+ assertEquals("abcd", rs.getString(2));
+ if (moveRegions) {
+ moveRegionsOfTable(dataTableName);
+ moveRegionsOfTable(indexTableName);
+ }
+ assertTrue(rs.next());
+ assertEquals("bcd", rs.getString(1));
+ assertEquals("bcde", rs.getString(2));
+ if (moveRegions) {
+ moveRegionsOfTable(dataTableName);
+ moveRegionsOfTable(indexTableName);
+ }
+ assertTrue(rs.next());
+ assertEquals("cde", rs.getString(1));
+ assertEquals("cdef", rs.getString(2));
+ assertTrue(rs.next());
+ assertEquals("cde1", rs.getString(1));
+ assertEquals("cdef1", rs.getString(2));
+ assertTrue(rs.next());
+ assertEquals("de1", rs.getString(1));
+ assertEquals("de11", rs.getString(2));
+ assertTrue(rs.next());
+ assertEquals("ef1", rs.getString(1));
+ assertEquals("ef11", rs.getString(2));
+ assertTrue(rs.next());
+ assertEquals("fg1", rs.getString(1));
+ assertEquals("fg11", rs.getString(2));
+ if (moveRegions) {
+ moveRegionsOfTable(dataTableName);
+ moveRegionsOfTable(indexTableName);
+ }
+ assertTrue(rs.next());
+ assertEquals("gh1", rs.getString(1));
+ assertEquals("gh11", rs.getString(2));
+ assertTrue(rs.next());
+ assertEquals("gh11", rs.getString(1));
+ assertEquals("gh111", rs.getString(2));
+ assertTrue(rs.next());
+ assertEquals("hi1", rs.getString(1));
+ assertEquals("hi11", rs.getString(2));
+ if (moveRegions) {
+ moveRegionsOfTable(dataTableName);
+ moveRegionsOfTable(indexTableName);
+ }
+ assertTrue(rs.next());
+ assertEquals("ij1", rs.getString(1));
+ assertEquals("ij11", rs.getString(2));
+ assertTrue(rs.next());
+ assertEquals("jk1", rs.getString(1));
+ assertEquals("jk11", rs.getString(2));
+ assertTrue(rs.next());
+ assertEquals("kl1", rs.getString(1));
+ assertEquals("kl11", rs.getString(2));
+ assertTrue(rs.next());
+ assertEquals("lmn", rs.getString(1));
+ assertEquals("lmno", rs.getString(2));
+ assertTrue(rs.next());
+ assertEquals("mno", rs.getString(1));
+ assertEquals("mnop", rs.getString(2));
+ assertFalse(rs.next());
+ }
+
+ private static void assertRowsWithOldScanner(String dataTableName, String indexTableName,
+ ResultSet rs, boolean moveRegions)
+ throws SQLException, IOException {
+ assertTrue(rs.next());
+ assertEquals("bcd", rs.getString(1));
+ assertEquals("bcde", rs.getString(2));
+ if (moveRegions) {
+ moveRegionsOfTable(dataTableName);
+ moveRegionsOfTable(indexTableName);
+ }
+ assertTrue(rs.next());
+ assertEquals("cde", rs.getString(1));
+ assertEquals("cdef", rs.getString(2));
+ assertTrue(rs.next());
+ assertEquals("de1", rs.getString(1));
+ assertEquals("de11", rs.getString(2));
+ assertTrue(rs.next());
+ assertEquals("ef1", rs.getString(1));
+ assertEquals("ef11", rs.getString(2));
+ assertTrue(rs.next());
+ assertEquals("fg1", rs.getString(1));
+ assertEquals("fg11", rs.getString(2));
+ if (moveRegions) {
+ moveRegionsOfTable(dataTableName);
+ moveRegionsOfTable(indexTableName);
+ }
+ assertTrue(rs.next());
+ assertEquals("gh1", rs.getString(1));
+ assertEquals("gh11", rs.getString(2));
+ assertTrue(rs.next());
+ assertEquals("hi1", rs.getString(1));
+ assertEquals("hi11", rs.getString(2));
+ if (moveRegions) {
+ moveRegionsOfTable(dataTableName);
+ moveRegionsOfTable(indexTableName);
+ }
+ assertTrue(rs.next());
+ assertEquals("ij1", rs.getString(1));
+ assertEquals("ij11", rs.getString(2));
+ assertTrue(rs.next());
+ assertEquals("jk1", rs.getString(1));
+ assertEquals("jk11", rs.getString(2));
+ assertTrue(rs.next());
+ assertEquals("kl1", rs.getString(1));
+ assertEquals("kl11", rs.getString(2));
+ assertFalse(rs.next());
+ }
+
+ private void populateTable(String tableName) throws Exception {
+ Connection conn = DriverManager.getConnection(getUrl());
+ conn.createStatement().execute("create table " + tableName +
+ " (id varchar(10) not null primary key, val1 varchar(10), val2 varchar(10)," +
+ " val3 varchar(10)) SPLIT ON ('d', 'h', 'k')");
+ conn.createStatement().execute("upsert into " + tableName
+ + " values ('a', 'ab', 'abc', 'abcd')");
+ conn.commit();
+ conn.createStatement().execute("upsert into " + tableName
+ + " values ('b', 'bc', 'bcd', 'bcde')");
+ conn.commit();
+ conn.close();
+ }
+}
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/ServerPagingIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/ServerPagingIT.java
index 7865890bde..db19a06ee7 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/ServerPagingIT.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/ServerPagingIT.java
@@ -223,8 +223,7 @@ public class ServerPagingIT extends ParallelStatsDisabledIT {
assertEquals("Expected string didn't match for i = " + i, STRINGS[offset + i], rs.getString(1));
i++;
}
- // no paging when serial offset
- assertServerPagingMetric(tablename, rs, false);
+ assertServerPagingMetric(tablename, rs, true);
// Testing query with offset + filter
int filterCond = 10;
@@ -239,8 +238,7 @@ public class ServerPagingIT extends ParallelStatsDisabledIT {
STRINGS[offset + filterCond + i], rs.getString(1));
i++;
}
- // no paging when serial offset
- assertServerPagingMetric(tablename, rs, false);
+ assertServerPagingMetric(tablename, rs, true);
limit = 35;
rs = conn.createStatement().executeQuery("SELECT t_id from " + tablename + " union all SELECT t_id from "
@@ -255,8 +253,7 @@ public class ServerPagingIT extends ParallelStatsDisabledIT {
assertTrue(rs.next());
assertEquals(STRINGS[i - 1], rs.getString(1));
}
- // no paging when serial offset
- assertServerPagingMetric(tablename, rs, false);
+ assertServerPagingMetric(tablename, rs, true);
limit = 1;
offset = 1;
rs = conn.createStatement()
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/ServerPagingWithRegionMovesIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/ServerPagingWithRegionMovesIT.java
new file mode 100644
index 0000000000..76aea5b681
--- /dev/null
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/ServerPagingWithRegionMovesIT.java
@@ -0,0 +1,840 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.phoenix.end2end;
+
+import org.apache.hadoop.hbase.HConstants;
+import org.apache.hadoop.hbase.ServerName;
+import org.apache.hadoop.hbase.TableName;
+import org.apache.hadoop.hbase.client.Admin;
+import org.apache.hadoop.hbase.client.RegionInfo;
+import org.apache.hadoop.hbase.util.Bytes;
+import org.apache.phoenix.iterate.ScanningResultPostDummyResultCaller;
+import org.apache.phoenix.iterate.ScanningResultPostValidResultCaller;
+import org.apache.phoenix.monitoring.MetricType;
+import org.apache.phoenix.query.QueryServices;
+import org.apache.phoenix.schema.types.PDate;
+import org.apache.phoenix.thirdparty.com.google.common.collect.Maps;
+import org.apache.phoenix.util.ByteUtil;
+import org.apache.phoenix.util.DateUtil;
+import org.apache.phoenix.util.PhoenixRuntime;
+import org.apache.phoenix.util.PropertiesUtil;
+import org.apache.phoenix.util.ReadOnlyProps;
+import org.apache.phoenix.util.TestUtil;
+import org.junit.After;
+import org.junit.Assert;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.sql.Connection;
+import java.sql.Date;
+import java.sql.DriverManager;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+
+import static org.apache.phoenix.monitoring.GlobalClientMetrics.GLOBAL_PAGED_ROWS_COUNTER;
+import static org.apache.phoenix.util.TestUtil.TEST_PROPERTIES;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+
+/**
+ * ServerPagingIT tests that include some region moves while performing rs#next.
+ */
+@Category(NeedsOwnMiniClusterTest.class)
+public class ServerPagingWithRegionMovesIT extends ParallelStatsDisabledIT {
+
+ private static final Logger LOGGER =
+ LoggerFactory.getLogger(ServerPagingWithRegionMovesIT.class);
+
+ private static boolean hasTestStarted = false;
+ private static int countOfDummyResults = 0;
+ private static int countOfValidResults = 0;
+ private static final List<String> TABLE_NAMES = Collections.synchronizedList(new ArrayList<>());
+
+ private static class TestScanningResultPostValidResultCaller extends
+ ScanningResultPostValidResultCaller {
+
+ @Override
+ public void postValidRowProcess() {
+ if (hasTestStarted && (countOfValidResults++ % 2) == 0 &&
+ (countOfValidResults < 17 ||
+ countOfValidResults > 28 && countOfValidResults < 40)) {
+ LOGGER.info("Moving regions of tables {}. current count of valid results: {}",
+ TABLE_NAMES, countOfValidResults);
+ TABLE_NAMES.forEach(table -> {
+ try {
+ moveRegionsOfTable(table);
+ } catch (Exception e) {
+ LOGGER.error("Unable to move regions of table: {}", table);
+ }
+ });
+ }
+ }
+ }
+
+ private static class TestScanningResultPostDummyResultCaller extends
+ ScanningResultPostDummyResultCaller {
+
+ @Override
+ public void postDummyProcess() {
+ if (hasTestStarted && (countOfDummyResults++ % 3) == 0 &&
+ (countOfDummyResults < 17 ||
+ countOfDummyResults > 28 && countOfDummyResults < 40)) {
+ LOGGER.info("Moving regions of tables {}. current count of dummy results: {}",
+ TABLE_NAMES, countOfDummyResults);
+ TABLE_NAMES.forEach(table -> {
+ try {
+ moveRegionsOfTable(table);
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ });
+ }
+ }
+ }
+
+ @BeforeClass
+ public static synchronized void doSetup() throws Exception {
+ Map<String, String> props = Maps.newHashMapWithExpectedSize(2);
+ props.put(QueryServices.PHOENIX_SERVER_PAGE_SIZE_MS, Long.toString(0));
+ props.put(QueryServices.COLLECT_REQUEST_LEVEL_METRICS, String.valueOf(true));
+ props.put(QueryServices.TESTS_MINI_CLUSTER_NUM_REGION_SERVERS, String.valueOf(2));
+ props.put(HConstants.HBASE_CLIENT_SCANNER_MAX_RESULT_SIZE_KEY, String.valueOf(1));
+ props.put(QueryServices.PHOENIX_POST_DUMMY_PROCESS,
+ TestScanningResultPostDummyResultCaller.class.getName());
+ props.put(QueryServices.PHOENIX_POST_VALID_PROCESS,
+ TestScanningResultPostValidResultCaller.class.getName());
+ setUpTestDriver(new ReadOnlyProps(props.entrySet().iterator()));
+ }
+
+ @After
+ public void tearDown() throws Exception {
+ TABLE_NAMES.clear();
+ hasTestStarted = false;
+ countOfDummyResults = 0;
+ countOfValidResults = 0;
+ }
+
+ private void assertServerPagingMetric(String tableName, ResultSet rs, boolean isPaged)
+ throws SQLException {
+ Map<String, Map<MetricType, Long>> metrics = PhoenixRuntime.getRequestReadMetricInfo(rs);
+ for (Map.Entry<String, Map<MetricType, Long>> entry : metrics.entrySet()) {
+ assertEquals(String.format("Got %s", entry.getKey()), tableName, entry.getKey());
+ Map<MetricType, Long> metricValues = entry.getValue();
+ Long pagedRowsCntr = metricValues.get(MetricType.PAGED_ROWS_COUNTER);
+ assertNotNull(pagedRowsCntr);
+ if (isPaged) {
+ assertTrue(String.format("Got %d", pagedRowsCntr), pagedRowsCntr > 0);
+ } else {
+ assertEquals(String.format("Got %d", pagedRowsCntr), 0, (long) pagedRowsCntr);
+ }
+ }
+ assertTrue(GLOBAL_PAGED_ROWS_COUNTER.getMetric().getValue() > 0);
+ }
+
+ @Test
+ public void testOrderByNonAggregation() throws Exception {
+ hasTestStarted = true;
+ final String tablename = generateUniqueName();
+ final String tenantId = getOrganizationId();
+
+ final Date D1 = DateUtil.parseDate("1970-01-01 00:58:00");
+ final Date D2 = DateUtil.parseDate("1970-01-01 01:02:00");
+ final Date D3 = DateUtil.parseDate("1970-01-01 01:30:00");
+ final Date D4 = DateUtil.parseDate("1970-01-01 01:45:00");
+ final Date D5 = DateUtil.parseDate("1970-01-01 02:00:00");
+ final Date D6 = DateUtil.parseDate("1970-01-01 04:00:00");
+ final String F1 = "A";
+ final String F2 = "B";
+ final String F3 = "C";
+ final String R1 = "R1";
+ final String R2 = "R2";
+ byte[][] splits = new byte[][] {
+ ByteUtil.concat(Bytes.toBytes(tenantId), PDate.INSTANCE.toBytes(D3)),
+ ByteUtil.concat(Bytes.toBytes(tenantId), PDate.INSTANCE.toBytes(D5)),
+ };
+ Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
+
+ try (Connection conn = DriverManager.getConnection(getUrl(), props)) {
+ String ddl = "create table " + tablename +
+ " (organization_id char(15) not null," +
+ " date date not null," +
+ " feature char(1) not null," +
+ " unique_users integer not null,\n" +
+ " transactions bigint,\n" +
+ " region varchar,\n" +
+ " CONSTRAINT pk PRIMARY KEY (organization_id, \"DATE\", feature, unique_users))";
+ TABLE_NAMES.add(tablename);
+ StringBuilder buf = new StringBuilder(ddl);
+ if (splits != null) {
+ buf.append(" SPLIT ON (");
+ for (int i = 0; i < splits.length; i++) {
+ buf.append("'").append(Bytes.toString(splits[i])).append("'").append(",");
+ }
+ buf.setCharAt(buf.length()-1, ')');
+ }
+ ddl = buf.toString();
+ conn.createStatement().execute(ddl);
+
+ PreparedStatement stmt = conn.prepareStatement(
+ "upsert into " + tablename +
+ " (" +
+ " ORGANIZATION_ID, " +
+ " \"DATE\", " +
+ " FEATURE, " +
+ " UNIQUE_USERS, " +
+ " TRANSACTIONS, " +
+ " REGION) " +
+ "VALUES (?, ?, ?, ?, ?, ?)");
+ stmt.setString(1, tenantId);
+ stmt.setDate(2, D1);
+ stmt.setString(3, F1);
+ stmt.setInt(4, 10);
+ stmt.setLong(5, 100L);
+ stmt.setString(6, R2);
+ stmt.execute();
+
+ stmt.setString(1, tenantId);
+ stmt.setDate(2, D2);
+ stmt.setString(3, F1);
+ stmt.setInt(4, 20);
+ stmt.setLong(5, 200);
+ stmt.setString(6, null);
+ stmt.execute();
+
+ stmt.setString(1, tenantId);
+ stmt.setDate(2, D3);
+ stmt.setString(3, F1);
+ stmt.setInt(4, 30);
+ stmt.setLong(5, 300);
+ stmt.setString(6, R1);
+ stmt.execute();
+
+ stmt.setString(1, tenantId);
+ stmt.setDate(2, D4);
+ stmt.setString(3, F2);
+ stmt.setInt(4, 40);
+ stmt.setLong(5, 400);
+ stmt.setString(6, R1);
+ stmt.execute();
+
+ stmt.setString(1, tenantId);
+ stmt.setDate(2, D5);
+ stmt.setString(3, F3);
+ stmt.setInt(4, 50);
+ stmt.setLong(5, 500);
+ stmt.setString(6, R2);
+ stmt.execute();
+
+ stmt.setString(1, tenantId);
+ stmt.setDate(2, D6);
+ stmt.setString(3, F1);
+ stmt.setInt(4, 60);
+ stmt.setLong(5, 600);
+ stmt.setString(6, null);
+ stmt.execute();
+ conn.commit();
+ }
+
+ String query = "SELECT \"DATE\", transactions t FROM "+tablename+
+ " WHERE organization_id=? AND unique_users <= 30 ORDER BY t DESC LIMIT 2";
+ try (Connection conn = DriverManager.getConnection(getUrl(), props);
+ PreparedStatement statement = conn.prepareStatement(query)) {
+ TestUtil.dumpTable(conn, TableName.valueOf(tablename));
+ statement.setString(1, tenantId);
+ try (ResultSet rs = statement.executeQuery()) {
+ moveRegionsOfTable(tablename);
+ assertTrue(rs.next());
+ assertEquals(D3.getTime(), rs.getDate(1).getTime());
+ moveRegionsOfTable(tablename);
+ assertTrue(rs.next());
+ moveRegionsOfTable(tablename);
+ assertEquals(D2.getTime(), rs.getDate(1).getTime());
+ assertFalse(rs.next());
+ assertServerPagingMetric(tablename, rs, true);
+ }
+ }
+ }
+
+ private static void moveRegionsOfTable(String tableName)
+ throws IOException {
+ Admin admin = getUtility().getAdmin();
+ List<ServerName> servers =
+ new ArrayList<>(admin.getRegionServers());
+ ServerName server1 = servers.get(0);
+ ServerName server2 = servers.get(1);
+ List<RegionInfo> regionsOnServer1;
+ try {
+ regionsOnServer1 = admin.getRegions(server1);
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ List<RegionInfo> regionsOnServer2;
+ try {
+ regionsOnServer2 = admin.getRegions(server2);
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ regionsOnServer1.forEach(regionInfo -> {
+ if (regionInfo.getTable().equals(TableName.valueOf(tableName))) {
+ try {
+ admin.move(regionInfo.getEncodedNameAsBytes(), server2);
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ }
+ });
+ regionsOnServer2.forEach(regionInfo -> {
+ if (regionInfo.getTable().equals(TableName.valueOf(tableName))) {
+ try {
+ admin.move(regionInfo.getEncodedNameAsBytes(), server1);
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ }
+ });
+ }
+
+ private static void moveAllRegions() throws IOException {
+ Admin admin = getUtility().getAdmin();
+ List<ServerName> servers =
+ new ArrayList<>(admin.getRegionServers());
+ ServerName server1 = servers.get(0);
+ ServerName server2 = servers.get(1);
+ List<RegionInfo> regionsOnServer1;
+ try {
+ regionsOnServer1 = admin.getRegions(server1);
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ List<RegionInfo> regionsOnServer2;
+ try {
+ regionsOnServer2 = admin.getRegions(server2);
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ regionsOnServer1.forEach(regionInfo -> {
+ try {
+ admin.move(regionInfo.getEncodedNameAsBytes(), server2);
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ });
+ regionsOnServer2.forEach(regionInfo -> {
+ try {
+ admin.move(regionInfo.getEncodedNameAsBytes(), server1);
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ });
+ }
+
+ @Test
+ public void testLimitOffsetWithSplit() throws Exception {
+ hasTestStarted = true;
+ final String tablename = generateUniqueName();
+ final String[] STRINGS = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l",
+ "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" };
+ String ddl = "CREATE TABLE " + tablename + " (t_id VARCHAR NOT NULL,\n"
+ + "k1 INTEGER NOT NULL,\n" + "k2 INTEGER NOT NULL,\n" + "C3.k3 INTEGER,\n"
+ + "C2.v1 VARCHAR,\n" + "CONSTRAINT pk PRIMARY KEY (t_id, k1, k2)) "
+ + "SPLIT ON ('e','i','o')";
+ TABLE_NAMES.add(tablename);
+ Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
+ try (Connection conn = DriverManager.getConnection(getUrl(), props)) {
+ createTestTable(getUrl(), ddl);
+ for (int i = 0; i < 26; i++) {
+ conn.createStatement().execute("UPSERT INTO " + tablename + " values('"
+ + STRINGS[i] + "'," + i + ","
+ + (i + 1) + "," + (i + 2) + ",'" + STRINGS[25 - i] + "')");
+ }
+ conn.commit();
+ int limit = 10;
+ // Testing 0 as remaining offset after 4 rows in first region, 4 rows in second region
+ int offset = 8;
+ ResultSet rs;
+ rs = conn.createStatement()
+ .executeQuery("SELECT t_id from " + tablename + " order by t_id limit "
+ + limit + " offset " + offset);
+ int i = 0;
+ while (i < limit) {
+ if (i % 3 == 0) {
+ moveRegionsOfTable(tablename);
+ }
+ assertTrue(rs.next());
+ assertEquals("Expected string didn't match for i = " + i, STRINGS[offset + i],
+ rs.getString(1));
+ i++;
+ }
+ assertServerPagingMetric(tablename, rs, true);
+
+ // Testing query with offset + filter
+ int filterCond = 10;
+ rs = conn.createStatement().executeQuery(
+ "SELECT t_id from " + tablename + " where k2 > " + filterCond +
+ " order by t_id limit " + limit + " offset " + offset);
+ i = 0;
+ limit = 5;
+ while (i < limit) {
+ if (i % 4 == 0) {
+ moveRegionsOfTable(tablename);
+ }
+ assertTrue(rs.next());
+ assertEquals("Expected string didn't match for i = " + i,
+ STRINGS[offset + filterCond + i], rs.getString(1));
+ i++;
+ }
+ assertServerPagingMetric(tablename, rs, true);
+
+ limit = 35;
+ rs = conn.createStatement().executeQuery("SELECT t_id from " + tablename
+ + " union all SELECT t_id from "
+ + tablename + " offset " + offset + " FETCH FIRST " + limit + " rows only");
+ i = 0;
+ while (i++ < STRINGS.length - offset) {
+ if (i % 3 == 0) {
+ moveRegionsOfTable(tablename);
+ }
+ assertTrue(rs.next());
+ assertEquals(STRINGS[offset + i - 1], rs.getString(1));
+ }
+ i = 0;
+ while (i++ < limit - STRINGS.length - offset) {
+ if (i % 3 == 0) {
+ moveRegionsOfTable(tablename);
+ }
+ assertTrue(rs.next());
+ assertEquals(STRINGS[i - 1], rs.getString(1));
+ }
+ // no paging when serial offset
+ assertServerPagingMetric(tablename, rs, true);
+ limit = 1;
+ offset = 1;
+ rs = conn.createStatement()
+ .executeQuery("SELECT k2 from " + tablename + " order by k2 desc limit "
+ + limit + " offset " + offset);
+ moveRegionsOfTable(tablename);
+ assertTrue(rs.next());
+ assertEquals(25, rs.getInt(1));
+ assertFalse(rs.next());
+ assertServerPagingMetric(tablename, rs, true);
+ }
+ }
+
+ @Test
+ public void testLimitOffsetWithoutSplit() throws Exception {
+ hasTestStarted = true;
+ final String tablename = generateUniqueName();
+ final String[] STRINGS = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l",
+ "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" };
+ String ddl = "CREATE TABLE " + tablename + " (t_id VARCHAR NOT NULL,\n"
+ + "k1 INTEGER NOT NULL,\n" + "k2 INTEGER NOT NULL,\n" + "C3.k3 INTEGER,\n"
+ + "C2.v1 VARCHAR,\n" + "CONSTRAINT pk PRIMARY KEY (t_id, k1, k2))";
+ TABLE_NAMES.add(tablename);
+ Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
+ try (Connection conn = DriverManager.getConnection(getUrl(), props)) {
+ createTestTable(getUrl(), ddl);
+ for (int i = 0; i < 26; i++) {
+ conn.createStatement().execute("UPSERT INTO " + tablename + " values('"
+ + STRINGS[i] + "'," + i + ","
+ + (i + 1) + "," + (i + 2) + ",'" + STRINGS[25 - i] + "')");
+ }
+ conn.commit();
+ int limit = 10;
+ // Testing 0 as remaining offset after 4 rows in first region, 4 rows in second region
+ int offset = 8;
+ ResultSet rs;
+ rs = conn.createStatement()
+ .executeQuery("SELECT t_id from " + tablename + " order by t_id limit "
+ + limit + " offset " + offset);
+ int i = 0;
+ while (i < limit) {
+ if (i % 3 == 0) {
+ moveRegionsOfTable(tablename);
+ }
+ assertTrue(rs.next());
+ assertEquals("Expected string didn't match for i = " + i, STRINGS[offset + i],
+ rs.getString(1));
+ i++;
+ }
+ assertServerPagingMetric(tablename, rs, false);
+
+ // Testing query with offset + filter
+ int filterCond = 10;
+ rs = conn.createStatement().executeQuery(
+ "SELECT t_id from " + tablename + " where k2 > " + filterCond +
+ " order by t_id limit " + limit + " offset " + offset);
+ i = 0;
+ limit = 5;
+ while (i < limit) {
+ if (i % 4 == 0) {
+ moveRegionsOfTable(tablename);
+ }
+ assertTrue(rs.next());
+ assertEquals("Expected string didn't match for i = " + i,
+ STRINGS[offset + filterCond + i], rs.getString(1));
+ i++;
+ }
+ assertServerPagingMetric(tablename, rs, false);
+
+ limit = 35;
+ rs = conn.createStatement().executeQuery("SELECT t_id from " + tablename
+ + " union all SELECT t_id from "
+ + tablename + " offset " + offset + " FETCH FIRST " + limit + " rows only");
+ i = 0;
+ while (i++ < STRINGS.length - offset) {
+ if (i % 3 == 0) {
+ moveRegionsOfTable(tablename);
+ }
+ assertTrue(rs.next());
+ assertEquals(STRINGS[offset + i - 1], rs.getString(1));
+ }
+ i = 0;
+ while (i++ < limit - STRINGS.length - offset) {
+ if (i % 3 == 0) {
+ moveRegionsOfTable(tablename);
+ }
+ assertTrue(rs.next());
+ assertEquals(STRINGS[i - 1], rs.getString(1));
+ }
+ assertServerPagingMetric(tablename, rs, false);
+ limit = 1;
+ offset = 1;
+ rs = conn.createStatement()
+ .executeQuery("SELECT k2 from " + tablename + " order by k2 desc limit "
+ + limit + " offset " + offset);
+ moveRegionsOfTable(tablename);
+ assertTrue(rs.next());
+ assertEquals(25, rs.getInt(1));
+ assertFalse(rs.next());
+ assertServerPagingMetric(tablename, rs, true);
+ }
+ }
+
+ @Test
+ public void testLimitOffsetWithSplit2() throws Exception {
+ hasTestStarted = true;
+ final String tablename = generateUniqueName();
+ final String[] STRINGS = {"a_xyz", "b_xyz", "c_xyz", "d_xyz", "e_xyz", "f_xyz", "g_xyz",
+ "h_xyz", "i_xyz", "j_xyz", "k_xyz", "l_xyz",
+ "m_xyz", "n_xyz", "o_xyz", "p_xyz", "q_xyz", "r_xyz", "s_xyz", "t_xyz", "u_xyz",
+ "v_xyz", "w_xyz", "x_xyz", "y_xyz", "z_xyz"};
+ String ddl = "CREATE TABLE " + tablename + " (t_id VARCHAR,\n"
+ + "k1 INTEGER,\n" + "k2 INTEGER,\n" + "C3.k3 INTEGER,\n"
+ + "C2.v1 VARCHAR,\n" + "CONSTRAINT pk PRIMARY KEY (t_id)) "
+ + "SPLIT ON ('e123','i123','o123')";
+ TABLE_NAMES.add(tablename);
+ Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
+ try (Connection conn = DriverManager.getConnection(getUrl(), props)) {
+ createTestTable(getUrl(), ddl);
+ for (int i = 0; i < 26; i++) {
+ conn.createStatement().execute("UPSERT INTO " + tablename + " values('"
+ + STRINGS[i] + "'," + (i + 1) * 2 + ","
+ + (i + 1) * 3 + "," + (i + 2) * 2 + ",'" + STRINGS[25 - i] + "')");
+ }
+ conn.commit();
+ int limit = 10;
+ // Testing 0 as remaining offset after 4 rows in first region, 4 rows in second region
+ int offset = 8;
+ ResultSet rs;
+ rs = conn.createStatement()
+ .executeQuery("SELECT t_id from " + tablename + " order by t_id limit "
+ + limit + " offset " + offset);
+ int i = 0;
+ while (i < limit) {
+ if (i % 3 == 0) {
+ moveRegionsOfTable(tablename);
+ }
+ assertTrue(rs.next());
+ assertEquals("Expected string didn't match for i = " + i, STRINGS[offset + i],
+ rs.getString(1));
+ i++;
+ }
+ assertServerPagingMetric(tablename, rs, true);
+
+ // Testing query with offset + filter
+ int filterCond = 30;
+ rs = conn.createStatement().executeQuery(
+ "SELECT t_id from " + tablename + " where k2 > " + filterCond +
+ " order by t_id limit " + limit + " offset " + offset);
+ i = 0;
+ limit = 5;
+ while (i < limit) {
+ if (i % 4 == 0) {
+ moveRegionsOfTable(tablename);
+ }
+ assertTrue(rs.next());
+ assertEquals("Expected string didn't match for i = " + i,
+ STRINGS[offset + 10 + i], rs.getString(1));
+ i++;
+ }
+ assertServerPagingMetric(tablename, rs, true);
+
+ limit = 35;
+ rs = conn.createStatement().executeQuery("SELECT t_id from " + tablename
+ + " union all SELECT t_id from "
+ + tablename + " offset " + offset + " FETCH FIRST " + limit + " rows only");
+ i = 0;
+ while (i++ < STRINGS.length - offset) {
+ if (i % 3 == 0) {
+ moveRegionsOfTable(tablename);
+ }
+ assertTrue(rs.next());
+ assertEquals(STRINGS[offset + i - 1], rs.getString(1));
+ }
+ i = 0;
+ while (i++ < limit - STRINGS.length - offset) {
+ if (i % 3 == 0) {
+ moveRegionsOfTable(tablename);
+ }
+ assertTrue(rs.next());
+ assertEquals(STRINGS[i - 1], rs.getString(1));
+ }
+ // no paging when serial offset
+ assertServerPagingMetric(tablename, rs, true);
+ limit = 1;
+ offset = 1;
+ rs = conn.createStatement()
+ .executeQuery("SELECT k2 from " + tablename + " order by k2 desc limit "
+ + limit + " offset " + offset);
+ moveRegionsOfTable(tablename);
+ assertTrue(rs.next());
+ assertEquals(75, rs.getInt(1));
+ assertFalse(rs.next());
+ assertServerPagingMetric(tablename, rs, true);
+ }
+ }
+
+ @Test
+ public void testLimitOffsetWithoutSplit2() throws Exception {
+ hasTestStarted = true;
+ final String tablename = generateUniqueName();
+ final String[] STRINGS = {"a_xyz", "b_xyz", "c_xyz", "d_xyz", "e_xyz", "f_xyz", "g_xyz",
+ "h_xyz", "i_xyz", "j_xyz", "k_xyz", "l_xyz",
+ "m_xyz", "n_xyz", "o_xyz", "p_xyz", "q_xyz", "r_xyz", "s_xyz", "t_xyz", "u_xyz",
+ "v_xyz", "w_xyz", "x_xyz", "y_xyz", "z_xyz"};
+ String ddl = "CREATE TABLE " + tablename + " (t_id VARCHAR,\n"
+ + "k1 INTEGER,\n" + "k2 INTEGER,\n" + "C3.k3 INTEGER,\n"
+ + "C2.v1 VARCHAR,\n" + "CONSTRAINT pk PRIMARY KEY (t_id))";
+ TABLE_NAMES.add(tablename);
+ Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
+ try (Connection conn = DriverManager.getConnection(getUrl(), props)) {
+ createTestTable(getUrl(), ddl);
+ for (int i = 0; i < 26; i++) {
+ conn.createStatement().execute("UPSERT INTO " + tablename + " values('"
+ + STRINGS[i] + "'," + (i + 1) * 2 + ","
+ + (i + 1) * 3 + "," + (i + 2) * 2 + ",'" + STRINGS[25 - i] + "')");
+ }
+ conn.commit();
+ int limit = 10;
+ // Testing 0 as remaining offset after 4 rows in first region, 4 rows in second region
+ int offset = 8;
+ ResultSet rs;
+ rs = conn.createStatement()
+ .executeQuery("SELECT t_id from " + tablename + " order by t_id limit "
+ + limit + " offset " + offset);
+ int i = 0;
+ while (i < limit) {
+ if (i % 3 == 0) {
+ moveRegionsOfTable(tablename);
+ }
+ assertTrue(rs.next());
+ assertEquals("Expected string didn't match for i = " + i, STRINGS[offset + i],
+ rs.getString(1));
+ i++;
+ }
+ assertServerPagingMetric(tablename, rs, false);
+
+ // Testing query with offset + filter
+ int filterCond = 30;
+ rs = conn.createStatement().executeQuery(
+ "SELECT t_id from " + tablename + " where k2 > " + filterCond +
+ " order by t_id limit " + limit + " offset " + offset);
+ i = 0;
+ limit = 5;
+ while (i < limit) {
+ if (i % 4 == 0) {
+ moveRegionsOfTable(tablename);
+ }
+ assertTrue(rs.next());
+ assertEquals("Expected string didn't match for i = " + i,
+ STRINGS[offset + 10 + i], rs.getString(1));
+ i++;
+ }
+ assertServerPagingMetric(tablename, rs, false);
+
+ limit = 35;
+ rs = conn.createStatement().executeQuery("SELECT t_id from " + tablename
+ + " union all SELECT t_id from "
+ + tablename + " offset " + offset + " FETCH FIRST " + limit + " rows only");
+ i = 0;
+ while (i++ < STRINGS.length - offset) {
+ if (i % 3 == 0) {
+ moveRegionsOfTable(tablename);
+ }
+ assertTrue(rs.next());
+ assertEquals(STRINGS[offset + i - 1], rs.getString(1));
+ }
+ i = 0;
+ while (i++ < limit - STRINGS.length - offset) {
+ if (i % 3 == 0) {
+ moveRegionsOfTable(tablename);
+ }
+ assertTrue(rs.next());
+ assertEquals(STRINGS[i - 1], rs.getString(1));
+ }
+ // no paging when serial offset
+ assertServerPagingMetric(tablename, rs, false);
+ limit = 1;
+ offset = 1;
+ rs = conn.createStatement()
+ .executeQuery("SELECT k2 from " + tablename + " order by k2 desc limit "
+ + limit + " offset " + offset);
+ moveRegionsOfTable(tablename);
+ assertTrue(rs.next());
+ assertEquals(75, rs.getInt(1));
+ assertFalse(rs.next());
+ assertServerPagingMetric(tablename, rs, true);
+ }
+ }
+
+ @Test
+ public void testGroupBy() throws Exception {
+ hasTestStarted = true;
+ final String tablename = generateUniqueName();
+ TABLE_NAMES.add(tablename);
+ String ddl = "CREATE TABLE " + tablename + " (t_id VARCHAR NOT NULL,\n"
+ + "k1 INTEGER NOT NULL,\n"
+ + "k2 INTEGER CONSTRAINT pk PRIMARY KEY (t_id, k1)) ";
+ Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
+ try (Connection conn = DriverManager.getConnection(getUrl(), props)) {
+ createTestTable(getUrl(), ddl);
+ for (int i = 0; i < 8; i++) {
+ conn.createStatement().execute("UPSERT INTO " + tablename
+ + " values('tenant1'," + i + ","
+ + (i + 1) + ")");
+ }
+ conn.createStatement()
+ .execute("UPSERT INTO " + tablename + " values('tenant1', 10, 2)");
+ conn.createStatement()
+ .execute("UPSERT INTO " + tablename + " values('tenant1', 11, 2)");
+ conn.createStatement()
+ .execute("UPSERT INTO " + tablename + " values('tenant1', 12, 3)");
+ conn.createStatement()
+ .execute("UPSERT INTO " + tablename + " values('tenant1', 13, 3)");
+ conn.createStatement()
+ .execute("UPSERT INTO " + tablename + " values('tenant1', 14, 4)");
+ conn.createStatement()
+ .execute("UPSERT INTO " + tablename + " values('tenant1', 15, 4)");
+ conn.createStatement()
+ .execute("UPSERT INTO " + tablename + " values('tenant1', 16, 4)");
+ conn.createStatement()
+ .execute("UPSERT INTO " + tablename + " values('tenant1', 17, 5)");
+ conn.createStatement()
+ .execute("UPSERT INTO " + tablename + " values('tenant1', 18, 5)");
+ conn.commit();
+ TestUtil.dumpTable(conn, TableName.valueOf(tablename));
+ ResultSet rs =
+ conn.createStatement().executeQuery("SELECT k2, count(*) FROM " + tablename
+ + " where t_id = 'tenant1' group by k2");
+ moveRegionsOfTable(tablename);
+ Assert.assertTrue(rs.next());
+ Assert.assertEquals(1, rs.getInt(1));
+ Assert.assertEquals(1, rs.getInt(2));
+ Assert.assertTrue(rs.next());
+ Assert.assertEquals(2, rs.getInt(1));
+ Assert.assertEquals(3, rs.getInt(2));
+ Assert.assertTrue(rs.next());
+ Assert.assertEquals(3, rs.getInt(1));
+ Assert.assertEquals(3, rs.getInt(2));
+ Assert.assertTrue(rs.next());
+ Assert.assertEquals(4, rs.getInt(1));
+ Assert.assertEquals(4, rs.getInt(2));
+ Assert.assertTrue(rs.next());
+ Assert.assertEquals(5, rs.getInt(1));
+ Assert.assertEquals(3, rs.getInt(2));
+ Assert.assertTrue(rs.next());
+ Assert.assertEquals(6, rs.getInt(1));
+ Assert.assertEquals(1, rs.getInt(2));
+ Assert.assertTrue(rs.next());
+ Assert.assertEquals(7, rs.getInt(1));
+ Assert.assertEquals(1, rs.getInt(2));
+ Assert.assertTrue(rs.next());
+ Assert.assertEquals(8, rs.getInt(1));
+ Assert.assertEquals(1, rs.getInt(2));
+ Assert.assertFalse(rs.next());
+ assertServerPagingMetric(tablename, rs, true);
+ }
+ }
+
+ @Test
+ public void testGroupByWithIndex() throws Exception {
+ hasTestStarted = true;
+ final String tablename = generateUniqueName();
+ final String indexName = generateUniqueName();
+ TABLE_NAMES.add(tablename);
+ TABLE_NAMES.add(indexName);
+
+ String ddl = "CREATE TABLE " + tablename + " (t_id VARCHAR NOT NULL,\n"
+ + "k1 INTEGER NOT NULL,\n"
+ + "k2 INTEGER CONSTRAINT pk PRIMARY KEY (t_id, k1)) ";
+ String indexDDl = "CREATE INDEX IF NOT EXISTS " + indexName + " ON "
+ + tablename + "(k2)";
+
+ Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
+ try (Connection conn = DriverManager.getConnection(getUrl(), props)) {
+ createTestTable(getUrl(), ddl);
+ createTestTable(getUrl(), indexDDl);
+ for (int i = 0; i < 8; i++) {
+ conn.createStatement().execute("UPSERT INTO " + tablename
+ + " values('tenant1'," + i + ","
+ + (i + 1) + ")");
+ }
+ conn.commit();
+ ResultSet rs = conn.createStatement().executeQuery("SELECT count(*) FROM " + tablename
+ + " where t_id = 'tenant1' AND (k2 IN (5,6) or k2 is null) group by k2=6");
+ boolean moveRegions = true;
+ moveRegionsOfTable(tablename);
+ moveRegionsOfTable(indexName);
+ while (rs.next()) {
+ if (moveRegions) {
+ moveRegionsOfTable(tablename);
+ moveRegionsOfTable(indexName);
+ moveRegions = false;
+ } else {
+ moveRegions = true;
+ }
+ Assert.assertEquals(1, rs.getInt(1));
+ }
+ Assert.assertFalse(rs.next());
+ assertServerPagingMetric(indexName, rs, true);
+ }
+ }
+
+}
diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/SortOrderIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/SortOrderIT.java
index 86a0666d31..e52dbb4e23 100644
--- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/SortOrderIT.java
+++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/SortOrderIT.java
@@ -34,8 +34,10 @@ import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.GregorianCalendar;
+import java.util.HashSet;
import java.util.List;
import java.util.Properties;
+import java.util.Set;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.phoenix.schema.SortOrder;
@@ -44,6 +46,7 @@ import org.apache.phoenix.schema.types.PDecimal;
import org.apache.phoenix.schema.types.PDouble;
import org.apache.phoenix.schema.types.PFloat;
import org.apache.phoenix.util.PropertiesUtil;
+import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
@@ -57,16 +60,23 @@ import org.apache.phoenix.thirdparty.com.google.common.collect.Lists;
@Category(ParallelStatsDisabledTest.class)
public class SortOrderIT extends ParallelStatsDisabledIT {
- private String baseTableName;
-
+ protected String baseTableName;
+ protected static final Set<String> TABLE_NAMES = new HashSet<>();
+
@Before
public void generateTableName() {
baseTableName = generateUniqueName();
}
-
+
+ @After
+ public void tearDown() throws Exception {
+ TABLE_NAMES.clear();
+ }
+
@Test
public void noOrder() throws Exception {
String table = generateUniqueName();
+ TABLE_NAMES.add(table);
String ddl = "CREATE table " + table + " (pk VARCHAR NOT NULL PRIMARY KEY)";
runQueryTest(ddl, "pk", new Object[][]{{"a"}, {"b"}, {"c"}}, new Object[][]{{"a"}, {"b"}, {"c"}},
table);
@@ -75,6 +85,7 @@ public class SortOrderIT extends ParallelStatsDisabledIT {
@Test
public void noOrderCompositePK() throws Exception {
String table = generateUniqueName();
+ TABLE_NAMES.add(table);
String ddl = "CREATE table " + table + " (oid CHAR(2) NOT NULL, code INTEGER NOT NULL constraint pk primary key (oid, code))";
Object[][] rows = new Object[][]{{"o1", 1}, {"o2", 2}, {"o3", 3}};
runQueryTest(ddl, upsert("oid", "code"), rows, rows, table);
@@ -83,6 +94,7 @@ public class SortOrderIT extends ParallelStatsDisabledIT {
@Test
public void ascOrderInlinePK() throws Exception {
String table = generateUniqueName();
+ TABLE_NAMES.add(table);
String ddl = "CREATE table " + table + " (pk VARCHAR NOT NULL PRIMARY KEY ASC)";
runQueryTest(ddl, "pk", new Object[][]{{"a"}, {"b"}, {"c"}}, new Object[][]{{"a"}, {"b"}, {"c"}},
table);
@@ -91,6 +103,7 @@ public class SortOrderIT extends ParallelStatsDisabledIT {
@Test
public void ascOrderCompositePK() throws Exception {
String table = generateUniqueName();
+ TABLE_NAMES.add(table);
String ddl = "CREATE table " + table + " (oid CHAR(2) NOT NULL, code INTEGER NOT NULL constraint pk primary key (oid ASC, code DESC))";
Object[][] insertedRows = new Object[][]{{"o1", 1}, {"o1", 2}, {"o1", 3}};
Object[][] expectedRows = new Object[][]{{"o1", 3}, {"o1", 2}, {"o1", 1}};
@@ -100,6 +113,7 @@ public class SortOrderIT extends ParallelStatsDisabledIT {
@Test
public void descOrderInlinePK() throws Exception {
String table = generateUniqueName();
+ TABLE_NAMES.add(table);
for (String type : new String[]{"CHAR(2)", "VARCHAR"}) {
String ddl = "CREATE table " + table + " (pk ${type} NOT NULL PRIMARY KEY DESC)".replace("${type}", type);
runQueryTest(ddl, "pk", new Object[][]{{"aa"}, {"bb"}, {"cc"}}, new Object[][]{{"cc"}, {"bb"}, {"aa"}},
@@ -110,6 +124,7 @@ public class SortOrderIT extends ParallelStatsDisabledIT {
@Test
public void descOrderCompositePK1() throws Exception {
String table = generateUniqueName();
+ TABLE_NAMES.add(table);
String ddl = "CREATE table " + table + " (oid CHAR(2) NOT NULL, code INTEGER NOT NULL constraint pk primary key (oid DESC, code))";
Object[][] insertedRows = new Object[][]{{"o1", 1}, {"o2", 2}, {"o3", 3}};
Object[][] expectedRows = new Object[][]{{"o3", 3}, {"o2", 2}, {"o1", 1}};
@@ -119,6 +134,7 @@ public class SortOrderIT extends ParallelStatsDisabledIT {
@Test
public void descOrderCompositePK2() throws Exception {
String table = generateUniqueName();
... 8797 lines suppressed ...