Search in sources :

Example 1 with Statement

use of org.apache.calcite.linq4j.tree.Statement in project calcite by apache.

the class BlockBuilderBase method optimizeStatement.

public static BlockStatement optimizeStatement(Statement statement) {
    BlockBuilder b = new BlockBuilder(true);
    if (!(statement instanceof BlockStatement)) {
        b.add(statement);
    } else {
        BlockStatement bs = (BlockStatement) statement;
        for (Statement stmt : bs.statements) {
            b.add(stmt);
        }
    }
    BlockStatement bs = b.toBlock();
    return bs;
}
Also used : BlockStatement(org.apache.calcite.linq4j.tree.BlockStatement) Statement(org.apache.calcite.linq4j.tree.Statement) BlockStatement(org.apache.calcite.linq4j.tree.BlockStatement) BlockBuilder(org.apache.calcite.linq4j.tree.BlockBuilder)

Example 2 with Statement

use of org.apache.calcite.linq4j.tree.Statement in project apex-malhar by apache.

the class ExpressionCompiler method getExpression.

/**
 * Create quasi-Java expression from given {@link RexNode}
 *
 * @param node Expression in the form of {@link RexNode}
 * @param inputRowType Input Data type to expression in the form of {@link RelDataType}
 * @param outputRowType Output data type of expression in the form of {@link RelDataType}
 *
 * @return Returns quasi-Java expression
 */
public String getExpression(RexNode node, RelDataType inputRowType, RelDataType outputRowType) {
    final RexProgramBuilder programBuilder = new RexProgramBuilder(inputRowType, rexBuilder);
    programBuilder.addProject(node, null);
    final RexProgram program = programBuilder.getProgram();
    final BlockBuilder builder = new BlockBuilder();
    final JavaTypeFactory javaTypeFactory = (JavaTypeFactory) rexBuilder.getTypeFactory();
    final RexToLixTranslator.InputGetter inputGetter = new RexToLixTranslator.InputGetterImpl(ImmutableList.of(Pair.<Expression, PhysType>of(Expressions.variable(Object[].class, "inputValues"), PhysTypeImpl.of(javaTypeFactory, inputRowType, JavaRowFormat.ARRAY, false))));
    final Function1<String, RexToLixTranslator.InputGetter> correlates = new Function1<String, RexToLixTranslator.InputGetter>() {

        public RexToLixTranslator.InputGetter apply(String a0) {
            throw new UnsupportedOperationException();
        }
    };
    final List<Expression> list = RexToLixTranslator.translateProjects(program, javaTypeFactory, builder, PhysTypeImpl.of(javaTypeFactory, outputRowType, JavaRowFormat.ARRAY, false), null, inputGetter, correlates);
    for (int i = 0; i < list.size(); i++) {
        Statement statement = Expressions.statement(list.get(i));
        builder.add(statement);
    }
    return finalizeExpression(builder.toBlock(), inputRowType);
}
Also used : RexProgram(org.apache.calcite.rex.RexProgram) BlockStatement(org.apache.calcite.linq4j.tree.BlockStatement) Statement(org.apache.calcite.linq4j.tree.Statement) Function1(org.apache.calcite.linq4j.function.Function1) PhysType(org.apache.calcite.adapter.enumerable.PhysType) Expression(org.apache.calcite.linq4j.tree.Expression) JavaTypeFactory(org.apache.calcite.adapter.java.JavaTypeFactory) RexToLixTranslator(org.apache.calcite.adapter.enumerable.RexToLixTranslator) RexProgramBuilder(org.apache.calcite.rex.RexProgramBuilder) BlockBuilder(org.apache.calcite.linq4j.tree.BlockBuilder)

Example 3 with Statement

use of org.apache.calcite.linq4j.tree.Statement in project calcite by apache.

the class EnumerableRelImplementor method implementRoot.

public ClassDeclaration implementRoot(EnumerableRel rootRel, EnumerableRel.Prefer prefer) {
    EnumerableRel.Result result = rootRel.implement(this, prefer);
    switch(prefer) {
        case ARRAY:
            if (result.physType.getFormat() == JavaRowFormat.ARRAY && rootRel.getRowType().getFieldCount() == 1) {
                BlockBuilder bb = new BlockBuilder();
                Expression e = null;
                for (Statement statement : result.block.statements) {
                    if (statement instanceof GotoStatement) {
                        e = bb.append("v", ((GotoStatement) statement).expression);
                    } else {
                        bb.add(statement);
                    }
                }
                if (e != null) {
                    bb.add(Expressions.return_(null, Expressions.call(null, BuiltInMethod.SLICE0.method, e)));
                }
                result = new EnumerableRel.Result(bb.toBlock(), result.physType, JavaRowFormat.SCALAR);
            }
    }
    final List<MemberDeclaration> memberDeclarations = new ArrayList<>();
    new TypeRegistrar(memberDeclarations).go(result);
    // The following is a workaround to
    // http://jira.codehaus.org/browse/JANINO-169. Otherwise we'd remove the
    // member variable, rename the "root0" parameter as "root", and reference it
    // directly from inner classes.
    final ParameterExpression root0_ = Expressions.parameter(Modifier.FINAL, DataContext.class, "root0");
    // This creates the following code
    // final Integer v1stashed = (Integer) root.get("v1stashed")
    // It is convenient for passing non-literal "compile-time" constants
    final Collection<Statement> stashed = Collections2.transform(stashedParameters.values(), new Function<ParameterExpression, Statement>() {

        public Statement apply(ParameterExpression input) {
            return Expressions.declare(Modifier.FINAL, input, Expressions.convert_(Expressions.call(DataContext.ROOT, BuiltInMethod.DATA_CONTEXT_GET.method, Expressions.constant(input.name)), input.type));
        }
    });
    final BlockStatement block = Expressions.block(Iterables.concat(ImmutableList.of(Expressions.statement(Expressions.assign(DataContext.ROOT, root0_))), stashed, result.block.statements));
    memberDeclarations.add(Expressions.fieldDecl(0, DataContext.ROOT, null));
    memberDeclarations.add(Expressions.methodDecl(Modifier.PUBLIC, Enumerable.class, BuiltInMethod.BINDABLE_BIND.method.getName(), Expressions.list(root0_), block));
    memberDeclarations.add(Expressions.methodDecl(Modifier.PUBLIC, Class.class, BuiltInMethod.TYPED_GET_ELEMENT_TYPE.method.getName(), Collections.<ParameterExpression>emptyList(), Blocks.toFunctionBlock(Expressions.return_(null, Expressions.constant(result.physType.getJavaRowType())))));
    return Expressions.classDecl(Modifier.PUBLIC, "Baz", null, Collections.<Type>singletonList(Bindable.class), memberDeclarations);
}
Also used : GotoStatement(org.apache.calcite.linq4j.tree.GotoStatement) Statement(org.apache.calcite.linq4j.tree.Statement) BlockStatement(org.apache.calcite.linq4j.tree.BlockStatement) ConditionalStatement(org.apache.calcite.linq4j.tree.ConditionalStatement) MemberDeclaration(org.apache.calcite.linq4j.tree.MemberDeclaration) ArrayList(java.util.ArrayList) Bindable(org.apache.calcite.runtime.Bindable) BlockStatement(org.apache.calcite.linq4j.tree.BlockStatement) GotoStatement(org.apache.calcite.linq4j.tree.GotoStatement) NewArrayExpression(org.apache.calcite.linq4j.tree.NewArrayExpression) Expression(org.apache.calcite.linq4j.tree.Expression) NewExpression(org.apache.calcite.linq4j.tree.NewExpression) MethodCallExpression(org.apache.calcite.linq4j.tree.MethodCallExpression) ConstantExpression(org.apache.calcite.linq4j.tree.ConstantExpression) ParameterExpression(org.apache.calcite.linq4j.tree.ParameterExpression) ParameterExpression(org.apache.calcite.linq4j.tree.ParameterExpression) Enumerable(org.apache.calcite.linq4j.Enumerable) BlockBuilder(org.apache.calcite.linq4j.tree.BlockBuilder)

Example 4 with Statement

use of org.apache.calcite.linq4j.tree.Statement in project calcite by apache.

the class EnumerableWindow method implement.

public Result implement(EnumerableRelImplementor implementor, Prefer pref) {
    final JavaTypeFactory typeFactory = implementor.getTypeFactory();
    final EnumerableRel child = (EnumerableRel) getInput();
    final BlockBuilder builder = new BlockBuilder();
    final Result result = implementor.visitChild(this, 0, child, pref);
    Expression source_ = builder.append("source", result.block);
    final List<Expression> translatedConstants = new ArrayList<Expression>(constants.size());
    for (RexLiteral constant : constants) {
        translatedConstants.add(RexToLixTranslator.translateLiteral(constant, constant.getType(), typeFactory, RexImpTable.NullAs.NULL));
    }
    PhysType inputPhysType = result.physType;
    final int w = implementor.windowCount++;
    ParameterExpression prevStart = Expressions.parameter(int.class, builder.newName("prevStart" + w));
    ParameterExpression prevEnd = Expressions.parameter(int.class, builder.newName("prevEnd" + w));
    builder.add(Expressions.declare(0, prevStart, null));
    builder.add(Expressions.declare(0, prevEnd, null));
    for (int windowIdx = 0; windowIdx < groups.size(); windowIdx++) {
        Group group = groups.get(windowIdx);
        // Comparator:
        // final Comparator<JdbcTest.Employee> comparator =
        // new Comparator<JdbcTest.Employee>() {
        // public int compare(JdbcTest.Employee o1,
        // JdbcTest.Employee o2) {
        // return Integer.compare(o1.empid, o2.empid);
        // }
        // };
        final Expression comparator_ = builder.append("comparator", inputPhysType.generateComparator(group.collation()));
        Pair<Expression, Expression> partitionIterator = getPartitionIterator(builder, source_, inputPhysType, group, comparator_);
        final Expression collectionExpr = partitionIterator.left;
        final Expression iterator_ = partitionIterator.right;
        List<AggImpState> aggs = new ArrayList<AggImpState>();
        List<AggregateCall> aggregateCalls = group.getAggregateCalls(this);
        for (int aggIdx = 0; aggIdx < aggregateCalls.size(); aggIdx++) {
            AggregateCall call = aggregateCalls.get(aggIdx);
            aggs.add(new AggImpState(aggIdx, call, true));
        }
        // The output from this stage is the input plus the aggregate functions.
        final RelDataTypeFactory.Builder typeBuilder = typeFactory.builder();
        typeBuilder.addAll(inputPhysType.getRowType().getFieldList());
        for (AggImpState agg : aggs) {
            typeBuilder.add(agg.call.name, agg.call.type);
        }
        RelDataType outputRowType = typeBuilder.build();
        final PhysType outputPhysType = PhysTypeImpl.of(typeFactory, outputRowType, pref.prefer(result.format));
        final Expression list_ = builder.append("list", Expressions.new_(ArrayList.class, Expressions.call(collectionExpr, BuiltInMethod.COLLECTION_SIZE.method)), false);
        Pair<Expression, Expression> collationKey = getRowCollationKey(builder, inputPhysType, group, windowIdx);
        Expression keySelector = collationKey.left;
        Expression keyComparator = collationKey.right;
        final BlockBuilder builder3 = new BlockBuilder();
        final Expression rows_ = builder3.append("rows", Expressions.convert_(Expressions.call(iterator_, BuiltInMethod.ITERATOR_NEXT.method), Object[].class), false);
        builder3.add(Expressions.statement(Expressions.assign(prevStart, Expressions.constant(-1))));
        builder3.add(Expressions.statement(Expressions.assign(prevEnd, Expressions.constant(Integer.MAX_VALUE))));
        final BlockBuilder builder4 = new BlockBuilder();
        final ParameterExpression i_ = Expressions.parameter(int.class, builder4.newName("i"));
        final Expression row_ = builder4.append("row", RexToLixTranslator.convert(Expressions.arrayIndex(rows_, i_), inputPhysType.getJavaRowType()));
        final RexToLixTranslator.InputGetter inputGetter = new WindowRelInputGetter(row_, inputPhysType, result.physType.getRowType().getFieldCount(), translatedConstants);
        final RexToLixTranslator translator = RexToLixTranslator.forAggregation(typeFactory, builder4, inputGetter);
        final List<Expression> outputRow = new ArrayList<Expression>();
        int fieldCountWithAggResults = inputPhysType.getRowType().getFieldCount();
        for (int i = 0; i < fieldCountWithAggResults; i++) {
            outputRow.add(inputPhysType.fieldReference(row_, i, outputPhysType.getJavaFieldType(i)));
        }
        declareAndResetState(typeFactory, builder, result, windowIdx, aggs, outputPhysType, outputRow);
        // There are assumptions that minX==0. If ever change this, look for
        // frameRowCount, bounds checking, etc
        final Expression minX = Expressions.constant(0);
        final Expression partitionRowCount = builder3.append("partRows", Expressions.field(rows_, "length"));
        final Expression maxX = builder3.append("maxX", Expressions.subtract(partitionRowCount, Expressions.constant(1)));
        final Expression startUnchecked = builder4.append("start", translateBound(translator, i_, row_, minX, maxX, rows_, group, true, inputPhysType, comparator_, keySelector, keyComparator));
        final Expression endUnchecked = builder4.append("end", translateBound(translator, i_, row_, minX, maxX, rows_, group, false, inputPhysType, comparator_, keySelector, keyComparator));
        final Expression startX;
        final Expression endX;
        final Expression hasRows;
        if (group.isAlwaysNonEmpty()) {
            startX = startUnchecked;
            endX = endUnchecked;
            hasRows = Expressions.constant(true);
        } else {
            Expression startTmp = group.lowerBound.isUnbounded() || startUnchecked == i_ ? startUnchecked : builder4.append("startTmp", Expressions.call(null, BuiltInMethod.MATH_MAX.method, startUnchecked, minX));
            Expression endTmp = group.upperBound.isUnbounded() || endUnchecked == i_ ? endUnchecked : builder4.append("endTmp", Expressions.call(null, BuiltInMethod.MATH_MIN.method, endUnchecked, maxX));
            ParameterExpression startPe = Expressions.parameter(0, int.class, builder4.newName("startChecked"));
            ParameterExpression endPe = Expressions.parameter(0, int.class, builder4.newName("endChecked"));
            builder4.add(Expressions.declare(Modifier.FINAL, startPe, null));
            builder4.add(Expressions.declare(Modifier.FINAL, endPe, null));
            hasRows = builder4.append("hasRows", Expressions.lessThanOrEqual(startTmp, endTmp));
            builder4.add(Expressions.ifThenElse(hasRows, Expressions.block(Expressions.statement(Expressions.assign(startPe, startTmp)), Expressions.statement(Expressions.assign(endPe, endTmp))), Expressions.block(Expressions.statement(Expressions.assign(startPe, Expressions.constant(-1))), Expressions.statement(Expressions.assign(endPe, Expressions.constant(-1))))));
            startX = startPe;
            endX = endPe;
        }
        final BlockBuilder builder5 = new BlockBuilder(true, builder4);
        BinaryExpression rowCountWhenNonEmpty = Expressions.add(startX == minX ? endX : Expressions.subtract(endX, startX), Expressions.constant(1));
        final Expression frameRowCount;
        if (hasRows.equals(Expressions.constant(true))) {
            frameRowCount = builder4.append("totalRows", rowCountWhenNonEmpty);
        } else {
            frameRowCount = builder4.append("totalRows", Expressions.condition(hasRows, rowCountWhenNonEmpty, Expressions.constant(0)));
        }
        ParameterExpression actualStart = Expressions.parameter(0, int.class, builder5.newName("actualStart"));
        final BlockBuilder builder6 = new BlockBuilder(true, builder5);
        builder6.add(Expressions.statement(Expressions.assign(actualStart, startX)));
        for (final AggImpState agg : aggs) {
            agg.implementor.implementReset(agg.context, new WinAggResetContextImpl(builder6, agg.state, i_, startX, endX, hasRows, partitionRowCount, frameRowCount));
        }
        Expression lowerBoundCanChange = group.lowerBound.isUnbounded() && group.lowerBound.isPreceding() ? Expressions.constant(false) : Expressions.notEqual(startX, prevStart);
        Expression needRecomputeWindow = Expressions.orElse(lowerBoundCanChange, Expressions.lessThan(endX, prevEnd));
        BlockStatement resetWindowState = builder6.toBlock();
        if (resetWindowState.statements.size() == 1) {
            builder5.add(Expressions.declare(0, actualStart, Expressions.condition(needRecomputeWindow, startX, Expressions.add(prevEnd, Expressions.constant(1)))));
        } else {
            builder5.add(Expressions.declare(0, actualStart, null));
            builder5.add(Expressions.ifThenElse(needRecomputeWindow, resetWindowState, Expressions.statement(Expressions.assign(actualStart, Expressions.add(prevEnd, Expressions.constant(1))))));
        }
        if (lowerBoundCanChange instanceof BinaryExpression) {
            builder5.add(Expressions.statement(Expressions.assign(prevStart, startX)));
        }
        builder5.add(Expressions.statement(Expressions.assign(prevEnd, endX)));
        final BlockBuilder builder7 = new BlockBuilder(true, builder5);
        final DeclarationStatement jDecl = Expressions.declare(0, "j", actualStart);
        final PhysType inputPhysTypeFinal = inputPhysType;
        final Function<BlockBuilder, WinAggFrameResultContext> resultContextBuilder = getBlockBuilderWinAggFrameResultContextFunction(typeFactory, result, translatedConstants, comparator_, rows_, i_, startX, endX, minX, maxX, hasRows, frameRowCount, partitionRowCount, jDecl, inputPhysTypeFinal);
        final Function<AggImpState, List<RexNode>> rexArguments = new Function<AggImpState, List<RexNode>>() {

            public List<RexNode> apply(AggImpState agg) {
                List<Integer> argList = agg.call.getArgList();
                List<RelDataType> inputTypes = EnumUtils.fieldRowTypes(result.physType.getRowType(), constants, argList);
                List<RexNode> args = new ArrayList<RexNode>(inputTypes.size());
                for (int i = 0; i < argList.size(); i++) {
                    Integer idx = argList.get(i);
                    args.add(new RexInputRef(idx, inputTypes.get(i)));
                }
                return args;
            }
        };
        implementAdd(aggs, builder7, resultContextBuilder, rexArguments, jDecl);
        BlockStatement forBlock = builder7.toBlock();
        if (!forBlock.statements.isEmpty()) {
            // For instance, row_number does not use for loop to compute the value
            Statement forAggLoop = Expressions.for_(Arrays.asList(jDecl), Expressions.lessThanOrEqual(jDecl.parameter, endX), Expressions.preIncrementAssign(jDecl.parameter), forBlock);
            if (!hasRows.equals(Expressions.constant(true))) {
                forAggLoop = Expressions.ifThen(hasRows, forAggLoop);
            }
            builder5.add(forAggLoop);
        }
        if (implementResult(aggs, builder5, resultContextBuilder, rexArguments, true)) {
            builder4.add(Expressions.ifThen(Expressions.orElse(lowerBoundCanChange, Expressions.notEqual(endX, prevEnd)), builder5.toBlock()));
        }
        implementResult(aggs, builder4, resultContextBuilder, rexArguments, false);
        builder4.add(Expressions.statement(Expressions.call(list_, BuiltInMethod.COLLECTION_ADD.method, outputPhysType.record(outputRow))));
        builder3.add(Expressions.for_(Expressions.declare(0, i_, Expressions.constant(0)), Expressions.lessThan(i_, Expressions.field(rows_, "length")), Expressions.preIncrementAssign(i_), builder4.toBlock()));
        builder.add(Expressions.while_(Expressions.call(iterator_, BuiltInMethod.ITERATOR_HAS_NEXT.method), builder3.toBlock()));
        builder.add(Expressions.statement(Expressions.call(collectionExpr, BuiltInMethod.MAP_CLEAR.method)));
        // We're not assigning to "source". For each group, create a new
        // final variable called "source" or "sourceN".
        source_ = builder.append("source", Expressions.call(BuiltInMethod.AS_ENUMERABLE.method, list_));
        inputPhysType = outputPhysType;
    }
    // return Linq4j.asEnumerable(list);
    builder.add(Expressions.return_(null, source_));
    return implementor.result(inputPhysType, builder.toBlock());
}
Also used : WinAggResetContextImpl(org.apache.calcite.adapter.enumerable.impl.WinAggResetContextImpl) RexLiteral(org.apache.calcite.rex.RexLiteral) ArrayList(java.util.ArrayList) RelDataType(org.apache.calcite.rel.type.RelDataType) BlockStatement(org.apache.calcite.linq4j.tree.BlockStatement) Function(com.google.common.base.Function) SqlAggFunction(org.apache.calcite.sql.SqlAggFunction) BinaryExpression(org.apache.calcite.linq4j.tree.BinaryExpression) JavaTypeFactory(org.apache.calcite.adapter.java.JavaTypeFactory) RelDataTypeFactory(org.apache.calcite.rel.type.RelDataTypeFactory) ArrayList(java.util.ArrayList) ImmutableList(com.google.common.collect.ImmutableList) List(java.util.List) BlockBuilder(org.apache.calcite.linq4j.tree.BlockBuilder) DeclarationStatement(org.apache.calcite.linq4j.tree.DeclarationStatement) Statement(org.apache.calcite.linq4j.tree.Statement) DeclarationStatement(org.apache.calcite.linq4j.tree.DeclarationStatement) BlockStatement(org.apache.calcite.linq4j.tree.BlockStatement) AggregateCall(org.apache.calcite.rel.core.AggregateCall) BinaryExpression(org.apache.calcite.linq4j.tree.BinaryExpression) Expression(org.apache.calcite.linq4j.tree.Expression) ParameterExpression(org.apache.calcite.linq4j.tree.ParameterExpression) ParameterExpression(org.apache.calcite.linq4j.tree.ParameterExpression) RexInputRef(org.apache.calcite.rex.RexInputRef) RexNode(org.apache.calcite.rex.RexNode)

Aggregations

BlockBuilder (org.apache.calcite.linq4j.tree.BlockBuilder)4 BlockStatement (org.apache.calcite.linq4j.tree.BlockStatement)4 Statement (org.apache.calcite.linq4j.tree.Statement)4 Expression (org.apache.calcite.linq4j.tree.Expression)3 ArrayList (java.util.ArrayList)2 JavaTypeFactory (org.apache.calcite.adapter.java.JavaTypeFactory)2 ParameterExpression (org.apache.calcite.linq4j.tree.ParameterExpression)2 Function (com.google.common.base.Function)1 ImmutableList (com.google.common.collect.ImmutableList)1 List (java.util.List)1 PhysType (org.apache.calcite.adapter.enumerable.PhysType)1 RexToLixTranslator (org.apache.calcite.adapter.enumerable.RexToLixTranslator)1 WinAggResetContextImpl (org.apache.calcite.adapter.enumerable.impl.WinAggResetContextImpl)1 Enumerable (org.apache.calcite.linq4j.Enumerable)1 Function1 (org.apache.calcite.linq4j.function.Function1)1 BinaryExpression (org.apache.calcite.linq4j.tree.BinaryExpression)1 ConditionalStatement (org.apache.calcite.linq4j.tree.ConditionalStatement)1 ConstantExpression (org.apache.calcite.linq4j.tree.ConstantExpression)1 DeclarationStatement (org.apache.calcite.linq4j.tree.DeclarationStatement)1 GotoStatement (org.apache.calcite.linq4j.tree.GotoStatement)1