You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@drill.apache.org by ja...@apache.org on 2013/09/04 13:09:50 UTC
[20/52] [abbrv] [partial] DRILL-165: Reorganize directories (moves
only)
http://git-wip-us.apache.org/repos/asf/incubator-drill/blob/a593d908/exec/java-exec/src/test/java/org/apache/drill/exec/record/ExpressionTreeMaterializerTest.java
----------------------------------------------------------------------
diff --git a/exec/java-exec/src/test/java/org/apache/drill/exec/record/ExpressionTreeMaterializerTest.java b/exec/java-exec/src/test/java/org/apache/drill/exec/record/ExpressionTreeMaterializerTest.java
new file mode 100644
index 0000000..f0d9901
--- /dev/null
+++ b/exec/java-exec/src/test/java/org/apache/drill/exec/record/ExpressionTreeMaterializerTest.java
@@ -0,0 +1,210 @@
+package org.apache.drill.exec.record;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import java.util.List;
+
+import mockit.Injectable;
+import mockit.NonStrictExpectations;
+
+import org.apache.drill.common.expression.ArgumentValidator;
+import org.apache.drill.common.expression.ErrorCollector;
+import org.apache.drill.common.expression.ErrorCollectorImpl;
+import org.apache.drill.common.expression.ExpressionPosition;
+import org.apache.drill.common.expression.FieldReference;
+import org.apache.drill.common.expression.FunctionCall;
+import org.apache.drill.common.expression.FunctionDefinition;
+import org.apache.drill.common.expression.IfExpression;
+import org.apache.drill.common.expression.LogicalExpression;
+import org.apache.drill.common.expression.OutputTypeDeterminer;
+import org.apache.drill.common.expression.ValueExpressions;
+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.exec.exception.SchemaChangeException;
+import org.apache.drill.exec.expr.ExpressionTreeMaterializer;
+import org.apache.drill.exec.proto.SchemaDefProtos.FieldDef;
+import org.apache.drill.exec.proto.SchemaDefProtos.NamePart;
+import org.junit.Test;
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.Range;
+
+public class ExpressionTreeMaterializerTest {
+
+ static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(ExpressionTreeMaterializerTest.class);
+
+ final MajorType boolConstant = MajorType.newBuilder().setMode(DataMode.REQUIRED).setMinorType(MinorType.BIT).build();
+ final MajorType bigIntType = MajorType.newBuilder().setMode(DataMode.REQUIRED).setMinorType(MinorType.BIGINT).build();
+ final MajorType intType = MajorType.newBuilder().setMode(DataMode.REQUIRED).setMinorType(MinorType.INT).build();
+
+ private MaterializedField getField(int fieldId, String name, MajorType type) {
+ return new MaterializedField(FieldDef.newBuilder().setMajorType(type).addName(NamePart.newBuilder().setName(name))
+ .build());
+ }
+
+ @Test
+ public void testMaterializingConstantTree(@Injectable RecordBatch batch) throws SchemaChangeException {
+
+ ErrorCollector ec = new ErrorCollectorImpl();
+ LogicalExpression expr = ExpressionTreeMaterializer.materialize(new ValueExpressions.LongExpression(1L,
+ ExpressionPosition.UNKNOWN), batch, ec);
+ assertTrue(expr instanceof ValueExpressions.LongExpression);
+ assertEquals(1L, ValueExpressions.LongExpression.class.cast(expr).getLong());
+ assertFalse(ec.hasErrors());
+ }
+
+ @Test
+ public void testMaterializingLateboundField(final @Injectable RecordBatch batch) throws SchemaChangeException {
+ final SchemaBuilder builder = BatchSchema.newBuilder();
+ builder.addField(getField(2, "test", bigIntType));
+ final BatchSchema schema = builder.build();
+
+ new NonStrictExpectations() {
+ {
+ batch.getValueVectorId(new FieldReference("test", ExpressionPosition.UNKNOWN));
+ result = new TypedFieldId(Types.required(MinorType.BIGINT), -5);
+ }
+ };
+
+ ErrorCollector ec = new ErrorCollectorImpl();
+ LogicalExpression expr = ExpressionTreeMaterializer.materialize(new FieldReference("test",
+ ExpressionPosition.UNKNOWN), batch, ec);
+ assertEquals(bigIntType, expr.getMajorType());
+ assertFalse(ec.hasErrors());
+ }
+
+ @Test
+ public void testMaterializingLateboundTree(final @Injectable RecordBatch batch) throws SchemaChangeException {
+ new NonStrictExpectations() {
+ {
+ batch.getValueVectorId(new FieldReference("test", ExpressionPosition.UNKNOWN));
+ result = new TypedFieldId(Types.required(MinorType.BIT), -4);
+ batch.getValueVectorId(new FieldReference("test1", ExpressionPosition.UNKNOWN));
+ result = new TypedFieldId(Types.required(MinorType.BIGINT), -5);
+ }
+ };
+
+ ErrorCollector ec = new ErrorCollectorImpl();
+
+ LogicalExpression expr = new IfExpression.Builder()
+ .addCondition(
+ new IfExpression.IfCondition( //
+ new FieldReference("test", ExpressionPosition.UNKNOWN), //
+ new IfExpression.Builder()
+ //
+ .addCondition( //
+ new IfExpression.IfCondition(
+ //
+ new ValueExpressions.BooleanExpression("true", ExpressionPosition.UNKNOWN),
+ new FieldReference("test1", ExpressionPosition.UNKNOWN)))
+ .setElse(new ValueExpressions.LongExpression(1L, ExpressionPosition.UNKNOWN)).build()) //
+ ) //
+ .setElse(new ValueExpressions.LongExpression(1L, ExpressionPosition.UNKNOWN)).build();
+ LogicalExpression newExpr = ExpressionTreeMaterializer.materialize(expr, batch, ec);
+ assertTrue(newExpr instanceof IfExpression);
+ IfExpression newIfExpr = (IfExpression) newExpr;
+ assertEquals(1, newIfExpr.conditions.size());
+ IfExpression.IfCondition ifCondition = newIfExpr.conditions.get(0);
+ assertTrue(ifCondition.expression instanceof IfExpression);
+ newIfExpr = (IfExpression) ifCondition.expression;
+ assertEquals(1, newIfExpr.conditions.size());
+ ifCondition = newIfExpr.conditions.get(0);
+ assertEquals(bigIntType, ifCondition.expression.getMajorType());
+ assertEquals(true, ((ValueExpressions.BooleanExpression) ifCondition.condition).value);
+ if (ec.hasErrors())
+ System.out.println(ec.toErrorString());
+ assertFalse(ec.hasErrors());
+ }
+
+ @Test
+ public void testMaterializingLateboundTreeValidated(final @Injectable RecordBatch batch) throws SchemaChangeException {
+ ErrorCollector ec = new ErrorCollector() {
+ int errorCount = 0;
+
+ @Override
+ public void addGeneralError(ExpressionPosition expr, String s) {
+ errorCount++;
+ }
+
+ @Override
+ public void addUnexpectedArgumentType(ExpressionPosition expr, String name, MajorType actual,
+ MajorType[] expected, int argumentIndex) {
+ errorCount++;
+ }
+
+ @Override
+ public void addUnexpectedArgumentCount(ExpressionPosition expr, int actual, Range<Integer> expected) {
+ errorCount++;
+ }
+
+ @Override
+ public void addUnexpectedArgumentCount(ExpressionPosition expr, int actual, int expected) {
+ errorCount++;
+ }
+
+ @Override
+ public void addNonNumericType(ExpressionPosition expr, MajorType actual) {
+ errorCount++;
+ }
+
+ @Override
+ public void addUnexpectedType(ExpressionPosition expr, int index, MajorType actual) {
+ errorCount++;
+ }
+
+ @Override
+ public void addExpectedConstantValue(ExpressionPosition expr, int actual, String s) {
+ errorCount++;
+ }
+
+ @Override
+ public boolean hasErrors() {
+ return errorCount > 0;
+ }
+
+ @Override
+ public String toErrorString() {
+ return String.format("Found %s errors.", errorCount);
+ }
+
+ @Override
+ public int getErrorCount() {
+ return errorCount;
+ }
+ };
+
+ new NonStrictExpectations() {
+ {
+ batch.getValueVectorId(new FieldReference("test", ExpressionPosition.UNKNOWN));
+ result = new TypedFieldId(Types.required(MinorType.BIGINT), -5);
+ }
+ };
+
+
+ LogicalExpression functionCallExpr = new FunctionCall(FunctionDefinition.simple("testFunc",
+ new ArgumentValidator() {
+ @Override
+ public void validateArguments(ExpressionPosition expr, List<LogicalExpression> expressions,
+ ErrorCollector errors) {
+ errors.addGeneralError(expr, "Error!");
+ }
+
+ @Override
+ public String[] getArgumentNamesByPosition() {
+ return new String[0];
+ }
+ }, OutputTypeDeterminer.FIXED_BIT), ImmutableList.of((LogicalExpression) //
+ new FieldReference("test", ExpressionPosition.UNKNOWN) ), ExpressionPosition.UNKNOWN);
+ LogicalExpression newExpr = ExpressionTreeMaterializer.materialize(functionCallExpr, batch, ec);
+ assertTrue(newExpr instanceof FunctionCall);
+ FunctionCall funcExpr = (FunctionCall) newExpr;
+ assertEquals(1, funcExpr.args.size());
+ assertEquals(bigIntType, funcExpr.args.get(0).getMajorType());
+ assertEquals(1, ec.getErrorCount());
+ System.out.println(ec.toErrorString());
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-drill/blob/a593d908/exec/java-exec/src/test/java/org/apache/drill/exec/record/vector/TestLoad.java
----------------------------------------------------------------------
diff --git a/exec/java-exec/src/test/java/org/apache/drill/exec/record/vector/TestLoad.java b/exec/java-exec/src/test/java/org/apache/drill/exec/record/vector/TestLoad.java
new file mode 100644
index 0000000..70f43ab
--- /dev/null
+++ b/exec/java-exec/src/test/java/org/apache/drill/exec/record/vector/TestLoad.java
@@ -0,0 +1,111 @@
+package org.apache.drill.exec.record.vector;
+
+import com.google.common.collect.Lists;
+import io.netty.buffer.ByteBuf;
+import org.apache.drill.common.expression.ExpressionPosition;
+import org.apache.drill.common.expression.SchemaPath;
+import org.apache.drill.common.types.TypeProtos;
+import org.apache.drill.common.types.TypeProtos.*;
+import org.apache.drill.common.types.Types;
+import org.apache.drill.exec.memory.BufferAllocator;
+import org.apache.drill.exec.record.MaterializedField;
+import org.apache.drill.exec.record.RecordBatchLoader;
+import org.apache.drill.exec.record.VectorWrapper;
+import org.apache.drill.exec.record.WritableBatch;
+import org.apache.drill.exec.vector.*;
+import org.junit.Test;
+
+import java.util.List;
+
+import static org.junit.Assert.assertEquals;
+
+/**
+ * Created with IntelliJ IDEA.
+ * User: witwolf
+ * Date: 8/30/13
+ * Time: 5:00 PM
+ */
+
+public class TestLoad {
+ @Test
+ public void testLoadValueVector() {
+ BufferAllocator allocator = BufferAllocator.getAllocator(null);
+ ValueVector fixedV = new IntVector(
+ MaterializedField.create(new SchemaPath("ints", ExpressionPosition.UNKNOWN), Types.required(MinorType.INT)),
+ allocator);
+ ValueVector varlenV = new VarCharVector(
+ MaterializedField.create(new SchemaPath("chars", ExpressionPosition.UNKNOWN), Types.required(MinorType.VARCHAR)),
+ allocator
+ );
+ ValueVector nullableVarlenV = new NullableVarCharVector(
+ MaterializedField.create(new SchemaPath("chars", ExpressionPosition.UNKNOWN), Types.optional(MinorType.VARCHAR)),
+ allocator
+ );
+
+ List<ValueVector> vectors = Lists.newArrayList(fixedV, varlenV, nullableVarlenV);
+ for (ValueVector v : vectors) {
+ AllocationHelper.allocate(v, 100, 50);
+ v.getMutator().generateTestData();
+ v.getMutator().setValueCount(100);
+ }
+
+ WritableBatch writableBatch = WritableBatch.getBatchNoSV(100, vectors);
+ RecordBatchLoader batchLoader = new RecordBatchLoader(allocator);
+ ByteBuf[] byteBufs = writableBatch.getBuffers();
+ int bytes = 0;
+ for (int i = 0; i < byteBufs.length; i++) {
+ bytes += byteBufs[i].writerIndex();
+ }
+ ByteBuf byteBuf = allocator.buffer(bytes);
+ int index = 0;
+ for (int i = 0; i < byteBufs.length; i++) {
+ byteBufs[i].readBytes(byteBuf, index, byteBufs[i].writerIndex());
+ index += byteBufs[i].writerIndex();
+ }
+ byteBuf.writerIndex(bytes);
+ try {
+ batchLoader.load(writableBatch.getDef(), byteBuf);
+ boolean firstColumn = true;
+ int recordCount = 0;
+ for (VectorWrapper<?> v : batchLoader) {
+ if (firstColumn) {
+ firstColumn = false;
+ } else {
+ System.out.print("\t");
+ }
+ System.out.print(v.getField().getName());
+ System.out.print("[");
+ System.out.print(v.getField().getType().getMinorType());
+ System.out.print("]");
+ }
+
+ System.out.println();
+ for (int r = 0; r < batchLoader.getRecordCount(); r++) {
+ boolean first = true;
+ recordCount++;
+ for (VectorWrapper<?> v : batchLoader) {
+ if (first) {
+ first = false;
+ } else {
+ System.out.print("\t");
+ }
+ ValueVector.Accessor accessor = v.getValueVector().getAccessor();
+ if (v.getField().getType().getMinorType() == TypeProtos.MinorType.VARCHAR) {
+ Object obj = accessor.getObject(r) ;
+ if(obj != null)
+ System.out.print(new String((byte[]) accessor.getObject(r)));
+ else
+ System.out.print("NULL");
+ } else {
+ System.out.print(accessor.getObject(r));
+ }
+ }
+ if (!first) System.out.println();
+ }
+ assertEquals(100, recordCount);
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-drill/blob/a593d908/exec/java-exec/src/test/java/org/apache/drill/exec/record/vector/TestValueVector.java
----------------------------------------------------------------------
diff --git a/exec/java-exec/src/test/java/org/apache/drill/exec/record/vector/TestValueVector.java b/exec/java-exec/src/test/java/org/apache/drill/exec/record/vector/TestValueVector.java
new file mode 100644
index 0000000..b4412c0
--- /dev/null
+++ b/exec/java-exec/src/test/java/org/apache/drill/exec/record/vector/TestValueVector.java
@@ -0,0 +1,297 @@
+package org.apache.drill.exec.record.vector;
+
+import static org.junit.Assert.assertEquals;
+
+import java.nio.charset.Charset;
+
+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.exec.expr.TypeHelper;
+import org.apache.drill.exec.memory.DirectBufferAllocator;
+import org.apache.drill.exec.proto.SchemaDefProtos.FieldDef;
+import org.apache.drill.exec.record.MaterializedField;
+import org.apache.drill.exec.vector.BitVector;
+import org.apache.drill.exec.vector.NullableFloat4Vector;
+import org.apache.drill.exec.vector.NullableUInt4Vector;
+import org.apache.drill.exec.vector.NullableVarCharVector;
+import org.apache.drill.exec.vector.UInt4Vector;
+import org.junit.Test;
+
+public class TestValueVector {
+
+ DirectBufferAllocator allocator = new DirectBufferAllocator();
+
+ @Test
+ public void testFixedType() {
+ // Build a required uint field definition
+ MajorType.Builder typeBuilder = MajorType.newBuilder();
+ FieldDef.Builder defBuilder = FieldDef.newBuilder();
+ typeBuilder
+ .setMinorType(MinorType.UINT4)
+ .setMode(DataMode.REQUIRED)
+ .setWidth(4);
+ defBuilder
+ .setMajorType(typeBuilder.build());
+ MaterializedField field = MaterializedField.create(defBuilder.build());
+
+ // Create a new value vector for 1024 integers
+ UInt4Vector v = new UInt4Vector(field, allocator);
+ UInt4Vector.Mutator m = v.getMutator();
+ v.allocateNew(1024);
+
+ // Put and set a few values
+ m.set(0, 100);
+ m.set(1, 101);
+ m.set(100, 102);
+ m.set(1022, 103);
+ m.set(1023, 104);
+ assertEquals(100, v.getAccessor().get(0));
+ assertEquals(101, v.getAccessor().get(1));
+ assertEquals(102, v.getAccessor().get(100));
+ assertEquals(103, v.getAccessor().get(1022));
+ assertEquals(104, v.getAccessor().get(1023));
+
+ // Ensure unallocated space returns 0
+ assertEquals(0, v.getAccessor().get(3));
+ }
+
+ @Test
+ public void testNullableVarLen2() {
+ // Build an optional varchar field definition
+ MajorType.Builder typeBuilder = MajorType.newBuilder();
+ FieldDef.Builder defBuilder = FieldDef.newBuilder();
+ typeBuilder
+ .setMinorType(MinorType.VARCHAR)
+ .setMode(DataMode.OPTIONAL)
+ .setWidth(2);
+ defBuilder
+ .setMajorType(typeBuilder.build());
+ MaterializedField field = MaterializedField.create(defBuilder.build());
+
+ // Create a new value vector for 1024 integers
+ NullableVarCharVector v = new NullableVarCharVector(field, allocator);
+ NullableVarCharVector.Mutator m = v.getMutator();
+ v.allocateNew(1024*10, 1024);
+
+ // Create and set 3 sample strings
+ String str1 = new String("AAAAA1");
+ String str2 = new String("BBBBBBBBB2");
+ String str3 = new String("CCCC3");
+ m.set(0, str1.getBytes(Charset.forName("UTF-8")));
+ m.set(1, str2.getBytes(Charset.forName("UTF-8")));
+ m.set(2, str3.getBytes(Charset.forName("UTF-8")));
+
+ // Check the sample strings
+ assertEquals(str1, new String(v.getAccessor().get(0), Charset.forName("UTF-8")));
+ assertEquals(str2, new String(v.getAccessor().get(1), Charset.forName("UTF-8")));
+ assertEquals(str3, new String(v.getAccessor().get(2), Charset.forName("UTF-8")));
+
+ // Ensure null value throws
+ boolean b = false;
+ try {
+ v.getAccessor().get(3);
+ } catch(AssertionError e) {
+ b = true;
+ }finally{
+ if(!b){
+ assert false;
+ }
+ }
+
+ }
+
+
+ @Test
+ public void testNullableFixedType() {
+ // Build an optional uint field definition
+ MajorType.Builder typeBuilder = MajorType.newBuilder();
+ FieldDef.Builder defBuilder = FieldDef.newBuilder();
+ typeBuilder
+ .setMinorType(MinorType.UINT4)
+ .setMode(DataMode.OPTIONAL)
+ .setWidth(4);
+ defBuilder
+ .setMajorType(typeBuilder.build());
+ MaterializedField field = MaterializedField.create(defBuilder.build());
+
+ // Create a new value vector for 1024 integers
+ NullableUInt4Vector v = new NullableUInt4Vector(field, allocator);
+ NullableUInt4Vector.Mutator m = v.getMutator();
+ v.allocateNew(1024);
+
+ // Put and set a few values
+ m.set(0, 100);
+ m.set(1, 101);
+ m.set(100, 102);
+ m.set(1022, 103);
+ m.set(1023, 104);
+ assertEquals(100, v.getAccessor().get(0));
+ assertEquals(101, v.getAccessor().get(1));
+ assertEquals(102, v.getAccessor().get(100));
+ assertEquals(103, v.getAccessor().get(1022));
+ assertEquals(104, v.getAccessor().get(1023));
+
+ // Ensure null values throw
+ {
+ boolean b = false;
+ try {
+ v.getAccessor().get(3);
+ } catch(AssertionError e) {
+ b = true;
+ }finally{
+ if(!b){
+ assert false;
+ }
+ }
+ }
+
+
+ v.allocateNew(2048);
+ {
+ boolean b = false;
+ try {
+ v.getAccessor().get(0);
+ } catch(AssertionError e) {
+ b = true;
+ }finally{
+ if(!b){
+ assert false;
+ }
+ }
+ }
+
+ m.set(0, 100);
+ m.set(1, 101);
+ m.set(100, 102);
+ m.set(1022, 103);
+ m.set(1023, 104);
+ assertEquals(100, v.getAccessor().get(0));
+ assertEquals(101, v.getAccessor().get(1));
+ assertEquals(102, v.getAccessor().get(100));
+ assertEquals(103, v.getAccessor().get(1022));
+ assertEquals(104, v.getAccessor().get(1023));
+
+ // Ensure null values throw
+
+ {
+ boolean b = false;
+ try {
+ v.getAccessor().get(3);
+ } catch(AssertionError e) {
+ b = true;
+ }finally{
+ if(!b){
+ assert false;
+ }
+ }
+ }
+
+ }
+
+ @Test
+ public void testNullableFloat() {
+ // Build an optional float field definition
+ MajorType.Builder typeBuilder = MajorType.newBuilder();
+ FieldDef.Builder defBuilder = FieldDef.newBuilder();
+ typeBuilder
+ .setMinorType(MinorType.FLOAT4)
+ .setMode(DataMode.OPTIONAL)
+ .setWidth(4);
+ defBuilder
+ .setMajorType(typeBuilder.build());
+ MaterializedField field = MaterializedField.create(defBuilder.build());
+
+ // Create a new value vector for 1024 integers
+ NullableFloat4Vector v = (NullableFloat4Vector) TypeHelper.getNewVector(field, allocator);
+ NullableFloat4Vector.Mutator m = v.getMutator();
+ v.allocateNew(1024);
+
+ // Put and set a few values
+ m.set(0, 100.1f);
+ m.set(1, 101.2f);
+ m.set(100, 102.3f);
+ m.set(1022, 103.4f);
+ m.set(1023, 104.5f);
+ assertEquals(100.1f, v.getAccessor().get(0), 0);
+ assertEquals(101.2f, v.getAccessor().get(1), 0);
+ assertEquals(102.3f, v.getAccessor().get(100), 0);
+ assertEquals(103.4f, v.getAccessor().get(1022), 0);
+ assertEquals(104.5f, v.getAccessor().get(1023), 0);
+
+ // Ensure null values throw
+ {
+ boolean b = false;
+ try {
+ v.getAccessor().get(3);
+ } catch(AssertionError e) {
+ b = true;
+ }finally{
+ if(!b){
+ assert false;
+ }
+ }
+ }
+
+ v.allocateNew(2048);
+ {
+ boolean b = false;
+ try {
+ v.getAccessor().get(0);
+ } catch(AssertionError e) {
+ b = true;
+ }finally{
+ if(!b){
+ assert false;
+ }
+ }
+ }
+ }
+
+ @Test
+ public void testBitVector() {
+ // Build a required boolean field definition
+ MajorType.Builder typeBuilder = MajorType.newBuilder();
+ FieldDef.Builder defBuilder = FieldDef.newBuilder();
+ typeBuilder
+ .setMinorType(MinorType.BIT)
+ .setMode(DataMode.REQUIRED)
+ .setWidth(4);
+ defBuilder
+ .setMajorType(typeBuilder.build());
+ MaterializedField field = MaterializedField.create(defBuilder.build());
+
+ // Create a new value vector for 1024 integers
+ BitVector v = new BitVector(field, allocator);
+ BitVector.Mutator m = v.getMutator();
+ v.allocateNew(1024);
+
+ // Put and set a few values
+ m.set(0, 1);
+ m.set(1, 0);
+ m.set(100, 0);
+ m.set(1022, 1);
+ assertEquals(1, v.getAccessor().get(0));
+ assertEquals(0, v.getAccessor().get(1));
+ assertEquals(0, v.getAccessor().get(100));
+ assertEquals(1, v.getAccessor().get(1022));
+
+ // test setting the same value twice
+ m.set(0, 1);
+ m.set(0, 1);
+ m.set(1, 0);
+ m.set(1, 0);
+ assertEquals(1, v.getAccessor().get(0));
+ assertEquals(0, v.getAccessor().get(1));
+
+ // test toggling the values
+ m.set(0, 0);
+ m.set(1, 1);
+ assertEquals(0, v.getAccessor().get(0));
+ assertEquals(1, v.getAccessor().get(1));
+
+ // Ensure unallocated space returns 0
+ assertEquals(0, v.getAccessor().get(3));
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-drill/blob/a593d908/exec/java-exec/src/test/java/org/apache/drill/exec/server/TestBitRpc.java
----------------------------------------------------------------------
diff --git a/exec/java-exec/src/test/java/org/apache/drill/exec/server/TestBitRpc.java b/exec/java-exec/src/test/java/org/apache/drill/exec/server/TestBitRpc.java
new file mode 100644
index 0000000..038b093
--- /dev/null
+++ b/exec/java-exec/src/test/java/org/apache/drill/exec/server/TestBitRpc.java
@@ -0,0 +1,88 @@
+/*******************************************************************************
+ * 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.server;
+
+import io.netty.buffer.ByteBuf;
+
+import org.apache.drill.common.config.DrillConfig;
+import org.apache.drill.exec.proto.CoordinationProtos.DrillbitEndpoint;
+import org.apache.drill.exec.proto.ExecProtos.FragmentHandle;
+import org.apache.drill.exec.proto.ExecProtos.FragmentStatus;
+import org.apache.drill.exec.proto.ExecProtos.PlanFragment;
+import org.apache.drill.exec.proto.GeneralRPCProtos.Ack;
+import org.apache.drill.exec.rpc.Response;
+import org.apache.drill.exec.rpc.RpcException;
+import org.apache.drill.exec.rpc.bit.BitConnection;
+import org.apache.drill.exec.rpc.bit.BitConnectionManager;
+import org.apache.drill.exec.rpc.bit.BitRpcConfig;
+import org.apache.drill.exec.rpc.bit.BitServer;
+import org.apache.drill.exec.rpc.bit.BitTunnel.SendFragmentStatus;
+import org.apache.drill.exec.rpc.bit.ConnectionManagerRegistry;
+import org.apache.drill.exec.rpc.bit.ListenerPool;
+import org.apache.drill.exec.work.batch.BitComHandler;
+import org.apache.drill.exec.work.fragment.IncomingFragmentHandler;
+import org.junit.Test;
+
+public class TestBitRpc {
+ static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(TestBitRpc.class);
+
+ @Test
+ public void testBasicConnectionAndHandshake() throws Exception{
+ int port = 1234;
+ BootStrapContext c = new BootStrapContext(DrillConfig.create());
+ final BitComTestHandler handler = new BitComTestHandler();
+ final ListenerPool listeners = new ListenerPool(2);
+ ConnectionManagerRegistry registry = new ConnectionManagerRegistry(handler, c, listeners);
+ BitServer server = new BitServer(handler, c, registry, listeners);
+ port = server.bind(port);
+ DrillbitEndpoint ep = DrillbitEndpoint.newBuilder().setAddress("localhost").setBitPort(port).build();
+ registry.setEndpoint(ep);
+ for(int i =0; i < 10; i++){
+ try(BitConnectionManager cm = new BitConnectionManager(ep, ep, handler, c, listeners)){
+ SendFragmentStatus cmd = new SendFragmentStatus(FragmentStatus.getDefaultInstance());
+ cm.runCommand(cmd);
+ cmd.getFuture().checkedGet();
+ }
+ }
+ System.out.println("connected");
+ }
+
+
+
+ private class BitComTestHandler implements BitComHandler{
+
+ @Override
+ public Response handle(BitConnection connection, int rpcType, ByteBuf pBody, ByteBuf dBody) throws RpcException {
+ return BitRpcConfig.OK;
+ }
+
+ @Override
+ public void startNewRemoteFragment(PlanFragment fragment) {
+ }
+
+ @Override
+ public Ack cancelFragment(FragmentHandle handle) {
+ return null;
+ }
+
+ @Override
+ public void registerIncomingFragmentHandler(IncomingFragmentHandler handler) {
+ }
+
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-drill/blob/a593d908/exec/java-exec/src/test/java/org/apache/drill/exec/store/ByteArrayUtil.java
----------------------------------------------------------------------
diff --git a/exec/java-exec/src/test/java/org/apache/drill/exec/store/ByteArrayUtil.java b/exec/java-exec/src/test/java/org/apache/drill/exec/store/ByteArrayUtil.java
new file mode 100644
index 0000000..ea1404b
--- /dev/null
+++ b/exec/java-exec/src/test/java/org/apache/drill/exec/store/ByteArrayUtil.java
@@ -0,0 +1,181 @@
+/*******************************************************************************
+ * 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.store;
+
+//TODO - make sure we figure out the license on these
+public class ByteArrayUtil {
+
+ public static byte[] toByta(Object data) throws Exception {
+ if (data instanceof Integer) return toByta((int) data);
+ else if (data instanceof Double) return toByta((double) data);
+ else if (data instanceof Float) return toByta((float) data);
+ else if (data instanceof Boolean) return toByta((boolean) data);
+ else if (data instanceof Long) return toByta((long) data);
+ else throw new Exception("Cannot convert that type to a byte array.");
+ }
+
+ // found at http://www.daniweb.com/software-development/java/code/216874/primitive-types-as-byte-arrays
+ // I have modified them to switch the endianess of integers and longs
+ /* ========================= */
+ /* "primitive type --> byte[] data" Methods */
+ /* ========================= */
+ public static byte[] toByta(byte data) {
+ return new byte[]{data};
+ }
+
+ public static byte[] toByta(byte[] data) {
+ return data;
+ }
+
+ /* ========================= */
+ public static byte[] toByta(short data) {
+ return new byte[]{
+ (byte) ((data >> 8) & 0xff),
+ (byte) ((data >> 0) & 0xff),
+ };
+ }
+
+ public static byte[] toByta(short[] data) {
+ if (data == null) return null;
+ // ----------
+ byte[] byts = new byte[data.length * 2];
+ for (int i = 0; i < data.length; i++)
+ System.arraycopy(toByta(data[i]), 0, byts, i * 2, 2);
+ return byts;
+ }
+
+ /* ========================= */
+ public static byte[] toByta(char data) {
+ return new byte[]{
+ (byte) ((data >> 8) & 0xff),
+ (byte) ((data >> 0) & 0xff),
+ };
+ }
+
+ public static byte[] toByta(char[] data) {
+ if (data == null) return null;
+ // ----------
+ byte[] byts = new byte[data.length * 2];
+ for (int i = 0; i < data.length; i++)
+ System.arraycopy(toByta(data[i]), 0, byts, i * 2, 2);
+ return byts;
+ }
+
+ /* ========================= */
+ public static byte[] toByta(int data) {
+ return new byte[]{
+ (byte) ((data >> 0) & 0xff),
+ (byte) ((data >> 8) & 0xff),
+ (byte) ((data >> 16) & 0xff),
+ (byte) ((data >> 24) & 0xff),
+ };
+ }
+
+ public static byte[] toByta(int[] data) {
+ if (data == null) return null;
+ // ----------
+ byte[] byts = new byte[data.length * 4];
+ for (int i = 0; i < data.length; i++)
+ System.arraycopy(toByta(data[i]), 0, byts, i * 4, 4);
+ return byts;
+ }
+
+ /* ========================= */
+ public static byte[] toByta(long data) {
+ return new byte[]{
+ (byte) ((data >> 0) & 0xff),
+ (byte) ((data >> 8) & 0xff),
+ (byte) ((data >> 16) & 0xff),
+ (byte) ((data >> 24) & 0xff),
+ (byte) ((data >> 32) & 0xff),
+ (byte) ((data >> 40) & 0xff),
+ (byte) ((data >> 48) & 0xff),
+ (byte) ((data >> 56) & 0xff),
+ };
+ }
+
+ public static byte[] toByta(long[] data) {
+ if (data == null) return null;
+ // ----------
+ byte[] byts = new byte[data.length * 8];
+ for (int i = 0; i < data.length; i++)
+ System.arraycopy(toByta(data[i]), 0, byts, i * 8, 8);
+ return byts;
+ }
+
+ /* ========================= */
+ public static byte[] toByta(float data) {
+ return toByta(Float.floatToRawIntBits(data));
+ }
+
+ public static byte[] toByta(float[] data) {
+ if (data == null) return null;
+ // ----------
+ byte[] byts = new byte[data.length * 4];
+ for (int i = 0; i < data.length; i++)
+ System.arraycopy(toByta(data[i]), 0, byts, i * 4, 4);
+ return byts;
+ }
+
+ /* ========================= */
+ public static byte[] toByta(double data) {
+ return toByta(Double.doubleToRawLongBits(data));
+ }
+
+ public static byte[] toByta(double[] data) {
+ if (data == null) return null;
+ // ----------
+ byte[] byts = new byte[data.length * 8];
+ for (int i = 0; i < data.length; i++)
+ System.arraycopy(toByta(data[i]), 0, byts, i * 8, 8);
+ return byts;
+ }
+
+ /* ========================= */
+ public static byte[] toByta(boolean data) {
+ return new byte[]{(byte) (data ? 0x01 : 0x00)}; // bool -> {1 byte}
+ }
+
+ public static byte[] toByta(boolean[] data) {
+ // Advanced Technique: The byte array containts information
+ // about how many boolean values are involved, so the exact
+ // array is returned when later decoded.
+ // ----------
+ if (data == null) return null;
+ // ----------
+ int len = data.length;
+ byte[] lena = toByta(len); // int conversion; length array = lena
+ byte[] byts = new byte[lena.length + (len / 8) + (len % 8 != 0 ? 1 : 0)];
+ // (Above) length-array-length + sets-of-8-booleans +? byte-for-remainder
+ System.arraycopy(lena, 0, byts, 0, lena.length);
+ // ----------
+ // (Below) algorithm by Matthew Cudmore: boolean[] -> bits -> byte[]
+ for (int i = 0, j = lena.length, k = 7; i < data.length; i++) {
+ byts[j] |= (data[i] ? 1 : 0) << k--;
+ if (k < 0) {
+ j++;
+ k = 7;
+ }
+ }
+ // ----------
+ return byts;
+ }
+
+ // above utility methods found here:
+ // http://www.daniweb.com/software-development/java/code/216874/primitive-types-as-byte-arrays
+}
http://git-wip-us.apache.org/repos/asf/incubator-drill/blob/a593d908/exec/java-exec/src/test/java/org/apache/drill/exec/store/JSONRecordReaderTest.java
----------------------------------------------------------------------
diff --git a/exec/java-exec/src/test/java/org/apache/drill/exec/store/JSONRecordReaderTest.java b/exec/java-exec/src/test/java/org/apache/drill/exec/store/JSONRecordReaderTest.java
new file mode 100644
index 0000000..f0217be
--- /dev/null
+++ b/exec/java-exec/src/test/java/org/apache/drill/exec/store/JSONRecordReaderTest.java
@@ -0,0 +1,335 @@
+package org.apache.drill.exec.store;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+import java.io.IOException;
+import java.nio.charset.Charset;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+import com.google.common.base.Predicate;
+import com.google.common.collect.Iterables;
+
+import mockit.Expectations;
+import mockit.Injectable;
+
+import org.apache.drill.common.exceptions.ExecutionSetupException;
+import org.apache.drill.common.types.TypeProtos.MinorType;
+import org.apache.drill.common.util.FileUtils;
+import org.apache.drill.exec.exception.SchemaChangeException;
+import org.apache.drill.exec.memory.DirectBufferAllocator;
+import org.apache.drill.exec.ops.FragmentContext;
+import org.apache.drill.exec.physical.impl.OutputMutator;
+import org.apache.drill.exec.proto.SchemaDefProtos;
+import org.apache.drill.exec.proto.UserBitShared;
+import org.apache.drill.exec.record.MaterializedField;
+import org.apache.drill.exec.store.json.JSONRecordReader;
+import org.apache.drill.exec.vector.ValueVector;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.fs.FileSystem;
+import org.junit.Ignore;
+import org.junit.Test;
+
+import com.google.common.collect.Lists;
+
+
+public class JSONRecordReaderTest {
+ private static final Charset UTF_8 = Charset.forName("UTF-8");
+
+ private String getResource(String resourceName) {
+ return "resource:" + resourceName;
+ }
+
+ class MockOutputMutator implements OutputMutator {
+ List<MaterializedField> removedFields = Lists.newArrayList();
+ List<ValueVector> addFields = Lists.newArrayList();
+
+ @Override
+ public void removeField(MaterializedField field) throws SchemaChangeException {
+ removedFields.add(field);
+ }
+
+ @Override
+ public void addField(ValueVector vector) throws SchemaChangeException {
+ addFields.add(vector);
+ }
+
+ @Override
+ public void removeAllFields() {
+ addFields.clear();
+ }
+
+ @Override
+ public void setNewSchema() throws SchemaChangeException {
+ }
+
+ List<MaterializedField> getRemovedFields() {
+ return removedFields;
+ }
+
+ List<ValueVector> getAddFields() {
+ return addFields;
+ }
+ }
+
+ private <T> void assertField(ValueVector valueVector, int index, MinorType expectedMinorType, T value, String name) {
+ UserBitShared.FieldMetadata metadata = valueVector.getMetadata();
+ SchemaDefProtos.FieldDef def = metadata.getDef();
+ assertEquals(expectedMinorType, def.getMajorType().getMinorType());
+ String[] parts = name.split("\\.");
+ int expected = parts.length;
+ assertEquals(expected, def.getNameList().size());
+ for(int i = 0; i < parts.length; ++i) {
+ assertEquals(parts[i], def.getName(i).getName());
+ }
+
+ if (expectedMinorType == MinorType.MAP) {
+ return;
+ }
+
+ T val = (T) valueVector.getAccessor().getObject(index);
+ assertValue(value, val);
+ }
+
+ private void assertValue(Object expected, Object found) {
+ if (found instanceof byte[]) {
+ assertTrue(Arrays.equals((byte[]) expected, (byte[]) found));
+ } else if(found instanceof ArrayList) {
+ List expectedArray = (List) expected;
+ List foundArray = (List) found;
+ assertEquals(expectedArray.size(), foundArray.size());
+ for(int i = 0; i < expectedArray.size(); ++i) {
+ assertValue(expectedArray.get(i), foundArray.get(i));
+ }
+ } else {
+ assertEquals(expected, found);
+ }
+ }
+
+ @Test
+ public void testSameSchemaInSameBatch(@Injectable final FragmentContext context) throws IOException,
+ ExecutionSetupException {
+ new Expectations() {
+ {
+ context.getAllocator();
+ returns(new DirectBufferAllocator());
+ }
+ };
+ JSONRecordReader jr = new JSONRecordReader(context,
+ FileUtils.getResourceAsFile("/scan_json_test_1.json").toURI().toString(),
+ FileSystem.getLocal(new Configuration()), null);
+
+ MockOutputMutator mutator = new MockOutputMutator();
+ List<ValueVector> addFields = mutator.getAddFields();
+ jr.setup(mutator);
+ assertEquals(2, jr.next());
+ assertEquals(3, addFields.size());
+ assertField(addFields.get(0), 0, MinorType.INT, 123, "test");
+ assertField(addFields.get(1), 0, MinorType.BIT, true, "b");
+ assertField(addFields.get(2), 0, MinorType.VARCHAR, "hi!".getBytes(UTF_8), "c");
+ assertField(addFields.get(0), 1, MinorType.INT, 1234, "test");
+ assertField(addFields.get(1), 1, MinorType.BIT, false, "b");
+ assertField(addFields.get(2), 1, MinorType.VARCHAR, "drill!".getBytes(UTF_8), "c");
+
+ assertEquals(0, jr.next());
+ assertTrue(mutator.getRemovedFields().isEmpty());
+ }
+
+ @Test
+ public void testChangedSchemaInSameBatch(@Injectable final FragmentContext context) throws IOException,
+ ExecutionSetupException {
+ new Expectations() {
+ {
+ context.getAllocator();
+ returns(new DirectBufferAllocator());
+ }
+ };
+
+ JSONRecordReader jr = new JSONRecordReader(context,
+ FileUtils.getResourceAsFile("/scan_json_test_2.json").toURI().toString(),
+ FileSystem.getLocal(new Configuration()), null);
+
+ MockOutputMutator mutator = new MockOutputMutator();
+ List<ValueVector> addFields = mutator.getAddFields();
+
+ jr.setup(mutator);
+ assertEquals(3, jr.next());
+ assertEquals(7, addFields.size());
+ assertField(addFields.get(0), 0, MinorType.INT, 123, "test");
+ assertField(addFields.get(1), 0, MinorType.INT, 1, "b");
+ assertField(addFields.get(2), 0, MinorType.FLOAT4, (float) 2.15, "c");
+ assertField(addFields.get(3), 0, MinorType.BIT, true, "bool");
+ assertField(addFields.get(4), 0, MinorType.VARCHAR, "test1".getBytes(UTF_8), "str1");
+
+ assertField(addFields.get(0), 1, MinorType.INT, 1234, "test");
+ assertField(addFields.get(1), 1, MinorType.INT, 3, "b");
+ assertField(addFields.get(3), 1, MinorType.BIT, false, "bool");
+ assertField(addFields.get(4), 1, MinorType.VARCHAR, "test2".getBytes(UTF_8), "str1");
+ assertField(addFields.get(5), 1, MinorType.INT, 4, "d");
+
+ assertField(addFields.get(0), 2, MinorType.INT, 12345, "test");
+ assertField(addFields.get(2), 2, MinorType.FLOAT4, (float) 5.16, "c");
+ assertField(addFields.get(3), 2, MinorType.BIT, true, "bool");
+ assertField(addFields.get(5), 2, MinorType.INT, 6, "d");
+ assertField(addFields.get(6), 2, MinorType.VARCHAR, "test3".getBytes(UTF_8), "str2");
+ assertTrue(mutator.getRemovedFields().isEmpty());
+ assertEquals(0, jr.next());
+ }
+
+ @Test
+ public void testChangedSchemaInTwoBatches(@Injectable final FragmentContext context) throws IOException,
+ ExecutionSetupException {
+ new Expectations() {
+ {
+ context.getAllocator();
+ returns(new DirectBufferAllocator());
+ }
+ };
+
+ JSONRecordReader jr = new JSONRecordReader(context,
+ FileUtils.getResourceAsFile("/scan_json_test_2.json").toURI().toString(),
+ FileSystem.getLocal(new Configuration()),
+ 64, null); // batch only fits 1 int
+ MockOutputMutator mutator = new MockOutputMutator();
+ List<ValueVector> addFields = mutator.getAddFields();
+ List<MaterializedField> removedFields = mutator.getRemovedFields();
+
+ jr.setup(mutator);
+ assertEquals(1, jr.next());
+ assertEquals(5, addFields.size());
+ assertField(addFields.get(0), 0, MinorType.INT, 123, "test");
+ assertField(addFields.get(1), 0, MinorType.INT, 1, "b");
+ assertField(addFields.get(2), 0, MinorType.FLOAT4, (float) 2.15, "c");
+ assertField(addFields.get(3), 0, MinorType.BIT, true, "bool");
+ assertField(addFields.get(4), 0, MinorType.VARCHAR, "test1".getBytes(UTF_8), "str1");
+ assertTrue(removedFields.isEmpty());
+ assertEquals(1, jr.next());
+ assertEquals(6, addFields.size());
+ assertField(addFields.get(0), 0, MinorType.INT, 1234, "test");
+ assertField(addFields.get(1), 0, MinorType.INT, 3, "b");
+ assertField(addFields.get(3), 0, MinorType.BIT, false, "bool");
+ assertField(addFields.get(4), 0, MinorType.VARCHAR, "test2".getBytes(UTF_8), "str1");
+ assertField(addFields.get(5), 0, MinorType.INT, 4, "d");
+ assertEquals(1, removedFields.size());
+ assertEquals("c", removedFields.get(0).getName());
+ removedFields.clear();
+ assertEquals(1, jr.next());
+ assertEquals(7, addFields.size()); // The reappearing of field 'c' is also included
+ assertField(addFields.get(0), 0, MinorType.INT, 12345, "test");
+ assertField(addFields.get(3), 0, MinorType.BIT, true, "bool");
+ assertField(addFields.get(5), 0, MinorType.INT, 6, "d");
+ assertField(addFields.get(2), 0, MinorType.FLOAT4, (float) 5.16, "c");
+ assertField(addFields.get(6), 0, MinorType.VARCHAR, "test3".getBytes(UTF_8), "str2");
+ assertEquals(2, removedFields.size());
+ Iterables.find(removedFields, new Predicate<MaterializedField>() {
+ @Override
+ public boolean apply(MaterializedField materializedField) {
+ return materializedField.getName().equals("str1");
+ }
+ });
+ Iterables.find(removedFields, new Predicate<MaterializedField>() {
+ @Override
+ public boolean apply(MaterializedField materializedField) {
+ return materializedField.getName().equals("b");
+ }
+ });
+ assertEquals(0, jr.next());
+ }
+
+ @Test
+ public void testNestedFieldInSameBatch(@Injectable final FragmentContext context) throws ExecutionSetupException, IOException {
+ new Expectations() {
+ {
+ context.getAllocator();
+ returns(new DirectBufferAllocator());
+ }
+ };
+
+ JSONRecordReader jr = new JSONRecordReader(context,
+ FileUtils.getResourceAsFile("/scan_json_test_3.json").toURI().toString(),
+ FileSystem.getLocal(new Configuration()), null);
+
+ MockOutputMutator mutator = new MockOutputMutator();
+ List<ValueVector> addFields = mutator.getAddFields();
+ jr.setup(mutator);
+ assertEquals(2, jr.next());
+ assertEquals(3, addFields.size());
+ assertField(addFields.get(0), 0, MinorType.INT, 123, "test");
+ assertField(addFields.get(1), 0, MinorType.VARCHAR, "test".getBytes(UTF_8), "a.b");
+ assertField(addFields.get(2), 0, MinorType.BIT, true, "a.a.d");
+ assertField(addFields.get(0), 1, MinorType.INT, 1234, "test");
+ assertField(addFields.get(1), 1, MinorType.VARCHAR, "test2".getBytes(UTF_8), "a.b");
+ assertField(addFields.get(2), 1, MinorType.BIT, false, "a.a.d");
+
+ assertEquals(0, jr.next());
+ assertTrue(mutator.getRemovedFields().isEmpty());
+ }
+
+ @Test
+ public void testRepeatedFields(@Injectable final FragmentContext context) throws ExecutionSetupException, IOException {
+ new Expectations() {
+ {
+ context.getAllocator();
+ returns(new DirectBufferAllocator());
+ }
+ };
+
+ JSONRecordReader jr = new JSONRecordReader(context,
+ FileUtils.getResourceAsFile("/scan_json_test_4.json").toURI().toString(),
+ FileSystem.getLocal(new Configuration()), null);
+
+ MockOutputMutator mutator = new MockOutputMutator();
+ List<ValueVector> addFields = mutator.getAddFields();
+ jr.setup(mutator);
+ assertEquals(2, jr.next());
+ assertEquals(7, addFields.size());
+ assertField(addFields.get(0), 0, MinorType.INT, 123, "test");
+ assertField(addFields.get(1), 0, MinorType.INT, Arrays.asList(1, 2, 3), "test2");
+ assertField(addFields.get(2), 0, MinorType.INT, Arrays.asList(4, 5, 6), "test3.a");
+ assertField(addFields.get(3), 0, MinorType.INT, Arrays.asList(7, 8, 9), "test3.b");
+ assertField(addFields.get(4), 0, MinorType.INT, Arrays.asList(10, 11, 12), "test3.c.d");
+ assertField(addFields.get(5), 0, MinorType.FLOAT4, Arrays.<Float>asList((float) 1.1, (float) 1.2, (float) 1.3), "testFloat");
+ assertField(addFields.get(6), 0, MinorType.VARCHAR, Arrays.asList("hello".getBytes(UTF_8), "drill".getBytes(UTF_8)), "testStr");
+ assertField(addFields.get(1), 1, MinorType.INT, Arrays.asList(1, 2), "test2");
+ assertField(addFields.get(2), 1, MinorType.INT, Arrays.asList(7, 7, 7, 8), "test3.a");
+ assertField(addFields.get(5), 1, MinorType.FLOAT4, Arrays.<Float>asList((float) 2.2, (float) 2.3,(float) 2.4), "testFloat");
+
+ assertEquals(0, jr.next());
+ assertTrue(mutator.getRemovedFields().isEmpty());
+ }
+
+ @Test
+ public void testRepeatedMissingFields(@Injectable final FragmentContext context) throws ExecutionSetupException, IOException {
+ new Expectations() {
+ {
+ context.getAllocator();
+ returns(new DirectBufferAllocator());
+ }
+ };
+
+ JSONRecordReader jr = new JSONRecordReader(context,
+ FileUtils.getResourceAsFile("/scan_json_test_5.json").toURI().toString(),
+ FileSystem.getLocal(new Configuration()), null);
+
+ MockOutputMutator mutator = new MockOutputMutator();
+ List<ValueVector> addFields = mutator.getAddFields();
+ jr.setup(mutator);
+ assertEquals(9, jr.next());
+ assertEquals(1, addFields.size());
+ assertField(addFields.get(0), 0, MinorType.INT, Arrays.<Integer>asList(), "test");
+ assertField(addFields.get(0), 1, MinorType.INT, Arrays.asList(1, 2, 3), "test");
+ assertField(addFields.get(0), 2, MinorType.INT, Arrays.<Integer>asList(), "test");
+ assertField(addFields.get(0), 3, MinorType.INT, Arrays.<Integer>asList(), "test");
+ assertField(addFields.get(0), 4, MinorType.INT, Arrays.asList(4, 5, 6), "test");
+ assertField(addFields.get(0), 5, MinorType.INT, Arrays.<Integer>asList(), "test");
+ assertField(addFields.get(0), 6, MinorType.INT, Arrays.<Integer>asList(), "test");
+ assertField(addFields.get(0), 7, MinorType.INT, Arrays.asList(7, 8, 9), "test");
+ assertField(addFields.get(0), 8, MinorType.INT, Arrays.<Integer>asList(), "test");
+
+
+ assertEquals(0, jr.next());
+ assertTrue(mutator.getRemovedFields().isEmpty());
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-drill/blob/a593d908/exec/java-exec/src/test/java/org/apache/drill/exec/store/ParquetRecordReaderTest.java
----------------------------------------------------------------------
diff --git a/exec/java-exec/src/test/java/org/apache/drill/exec/store/ParquetRecordReaderTest.java b/exec/java-exec/src/test/java/org/apache/drill/exec/store/ParquetRecordReaderTest.java
new file mode 100644
index 0000000..cf790ac
--- /dev/null
+++ b/exec/java-exec/src/test/java/org/apache/drill/exec/store/ParquetRecordReaderTest.java
@@ -0,0 +1,657 @@
+/*******************************************************************************
+ * 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.store;
+
+import com.beust.jcommander.internal.Lists;
+import com.google.common.base.Charsets;
+import com.google.common.io.Files;
+
+import com.google.common.util.concurrent.SettableFuture;
+import org.apache.drill.common.config.DrillConfig;
+import org.apache.drill.common.types.TypeProtos;
+import org.apache.drill.common.util.FileUtils;
+import org.apache.drill.exec.client.DrillClient;
+import org.apache.drill.exec.exception.SchemaChangeException;
+import org.apache.drill.exec.physical.impl.OutputMutator;
+
+import org.apache.drill.exec.proto.UserProtos;
+import org.apache.drill.exec.record.MaterializedField;
+import org.apache.drill.exec.record.RecordBatchLoader;
+import org.apache.drill.exec.record.VectorWrapper;
+import org.apache.drill.exec.rpc.RpcException;
+import org.apache.drill.exec.rpc.user.QueryResultBatch;
+import org.apache.drill.exec.rpc.user.UserResultsListener;
+import org.apache.drill.exec.server.Drillbit;
+import org.apache.drill.exec.server.RemoteServiceSet;
+
+import org.apache.drill.exec.store.json.JsonSchemaProvider;
+import org.apache.drill.exec.store.parquet.ParquetStorageEngine;
+import org.apache.drill.exec.vector.BaseDataValueVector;
+import org.apache.drill.exec.vector.ValueVector;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.junit.Ignore;
+import org.junit.Test;
+import parquet.bytes.BytesInput;
+import parquet.column.ColumnDescriptor;
+
+import parquet.hadoop.ParquetFileWriter;
+import parquet.hadoop.metadata.CompressionCodecName;
+import parquet.schema.MessageType;
+import parquet.schema.MessageTypeParser;
+
+import java.util.*;
+
+import static org.junit.Assert.*;
+import static org.junit.Assert.assertEquals;
+import static parquet.column.Encoding.PLAIN;
+
+public class ParquetRecordReaderTest {
+ org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(ParquetRecordReaderTest.class);
+
+ private static final boolean VERBOSE_DEBUG = false;
+
+ // { 00000001, 00000010, 00000100, 00001000, 00010000, ... }
+ byte[] bitFields = {1, 2, 4, 8, 16, 32, 64, -128};
+ byte allBitsTrue = -1;
+ byte allBitsFalse = 0;
+ int DEFAULT_BYTES_PER_PAGE = 1024 * 1024 * 1;
+ static Object[] intVals = {-200, 100, Integer.MAX_VALUE };
+ static Object[] longVals = { -5000l, 5000l, Long.MAX_VALUE};
+ static Object[] floatVals = { 1.74f, Float.MAX_VALUE, Float.MIN_VALUE};
+ static Object[] doubleVals = {100.45d, Double.MAX_VALUE, Double.MIN_VALUE,};
+ static Object[] boolVals = {false, false, true};
+ static byte[] varLen1 = {50, 51, 52, 53, 54, 55, 56, 57, 58, 59};
+ static byte[] varLen2 = {15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1};
+ static byte[] varLen3 = {100, 99, 98};
+ static Object[] binVals = { varLen3, varLen2, varLen3};
+ static Object[] bin2Vals = { varLen3, varLen2, varLen1};
+
+ private void populateFieldInfoMap(ParquetTestProperties props){
+ props.fields.put("integer", new FieldInfo("int32", "integer", 32, intVals, TypeProtos.MinorType.INT, props));
+ props.fields.put("bigInt", new FieldInfo("int64", "bigInt", 64, longVals, TypeProtos.MinorType.BIGINT, props));
+ props.fields.put("f", new FieldInfo("float", "f", 32, floatVals, TypeProtos.MinorType.FLOAT4, props));
+ props.fields.put("d", new FieldInfo("double", "d", 64, doubleVals, TypeProtos.MinorType.FLOAT8, props));
+ props.fields.put("b", new FieldInfo("boolean", "b", 1, boolVals, TypeProtos.MinorType.BIT, props));
+ props.fields.put("bin", new FieldInfo("binary", "bin", -1, binVals, TypeProtos.MinorType.VARBINARY, props));
+ props.fields.put("bin2", new FieldInfo("binary", "bin2", -1, bin2Vals, TypeProtos.MinorType.VARBINARY, props));
+ }
+
+ @Test
+ public void testMultipleRowGroups() throws Exception {
+ HashMap<String, FieldInfo> fields = new HashMap<>();
+ ParquetTestProperties props = new ParquetTestProperties(3, 3000, DEFAULT_BYTES_PER_PAGE, fields);
+ populateFieldInfoMap(props);
+ testParquetFullEngine(true, "/parquet_scan_screen.json", "/tmp/test.parquet", 1, props);
+ }
+
+ // TODO - Test currently marked ignore to prevent breaking of the build process, requires a binary file that was
+ // generated using pig. Will need to find a good place to keep files like this.
+ // For now I will upload it to the JIRA as an attachment.
+ @Ignore
+ @Test
+ public void testNullableColumns() throws Exception {
+ HashMap<String, FieldInfo> fields = new HashMap<>();
+ ParquetTestProperties props = new ParquetTestProperties(1, 3000000, DEFAULT_BYTES_PER_PAGE, fields);
+ Object[] boolVals = {true, null, null};
+ props.fields.put("a", new FieldInfo("boolean", "a", 1, boolVals, TypeProtos.MinorType.BIT, props));
+ testParquetFullEngine(false, "/parquet_nullable.json", "/tmp/nullable.parquet", 1, props);
+ }
+
+ @Ignore
+ @Test
+ public void testNullableColumnsVarLen() throws Exception {
+ HashMap<String, FieldInfo> fields = new HashMap<>();
+ ParquetTestProperties props = new ParquetTestProperties(1, 3000000, DEFAULT_BYTES_PER_PAGE, fields);
+ byte[] val = {'b'};
+// Object[] boolVals = { val, null, null};
+// Object[] boolVals = { null, null, null};
+ Object[] boolVals = { val, val, val};
+ props.fields.put("a", new FieldInfo("boolean", "a", 1, boolVals, TypeProtos.MinorType.BIT, props));
+ testParquetFullEngine(false, "/parquet_nullable_varlen.json", "/tmp/nullable.parquet", 1, props);
+ }
+
+ @Test
+ public void testMultipleRowGroupsAndReads() throws Exception {
+ HashMap<String, FieldInfo> fields = new HashMap<>();
+ ParquetTestProperties props = new ParquetTestProperties(4, 3000, DEFAULT_BYTES_PER_PAGE, fields);
+ populateFieldInfoMap(props);
+ String readEntries = "";
+ // number of times to read the file
+ int i = 3;
+ for (int j = 0; j < i; j++){
+ readEntries += "{path: \"/tmp/test.parquet\"}";
+ if (j < i - 1)
+ readEntries += ",";
+ }
+ testParquetFullEngineEventBased(true, "/parquet_scan_screen_read_entry_replace.json", readEntries,
+ "/tmp/test.parquet", i, props);
+ }
+
+ @Test
+ public void testMultipleRowGroupsEvent() throws Exception {
+ HashMap<String, FieldInfo> fields = new HashMap<>();
+ ParquetTestProperties props = new ParquetTestProperties(4, 3000, DEFAULT_BYTES_PER_PAGE, fields);
+ populateFieldInfoMap(props);
+ testParquetFullEngineEventBased(true, "/parquet_scan_screen.json", "/tmp/test.parquet", 1, props);
+ }
+
+
+ private class ParquetTestProperties{
+ int numberRowGroups;
+ int recordsPerRowGroup;
+ int bytesPerPage = 1024 * 1024 * 1;
+ HashMap<String, FieldInfo> fields = new HashMap<>();
+
+ public ParquetTestProperties(int numberRowGroups, int recordsPerRowGroup, int bytesPerPage,
+ HashMap<String, FieldInfo> fields){
+ this.numberRowGroups = numberRowGroups;
+ this.recordsPerRowGroup = recordsPerRowGroup;
+ this.bytesPerPage = bytesPerPage;
+ this.fields = fields;
+ }
+
+ }
+
+ private static class FieldInfo {
+
+ String parquetType;
+ String name;
+ int bitLength;
+ int numberOfPages;
+ Object[] values;
+ TypeProtos.MinorType type;
+
+ FieldInfo(String parquetType, String name, int bitLength, Object[] values, TypeProtos.MinorType type, ParquetTestProperties props){
+ this.parquetType = parquetType;
+ this.name = name;
+ this.bitLength = bitLength;
+ this.numberOfPages = Math.max(1, (int) Math.ceil( ((long) props.recordsPerRowGroup) * bitLength / 8.0 / props.bytesPerPage));
+ this.values = values;
+ // generator is designed to use 3 values
+ assert values.length == 3;
+ this.type = type;
+ }
+ }
+
+ private String getResource(String resourceName) {
+ return "resource:" + resourceName;
+ }
+
+ public void generateParquetFile(String filename, ParquetTestProperties props) throws Exception {
+
+ int currentBooleanByte = 0;
+ WrapAroundCounter booleanBitCounter = new WrapAroundCounter(7);
+
+ Configuration configuration = new Configuration();
+ configuration.set(JsonSchemaProvider.HADOOP_DEFAULT_NAME, "file:///");
+ //"message m { required int32 integer; required int64 integer64; required boolean b; required float f; required double d;}"
+
+ FileSystem fs = FileSystem.get(configuration);
+ Path path = new Path(filename);
+ if (fs.exists(path)) fs.delete(path, false);
+
+
+ String messageSchema = "message m {";
+ for (FieldInfo fieldInfo : props.fields.values()) {
+ messageSchema += " required " + fieldInfo.parquetType + " " + fieldInfo.name + ";";
+ }
+ // remove the last semicolon, java really needs a join method for strings...
+ // TODO - nvm apparently it requires a semicolon after every field decl, might want to file a bug
+ //messageSchema = messageSchema.substring(schemaType, messageSchema.length() - 1);
+ messageSchema += "}";
+
+ MessageType schema = MessageTypeParser.parseMessageType(messageSchema);
+
+ CompressionCodecName codec = CompressionCodecName.UNCOMPRESSED;
+ ParquetFileWriter w = new ParquetFileWriter(configuration, schema, path);
+ w.start();
+ HashMap<String, Integer> columnValuesWritten = new HashMap();
+ int valsWritten;
+ for (int k = 0; k < props.numberRowGroups; k++){
+ w.startBlock(1);
+ currentBooleanByte = 0;
+ booleanBitCounter.reset();
+
+ for (FieldInfo fieldInfo : props.fields.values()) {
+
+ if ( ! columnValuesWritten.containsKey(fieldInfo.name)){
+ columnValuesWritten.put((String) fieldInfo.name, 0);
+ valsWritten = 0;
+ } else {
+ valsWritten = columnValuesWritten.get(fieldInfo.name);
+ }
+
+ String[] path1 = {(String) fieldInfo.name};
+ ColumnDescriptor c1 = schema.getColumnDescription(path1);
+
+ w.startColumn(c1, props.recordsPerRowGroup, codec);
+ int valsPerPage = (int) Math.ceil(props.recordsPerRowGroup / (float) fieldInfo.numberOfPages);
+ byte[] bytes;
+ // for variable length binary fields
+ int bytesNeededToEncodeLength = 4;
+ if ((int) fieldInfo.bitLength > 0) {
+ bytes = new byte[(int) Math.ceil(valsPerPage * (int) fieldInfo.bitLength / 8.0)];
+ } else {
+ // the twelve at the end is to account for storing a 4 byte length with each value
+ int totalValLength = ((byte[]) fieldInfo.values[0]).length + ((byte[]) fieldInfo.values[1]).length + ((byte[]) fieldInfo.values[2]).length + 3 * bytesNeededToEncodeLength;
+ // used for the case where there is a number of values in this row group that is not divisible by 3
+ int leftOverBytes = 0;
+ if ( valsPerPage % 3 > 0 ) leftOverBytes += ((byte[])fieldInfo.values[1]).length + bytesNeededToEncodeLength;
+ if ( valsPerPage % 3 > 1 ) leftOverBytes += ((byte[])fieldInfo.values[2]).length + bytesNeededToEncodeLength;
+ bytes = new byte[valsPerPage / 3 * totalValLength + leftOverBytes];
+ }
+ int bytesPerPage = (int) (valsPerPage * ((int) fieldInfo.bitLength / 8.0));
+ int bytesWritten = 0;
+ for (int z = 0; z < (int) fieldInfo.numberOfPages; z++, bytesWritten = 0) {
+ for (int i = 0; i < valsPerPage; i++) {
+ //System.out.print(i + ", " + (i % 25 == 0 ? "\n gen " + fieldInfo.name + ": " : ""));
+ if (fieldInfo.values[0] instanceof Boolean) {
+
+ bytes[currentBooleanByte] |= bitFields[booleanBitCounter.val] & ((boolean) fieldInfo.values[valsWritten % 3]
+ ? allBitsTrue : allBitsFalse);
+ booleanBitCounter.increment();
+ if (booleanBitCounter.val == 0) {
+ currentBooleanByte++;
+ }
+ valsWritten++;
+ if (currentBooleanByte > bytesPerPage) break;
+ } else {
+ if (fieldInfo.values[valsWritten % 3] instanceof byte[]){
+ System.arraycopy(ByteArrayUtil.toByta(((byte[])fieldInfo.values[valsWritten % 3]).length),
+ 0, bytes, bytesWritten, bytesNeededToEncodeLength);
+ try{
+ System.arraycopy(fieldInfo.values[valsWritten % 3],
+ 0, bytes, bytesWritten + bytesNeededToEncodeLength, ((byte[])fieldInfo.values[valsWritten % 3]).length);
+ }
+ catch (Exception ex){
+ Math.min(4, 5);
+ }
+ bytesWritten += ((byte[])fieldInfo.values[valsWritten % 3]).length + bytesNeededToEncodeLength;
+ }
+ else{
+ System.arraycopy( ByteArrayUtil.toByta(fieldInfo.values[valsWritten % 3]),
+ 0, bytes, i * ((int) fieldInfo.bitLength / 8), (int) fieldInfo.bitLength / 8);
+ }
+ valsWritten++;
+ }
+
+ }
+ w.writeDataPage((int) (props.recordsPerRowGroup / (int) fieldInfo.numberOfPages), bytes.length, BytesInput.from(bytes), PLAIN, PLAIN, PLAIN);
+ currentBooleanByte = 0;
+ }
+ w.endColumn();
+ columnValuesWritten.remove((String) fieldInfo.name);
+ columnValuesWritten.put((String) fieldInfo.name, valsWritten);
+ }
+
+ w.endBlock();
+ }
+ w.end(new HashMap<String, String>());
+ logger.debug("Finished generating parquet file.");
+ }
+
+ private class ParquetResultListener implements UserResultsListener {
+ private SettableFuture<Void> future = SettableFuture.create();
+ int count = 0;
+ RecordBatchLoader batchLoader;
+
+ int batchCounter = 1;
+ HashMap<String, Integer> valuesChecked = new HashMap();
+ ParquetTestProperties props;
+
+ ParquetResultListener(RecordBatchLoader batchLoader, ParquetTestProperties props){
+ this.batchLoader = batchLoader;
+ this.props = props;
+ }
+
+ @Override
+ public void submissionFailed(RpcException ex) {
+ logger.debug("Submission failed.", ex);
+ future.setException(ex);
+ }
+
+ @Override
+ public void resultArrived(QueryResultBatch result) {
+ logger.debug("result arrived in test batch listener.");
+ if(result.getHeader().getIsLastChunk()){
+ future.set(null);
+ }
+ int columnValCounter = 0;
+ int i = 0;
+ FieldInfo currentField;
+ count += result.getHeader().getRowCount();
+ boolean schemaChanged = false;
+ try {
+ schemaChanged = batchLoader.load(result.getHeader().getDef(), result.getData());
+ } catch (SchemaChangeException e) {
+ throw new RuntimeException(e);
+ }
+
+ int recordCount = 0;
+ // print headers.
+ if (schemaChanged) {
+ } // do not believe any change is needed for when the schema changes, with the current mock scan use case
+
+ for (VectorWrapper vw : batchLoader) {
+ ValueVector vv = vw.getValueVector();
+ currentField = props.fields.get(vv.getField().getName());
+ if (VERBOSE_DEBUG){
+ System.out.println("\n" + (String) currentField.name);
+ }
+ if ( ! valuesChecked.containsKey(vv.getField().getName())){
+ valuesChecked.put(vv.getField().getName(), 0);
+ columnValCounter = 0;
+ } else {
+ columnValCounter = valuesChecked.get(vv.getField().getName());
+ }
+ for (int j = 0; j < ((BaseDataValueVector)vv).getAccessor().getValueCount(); j++) {
+ if (VERBOSE_DEBUG){
+ System.out.print(vv.getAccessor().getObject(j) + ", " + (j % 25 == 0 ? "\n batch:" + batchCounter + " v:" + j + " - " : ""));
+ }
+ assertField(vv, j, (TypeProtos.MinorType) currentField.type,
+ currentField.values[columnValCounter % 3], (String) currentField.name + "/");
+ columnValCounter++;
+ }
+ if (VERBOSE_DEBUG){
+ System.out.println("\n" + ((BaseDataValueVector)vv).getAccessor().getValueCount());
+ }
+ valuesChecked.remove(vv.getField().getName());
+ valuesChecked.put(vv.getField().getName(), columnValCounter);
+ }
+
+ if (VERBOSE_DEBUG){
+ for (i = 0; i < batchLoader.getRecordCount(); i++) {
+ recordCount++;
+ if (i % 50 == 0){
+ System.out.println();
+ for (VectorWrapper vw : batchLoader) {
+ ValueVector v = vw.getValueVector();
+ System.out.print(pad(v.getField().getName(), 20) + " ");
+
+ }
+ System.out.println();
+ System.out.println();
+ }
+
+ for (VectorWrapper vw : batchLoader) {
+ ValueVector v = vw.getValueVector();
+ System.out.print(pad(v.getAccessor().getObject(i).toString(), 20) + " ");
+ }
+ System.out.println(
+
+ );
+ }
+ }
+ batchCounter++;
+ if(result.getHeader().getIsLastChunk()){
+ future.set(null);
+ }
+ }
+
+ public void getResults() throws RpcException{
+ try{
+ future.get();
+ }catch(Throwable t){
+ throw RpcException.mapException(t);
+ }
+ }
+ }
+
+ // specific tests should call this method, but it is not marked as a test itself intentionally
+ public void testParquetFullEngineEventBased(boolean generateNew, String plan, String filename, int numberOfTimesRead /* specified in json plan */, ParquetTestProperties props) throws Exception{
+ testParquetFullEngine(generateNew, plan, null, filename, numberOfTimesRead, props);
+ }
+
+ // specific tests should call this method, but it is not marked as a test itself intentionally
+ public void testParquetFullEngineEventBased(boolean generateNew, String plan, String readEntries, String filename,
+ int numberOfTimesRead /* specified in json plan */, ParquetTestProperties props) throws Exception{
+ RemoteServiceSet serviceSet = RemoteServiceSet.getLocalServiceSet();
+
+ if (generateNew) generateParquetFile(filename, props);
+
+ DrillConfig config = DrillConfig.create();
+
+ try(Drillbit bit1 = new Drillbit(config, serviceSet); DrillClient client = new DrillClient(config, serviceSet.getCoordinator());){
+ bit1.run();
+ client.connect();
+ RecordBatchLoader batchLoader = new RecordBatchLoader(bit1.getContext().getAllocator());
+ ParquetResultListener resultListener = new ParquetResultListener(batchLoader, props);
+ long C = System.nanoTime();
+ if (readEntries != null){
+ client.runQuery(UserProtos.QueryType.LOGICAL, (Files.toString(FileUtils.getResourceAsFile(plan), Charsets.UTF_8).replaceFirst( "&REPLACED_IN_PARQUET_TEST&", readEntries)), resultListener);
+ }
+ else{
+ client.runQuery(UserProtos.QueryType.LOGICAL, Files.toString(FileUtils.getResourceAsFile(plan), Charsets.UTF_8), resultListener);
+ }
+ resultListener.getResults();
+ long D = System.nanoTime();
+ System.out.println(String.format("Took %f s to run query", (float)(D-C) / 1E9));
+ }
+ }
+
+ // specific tests should call this method, but it is not marked as a test itself intentionally
+ public void testParquetFullEngine(boolean generateNew, String plan, String filename, int numberOfTimesRead /* specified in json plan */, ParquetTestProperties props) throws Exception{
+ testParquetFullEngine(generateNew, plan, null, filename, numberOfTimesRead, props);
+ }
+
+ // specific tests should call this method, but it is not marked as a test itself intentionally
+ public void testParquetFullEngine(boolean generateNew, String plan, String readEntries, String filename,
+ int numberOfTimesRead /* specified in json plan */, ParquetTestProperties props) throws Exception{
+ RemoteServiceSet serviceSet = RemoteServiceSet.getLocalServiceSet();
+
+ if (generateNew) generateParquetFile(filename, props);
+
+ DrillConfig config = DrillConfig.create();
+
+ try(Drillbit bit1 = new Drillbit(config, serviceSet); DrillClient client = new DrillClient(config, serviceSet.getCoordinator())) {
+ long A = System.nanoTime();
+ bit1.run();
+ long B = System.nanoTime();
+ client.connect();
+ long C = System.nanoTime();
+ List<QueryResultBatch> results;
+ // insert a variable number of reads
+ if (readEntries != null){
+ results = client.runQuery(UserProtos.QueryType.LOGICAL, (Files.toString(FileUtils.getResourceAsFile(plan), Charsets.UTF_8).replaceFirst( "&REPLACED_IN_PARQUET_TEST&", readEntries)));
+ }
+ else{
+ results = client.runQuery(UserProtos.QueryType.LOGICAL, Files.toString(FileUtils.getResourceAsFile(plan), Charsets.UTF_8));
+ }
+// List<QueryResultBatch> results = client.runQuery(UserProtos.QueryType.PHYSICAL, Files.toString(FileUtils.getResourceAsFile("/parquet_scan_union_screen_physical.json"), Charsets.UTF_8));
+ long D = System.nanoTime();
+ System.out.println(String.format("Took %f s to start drillbit", (float)(B-A) / 1E9));
+ System.out.println(String.format("Took %f s to connect", (float)(C-B) / 1E9));
+ System.out.println(String.format("Took %f s to run query", (float)(D-C) / 1E9));
+ //List<QueryResultBatch> results = client.runQuery(UserProtos.QueryType.PHYSICAL, Files.toString(FileUtils.getResourceAsFile("/parquet_scan_union_screen_physical.json"), Charsets.UTF_8));
+ int count = 0;
+// RecordBatchLoader batchLoader = new RecordBatchLoader(new BootStrapContext(config).getAllocator());
+ RecordBatchLoader batchLoader = new RecordBatchLoader(bit1.getContext().getAllocator());
+ byte[] bytes;
+
+ int batchCounter = 1;
+ int columnValCounter = 0;
+ int i = 0;
+ FieldInfo currentField;
+ HashMap<String, Integer> valuesChecked = new HashMap();
+ for(QueryResultBatch b : results){
+
+ count += b.getHeader().getRowCount();
+ boolean schemaChanged = batchLoader.load(b.getHeader().getDef(), b.getData());
+
+ int recordCount = 0;
+ // print headers.
+ if (schemaChanged) {
+ } // do not believe any change is needed for when the schema changes, with the current mock scan use case
+
+ for (VectorWrapper vw : batchLoader) {
+ ValueVector vv = vw.getValueVector();
+ currentField = props.fields.get(vv.getField().getName());
+ if (VERBOSE_DEBUG){
+ System.out.println("\n" + (String) currentField.name);
+ }
+ if ( ! valuesChecked.containsKey(vv.getField().getName())){
+ valuesChecked.put(vv.getField().getName(), 0);
+ columnValCounter = 0;
+ } else {
+ columnValCounter = valuesChecked.get(vv.getField().getName());
+ }
+ for (int j = 0; j < vv.getAccessor().getValueCount(); j++) {
+ if (VERBOSE_DEBUG){
+ System.out.print(vv.getAccessor().getObject(j) + ", " + (j % 25 == 0 ? "\n batch:" + batchCounter + " v:" + j + " - " : ""));
+ }
+ assertField(vv, j, currentField.type,
+ currentField.values[columnValCounter % 3], currentField.name + "/");
+ columnValCounter++;
+ }
+ if (VERBOSE_DEBUG){
+ System.out.println("\n" + vv.getAccessor().getValueCount());
+ }
+ valuesChecked.remove(vv.getField().getName());
+ valuesChecked.put(vv.getField().getName(), columnValCounter);
+ }
+
+ if (VERBOSE_DEBUG){
+ for (i = 0; i < batchLoader.getRecordCount(); i++) {
+ recordCount++;
+ if (i % 50 == 0){
+ System.out.println();
+ for (VectorWrapper vw : batchLoader) {
+ ValueVector v = vw.getValueVector();
+ System.out.print(pad(v.getField().getName(), 20) + " ");
+
+ }
+ System.out.println();
+ System.out.println();
+ }
+
+ for (VectorWrapper vw : batchLoader) {
+ ValueVector v = vw.getValueVector();
+ System.out.print(pad(v.getAccessor().getObject(i) + "", 20) + " ");
+ }
+ System.out.println(
+
+ );
+ }
+ }
+ batchCounter++;
+ }
+ for (String s : valuesChecked.keySet()) {
+ assertEquals("Record count incorrect for column: " + s, props.recordsPerRowGroup * props.numberRowGroups * numberOfTimesRead, (long) valuesChecked.get(s));
+ }
+ assert valuesChecked.keySet().size() > 0;
+ }
+ }
+
+ public String pad(String value, int length) {
+ return pad(value, length, " ");
+ }
+
+ public String pad(String value, int length, String with) {
+ StringBuilder result = new StringBuilder(length);
+ result.append(value);
+
+ while (result.length() < length) {
+ result.insert(0, with);
+ }
+
+ return result.toString();
+ }
+
+ class MockOutputMutator implements OutputMutator {
+ List<MaterializedField> removedFields = Lists.newArrayList();
+ List<ValueVector> addFields = Lists.newArrayList();
+
+ @Override
+ public void removeField(MaterializedField field) throws SchemaChangeException {
+ removedFields.add(field);
+ }
+
+ @Override
+ public void addField(ValueVector vector) throws SchemaChangeException {
+ addFields.add(vector);
+ }
+
+ @Override
+ public void removeAllFields() {
+ addFields.clear();
+ }
+
+ @Override
+ public void setNewSchema() throws SchemaChangeException {
+ }
+
+ List<MaterializedField> getRemovedFields() {
+ return removedFields;
+ }
+
+ List<ValueVector> getAddFields() {
+ return addFields;
+ }
+ }
+
+ private <T> void assertField(ValueVector valueVector, int index, TypeProtos.MinorType expectedMinorType, Object value, String name) {
+ assertField(valueVector, index, expectedMinorType, value, name, 0);
+ }
+
+ private <T> void assertField(ValueVector valueVector, int index, TypeProtos.MinorType expectedMinorType, T value, String name, int parentFieldId) {
+// UserBitShared.FieldMetadata metadata = valueVector.getMetadata();
+// SchemaDefProtos.FieldDef def = metadata.getDef();
+// assertEquals(expectedMinorType, def.getMajorType().getMinorType());
+// assertEquals(name, def.getNameList().get(0).getName());
+// assertEquals(parentFieldId, def.getParentId());
+
+ if (expectedMinorType == TypeProtos.MinorType.MAP) {
+ return;
+ }
+
+ T val = (T) valueVector.getAccessor().getObject(index);
+ if (val instanceof String){
+ assertEquals(value, val);
+ }
+ else if (val instanceof byte[]) {
+ assertTrue(Arrays.equals((byte[]) value, (byte[]) val));
+ } else {
+ assertEquals(value, val);
+ }
+ }
+
+ private class WrapAroundCounter {
+
+ int maxVal;
+ int val;
+
+ public WrapAroundCounter(int maxVal) {
+ this.maxVal = maxVal;
+ }
+
+ public int increment() {
+ val++;
+ if (val > maxVal) {
+ val = 0;
+ }
+ return val;
+ }
+
+ public void reset() {
+ val = 0;
+ }
+
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-drill/blob/a593d908/exec/java-exec/src/test/java/org/apache/drill/exec/store/TestAffinityCalculator.java
----------------------------------------------------------------------
diff --git a/exec/java-exec/src/test/java/org/apache/drill/exec/store/TestAffinityCalculator.java b/exec/java-exec/src/test/java/org/apache/drill/exec/store/TestAffinityCalculator.java
new file mode 100644
index 0000000..b25c805
--- /dev/null
+++ b/exec/java-exec/src/test/java/org/apache/drill/exec/store/TestAffinityCalculator.java
@@ -0,0 +1,229 @@
+package org.apache.drill.exec.store;
+
+import com.google.common.collect.ImmutableRangeMap;
+import com.google.common.collect.Range;
+import junit.framework.Assert;
+import mockit.Injectable;
+import mockit.NonStrictExpectations;
+import org.apache.drill.exec.physical.EndpointAffinity;
+import org.apache.drill.exec.proto.CoordinationProtos;
+import org.apache.drill.exec.server.DrillbitContext;
+import org.apache.drill.exec.store.parquet.ParquetGroupScan;
+import org.apache.drill.exec.store.parquet.ParquetRowGroupScan;
+import org.apache.drill.exec.store.parquet.ParquetStorageEngine;
+import org.apache.hadoop.fs.BlockLocation;
+import org.apache.hadoop.fs.FileStatus;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.junit.Before;
+import org.junit.Test;
+
+import static junit.framework.Assert.assertNull;
+import static org.junit.Assert.assertEquals;
+
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.LinkedList;
+import java.util.List;
+
+public class TestAffinityCalculator {
+ static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(TestAffinityCalculator.class);
+
+ String port = "1234";
+ final String path = "path";
+
+ public BlockLocation[] buildBlockLocations(String[] hosts, long blockSize) {
+ String[] names = new String[hosts.length];
+
+ for (int i = 0; i < hosts.length; i++) {
+ hosts[i] = "host" + i;
+ names[i] = "host:" + port;
+ }
+
+ BlockLocation[] blockLocations = new BlockLocation[3];
+ blockLocations[0] = new BlockLocation(new String[]{names[0], names[1], names[2]}, new String[]{hosts[0], hosts[1], hosts[2]}, 0, blockSize);
+ blockLocations[1] = new BlockLocation(new String[]{names[0], names[2], names[3]}, new String[]{hosts[0], hosts[2], hosts[3]}, blockSize, blockSize);
+ blockLocations[2] = new BlockLocation(new String[]{names[0], names[1], names[3]}, new String[]{hosts[0], hosts[1], hosts[3]}, blockSize*2, blockSize);
+
+ return blockLocations;
+ }
+
+ public BlockLocation[] buildBlockLocations2(String[] hosts, long blockSize) {
+ String[] names = new String[hosts.length];
+
+ for (int i = 0; i < hosts.length; i++) {
+ hosts[i] = "host" + i;
+ names[i] = "host:" + port;
+ }
+
+ BlockLocation[] blockLocations = new BlockLocation[4];
+ blockLocations[0] = new BlockLocation(new String[]{names[0]}, new String[]{hosts[0]}, 0, blockSize);
+ blockLocations[1] = new BlockLocation(new String[]{names[1]}, new String[]{hosts[1]}, blockSize, blockSize);
+ blockLocations[3] = new BlockLocation(new String[]{names[3]}, new String[]{hosts[3]}, blockSize*2, blockSize);
+ blockLocations[2] = new BlockLocation(new String[]{names[2]}, new String[]{hosts[2]}, blockSize*3, blockSize);
+
+ return blockLocations;
+ }
+ public void buildRowGroups(LinkedList<ParquetGroupScan.RowGroupInfo> rowGroups, int numberOfBlocks, long blockSize, int numberOfRowGroups) {
+ long rowGroupSize = numberOfBlocks * blockSize / numberOfRowGroups;
+
+ rowGroups.clear();
+
+ for (int i = 0; i < numberOfRowGroups; i++) {
+ rowGroups.add(new ParquetGroupScan.RowGroupInfo(path, (long)i*rowGroupSize, (long)rowGroupSize, i));
+ }
+ }
+
+ public LinkedList<CoordinationProtos.DrillbitEndpoint> buildEndpoints(int numberOfEndpoints) {
+ LinkedList<CoordinationProtos.DrillbitEndpoint> endPoints = new LinkedList();
+
+ for (int i = 0; i < numberOfEndpoints; i++) {
+ endPoints.add(CoordinationProtos.DrillbitEndpoint.newBuilder().setAddress("host" + i).build());
+ }
+ return endPoints;
+ }
+
+ @Test
+ public void testSetEndpointBytes(@Injectable final FileSystem fs, @Injectable final FileStatus file) throws Throwable{
+ final long blockSize = 256*1024*1024;
+ LinkedList<ParquetGroupScan.RowGroupInfo> rowGroups = new LinkedList<>();
+ int numberOfHosts = 4;
+ int numberOfBlocks = 3;
+ String port = "1234";
+ String[] hosts = new String[numberOfHosts];
+
+ final BlockLocation[] blockLocations = buildBlockLocations(hosts, blockSize);
+ final LinkedList<CoordinationProtos.DrillbitEndpoint> endPoints = buildEndpoints(numberOfHosts);
+ buildRowGroups(rowGroups, numberOfBlocks, blockSize, 3);
+
+ new NonStrictExpectations() {{
+ fs.getFileBlockLocations(file, 0, 3*blockSize); result = blockLocations;
+ fs.getFileStatus(new Path(path)); result = file;
+ file.getLen(); result = 3*blockSize;
+ }};
+
+
+ AffinityCalculator ac = new AffinityCalculator(fs, endPoints);
+ for (ParquetGroupScan.RowGroupInfo rowGroup : rowGroups) {
+ ac.setEndpointBytes(rowGroup);
+ }
+ ParquetGroupScan.RowGroupInfo rg = rowGroups.get(0);
+ Long b = rg.getEndpointBytes().get(endPoints.get(0));
+ assertEquals(blockSize,b.longValue());
+ b = rg.getEndpointBytes().get(endPoints.get(3));
+ assertNull(b);
+
+ buildRowGroups(rowGroups, numberOfBlocks, blockSize, 2);
+
+ ac = new AffinityCalculator(fs, endPoints);
+ for (ParquetGroupScan.RowGroupInfo rowGroup : rowGroups) {
+ ac.setEndpointBytes(rowGroup);
+ }
+ rg = rowGroups.get(0);
+ b = rg.getEndpointBytes().get(endPoints.get(0));
+ assertEquals(blockSize*3/2,b.longValue());
+ b = rg.getEndpointBytes().get(endPoints.get(3));
+ assertEquals(blockSize / 2, b.longValue());
+
+ buildRowGroups(rowGroups, numberOfBlocks, blockSize, 6);
+
+ ac = new AffinityCalculator(fs, endPoints);
+ for (ParquetGroupScan.RowGroupInfo rowGroup : rowGroups) {
+ ac.setEndpointBytes(rowGroup);
+ }
+ rg = rowGroups.get(0);
+ b = rg.getEndpointBytes().get(endPoints.get(0));
+ assertEquals(blockSize/2,b.longValue());
+ b = rg.getEndpointBytes().get(endPoints.get(3));
+ assertNull(b);
+ }
+
+ @Test
+ public void testBuildRangeMap() {
+ BlockLocation[] blocks = buildBlockLocations(new String[4], 256*1024*1024);
+ long tA = System.nanoTime();
+ ImmutableRangeMap.Builder<Long, BlockLocation> blockMapBuilder = new ImmutableRangeMap.Builder<Long,BlockLocation>();
+ for (BlockLocation block : blocks) {
+ long start = block.getOffset();
+ long end = start + block.getLength();
+ Range<Long> range = Range.closedOpen(start, end);
+ blockMapBuilder = blockMapBuilder.put(range, block);
+ }
+ ImmutableRangeMap<Long,BlockLocation> map = blockMapBuilder.build();
+ long tB = System.nanoTime();
+ System.out.println(String.format("Took %f ms to build range map", (float)(tB - tA) / 1e6));
+ }
+ /*
+ @Test
+ public void testApplyAssignments(@Injectable final DrillbitContext context, @Injectable final ParquetStorageEngine engine,
+ @Injectable final FileSystem fs, @Injectable final FileStatus file) throws IOException {
+
+ final long blockSize = 256*1024*1024;
+ LinkedList<ParquetGroupScan.RowGroupInfo> rowGroups = new LinkedList<>();
+ int numberOfHosts = 4;
+ int numberOfBlocks = 4;
+ String port = "1234";
+ String[] hosts = new String[numberOfHosts];
+
+ final BlockLocation[] blockLocations = buildBlockLocations2(hosts, blockSize);
+ final LinkedList<CoordinationProtos.DrillbitEndpoint> endPoints = buildEndpoints(numberOfHosts);
+
+ new NonStrictExpectations() {{
+ engine.getFileSystem(); result = fs;
+ engine.getContext(); result = context;
+ context.getBits(); result = endPoints;
+ fs.getFileBlockLocations(file, 0, 3*blockSize); result = blockLocations;
+ fs.getFileStatus(new Path(path)); result = file;
+ file.getLen(); result = 3*blockSize;
+ }};
+
+ buildRowGroups(rowGroups, numberOfBlocks, blockSize, 4);
+ ParquetGroupScan scan = new ParquetGroupScan(rowGroups, engine);
+
+ List<EndpointAffinity> affinities = scan.getOperatorAffinity();
+
+ for (EndpointAffinity affinity : affinities) {
+ CoordinationProtos.DrillbitEndpoint db = affinity.getEndpoint();
+ assertEquals((float)0.25, affinity.getAffinity(), .01);
+ }
+
+ scan.applyAssignments(endPoints);
+
+ for (int i = 0; i < endPoints.size(); i++) {
+ List<ParquetRowGroupScan.RowGroupReadEntry> rowGroupReadEntries = scan.getSpecificScan(i).getRowGroupReadEntries();
+ assertEquals(1, rowGroupReadEntries.size());
+ switch(i) {
+ case 0: assertEquals(0,rowGroupReadEntries.get(0).getRowGroupIndex());
+ break;
+ case 1: assertEquals(1,rowGroupReadEntries.get(0).getRowGroupIndex());
+ break;
+ case 2: assertEquals(3,rowGroupReadEntries.get(0).getRowGroupIndex());
+ break;
+ case 3: assertEquals(2,rowGroupReadEntries.get(0).getRowGroupIndex());
+ break;
+ }
+ }
+
+ scan.applyAssignments(endPoints.subList(2,4));
+
+ List<ParquetRowGroupScan.RowGroupReadEntry> rowGroupReadEntries = scan.getSpecificScan(0).getRowGroupReadEntries();
+ assertEquals(2, rowGroupReadEntries.size());
+ assertEquals(3,rowGroupReadEntries.get(0).getRowGroupIndex());
+
+ rowGroupReadEntries = scan.getSpecificScan(1).getRowGroupReadEntries();
+ assertEquals(2, rowGroupReadEntries.size());
+ assertEquals(2,rowGroupReadEntries.get(0).getRowGroupIndex());
+
+ LinkedList<CoordinationProtos.DrillbitEndpoint> dupList = new LinkedList<>();
+ dupList.add(endPoints.get(0));
+ dupList.add(endPoints.get(0));
+ scan.applyAssignments(dupList);
+
+ rowGroupReadEntries = scan.getSpecificScan(0).getRowGroupReadEntries();
+ assertEquals(2, rowGroupReadEntries.size());
+ rowGroupReadEntries = scan.getSpecificScan(1).getRowGroupReadEntries();
+ assertEquals(2, rowGroupReadEntries.size());
+ }
+ */
+
+}