Search in sources :

Example 6 with ErrorCollector

use of org.apache.drill.common.expression.ErrorCollector in project drill by apache.

the class ExpressionTreeMaterializerTest method testMaterializingLateboundTree.

@Test
public void testMaterializingLateboundTree(@Injectable final RecordBatch batch) throws SchemaChangeException {
    new NonStrictExpectations() {

        {
            batch.getValueVectorId(SchemaPath.getSimplePath("test"));
            result = new TypedFieldId(Types.required(MinorType.BIT), -4);
            batch.getValueVectorId(SchemaPath.getSimplePath("test1"));
            result = new TypedFieldId(Types.required(MinorType.BIGINT), -5);
        }
    };
    ErrorCollector ec = new ErrorCollectorImpl();
    LogicalExpression elseExpression = new IfExpression.Builder().setElse(new ValueExpressions.LongExpression(1L, ExpressionPosition.UNKNOWN)).setIfCondition(new IfExpression.IfCondition(new ValueExpressions.BooleanExpression("true", ExpressionPosition.UNKNOWN), new FieldReference("test1", ExpressionPosition.UNKNOWN))).build();
    LogicalExpression expr = new IfExpression.Builder().setIfCondition(new IfExpression.IfCondition(new FieldReference("test", ExpressionPosition.UNKNOWN), new ValueExpressions.LongExpression(2L, ExpressionPosition.UNKNOWN))).setElse(elseExpression).build();
    LogicalExpression newExpr = ExpressionTreeMaterializer.materialize(expr, batch, ec, registry);
    assertTrue(newExpr instanceof IfExpression);
    IfExpression newIfExpr = (IfExpression) newExpr;
    //assertEquals(1, newIfExpr.conditions.size());
    IfExpression.IfCondition ifCondition = newIfExpr.ifCondition;
    assertTrue(newIfExpr.elseExpression instanceof IfExpression);
    //assertEquals(1, newIfExpr.conditions.size());
    //ifCondition = newIfExpr.conditions.get(0);
    assertEquals(bigIntType, ifCondition.expression.getMajorType());
    assertEquals(true, ((ValueExpressions.BooleanExpression) ((IfExpression) (newIfExpr.elseExpression)).ifCondition.condition).value);
    if (ec.hasErrors()) {
        System.out.println(ec.toErrorString());
    }
    assertFalse(ec.hasErrors());
}
Also used : IfExpression(org.apache.drill.common.expression.IfExpression) FieldReference(org.apache.drill.common.expression.FieldReference) ValueExpressions(org.apache.drill.common.expression.ValueExpressions) ErrorCollector(org.apache.drill.common.expression.ErrorCollector) ErrorCollectorImpl(org.apache.drill.common.expression.ErrorCollectorImpl) LogicalExpression(org.apache.drill.common.expression.LogicalExpression) NonStrictExpectations(mockit.NonStrictExpectations) ExecTest(org.apache.drill.exec.ExecTest) Test(org.junit.Test)

Example 7 with ErrorCollector

use of org.apache.drill.common.expression.ErrorCollector in project drill by apache.

the class ExpressionTreeMaterializerTest method testMaterializingLateboundField.

@Test
public void testMaterializingLateboundField(@Injectable final 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 SchemaPath("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, registry);
    assertEquals(bigIntType, expr.getMajorType());
    assertFalse(ec.hasErrors());
}
Also used : ErrorCollectorImpl(org.apache.drill.common.expression.ErrorCollectorImpl) LogicalExpression(org.apache.drill.common.expression.LogicalExpression) FieldReference(org.apache.drill.common.expression.FieldReference) SchemaPath(org.apache.drill.common.expression.SchemaPath) ErrorCollector(org.apache.drill.common.expression.ErrorCollector) NonStrictExpectations(mockit.NonStrictExpectations) ExecTest(org.apache.drill.exec.ExecTest) Test(org.junit.Test)

Example 8 with ErrorCollector

use of org.apache.drill.common.expression.ErrorCollector in project drill by apache.

the class UnionAllRecordBatch method doWork.

@SuppressWarnings("resource")
private IterOutcome doWork() throws ClassTransformationException, IOException, SchemaChangeException {
    if (allocationVectors != null) {
        for (ValueVector v : allocationVectors) {
            v.clear();
        }
    }
    allocationVectors = Lists.newArrayList();
    transfers.clear();
    // If both sides of Union-All are empty
    if (unionAllInput.isBothSideEmpty()) {
        for (int i = 0; i < outputFields.size(); ++i) {
            final String colName = outputFields.get(i).getPath();
            final MajorType majorType = MajorType.newBuilder().setMinorType(MinorType.INT).setMode(DataMode.OPTIONAL).build();
            MaterializedField outputField = MaterializedField.create(colName, majorType);
            ValueVector vv = container.addOrGet(outputField, callBack);
            allocationVectors.add(vv);
        }
        container.buildSchema(BatchSchema.SelectionVectorMode.NONE);
        return IterOutcome.OK_NEW_SCHEMA;
    }
    final ClassGenerator<UnionAller> cg = CodeGenerator.getRoot(UnionAller.TEMPLATE_DEFINITION, context.getFunctionRegistry(), context.getOptions());
    cg.getCodeGenerator().plainJavaCapable(true);
    // Uncomment out this line to debug the generated code.
    //    cg.getCodeGenerator().saveCodeForDebugging(true);
    int index = 0;
    for (VectorWrapper<?> vw : current) {
        ValueVector vvIn = vw.getValueVector();
        // get the original input column names
        SchemaPath inputPath = SchemaPath.getSimplePath(vvIn.getField().getPath());
        // get the renamed column names
        SchemaPath outputPath = SchemaPath.getSimplePath(outputFields.get(index).getPath());
        final ErrorCollector collector = new ErrorCollectorImpl();
        // cast data types (Minortype or DataMode)
        if (hasSameTypeAndMode(outputFields.get(index), vw.getValueVector().getField())) {
            // Transfer column
            MajorType outputFieldType = outputFields.get(index).getType();
            MaterializedField outputField = MaterializedField.create(outputPath.getAsUnescapedPath(), outputFieldType);
            /*
          todo: Fix if condition when DRILL-4824 is merged
          If condition should be changed to:
          `if (outputFields.get(index).getPath().equals(inputPath.getAsUnescapedPath())) {`
          DRILL-5419 has changed condition to correct one but this caused regression (DRILL-5521).
          Root cause is missing indication of child column in map types when it is null.
          DRILL-4824 is re-working json reader implementation, including map types and will fix this problem.
          Reverting condition to previous one to avoid regression till DRILL-4824 is merged.
          Unit test - TestJsonReader.testKvgenWithUnionAll().
         */
            if (outputFields.get(index).getPath().equals(inputPath)) {
                ValueVector vvOut = container.addOrGet(outputField);
                TransferPair tp = vvIn.makeTransferPair(vvOut);
                transfers.add(tp);
            // Copy data in order to rename the column
            } else {
                final LogicalExpression expr = ExpressionTreeMaterializer.materialize(inputPath, current, collector, context.getFunctionRegistry());
                if (collector.hasErrors()) {
                    throw new SchemaChangeException(String.format("Failure while trying to materialize incoming schema.  Errors:\n %s.", collector.toErrorString()));
                }
                ValueVector vv = container.addOrGet(outputField, callBack);
                allocationVectors.add(vv);
                TypedFieldId fid = container.getValueVectorId(SchemaPath.getSimplePath(outputField.getPath()));
                ValueVectorWriteExpression write = new ValueVectorWriteExpression(fid, expr, true);
                cg.addExpr(write);
            }
        // Cast is necessary
        } else {
            LogicalExpression expr = ExpressionTreeMaterializer.materialize(inputPath, current, collector, context.getFunctionRegistry());
            if (collector.hasErrors()) {
                throw new SchemaChangeException(String.format("Failure while trying to materialize incoming schema.  Errors:\n %s.", collector.toErrorString()));
            }
            // cast to the one with the least restriction
            if (vvIn.getField().getType().getMode() == DataMode.REQUIRED && outputFields.get(index).getType().getMode() != DataMode.REQUIRED) {
                expr = ExpressionTreeMaterializer.convertToNullableType(expr, vvIn.getField().getType().getMinorType(), context.getFunctionRegistry(), collector);
                if (collector.hasErrors()) {
                    throw new SchemaChangeException(String.format("Failure while trying to materialize incoming schema.  Errors:\n %s.", collector.toErrorString()));
                }
            }
            // Insert a cast before the Union operation
            if (vvIn.getField().getType().getMinorType() != outputFields.get(index).getType().getMinorType()) {
                expr = ExpressionTreeMaterializer.addCastExpression(expr, outputFields.get(index).getType(), context.getFunctionRegistry(), collector);
                if (collector.hasErrors()) {
                    throw new SchemaChangeException(String.format("Failure while trying to materialize incoming schema.  Errors:\n %s.", collector.toErrorString()));
                }
            }
            final MaterializedField outputField = MaterializedField.create(outputPath.getAsUnescapedPath(), expr.getMajorType());
            ValueVector vector = container.addOrGet(outputField, callBack);
            allocationVectors.add(vector);
            TypedFieldId fid = container.getValueVectorId(SchemaPath.getSimplePath(outputField.getPath()));
            boolean useSetSafe = !(vector instanceof FixedWidthVector);
            ValueVectorWriteExpression write = new ValueVectorWriteExpression(fid, expr, useSetSafe);
            cg.addExpr(write);
        }
        ++index;
    }
    unionall = context.getImplementationClass(cg.getCodeGenerator());
    unionall.setup(context, current, this, transfers);
    if (!schemaAvailable) {
        container.buildSchema(BatchSchema.SelectionVectorMode.NONE);
        schemaAvailable = true;
    }
    if (!doAlloc()) {
        return IterOutcome.OUT_OF_MEMORY;
    }
    recordCount = unionall.unionRecords(0, current.getRecordCount(), 0);
    setValueCount(recordCount);
    return IterOutcome.OK;
}
Also used : TransferPair(org.apache.drill.exec.record.TransferPair) FixedWidthVector(org.apache.drill.exec.vector.FixedWidthVector) MajorType(org.apache.drill.common.types.TypeProtos.MajorType) MaterializedField(org.apache.drill.exec.record.MaterializedField) ErrorCollector(org.apache.drill.common.expression.ErrorCollector) ValueVector(org.apache.drill.exec.vector.ValueVector) ErrorCollectorImpl(org.apache.drill.common.expression.ErrorCollectorImpl) LogicalExpression(org.apache.drill.common.expression.LogicalExpression) SchemaChangeException(org.apache.drill.exec.exception.SchemaChangeException) SchemaPath(org.apache.drill.common.expression.SchemaPath) TypedFieldId(org.apache.drill.exec.record.TypedFieldId) ValueVectorWriteExpression(org.apache.drill.exec.expr.ValueVectorWriteExpression)

Example 9 with ErrorCollector

use of org.apache.drill.common.expression.ErrorCollector in project drill by apache.

the class OperatorCodeGenerator method generateComparisons.

protected void generateComparisons(ClassGenerator<?> g, VectorAccessible batch) {
    g.setMappingSet(MAIN_MAPPING);
    for (Ordering od : popConfig.getOrderings()) {
        // first, we rewrite the evaluation stack for each side of the comparison.
        ErrorCollector collector = new ErrorCollectorImpl();
        final LogicalExpression expr = ExpressionTreeMaterializer.materialize(od.getExpr(), batch, collector, context.getFunctionRegistry());
        if (collector.hasErrors()) {
            throw UserException.unsupportedError().message("Failure while materializing expression. " + collector.toErrorString()).build(logger);
        }
        g.setMappingSet(LEFT_MAPPING);
        HoldingContainer left = g.addExpr(expr, ClassGenerator.BlkCreateMode.FALSE);
        g.setMappingSet(RIGHT_MAPPING);
        HoldingContainer right = g.addExpr(expr, ClassGenerator.BlkCreateMode.FALSE);
        g.setMappingSet(MAIN_MAPPING);
        // next we wrap the two comparison sides and add the expression block for the comparison.
        LogicalExpression fh = FunctionGenerationHelper.getOrderingComparator(od.nullsSortHigh(), left, right, context.getFunctionRegistry());
        HoldingContainer out = g.addExpr(fh, ClassGenerator.BlkCreateMode.FALSE);
        JConditional jc = g.getEvalBlock()._if(out.getValue().ne(JExpr.lit(0)));
        if (od.getDirection() == Direction.ASCENDING) {
            jc._then()._return(out.getValue());
        } else {
            jc._then()._return(out.getValue().minus());
        }
        g.rotateBlock();
    }
    g.rotateBlock();
    g.getEvalBlock()._return(JExpr.lit(0));
}
Also used : ErrorCollectorImpl(org.apache.drill.common.expression.ErrorCollectorImpl) LogicalExpression(org.apache.drill.common.expression.LogicalExpression) HoldingContainer(org.apache.drill.exec.expr.ClassGenerator.HoldingContainer) Ordering(org.apache.drill.common.logical.data.Order.Ordering) ErrorCollector(org.apache.drill.common.expression.ErrorCollector) JConditional(com.sun.codemodel.JConditional)

Example 10 with ErrorCollector

use of org.apache.drill.common.expression.ErrorCollector in project drill by apache.

the class OperatorCodeGenerator method createNewMSorter.

private MSorter createNewMSorter(List<Ordering> orderings, VectorAccessible batch, MappingSet mainMapping, MappingSet leftMapping, MappingSet rightMapping) {
    CodeGenerator<MSorter> cg = CodeGenerator.get(MSorter.TEMPLATE_DEFINITION, context.getFunctionRegistry(), context.getOptions());
    cg.plainJavaCapable(true);
    // Uncomment out this line to debug the generated code.
    //  cg.saveCodeForDebugging(true);
    ClassGenerator<MSorter> g = cg.getRoot();
    g.setMappingSet(mainMapping);
    for (Ordering od : orderings) {
        // first, we rewrite the evaluation stack for each side of the comparison.
        ErrorCollector collector = new ErrorCollectorImpl();
        final LogicalExpression expr = ExpressionTreeMaterializer.materialize(od.getExpr(), batch, collector, context.getFunctionRegistry());
        if (collector.hasErrors()) {
            throw UserException.unsupportedError().message("Failure while materializing expression. " + collector.toErrorString()).build(logger);
        }
        g.setMappingSet(leftMapping);
        HoldingContainer left = g.addExpr(expr, ClassGenerator.BlkCreateMode.FALSE);
        g.setMappingSet(rightMapping);
        HoldingContainer right = g.addExpr(expr, ClassGenerator.BlkCreateMode.FALSE);
        g.setMappingSet(mainMapping);
        // next we wrap the two comparison sides and add the expression block for the comparison.
        LogicalExpression fh = FunctionGenerationHelper.getOrderingComparator(od.nullsSortHigh(), left, right, context.getFunctionRegistry());
        HoldingContainer out = g.addExpr(fh, ClassGenerator.BlkCreateMode.FALSE);
        JConditional jc = g.getEvalBlock()._if(out.getValue().ne(JExpr.lit(0)));
        if (od.getDirection() == Direction.ASCENDING) {
            jc._then()._return(out.getValue());
        } else {
            jc._then()._return(out.getValue().minus());
        }
        g.rotateBlock();
    }
    g.rotateBlock();
    g.getEvalBlock()._return(JExpr.lit(0));
    return getInstance(cg);
}
Also used : ErrorCollectorImpl(org.apache.drill.common.expression.ErrorCollectorImpl) LogicalExpression(org.apache.drill.common.expression.LogicalExpression) HoldingContainer(org.apache.drill.exec.expr.ClassGenerator.HoldingContainer) Ordering(org.apache.drill.common.logical.data.Order.Ordering) ErrorCollector(org.apache.drill.common.expression.ErrorCollector) JConditional(com.sun.codemodel.JConditional)

Aggregations

ErrorCollector (org.apache.drill.common.expression.ErrorCollector)31 LogicalExpression (org.apache.drill.common.expression.LogicalExpression)31 ErrorCollectorImpl (org.apache.drill.common.expression.ErrorCollectorImpl)30 SchemaChangeException (org.apache.drill.exec.exception.SchemaChangeException)18 HoldingContainer (org.apache.drill.exec.expr.ClassGenerator.HoldingContainer)10 TypedFieldId (org.apache.drill.exec.record.TypedFieldId)10 Ordering (org.apache.drill.common.logical.data.Order.Ordering)9 MaterializedField (org.apache.drill.exec.record.MaterializedField)9 ValueVector (org.apache.drill.exec.vector.ValueVector)9 JConditional (com.sun.codemodel.JConditional)8 IOException (java.io.IOException)8 ClassTransformationException (org.apache.drill.exec.exception.ClassTransformationException)7 SchemaPath (org.apache.drill.common.expression.SchemaPath)6 ValueVectorWriteExpression (org.apache.drill.exec.expr.ValueVectorWriteExpression)6 TransferPair (org.apache.drill.exec.record.TransferPair)6 FieldReference (org.apache.drill.common.expression.FieldReference)5 NamedExpression (org.apache.drill.common.logical.data.NamedExpression)5 ExecTest (org.apache.drill.exec.ExecTest)4 NonStrictExpectations (mockit.NonStrictExpectations)3 IfExpression (org.apache.drill.common.expression.IfExpression)3