You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@drill.apache.org by ar...@apache.org on 2018/05/18 18:43:16 UTC
[drill] branch master updated (89e0fe6 -> f4f4dc5)
This is an automated email from the ASF dual-hosted git repository.
arina pushed a change to branch master
in repository https://gitbox.apache.org/repos/asf/drill.git.
from 89e0fe6 DRILL-6027: - Added fallback option for HashJoin. - No copy of incoming for single partition, and avoid HT resize. - Fix memory leak when cancelling while spill file is read - get correct schema when probe side is empty - Re-create the HashJoinProbe
new 5a3a73a DRILL-6420: Add Lateral and Unnest Keyword for highlighting on WebUI
new 5dd8a6f DRILL-6255: Drillbit while sending control message to itself creates a connection instead of submitting locally
new bdbd93f DRILL-6421: Refactor DecimalUtility and CoreDecimalUtility classes
new 55f2599 DRILL-6426: Refactor TestFunctionsWithTypeExpoQueries test to be independent on limit 0 optimization option
new 5d22d70 DRILL-6413: Update ParquetFilterBuilder.visitBooleanOperator to handle simplified boolean expression
new 1cd6ee8 DRILL-6424: Updating FasterXML Jackson libraries
new 1a28fd8 DRILL-4525: Allow SqlBetweenOperator to accept LOWER_OPERAND and UPPER_OPERAND with different types
new f4f4dc5 DRILL-4525: Code cleanup
The 8 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails. The revisions
listed as "add" were already present in the repository and have only
been added to this reference.
Summary of changes:
.../java/org/apache/drill/common/types/Types.java | 106 ++--
.../drill/common/util/CoreDecimalUtility.java | 55 --
.../drill/exec/store/hive/HiveUtilities.java | 8 +-
contrib/storage-hive/hive-exec-shade/pom.xml | 19 -
.../templates/Decimal/CastVarDecimalDecimal.java | 6 +-
.../exec/expr/ExpressionTreeMaterializer.java | 43 +-
.../drill/exec/physical/impl/join/JoinUtils.java | 6 +-
.../sql/DrillCalciteSqlBetweenOperatorWrapper.java | 76 +++
.../drill/exec/planner/sql/DrillOperatorTable.java | 53 +-
.../drill/exec/planner/sql/TypeInferenceUtils.java | 4 +-
.../org/apache/drill/exec/rpc/BitRpcUtility.java | 18 +
.../rpc/control/ConnectionManagerRegistry.java | 6 +-
.../exec/rpc/control/ControlConnectionConfig.java | 9 +-
.../exec/rpc/control/ControlConnectionManager.java | 16 +-
.../drill/exec/rpc/control/ControlTunnel.java | 162 +++--
.../rpc/control/LocalControlConnectionManager.java | 236 ++++++++
...er.java => RemoteControlConnectionManager.java} | 26 +-
.../org/apache/drill/exec/rpc/data/DataTunnel.java | 25 +-
.../exec/store/easy/json/JsonRecordWriter.java | 4 +-
.../store/parquet/AbstractParquetGroupScan.java | 3 +-
.../exec/store/parquet/ParquetFilterBuilder.java | 19 +-
.../exec/store/parquet/ParquetRecordWriter.java | 3 +-
.../columnreaders/ParquetToDrillTypeConverter.java | 4 +-
.../exec/store/parquet/metadata/Metadata.java | 10 +-
.../exec/work/batch/ControlMessageHandler.java | 51 +-
.../drill/exec/work/foreman/FragmentsRunner.java | 105 +---
.../exec/work/fragment/FragmentStatusReporter.java | 15 +-
.../rest/static/js/ace-code-editor/mode-sql.js | 4 +-
.../drill/TestFunctionsWithTypeExpoQueries.java | 103 +++-
.../rpc/control/ConnectionManagerRegistryTest.java | 149 +++++
.../control/TestLocalControlConnectionManager.java | 278 +++++++++
.../rpc/user/security/TestUserBitKerberos.java | 36 +-
.../store/parquet/TestParquetFilterPushDown.java | 22 +-
.../work/fragment/FragmentStatusReporterTest.java | 73 +--
.../apache/drill/exec/rpc/FutureBitCommand.java | 20 +-
.../apache/drill/exec/rpc/ListeningCommand.java | 33 +-
.../drill/exec/rpc/ReconnectingConnection.java | 16 +-
.../java/org/apache/drill/exec/rpc/RpcCommand.java | 13 +-
.../main/codegen/templates/ColumnAccessors.java | 14 +-
.../main/codegen/templates/FixedValueVectors.java | 2 +-
.../org/apache/drill/exec/util/DecimalUtility.java | 672 ++++-----------------
.../drill/exec/vector/ValueHolderHelper.java | 8 +-
.../drill/common/expression/ValueExpressions.java | 21 +-
.../apache/drill/common/logical/data/Sequence.java | 192 ------
.../data/visitors/AbstractLogicalVisitor.java | 6 -
.../logical/data/visitors/LogicalVisitor.java | 3 -
pom.xml | 4 +-
47 files changed, 1397 insertions(+), 1360 deletions(-)
delete mode 100644 common/src/main/java/org/apache/drill/common/util/CoreDecimalUtility.java
create mode 100644 exec/java-exec/src/main/java/org/apache/drill/exec/planner/sql/DrillCalciteSqlBetweenOperatorWrapper.java
create mode 100644 exec/java-exec/src/main/java/org/apache/drill/exec/rpc/control/LocalControlConnectionManager.java
copy exec/java-exec/src/main/java/org/apache/drill/exec/rpc/control/{ControlConnectionManager.java => RemoteControlConnectionManager.java} (57%)
create mode 100644 exec/java-exec/src/test/java/org/apache/drill/exec/rpc/control/ConnectionManagerRegistryTest.java
create mode 100644 exec/java-exec/src/test/java/org/apache/drill/exec/rpc/control/TestLocalControlConnectionManager.java
delete mode 100644 logical/src/main/java/org/apache/drill/common/logical/data/Sequence.java
--
To stop receiving notification emails like this one, please contact
arina@apache.org.
[drill] 02/08: DRILL-6255: Drillbit while sending control message
to itself creates a connection instead of submitting locally
Posted by ar...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
arina pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/drill.git
commit 5dd8a6f60e006c2dc707f241b7619634e4e82bbd
Author: Sorabh Hamirwasia <sh...@maprtech.com>
AuthorDate: Tue May 8 13:06:20 2018 -0700
DRILL-6255: Drillbit while sending control message to itself creates a connection instead of submitting locally
closes #1253
---
.../org/apache/drill/exec/rpc/BitRpcUtility.java | 18 ++
.../rpc/control/ConnectionManagerRegistry.java | 6 +-
.../exec/rpc/control/ControlConnectionConfig.java | 9 +-
.../exec/rpc/control/ControlConnectionManager.java | 16 +-
.../drill/exec/rpc/control/ControlTunnel.java | 162 ++++++++----
.../rpc/control/LocalControlConnectionManager.java | 236 +++++++++++++++++
...er.java => RemoteControlConnectionManager.java} | 26 +-
.../org/apache/drill/exec/rpc/data/DataTunnel.java | 25 +-
.../exec/work/batch/ControlMessageHandler.java | 51 ++--
.../drill/exec/work/foreman/FragmentsRunner.java | 105 ++------
.../exec/work/fragment/FragmentStatusReporter.java | 15 +-
.../rpc/control/ConnectionManagerRegistryTest.java | 149 +++++++++++
.../control/TestLocalControlConnectionManager.java | 278 +++++++++++++++++++++
.../rpc/user/security/TestUserBitKerberos.java | 36 ++-
.../work/fragment/FragmentStatusReporterTest.java | 73 +-----
.../apache/drill/exec/rpc/FutureBitCommand.java | 20 +-
.../apache/drill/exec/rpc/ListeningCommand.java | 33 +--
.../drill/exec/rpc/ReconnectingConnection.java | 16 +-
.../java/org/apache/drill/exec/rpc/RpcCommand.java | 13 +-
19 files changed, 983 insertions(+), 304 deletions(-)
diff --git a/exec/java-exec/src/main/java/org/apache/drill/exec/rpc/BitRpcUtility.java b/exec/java-exec/src/main/java/org/apache/drill/exec/rpc/BitRpcUtility.java
index c398033..0bc01f5 100644
--- a/exec/java-exec/src/main/java/org/apache/drill/exec/rpc/BitRpcUtility.java
+++ b/exec/java-exec/src/main/java/org/apache/drill/exec/rpc/BitRpcUtility.java
@@ -103,6 +103,24 @@ public final class BitRpcUtility {
}
}
+ /**
+ * Verifies if local and remote Drillbit Endpoint has same control server by using address and control port
+ * information. This method is used instead of equals in {@link DrillbitEndpoint} because DrillbitEndpoint stores
+ * state information in it.
+ * For local Drillbit a reference is stored in {@link org.apache.drill.exec.server.DrillbitContext} as soon as
+ * Drillbit is started in {@link org.apache.drill.exec.service.ServiceEngine#start} with state as STARTUP, but
+ * while planning minor fragment the assignment list is used from active list of Drillbits in which state for local
+ * Drillbit will not be STARTUP
+ * @param local - DrillbitEndpoint instance for local bit
+ * @param remote - DrillbitEndpoint instance for remote bit
+ * @return true if address and control port for local and remote are same.
+ * false - otherwise
+ */
+ public static boolean isLocalControlServer(DrillbitEndpoint local, DrillbitEndpoint remote) {
+ return local.hasAddress() && local.hasControlPort() && remote.hasAddress() && remote.hasControlPort() &&
+ local.getAddress().equals(remote.getAddress()) && local.getControlPort() == remote.getControlPort();
+ }
+
// Suppress default constructor
private BitRpcUtility() {
}
diff --git a/exec/java-exec/src/main/java/org/apache/drill/exec/rpc/control/ConnectionManagerRegistry.java b/exec/java-exec/src/main/java/org/apache/drill/exec/rpc/control/ConnectionManagerRegistry.java
index 800cf3c..e27729c 100644
--- a/exec/java-exec/src/main/java/org/apache/drill/exec/rpc/control/ConnectionManagerRegistry.java
+++ b/exec/java-exec/src/main/java/org/apache/drill/exec/rpc/control/ConnectionManagerRegistry.java
@@ -23,6 +23,7 @@ import java.util.concurrent.ConcurrentMap;
import org.apache.drill.exec.proto.CoordinationProtos.DrillbitEndpoint;
import com.google.common.collect.Maps;
+import org.apache.drill.exec.rpc.BitRpcUtility;
public class ConnectionManagerRegistry implements Iterable<ControlConnectionManager> {
static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(ConnectionManagerRegistry.class);
@@ -40,9 +41,12 @@ public class ConnectionManagerRegistry implements Iterable<ControlConnectionMana
public ControlConnectionManager getConnectionManager(DrillbitEndpoint remoteEndpoint) {
assert localEndpoint != null :
"DrillbitEndpoint must be set before a connection manager can be retrieved";
+
+ final boolean isLocalServer = BitRpcUtility.isLocalControlServer(localEndpoint, remoteEndpoint);
ControlConnectionManager m = registry.get(remoteEndpoint);
if (m == null) {
- m = new ControlConnectionManager(config, localEndpoint, remoteEndpoint);
+ m = (isLocalServer) ? new LocalControlConnectionManager(config, remoteEndpoint)
+ : new RemoteControlConnectionManager(config, localEndpoint, remoteEndpoint);
final ControlConnectionManager m2 = registry.putIfAbsent(remoteEndpoint, m);
if (m2 != null) {
m = m2;
diff --git a/exec/java-exec/src/main/java/org/apache/drill/exec/rpc/control/ControlConnectionConfig.java b/exec/java-exec/src/main/java/org/apache/drill/exec/rpc/control/ControlConnectionConfig.java
index b19fb8b..f114af4 100644
--- a/exec/java-exec/src/main/java/org/apache/drill/exec/rpc/control/ControlConnectionConfig.java
+++ b/exec/java-exec/src/main/java/org/apache/drill/exec/rpc/control/ControlConnectionConfig.java
@@ -17,6 +17,7 @@
*/
package org.apache.drill.exec.rpc.control;
+import com.google.common.annotations.VisibleForTesting;
import org.apache.drill.exec.exception.DrillbitStartupException;
import org.apache.drill.exec.memory.BufferAllocator;
import org.apache.drill.exec.rpc.BitConnectionConfig;
@@ -24,8 +25,8 @@ import org.apache.drill.exec.server.BootStrapContext;
import org.apache.drill.exec.work.batch.ControlMessageHandler;
// config for bit to bit connection
-// package private
-class ControlConnectionConfig extends BitConnectionConfig {
+@VisibleForTesting
+public class ControlConnectionConfig extends BitConnectionConfig {
// private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(ControlConnectionConfig.class);
private final ControlMessageHandler handler;
@@ -41,8 +42,8 @@ class ControlConnectionConfig extends BitConnectionConfig {
return "control"; // unused
}
- ControlMessageHandler getMessageHandler() {
+ @VisibleForTesting
+ public ControlMessageHandler getMessageHandler() {
return handler;
}
-
}
diff --git a/exec/java-exec/src/main/java/org/apache/drill/exec/rpc/control/ControlConnectionManager.java b/exec/java-exec/src/main/java/org/apache/drill/exec/rpc/control/ControlConnectionManager.java
index 6bfcbd5..240421e 100644
--- a/exec/java-exec/src/main/java/org/apache/drill/exec/rpc/control/ControlConnectionManager.java
+++ b/exec/java-exec/src/main/java/org/apache/drill/exec/rpc/control/ControlConnectionManager.java
@@ -25,14 +25,10 @@ import org.apache.drill.exec.rpc.ReconnectingConnection;
/**
* Maintains connection between two particular bits.
*/
-public class ControlConnectionManager extends ReconnectingConnection<ControlConnection, BitControlHandshake>{
+public abstract class ControlConnectionManager extends ReconnectingConnection<ControlConnection, BitControlHandshake>{
static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(ControlConnectionManager.class);
- private final ControlConnectionConfig config;
- private final DrillbitEndpoint remoteEndpoint;
-
- public ControlConnectionManager(ControlConnectionConfig config, DrillbitEndpoint localEndpoint,
- DrillbitEndpoint remoteEndpoint) {
+ public ControlConnectionManager(DrillbitEndpoint localEndpoint, DrillbitEndpoint remoteEndpoint) {
super(
BitControlHandshake.newBuilder()
.setRpcVersion(ControlRpcConfig.RPC_VERSION)
@@ -40,14 +36,8 @@ public class ControlConnectionManager extends ReconnectingConnection<ControlConn
.build(),
remoteEndpoint.getAddress(),
remoteEndpoint.getControlPort());
-
- this.config = config;
- this.remoteEndpoint = remoteEndpoint;
}
@Override
- protected BasicClient<?, ControlConnection, BitControlHandshake, ?> getNewClient() {
- return new ControlClient(config, remoteEndpoint, new CloseHandlerCreator());
- }
-
+ protected abstract BasicClient<?, ControlConnection, BitControlHandshake, ?> getNewClient();
}
diff --git a/exec/java-exec/src/main/java/org/apache/drill/exec/rpc/control/ControlTunnel.java b/exec/java-exec/src/main/java/org/apache/drill/exec/rpc/control/ControlTunnel.java
index 1a4af90..492d4de 100644
--- a/exec/java-exec/src/main/java/org/apache/drill/exec/rpc/control/ControlTunnel.java
+++ b/exec/java-exec/src/main/java/org/apache/drill/exec/rpc/control/ControlTunnel.java
@@ -17,11 +17,20 @@
*/
package org.apache.drill.exec.rpc.control;
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.JsonDeserializer;
+import com.fasterxml.jackson.databind.JsonSerializer;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.ObjectReader;
+import com.fasterxml.jackson.databind.ObjectWriter;
+import com.fasterxml.jackson.databind.module.SimpleModule;
+import com.google.protobuf.ByteString;
+import com.google.protobuf.InvalidProtocolBufferException;
+import com.google.protobuf.Message;
+import com.google.protobuf.MessageLite;
+import com.google.protobuf.Parser;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.DrillBuf;
-
-import java.util.concurrent.TimeUnit;
-
import org.apache.drill.exec.proto.BitControl.CustomMessage;
import org.apache.drill.exec.proto.BitControl.FinishedReceiver;
import org.apache.drill.exec.proto.BitControl.FragmentStatus;
@@ -38,19 +47,7 @@ import org.apache.drill.exec.rpc.RpcException;
import org.apache.drill.exec.rpc.RpcOutcomeListener;
import org.apache.drill.exec.rpc.control.Controller.CustomSerDe;
-import com.fasterxml.jackson.core.JsonProcessingException;
-import com.fasterxml.jackson.databind.JsonDeserializer;
-import com.fasterxml.jackson.databind.JsonSerializer;
-import com.fasterxml.jackson.databind.ObjectMapper;
-import com.fasterxml.jackson.databind.ObjectReader;
-import com.fasterxml.jackson.databind.ObjectWriter;
-import com.fasterxml.jackson.databind.module.SimpleModule;
-import com.google.protobuf.ByteString;
-import com.google.protobuf.InvalidProtocolBufferException;
-import com.google.protobuf.Message;
-import com.google.protobuf.MessageLite;
-import com.google.protobuf.Parser;
-
+import java.util.concurrent.TimeUnit;
public class ControlTunnel {
static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(ControlTunnel.class);
@@ -99,8 +96,7 @@ public class ControlTunnel {
return b.getFuture();
}
-
- public static class SendFragmentStatus extends FutureBitCommand<Ack, ControlConnection> {
+ public static class SendFragmentStatus extends FutureBitCommand<Ack, ControlConnection, RpcType, FragmentStatus> {
final FragmentStatus status;
public SendFragmentStatus(FragmentStatus status) {
@@ -110,13 +106,22 @@ public class ControlTunnel {
@Override
public void doRpcCall(RpcOutcomeListener<Ack> outcomeListener, ControlConnection connection) {
- connection.sendUnsafe(outcomeListener, RpcType.REQ_FRAGMENT_STATUS, status, Ack.class);
+ connection.sendUnsafe(outcomeListener, getRpcType(), status, Ack.class);
}
- }
+ @Override
+ public RpcType getRpcType() {
+ return RpcType.REQ_FRAGMENT_STATUS;
+ }
+ @Override
+ public FragmentStatus getMessage() {
+ return status;
+ }
- public static class ReceiverFinished extends ListeningCommand<Ack, ControlConnection> {
+ }
+
+ public static class ReceiverFinished extends ListeningCommand<Ack, ControlConnection, RpcType, FinishedReceiver> {
final FinishedReceiver finishedReceiver;
public ReceiverFinished(RpcOutcomeListener<Ack> listener, FinishedReceiver finishedReceiver) {
@@ -126,11 +131,21 @@ public class ControlTunnel {
@Override
public void doRpcCall(RpcOutcomeListener<Ack> outcomeListener, ControlConnection connection) {
- connection.send(outcomeListener, RpcType.REQ_RECEIVER_FINISHED, finishedReceiver, Ack.class);
+ connection.send(outcomeListener, getRpcType(), finishedReceiver, Ack.class);
+ }
+
+ @Override
+ public RpcType getRpcType() {
+ return RpcType.REQ_RECEIVER_FINISHED;
+ }
+
+ @Override
+ public FinishedReceiver getMessage() {
+ return finishedReceiver;
}
}
- public static class SignalFragment extends ListeningCommand<Ack, ControlConnection> {
+ public static class SignalFragment extends ListeningCommand<Ack, ControlConnection, RpcType, FragmentHandle> {
final FragmentHandle handle;
final RpcType type;
@@ -145,9 +160,18 @@ public class ControlTunnel {
connection.sendUnsafe(outcomeListener, type, handle, Ack.class);
}
+ @Override
+ public RpcType getRpcType() {
+ return type;
+ }
+
+ @Override
+ public FragmentHandle getMessage() {
+ return handle;
+ }
}
- public static class SendFragment extends ListeningCommand<Ack, ControlConnection> {
+ public static class SendFragment extends ListeningCommand<Ack, ControlConnection, RpcType, InitializeFragments> {
final InitializeFragments fragments;
public SendFragment(RpcOutcomeListener<Ack> listener, InitializeFragments fragments) {
@@ -157,12 +181,21 @@ public class ControlTunnel {
@Override
public void doRpcCall(RpcOutcomeListener<Ack> outcomeListener, ControlConnection connection) {
- connection.send(outcomeListener, RpcType.REQ_INITIALIZE_FRAGMENTS, fragments, Ack.class);
+ connection.send(outcomeListener, getRpcType(), fragments, Ack.class);
+ }
+
+ @Override
+ public RpcType getRpcType() {
+ return RpcType.REQ_INITIALIZE_FRAGMENTS;
}
+ @Override
+ public InitializeFragments getMessage() {
+ return fragments;
+ }
}
- public static class RequestProfile extends FutureBitCommand<QueryProfile, ControlConnection> {
+ public static class RequestProfile extends FutureBitCommand<QueryProfile, ControlConnection, RpcType, QueryId> {
final QueryId queryId;
public RequestProfile(QueryId queryId) {
@@ -172,11 +205,21 @@ public class ControlTunnel {
@Override
public void doRpcCall(RpcOutcomeListener<QueryProfile> outcomeListener, ControlConnection connection) {
- connection.send(outcomeListener, RpcType.REQ_QUERY_STATUS, queryId, QueryProfile.class);
+ connection.send(outcomeListener, getRpcType(), queryId, QueryProfile.class);
+ }
+
+ @Override
+ public RpcType getRpcType() {
+ return RpcType.REQ_QUERY_STATUS;
+ }
+
+ @Override
+ public QueryId getMessage() {
+ return queryId;
}
}
- public static class CancelQuery extends FutureBitCommand<Ack, ControlConnection> {
+ public static class CancelQuery extends FutureBitCommand<Ack, ControlConnection, RpcType, QueryId> {
final QueryId queryId;
public CancelQuery(QueryId queryId) {
@@ -186,7 +229,17 @@ public class ControlTunnel {
@Override
public void doRpcCall(RpcOutcomeListener<Ack> outcomeListener, ControlConnection connection) {
- connection.send(outcomeListener, RpcType.REQ_QUERY_CANCEL, queryId, Ack.class);
+ connection.send(outcomeListener, getRpcType(), queryId, Ack.class);
+ }
+
+ @Override
+ public RpcType getRpcType() {
+ return RpcType.REQ_QUERY_CANCEL;
+ }
+
+ @Override
+ public QueryId getMessage() {
+ return queryId;
}
}
@@ -204,8 +257,8 @@ public class ControlTunnel {
return new CustomTunnel<SEND, RECEIVE>(messageTypeId, send, receive);
}
-
- private static class CustomMessageSender extends ListeningCommand<CustomMessage, ControlConnection> {
+ public static class CustomMessageSender extends
+ ListeningCommand<CustomMessage, ControlConnection, RpcType, CustomMessage> {
private CustomMessage message;
private ByteBuf[] dataBodies;
@@ -218,12 +271,27 @@ public class ControlTunnel {
@Override
public void doRpcCall(RpcOutcomeListener<CustomMessage> outcomeListener, ControlConnection connection) {
- connection.send(outcomeListener, RpcType.REQ_CUSTOM, message, CustomMessage.class, dataBodies);
+ connection.send(outcomeListener, getRpcType(), message, CustomMessage.class, dataBodies);
+ }
+
+ @Override
+ public RpcType getRpcType() {
+ return RpcType.REQ_CUSTOM;
+ }
+
+ @Override
+ public CustomMessage getMessage() {
+ return message;
+ }
+
+ public ByteBuf[] getDataBodies() {
+ return dataBodies;
}
}
- private static class SyncCustomMessageSender extends FutureBitCommand<CustomMessage, ControlConnection> {
+ public static class SyncCustomMessageSender extends
+ FutureBitCommand<CustomMessage, ControlConnection, RpcType, CustomMessage> {
private CustomMessage message;
private ByteBuf[] dataBodies;
@@ -236,7 +304,21 @@ public class ControlTunnel {
@Override
public void doRpcCall(RpcOutcomeListener<CustomMessage> outcomeListener, ControlConnection connection) {
- connection.send(outcomeListener, RpcType.REQ_CUSTOM, message, CustomMessage.class, dataBodies);
+ connection.send(outcomeListener, getRpcType(), message, CustomMessage.class, dataBodies);
+ }
+
+ @Override
+ public RpcType getRpcType() {
+ return RpcType.REQ_CUSTOM;
+ }
+
+ @Override
+ public CustomMessage getMessage() {
+ return message;
+ }
+
+ public ByteBuf[] getDataBodies() {
+ return dataBodies;
}
}
@@ -261,8 +343,7 @@ public class ControlTunnel {
return serde.deserializeReceived(message.getMessage().toByteArray());
}
- public RECEIVE get(long timeout, TimeUnit unit) throws Exception,
- InvalidProtocolBufferException {
+ public RECEIVE get(long timeout, TimeUnit unit) throws Exception, InvalidProtocolBufferException {
CustomMessage message = future.checkedGet(timeout, unit);
return serde.deserializeReceived(message.getMessage().toByteArray());
}
@@ -270,7 +351,6 @@ public class ControlTunnel {
public DrillBuf getBuffer() throws RpcException {
return (DrillBuf) future.getBuffer();
}
-
}
@@ -351,21 +431,15 @@ public class ControlTunnel {
} catch (Exception e) {
innerListener.failed(new RpcException("Failure while parsing message locally.", e));
}
-
}
@Override
public void interrupted(InterruptedException e) {
innerListener.interrupted(e);
}
-
}
-
}
-
-
-
public static class ProtoSerDe<MSG extends MessageLite> implements CustomSerDe<MSG> {
private final Parser<MSG> parser;
@@ -420,7 +494,5 @@ public class ControlTunnel {
public MSG deserializeReceived(byte[] bytes) throws Exception {
return (MSG) reader.readValue(bytes);
}
-
}
-
}
diff --git a/exec/java-exec/src/main/java/org/apache/drill/exec/rpc/control/LocalControlConnectionManager.java b/exec/java-exec/src/main/java/org/apache/drill/exec/rpc/control/LocalControlConnectionManager.java
new file mode 100644
index 0000000..fa6a2e9
--- /dev/null
+++ b/exec/java-exec/src/main/java/org/apache/drill/exec/rpc/control/LocalControlConnectionManager.java
@@ -0,0 +1,236 @@
+/*
+ * 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.drill.exec.rpc.control;
+
+import io.netty.buffer.ByteBuf;
+import io.netty.buffer.DrillBuf;
+import org.apache.drill.exec.exception.OutOfMemoryException;
+import org.apache.drill.exec.proto.BitControl;
+import org.apache.drill.exec.proto.CoordinationProtos.DrillbitEndpoint;
+import org.apache.drill.exec.proto.GeneralRPCProtos.Ack;
+import org.apache.drill.exec.proto.UserBitShared;
+import org.apache.drill.exec.rpc.BasicClient;
+import org.apache.drill.exec.rpc.Response;
+import org.apache.drill.exec.rpc.RpcCommand;
+import org.apache.drill.exec.rpc.RpcConstants;
+import org.apache.drill.exec.rpc.RpcException;
+import org.apache.drill.exec.rpc.RpcOutcomeListener;
+import org.apache.drill.exec.work.batch.ControlMessageHandler;
+
+public class LocalControlConnectionManager extends ControlConnectionManager {
+ private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(LocalControlConnectionManager.class);
+
+ private final ControlConnectionConfig config;
+
+ public LocalControlConnectionManager(ControlConnectionConfig config, DrillbitEndpoint localEndpoint) {
+ super(localEndpoint, localEndpoint);
+ this.config = config;
+ }
+
+ @Override
+ protected BasicClient<?, ControlConnection, BitControl.BitControlHandshake, ?> getNewClient() {
+ throw new UnsupportedOperationException("LocalControlConnectionManager doesn't support creating a control client");
+ }
+
+ @Override
+ public void runCommand(RpcCommand cmd) {
+ final int rpcType = cmd.getRpcType().getNumber();
+ final ControlMessageHandler messageHandler = config.getMessageHandler();
+
+ if (RpcConstants.EXTRA_DEBUGGING) {
+ logger.debug("Received bit com message of type {} over local connection manager", rpcType);
+ }
+
+ switch (rpcType) {
+
+ case BitControl.RpcType.REQ_CANCEL_FRAGMENT_VALUE: {
+ final ControlTunnel.SignalFragment signalFragment = ((ControlTunnel.SignalFragment) cmd);
+ final RpcOutcomeListener<Ack> outcomeListener = signalFragment.getOutcomeListener();
+ final Ack ackResponse = messageHandler.cancelFragment(signalFragment.getMessage());
+ outcomeListener.success(ackResponse, null);
+ break;
+ }
+
+ case BitControl.RpcType.REQ_CUSTOM_VALUE: {
+ final ByteBuf[] dataBodies;
+ final RpcOutcomeListener<BitControl.CustomMessage> outcomeListener;
+
+ if (cmd instanceof ControlTunnel.CustomMessageSender) {
+ dataBodies = ((ControlTunnel.CustomMessageSender)cmd).getDataBodies();
+ outcomeListener = ((ControlTunnel.CustomMessageSender)cmd).getOutcomeListener();
+ } else if (cmd instanceof ControlTunnel.SyncCustomMessageSender) {
+ dataBodies = ((ControlTunnel.SyncCustomMessageSender)cmd).getDataBodies();
+ outcomeListener = ((ControlTunnel.SyncCustomMessageSender)cmd).getOutcomeListener();
+ } else {
+ throw new UnsupportedOperationException("Unknown Custom Type control message received");
+ }
+
+ DrillBuf reqDrillBuff;
+ try {
+ reqDrillBuff = convertToByteBuf(dataBodies);
+ } catch (Exception ex) {
+ outcomeListener.failed(new RpcException("Failed to allocate memory while sending request in " +
+ "LocalControlConnectionManager#convertToByteBuff", ex));
+ return;
+ } finally {
+ releaseByteBuf(dataBodies);
+ }
+
+ try {
+ BitControl.CustomMessage message = (BitControl.CustomMessage) cmd.getMessage();
+ final Response response = messageHandler.getHandlerRegistry().handle(message, reqDrillBuff);
+ DrillBuf responseBuffer;
+ try {
+ responseBuffer = convertToByteBuf(response.dBodies);
+ } catch (Exception ex) {
+ outcomeListener.failed(new RpcException("Failed to allocate memory while sending response in " +
+ "LocalControlConnectionManager#convertToByteBuff", ex));
+ return;
+ } finally {
+ releaseByteBuf(response.dBodies);
+ }
+
+ // Passed responseBuffer will be owned by consumer
+ outcomeListener.success((BitControl.CustomMessage)response.pBody, responseBuffer);
+ } catch (RpcException ex) {
+ cmd.getOutcomeListener().failed(ex);
+ } finally {
+ // Release the reqDrillBuff passed into handler
+ releaseByteBuf(reqDrillBuff);
+ }
+ break;
+ }
+
+ case BitControl.RpcType.REQ_RECEIVER_FINISHED_VALUE: {
+ final ControlTunnel.ReceiverFinished receiverFinished = ((ControlTunnel.ReceiverFinished) cmd);
+ final RpcOutcomeListener<Ack> outcomeListener = receiverFinished.getOutcomeListener();
+ final Ack ackResponse = messageHandler.receivingFragmentFinished(receiverFinished.getMessage());
+ outcomeListener.success(ackResponse, null);
+ break;
+ }
+
+ case BitControl.RpcType.REQ_FRAGMENT_STATUS_VALUE: {
+ final ControlTunnel.SendFragmentStatus fragmentStatus = ((ControlTunnel.SendFragmentStatus) cmd);
+ final RpcOutcomeListener<Ack> outcomeListener = fragmentStatus.getOutcomeListener();
+ final Ack ackResponse = messageHandler.requestFragmentStatus(fragmentStatus.getMessage());
+ outcomeListener.success(ackResponse, null);
+ break;
+ }
+
+ case BitControl.RpcType.REQ_QUERY_CANCEL_VALUE: {
+ final ControlTunnel.CancelQuery cancelQuery = ((ControlTunnel.CancelQuery) cmd);
+ final RpcOutcomeListener<Ack> outcomeListener = cancelQuery.getOutcomeListener();
+ final Ack ackResponse = messageHandler.requestQueryCancel(cancelQuery.getMessage());
+ outcomeListener.success(ackResponse, null);
+ break;
+ }
+
+ case BitControl.RpcType.REQ_INITIALIZE_FRAGMENTS_VALUE: {
+ final ControlTunnel.SendFragment sendFragment = ((ControlTunnel.SendFragment) cmd);
+ final RpcOutcomeListener<Ack> outcomeListener = sendFragment.getOutcomeListener();
+
+ try {
+ final Ack ackResponse = messageHandler.initializeFragment(sendFragment.getMessage());
+ outcomeListener.success(ackResponse, null);
+ } catch (RpcException ex) {
+ outcomeListener.failed(ex);
+ }
+ break;
+ }
+
+ case BitControl.RpcType.REQ_QUERY_STATUS_VALUE: {
+ final ControlTunnel.RequestProfile requestProfile = ((ControlTunnel.RequestProfile) cmd);
+ final RpcOutcomeListener<UserBitShared.QueryProfile> outcomeListener = requestProfile.getOutcomeListener();
+
+ try {
+ final UserBitShared.QueryProfile profile = messageHandler.requestQueryStatus(requestProfile.getMessage());
+ outcomeListener.success(profile, null);
+ } catch (RpcException ex) {
+ outcomeListener.failed(ex);
+ }
+ break;
+ }
+
+ case BitControl.RpcType.REQ_UNPAUSE_FRAGMENT_VALUE: {
+ final ControlTunnel.SignalFragment signalFragment = ((ControlTunnel.SignalFragment) cmd);
+ final RpcOutcomeListener<Ack> outcomeListener = signalFragment.getOutcomeListener();
+ final Ack ackResponse = messageHandler.resumeFragment(signalFragment.getMessage());
+ outcomeListener.success(ackResponse, null);
+ break;
+ }
+
+ default:
+ final RpcException rpcException = new RpcException(String.format("Unsupported control request type %s " +
+ "received on LocalControlConnectionManager", rpcType));
+ cmd.getOutcomeListener().failed(rpcException);
+ }
+ }
+
+ /**
+ * Copies ByteBuf in the input array into a single DrillBuf
+ * @param byteBuffArray - input array of ByteBuf's
+ * @return DrillBuf - output Drillbuf with all the input bytes.
+ * @throws OutOfMemoryException
+ */
+ private DrillBuf convertToByteBuf(ByteBuf[] byteBuffArray) throws OutOfMemoryException {
+
+ if (byteBuffArray == null) {
+ return null;
+ }
+
+ int bytesToCopy = 0;
+ for (ByteBuf b : byteBuffArray) {
+ final int validBytes = b.readableBytes();
+ if (0 == validBytes) {
+ b.release();
+ } else {
+ bytesToCopy += validBytes;
+ }
+ }
+ final DrillBuf drillBuff = config.getAllocator().buffer(bytesToCopy);
+
+ for (ByteBuf b : byteBuffArray) {
+ final int validBytes = b.readableBytes();
+ drillBuff.writeBytes(b, 0, validBytes);
+ }
+
+ return drillBuff;
+ }
+
+ /**
+ * Releases all the ByteBuf inside the input ByteBuf array
+ * @param byteBuffArray - input array of ByteBuf's
+ */
+ private void releaseByteBuf(ByteBuf[] byteBuffArray) {
+ if (byteBuffArray != null) {
+ for (ByteBuf b : byteBuffArray) {
+ b.release();
+ }
+ }
+ }
+
+ /**
+ * Releases the input ByteBuf
+ * @param byteBuf - input ByteBuf
+ */
+ private void releaseByteBuf(ByteBuf byteBuf) {
+ if (byteBuf != null) {
+ byteBuf.release();
+ }
+ }
+}
diff --git a/exec/java-exec/src/main/java/org/apache/drill/exec/rpc/control/ControlConnectionManager.java b/exec/java-exec/src/main/java/org/apache/drill/exec/rpc/control/RemoteControlConnectionManager.java
similarity index 57%
copy from exec/java-exec/src/main/java/org/apache/drill/exec/rpc/control/ControlConnectionManager.java
copy to exec/java-exec/src/main/java/org/apache/drill/exec/rpc/control/RemoteControlConnectionManager.java
index 6bfcbd5..6a4dc21 100644
--- a/exec/java-exec/src/main/java/org/apache/drill/exec/rpc/control/ControlConnectionManager.java
+++ b/exec/java-exec/src/main/java/org/apache/drill/exec/rpc/control/RemoteControlConnectionManager.java
@@ -17,37 +17,25 @@
*/
package org.apache.drill.exec.rpc.control;
-import org.apache.drill.exec.proto.BitControl.BitControlHandshake;
+import org.apache.drill.exec.proto.BitControl;
import org.apache.drill.exec.proto.CoordinationProtos.DrillbitEndpoint;
import org.apache.drill.exec.rpc.BasicClient;
-import org.apache.drill.exec.rpc.ReconnectingConnection;
-/**
- * Maintains connection between two particular bits.
- */
-public class ControlConnectionManager extends ReconnectingConnection<ControlConnection, BitControlHandshake>{
- static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(ControlConnectionManager.class);
+public class RemoteControlConnectionManager extends ControlConnectionManager {
+ private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(RemoteControlConnectionManager.class);
private final ControlConnectionConfig config;
private final DrillbitEndpoint remoteEndpoint;
- public ControlConnectionManager(ControlConnectionConfig config, DrillbitEndpoint localEndpoint,
- DrillbitEndpoint remoteEndpoint) {
- super(
- BitControlHandshake.newBuilder()
- .setRpcVersion(ControlRpcConfig.RPC_VERSION)
- .setEndpoint(localEndpoint)
- .build(),
- remoteEndpoint.getAddress(),
- remoteEndpoint.getControlPort());
-
+ public RemoteControlConnectionManager(ControlConnectionConfig config, DrillbitEndpoint
+ localEndpoint, DrillbitEndpoint remoteEndpoint) {
+ super(localEndpoint, remoteEndpoint);
this.config = config;
this.remoteEndpoint = remoteEndpoint;
}
@Override
- protected BasicClient<?, ControlConnection, BitControlHandshake, ?> getNewClient() {
+ protected BasicClient<?, ControlConnection, BitControl.BitControlHandshake, ?> getNewClient() {
return new ControlClient(config, remoteEndpoint, new CloseHandlerCreator());
}
-
}
diff --git a/exec/java-exec/src/main/java/org/apache/drill/exec/rpc/data/DataTunnel.java b/exec/java-exec/src/main/java/org/apache/drill/exec/rpc/data/DataTunnel.java
index 7e286fa..7b05b81 100644
--- a/exec/java-exec/src/main/java/org/apache/drill/exec/rpc/data/DataTunnel.java
+++ b/exec/java-exec/src/main/java/org/apache/drill/exec/rpc/data/DataTunnel.java
@@ -17,6 +17,7 @@
*/
package org.apache.drill.exec.rpc.data;
+import com.google.protobuf.MessageLite;
import io.netty.buffer.ByteBuf;
import java.util.concurrent.Semaphore;
@@ -43,7 +44,6 @@ public class DataTunnel {
private ExecutionControls testControls;
private org.slf4j.Logger testLogger;
-
public DataTunnel(DataConnectionManager manager) {
this.manager = manager;
}
@@ -69,7 +69,7 @@ public class DataTunnel {
public void sendRecordBatch(RpcOutcomeListener<Ack> outcomeListener, FragmentWritableBatch batch) {
SendBatchAsyncListen b = new SendBatchAsyncListen(outcomeListener, batch);
- try{
+ try {
if (isInjectionControlSet) {
// Wait for interruption if set. Used to simulate the fragment interruption while the fragment is waiting for
// semaphore acquire. We expect the
@@ -78,9 +78,9 @@ public class DataTunnel {
sendingSemaphore.acquire();
manager.runCommand(b);
- }catch(final InterruptedException e){
+ } catch (final InterruptedException e) {
// Release the buffers first before informing the listener about the interrupt.
- for(ByteBuf buffer : batch.getBuffers()) {
+ for (ByteBuf buffer : batch.getBuffers()) {
buffer.release();
}
@@ -119,7 +119,7 @@ public class DataTunnel {
}
}
- private class SendBatchAsyncListen extends ListeningCommand<Ack, DataClientConnection> {
+ private class SendBatchAsyncListen extends ListeningCommand<Ack, DataClientConnection, RpcType, MessageLite> {
final FragmentWritableBatch batch;
public SendBatchAsyncListen(RpcOutcomeListener<Ack> listener, FragmentWritableBatch batch) {
@@ -129,7 +129,18 @@ public class DataTunnel {
@Override
public void doRpcCall(RpcOutcomeListener<Ack> outcomeListener, DataClientConnection connection) {
- connection.send(new ThrottlingOutcomeListener(outcomeListener), RpcType.REQ_RECORD_BATCH, batch.getHeader(), Ack.class, batch.getBuffers());
+ connection.send(new ThrottlingOutcomeListener(outcomeListener), getRpcType(), batch.getHeader(),
+ Ack.class, batch.getBuffers());
+ }
+
+ @Override
+ public RpcType getRpcType() {
+ return RpcType.REQ_RECORD_BATCH;
+ }
+
+ @Override
+ public MessageLite getMessage() {
+ return batch.getHeader();
}
@Override
@@ -139,7 +150,7 @@ public class DataTunnel {
@Override
public void connectionFailed(FailureType type, Throwable t) {
- for(ByteBuf buffer : batch.getBuffers()) {
+ for (ByteBuf buffer : batch.getBuffers()) {
buffer.release();
}
super.connectionFailed(type, t);
diff --git a/exec/java-exec/src/main/java/org/apache/drill/exec/work/batch/ControlMessageHandler.java b/exec/java-exec/src/main/java/org/apache/drill/exec/work/batch/ControlMessageHandler.java
index e562b16..963f53a 100644
--- a/exec/java-exec/src/main/java/org/apache/drill/exec/work/batch/ControlMessageHandler.java
+++ b/exec/java-exec/src/main/java/org/apache/drill/exec/work/batch/ControlMessageHandler.java
@@ -91,14 +91,16 @@ public class ControlMessageHandler implements RequestHandler<ControlConnection>
}
case RpcType.REQ_FRAGMENT_STATUS_VALUE:
- bee.getContext().getWorkBus().statusUpdate( get(pBody, FragmentStatus.PARSER));
+ final FragmentStatus status = get(pBody, FragmentStatus.PARSER);
+ requestFragmentStatus(status);
// TODO: Support a type of message that has no response.
sender.send(ControlRpcConfig.OK);
break;
case RpcType.REQ_QUERY_CANCEL_VALUE: {
final QueryId queryId = get(pBody, QueryId.PARSER);
- if (bee.cancelForeman(queryId, null)) {
+ final Ack cancelStatus = requestQueryCancel(queryId);
+ if (cancelStatus.getOk()) {
sender.send(ControlRpcConfig.OK);
} else {
sender.send(ControlRpcConfig.FAIL);
@@ -108,21 +110,14 @@ public class ControlMessageHandler implements RequestHandler<ControlConnection>
case RpcType.REQ_INITIALIZE_FRAGMENTS_VALUE: {
final InitializeFragments fragments = get(pBody, InitializeFragments.PARSER);
- final DrillbitContext drillbitContext = bee.getContext();
- for(int i = 0; i < fragments.getFragmentCount(); i++) {
- startNewFragment(fragments.getFragment(i), drillbitContext);
- }
+ initializeFragment(fragments);
sender.send(ControlRpcConfig.OK);
break;
}
case RpcType.REQ_QUERY_STATUS_VALUE: {
final QueryId queryId = get(pBody, QueryId.PARSER);
- final Foreman foreman = bee.getForemanForQueryId(queryId);
- if (foreman == null) {
- throw new RpcException("Query not running on node.");
- }
- final QueryProfile profile = foreman.getQueryManager().getQueryProfile();
+ final QueryProfile profile = requestQueryStatus(queryId);
sender.send(new Response(RpcType.RESP_QUERY_STATUS, profile));
break;
}
@@ -145,7 +140,7 @@ public class ControlMessageHandler implements RequestHandler<ControlConnection>
* @param fragment
* @throws UserRpcException
*/
- private void startNewFragment(final PlanFragment fragment, final DrillbitContext drillbitContext)
+ public void startNewFragment(final PlanFragment fragment, final DrillbitContext drillbitContext)
throws UserRpcException {
logger.debug("Received remote fragment start instruction", fragment);
@@ -182,7 +177,7 @@ public class ControlMessageHandler implements RequestHandler<ControlConnection>
/* (non-Javadoc)
* @see org.apache.drill.exec.work.batch.BitComHandler#cancelFragment(org.apache.drill.exec.proto.ExecProtos.FragmentHandle)
*/
- private Ack cancelFragment(final FragmentHandle handle) {
+ public Ack cancelFragment(final FragmentHandle handle) {
/**
* For case 1, see {@link org.apache.drill.exec.work.foreman.QueryManager#cancelExecutingFragments}.
* In comments below, "active" refers to fragment states: SENDING, AWAITING_ALLOCATION, RUNNING and
@@ -213,7 +208,7 @@ public class ControlMessageHandler implements RequestHandler<ControlConnection>
return Acks.OK;
}
- private Ack resumeFragment(final FragmentHandle handle) {
+ public Ack resumeFragment(final FragmentHandle handle) {
// resume a pending fragment
final FragmentManager manager = bee.getContext().getWorkBus().getFragmentManager(handle);
if (manager != null) {
@@ -233,7 +228,7 @@ public class ControlMessageHandler implements RequestHandler<ControlConnection>
return Acks.OK;
}
- private Ack receivingFragmentFinished(final FinishedReceiver finishedReceiver) {
+ public Ack receivingFragmentFinished(final FinishedReceiver finishedReceiver) {
final FragmentManager manager = bee.getContext().getWorkBus().getFragmentManager(finishedReceiver.getSender());
@@ -254,6 +249,32 @@ public class ControlMessageHandler implements RequestHandler<ControlConnection>
return Acks.OK;
}
+ public Ack requestFragmentStatus(FragmentStatus status) {
+ bee.getContext().getWorkBus().statusUpdate( status);
+ return Acks.OK;
+ }
+
+ public Ack requestQueryCancel(QueryId queryId) {
+ return bee.cancelForeman(queryId, null) ? Acks.OK : Acks.FAIL;
+ }
+
+ public Ack initializeFragment(InitializeFragments fragments) throws RpcException {
+ final DrillbitContext drillbitContext = bee.getContext();
+ for (int i = 0; i < fragments.getFragmentCount(); i++) {
+ startNewFragment(fragments.getFragment(i), drillbitContext);
+ }
+
+ return Acks.OK;
+ }
+
+ public QueryProfile requestQueryStatus(QueryId queryId) throws RpcException {
+ final Foreman foreman = bee.getForemanForQueryId(queryId);
+ if (foreman == null) {
+ throw new RpcException("Query not running on node.");
+ }
+ return foreman.getQueryManager().getQueryProfile();
+ }
+
public CustomHandlerRegistry getHandlerRegistry() {
return handlerRegistry;
}
diff --git a/exec/java-exec/src/main/java/org/apache/drill/exec/work/foreman/FragmentsRunner.java b/exec/java-exec/src/main/java/org/apache/drill/exec/work/foreman/FragmentsRunner.java
index 3d051bb..91b2a2a 100644
--- a/exec/java-exec/src/main/java/org/apache/drill/exec/work/foreman/FragmentsRunner.java
+++ b/exec/java-exec/src/main/java/org/apache/drill/exec/work/foreman/FragmentsRunner.java
@@ -44,11 +44,8 @@ import org.apache.drill.exec.work.EndpointListener;
import org.apache.drill.exec.work.WorkManager.WorkerBee;
import org.apache.drill.exec.work.fragment.FragmentExecutor;
import org.apache.drill.exec.work.fragment.FragmentStatusReporter;
-import org.apache.drill.exec.work.fragment.NonRootFragmentManager;
import org.apache.drill.exec.work.fragment.RootFragmentManager;
-
-import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
@@ -141,7 +138,6 @@ public class FragmentsRunner {
}
}
-
/**
* Set up the non-root fragments for execution. Some may be local, and some may be remote.
* Messages are sent immediately, so they may start returning data even before we complete this.
@@ -158,17 +154,11 @@ public class FragmentsRunner {
* executed there. We need to start up the intermediate fragments first so that they will be
* ready once the leaf fragments start producing data. To satisfy both of these, we will
* make a pass through the fragments and put them into the remote maps according to their
- * leaf/intermediate state, as well as their target drillbit. Also filter the leaf/intermediate
- * fragments which are assigned to run on local Drillbit node (or Foreman node) into separate lists.
- *
- * This will help to schedule local
+ * leaf/intermediate state, as well as their target drillbit.
*/
- final Multimap<DrillbitEndpoint, PlanFragment> remoteLeafFragmentMap = ArrayListMultimap.create();
- final List<PlanFragment> localLeafFragmentList = new ArrayList<>();
- final Multimap<DrillbitEndpoint, PlanFragment> remoteIntFragmentMap = ArrayListMultimap.create();
- final List<PlanFragment> localIntFragmentList = new ArrayList<>();
+ final Multimap<DrillbitEndpoint, PlanFragment> leafFragmentMap = ArrayListMultimap.create();
+ final Multimap<DrillbitEndpoint, PlanFragment> intFragmentMap = ArrayListMultimap.create();
- final DrillbitEndpoint localDrillbitEndpoint = drillbitContext.getEndpoint();
// record all fragments for status purposes.
for (final PlanFragment planFragment : fragments) {
@@ -180,44 +170,38 @@ public class FragmentsRunner {
foreman.getQueryManager().addFragmentStatusTracker(planFragment, false);
if (planFragment.getLeafFragment()) {
- updateFragmentCollection(planFragment, localDrillbitEndpoint, localLeafFragmentList, remoteLeafFragmentMap);
+ leafFragmentMap.put(planFragment.getAssignment(), planFragment);
} else {
- updateFragmentCollection(planFragment, localDrillbitEndpoint, localIntFragmentList, remoteIntFragmentMap);
+ intFragmentMap.put(planFragment.getAssignment(), planFragment);
}
}
/*
* We need to wait for the intermediates to be sent so that they'll be set up by the time
- * the leaves start producing data. We'll use this latch to wait for the responses.
+ * the leaves start producing data. We'll use this latch to wait for the responses. All the local intermediate
+ * fragments are submitted locally without creating any actual control connection to itself.
*
* However, in order not to hang the process if any of the RPC requests fails, we always
* count down (see FragmentSubmitFailures), but we count the number of failures so that we'll
* know if any submissions did fail.
*/
- scheduleRemoteIntermediateFragments(remoteIntFragmentMap);
-
- // Setup local intermediate fragments
- for (final PlanFragment fragment : localIntFragmentList) {
- startLocalFragment(fragment);
- }
+ scheduleIntermediateFragments(intFragmentMap);
injector.injectChecked(foreman.getQueryContext().getExecutionControls(), "send-fragments", ForemanException.class);
/*
* Send the remote (leaf) fragments; we don't wait for these. Any problems will come in through
- * the regular sendListener event delivery.
+ * the regular sendListener event delivery˚. All the local leaf fragments are submitted locally without creating
+ * any actual control connection to itself.
*/
- for (final DrillbitEndpoint ep : remoteLeafFragmentMap.keySet()) {
- sendRemoteFragments(ep, remoteLeafFragmentMap.get(ep), null, null);
- }
-
- // Setup local leaf fragments
- for (final PlanFragment fragment : localLeafFragmentList) {
- startLocalFragment(fragment);
+ for (final DrillbitEndpoint ep : leafFragmentMap.keySet()) {
+ sendRemoteFragments(ep, leafFragmentMap.get(ep), null, null);
}
}
/**
- * Send all the remote fragments belonging to a single target drillbit in one request.
+ * Send all the remote fragments belonging to a single target drillbit in one request. If the assignment
+ * DrillbitEndpoint is local Drillbit then {@link Controller#getTunnel(DrillbitEndpoint)} takes care of submitting it
+ * locally without actually creating a Control Connection to itself.
*
* @param assignment the drillbit assigned to these fragments
* @param fragments the set of fragments
@@ -241,41 +225,21 @@ public class FragmentsRunner {
}
/**
- * Add planFragment into either of local fragment list or remote fragment map based on assigned Drillbit Endpoint node
- * and the local Drillbit Endpoint.
+ * Send intermediate fragment to the assigned Drillbit node. If the assignment DrillbitEndpoint is local Drillbit
+ * then {@link Controller#getTunnel(DrillbitEndpoint)} takes care of submitting it locally without actually creating
+ * a Control Connection to itself. Throws {@link UserException} in case of failure to send the fragment.
*
- * @param planFragment plan fragment
- * @param localEndPoint local endpoint
- * @param localFragmentList local fragment list
- * @param remoteFragmentMap remote fragment map
+ * @param intermediateFragmentMap - Map of Drillbit Endpoint to list of intermediate PlanFragment's
*/
- private void updateFragmentCollection(final PlanFragment planFragment, final DrillbitEndpoint localEndPoint,
- final List<PlanFragment> localFragmentList,
- final Multimap<DrillbitEndpoint, PlanFragment> remoteFragmentMap) {
- final DrillbitEndpoint assignedDrillbit = planFragment.getAssignment();
+ private void scheduleIntermediateFragments(final Multimap<DrillbitEndpoint, PlanFragment> intermediateFragmentMap) {
- if (assignedDrillbit.equals(localEndPoint)) {
- localFragmentList.add(planFragment);
- } else {
- remoteFragmentMap.put(assignedDrillbit, planFragment);
- }
- }
-
- /**
- * Send remote intermediate fragment to the assigned Drillbit node.
- * Throw exception in case of failure to send the fragment.
- *
- * @param remoteFragmentMap - Map of Drillbit Endpoint to list of PlanFragment's
- */
- private void scheduleRemoteIntermediateFragments(final Multimap<DrillbitEndpoint, PlanFragment> remoteFragmentMap) {
-
- final int numIntFragments = remoteFragmentMap.keySet().size();
+ final int numIntFragments = intermediateFragmentMap.keySet().size();
final ExtendedLatch endpointLatch = new ExtendedLatch(numIntFragments);
final FragmentSubmitFailures fragmentSubmitFailures = new FragmentSubmitFailures();
// send remote intermediate fragments
- for (final DrillbitEndpoint ep : remoteFragmentMap.keySet()) {
- sendRemoteFragments(ep, remoteFragmentMap.get(ep), endpointLatch, fragmentSubmitFailures);
+ for (final DrillbitEndpoint ep : intermediateFragmentMap.keySet()) {
+ sendRemoteFragments(ep, intermediateFragmentMap.get(ep), endpointLatch, fragmentSubmitFailures);
}
final long timeout = drillbitContext.getOptionManager().getLong(ExecConstants.FRAG_RUNNER_RPC_TIMEOUT) * numIntFragments;
@@ -313,29 +277,6 @@ public class FragmentsRunner {
}
}
-
- /**
- * Start the locally assigned leaf or intermediate fragment
- *
- * @param fragment fragment
- */
- private void startLocalFragment(final PlanFragment fragment) throws ExecutionSetupException {
- logger.debug("Received local fragment start instruction", fragment);
-
- final FragmentContextImpl fragmentContext = new FragmentContextImpl(drillbitContext, fragment, drillbitContext.getFunctionImplementationRegistry());
- final FragmentStatusReporter statusReporter = new FragmentStatusReporter(fragmentContext);
- final FragmentExecutor fragmentExecutor = new FragmentExecutor(fragmentContext, fragment, statusReporter);
-
- // we either need to start the fragment if it is a leaf fragment, or set up a fragment manager if it is non leaf.
- if (fragment.getLeafFragment()) {
- bee.addFragmentRunner(fragmentExecutor);
- } else {
- // isIntermediate, store for incoming data.
- final NonRootFragmentManager manager = new NonRootFragmentManager(fragment, fragmentExecutor, statusReporter);
- drillbitContext.getWorkBus().addFragmentManager(manager);
- }
- }
-
/**
* Used by {@link FragmentSubmitListener} to track the number of submission failures.
*/
diff --git a/exec/java-exec/src/main/java/org/apache/drill/exec/work/fragment/FragmentStatusReporter.java b/exec/java-exec/src/main/java/org/apache/drill/exec/work/fragment/FragmentStatusReporter.java
index eb57658..c0c5b04 100644
--- a/exec/java-exec/src/main/java/org/apache/drill/exec/work/fragment/FragmentStatusReporter.java
+++ b/exec/java-exec/src/main/java/org/apache/drill/exec/work/fragment/FragmentStatusReporter.java
@@ -40,12 +40,9 @@ public class FragmentStatusReporter implements AutoCloseable {
protected final AtomicReference<DrillbitEndpoint> foremanDrillbit;
- protected final DrillbitEndpoint localDrillbit;
-
public FragmentStatusReporter(final ExecutorFragmentContext context) {
this.context = context;
this.foremanDrillbit = new AtomicReference<>(context.getForemanEndpoint());
- this.localDrillbit = context.getEndpoint();
}
/**
@@ -119,14 +116,10 @@ public class FragmentStatusReporter implements AutoCloseable {
return;
}
- if (localDrillbit.equals(foremanNode)) {
- // Update the status locally
- context.getWorkEventbus().statusUpdate(status);
- } else {
- // Send the status via Control Tunnel to remote foreman node
- final ControlTunnel tunnel = context.getController().getTunnel(foremanNode);
- tunnel.sendFragmentStatus(status);
- }
+ // Send status for both local and remote foreman node via Tunnel. For local there won't be any network connection
+ // created and it will be submitted locally using LocalControlConnectionManager
+ final ControlTunnel tunnel = context.getController().getTunnel(foremanNode);
+ tunnel.sendFragmentStatus(status);
}
/**
diff --git a/exec/java-exec/src/test/java/org/apache/drill/exec/rpc/control/ConnectionManagerRegistryTest.java b/exec/java-exec/src/test/java/org/apache/drill/exec/rpc/control/ConnectionManagerRegistryTest.java
new file mode 100644
index 0000000..667e440
--- /dev/null
+++ b/exec/java-exec/src/test/java/org/apache/drill/exec/rpc/control/ConnectionManagerRegistryTest.java
@@ -0,0 +1,149 @@
+/*
+ * 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.drill.exec.rpc.control;
+
+import org.apache.drill.exec.proto.CoordinationProtos.DrillbitEndpoint;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Mockito.mock;
+
+public class ConnectionManagerRegistryTest {
+
+ private static final DrillbitEndpoint localEndpoint = DrillbitEndpoint.newBuilder()
+ .setAddress("10.0.0.1")
+ .setControlPort(31012)
+ .setDataPort(31011)
+ .setUserPort(31010)
+ .setState(DrillbitEndpoint.State.STARTUP)
+ .build();
+
+ private static final DrillbitEndpoint foremanEndpoint = DrillbitEndpoint.newBuilder()
+ .setAddress("10.0.0.2")
+ .setControlPort(31012)
+ .setDataPort(31011)
+ .setUserPort(31010)
+ .setState(DrillbitEndpoint.State.STARTUP)
+ .build();
+
+ private static ControlConnectionConfig config;
+
+ @BeforeClass
+ public static void setup() {
+ config = mock(ControlConnectionConfig.class);
+ }
+
+ @Test
+ public void testLocalConnectionManager() {
+ final ConnectionManagerRegistry registry = new ConnectionManagerRegistry(config);
+ registry.setLocalEndpoint(localEndpoint);
+ final ControlConnectionManager manager = registry.getConnectionManager(localEndpoint);
+ assertTrue(registry.iterator().hasNext());
+ assertEquals(manager, registry.iterator().next());
+ assertTrue(manager instanceof LocalControlConnectionManager);
+ }
+
+ @Test
+ public void testLocalConnectionManager_differentState() {
+ final ConnectionManagerRegistry registry = new ConnectionManagerRegistry(config);
+ registry.setLocalEndpoint(localEndpoint);
+
+ final DrillbitEndpoint foremanEndpoint2 = localEndpoint.toBuilder().setState(DrillbitEndpoint.State.ONLINE).build();
+ final ControlConnectionManager manager = registry.getConnectionManager(foremanEndpoint2);
+ assertTrue(registry.iterator().hasNext());
+ assertEquals(manager, registry.iterator().next());
+ assertTrue(manager instanceof LocalControlConnectionManager);
+ }
+
+ @Test
+ public void testLocalConnectionManager_differentUserDataPort() {
+ final ConnectionManagerRegistry registry = new ConnectionManagerRegistry(config);
+ registry.setLocalEndpoint(localEndpoint);
+
+ final DrillbitEndpoint foremanEndpoint2 = localEndpoint.toBuilder()
+ .setState(DrillbitEndpoint.State.ONLINE)
+ .setUserPort(10000)
+ .setDataPort(11000)
+ .build();
+ final ControlConnectionManager manager = registry.getConnectionManager(foremanEndpoint2);
+ assertTrue(registry.iterator().hasNext());
+ assertEquals(manager, registry.iterator().next());
+ assertTrue(manager instanceof LocalControlConnectionManager);
+ }
+
+ @Test
+ public void testRemoteConnectionManager() {
+ final ConnectionManagerRegistry registry = new ConnectionManagerRegistry(config);
+ registry.setLocalEndpoint(localEndpoint);
+ final ControlConnectionManager manager = registry.getConnectionManager(foremanEndpoint);
+ assertTrue(registry.iterator().hasNext());
+ assertTrue(manager instanceof RemoteControlConnectionManager);
+ }
+
+ @Test
+ public void testRemoteConnectionManager_differentControlPort() {
+ final ConnectionManagerRegistry registry = new ConnectionManagerRegistry(config);
+ registry.setLocalEndpoint(localEndpoint);
+
+ final DrillbitEndpoint foremanEndpoint2 = localEndpoint.toBuilder()
+ .setControlPort(10000)
+ .build();
+ final ControlConnectionManager manager = registry.getConnectionManager(foremanEndpoint2);
+ assertTrue(registry.iterator().hasNext());
+ assertEquals(manager, registry.iterator().next());
+ assertTrue(manager instanceof RemoteControlConnectionManager);
+ }
+
+ @Test
+ public void testRemoteConnectionManager_differentAddress() {
+ final ConnectionManagerRegistry registry = new ConnectionManagerRegistry(config);
+ registry.setLocalEndpoint(localEndpoint);
+
+ final DrillbitEndpoint foremanEndpoint2 = localEndpoint.toBuilder()
+ .setAddress("10.0.0.0")
+ .build();
+ final ControlConnectionManager manager = registry.getConnectionManager(foremanEndpoint2);
+ assertTrue(registry.iterator().hasNext());
+ assertEquals(manager, registry.iterator().next());
+ assertTrue(manager instanceof RemoteControlConnectionManager);
+ }
+
+ @Test
+ public void testRemoteAndLocalConnectionManager() {
+ final ConnectionManagerRegistry registry = new ConnectionManagerRegistry(config);
+ registry.setLocalEndpoint(localEndpoint);
+
+ final DrillbitEndpoint foremanEndpoint2 = localEndpoint.toBuilder()
+ .setAddress("10.0.0.0")
+ .build();
+
+ final ControlConnectionManager remoteManager = registry.getConnectionManager(foremanEndpoint2);
+ final ControlConnectionManager localManager = registry.getConnectionManager(localEndpoint);
+
+ final ControlConnectionManager remoteManager_2 = registry.getConnectionManager(foremanEndpoint2);
+ final ControlConnectionManager localManager_2 = registry.getConnectionManager(localEndpoint);
+
+ assertTrue(remoteManager instanceof RemoteControlConnectionManager);
+ assertEquals(remoteManager, remoteManager_2);
+
+ assertTrue(localManager instanceof LocalControlConnectionManager);
+ assertEquals(localManager, localManager_2);
+ }
+}
diff --git a/exec/java-exec/src/test/java/org/apache/drill/exec/rpc/control/TestLocalControlConnectionManager.java b/exec/java-exec/src/test/java/org/apache/drill/exec/rpc/control/TestLocalControlConnectionManager.java
new file mode 100644
index 0000000..c0cf09b
--- /dev/null
+++ b/exec/java-exec/src/test/java/org/apache/drill/exec/rpc/control/TestLocalControlConnectionManager.java
@@ -0,0 +1,278 @@
+/*
+ * 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.drill.exec.rpc.control;
+
+import io.netty.buffer.ByteBuf;
+import org.apache.drill.exec.proto.BitControl;
+import org.apache.drill.exec.proto.CoordinationProtos.DrillbitEndpoint;
+import org.apache.drill.exec.proto.ExecProtos;
+import org.apache.drill.exec.proto.GeneralRPCProtos;
+import org.apache.drill.exec.proto.UserBitShared;
+import org.apache.drill.exec.rpc.Acks;
+import org.apache.drill.exec.rpc.RpcException;
+import org.apache.drill.exec.rpc.RpcOutcomeListener;
+import org.apache.drill.exec.work.batch.ControlMessageHandler;
+import org.hamcrest.Description;
+import org.hamcrest.TypeSafeMatcher;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.ExpectedException;
+
+import java.util.concurrent.CountDownLatch;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+public class TestLocalControlConnectionManager {
+
+ private static final DrillbitEndpoint localEndpoint = DrillbitEndpoint.newBuilder()
+ .setAddress("10.0.0.1")
+ .setControlPort(31011)
+ .setState(DrillbitEndpoint.State.STARTUP)
+ .build();
+
+ private static ControlConnectionConfig mockConfig;
+
+ private static ControlMessageHandler mockHandler;
+
+ private static ControlTunnel controlTunnel;
+
+ private static CountDownLatch latch;
+
+ private static final String NEGATIVE_ACK_MESSAGE = "Negative Ack received";
+
+ private static final RpcOutcomeListener<GeneralRPCProtos.Ack> outcomeListener =
+ new RpcOutcomeListener<GeneralRPCProtos.Ack>() {
+ @Override
+ public void failed(RpcException ex) {
+ throw new IllegalStateException(ex);
+ }
+
+ @Override
+ public void success(GeneralRPCProtos.Ack value, ByteBuf buffer) {
+ if (value.getOk()) {
+ latch.countDown();
+ } else {
+ throw new IllegalStateException(NEGATIVE_ACK_MESSAGE);
+ }
+ }
+
+ @Override
+ public void interrupted(InterruptedException e) {
+ // Do nothing
+ }
+ };
+
+ @Rule
+ public ExpectedException exceptionThrown = ExpectedException.none();
+
+ @BeforeClass
+ public static void setup() {
+ mockConfig = mock(ControlConnectionConfig.class);
+ final ConnectionManagerRegistry registry = new ConnectionManagerRegistry(mockConfig);
+ registry.setLocalEndpoint(localEndpoint);
+ ControlConnectionManager manager = registry.getConnectionManager(localEndpoint);
+ assertTrue(manager instanceof LocalControlConnectionManager);
+ controlTunnel = new ControlTunnel(manager);
+ }
+
+ @Before
+ public void setupForTest() {
+ mockHandler = mock(ControlMessageHandler.class);
+ when(mockConfig.getMessageHandler()).thenReturn(mockHandler);
+ }
+
+ /**
+ * Verify that SendFragmentStatus is handled correctly using ControlTunnel with LocalControlConnectionManager
+ */
+ @Test
+ public void testLocalSendFragmentStatus_Success() throws Exception {
+ final UserBitShared.QueryId mockQueryId = UserBitShared.QueryId.getDefaultInstance();
+ final UserBitShared.QueryProfile mockProfile = UserBitShared.QueryProfile.getDefaultInstance();
+ when(mockHandler.requestQueryStatus(mockQueryId)).thenReturn(mockProfile);
+ final UserBitShared.QueryProfile returnedProfile = controlTunnel.requestQueryProfile(mockQueryId).checkedGet();
+ assertEquals(returnedProfile, mockProfile);
+ }
+
+ /**
+ * Verify that SendFragmentStatus failure scenario is handled correctly using ControlTunnel with
+ * LocalControlConnectionManager
+ */
+ @Test
+ public void testLocalSendFragmentStatus_Failure() throws Exception {
+ final UserBitShared.QueryId mockQueryId = UserBitShared.QueryId.getDefaultInstance();
+ final String exceptionMessage = "Testing failure case";
+ exceptionThrown.expect(RpcException.class);
+ exceptionThrown.expectMessage(exceptionMessage);
+ when(mockHandler.requestQueryStatus(mockQueryId)).thenThrow(new RpcException(exceptionMessage));
+ controlTunnel.requestQueryProfile(mockQueryId).checkedGet();
+ }
+
+ /**
+ * Verify that CancelFragment with positive ack is handled correctly using ControlTunnel with
+ * LocalControlConnectionManager
+ */
+ @Test
+ public void testLocalCancelFragment_PositiveAck() throws Exception {
+ final ExecProtos.FragmentHandle mockHandle = ExecProtos.FragmentHandle.getDefaultInstance();
+ latch = new CountDownLatch(1);
+ final GeneralRPCProtos.Ack mockResponse = Acks.OK;
+ when(mockHandler.cancelFragment(mockHandle)).thenReturn(mockResponse);
+ controlTunnel.cancelFragment(outcomeListener, mockHandle);
+ latch.await();
+ }
+
+ /**
+ * Verify that CancelFragment with negative ack is handled correctly using ControlTunnel with
+ * LocalControlConnectionManager
+ */
+ @Test
+ public void testLocalCancelFragment_NegativeAck() throws Exception {
+ final ExecProtos.FragmentHandle mockHandle = ExecProtos.FragmentHandle.getDefaultInstance();
+ latch = new CountDownLatch(1);
+ exceptionThrown.expect(IllegalStateException.class);
+ exceptionThrown.expectMessage(NEGATIVE_ACK_MESSAGE);
+ final GeneralRPCProtos.Ack mockResponse = Acks.FAIL;
+ when(mockHandler.cancelFragment(mockHandle)).thenReturn(mockResponse);
+ controlTunnel.cancelFragment(outcomeListener, mockHandle);
+ latch.await();
+ }
+
+ /**
+ * Verify that InitializeFragments with positive ack is handled correctly using ControlTunnel with
+ * LocalControlConnectionManager
+ */
+ @Test
+ public void testLocalSendFragments_PositiveAck() throws Exception {
+ final BitControl.InitializeFragments mockFragments = BitControl.InitializeFragments.getDefaultInstance();
+ latch = new CountDownLatch(1);
+ final GeneralRPCProtos.Ack mockResponse = Acks.OK;
+ when(mockHandler.initializeFragment(mockFragments)).thenReturn(mockResponse);
+ controlTunnel.sendFragments(outcomeListener, mockFragments);
+ latch.await();
+ }
+
+ /**
+ * Verify that InitializeFragments with negative ack is handled correctly using ControlTunnel with
+ * LocalControlConnectionManager
+ */
+ @Test
+ public void testLocalSendFragments_NegativeAck() throws Exception {
+ final BitControl.InitializeFragments mockFragments = BitControl.InitializeFragments.getDefaultInstance();
+ latch = new CountDownLatch(1);
+ exceptionThrown.expect(IllegalStateException.class);
+ exceptionThrown.expectMessage(NEGATIVE_ACK_MESSAGE);
+ final GeneralRPCProtos.Ack mockResponse = Acks.FAIL;
+ when(mockHandler.initializeFragment(mockFragments)).thenReturn(mockResponse);
+ controlTunnel.sendFragments(outcomeListener, mockFragments);
+ latch.await();
+ }
+
+ /**
+ * Verify that InitializeFragments failure case is handled correctly using ControlTunnel with
+ * LocalControlConnectionManager
+ */
+ @Test
+ public void testLocalSendFragments_Failure() throws Exception {
+ final BitControl.InitializeFragments mockFragments = BitControl.InitializeFragments.getDefaultInstance();
+ latch = new CountDownLatch(1);
+ exceptionThrown.expect(IllegalStateException.class);
+ exceptionThrown.expectCause(new TypeSafeMatcher<Throwable>(RpcException.class) {
+ @Override
+ protected boolean matchesSafely(Throwable throwable) {
+ return (throwable != null && throwable instanceof RpcException);
+ }
+
+ @Override
+ public void describeTo(Description description) {
+ // Do nothing
+ }
+ });
+ when(mockHandler.initializeFragment(mockFragments)).thenThrow(new RpcException("Failed to initialize"));
+ controlTunnel.sendFragments(outcomeListener, mockFragments);
+ latch.await();
+ }
+
+ /**
+ * Verify that UnpauseFragment is handled correctly using ControlTunnel with LocalControlConnectionManager
+ */
+ @Test
+ public void testUnpauseFragments() throws Exception {
+ final ExecProtos.FragmentHandle mockHandle = ExecProtos.FragmentHandle.getDefaultInstance();
+ latch = new CountDownLatch(1);
+ final GeneralRPCProtos.Ack mockResponse = Acks.OK;
+ when(mockHandler.resumeFragment(mockHandle)).thenReturn(mockResponse);
+ controlTunnel.unpauseFragment(outcomeListener, mockHandle);
+ latch.await();
+ }
+
+ /**
+ * Verify that RequestQueryStatus is handled correctly using ControlTunnel with LocalControlConnectionManager
+ */
+ @Test
+ public void testRequestQueryStatus() throws Exception {
+ final UserBitShared.QueryId mockQueryId = UserBitShared.QueryId.getDefaultInstance();
+ final UserBitShared.QueryProfile mockProfile = UserBitShared.QueryProfile.getDefaultInstance();
+ when(mockHandler.requestQueryStatus(mockQueryId)).thenReturn(mockProfile);
+ final UserBitShared.QueryProfile returnedProfile = controlTunnel.requestQueryProfile(mockQueryId).checkedGet();
+ assertEquals(returnedProfile, mockProfile);
+ }
+
+ /**
+ * Verify that CancelQuery with positive ack is handled correctly using ControlTunnel with
+ * LocalControlConnectionManager
+ */
+ @Test
+ public void testCancelQuery_PositiveAck() throws Exception {
+ final UserBitShared.QueryId mockQueryId = UserBitShared.QueryId.getDefaultInstance();
+ final GeneralRPCProtos.Ack mockResponse = Acks.OK;
+ when(mockHandler.requestQueryCancel(mockQueryId)).thenReturn(mockResponse);
+ GeneralRPCProtos.Ack response = controlTunnel.requestCancelQuery(mockQueryId).checkedGet();
+ assertEquals(response, mockResponse);
+ }
+
+ /**
+ * Verify that CancelQuery with negative ack is handled correctly using ControlTunnel with
+ * LocalControlConnectionManager
+ */
+ @Test
+ public void testCancelQuery_NegativeAck() throws Exception {
+ final UserBitShared.QueryId mockQueryId = UserBitShared.QueryId.getDefaultInstance();
+ final GeneralRPCProtos.Ack mockResponse = Acks.FAIL;
+ when(mockHandler.requestQueryCancel(mockQueryId)).thenReturn(mockResponse);
+ GeneralRPCProtos.Ack response = controlTunnel.requestCancelQuery(mockQueryId).checkedGet();
+ assertEquals(response, mockResponse);
+ }
+
+ /**
+ * Verify that FinishedReceiver is handled correctly using ControlTunnel with LocalControlConnectionManager
+ */
+ @Test
+ public void testInformReceiverFinished_success() throws Exception {
+ final BitControl.FinishedReceiver finishedReceiver = BitControl.FinishedReceiver.getDefaultInstance();
+ latch = new CountDownLatch(1);
+ final GeneralRPCProtos.Ack mockResponse = Acks.OK;
+ when(mockHandler.receivingFragmentFinished(finishedReceiver)).thenReturn(mockResponse);
+ controlTunnel.informReceiverFinished(outcomeListener, finishedReceiver);
+ latch.await();
+ }
+}
diff --git a/exec/java-exec/src/test/java/org/apache/drill/exec/rpc/user/security/TestUserBitKerberos.java b/exec/java-exec/src/test/java/org/apache/drill/exec/rpc/user/security/TestUserBitKerberos.java
index aaff154..04d54d5 100644
--- a/exec/java-exec/src/test/java/org/apache/drill/exec/rpc/user/security/TestUserBitKerberos.java
+++ b/exec/java-exec/src/test/java/org/apache/drill/exec/rpc/user/security/TestUserBitKerberos.java
@@ -19,16 +19,16 @@ package org.apache.drill.exec.rpc.user.security;
import com.google.common.collect.Lists;
import com.typesafe.config.ConfigValueFactory;
-import org.apache.drill.test.BaseTestQuery;
import org.apache.drill.categories.SecurityTest;
-import org.apache.drill.common.config.DrillProperties;
import org.apache.drill.common.config.DrillConfig;
+import org.apache.drill.common.config.DrillProperties;
import org.apache.drill.exec.ExecConstants;
import org.apache.drill.exec.rpc.control.ControlRpcMetrics;
import org.apache.drill.exec.rpc.data.DataRpcMetrics;
import org.apache.drill.exec.rpc.security.KerberosHelper;
import org.apache.drill.exec.rpc.user.UserRpcMetrics;
import org.apache.drill.exec.rpc.user.security.testing.UserAuthenticatorTestImpl;
+import org.apache.drill.test.BaseTestQuery;
import org.apache.hadoop.security.authentication.util.KerberosName;
import org.apache.hadoop.security.authentication.util.KerberosUtil;
import org.apache.kerby.kerberos.kerb.client.JaasKrbUtil;
@@ -178,6 +178,38 @@ public class TestUserBitKerberos extends BaseTestQuery {
assertTrue(0 == DataRpcMetrics.getInstance().getUnEncryptedConnectionCount());
}
+ @Test
+ public void testUnecryptedConnectionCounter_LocalControlMessage() throws Exception {
+ final Properties connectionProps = new Properties();
+ connectionProps.setProperty(DrillProperties.SERVICE_PRINCIPAL, krbHelper.SERVER_PRINCIPAL);
+ connectionProps.setProperty(DrillProperties.KERBEROS_FROM_SUBJECT, "true");
+ final Subject clientSubject = JaasKrbUtil.loginUsingKeytab(krbHelper.CLIENT_PRINCIPAL,
+ krbHelper.clientKeytab.getAbsoluteFile());
+
+ Subject.doAs(clientSubject, new PrivilegedExceptionAction<Void>() {
+ @Override
+ public Void run() throws Exception {
+ updateClient(connectionProps);
+ return null;
+ }
+ });
+
+ // Run query on memory system table this sends remote fragments to all Drillbit and Drillbits then send data
+ // using data channel. In this test we have only 1 Drillbit so there should not be any control connection but a
+ // local data connections
+ testSql("SELECT * FROM sys.memory");
+
+ // Check encrypted counters value
+ assertTrue(0 == UserRpcMetrics.getInstance().getEncryptedConnectionCount());
+ assertTrue(0 == ControlRpcMetrics.getInstance().getEncryptedConnectionCount());
+ assertTrue(0 == DataRpcMetrics.getInstance().getEncryptedConnectionCount());
+
+ // Check unencrypted counters value
+ assertTrue(1 == UserRpcMetrics.getInstance().getUnEncryptedConnectionCount());
+ assertTrue(0 == ControlRpcMetrics.getInstance().getUnEncryptedConnectionCount());
+ assertTrue(2 == DataRpcMetrics.getInstance().getUnEncryptedConnectionCount());
+ }
+
@AfterClass
public static void cleanTest() throws Exception {
krbHelper.stopKdc();
diff --git a/exec/java-exec/src/test/java/org/apache/drill/exec/work/fragment/FragmentStatusReporterTest.java b/exec/java-exec/src/test/java/org/apache/drill/exec/work/fragment/FragmentStatusReporterTest.java
index 83c1eca..a119a8c 100644
--- a/exec/java-exec/src/test/java/org/apache/drill/exec/work/fragment/FragmentStatusReporterTest.java
+++ b/exec/java-exec/src/test/java/org/apache/drill/exec/work/fragment/FragmentStatusReporterTest.java
@@ -17,54 +17,44 @@
*/
package org.apache.drill.exec.work.fragment;
-import org.apache.drill.exec.proto.CoordinationProtos.DrillbitEndpoint;
-import org.apache.drill.exec.rpc.control.Controller;
-import org.apache.drill.exec.rpc.control.WorkEventBus;
-import org.junit.Before;
-import org.junit.Test;
-
import org.apache.drill.exec.memory.BufferAllocator;
import org.apache.drill.exec.ops.FragmentContextImpl;
import org.apache.drill.exec.ops.FragmentStats;
import org.apache.drill.exec.proto.BitControl.FragmentStatus;
+import org.apache.drill.exec.proto.CoordinationProtos.DrillbitEndpoint;
import org.apache.drill.exec.proto.ExecProtos.FragmentHandle;
import org.apache.drill.exec.proto.UserBitShared.FragmentState;
import org.apache.drill.exec.rpc.control.ControlTunnel;
+import org.apache.drill.exec.rpc.control.Controller;
+import org.junit.Before;
+import org.junit.Test;
-import static org.junit.Assert.assertTrue;
+import static org.apache.drill.exec.proto.UserBitShared.FragmentState.CANCELLATION_REQUESTED;
+import static org.apache.drill.exec.proto.UserBitShared.FragmentState.FAILED;
+import static org.apache.drill.exec.proto.UserBitShared.FragmentState.RUNNING;
import static org.junit.Assert.fail;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
-import static org.apache.drill.exec.proto.UserBitShared.FragmentState.CANCELLATION_REQUESTED;
-import static org.apache.drill.exec.proto.UserBitShared.FragmentState.FAILED;
-import static org.apache.drill.exec.proto.UserBitShared.FragmentState.RUNNING;
-
public class FragmentStatusReporterTest {
private FragmentStatusReporter statusReporter;
private ControlTunnel foremanTunnel;
- private FragmentContextImpl context;
-
@Before
public void setUp() throws Exception {
- context = mock(FragmentContextImpl.class);
+ final FragmentContextImpl context = mock(FragmentContextImpl.class);
Controller controller = mock(Controller.class);
- // Create 2 different endpoint such that foremanEndpoint is different than
- // localEndpoint
- DrillbitEndpoint localEndpoint = DrillbitEndpoint.newBuilder().setAddress("10.0.0.1").build();
+ // Create Foreman Endpoint and it's tunnel
DrillbitEndpoint foremanEndpoint = DrillbitEndpoint.newBuilder().setAddress("10.0.0.2").build();
foremanTunnel = mock(ControlTunnel.class);
- when(context.getEndpoint()).thenReturn(localEndpoint);
when(context.getController()).thenReturn(controller);
when(controller.getTunnel(foremanEndpoint)).thenReturn(foremanTunnel);
@@ -120,49 +110,4 @@ public class FragmentStatusReporterTest {
statusReporter.stateChanged(CANCELLATION_REQUESTED);
verify(foremanTunnel).sendFragmentStatus(any(FragmentStatus.class));
}
-
-
- /**
- * With LocalEndpoint and Foreman Endpoint being same node, test that status change
- * message doesn't happen via Control Tunnel instead it happens locally via WorkEventBus
- *
- * @throws Exception
- */
- @Test
- public void testStateChangedLocalForeman() throws Exception {
-
- DrillbitEndpoint localEndpoint = DrillbitEndpoint.newBuilder().setAddress("10.0.0.1").build();
-
- when(context.getEndpoint()).thenReturn(localEndpoint);
- when(context.getForemanEndpoint()).thenReturn(localEndpoint);
- when(context.getWorkEventbus()).thenReturn(mock(WorkEventBus.class));
-
- statusReporter = new FragmentStatusReporter(context);
- statusReporter.stateChanged(RUNNING);
- verifyZeroInteractions(foremanTunnel);
- verify(context.getWorkEventbus()).statusUpdate(any(FragmentStatus.class));
- }
-
- /**
- * With LocalEndpoint and Foreman Endpoint being same node, test that after close of
- * FragmentStatusReporter, status update doesn't happen either through Control Tunnel
- * or through WorkEventBus.
- *
- * @throws Exception
- */
- @Test
- public void testCloseLocalForeman() throws Exception {
- DrillbitEndpoint localEndpoint = DrillbitEndpoint.newBuilder().setAddress("10.0.0.1").build();
-
- when(context.getEndpoint()).thenReturn(localEndpoint);
- when(context.getForemanEndpoint()).thenReturn(localEndpoint);
- when(context.getWorkEventbus()).thenReturn(mock(WorkEventBus.class));
- statusReporter = new FragmentStatusReporter(context);
-
- statusReporter.close();
- assertTrue(statusReporter.foremanDrillbit.get() == null);
- statusReporter.stateChanged(RUNNING);
- verifyZeroInteractions(foremanTunnel);
- verify(context.getWorkEventbus(), never()).statusUpdate(any(FragmentStatus.class));
- }
}
diff --git a/exec/rpc/src/main/java/org/apache/drill/exec/rpc/FutureBitCommand.java b/exec/rpc/src/main/java/org/apache/drill/exec/rpc/FutureBitCommand.java
index 90b2d19..2437ddb 100644
--- a/exec/rpc/src/main/java/org/apache/drill/exec/rpc/FutureBitCommand.java
+++ b/exec/rpc/src/main/java/org/apache/drill/exec/rpc/FutureBitCommand.java
@@ -17,20 +17,24 @@
*/
package org.apache.drill.exec.rpc;
-import io.netty.buffer.ByteBuf;
-
import com.google.common.util.concurrent.SettableFuture;
+import com.google.protobuf.Internal.EnumLite;
import com.google.protobuf.MessageLite;
+import io.netty.buffer.ByteBuf;
-public abstract class FutureBitCommand<T extends MessageLite, C extends RemoteConnection> implements RpcCommand<T,C> {
+public abstract class FutureBitCommand<T extends MessageLite, C extends RemoteConnection,
+ E extends EnumLite, M extends MessageLite> implements RpcCommand<T, C, E, M> {
static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(FutureBitCommand.class);
protected final SettableFuture<T> settableFuture;
private final RpcCheckedFuture<T> parentFuture;
+ private final RpcOutcomeListener<T> outcomeListener;
+
public FutureBitCommand() {
this.settableFuture = SettableFuture.create();
this.parentFuture = new RpcCheckedFuture<T>(settableFuture);
+ outcomeListener = new DeferredRpcOutcome();
}
public abstract void doRpcCall(RpcOutcomeListener<T> outcomeListener, C connection);
@@ -38,7 +42,7 @@ public abstract class FutureBitCommand<T extends MessageLite, C extends RemoteCo
@Override
public void connectionAvailable(C connection) {
- doRpcCall(new DeferredRpcOutcome(), connection);
+ doRpcCall(outcomeListener, connection);
}
@Override
@@ -72,9 +76,13 @@ public abstract class FutureBitCommand<T extends MessageLite, C extends RemoteCo
}
@Override
+ public RpcOutcomeListener<T> getOutcomeListener() {
+ return outcomeListener;
+ }
+
+ @Override
public void connectionFailed(FailureType type, Throwable t) {
settableFuture.setException(RpcException.mapException(
String.format("Command failed while establishing connection. Failure type %s.", type), t));
}
-
-}
\ No newline at end of file
+}
diff --git a/exec/rpc/src/main/java/org/apache/drill/exec/rpc/ListeningCommand.java b/exec/rpc/src/main/java/org/apache/drill/exec/rpc/ListeningCommand.java
index c9b8b3a..964abf4 100644
--- a/exec/rpc/src/main/java/org/apache/drill/exec/rpc/ListeningCommand.java
+++ b/exec/rpc/src/main/java/org/apache/drill/exec/rpc/ListeningCommand.java
@@ -17,11 +17,11 @@
*/
package org.apache.drill.exec.rpc;
-import io.netty.buffer.ByteBuf;
-
+import com.google.protobuf.Internal.EnumLite;
import com.google.protobuf.MessageLite;
-public abstract class ListeningCommand<T extends MessageLite, C extends RemoteConnection> implements RpcCommand<T, C> {
+public abstract class ListeningCommand<T extends MessageLite, C extends RemoteConnection,
+ E extends EnumLite, M extends MessageLite> implements RpcCommand<T, C, E, M> {
static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(ListeningCommand.class);
private final RpcOutcomeListener<T> listener;
@@ -35,7 +35,7 @@ public abstract class ListeningCommand<T extends MessageLite, C extends RemoteCo
@Override
public void connectionAvailable(C connection) {
- doRpcCall(new DeferredRpcOutcome(), connection);
+ doRpcCall(listener, connection);
}
@Override
@@ -43,28 +43,15 @@ public abstract class ListeningCommand<T extends MessageLite, C extends RemoteCo
connectionAvailable(connection);
}
- private class DeferredRpcOutcome implements RpcOutcomeListener<T> {
-
- @Override
- public void failed(RpcException ex) {
- listener.failed(ex);
- }
-
- @Override
- public void success(T value, ByteBuf buf) {
- listener.success(value, buf);
- }
-
- @Override
- public void interrupted(final InterruptedException e) {
- listener.interrupted(e);
- }
- }
-
@Override
public void connectionFailed(FailureType type, Throwable t) {
listener.failed(RpcException.mapException(
String.format("Command failed while establishing connection. Failure type %s.", type), t));
}
-}
\ No newline at end of file
+ @Override
+ public RpcOutcomeListener<T> getOutcomeListener() {
+ return listener;
+ }
+
+}
diff --git a/exec/rpc/src/main/java/org/apache/drill/exec/rpc/ReconnectingConnection.java b/exec/rpc/src/main/java/org/apache/drill/exec/rpc/ReconnectingConnection.java
index fec3962..c648a16 100644
--- a/exec/rpc/src/main/java/org/apache/drill/exec/rpc/ReconnectingConnection.java
+++ b/exec/rpc/src/main/java/org/apache/drill/exec/rpc/ReconnectingConnection.java
@@ -17,6 +17,7 @@
*/
package org.apache.drill.exec.rpc;
+import com.google.protobuf.Internal.EnumLite;
import io.netty.channel.ChannelFuture;
import io.netty.util.concurrent.GenericFutureListener;
@@ -52,7 +53,8 @@ public abstract class ReconnectingConnection<C extends ClientConnection, HS exte
protected abstract BasicClient<?, C, HS, ?> getNewClient();
- public <T extends MessageLite, R extends RpcCommand<T, C>> void runCommand(R cmd) {
+ public <T extends MessageLite, E extends EnumLite, M extends MessageLite,
+ R extends RpcCommand<T, C, E, M>> void runCommand(R cmd) {
// if(logger.isDebugEnabled()) logger.debug(String.format("Running command %s sending to host %s:%d", cmd, host, port));
C connection = connectionHolder.get();
if (connection != null) {
@@ -78,7 +80,7 @@ public abstract class ReconnectingConnection<C extends ClientConnection, HS exte
} else {
// logger.debug("No connection active, opening client connection.");
BasicClient<?, C, HS, ?> client = getNewClient();
- ConnectionListeningFuture<T> future = new ConnectionListeningFuture<>(cmd);
+ ConnectionListeningFuture<T,E,M> future = new ConnectionListeningFuture<>(cmd);
client.connectAsClient(future, handshake, host, port);
future.waitAndRun();
// logger.debug("Connection available and active, command now being run inline.");
@@ -88,13 +90,13 @@ public abstract class ReconnectingConnection<C extends ClientConnection, HS exte
}
}
- public class ConnectionListeningFuture<R extends MessageLite>
+ public class ConnectionListeningFuture<R extends MessageLite, E extends EnumLite, M extends MessageLite>
extends AbstractFuture<C>
implements RpcConnectionHandler<C> {
- private RpcCommand<R, C> cmd;
+ private RpcCommand<R, C, E, M> cmd;
- public ConnectionListeningFuture(RpcCommand<R, C> cmd) {
+ public ConnectionListeningFuture(RpcCommand<R, C, E, M> cmd) {
super();
this.cmd = cmd;
}
@@ -173,9 +175,7 @@ public abstract class ReconnectingConnection<C extends ClientConnection, HS exte
incoming.getChannel().close();
}
set(connection);
-
}
-
}
/** Factory for close handlers **/
@@ -204,7 +204,6 @@ public abstract class ReconnectingConnection<C extends ClientConnection, HS exte
connectionHolder.compareAndSet(connection, null);
parent.operationComplete(future);
}
-
}
public CloseHandlerCreator getCloseHandlerCreator() {
@@ -223,5 +222,4 @@ public abstract class ReconnectingConnection<C extends ClientConnection, HS exte
c.getChannel().close();
}
}
-
}
diff --git a/exec/rpc/src/main/java/org/apache/drill/exec/rpc/RpcCommand.java b/exec/rpc/src/main/java/org/apache/drill/exec/rpc/RpcCommand.java
index 1bb39ac..821b8fb 100644
--- a/exec/rpc/src/main/java/org/apache/drill/exec/rpc/RpcCommand.java
+++ b/exec/rpc/src/main/java/org/apache/drill/exec/rpc/RpcCommand.java
@@ -17,10 +17,17 @@
*/
package org.apache.drill.exec.rpc;
+import com.google.protobuf.Internal.EnumLite;
import com.google.protobuf.MessageLite;
-public interface RpcCommand<T extends MessageLite, C extends RemoteConnection> extends RpcConnectionHandler<C>{
+public interface RpcCommand<T extends MessageLite, C extends RemoteConnection,
+ E extends EnumLite, M extends MessageLite> extends RpcConnectionHandler<C> {
- public abstract void connectionAvailable(C connection);
+ void connectionAvailable(C connection);
-}
\ No newline at end of file
+ E getRpcType();
+
+ M getMessage();
+
+ RpcOutcomeListener<T> getOutcomeListener();
+}
--
To stop receiving notification emails like this one, please contact
arina@apache.org.
[drill] 08/08: DRILL-4525: Code cleanup
Posted by ar...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
arina pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/drill.git
commit f4f4dc54520e33f0b880334ff97a8a55078e9d1c
Author: Bohdan Kazydub <bo...@gmail.com>
AuthorDate: Thu May 17 13:08:31 2018 +0300
DRILL-4525: Code cleanup
- Fixed failing test
closes #1268
---
.../sql/DrillCalciteSqlBetweenOperatorWrapper.java | 28 ++++++---------
.../drill/exec/planner/sql/DrillOperatorTable.java | 41 +++++++++++-----------
.../drill/TestFunctionsWithTypeExpoQueries.java | 29 +++++++--------
3 files changed, 46 insertions(+), 52 deletions(-)
diff --git a/exec/java-exec/src/main/java/org/apache/drill/exec/planner/sql/DrillCalciteSqlBetweenOperatorWrapper.java b/exec/java-exec/src/main/java/org/apache/drill/exec/planner/sql/DrillCalciteSqlBetweenOperatorWrapper.java
index e26da95..f112e57 100644
--- a/exec/java-exec/src/main/java/org/apache/drill/exec/planner/sql/DrillCalciteSqlBetweenOperatorWrapper.java
+++ b/exec/java-exec/src/main/java/org/apache/drill/exec/planner/sql/DrillCalciteSqlBetweenOperatorWrapper.java
@@ -1,4 +1,4 @@
-/**
+/*
* 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
@@ -17,18 +17,14 @@
*/
package org.apache.drill.exec.planner.sql;
-import com.google.common.collect.Lists;
-
-import org.apache.calcite.rel.type.RelDataType;
import org.apache.calcite.sql.fun.SqlBetweenOperator;
import org.apache.calcite.sql.SqlCallBinding;
import org.apache.calcite.sql.SqlOperator;
-import org.apache.calcite.sql.type.SqlTypeName;
-import org.apache.calcite.sql.type.SqlTypeUtil;
import org.apache.drill.common.types.TypeProtos;
import org.apache.drill.exec.resolver.TypeCastRules;
+import java.util.ArrayList;
import java.util.List;
/**
@@ -55,26 +51,24 @@ public class DrillCalciteSqlBetweenOperatorWrapper extends SqlBetweenOperator im
}
/**
- *
- * Since Calcite has its rule for type compatibility (see {@link SqlTypeUtil#isComparable(RelDataType, RelDataType)}),
- * which is usually different from Drill's, this method is overridden here to avoid Calcite early terminating the
- * queries.
+ * Since Calcite has its rule for type compatibility
+ * (see {@link org.apache.calcite.sql.type.SqlTypeUtil#isComparable(org.apache.calcite.rel.type.RelDataType,
+ * org.apache.calcite.rel.type.RelDataType)}), which is usually different from Drill's, this method is overridden here to avoid
+ * Calcite early terminating the queries.
*/
@Override
- public boolean checkOperandTypes(
- SqlCallBinding callBinding,
- boolean throwOnFailure) {
- final List<TypeProtos.MinorType> types = Lists.newArrayList();
- for(int i = 0; i < callBinding.getOperandCount(); ++i) {
+ public boolean checkOperandTypes(SqlCallBinding callBinding, boolean throwOnFailure) {
+ final List<TypeProtos.MinorType> types = new ArrayList<>();
+ for (int i = 0; i < callBinding.getOperandCount(); i++) {
final TypeProtos.MinorType inMinorType = TypeInferenceUtils.getDrillTypeFromCalciteType(callBinding.getOperandType(i));
- if(inMinorType == TypeProtos.MinorType.LATE) {
+ if (inMinorType == TypeProtos.MinorType.LATE) {
return true;
}
types.add(inMinorType);
}
final boolean isCompatible = TypeCastRules.getLeastRestrictiveType(types) != null;
- if(!isCompatible && throwOnFailure) {
+ if (!isCompatible && throwOnFailure) {
throw callBinding.newValidationSignatureError();
}
return isCompatible;
diff --git a/exec/java-exec/src/main/java/org/apache/drill/exec/planner/sql/DrillOperatorTable.java b/exec/java-exec/src/main/java/org/apache/drill/exec/planner/sql/DrillOperatorTable.java
index d533c19..aea73d8 100644
--- a/exec/java-exec/src/main/java/org/apache/drill/exec/planner/sql/DrillOperatorTable.java
+++ b/exec/java-exec/src/main/java/org/apache/drill/exec/planner/sql/DrillOperatorTable.java
@@ -44,7 +44,6 @@ import java.util.Map;
* {@link #inner SqlStdOperatorTable}, and Drill User Defined Functions.
*/
public class DrillOperatorTable extends SqlStdOperatorTable {
-// private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(DrillOperatorTable.class);
private static final SqlOperatorTable inner = SqlStdOperatorTable.instance();
private final List<SqlOperator> calciteOperators = Lists.newArrayList();
private final List<SqlOperator> drillOperatorsWithoutInference = Lists.newArrayList();
@@ -102,8 +101,8 @@ public class DrillOperatorTable extends SqlStdOperatorTable {
@Override
public void lookupOperatorOverloads(SqlIdentifier opName, SqlFunctionCategory category,
- SqlSyntax syntax, List<SqlOperator> operatorList) {
- if(isInferenceEnabled()) {
+ SqlSyntax syntax, List<SqlOperator> operatorList) {
+ if (isInferenceEnabled()) {
populateFromTypeInference(opName, category, syntax, operatorList);
} else {
populateFromWithoutTypeInference(opName, category, syntax, operatorList);
@@ -111,12 +110,12 @@ public class DrillOperatorTable extends SqlStdOperatorTable {
}
private void populateFromTypeInference(SqlIdentifier opName, SqlFunctionCategory category,
- SqlSyntax syntax, List<SqlOperator> operatorList) {
+ SqlSyntax syntax, List<SqlOperator> operatorList) {
final List<SqlOperator> calciteOperatorList = Lists.newArrayList();
inner.lookupOperatorOverloads(opName, category, syntax, calciteOperatorList);
- if(!calciteOperatorList.isEmpty()) {
- for(SqlOperator calciteOperator : calciteOperatorList) {
- if(calciteToWrapper.containsKey(calciteOperator)) {
+ if (!calciteOperatorList.isEmpty()) {
+ for (SqlOperator calciteOperator : calciteOperatorList) {
+ if (calciteToWrapper.containsKey(calciteOperator)) {
operatorList.add(calciteToWrapper.get(calciteOperator));
} else {
operatorList.add(calciteOperator);
@@ -134,7 +133,7 @@ public class DrillOperatorTable extends SqlStdOperatorTable {
}
private void populateFromWithoutTypeInference(SqlIdentifier opName, SqlFunctionCategory category,
- SqlSyntax syntax, List<SqlOperator> operatorList) {
+ SqlSyntax syntax, List<SqlOperator> operatorList) {
inner.lookupOperatorOverloads(opName, category, syntax, operatorList);
if (operatorList.isEmpty() && (syntax == SqlSyntax.FUNCTION || syntax == SqlSyntax.FUNCTION_ID) && opName.isSimple()) {
List<SqlOperator> drillOps = drillOperatorsWithoutInferenceMap.get(opName.getSimple().toLowerCase());
@@ -148,7 +147,7 @@ public class DrillOperatorTable extends SqlStdOperatorTable {
public List<SqlOperator> getOperatorList() {
final List<SqlOperator> sqlOperators = Lists.newArrayList();
sqlOperators.addAll(calciteOperators);
- if(isInferenceEnabled()) {
+ if (isInferenceEnabled()) {
sqlOperators.addAll(drillOperatorsWithInference);
} else {
sqlOperators.addAll(drillOperatorsWithoutInference);
@@ -159,7 +158,7 @@ public class DrillOperatorTable extends SqlStdOperatorTable {
// Get the list of SqlOperator's with the given name.
public List<SqlOperator> getSqlOperator(String name) {
- if(isInferenceEnabled()) {
+ if (isInferenceEnabled()) {
return drillOperatorsWithInferenceMap.get(name.toLowerCase());
} else {
return drillOperatorsWithoutInferenceMap.get(name.toLowerCase());
@@ -167,15 +166,15 @@ public class DrillOperatorTable extends SqlStdOperatorTable {
}
private void populateWrappedCalciteOperators() {
- for(SqlOperator calciteOperator : inner.getOperatorList()) {
+ for (SqlOperator calciteOperator : inner.getOperatorList()) {
final SqlOperator wrapper;
- if(calciteOperator instanceof SqlAggFunction) {
+ if (calciteOperator instanceof SqlAggFunction) {
wrapper = new DrillCalciteSqlAggFunctionWrapper((SqlAggFunction) calciteOperator,
getFunctionListWithInference(calciteOperator.getName()));
- } else if(calciteOperator instanceof SqlFunction) {
+ } else if (calciteOperator instanceof SqlFunction) {
wrapper = new DrillCalciteSqlFunctionWrapper((SqlFunction) calciteOperator,
getFunctionListWithInference(calciteOperator.getName()));
- } else if(calciteOperator instanceof SqlBetweenOperator) {
+ } else if (calciteOperator instanceof SqlBetweenOperator) {
// During the procedure of converting to RexNode,
// StandardConvertletTable.convertBetween expects the SqlOperator to be a subclass of SqlBetweenOperator
final SqlBetweenOperator sqlBetweenOperator = (SqlBetweenOperator) calciteOperator;
@@ -184,14 +183,14 @@ public class DrillOperatorTable extends SqlStdOperatorTable {
final String drillOpName;
// For UNARY_MINUS (-) or UNARY_PLUS (+), we do not rename them as function_add or function_subtract.
// Otherwise, Calcite will mix them up with binary operator subtract (-) or add (+)
- if(calciteOperator == SqlStdOperatorTable.UNARY_MINUS || calciteOperator == SqlStdOperatorTable.UNARY_PLUS) {
+ if (calciteOperator == SqlStdOperatorTable.UNARY_MINUS || calciteOperator == SqlStdOperatorTable.UNARY_PLUS) {
drillOpName = calciteOperator.getName();
} else {
drillOpName = FunctionCallFactory.replaceOpWithFuncName(calciteOperator.getName());
}
final List<DrillFuncHolder> drillFuncHolders = getFunctionListWithInference(drillOpName);
- if(drillFuncHolders.isEmpty()) {
+ if (drillFuncHolders.isEmpty()) {
continue;
}
@@ -203,17 +202,17 @@ public class DrillOperatorTable extends SqlStdOperatorTable {
private List<DrillFuncHolder> getFunctionListWithInference(String name) {
final List<DrillFuncHolder> functions = Lists.newArrayList();
- for(SqlOperator sqlOperator : drillOperatorsWithInferenceMap.get(name.toLowerCase())) {
- if(sqlOperator instanceof DrillSqlOperator) {
+ for (SqlOperator sqlOperator : drillOperatorsWithInferenceMap.get(name.toLowerCase())) {
+ if (sqlOperator instanceof DrillSqlOperator) {
final List<DrillFuncHolder> list = ((DrillSqlOperator) sqlOperator).getFunctions();
- if(list != null) {
+ if (list != null) {
functions.addAll(list);
}
}
- if(sqlOperator instanceof DrillSqlAggOperator) {
+ if (sqlOperator instanceof DrillSqlAggOperator) {
final List<DrillFuncHolder> list = ((DrillSqlAggOperator) sqlOperator).getFunctions();
- if(list != null) {
+ if (list != null) {
functions.addAll(list);
}
}
diff --git a/exec/java-exec/src/test/java/org/apache/drill/TestFunctionsWithTypeExpoQueries.java b/exec/java-exec/src/test/java/org/apache/drill/TestFunctionsWithTypeExpoQueries.java
index 74676de..1f30e24 100644
--- a/exec/java-exec/src/test/java/org/apache/drill/TestFunctionsWithTypeExpoQueries.java
+++ b/exec/java-exec/src/test/java/org/apache/drill/TestFunctionsWithTypeExpoQueries.java
@@ -31,6 +31,7 @@ import org.junit.Test;
import org.junit.experimental.categories.Category;
import java.nio.file.Paths;
+import java.util.ArrayList;
import java.util.List;
@Category(SqlFunctionTest.class)
@@ -412,9 +413,9 @@ public class TestFunctionsWithTypeExpoQueries extends BaseTestQuery {
final List<Pair<SchemaPath, TypeProtos.MajorType>> expectedSchema = Lists.newArrayList();
final TypeProtos.MajorType majorType = TypeProtos.MajorType.newBuilder()
- .setMinorType(TypeProtos.MinorType.TIMESTAMP)
- .setMode(TypeProtos.DataMode.REQUIRED)
- .build();
+ .setMinorType(TypeProtos.MinorType.TIMESTAMP)
+ .setMode(TypeProtos.DataMode.REQUIRED)
+ .build();
expectedSchema.add(Pair.of(SchemaPath.getSimplePath("col"), majorType));
testBuilder()
@@ -546,19 +547,19 @@ public class TestFunctionsWithTypeExpoQueries extends BaseTestQuery {
final List<Pair<SchemaPath, TypeProtos.MajorType>> expectedSchema = Lists.newArrayList();
final TypeProtos.MajorType majorType1 = TypeProtos.MajorType.newBuilder()
- .setMinorType(TypeProtos.MinorType.BIGINT)
- .setMode(TypeProtos.DataMode.OPTIONAL)
- .build();
+ .setMinorType(TypeProtos.MinorType.BIGINT)
+ .setMode(TypeProtos.DataMode.OPTIONAL)
+ .build();
final TypeProtos.MajorType majorType2 = TypeProtos.MajorType.newBuilder()
- .setMinorType(TypeProtos.MinorType.FLOAT8)
- .setMode(TypeProtos.DataMode.OPTIONAL)
- .build();
+ .setMinorType(TypeProtos.MinorType.FLOAT8)
+ .setMode(TypeProtos.DataMode.OPTIONAL)
+ .build();
final TypeProtos.MajorType majorType3 = TypeProtos.MajorType.newBuilder()
- .setMinorType(TypeProtos.MinorType.BIGINT)
- .setMode(TypeProtos.DataMode.REQUIRED)
- .build();
+ .setMinorType(TypeProtos.MinorType.BIGINT)
+ .setMode(TypeProtos.DataMode.REQUIRED)
+ .build();
expectedSchema.add(Pair.of(SchemaPath.getSimplePath("col1"), majorType1));
expectedSchema.add(Pair.of(SchemaPath.getSimplePath("col2"), majorType2));
expectedSchema.add(Pair.of(SchemaPath.getSimplePath("col3"), majorType3));
@@ -753,7 +754,7 @@ public class TestFunctionsWithTypeExpoQueries extends BaseTestQuery {
.setMode(TypeProtos.DataMode.REQUIRED)
.build();
- final List<Pair<SchemaPath, TypeProtos.MajorType>> expectedSchema = Lists.newArrayList();
+ final List<Pair<SchemaPath, TypeProtos.MajorType>> expectedSchema = new ArrayList<>();
expectedSchema.add(Pair.of(SchemaPath.getSimplePath("col"), majorType));
testBuilder()
@@ -775,7 +776,7 @@ public class TestFunctionsWithTypeExpoQueries extends BaseTestQuery {
.setMode(TypeProtos.DataMode.OPTIONAL)
.build();
- final List<Pair<SchemaPath, TypeProtos.MajorType>> expectedSchema = Lists.newArrayList();
+ final List<Pair<SchemaPath, TypeProtos.MajorType>> expectedSchema = new ArrayList<>();
expectedSchema.add(Pair.of(SchemaPath.getSimplePath("col"), majorType));
testBuilder()
--
To stop receiving notification emails like this one, please contact
arina@apache.org.
[drill] 06/08: DRILL-6424: Updating FasterXML Jackson libraries
Posted by ar...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
arina pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/drill.git
commit 1cd6ee8a04255049393492e5d4babdcad9d1c1e6
Author: Vitalii Diravka <vi...@gmail.com>
AuthorDate: Thu May 17 12:59:08 2018 +0300
DRILL-6424: Updating FasterXML Jackson libraries
closes #1274
---
contrib/storage-hive/hive-exec-shade/pom.xml | 19 --
.../exec/store/easy/json/JsonRecordWriter.java | 4 +-
.../exec/store/parquet/metadata/Metadata.java | 10 +-
.../apache/drill/common/logical/data/Sequence.java | 192 ---------------------
.../data/visitors/AbstractLogicalVisitor.java | 6 -
.../logical/data/visitors/LogicalVisitor.java | 3 -
pom.xml | 4 +-
7 files changed, 9 insertions(+), 229 deletions(-)
diff --git a/contrib/storage-hive/hive-exec-shade/pom.xml b/contrib/storage-hive/hive-exec-shade/pom.xml
index ad572ef..6f511ad 100644
--- a/contrib/storage-hive/hive-exec-shade/pom.xml
+++ b/contrib/storage-hive/hive-exec-shade/pom.xml
@@ -167,23 +167,4 @@
</plugin>
</plugins>
</build>
- <profiles>
- <profile>
- <id>mapr</id>
- <properties>
- <!-- TODO: MapR Hive 2.1 client version libraries use older jackson libraries than Hive 2.3 client.
- It can be removed after updating onto 2.3 version -->
- <jackson.databind.mapr.hive.version>2.4.2</jackson.databind.mapr.hive.version>
- </properties>
- <dependencyManagement>
- <dependencies>
- <dependency>
- <groupId>com.fasterxml.jackson.core</groupId>
- <artifactId>jackson-databind</artifactId>
- <version>${jackson.databind.mapr.hive.version}</version>
- </dependency>
- </dependencies>
- </dependencyManagement>
- </profile>
- </profiles>
</project>
diff --git a/exec/java-exec/src/main/java/org/apache/drill/exec/store/easy/json/JsonRecordWriter.java b/exec/java-exec/src/main/java/org/apache/drill/exec/store/easy/json/JsonRecordWriter.java
index b350d57..bd81578 100644
--- a/exec/java-exec/src/main/java/org/apache/drill/exec/store/easy/json/JsonRecordWriter.java
+++ b/exec/java-exec/src/main/java/org/apache/drill/exec/store/easy/json/JsonRecordWriter.java
@@ -18,6 +18,7 @@
package org.apache.drill.exec.store.easy.json;
import java.io.IOException;
+import java.io.OutputStream;
import java.util.List;
import java.util.Map;
@@ -33,7 +34,6 @@ import org.apache.drill.exec.vector.complex.fn.ExtendedJsonOutput;
import org.apache.drill.exec.vector.complex.fn.JsonWriter;
import org.apache.drill.exec.vector.complex.reader.FieldReader;
import org.apache.hadoop.conf.Configuration;
-import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
@@ -56,7 +56,7 @@ public class JsonRecordWriter extends JSONOutputRecordWriter implements RecordWr
private int index;
private FileSystem fs = null;
- private FSDataOutputStream stream = null;
+ private OutputStream stream = null;
private final JsonFactory factory = new JsonFactory();
private final StorageStrategy storageStrategy;
diff --git a/exec/java-exec/src/main/java/org/apache/drill/exec/store/parquet/metadata/Metadata.java b/exec/java-exec/src/main/java/org/apache/drill/exec/store/parquet/metadata/Metadata.java
index cdf98e6..ab655e9 100644
--- a/exec/java-exec/src/main/java/org/apache/drill/exec/store/parquet/metadata/Metadata.java
+++ b/exec/java-exec/src/main/java/org/apache/drill/exec/store/parquet/metadata/Metadata.java
@@ -40,8 +40,6 @@ import org.apache.drill.exec.store.parquet.ParquetReaderUtility;
import org.apache.drill.exec.util.DrillFileSystemUtil;
import org.apache.drill.exec.util.ImpersonationUtil;
import org.apache.hadoop.fs.BlockLocation;
-import org.apache.hadoop.fs.FSDataInputStream;
-import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
@@ -60,6 +58,8 @@ import org.apache.parquet.schema.Type;
import javax.annotation.Nullable;
import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
import java.security.PrivilegedExceptionAction;
import java.util.ArrayList;
import java.util.Iterator;
@@ -542,7 +542,7 @@ public class Metadata {
SimpleModule module = new SimpleModule();
module.addSerializer(ColumnMetadata_v3.class, new ColumnMetadata_v3.Serializer());
mapper.registerModule(module);
- FSDataOutputStream os = fs.create(p);
+ OutputStream os = fs.create(p);
mapper.writerWithDefaultPrettyPrinter().writeValue(os, parquetTableMetadata);
os.flush();
os.close();
@@ -555,7 +555,7 @@ public class Metadata {
ObjectMapper mapper = new ObjectMapper(jsonFactory);
SimpleModule module = new SimpleModule();
mapper.registerModule(module);
- FSDataOutputStream os = fs.create(p);
+ OutputStream os = fs.create(p);
mapper.writerWithDefaultPrettyPrinter().writeValue(os, parquetTableMetadataDirs);
os.flush();
os.close();
@@ -586,7 +586,7 @@ public class Metadata {
mapper.registerModule(serialModule);
mapper.registerModule(module);
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
- try (FSDataInputStream is = fs.open(path)) {
+ try (InputStream is = fs.open(path)) {
boolean alreadyCheckedModification;
boolean newMetadata = false;
alreadyCheckedModification = metaContext.getStatus(metadataParentDirPath);
diff --git a/logical/src/main/java/org/apache/drill/common/logical/data/Sequence.java b/logical/src/main/java/org/apache/drill/common/logical/data/Sequence.java
deleted file mode 100644
index c9d68ff..0000000
--- a/logical/src/main/java/org/apache/drill/common/logical/data/Sequence.java
+++ /dev/null
@@ -1,192 +0,0 @@
-/*
- * 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.drill.common.logical.data;
-
-import java.io.IOException;
-import java.util.Iterator;
-import java.util.List;
-
-import org.apache.drill.common.logical.data.Sequence.De;
-import org.apache.drill.common.logical.data.visitors.LogicalVisitor;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.fasterxml.jackson.annotation.JsonProperty;
-import com.fasterxml.jackson.annotation.JsonTypeName;
-import com.fasterxml.jackson.annotation.ObjectIdGenerator;
-import com.fasterxml.jackson.annotation.ObjectIdGenerators;
-import com.fasterxml.jackson.core.JsonLocation;
-import com.fasterxml.jackson.core.JsonParseException;
-import com.fasterxml.jackson.core.JsonParser;
-import com.fasterxml.jackson.core.JsonProcessingException;
-import com.fasterxml.jackson.core.JsonToken;
-import com.fasterxml.jackson.databind.DeserializationContext;
-import com.fasterxml.jackson.databind.JavaType;
-import com.fasterxml.jackson.databind.JsonDeserializer;
-import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
-import com.fasterxml.jackson.databind.deser.impl.ReadableObjectId;
-import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
-import com.google.common.collect.Iterators;
-
-// TODO - is this even ever used anymore? I don't believe the planner will ever
-// generate this, we might have some tests with old logical plans that use this
-// but it should probably be removed
-/**
- * Describes a list of operators where each operator only has one input and that
- * input is the operator that came before.
- *
- */
-@Deprecated
-@JsonDeserialize(using = De.class)
-@JsonTypeName("sequence")
-public class Sequence extends LogicalOperatorBase {
- static final Logger logger = LoggerFactory.getLogger(Sequence.class);
-
- private Sequence() {}
-
- public boolean openTop;
- public LogicalOperator input;
- @JsonProperty("do")
- public List<LogicalOperator> stream;
-
- @Override
- public <T, X, E extends Throwable> T accept(LogicalVisitor<T, X, E> logicalVisitor, X value) throws E {
- return logicalVisitor.visitSequence(this, value);
- }
-
- @Override
- public Iterator<LogicalOperator> iterator() {
- return Iterators.singletonIterator(stream.get(stream.size() - 1));
- }
-
- public static class De extends StdDeserializer<LogicalOperator> {
-
- protected De() {
- super(Sequence.class);
- }
-
- @Override
- public LogicalOperator deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException,
- JsonProcessingException {
- ObjectIdGenerator<Integer> idGenerator = new ObjectIdGenerators.IntSequenceGenerator();
- JsonLocation start = jp.getCurrentLocation();
- JsonToken t = jp.getCurrentToken();
- LogicalOperator parent = null;
- LogicalOperator first = null;
- LogicalOperator prev = null;
- Integer id = null;
-
- while (true) {
- String fieldName = jp.getText();
- t = jp.nextToken();
- switch (fieldName) { // switch on field names.
- case "@id":
- id = _parseIntPrimitive(jp, ctxt);
- break;
- case "input":
- JavaType tp = ctxt.constructType(LogicalOperator.class);
- JsonDeserializer<Object> d = ctxt.findRootValueDeserializer(tp);
- parent = (LogicalOperator) d.deserialize(jp, ctxt);
- break;
-
- case "do":
- if (!jp.isExpectedStartArrayToken()) {
- throwE(
- jp,
- "The do parameter of sequence should be an array of SimpleOperators. Expected a JsonToken.START_ARRAY token but received a "
- + t.name() + "token.");
- }
-
- int pos = 0;
- while ((t = jp.nextToken()) != JsonToken.END_ARRAY) {
- // logger.debug("Reading sequence child {}.", pos);
- JsonLocation l = jp.getCurrentLocation(); // get current location
- // first so we can
- // correctly reference the
- // start of the object in
- // the case that the type
- // is wrong.
- LogicalOperator o = jp.readValueAs(LogicalOperator.class);
-
- if (pos == 0) {
- if (!(o instanceof SingleInputOperator) && !(o instanceof SourceOperator)) {
- throwE(
- l,
- "The first operator in a sequence must be either a ZeroInput or SingleInput operator. The provided first operator was not. It was of type "
- + o.getClass().getName());
- }
- first = o;
- } else {
- if (!(o instanceof SingleInputOperator)) {
- throwE(l, "All operators after the first must be single input operators. The operator at position "
- + pos + " was not. It was of type " + o.getClass().getName());
- }
- SingleInputOperator now = (SingleInputOperator) o;
- now.setInput(prev);
- }
- prev = o;
-
- pos++;
- }
- break;
- default:
- throwE(jp, "Unknown field name provided for Sequence: " + jp.getText());
- }
-
- t = jp.nextToken();
- if (t == JsonToken.END_OBJECT) {
- break;
- }
- }
-
- if (first == null) {
- throwE(start, "A sequence must include at least one operator.");
- }
- if ((parent == null && first instanceof SingleInputOperator)
- || (parent != null && first instanceof SourceOperator)) {
- throwE(start,
- "A sequence must either start with a ZeroInputOperator or have a provided input. It cannot have both or neither.");
- }
-
- if (parent != null && first instanceof SingleInputOperator) {
- ((SingleInputOperator) first).setInput(parent);
- }
-
- // set input reference.
- if (id != null) {
-
- ReadableObjectId rid = ctxt.findObjectId(id, idGenerator);
- rid.bindItem(prev);
- // logger.debug("Binding id {} to item {}.", rid.id, rid.item);
-
- }
-
- return first;
- }
-
- }
-
- private static void throwE(JsonLocation l, String e) throws JsonParseException {
- throw new JsonParseException(e, l);
- }
-
- private static void throwE(JsonParser jp, String e) throws JsonParseException {
- throw new JsonParseException(e, jp.getCurrentLocation());
- }
-
-}
diff --git a/logical/src/main/java/org/apache/drill/common/logical/data/visitors/AbstractLogicalVisitor.java b/logical/src/main/java/org/apache/drill/common/logical/data/visitors/AbstractLogicalVisitor.java
index 4fd64c5..482146f 100644
--- a/logical/src/main/java/org/apache/drill/common/logical/data/visitors/AbstractLogicalVisitor.java
+++ b/logical/src/main/java/org/apache/drill/common/logical/data/visitors/AbstractLogicalVisitor.java
@@ -30,7 +30,6 @@ import org.apache.drill.common.logical.data.Order;
import org.apache.drill.common.logical.data.Project;
import org.apache.drill.common.logical.data.RunningAggregate;
import org.apache.drill.common.logical.data.Scan;
-import org.apache.drill.common.logical.data.Sequence;
import org.apache.drill.common.logical.data.Store;
import org.apache.drill.common.logical.data.Transform;
import org.apache.drill.common.logical.data.Union;
@@ -97,11 +96,6 @@ public abstract class AbstractLogicalVisitor<T, X, E extends Throwable> implemen
}
@Override
- public T visitSequence(Sequence sequence, X value) throws E {
- return visitOp(sequence, value);
- }
-
- @Override
public T visitTransform(Transform transform, X value) throws E {
return visitOp(transform, value);
}
diff --git a/logical/src/main/java/org/apache/drill/common/logical/data/visitors/LogicalVisitor.java b/logical/src/main/java/org/apache/drill/common/logical/data/visitors/LogicalVisitor.java
index 55fa838..9d9013e 100644
--- a/logical/src/main/java/org/apache/drill/common/logical/data/visitors/LogicalVisitor.java
+++ b/logical/src/main/java/org/apache/drill/common/logical/data/visitors/LogicalVisitor.java
@@ -30,12 +30,10 @@ import org.apache.drill.common.logical.data.Order;
import org.apache.drill.common.logical.data.Project;
import org.apache.drill.common.logical.data.RunningAggregate;
import org.apache.drill.common.logical.data.Scan;
-import org.apache.drill.common.logical.data.Sequence;
import org.apache.drill.common.logical.data.Store;
import org.apache.drill.common.logical.data.Transform;
import org.apache.drill.common.logical.data.Union;
import org.apache.drill.common.logical.data.Window;
-import org.apache.drill.common.logical.data.Window;
import org.apache.drill.common.logical.data.Writer;
/**
@@ -60,7 +58,6 @@ public interface LogicalVisitor<RETURN, EXTRA, EXCEP extends Throwable> {
public RETURN visitJoin(Join join, EXTRA value) throws EXCEP;
public RETURN visitLimit(Limit limit, EXTRA value) throws EXCEP;
public RETURN visitRunningAggregate(RunningAggregate runningAggregate, EXTRA value) throws EXCEP;
- public RETURN visitSequence(Sequence sequence, EXTRA value) throws EXCEP;
public RETURN visitTransform(Transform transform, EXTRA value) throws EXCEP;
public RETURN visitUnion(Union union, EXTRA value) throws EXCEP;
public RETURN visitWindow(Window window, EXTRA value) throws EXCEP;
diff --git a/pom.xml b/pom.xml
index 43207c1..620f73c 100644
--- a/pom.xml
+++ b/pom.xml
@@ -49,8 +49,8 @@
<avatica.version>1.11.0</avatica.version>
<janino.version>2.7.6</janino.version>
<sqlline.version>1.1.9-drill-r7</sqlline.version>
- <jackson.version>2.7.9</jackson.version>
- <jackson.databind.version>2.7.9.1</jackson.databind.version>
+ <jackson.version>2.9.5</jackson.version>
+ <jackson.databind.version>2.9.5</jackson.databind.version>
<mapr.release.version>5.2.1-mapr</mapr.release.version>
<ojai.version>1.1</ojai.version>
<kerby.version>1.0.0-RC2</kerby.version>
--
To stop receiving notification emails like this one, please contact
arina@apache.org.
[drill] 04/08: DRILL-6426: Refactor
TestFunctionsWithTypeExpoQueries test to be independent on limit 0
optimization option
Posted by ar...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
arina pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/drill.git
commit 55f2599d6a357b047c5a9d5e7e8a932502cda75d
Author: Arina Ielchiieva <ar...@gmail.com>
AuthorDate: Fri May 18 13:11:05 2018 +0300
DRILL-6426: Refactor TestFunctionsWithTypeExpoQueries test to be independent on limit 0 optimization option
closes #1273
---
.../drill/TestFunctionsWithTypeExpoQueries.java | 34 ++++++++++++++++------
1 file changed, 25 insertions(+), 9 deletions(-)
diff --git a/exec/java-exec/src/test/java/org/apache/drill/TestFunctionsWithTypeExpoQueries.java b/exec/java-exec/src/test/java/org/apache/drill/TestFunctionsWithTypeExpoQueries.java
index 88558ae..d298acc 100644
--- a/exec/java-exec/src/test/java/org/apache/drill/TestFunctionsWithTypeExpoQueries.java
+++ b/exec/java-exec/src/test/java/org/apache/drill/TestFunctionsWithTypeExpoQueries.java
@@ -22,7 +22,10 @@ import org.apache.commons.lang3.tuple.Pair;
import org.apache.drill.categories.SqlFunctionTest;
import org.apache.drill.common.expression.SchemaPath;
import org.apache.drill.common.types.TypeProtos;
+import org.apache.drill.common.types.Types;
+import org.apache.drill.exec.ExecConstants;
import org.apache.drill.test.BaseTestQuery;
+import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.categories.Category;
@@ -32,9 +35,16 @@ import java.util.List;
@Category(SqlFunctionTest.class)
public class TestFunctionsWithTypeExpoQueries extends BaseTestQuery {
+
@BeforeClass
- public static void setupFiles() {
+ public static void setup() {
dirTestWatcher.copyResourceToRoot(Paths.get("typeExposure"));
+ alterSession(ExecConstants.EARLY_LIMIT0_OPT_KEY, true);
+ }
+
+ @AfterClass
+ public static void tearDown() {
+ resetSessionOption(ExecConstants.EARLY_LIMIT0_OPT_KEY);
}
@Test
@@ -44,9 +54,10 @@ public class TestFunctionsWithTypeExpoQueries extends BaseTestQuery {
List<Pair<SchemaPath, TypeProtos.MajorType>> expectedSchema = Lists.newArrayList();
TypeProtos.MajorType majorType = TypeProtos.MajorType.newBuilder()
- .setMinorType(TypeProtos.MinorType.VARCHAR)
- .setMode(TypeProtos.DataMode.REQUIRED)
- .build();
+ .setMinorType(TypeProtos.MinorType.VARCHAR)
+ .setMode(TypeProtos.DataMode.REQUIRED)
+ .setPrecision(Types.MAX_VARCHAR_LENGTH)
+ .build();
expectedSchema.add(Pair.of(SchemaPath.getSimplePath("col"), majorType));
testBuilder()
@@ -95,6 +106,7 @@ public class TestFunctionsWithTypeExpoQueries extends BaseTestQuery {
TypeProtos.MajorType majorType = TypeProtos.MajorType.newBuilder()
.setMinorType(TypeProtos.MinorType.VARCHAR)
.setMode(TypeProtos.DataMode.REQUIRED)
+ .setPrecision(Types.MAX_VARCHAR_LENGTH)
.build();
expectedSchema.add(Pair.of(SchemaPath.getSimplePath("col"), majorType));
@@ -125,9 +137,10 @@ public class TestFunctionsWithTypeExpoQueries extends BaseTestQuery {
List<Pair<SchemaPath, TypeProtos.MajorType>> expectedSchema = Lists.newArrayList();
TypeProtos.MajorType majorType = TypeProtos.MajorType.newBuilder()
- .setMinorType(TypeProtos.MinorType.VARCHAR)
- .setMode(TypeProtos.DataMode.REQUIRED)
- .build();
+ .setMinorType(TypeProtos.MinorType.VARCHAR)
+ .setMode(TypeProtos.DataMode.REQUIRED)
+ .setPrecision(Types.MAX_VARCHAR_LENGTH)
+ .build();
expectedSchema.add(Pair.of(SchemaPath.getSimplePath("col"), majorType));
testBuilder()
@@ -159,6 +172,7 @@ public class TestFunctionsWithTypeExpoQueries extends BaseTestQuery {
TypeProtos.MajorType majorType = TypeProtos.MajorType.newBuilder()
.setMinorType(TypeProtos.MinorType.VARCHAR)
.setMode(TypeProtos.DataMode.REQUIRED)
+ .setPrecision(Types.MAX_VARCHAR_LENGTH)
.build();
expectedSchema.add(Pair.of(SchemaPath.getSimplePath("col"), majorType));
@@ -191,6 +205,7 @@ public class TestFunctionsWithTypeExpoQueries extends BaseTestQuery {
TypeProtos.MajorType majorType = TypeProtos.MajorType.newBuilder()
.setMinorType(TypeProtos.MinorType.VARCHAR)
.setMode(TypeProtos.DataMode.REQUIRED)
+ .setPrecision(Types.MAX_VARCHAR_LENGTH)
.build();
expectedSchema.add(Pair.of(SchemaPath.getSimplePath("col"), majorType));
@@ -214,12 +229,12 @@ public class TestFunctionsWithTypeExpoQueries extends BaseTestQuery {
}
@Test
- public void tesIsNull() throws Exception {
+ public void testIsNull() throws Exception {
final String query = "select r_name is null as col from cp.`tpch/region.parquet` limit 0";
List<Pair<SchemaPath, TypeProtos.MajorType>> expectedSchema = Lists.newArrayList();
TypeProtos.MajorType majorType = TypeProtos.MajorType.newBuilder()
.setMinorType(TypeProtos.MinorType.BIT)
- .setMode(TypeProtos.DataMode.REQUIRED)
+ .setMode(TypeProtos.DataMode.OPTIONAL)
.build();
expectedSchema.add(Pair.of(SchemaPath.getSimplePath("col"), majorType));
@@ -501,6 +516,7 @@ public class TestFunctionsWithTypeExpoQueries extends BaseTestQuery {
final TypeProtos.MajorType majorType2 = TypeProtos.MajorType.newBuilder()
.setMinorType(TypeProtos.MinorType.VARCHAR)
.setMode(TypeProtos.DataMode.OPTIONAL)
+ .setPrecision(Types.MAX_VARCHAR_LENGTH)
.build();
final TypeProtos.MajorType majorType3 = TypeProtos.MajorType.newBuilder()
--
To stop receiving notification emails like this one, please contact
arina@apache.org.
[drill] 03/08: DRILL-6421: Refactor DecimalUtility and
CoreDecimalUtility classes
Posted by ar...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
arina pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/drill.git
commit bdbd93fc726224ec45d06f09434c7406e444242e
Author: Volodymyr Vysotskyi <vv...@gmail.com>
AuthorDate: Wed May 16 21:34:56 2018 +0300
DRILL-6421: Refactor DecimalUtility and CoreDecimalUtility classes
closes #1267
---
.../java/org/apache/drill/common/types/Types.java | 106 ++--
.../drill/common/util/CoreDecimalUtility.java | 55 --
.../drill/exec/store/hive/HiveUtilities.java | 8 +-
.../templates/Decimal/CastVarDecimalDecimal.java | 6 +-
.../exec/expr/ExpressionTreeMaterializer.java | 43 +-
.../drill/exec/physical/impl/join/JoinUtils.java | 6 +-
.../drill/exec/planner/sql/TypeInferenceUtils.java | 4 +-
.../exec/store/parquet/ParquetRecordWriter.java | 3 +-
.../columnreaders/ParquetToDrillTypeConverter.java | 4 +-
.../main/codegen/templates/ColumnAccessors.java | 14 +-
.../main/codegen/templates/FixedValueVectors.java | 2 +-
.../org/apache/drill/exec/util/DecimalUtility.java | 672 ++++-----------------
.../drill/exec/vector/ValueHolderHelper.java | 8 +-
.../drill/common/expression/ValueExpressions.java | 21 +-
14 files changed, 185 insertions(+), 767 deletions(-)
diff --git a/common/src/main/java/org/apache/drill/common/types/Types.java b/common/src/main/java/org/apache/drill/common/types/Types.java
index 5c6e7f3..e66a340 100644
--- a/common/src/main/java/org/apache/drill/common/types/Types.java
+++ b/common/src/main/java/org/apache/drill/common/types/Types.java
@@ -27,12 +27,11 @@ import org.apache.drill.common.exceptions.DrillRuntimeException;
import org.apache.drill.common.types.TypeProtos.DataMode;
import org.apache.drill.common.types.TypeProtos.MajorType;
import org.apache.drill.common.types.TypeProtos.MinorType;
-import org.apache.drill.common.util.CoreDecimalUtility;
import com.google.protobuf.TextFormat;
+@SuppressWarnings("WeakerAccess")
public class Types {
- static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(Types.class);
public static final int MAX_VARCHAR_LENGTH = 65535;
public static final int UNDEFINED = 0;
@@ -47,10 +46,6 @@ public class Types {
return toType.getMinorType() == MinorType.UNION;
}
- public enum Comparability {
- UNKNOWN, NONE, EQUAL, ORDERED
- }
-
public static boolean isComplex(final MajorType type) {
switch(type.getMinorType()) {
case LIST:
@@ -90,6 +85,37 @@ public class Types {
case UINT4:
case UINT8:
return true;
+ default:
+ return false;
+ }
+ }
+
+ /**
+ * Returns true if specified type is decimal data type.
+ *
+ * @param type type to check
+ * @return true if specified type is decimal data type.
+ */
+ public static boolean isDecimalType(MajorType type) {
+ return isDecimalType(type.getMinorType());
+ }
+
+ /**
+ * Returns true if specified type is decimal data type.
+ *
+ * @param minorType type to check
+ * @return true if specified type is decimal data type.
+ */
+ public static boolean isDecimalType(MinorType minorType) {
+ switch(minorType) {
+ case VARDECIMAL:
+ case DECIMAL38SPARSE:
+ case DECIMAL38DENSE:
+ case DECIMAL28SPARSE:
+ case DECIMAL28DENSE:
+ case DECIMAL18:
+ case DECIMAL9:
+ return true;
default:
return false;
}
@@ -182,11 +208,9 @@ public class Types {
* Extend decimal type with precision and scale.
*
* @param type major type
- * @param typeName type converted to a string
* @return type name augmented with precision and scale,
* if type is a decimal
*/
-
public static String getExtendedSqlTypeName(MajorType type) {
String typeName = getSqlTypeName(type);
@@ -266,7 +290,7 @@ public class Types {
/**
* Reports whether given RPC-level type is a signed type (per semantics of
- * {@link ResultSetMetaData#isSigned(int)}).
+ * {@link java.sql.ResultSetMetaData#isSigned(int)}).
*/
public static boolean isJdbcSignedType( final MajorType type ) {
final boolean isSigned;
@@ -477,41 +501,6 @@ public class Types {
}
}
- public static boolean isBytesScalarType(final MajorType type) {
- if (type.getMode() == REPEATED) {
- return false;
- }
- switch(type.getMinorType()) {
- case FIXEDBINARY:
- case VARBINARY:
- return true;
- default:
- return false;
- }
- }
-
- public static Comparability getComparability(final MajorType type) {
- if (type.getMode() == REPEATED) {
- return Comparability.NONE;
- }
- if (type.getMinorType() == MinorType.LATE) {
- return Comparability.UNKNOWN;
- }
-
- switch(type.getMinorType()) {
- case LATE:
- return Comparability.UNKNOWN;
- case MAP:
- return Comparability.NONE;
- case BIT:
- return Comparability.EQUAL;
- default:
- return Comparability.ORDERED;
- }
-
- }
-
-
public static boolean softEquals(final MajorType a, final MajorType b, final boolean allowNullSwap) {
if (a.getMinorType() != b.getMinorType()) {
return false;
@@ -532,10 +521,6 @@ public class Types {
return a.getMode() == b.getMode();
}
- public static boolean isLateBind(final MajorType type) {
- return type.getMinorType() == MinorType.LATE;
- }
-
public static boolean isUntypedNull(final MajorType type) {
return type.getMinorType() == MinorType.NULL;
}
@@ -572,19 +557,6 @@ public class Types {
return MajorType.newBuilder().setMode(DataMode.OPTIONAL).setMinorType(type).build();
}
- public static MajorType overrideMinorType(final MajorType originalMajorType, final MinorType overrideMinorType) {
- switch (originalMajorType.getMode()) {
- case REPEATED:
- return repeated(overrideMinorType);
- case OPTIONAL:
- return optional(overrideMinorType);
- case REQUIRED:
- return required(overrideMinorType);
- default:
- throw new UnsupportedOperationException();
- }
- }
-
public static MajorType overrideMode(final MajorType originalMajorType, final DataMode overrideMode) {
return withScaleAndPrecision(originalMajorType.getMinorType(), overrideMode, originalMajorType.getScale(), originalMajorType.getPrecision());
}
@@ -765,7 +737,7 @@ public class Types {
public static MajorType.Builder calculateTypePrecisionAndScale(MajorType leftType, MajorType rightType, MajorType.Builder typeBuilder) {
if (leftType.getMinorType().equals(rightType.getMinorType())) {
boolean isScalarString = Types.isScalarStringType(leftType) && Types.isScalarStringType(rightType);
- boolean isDecimal = CoreDecimalUtility.isDecimalType(leftType);
+ boolean isDecimal = isDecimalType(leftType);
if ((isScalarString || isDecimal) && leftType.hasPrecision() && rightType.hasPrecision()) {
typeBuilder.setPrecision(Math.max(leftType.getPrecision(), rightType.getPrecision()));
@@ -778,10 +750,6 @@ public class Types {
return typeBuilder;
}
- public static boolean isLaterType(MajorType type) {
- return type.getMinorType() == MinorType.LATE;
- }
-
public static boolean isEquivalent(MajorType type1, MajorType type2) {
// Requires full type equality, including fields such as precision and scale.
@@ -815,10 +783,8 @@ public class Types {
// Now it gets slow because subtype lists are not ordered.
- List<MinorType> copy1 = new ArrayList<>();
- List<MinorType> copy2 = new ArrayList<>();
- copy1.addAll(subtypes1);
- copy2.addAll(subtypes2);
+ List<MinorType> copy1 = new ArrayList<>(subtypes1);
+ List<MinorType> copy2 = new ArrayList<>(subtypes2);
Collections.sort(copy1);
Collections.sort(copy2);
return copy1.equals(copy2);
diff --git a/common/src/main/java/org/apache/drill/common/util/CoreDecimalUtility.java b/common/src/main/java/org/apache/drill/common/util/CoreDecimalUtility.java
deleted file mode 100644
index 0e8a1c7..0000000
--- a/common/src/main/java/org/apache/drill/common/util/CoreDecimalUtility.java
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * 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.drill.common.util;
-
-import java.math.BigDecimal;
-
-import org.apache.drill.common.types.TypeProtos;
-
-public class CoreDecimalUtility {
- static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(CoreDecimalUtility.class);
-
- public static long getDecimal18FromBigDecimal(BigDecimal input, int scale, int precision) {
- // Truncate or pad to set the input to the correct scale
- input = input.setScale(scale, BigDecimal.ROUND_HALF_UP);
-
- return (input.unscaledValue().longValue());
- }
-
- public static int getDecimal9FromBigDecimal(BigDecimal input, int scale, int precision) {
- // Truncate/ or pad to set the input to the correct scale
- input = input.setScale(scale, BigDecimal.ROUND_HALF_UP);
-
- return (input.unscaledValue().intValue());
- }
-
- /*
- * Helper function to detect if the given data type is Decimal
- */
- public static boolean isDecimalType(TypeProtos.MajorType type) {
- return isDecimalType(type.getMinorType());
- }
-
- public static boolean isDecimalType(TypeProtos.MinorType minorType) {
- return minorType == TypeProtos.MinorType.VARDECIMAL ||
- minorType == TypeProtos.MinorType.DECIMAL9 ||
- minorType == TypeProtos.MinorType.DECIMAL18 ||
- minorType == TypeProtos.MinorType.DECIMAL28SPARSE ||
- minorType == TypeProtos.MinorType.DECIMAL38SPARSE;
- }
-}
diff --git a/contrib/storage-hive/core/src/main/java/org/apache/drill/exec/store/hive/HiveUtilities.java b/contrib/storage-hive/core/src/main/java/org/apache/drill/exec/store/hive/HiveUtilities.java
index 8f34584..5279f28 100644
--- a/contrib/storage-hive/core/src/main/java/org/apache/drill/exec/store/hive/HiveUtilities.java
+++ b/contrib/storage-hive/core/src/main/java/org/apache/drill/exec/store/hive/HiveUtilities.java
@@ -233,7 +233,7 @@ public class HiveUtilities {
final Decimal9Holder holder = new Decimal9Holder();
holder.scale = v.getField().getScale();
holder.precision = v.getField().getPrecision();
- holder.value = DecimalUtility.getDecimal9FromBigDecimal(value, holder.scale, holder.precision);
+ holder.value = DecimalUtility.getDecimal9FromBigDecimal(value, holder.scale);
for (int i = start; i < end; i++) {
v.getMutator().setSafe(i, holder);
}
@@ -246,7 +246,7 @@ public class HiveUtilities {
final Decimal18Holder holder = new Decimal18Holder();
holder.scale = v.getField().getScale();
holder.precision = v.getField().getPrecision();
- holder.value = DecimalUtility.getDecimal18FromBigDecimal(value, holder.scale, holder.precision);
+ holder.value = DecimalUtility.getDecimal18FromBigDecimal(value, holder.scale);
for (int i = start; i < end; i++) {
v.getMutator().setSafe(i, holder);
}
@@ -266,7 +266,7 @@ public class HiveUtilities {
holder.precision = v.getField().getPrecision();
holder.buffer = managedBuffer;
holder.start = 0;
- DecimalUtility.getSparseFromBigDecimal(value, holder.buffer, 0, holder.scale, holder.precision,
+ DecimalUtility.getSparseFromBigDecimal(value, holder.buffer, 0, holder.scale,
Decimal28SparseHolder.nDecimalDigits);
for (int i = start; i < end; i++) {
v.getMutator().setSafe(i, holder);
@@ -286,7 +286,7 @@ public class HiveUtilities {
holder.precision = v.getField().getPrecision();
holder.buffer = managedBuffer;
holder.start = 0;
- DecimalUtility.getSparseFromBigDecimal(value, holder.buffer, 0, holder.scale, holder.precision,
+ DecimalUtility.getSparseFromBigDecimal(value, holder.buffer, 0, holder.scale,
Decimal38SparseHolder.nDecimalDigits);
for (int i = start; i < end; i++) {
v.getMutator().setSafe(i, holder);
diff --git a/exec/java-exec/src/main/codegen/templates/Decimal/CastVarDecimalDecimal.java b/exec/java-exec/src/main/codegen/templates/Decimal/CastVarDecimalDecimal.java
index 8ef2bf9..828d486 100644
--- a/exec/java-exec/src/main/codegen/templates/Decimal/CastVarDecimalDecimal.java
+++ b/exec/java-exec/src/main/codegen/templates/Decimal/CastVarDecimalDecimal.java
@@ -77,14 +77,14 @@ public class Cast${type.from}${type.to} implements DrillSimpleFunc {
.round(new java.math.MathContext(precision.value, java.math.RoundingMode.HALF_UP));
<#if type.to.endsWith("Decimal9")>
- out.value = org.apache.drill.exec.util.DecimalUtility.getDecimal9FromBigDecimal(bd, out.scale, out.precision);
+ out.value = org.apache.drill.exec.util.DecimalUtility.getDecimal9FromBigDecimal(bd, out.scale);
<#elseif type.to.endsWith("Decimal18")>
- out.value = org.apache.drill.exec.util.DecimalUtility.getDecimal18FromBigDecimal(bd, out.scale, out.precision);
+ out.value = org.apache.drill.exec.util.DecimalUtility.getDecimal18FromBigDecimal(bd, out.scale);
<#elseif type.to.endsWith("Sparse")>
out.start = 0;
out.buffer = buffer;
org.apache.drill.exec.util.DecimalUtility
- .getSparseFromBigDecimal(bd, out.buffer, out.start, out.scale, out.precision, out.nDecimalDigits);
+ .getSparseFromBigDecimal(bd, out.buffer, out.start, out.scale, out.nDecimalDigits);
</#if>
}
}
diff --git a/exec/java-exec/src/main/java/org/apache/drill/exec/expr/ExpressionTreeMaterializer.java b/exec/java-exec/src/main/java/org/apache/drill/exec/expr/ExpressionTreeMaterializer.java
index ff38e0c..283953a 100644
--- a/exec/java-exec/src/main/java/org/apache/drill/exec/expr/ExpressionTreeMaterializer.java
+++ b/exec/java-exec/src/main/java/org/apache/drill/exec/expr/ExpressionTreeMaterializer.java
@@ -21,15 +21,12 @@ import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Collections;
import java.util.Deque;
-import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Queue;
-import java.util.Set;
import com.google.common.base.Preconditions;
import com.google.common.collect.Maps;
-import com.google.common.collect.Sets;
import org.apache.drill.common.exceptions.DrillRuntimeException;
import org.apache.drill.common.expression.BooleanOperator;
import org.apache.drill.common.expression.CastExpression;
@@ -72,7 +69,6 @@ import org.apache.drill.common.types.TypeProtos.DataMode;
import org.apache.drill.common.types.TypeProtos.MajorType;
import org.apache.drill.common.types.TypeProtos.MinorType;
import org.apache.drill.common.types.Types;
-import org.apache.drill.common.util.CoreDecimalUtility;
import org.apache.drill.exec.exception.SchemaChangeException;
import org.apache.drill.exec.expr.annotations.FunctionTemplate;
import org.apache.drill.exec.expr.fn.AbstractFuncHolder;
@@ -121,8 +117,7 @@ public class ExpressionTreeMaterializer {
public static LogicalExpression materializeFilterExpr(LogicalExpression expr, Map<SchemaPath, ColumnStatistics> fieldTypes, ErrorCollector errorCollector, FunctionLookupContext functionLookupContext) {
final FilterMaterializeVisitor filterMaterializeVisitor = new FilterMaterializeVisitor(fieldTypes, errorCollector);
- LogicalExpression out = expr.accept(filterMaterializeVisitor, functionLookupContext);
- return out;
+ return expr.accept(filterMaterializeVisitor, functionLookupContext);
}
/**
@@ -211,7 +206,7 @@ public class ExpressionTreeMaterializer {
return fromExpr;
}
- if (CoreDecimalUtility.isDecimalType(toType)) {
+ if (Types.isDecimalType(toType)) {
// Add the scale and precision to the arguments of the implicit cast
castArgs.add(new ValueExpressions.IntExpression(toType.getPrecision(), null));
castArgs.add(new ValueExpressions.IntExpression(toType.getScale(), null));
@@ -338,10 +333,6 @@ public class ExpressionTreeMaterializer {
* Once this code is more well tested, we will probably remove this flag
*/
private final boolean unionTypeEnabled;
- /**
- * Avoid revisiting portions of the tree that have already been materialized
- */
- private Set<LogicalExpression> materializedExpressions = Sets.newIdentityHashSet();
public AbstractMaterializeVisitor(ErrorCollector errorCollector, boolean allowComplexWriter, boolean unionTypeEnabled) {
this.errorCollector = errorCollector;
@@ -430,7 +421,7 @@ public class ExpressionTreeMaterializer {
argsWithCast.add(currentArg);
} else {
//Case 3: insert cast if param type is different from arg type.
- if (CoreDecimalUtility.isDecimalType(parmType)) {
+ if (Types.isDecimalType(parmType)) {
// We are implicitly promoting a decimal type, set the required scale and precision
parmType = MajorType.newBuilder().setMinorType(parmType.getMinorType()).setMode(parmType.getMode()).
setScale(currentArg.getMajorType().getScale()).setPrecision(computePrecision(currentArg)).build();
@@ -468,7 +459,7 @@ public class ExpressionTreeMaterializer {
extArgsWithCast.add(currentArg);
} else {
// Insert cast if param type is different from arg type.
- if (CoreDecimalUtility.isDecimalType(parmType)) {
+ if (Types.isDecimalType(parmType)) {
// We are implicitly promoting a decimal type, set the required scale and precision
parmType = MajorType.newBuilder().setMinorType(parmType.getMinorType()).setMode(parmType.getMode()).
setScale(currentArg.getMajorType().getScale()).setPrecision(computePrecision(currentArg)).build();
@@ -488,17 +479,6 @@ public class ExpressionTreeMaterializer {
return NullExpression.INSTANCE;
}
- private static final Set<String> UNION_FUNCTIONS;
-
- static {
- UNION_FUNCTIONS = new HashSet<>();
- for (MinorType t : MinorType.values()) {
- UNION_FUNCTIONS.add("assert_" + t.name().toLowerCase());
- UNION_FUNCTIONS.add("is_" + t.name().toLowerCase());
- }
- UNION_FUNCTIONS.add("typeof");
- }
-
private boolean hasUnionInput(FunctionCall call) {
for (LogicalExpression arg : call.args) {
if (arg.getMajorType().getMinorType() == MinorType.UNION) {
@@ -583,8 +563,7 @@ public class ExpressionTreeMaterializer {
QuotedString msg = new QuotedString(message, message.length(), ExpressionPosition.UNKNOWN);
List<LogicalExpression> args = Lists.newArrayList();
args.add(msg);
- FunctionCall call = new FunctionCall(ExceptionFunction.EXCEPTION_FUNCTION_NAME, args, ExpressionPosition.UNKNOWN);
- return call;
+ return new FunctionCall(ExceptionFunction.EXCEPTION_FUNCTION_NAME, args, ExpressionPosition.UNKNOWN);
}
/**
@@ -602,7 +581,6 @@ public class ExpressionTreeMaterializer {
return getExceptionFunction("Unable to cast union to " + type);
}
String castFuncName = String.format("assert_%s", type.toString());
- Collections.singletonList(arg);
return new FunctionCall(castFuncName, Collections.singletonList(arg), ExpressionPosition.UNKNOWN);
}
@@ -634,7 +612,6 @@ public class ExpressionTreeMaterializer {
if (unionTypeEnabled) {
if (thenType != elseType && !(thenType == MinorType.NULL || elseType == MinorType.NULL)) {
- MinorType leastRestrictive = MinorType.UNION;
MajorType.Builder builder = MajorType.newBuilder().setMinorType(MinorType.UNION).setMode(DataMode.OPTIONAL);
if (thenType == MinorType.UNION) {
for (MinorType subType : conditions.expression.getMajorType().getSubTypeList()) {
@@ -726,8 +703,12 @@ public class ExpressionTreeMaterializer {
}
}
- LogicalExpression expr = validateNewExpr(IfExpression.newBuilder().setElse(newElseExpr).setIfCondition(conditions).setOutputType(outputType).build());
- return expr;
+ return validateNewExpr(
+ IfExpression.newBuilder()
+ .setElse(newElseExpr)
+ .setIfCondition(conditions)
+ .setOutputType(outputType)
+ .build());
}
private LogicalExpression getConvertToNullableExpr(List<LogicalExpression> args, MinorType minorType,
@@ -880,7 +861,7 @@ public class ExpressionTreeMaterializer {
List<LogicalExpression> newArgs = Lists.newArrayList();
newArgs.add(input); //input_expr
- if (CoreDecimalUtility.isDecimalType(type)) {
+ if (Types.isDecimalType(type)) {
newArgs.add(new ValueExpressions.IntExpression(type.getPrecision(), null));
newArgs.add(new ValueExpressions.IntExpression(type.getScale(), null));
} else if (!Types.isFixedWidthType(type)) { //VarLen type
diff --git a/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/join/JoinUtils.java b/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/join/JoinUtils.java
index b6604d2..e4dab91 100644
--- a/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/join/JoinUtils.java
+++ b/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/join/JoinUtils.java
@@ -25,6 +25,7 @@ import org.apache.drill.common.logical.data.JoinCondition;
import org.apache.calcite.rel.RelNode;
import org.apache.calcite.plan.RelOptUtil;
import org.apache.calcite.plan.volcano.RelSubset;
+import org.apache.drill.common.types.Types;
import org.apache.drill.exec.physical.impl.common.Comparator;
import org.apache.drill.exec.planner.logical.DrillAggregateRel;
import org.apache.drill.common.exceptions.DrillRuntimeException;
@@ -36,7 +37,6 @@ import org.apache.drill.exec.expr.ExpressionTreeMaterializer;
import org.apache.drill.exec.ops.FragmentContext;
import org.apache.drill.exec.record.VectorAccessible;
import org.apache.drill.exec.resolver.TypeCastRules;
-import org.apache.drill.exec.util.DecimalUtility;
import java.util.LinkedList;
import java.util.List;
@@ -123,8 +123,8 @@ public class JoinUtils {
// allow implicit cast if both the input types are numeric and any of them is non-decimal
// or both of them are decimal
if (TypeCastRules.isNumericType(input1) && TypeCastRules.isNumericType(input2)
- && ((!DecimalUtility.isDecimalType(input1) && !DecimalUtility.isDecimalType(input2))
- || DecimalUtility.isDecimalType(input1) && DecimalUtility.isDecimalType(input2))) {
+ && ((!Types.isDecimalType(input1) && !Types.isDecimalType(input2))
+ || Types.isDecimalType(input1) && Types.isDecimalType(input2))) {
return true;
}
diff --git a/exec/java-exec/src/main/java/org/apache/drill/exec/planner/sql/TypeInferenceUtils.java b/exec/java-exec/src/main/java/org/apache/drill/exec/planner/sql/TypeInferenceUtils.java
index 529546f..4b5ac7b 100644
--- a/exec/java-exec/src/main/java/org/apache/drill/exec/planner/sql/TypeInferenceUtils.java
+++ b/exec/java-exec/src/main/java/org/apache/drill/exec/planner/sql/TypeInferenceUtils.java
@@ -46,7 +46,6 @@ import org.apache.drill.common.expression.MajorTypeInLogicalExpression;
import org.apache.drill.common.exceptions.UserException;
import org.apache.drill.common.types.TypeProtos;
import org.apache.drill.common.types.Types;
-import org.apache.drill.common.util.CoreDecimalUtility;
import org.apache.drill.exec.expr.annotations.FunctionTemplate;
import org.apache.drill.exec.expr.fn.DrillFuncHolder;
import org.apache.drill.exec.planner.types.DrillRelDataTypeSystem;
@@ -57,6 +56,7 @@ import org.apache.drill.exec.resolver.TypeCastRules;
import java.util.List;
import java.util.Set;
+@SuppressWarnings("WeakerAccess")
public class TypeInferenceUtils {
private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(TypeInferenceUtils.class);
@@ -906,7 +906,7 @@ public class TypeInferenceUtils {
.setMode(dataMode)
.setMinorType(minorType);
- if (CoreDecimalUtility.isDecimalType(minorType)) {
+ if (Types.isDecimalType(minorType)) {
builder
.setScale(type.getScale())
.setPrecision(type.getPrecision());
diff --git a/exec/java-exec/src/main/java/org/apache/drill/exec/store/parquet/ParquetRecordWriter.java b/exec/java-exec/src/main/java/org/apache/drill/exec/store/parquet/ParquetRecordWriter.java
index ec78619..114bae4 100644
--- a/exec/java-exec/src/main/java/org/apache/drill/exec/store/parquet/ParquetRecordWriter.java
+++ b/exec/java-exec/src/main/java/org/apache/drill/exec/store/parquet/ParquetRecordWriter.java
@@ -30,6 +30,7 @@ import org.apache.drill.common.exceptions.DrillRuntimeException;
import org.apache.drill.common.expression.SchemaPath;
import org.apache.drill.common.types.TypeProtos.DataMode;
import org.apache.drill.common.types.TypeProtos.MinorType;
+import org.apache.drill.common.types.Types;
import org.apache.drill.common.util.DrillVersionInfo;
import org.apache.drill.exec.ExecConstants;
import org.apache.drill.exec.exception.OutOfMemoryException;
@@ -251,7 +252,7 @@ public class ParquetRecordWriter extends ParquetOutputRecordWriter {
String name = field.getName();
int length = ParquetTypeHelper.getLengthForMinorType(minorType);
PrimitiveTypeName primitiveTypeName = ParquetTypeHelper.getPrimitiveTypeNameForMinorType(minorType);
- if (DecimalUtility.isDecimalType(minorType)) {
+ if (Types.isDecimalType(minorType)) {
primitiveTypeName = logicalTypeForDecimals;
if (usePrimitiveTypesForDecimals) {
if (field.getPrecision() <= ParquetTypeHelper.getMaxPrecisionForPrimitiveType(PrimitiveTypeName.INT32)) {
diff --git a/exec/java-exec/src/main/java/org/apache/drill/exec/store/parquet/columnreaders/ParquetToDrillTypeConverter.java b/exec/java-exec/src/main/java/org/apache/drill/exec/store/parquet/columnreaders/ParquetToDrillTypeConverter.java
index 309ed89..cb688fd 100644
--- a/exec/java-exec/src/main/java/org/apache/drill/exec/store/parquet/columnreaders/ParquetToDrillTypeConverter.java
+++ b/exec/java-exec/src/main/java/org/apache/drill/exec/store/parquet/columnreaders/ParquetToDrillTypeConverter.java
@@ -20,7 +20,7 @@ package org.apache.drill.exec.store.parquet.columnreaders;
import org.apache.drill.common.types.TypeProtos;
import org.apache.drill.common.types.TypeProtos.MinorType;
-import org.apache.drill.common.util.CoreDecimalUtility;
+import org.apache.drill.common.types.Types;
import org.apache.drill.exec.ExecConstants;
import org.apache.drill.exec.server.options.OptionManager;
import org.apache.drill.exec.store.parquet.ParquetReaderUtility;
@@ -128,7 +128,7 @@ public class ParquetToDrillTypeConverter {
MinorType minorType = getMinorType(primitiveTypeName, length, convertedType, options);
TypeProtos.MajorType.Builder typeBuilder = TypeProtos.MajorType.newBuilder().setMinorType(minorType).setMode(mode);
- if (CoreDecimalUtility.isDecimalType(minorType)) {
+ if (Types.isDecimalType(minorType)) {
int precision = schemaElement.getPrecision();
int scale = schemaElement.getScale();
diff --git a/exec/vector/src/main/codegen/templates/ColumnAccessors.java b/exec/vector/src/main/codegen/templates/ColumnAccessors.java
index accf1b2..15349a2 100644
--- a/exec/vector/src/main/codegen/templates/ColumnAccessors.java
+++ b/exec/vector/src/main/codegen/templates/ColumnAccessors.java
@@ -178,13 +178,11 @@ public class ColumnAccessors {
<#elseif drillType == "Decimal9">
return DecimalUtility.getBigDecimalFromPrimitiveTypes(
buf.getInt(${getOffset}),
- type.getScale(),
- type.getPrecision());
+ type.getScale());
<#elseif drillType == "Decimal18">
return DecimalUtility.getBigDecimalFromPrimitiveTypes(
buf.getLong(${getOffset}),
- type.getScale(),
- type.getPrecision());
+ type.getScale());
<#elseif drillType == "IntervalYear">
return DateUtilities.fromIntervalYear(
buf.getInt(${getOffset}));
@@ -296,21 +294,21 @@ public class ColumnAccessors {
<#elseif drillType == "Decimal9">
drillBuf.setInt(${putOffset},
DecimalUtility.getDecimal9FromBigDecimal(value,
- type.getScale(), type.getPrecision()));
+ type.getScale()));
<#elseif drillType == "Decimal18">
drillBuf.setLong(${putOffset},
DecimalUtility.getDecimal18FromBigDecimal(value,
- type.getScale(), type.getPrecision()));
+ type.getScale()));
<#elseif drillType == "Decimal38Sparse">
<#-- Hard to optimize this case. Just use the available tools. -->
DecimalUtility.getSparseFromBigDecimal(value, drillBuf,
${putOffset},
- type.getScale(), type.getPrecision(), 6);
+ type.getScale(), 6);
<#elseif drillType == "Decimal28Sparse">
<#-- Hard to optimize this case. Just use the available tools. -->
DecimalUtility.getSparseFromBigDecimal(value, drillBuf,
${putOffset},
- type.getScale(), type.getPrecision(), 5);
+ type.getScale(), 5);
<#elseif drillType == "IntervalYear">
drillBuf.setInt(${putOffset},
value.getYears() * 12 + value.getMonths());
diff --git a/exec/vector/src/main/codegen/templates/FixedValueVectors.java b/exec/vector/src/main/codegen/templates/FixedValueVectors.java
index 4a98c26..eb2c93d 100644
--- a/exec/vector/src/main/codegen/templates/FixedValueVectors.java
+++ b/exec/vector/src/main/codegen/templates/FixedValueVectors.java
@@ -699,7 +699,7 @@ public final class ${minor.class}Vector extends BaseDataValueVector implements F
public void set(int index, BigDecimal value) {
DecimalUtility.getSparseFromBigDecimal(value, data, index * VALUE_WIDTH,
- field.getScale(), field.getPrecision(), ${minor.nDecimalDigits});
+ field.getScale(), ${minor.nDecimalDigits});
}
public void setSafe(int index, BigDecimal value) {
diff --git a/exec/vector/src/main/java/org/apache/drill/exec/util/DecimalUtility.java b/exec/vector/src/main/java/org/apache/drill/exec/util/DecimalUtility.java
index a451b97..f0a06d8 100644
--- a/exec/vector/src/main/java/org/apache/drill/exec/util/DecimalUtility.java
+++ b/exec/vector/src/main/java/org/apache/drill/exec/util/DecimalUtility.java
@@ -25,142 +25,40 @@ import io.netty.buffer.UnpooledByteBufAllocator;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
-import java.nio.ByteBuffer;
-import java.util.Arrays;
import org.apache.drill.common.types.TypeProtos;
-import org.apache.drill.common.util.CoreDecimalUtility;
-import org.apache.drill.exec.expr.fn.impl.ByteFunctionHelpers;
-import org.apache.drill.exec.expr.holders.Decimal38SparseHolder;
-public class DecimalUtility extends CoreDecimalUtility {
+@SuppressWarnings("WeakerAccess")
+public class DecimalUtility {
public final static int MAX_DIGITS = 9;
public final static int MAX_DIGITS_INT = 10;
public final static int MAX_DIGITS_BIGINT = 19;
public final static int DIGITS_BASE = 1000000000;
- public final static int DIGITS_MAX = 999999999;
- public final static int INTEGER_SIZE = (Integer.SIZE/8);
-
- public final static String[] decimalToString = {"",
- "0",
- "00",
- "000",
- "0000",
- "00000",
- "000000",
- "0000000",
- "00000000",
- "000000000"};
-
- public final static long[] scale_long_constants = {
- 1,
- 10,
- 100,
- 1000,
- 10000,
- 100000,
- 1000000,
- 10000000,
- 100000000,
- 1000000000,
- 10000000000l,
- 100000000000l,
- 1000000000000l,
- 10000000000000l,
- 100000000000000l,
- 1000000000000000l,
- 10000000000000000l,
- 100000000000000000l,
- 1000000000000000000l};
-
- /*
- * Simple function that returns the static precomputed
- * power of ten, instead of using Math.pow
- */
- public static long getPowerOfTen(int power) {
- assert power >= 0 && power < scale_long_constants.length;
- return scale_long_constants[(power)];
- }
-
- /*
- * Math.pow returns a double and while multiplying with large digits
- * in the decimal data type we encounter noise. So instead of multiplying
- * with Math.pow we use the static constants to perform the multiplication
- */
- public static long adjustScaleMultiply(long input, int factor) {
- int index = Math.abs(factor);
- assert index >= 0 && index < scale_long_constants.length;
- if (factor >= 0) {
- return input * scale_long_constants[index];
- } else {
- return input / scale_long_constants[index];
- }
- }
-
- public static long adjustScaleDivide(long input, int factor) {
- int index = Math.abs(factor);
- assert index >= 0 && index < scale_long_constants.length;
- if (factor >= 0) {
- return input / scale_long_constants[index];
- } else {
- return input * scale_long_constants[index];
- }
- }
+ public final static int INTEGER_SIZE = Integer.SIZE / 8;
- /* Given the number of actual digits this function returns the
+ /**
+ * Given the number of actual digits this function returns the
* number of indexes it will occupy in the array of integers
* which are stored in base 1 billion
*/
public static int roundUp(int ndigits) {
- return (ndigits + MAX_DIGITS - 1)/MAX_DIGITS;
+ return (ndigits + MAX_DIGITS - 1) / MAX_DIGITS;
}
- /** Returns a string representation of the given integer
- * If the length of the given integer is less than the
- * passed length, this function will prepend zeroes to the string
+ /**
+ * Create a BigDecimal object using the data in the DrillBuf.
+ * This function assumes that data is provided in a sparse format.
*/
- public static StringBuilder toStringWithZeroes(int number, int desiredLength) {
- String value = ((Integer) number).toString();
- int length = value.length();
-
- StringBuilder str = new StringBuilder();
- str.append(decimalToString[desiredLength - length]);
- str.append(value);
-
- return str;
- }
-
- public static StringBuilder toStringWithZeroes(long number, int desiredLength) {
- String value = ((Long) number).toString();
- int length = value.length();
-
- StringBuilder str = new StringBuilder();
-
- // Desired length can be > MAX_DIGITS
- int zeroesLength = desiredLength - length;
- while (zeroesLength > MAX_DIGITS) {
- str.append(decimalToString[MAX_DIGITS]);
- zeroesLength -= MAX_DIGITS;
- }
- str.append(decimalToString[zeroesLength]);
- str.append(value);
-
- return str;
- }
-
- public static BigDecimal getBigDecimalFromIntermediate(ByteBuf data, int startIndex, int nDecimalDigits, int scale) {
-
- // In the intermediate representation we don't pad the scale with zeroes, so set truncate = false
- return getBigDecimalFromDrillBuf(data, startIndex, nDecimalDigits, scale, false);
- }
-
public static BigDecimal getBigDecimalFromSparse(DrillBuf data, int startIndex, int nDecimalDigits, int scale) {
-
// In the sparse representation we pad the scale with zeroes for ease of arithmetic, need to truncate
return getBigDecimalFromDrillBuf(data, startIndex, nDecimalDigits, scale, true);
}
+ /**
+ * Create a BigDecimal object using the data in the DrillBuf.
+ * This function assumes that data is provided in format supported by {@link BigInteger}.
+ */
public static BigDecimal getBigDecimalFromDrillBuf(DrillBuf bytebuf, int start, int length, int scale) {
byte[] value = new byte[length];
bytebuf.getBytes(start, value, 0, length);
@@ -168,14 +66,8 @@ public class DecimalUtility extends CoreDecimalUtility {
return new BigDecimal(unscaledValue, scale);
}
- public static BigDecimal getBigDecimalFromByteBuffer(ByteBuffer bytebuf, int start, int length, int scale) {
- byte[] value = new byte[length];
- bytebuf.get(value);
- BigInteger unscaledValue = new BigInteger(value);
- return new BigDecimal(unscaledValue, scale);
- }
-
- /** Create a BigDecimal object using the data in the DrillBuf.
+ /**
+ * Create a BigDecimal object using the data in the DrillBuf.
* This function assumes that data is provided in a non-dense format
* It works on both sparse and intermediate representations.
*/
@@ -183,48 +75,47 @@ public class DecimalUtility extends CoreDecimalUtility {
boolean truncateScale) {
// For sparse decimal type we have padded zeroes at the end, strip them while converting to BigDecimal.
- int actualDigits;
+ int actualDigits = scale % MAX_DIGITS;
// Initialize the BigDecimal, first digit in the DrillBuf has the sign so mask it out
- BigInteger decimalDigits = BigInteger.valueOf((data.getInt(startIndex)) & 0x7FFFFFFF);
+ BigInteger decimalDigits = BigInteger.valueOf(data.getInt(startIndex) & 0x7FFFFFFF);
BigInteger base = BigInteger.valueOf(DIGITS_BASE);
for (int i = 1; i < nDecimalDigits; i++) {
-
- BigInteger temp = BigInteger.valueOf(data.getInt(startIndex + (i * INTEGER_SIZE)));
- decimalDigits = decimalDigits.multiply(base);
- decimalDigits = decimalDigits.add(temp);
+ BigInteger temp = BigInteger.valueOf(data.getInt(startIndex + i * INTEGER_SIZE));
+ decimalDigits = decimalDigits.multiply(base);
+ decimalDigits = decimalDigits.add(temp);
}
// Truncate any additional padding we might have added
- if (truncateScale == true && scale > 0 && (actualDigits = scale % MAX_DIGITS) != 0) {
- BigInteger truncate = BigInteger.valueOf((int)Math.pow(10, (MAX_DIGITS - actualDigits)));
- decimalDigits = decimalDigits.divide(truncate);
+ if (truncateScale && scale > 0 && actualDigits != 0) {
+ BigInteger truncate = BigInteger.valueOf((int) Math.pow(10, MAX_DIGITS - actualDigits));
+ decimalDigits = decimalDigits.divide(truncate);
}
// set the sign
if ((data.getInt(startIndex) & 0x80000000) != 0) {
- decimalDigits = decimalDigits.negate();
+ decimalDigits = decimalDigits.negate();
}
- BigDecimal decimal = new BigDecimal(decimalDigits, scale);
-
- return decimal;
+ return new BigDecimal(decimalDigits, scale);
}
- /* This function returns a BigDecimal object from the dense decimal representation.
+ /**
+ * Returns a BigDecimal object from the dense decimal representation.
* First step is to convert the dense representation into an intermediate representation
* and then invoke getBigDecimalFromDrillBuf() to get the BigDecimal object
*/
- public static BigDecimal getBigDecimalFromDense(DrillBuf data, int startIndex, int nDecimalDigits, int scale, int maxPrecision, int width) {
+ public static BigDecimal getBigDecimalFromDense(DrillBuf data, int startIndex, int nDecimalDigits,
+ int scale, int maxPrecision, int width) {
/* This method converts the dense representation to
* an intermediate representation. The intermediate
* representation has one more integer than the dense
* representation.
*/
- byte[] intermediateBytes = new byte[((nDecimalDigits + 1) * INTEGER_SIZE)];
+ byte[] intermediateBytes = new byte[(nDecimalDigits + 1) * INTEGER_SIZE];
// Start storing from the least significant byte of the first integer
int intermediateIndex = 3;
@@ -236,80 +127,72 @@ public class DecimalUtility extends CoreDecimalUtility {
int shiftOrder;
byte shiftBits;
- // TODO: Some of the logic here is common with casting from Dense to Sparse types, factor out common code
if (maxPrecision == 38) {
- maskIndex = 0;
- shiftOrder = 6;
- shiftBits = 0x00;
- intermediateBytes[intermediateIndex++] = (byte) (data.getByte(startIndex) & 0x7F);
+ maskIndex = 0;
+ shiftOrder = 6;
+ shiftBits = 0x00;
+ intermediateBytes[intermediateIndex++] = (byte) (data.getByte(startIndex) & 0x7F);
} else if (maxPrecision == 28) {
- maskIndex = 1;
- shiftOrder = 4;
- shiftBits = (byte) ((data.getByte(startIndex) & 0x03) << shiftOrder);
- intermediateBytes[intermediateIndex++] = (byte) (((data.getByte(startIndex) & 0x3C) & 0xFF) >>> 2);
+ maskIndex = 1;
+ shiftOrder = 4;
+ shiftBits = (byte) ((data.getByte(startIndex) & 0x03) << shiftOrder);
+ intermediateBytes[intermediateIndex++] = (byte) (((data.getByte(startIndex) & 0x3C) & 0xFF) >>> 2);
} else {
- throw new UnsupportedOperationException("Dense types with max precision 38 and 28 are only supported");
+ throw new UnsupportedOperationException("Dense types with max precision 38 and 28 are only supported");
}
int inputIndex = 1;
boolean sign = false;
if ((data.getByte(startIndex) & 0x80) != 0) {
- sign = true;
+ sign = true;
}
while (inputIndex < width) {
-
intermediateBytes[intermediateIndex] = (byte) ((shiftBits) | (((data.getByte(startIndex + inputIndex) & reverseMask[maskIndex]) & 0xFF) >>> (8 - shiftOrder)));
-
shiftBits = (byte) ((data.getByte(startIndex + inputIndex) & mask[maskIndex]) << shiftOrder);
inputIndex++;
intermediateIndex++;
if (((inputIndex - 1) % INTEGER_SIZE) == 0) {
- shiftBits = (byte) ((shiftBits & 0xFF) >>> 2);
- maskIndex++;
- shiftOrder -= 2;
+ shiftBits = (byte) ((shiftBits & 0xFF) >>> 2);
+ maskIndex++;
+ shiftOrder -= 2;
}
-
}
/* copy the last byte */
intermediateBytes[intermediateIndex] = shiftBits;
- if (sign == true) {
- intermediateBytes[0] = (byte) (intermediateBytes[0] | 0x80);
+ if (sign) {
+ intermediateBytes[0] = (byte) (intermediateBytes[0] | 0x80);
}
final ByteBuf intermediate = UnpooledByteBufAllocator.DEFAULT.buffer(intermediateBytes.length);
try {
- intermediate.setBytes(0, intermediateBytes);
+ intermediate.setBytes(0, intermediateBytes);
- BigDecimal ret = getBigDecimalFromIntermediate(intermediate, 0, nDecimalDigits + 1, scale);
- return ret;
+ // In the intermediate representation we don't pad the scale with zeroes, so set truncate = false
+ return getBigDecimalFromDrillBuf(intermediate, 0, nDecimalDigits + 1, scale, false);
} finally {
intermediate.release();
}
-
}
/**
* Function converts the BigDecimal and stores it in out internal sparse representation
*/
- public static void getSparseFromBigDecimal(BigDecimal input, ByteBuf data, int startIndex, int scale, int precision,
- int nDecimalDigits) {
+ public static void getSparseFromBigDecimal(BigDecimal input, ByteBuf data, int startIndex, int scale, int nDecimalDigits) {
// Initialize the buffer
- for (int i = 0; i < nDecimalDigits; i++) {
- data.setInt(startIndex + (i * INTEGER_SIZE), 0);
- }
+ data.setZero(startIndex, nDecimalDigits * INTEGER_SIZE);
boolean sign = false;
if (input.signum() == -1) {
- // negative input
- sign = true;
- input = input.abs();
+ // negative input
+ sign = true;
+ input = input.abs();
}
// Truncate the input as per the scale provided
@@ -320,25 +203,25 @@ public class DecimalUtility extends CoreDecimalUtility {
int destIndex = nDecimalDigits - roundUp(scale) - 1;
- // we use base 1 billion integer digits for out integernal representation
+ // we use base 1 billion integer digits for out internal representation
BigDecimal base = new BigDecimal(DIGITS_BASE);
while (integerPart.compareTo(BigDecimal.ZERO) == 1) {
- // store the modulo as the integer value
- data.setInt(startIndex + (destIndex * INTEGER_SIZE), (integerPart.remainder(base)).intValue());
- destIndex--;
- // Divide by base 1 billion
- integerPart = (integerPart.divide(base)).setScale(0, BigDecimal.ROUND_DOWN);
+ // store the modulo as the integer value
+ data.setInt(startIndex + destIndex * INTEGER_SIZE, integerPart.remainder(base).intValue());
+ destIndex--;
+ // Divide by base 1 billion
+ integerPart = integerPart.divide(base, BigDecimal.ROUND_DOWN).setScale(0, BigDecimal.ROUND_DOWN);
}
/* Sparse representation contains padding of additional zeroes
* so each digit contains MAX_DIGITS for ease of arithmetic
*/
- int actualDigits;
- if ((actualDigits = (scale % MAX_DIGITS)) != 0) {
- // Pad additional zeroes
- scale = scale + (MAX_DIGITS - actualDigits);
- input = input.setScale(scale, BigDecimal.ROUND_DOWN);
+ int actualDigits = scale % MAX_DIGITS;
+ if (actualDigits != 0) {
+ // Pad additional zeroes
+ scale = scale + MAX_DIGITS - actualDigits;
+ input = input.setScale(scale, BigDecimal.ROUND_DOWN);
}
//separate out the fractional part
@@ -347,15 +230,15 @@ public class DecimalUtility extends CoreDecimalUtility {
destIndex = nDecimalDigits - 1;
while (scale > 0) {
- // Get next set of MAX_DIGITS (9) store it in the DrillBuf
- fractionalPart = fractionalPart.movePointLeft(MAX_DIGITS);
- BigDecimal temp = fractionalPart.remainder(BigDecimal.ONE);
+ // Get next set of MAX_DIGITS (9) store it in the DrillBuf
+ fractionalPart = fractionalPart.movePointLeft(MAX_DIGITS);
+ BigDecimal temp = fractionalPart.remainder(BigDecimal.ONE);
- data.setInt(startIndex + (destIndex * INTEGER_SIZE), (temp.unscaledValue().intValue()));
- destIndex--;
+ data.setInt(startIndex + destIndex * INTEGER_SIZE, temp.unscaledValue().intValue());
+ destIndex--;
- fractionalPart = fractionalPart.setScale(0, BigDecimal.ROUND_DOWN);
- scale -= MAX_DIGITS;
+ fractionalPart = fractionalPart.setScale(0, BigDecimal.ROUND_DOWN);
+ scale -= MAX_DIGITS;
}
// Set the negative sign
@@ -365,93 +248,55 @@ public class DecimalUtility extends CoreDecimalUtility {
}
/**
- * Converts from an input BigDecimal into varying width "VarDecimal" representation.
- * The object that manages the "data" is assumed to already have the proper scale set,
- * matching that of input.scale().
- * @param input input decimal number to be stored
- * @param data destination buffer to store the byte array representation of input
- * @param startIndex starting index in data to hold the bytes
- * @return startIndex + length of bytes stored (i.e., the next startIndex in the data buffer)
+ * Returns unsigned long value taken from specified {@link BigDecimal} input with specified scale
+ *
+ * @param input {@link BigDecimal} with desired value
+ * @param scale scale of the value
+ * @return long value taken from specified {@link BigDecimal}
*/
- public static int getVarDecimalFromBigDecimal(BigDecimal input, ByteBuf data, int startIndex) {
- byte[] bytes = input.unscaledValue().toByteArray();
- int len = bytes.length;
- data.setBytes(startIndex, bytes);
- return startIndex + len;
- }
-
- public static long getDecimal18FromBigDecimal(BigDecimal input, int scale, int precision) {
+ public static long getDecimal18FromBigDecimal(BigDecimal input, int scale) {
// Truncate or pad to set the input to the correct scale
input = input.setScale(scale, BigDecimal.ROUND_HALF_UP);
return input.unscaledValue().longValue();
}
- public static int getDecimal9FromBigDecimal(BigDecimal input, int scale, int precision) {
+ /**
+ * Returns unsigned int value taken from specified {@link BigDecimal} input with specified scale.
+ *
+ * @param input {@link BigDecimal} with desired value
+ * @param scale scale of the value
+ * @return int value taken from specified {@link BigDecimal}
+ */
+ public static int getDecimal9FromBigDecimal(BigDecimal input, int scale) {
// Truncate or pad to set the input to the correct scale
input = input.setScale(scale, BigDecimal.ROUND_HALF_UP);
return input.unscaledValue().intValue();
}
- public static BigDecimal getBigDecimalFromPrimitiveTypes(int input, int scale, int precision) {
+ /**
+ * Returns {@link BigDecimal} value created from specified integer value with specified scale.
+ *
+ * @param input integer value to use for creating of {@link BigDecimal}
+ * @param scale scale for resulting {@link BigDecimal}
+ * @return {@link BigDecimal} value
+ */
+ public static BigDecimal getBigDecimalFromPrimitiveTypes(int input, int scale) {
return BigDecimal.valueOf(input, scale);
}
- public static BigDecimal getBigDecimalFromPrimitiveTypes(long input, int scale, int precision) {
+ /**
+ * Returns {@link BigDecimal} value created from specified long value with specified scale.
+ *
+ * @param input long value to use for creating of {@link BigDecimal}
+ * @param scale scale for resulting {@link BigDecimal}
+ * @return {@link BigDecimal} value
+ */
+ public static BigDecimal getBigDecimalFromPrimitiveTypes(long input, int scale) {
return BigDecimal.valueOf(input, scale);
}
- public static int compareDenseBytes(DrillBuf left, int leftStart, boolean leftSign, DrillBuf right, int rightStart, boolean rightSign, int width) {
-
- int invert = 1;
-
- /* If signs are different then simply look at the
- * sign of the two inputs and determine which is greater
- */
- if (leftSign != rightSign) {
-
- return((leftSign == true) ? -1 : 1);
- } else if(leftSign == true) {
- /* Both inputs are negative, at the end we will
- * have to invert the comparison
- */
- invert = -1;
- }
-
- int cmp = 0;
-
- for (int i = 0; i < width; i++) {
- byte leftByte = left.getByte(leftStart + i);
- byte rightByte = right.getByte(rightStart + i);
- // Unsigned byte comparison
- if ((leftByte & 0xFF) > (rightByte & 0xFF)) {
- cmp = 1;
- break;
- } else if ((leftByte & 0xFF) < (rightByte & 0xFF)) {
- cmp = -1;
- break;
- }
- }
- cmp *= invert; // invert the comparison if both were negative values
-
- return cmp;
- }
-
- public static int getIntegerFromSparseBuffer(DrillBuf buffer, int start, int index) {
- int value = buffer.getInt(start + (index * 4));
-
- if (index == 0) {
- /* the first byte contains sign bit, return value without it */
- value = (value & 0x7FFFFFFF);
- }
- return value;
- }
-
- public static void setInteger(DrillBuf buffer, int start, int index, int value) {
- buffer.setInt(start + (index * 4), value);
- }
-
/**
* Compares two VarDecimal values, still stored in their respective Drill buffers
*
@@ -497,314 +342,6 @@ public class DecimalUtility extends CoreDecimalUtility {
return bdLeft.compareTo(bdRight);
}
- public static int compareSparseBytes(DrillBuf left, int leftStart, boolean leftSign, int leftScale, int leftPrecision, DrillBuf right, int rightStart, boolean rightSign, int rightPrecision, int rightScale, int width, int nDecimalDigits, boolean absCompare) {
-
- int invert = 1;
-
- if (absCompare == false) {
- if (leftSign != rightSign) {
- return (leftSign == true) ? -1 : 1;
- }
-
- // Both values are negative invert the outcome of the comparison
- if (leftSign == true) {
- invert = -1;
- }
- }
-
- int cmp = compareSparseBytesInner(left, leftStart, leftSign, leftScale, leftPrecision, right, rightStart, rightSign, rightPrecision, rightScale, width, nDecimalDigits);
- return cmp * invert;
- }
-
- public static int compareSparseBytesInner(DrillBuf left, int leftStart, boolean leftSign, int leftScale, int leftPrecision, DrillBuf right, int rightStart, boolean rightSign, int rightPrecision, int rightScale, int width, int nDecimalDigits) {
- /* compute the number of integer digits in each decimal */
- int leftInt = leftPrecision - leftScale;
- int rightInt = rightPrecision - rightScale;
-
- /* compute the number of indexes required for storing integer digits */
- int leftIntRoundedUp = org.apache.drill.exec.util.DecimalUtility.roundUp(leftInt);
- int rightIntRoundedUp = org.apache.drill.exec.util.DecimalUtility.roundUp(rightInt);
-
- /* compute number of indexes required for storing scale */
- int leftScaleRoundedUp = org.apache.drill.exec.util.DecimalUtility.roundUp(leftScale);
- int rightScaleRoundedUp = org.apache.drill.exec.util.DecimalUtility.roundUp(rightScale);
-
- /* compute index of the most significant integer digits */
- int leftIndex1 = nDecimalDigits - leftScaleRoundedUp - leftIntRoundedUp;
- int rightIndex1 = nDecimalDigits - rightScaleRoundedUp - rightIntRoundedUp;
-
- int leftStopIndex = nDecimalDigits - leftScaleRoundedUp;
- int rightStopIndex = nDecimalDigits - rightScaleRoundedUp;
-
- /* Discard the zeroes in the integer part */
- while (leftIndex1 < leftStopIndex) {
- if (getIntegerFromSparseBuffer(left, leftStart, leftIndex1) != 0) {
- break;
- }
-
- /* Digit in this location is zero, decrement the actual number
- * of integer digits
- */
- leftIntRoundedUp--;
- leftIndex1++;
- }
-
- /* If we reached the stop index then the number of integers is zero */
- if (leftIndex1 == leftStopIndex) {
- leftIntRoundedUp = 0;
- }
-
- while (rightIndex1 < rightStopIndex) {
- if (getIntegerFromSparseBuffer(right, rightStart, rightIndex1) != 0) {
- break;
- }
-
- /* Digit in this location is zero, decrement the actual number
- * of integer digits
- */
- rightIntRoundedUp--;
- rightIndex1++;
- }
-
- if (rightIndex1 == rightStopIndex) {
- rightIntRoundedUp = 0;
- }
-
- /* We have the accurate number of non-zero integer digits,
- * if the number of integer digits are different then we can determine
- * which decimal is larger and needn't go down to comparing individual values
- */
- if (leftIntRoundedUp > rightIntRoundedUp) {
- return 1;
- }
- else if (rightIntRoundedUp > leftIntRoundedUp) {
- return -1;
- }
-
- /* The number of integer digits are the same, set the each index
- * to the first non-zero integer and compare each digit
- */
- leftIndex1 = nDecimalDigits - leftScaleRoundedUp - leftIntRoundedUp;
- rightIndex1 = nDecimalDigits - rightScaleRoundedUp - rightIntRoundedUp;
-
- while (leftIndex1 < leftStopIndex && rightIndex1 < rightStopIndex) {
- if (getIntegerFromSparseBuffer(left, leftStart, leftIndex1) > getIntegerFromSparseBuffer(right, rightStart, rightIndex1)) {
- return 1;
- }
- else if (getIntegerFromSparseBuffer(right, rightStart, rightIndex1) > getIntegerFromSparseBuffer(left, leftStart, leftIndex1)) {
- return -1;
- }
-
- leftIndex1++;
- rightIndex1++;
- }
-
- /* The integer part of both the decimal's are equal, now compare
- * each individual fractional part. Set the index to be at the
- * beginning of the fractional part
- */
- leftIndex1 = leftStopIndex;
- rightIndex1 = rightStopIndex;
-
- /* Stop indexes will be the end of the array */
- leftStopIndex = nDecimalDigits;
- rightStopIndex = nDecimalDigits;
-
- /* compare the two fractional parts of the decimal */
- while (leftIndex1 < leftStopIndex && rightIndex1 < rightStopIndex) {
- if (getIntegerFromSparseBuffer(left, leftStart, leftIndex1) > getIntegerFromSparseBuffer(right, rightStart, rightIndex1)) {
- return 1;
- }
- else if (getIntegerFromSparseBuffer(right, rightStart, rightIndex1) > getIntegerFromSparseBuffer(left, leftStart, leftIndex1)) {
- return -1;
- }
-
- leftIndex1++;
- rightIndex1++;
- }
-
- /* Till now the fractional part of the decimals are equal, check
- * if one of the decimal has fractional part that is remaining
- * and is non-zero
- */
- while (leftIndex1 < leftStopIndex) {
- if (getIntegerFromSparseBuffer(left, leftStart, leftIndex1) != 0) {
- return 1;
- }
- leftIndex1++;
- }
-
- while(rightIndex1 < rightStopIndex) {
- if (getIntegerFromSparseBuffer(right, rightStart, rightIndex1) != 0) {
- return -1;
- }
- rightIndex1++;
- }
-
- /* Both decimal values are equal */
- return 0;
- }
-
- public static BigDecimal getBigDecimalFromByteArray(byte[] bytes, int start, int length, int scale) {
- byte[] value = Arrays.copyOfRange(bytes, start, start + length);
- BigInteger unscaledValue = new BigInteger(value);
- return new BigDecimal(unscaledValue, scale);
- }
-
- public static void roundDecimal(DrillBuf result, int start, int nDecimalDigits, int desiredScale, int currentScale) {
- int newScaleRoundedUp = org.apache.drill.exec.util.DecimalUtility.roundUp(desiredScale);
- int origScaleRoundedUp = org.apache.drill.exec.util.DecimalUtility.roundUp(currentScale);
-
- if (desiredScale < currentScale) {
-
- boolean roundUp = false;
-
- //Extract the first digit to be truncated to check if we need to round up
- int truncatedScaleIndex = desiredScale + 1;
- if (truncatedScaleIndex <= currentScale) {
- int extractDigitIndex = nDecimalDigits - origScaleRoundedUp -1;
- extractDigitIndex += org.apache.drill.exec.util.DecimalUtility.roundUp(truncatedScaleIndex);
- int extractDigit = getIntegerFromSparseBuffer(result, start, extractDigitIndex);
- int temp = org.apache.drill.exec.util.DecimalUtility.MAX_DIGITS - (truncatedScaleIndex % org.apache.drill.exec.util.DecimalUtility.MAX_DIGITS);
- if (temp != 0) {
- extractDigit = extractDigit / (int) (Math.pow(10, temp));
- }
- if ((extractDigit % 10) > 4) {
- roundUp = true;
- }
- }
-
- // Get the source index beyond which we will truncate
- int srcIntIndex = nDecimalDigits - origScaleRoundedUp - 1;
- int srcIndex = srcIntIndex + newScaleRoundedUp;
-
- // Truncate the remaining fractional part, move the integer part
- int destIndex = nDecimalDigits - 1;
- if (srcIndex != destIndex) {
- while (srcIndex >= 0) {
- setInteger(result, start, destIndex--, getIntegerFromSparseBuffer(result, start, srcIndex--));
- }
-
- // Set the remaining portion of the decimal to be zeroes
- while (destIndex >= 0) {
- setInteger(result, start, destIndex--, 0);
- }
- srcIndex = nDecimalDigits - 1;
- }
-
- // We truncated the decimal digit. Now we need to truncate within the base 1 billion fractional digit
- int truncateFactor = org.apache.drill.exec.util.DecimalUtility.MAX_DIGITS - (desiredScale % org.apache.drill.exec.util.DecimalUtility.MAX_DIGITS);
- if (truncateFactor != org.apache.drill.exec.util.DecimalUtility.MAX_DIGITS) {
- truncateFactor = (int) Math.pow(10, truncateFactor);
- int fractionalDigits = getIntegerFromSparseBuffer(result, start, nDecimalDigits - 1);
- fractionalDigits /= truncateFactor;
- setInteger(result, start, nDecimalDigits - 1, fractionalDigits * truncateFactor);
- }
-
- // Finally round up the digit if needed
- if (roundUp == true) {
- srcIndex = nDecimalDigits - 1;
- int carry;
- if (truncateFactor != org.apache.drill.exec.util.DecimalUtility.MAX_DIGITS) {
- carry = truncateFactor;
- } else {
- carry = 1;
- }
-
- while (srcIndex >= 0) {
- int value = getIntegerFromSparseBuffer(result, start, srcIndex);
- value += carry;
-
- if (value >= org.apache.drill.exec.util.DecimalUtility.DIGITS_BASE) {
- setInteger(result, start, srcIndex--, value % org.apache.drill.exec.util.DecimalUtility.DIGITS_BASE);
- carry = value / org.apache.drill.exec.util.DecimalUtility.DIGITS_BASE;
- } else {
- setInteger(result, start, srcIndex--, value);
- carry = 0;
- break;
- }
- }
- }
- } else if (desiredScale > currentScale) {
- // Add fractional digits to the decimal
-
- // Check if we need to shift the decimal digits to the left
- if (newScaleRoundedUp > origScaleRoundedUp) {
- int srcIndex = 0;
- int destIndex = newScaleRoundedUp - origScaleRoundedUp;
-
- // Check while extending scale, we are not overwriting integer part
- while (srcIndex < destIndex) {
- if (getIntegerFromSparseBuffer(result, start, srcIndex++) != 0) {
- throw new org.apache.drill.common.exceptions.DrillRuntimeException("Truncate resulting in loss of integer part, reduce scale specified");
- }
- }
-
- srcIndex = 0;
- while (destIndex < nDecimalDigits) {
- setInteger(result, start, srcIndex++, getIntegerFromSparseBuffer(result, start, destIndex++));
- }
-
- // Clear the remaining part
- while (srcIndex < nDecimalDigits) {
- setInteger(result, start, srcIndex++, 0);
- }
- }
- }
- }
-
- public static int getFirstFractionalDigit(int decimal, int scale) {
- if (scale == 0) {
- return 0;
- }
- int temp = (int) adjustScaleDivide(decimal, scale - 1);
- return Math.abs(temp % 10);
- }
-
- public static int getFirstFractionalDigit(long decimal, int scale) {
- if (scale == 0) {
- return 0;
- }
- long temp = adjustScaleDivide(decimal, scale - 1);
- return (int) (Math.abs(temp % 10));
- }
-
- public static int getFirstFractionalDigit(DrillBuf data, int scale, int start, int nDecimalDigits) {
- if (scale == 0) {
- return 0;
- }
-
- int index = nDecimalDigits - roundUp(scale);
- return (int) (adjustScaleDivide(data.getInt(start + (index * INTEGER_SIZE)), MAX_DIGITS - 1));
- }
-
- public static int compareSparseSamePrecScale(DrillBuf left, int lStart, byte[] right, int length) {
- // check the sign first
- boolean lSign = (left.getInt(lStart) & 0x80000000) != 0;
- boolean rSign = ByteFunctionHelpers.getSign(right);
- int cmp = 0;
-
- if (lSign != rSign) {
- return (lSign == false) ? 1 : -1;
- }
-
- // invert the comparison if we are comparing negative numbers
- int invert = (lSign == true) ? -1 : 1;
-
- // compare byte by byte
- int n = 0;
- while (n < length/4) {
- int leftInt = Decimal38SparseHolder.getInteger(n, lStart, left);
- int rightInt = ByteFunctionHelpers.getInteger(right, n);
- if (leftInt != rightInt) {
- cmp = (leftInt - rightInt ) > 0 ? 1 : -1;
- break;
- }
- n++;
- }
- return cmp * invert;
- }
-
/**
* Returns max length of byte array, required to store value with specified precision.
*
@@ -817,6 +354,13 @@ public class DecimalUtility extends CoreDecimalUtility {
return 0;
}
if (precision < 300) { // normal case, use exact heuristic formula
+ // Math.pow(10, precision) - 1 returns max integer value for the specified precision, example 999 for precision 3
+ // Math.log(Math.pow(10, precision) - 1) / Math.log(2) is just log with base 2 to calculate size
+ // in bits for max integer value mentioned above
+ // Math.log(Math.pow(10, precision) - 1) / Math.log(2) + 1 in this expression was added 1 to the count of bits to
+ // take into account case with negative value
+ // size in bits was divided by size of byte to calculate bytes count required to store value
+ // with the specified precision
return (int) Math.ceil((Math.log(Math.pow(10, precision) - 1) / Math.log(2) + 1) / Byte.SIZE);
} else {
// for values greater than 304 Math.pow(10, precision) returns Infinity, therefore 1 is neglected in Math.log()
diff --git a/exec/vector/src/main/java/org/apache/drill/exec/vector/ValueHolderHelper.java b/exec/vector/src/main/java/org/apache/drill/exec/vector/ValueHolderHelper.java
index d1cc3b4..73027aa 100644
--- a/exec/vector/src/main/java/org/apache/drill/exec/vector/ValueHolderHelper.java
+++ b/exec/vector/src/main/java/org/apache/drill/exec/vector/ValueHolderHelper.java
@@ -127,7 +127,7 @@ public class ValueHolderHelper {
byte[] b = s.getBytes(Charsets.UTF_8);
vch.start = 0;
vch.end = b.length;
- vch.buffer = a.buffer(b.length); //
+ vch.buffer = a.buffer(b.length);
vch.buffer.setBytes(0, b);
return vch;
}
@@ -180,7 +180,7 @@ public class ValueHolderHelper {
dch.start = 0;
dch.buffer = buf.reallocIfNeeded(5 * DecimalUtility.INTEGER_SIZE);
DecimalUtility
- .getSparseFromBigDecimal(bigDecimal, dch.buffer, dch.start, dch.scale, dch.precision, dch.nDecimalDigits);
+ .getSparseFromBigDecimal(bigDecimal, dch.buffer, dch.start, dch.scale, Decimal28SparseHolder.nDecimalDigits);
return dch;
}
@@ -195,9 +195,9 @@ public class ValueHolderHelper {
dch.precision = bigDecimal.precision();
Decimal38SparseHolder.setSign(bigDecimal.signum() == -1, dch.start, dch.buffer);
dch.start = 0;
- dch.buffer = buf.reallocIfNeeded(dch.maxPrecision * DecimalUtility.INTEGER_SIZE);
+ dch.buffer = buf.reallocIfNeeded(Decimal38SparseHolder.maxPrecision * DecimalUtility.INTEGER_SIZE);
DecimalUtility
- .getSparseFromBigDecimal(bigDecimal, dch.buffer, dch.start, dch.scale, dch.precision, dch.nDecimalDigits);
+ .getSparseFromBigDecimal(bigDecimal, dch.buffer, dch.start, dch.scale, Decimal38SparseHolder.nDecimalDigits);
return dch;
}
diff --git a/logical/src/main/java/org/apache/drill/common/expression/ValueExpressions.java b/logical/src/main/java/org/apache/drill/common/expression/ValueExpressions.java
index 2ef809a..538e6c8 100644
--- a/logical/src/main/java/org/apache/drill/common/expression/ValueExpressions.java
+++ b/logical/src/main/java/org/apache/drill/common/expression/ValueExpressions.java
@@ -28,7 +28,6 @@ import org.apache.drill.common.types.TypeProtos.DataMode;
import org.apache.drill.common.types.TypeProtos.MajorType;
import org.apache.drill.common.types.TypeProtos.MinorType;
import org.apache.drill.common.types.Types;
-import org.apache.drill.common.util.CoreDecimalUtility;
import com.google.common.collect.Iterators;
@@ -94,22 +93,6 @@ public class ValueExpressions {
return new IntervalDayExpression(intervalInMillis);
}
- public static LogicalExpression getDecimal9(BigDecimal i) {
- return new Decimal9Expression(i, ExpressionPosition.UNKNOWN);
- }
-
- public static LogicalExpression getDecimal18(BigDecimal i) {
- return new Decimal18Expression(i, ExpressionPosition.UNKNOWN);
- }
-
- public static LogicalExpression getDecimal28(BigDecimal i) {
- return new Decimal28Expression(i, ExpressionPosition.UNKNOWN);
- }
-
- public static LogicalExpression getDecimal38(BigDecimal i) {
- return new Decimal38Expression(i, ExpressionPosition.UNKNOWN);
- }
-
public static LogicalExpression getVarDecimal(BigDecimal input, int precision, int scale) {
return new VarDecimalExpression(input, precision, scale, ExpressionPosition.UNKNOWN);
}
@@ -265,7 +248,7 @@ public class ValueExpressions {
super(pos);
this.scale = input.scale();
this.precision = input.precision();
- this.decimal = CoreDecimalUtility.getDecimal9FromBigDecimal(input, scale, precision);
+ this.decimal = input.setScale(scale, BigDecimal.ROUND_HALF_UP).intValue();
}
@@ -307,7 +290,7 @@ public class ValueExpressions {
super(pos);
this.scale = input.scale();
this.precision = input.precision();
- this.decimal = CoreDecimalUtility.getDecimal18FromBigDecimal(input, scale, precision);
+ this.decimal = input.setScale(scale, BigDecimal.ROUND_HALF_UP).longValue();
}
--
To stop receiving notification emails like this one, please contact
arina@apache.org.
[drill] 07/08: DRILL-4525: Allow SqlBetweenOperator to accept
LOWER_OPERAND and UPPER_OPERAND with different types
Posted by ar...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
arina pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/drill.git
commit 1a28fd8c666a81bec2a453dbc26150349ac66cc0
Author: Hsuan-Yi Chu <hs...@usc.edu>
AuthorDate: Mon Mar 21 14:43:54 2016 -0700
DRILL-4525: Allow SqlBetweenOperator to accept LOWER_OPERAND and UPPER_OPERAND with different types
---
.../sql/DrillCalciteSqlBetweenOperatorWrapper.java | 82 ++++++++++++++++++++++
.../drill/exec/planner/sql/DrillOperatorTable.java | 18 ++++-
.../drill/TestFunctionsWithTypeExpoQueries.java | 44 ++++++++++++
3 files changed, 142 insertions(+), 2 deletions(-)
diff --git a/exec/java-exec/src/main/java/org/apache/drill/exec/planner/sql/DrillCalciteSqlBetweenOperatorWrapper.java b/exec/java-exec/src/main/java/org/apache/drill/exec/planner/sql/DrillCalciteSqlBetweenOperatorWrapper.java
new file mode 100644
index 0000000..e26da95
--- /dev/null
+++ b/exec/java-exec/src/main/java/org/apache/drill/exec/planner/sql/DrillCalciteSqlBetweenOperatorWrapper.java
@@ -0,0 +1,82 @@
+/**
+ * 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.drill.exec.planner.sql;
+
+import com.google.common.collect.Lists;
+
+import org.apache.calcite.rel.type.RelDataType;
+import org.apache.calcite.sql.fun.SqlBetweenOperator;
+import org.apache.calcite.sql.SqlCallBinding;
+import org.apache.calcite.sql.SqlOperator;
+import org.apache.calcite.sql.type.SqlTypeName;
+import org.apache.calcite.sql.type.SqlTypeUtil;
+
+import org.apache.drill.common.types.TypeProtos;
+import org.apache.drill.exec.resolver.TypeCastRules;
+
+import java.util.List;
+
+/**
+ * This class serves as a wrapper class for SqlBetweenOperator. The motivation is to plug-in the return type inference and operand
+ * type check algorithms of Drill into Calcite's sql validation procedure.
+ *
+ * Except for the methods which are relevant to the return type inference and operand type check algorithms, the wrapper
+ * simply forwards the method calls to the wrapped SqlOperator.
+ *
+ * Note that SqlBetweenOperator cannot be wrapped in {@link DrillCalciteSqlOperatorWrapper}. The reason is when RexNode
+ * conversion is happening, StandardConvertletTable.convertBetween expects the SqlOperator to be a subclass of SqlBetweenOperator.
+ */
+public class DrillCalciteSqlBetweenOperatorWrapper extends SqlBetweenOperator implements DrillCalciteSqlWrapper {
+ private final SqlBetweenOperator operator;
+
+ public DrillCalciteSqlBetweenOperatorWrapper(SqlBetweenOperator sqlBetweenOperator) {
+ super(sqlBetweenOperator.flag, sqlBetweenOperator.isNegated());
+ operator = sqlBetweenOperator;
+ }
+
+ @Override
+ public SqlOperator getOperator() {
+ return operator;
+ }
+
+ /**
+ *
+ * Since Calcite has its rule for type compatibility (see {@link SqlTypeUtil#isComparable(RelDataType, RelDataType)}),
+ * which is usually different from Drill's, this method is overridden here to avoid Calcite early terminating the
+ * queries.
+ */
+ @Override
+ public boolean checkOperandTypes(
+ SqlCallBinding callBinding,
+ boolean throwOnFailure) {
+ final List<TypeProtos.MinorType> types = Lists.newArrayList();
+ for(int i = 0; i < callBinding.getOperandCount(); ++i) {
+ final TypeProtos.MinorType inMinorType = TypeInferenceUtils.getDrillTypeFromCalciteType(callBinding.getOperandType(i));
+ if(inMinorType == TypeProtos.MinorType.LATE) {
+ return true;
+ }
+ types.add(inMinorType);
+ }
+
+ final boolean isCompatible = TypeCastRules.getLeastRestrictiveType(types) != null;
+ if(!isCompatible && throwOnFailure) {
+ throw callBinding.newValidationSignatureError();
+ }
+ return isCompatible;
+ }
+}
diff --git a/exec/java-exec/src/main/java/org/apache/drill/exec/planner/sql/DrillOperatorTable.java b/exec/java-exec/src/main/java/org/apache/drill/exec/planner/sql/DrillOperatorTable.java
index cf858d3..d533c19 100644
--- a/exec/java-exec/src/main/java/org/apache/drill/exec/planner/sql/DrillOperatorTable.java
+++ b/exec/java-exec/src/main/java/org/apache/drill/exec/planner/sql/DrillOperatorTable.java
@@ -22,6 +22,7 @@ import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.calcite.sql.SqlAggFunction;
import org.apache.calcite.sql.SqlFunction;
+import org.apache.calcite.sql.fun.SqlBetweenOperator;
import org.apache.drill.common.expression.FunctionCallFactory;
import org.apache.drill.exec.expr.fn.DrillFuncHolder;
import org.apache.drill.exec.expr.fn.FunctionImplementationRegistry;
@@ -174,10 +175,23 @@ public class DrillOperatorTable extends SqlStdOperatorTable {
} else if(calciteOperator instanceof SqlFunction) {
wrapper = new DrillCalciteSqlFunctionWrapper((SqlFunction) calciteOperator,
getFunctionListWithInference(calciteOperator.getName()));
+ } else if(calciteOperator instanceof SqlBetweenOperator) {
+ // During the procedure of converting to RexNode,
+ // StandardConvertletTable.convertBetween expects the SqlOperator to be a subclass of SqlBetweenOperator
+ final SqlBetweenOperator sqlBetweenOperator = (SqlBetweenOperator) calciteOperator;
+ wrapper = new DrillCalciteSqlBetweenOperatorWrapper(sqlBetweenOperator);
} else {
- final String drillOpName = FunctionCallFactory.replaceOpWithFuncName(calciteOperator.getName());
+ final String drillOpName;
+ // For UNARY_MINUS (-) or UNARY_PLUS (+), we do not rename them as function_add or function_subtract.
+ // Otherwise, Calcite will mix them up with binary operator subtract (-) or add (+)
+ if(calciteOperator == SqlStdOperatorTable.UNARY_MINUS || calciteOperator == SqlStdOperatorTable.UNARY_PLUS) {
+ drillOpName = calciteOperator.getName();
+ } else {
+ drillOpName = FunctionCallFactory.replaceOpWithFuncName(calciteOperator.getName());
+ }
+
final List<DrillFuncHolder> drillFuncHolders = getFunctionListWithInference(drillOpName);
- if(drillFuncHolders.isEmpty() || calciteOperator == SqlStdOperatorTable.UNARY_MINUS || calciteOperator == SqlStdOperatorTable.UNARY_PLUS) {
+ if(drillFuncHolders.isEmpty()) {
continue;
}
diff --git a/exec/java-exec/src/test/java/org/apache/drill/TestFunctionsWithTypeExpoQueries.java b/exec/java-exec/src/test/java/org/apache/drill/TestFunctionsWithTypeExpoQueries.java
index d298acc..74676de 100644
--- a/exec/java-exec/src/test/java/org/apache/drill/TestFunctionsWithTypeExpoQueries.java
+++ b/exec/java-exec/src/test/java/org/apache/drill/TestFunctionsWithTypeExpoQueries.java
@@ -740,4 +740,48 @@ public class TestFunctionsWithTypeExpoQueries extends BaseTestQuery {
final String[] excludedPlan = {};
PlanTestBase.testPlanMatchingPatterns(query, expectedPlan, excludedPlan);
}
+
+ @Test // DRILL-4525
+ public void testBetweenDateAndTimeStamp() throws Exception {
+ final String query = "select count(*) as col \n" +
+ "from cp.`employee.json` \n" +
+ "where cast(birth_date as DATE) BETWEEN cast('1970-01-01' AS DATE) AND (cast('1999-01-01' AS DATE) + INTERVAL '60' day) \n" +
+ "limit 0";
+
+ final TypeProtos.MajorType majorType = TypeProtos.MajorType.newBuilder()
+ .setMinorType(TypeProtos.MinorType.BIGINT)
+ .setMode(TypeProtos.DataMode.REQUIRED)
+ .build();
+
+ final List<Pair<SchemaPath, TypeProtos.MajorType>> expectedSchema = Lists.newArrayList();
+ expectedSchema.add(Pair.of(SchemaPath.getSimplePath("col"), majorType));
+
+ testBuilder()
+ .sqlQuery(query)
+ .schemaBaseLine(expectedSchema)
+ .build()
+ .run();
+ }
+
+ @Test // DRILL-4525
+ public void testBetweenDecimalAndDouble() throws Exception {
+ final String query = "select cast(r_regionkey as Integer) as col \n" +
+ "from cp.`tpch/region.parquet` \n" +
+ "where cast(r_regionkey as double) BETWEEN 1.1 AND 4.5 \n" +
+ "limit 0";
+
+ final TypeProtos.MajorType majorType = TypeProtos.MajorType.newBuilder()
+ .setMinorType(TypeProtos.MinorType.INT)
+ .setMode(TypeProtos.DataMode.OPTIONAL)
+ .build();
+
+ final List<Pair<SchemaPath, TypeProtos.MajorType>> expectedSchema = Lists.newArrayList();
+ expectedSchema.add(Pair.of(SchemaPath.getSimplePath("col"), majorType));
+
+ testBuilder()
+ .sqlQuery(query)
+ .schemaBaseLine(expectedSchema)
+ .build()
+ .run();
+ }
}
--
To stop receiving notification emails like this one, please contact
arina@apache.org.
[drill] 01/08: DRILL-6420: Add Lateral and Unnest Keyword for
highlighting on WebUI
Posted by ar...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
arina pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/drill.git
commit 5a3a73ad098f77ad01d9366dc1a0f8f4ac539746
Author: Sorabh Hamirwasia <sh...@maprtech.com>
AuthorDate: Fri May 4 10:47:28 2018 -0700
DRILL-6420: Add Lateral and Unnest Keyword for highlighting on WebUI
closes #1261
---
.../src/main/resources/rest/static/js/ace-code-editor/mode-sql.js | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/exec/java-exec/src/main/resources/rest/static/js/ace-code-editor/mode-sql.js b/exec/java-exec/src/main/resources/rest/static/js/ace-code-editor/mode-sql.js
index 992fdb6..ceb47c8 100644
--- a/exec/java-exec/src/main/resources/rest/static/js/ace-code-editor/mode-sql.js
+++ b/exec/java-exec/src/main/resources/rest/static/js/ace-code-editor/mode-sql.js
@@ -15,11 +15,11 @@ var SqlHighlightRules = function() {
//Covered: https://drill.apache.org/docs/supported-sql-commands/
var keywords = (
"select|insert|update|delete|from|where|and|or|group|by|order|limit|offset|having|as|case|" +
- "when|else|end|type|left|right|join|on|outer|desc|asc|union|create|table|key|if|" +
+ "when|else|end|type|left|right|join|on|outer|desc|asc|union|create|table|key|if|lateral|apply|unnest|" +
"not|default|null|inner|database|drop|" +
"flatten|kvgen|columns|" +
"set|reset|alter|session|system|" +
- "temporary|function|using|jar|between|distinct" +
+ "temporary|function|using|jar|between|distinct|" +
"partition|view|schema|files|" +
"explain|plan|with|without|implementation|" +
"show|describe|use"
--
To stop receiving notification emails like this one, please contact
arina@apache.org.
[drill] 05/08: DRILL-6413: Update
ParquetFilterBuilder.visitBooleanOperator to handle simplified boolean
expression
Posted by ar...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
arina pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/drill.git
commit 5d22d708252bd5a84fe2f277f2b8b9a6abc0d9ce
Author: Arina Ielchiieva <ar...@gmail.com>
AuthorDate: Thu May 17 18:24:35 2018 +0300
DRILL-6413: Update ParquetFilterBuilder.visitBooleanOperator to handle simplified boolean expression
closes #1269
---
.../store/parquet/AbstractParquetGroupScan.java | 3 +--
.../exec/store/parquet/ParquetFilterBuilder.java | 19 +++++++++++++++----
.../store/parquet/TestParquetFilterPushDown.java | 22 +++++++++++-----------
3 files changed, 27 insertions(+), 17 deletions(-)
diff --git a/exec/java-exec/src/main/java/org/apache/drill/exec/store/parquet/AbstractParquetGroupScan.java b/exec/java-exec/src/main/java/org/apache/drill/exec/store/parquet/AbstractParquetGroupScan.java
index 1f8c535..33472bb 100644
--- a/exec/java-exec/src/main/java/org/apache/drill/exec/store/parquet/AbstractParquetGroupScan.java
+++ b/exec/java-exec/src/main/java/org/apache/drill/exec/store/parquet/AbstractParquetGroupScan.java
@@ -255,8 +255,7 @@ public abstract class AbstractParquetGroupScan extends AbstractFileGroupScan {
logger.debug("materializedFilter : {}", ExpressionStringBuilder.toString(materializedFilter));
Set<LogicalExpression> constantBoundaries = ConstantExpressionIdentifier.getConstantExpressionSet(materializedFilter);
- filterPredicate = (ParquetFilterPredicate) ParquetFilterBuilder.buildParquetFilterPredicate(
- materializedFilter, constantBoundaries, udfUtilities);
+ filterPredicate = ParquetFilterBuilder.buildParquetFilterPredicate(materializedFilter, constantBoundaries, udfUtilities);
if (filterPredicate == null) {
return null;
diff --git a/exec/java-exec/src/main/java/org/apache/drill/exec/store/parquet/ParquetFilterBuilder.java b/exec/java-exec/src/main/java/org/apache/drill/exec/store/parquet/ParquetFilterBuilder.java
index e55425e..a8e101d 100644
--- a/exec/java-exec/src/main/java/org/apache/drill/exec/store/parquet/ParquetFilterBuilder.java
+++ b/exec/java-exec/src/main/java/org/apache/drill/exec/store/parquet/ParquetFilterBuilder.java
@@ -42,6 +42,7 @@ import org.apache.drill.exec.expr.holders.ValueHolder;
import org.apache.drill.exec.expr.holders.VarDecimalHolder;
import org.apache.drill.exec.expr.stat.ParquetBooleanPredicates;
import org.apache.drill.exec.expr.stat.ParquetComparisonPredicates;
+import org.apache.drill.exec.expr.stat.ParquetFilterPredicate;
import org.apache.drill.exec.expr.stat.ParquetIsPredicates;
import org.apache.drill.exec.ops.UdfUtilities;
import org.apache.drill.exec.util.DecimalUtility;
@@ -54,7 +55,7 @@ import java.util.Set;
/**
* A visitor which visits a materialized logical expression, and build ParquetFilterPredicate
- * If a visitXXX method returns null, that means the corresponding filter branch is not qualified for pushdown.
+ * If a visitXXX method returns null, that means the corresponding filter branch is not qualified for push down.
*/
public class ParquetFilterBuilder extends AbstractExprVisitor<LogicalExpression, Set<LogicalExpression>, RuntimeException> {
static final Logger logger = LoggerFactory.getLogger(ParquetFilterBuilder.class);
@@ -66,12 +67,18 @@ public class ParquetFilterBuilder extends AbstractExprVisitor<LogicalExpression,
* @param constantBoundaries set of constant expressions
* @param udfUtilities udf utilities
*
- * @return logical expression
+ * @return parquet filter predicate
*/
- public static LogicalExpression buildParquetFilterPredicate(LogicalExpression expr, final Set<LogicalExpression> constantBoundaries, UdfUtilities udfUtilities) {
- return expr.accept(new ParquetFilterBuilder(udfUtilities), constantBoundaries);
+ public static ParquetFilterPredicate buildParquetFilterPredicate(LogicalExpression expr, final Set<LogicalExpression> constantBoundaries, UdfUtilities udfUtilities) {
+ LogicalExpression logicalExpression = expr.accept(new ParquetFilterBuilder(udfUtilities), constantBoundaries);
+ if (logicalExpression instanceof ParquetFilterPredicate) {
+ return (ParquetFilterPredicate) logicalExpression;
+ }
+ logger.debug("Logical expression {} was not qualified for filter push down", logicalExpression);
+ return null;
}
+
private ParquetFilterBuilder(UdfUtilities udfUtilities) {
this.udfUtilities = udfUtilities;
}
@@ -150,6 +157,10 @@ public class ParquetFilterBuilder extends AbstractExprVisitor<LogicalExpression,
return null;
}
} else {
+ if (childPredicate instanceof TypedFieldExpr) {
+ // Calcite simplifies `= true` expression to field name, wrap it with is true predicate
+ childPredicate = new ParquetIsPredicates.IsTruePredicate(childPredicate);
+ }
childPredicates.add(childPredicate);
}
}
diff --git a/exec/java-exec/src/test/java/org/apache/drill/exec/store/parquet/TestParquetFilterPushDown.java b/exec/java-exec/src/test/java/org/apache/drill/exec/store/parquet/TestParquetFilterPushDown.java
index 83a4e8e..3bbd397 100644
--- a/exec/java-exec/src/test/java/org/apache/drill/exec/store/parquet/TestParquetFilterPushDown.java
+++ b/exec/java-exec/src/test/java/org/apache/drill/exec/store/parquet/TestParquetFilterPushDown.java
@@ -26,6 +26,7 @@ import org.apache.drill.exec.proto.BitControl;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
+import org.apache.parquet.format.converter.ParquetMetadataConverter;
import org.apache.parquet.hadoop.ParquetFileReader;
import org.apache.parquet.hadoop.metadata.ParquetMetadata;
import org.junit.Assert;
@@ -424,6 +425,9 @@ public class TestParquetFilterPushDown extends PlanTestBase {
final String queryNotEqualFalse = "select col_bln from dfs.`parquetFilterPush/blnTbl` where not col_bln = false";
testParquetFilterPD(queryNotEqualFalse, 4, 2, false);
+
+ final String queryEqualTrueWithAnd = "select col_bln from dfs.`parquetFilterPush/blnTbl` where col_bln = true and unk_col = 'a'";
+ testParquetFilterPD(queryEqualTrueWithAnd, 0, 2, false);
}
@Test // DRILL-5359
@@ -445,10 +449,9 @@ public class TestParquetFilterPushDown extends PlanTestBase {
public void testMultiRowGroup() throws Exception {
// multirowgroup is a parquet file with 2 rowgroups inside. One with a = 1 and the other with a = 2;
// FilterPushDown should be able to remove the rowgroup with a = 1 from the scan operator.
- final String sql = String.format("select * from dfs.`parquet/multirowgroup.parquet` where a > 1");
+ final String sql = "select * from dfs.`parquet/multirowgroup.parquet` where a > 1";
final String[] expectedPlan = {"numRowGroups=1"};
- final String[] excludedPlan = {};
- PlanTestBase.testPlanMatchingPatterns(sql, expectedPlan, excludedPlan);
+ PlanTestBase.testPlanMatchingPatterns(sql, expectedPlan);
}
//////////////////////////////////////////////////////////////////////////////////////////////////
@@ -461,23 +464,20 @@ public class TestParquetFilterPushDown extends PlanTestBase {
String numFilesPattern = "numFiles=" + expectedNumFiles;
String usedMetaPattern = "usedMetadataFile=" + usedMetadataFile;
- testPlanMatchingPatterns(query, new String[]{numFilesPattern, usedMetaPattern}, new String[] {});
+ testPlanMatchingPatterns(query, new String[]{numFilesPattern, usedMetaPattern});
}
- private void testParquetRowGroupFilterEval(final ParquetMetadata footer, final String exprStr,
- boolean canDropExpected) throws Exception{
+ private void testParquetRowGroupFilterEval(final ParquetMetadata footer, final String exprStr, boolean canDropExpected) throws Exception{
final LogicalExpression filterExpr = parseExpr(exprStr);
testParquetRowGroupFilterEval(footer, 0, filterExpr, canDropExpected);
}
- private void testParquetRowGroupFilterEval(final ParquetMetadata footer, final int rowGroupIndex,
- final LogicalExpression filterExpr, boolean canDropExpected) throws Exception {
- boolean canDrop = ParquetRGFilterEvaluator.evalFilter(filterExpr, footer, rowGroupIndex,
- fragContext.getOptions(), fragContext);
+ private void testParquetRowGroupFilterEval(final ParquetMetadata footer, final int rowGroupIndex, final LogicalExpression filterExpr, boolean canDropExpected) {
+ boolean canDrop = ParquetRGFilterEvaluator.evalFilter(filterExpr, footer, rowGroupIndex, fragContext.getOptions(), fragContext);
Assert.assertEquals(canDropExpected, canDrop);
}
private ParquetMetadata getParquetMetaData(File file) throws IOException{
- return ParquetFileReader.readFooter(new Configuration(fs.getConf()), new Path(file.toURI()));
+ return ParquetFileReader.readFooter(new Configuration(fs.getConf()), new Path(file.toURI()), ParquetMetadataConverter.NO_FILTER);
}
}
--
To stop receiving notification emails like this one, please contact
arina@apache.org.