1908: new window function implementation
Project: http://git-wip-us.apache.org/repos/asf/drill/repo Commit: http://git-wip-us.apache.org/repos/asf/drill/commit/fb293ba5 Tree: http://git-wip-us.apache.org/repos/asf/drill/tree/fb293ba5 Diff: http://git-wip-us.apache.org/repos/asf/drill/diff/fb293ba5 Branch: refs/heads/master Commit: fb293ba520e25162c4ab8858ddba51b392878ae3 Parents: 4b58ac8 Author: adeneche <[email protected]> Authored: Tue Dec 30 10:15:05 2014 -0800 Committer: adeneche <[email protected]> Committed: Fri Mar 6 09:16:33 2015 -0800 ---------------------------------------------------------------------- .../common/logical/data/AbstractBuilder.java | 4 + .../drill/common/logical/data/Window.java | 10 +- contrib/data/pom.xml | 1 + contrib/data/window-test-data/pom.xml | 64 ++++ exec/java-exec/pom.xml | 6 + .../org/apache/drill/exec/ExecConstants.java | 3 + .../apache/drill/exec/opt/BasicOptimizer.java | 2 +- .../drill/exec/physical/config/WindowPOP.java | 10 +- .../exec/physical/impl/window/OverFinder.java | 53 +++ .../StreamingWindowFrameBatchCreator.java | 36 -- .../window/StreamingWindowFrameRecordBatch.java | 274 -------------- .../window/StreamingWindowFrameTemplate.java | 282 -------------- .../impl/window/StreamingWindowFramer.java | 44 --- .../impl/window/WindowFrameBatchCreator.java | 37 ++ .../impl/window/WindowFrameRecordBatch.java | 354 +++++++++++++++++ .../impl/window/WindowFrameTemplate.java | 379 +++++++++++++++++++ .../exec/physical/impl/window/WindowFramer.java | 59 +++ .../exec/planner/logical/DrillRuleSets.java | 7 +- .../planner/physical/StreamingWindowPrel.java | 136 ------- .../planner/physical/StreamingWindowPrule.java | 133 ------- .../drill/exec/planner/physical/WindowPrel.java | 146 +++++++ .../exec/planner/physical/WindowPrule.java | 138 +++++++ .../planner/sql/handlers/DefaultSqlHandler.java | 9 + .../server/options/SystemOptionManager.java | 3 +- .../physical/impl/window/TestWindowFrame.java | 262 +++++-------- .../drill/exec/sql/TestWindowFunctions.java | 31 -- 26 files changed, 1363 insertions(+), 1120 deletions(-) ---------------------------------------------------------------------- http://git-wip-us.apache.org/repos/asf/drill/blob/fb293ba5/common/src/main/java/org/apache/drill/common/logical/data/AbstractBuilder.java ---------------------------------------------------------------------- diff --git a/common/src/main/java/org/apache/drill/common/logical/data/AbstractBuilder.java b/common/src/main/java/org/apache/drill/common/logical/data/AbstractBuilder.java index 28424a5..b178cd9 100644 --- a/common/src/main/java/org/apache/drill/common/logical/data/AbstractBuilder.java +++ b/common/src/main/java/org/apache/drill/common/logical/data/AbstractBuilder.java @@ -39,4 +39,8 @@ public abstract class AbstractBuilder<T extends LogicalOperator> { return exprs.toArray(new NamedExpression[exprs.size()]); } + protected Order.Ordering[] aO(List<Order.Ordering> orderings) { + return orderings.toArray(new Order.Ordering[orderings.size()]); + } + } http://git-wip-us.apache.org/repos/asf/drill/blob/fb293ba5/common/src/main/java/org/apache/drill/common/logical/data/Window.java ---------------------------------------------------------------------- diff --git a/common/src/main/java/org/apache/drill/common/logical/data/Window.java b/common/src/main/java/org/apache/drill/common/logical/data/Window.java index 6dba77c..0f550dc 100644 --- a/common/src/main/java/org/apache/drill/common/logical/data/Window.java +++ b/common/src/main/java/org/apache/drill/common/logical/data/Window.java @@ -38,6 +38,7 @@ import static com.google.common.base.Preconditions.checkState; public class Window extends SingleInputOperator { private final NamedExpression[] withins; private final NamedExpression[] aggregations; + private final Order.Ordering[] orderings; private final long start; private final long end; @@ -45,6 +46,7 @@ public class Window extends SingleInputOperator { @JsonCreator public Window(@JsonProperty("withins") NamedExpression[] withins, @JsonProperty("aggregations") NamedExpression[] aggregations, + @JsonProperty("orderings") Order.Ordering[] orderings, @JsonProperty("start") Long start, @JsonProperty("end") Long end) { super(); @@ -52,6 +54,7 @@ public class Window extends SingleInputOperator { this.start = start == null ? Long.MIN_VALUE : start; this.end = end == null ? Long.MIN_VALUE : end; this.aggregations = aggregations; + this.orderings = orderings; } public NamedExpression[] getWithins() { @@ -70,6 +73,10 @@ public class Window extends SingleInputOperator { return aggregations; } + public Order.Ordering[] getOrderings() { + return orderings; + } + @Override public <T, X, E extends Throwable> T accept(LogicalVisitor<T, X, E> logicalVisitor, X value) throws E { return logicalVisitor.visitWindow(this, value); @@ -99,9 +106,10 @@ public class Window extends SingleInputOperator { } public Window internalBuild() { + //TODO withins can actually be empty: over(), over(order by <expression>), ... checkState(!withins.isEmpty(), "Withins in window must not be empty."); checkState(!aggregations.isEmpty(), "Aggregations in window must not be empty."); - return new Window(aN(withins), aN(aggregations), start, end); + return new Window(aN(withins), aN(aggregations), aO(orderings), start, end); } public Builder addOrdering(Order.Ordering ordering) { http://git-wip-us.apache.org/repos/asf/drill/blob/fb293ba5/contrib/data/pom.xml ---------------------------------------------------------------------- diff --git a/contrib/data/pom.xml b/contrib/data/pom.xml index 86075f2..3f6b748 100644 --- a/contrib/data/pom.xml +++ b/contrib/data/pom.xml @@ -33,5 +33,6 @@ <modules> <module>tpch-sample-data</module> + <module>window-test-data</module> </modules> </project> http://git-wip-us.apache.org/repos/asf/drill/blob/fb293ba5/contrib/data/window-test-data/pom.xml ---------------------------------------------------------------------- diff --git a/contrib/data/window-test-data/pom.xml b/contrib/data/window-test-data/pom.xml new file mode 100644 index 0000000..357a5a9 --- /dev/null +++ b/contrib/data/window-test-data/pom.xml @@ -0,0 +1,64 @@ +<?xml version="1.0"?> +<!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor + license agreements. See the NOTICE file distributed with this work for additional + information regarding copyright ownership. The ASF licenses this file to + You under the Apache License, Version 2.0 (the "License"); you may not use + this file except in compliance with the License. You may obtain a copy of + the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required + by applicable law or agreed to in writing, software distributed under the + License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS + OF ANY KIND, either express or implied. See the License for the specific + language governing permissions and limitations under the License. --> +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + <parent> + <artifactId>drill-contrib-data-parent</artifactId> + <groupId>org.apache.drill.contrib.data</groupId> + <version>0.8.0-SNAPSHOT</version> + </parent> + + <artifactId>window-test-data</artifactId> + <name>contrib/data/window-test-data</name> + <packaging>jar</packaging> + + <dependencies> + </dependencies> + <build> + <plugins> + <plugin> + <groupId>com.googlecode.maven-download-plugin</groupId> + <artifactId>download-maven-plugin</artifactId> + <version>1.2.0</version> + <executions> + <execution> + <id>install-tgz</id> + <phase>prepare-package</phase> + <goals> + <goal>wget</goal> + </goals> + <configuration> + <url>https://s3-us-west-2.amazonaws.com/denbucket/window_test_data_0.1.tgz</url> + <outputFileName>window.tgz</outputFileName> + <unpack>true</unpack> + <outputDirectory>${project.build.directory}/classes/window</outputDirectory> + </configuration> + </execution> + </executions> + </plugin> + </plugins> + </build> + <pluginRepositories> + <pluginRepository> + <id>sonatype-public-repository</id> + <url>https://oss.sonatype.org/content/groups/public</url> + <snapshots> + <enabled>true</enabled> + </snapshots> + <releases> + <enabled>true</enabled> + </releases> + </pluginRepository> + </pluginRepositories> + +</project> http://git-wip-us.apache.org/repos/asf/drill/blob/fb293ba5/exec/java-exec/pom.xml ---------------------------------------------------------------------- diff --git a/exec/java-exec/pom.xml b/exec/java-exec/pom.xml index 28eca2b..a7b6a67 100644 --- a/exec/java-exec/pom.xml +++ b/exec/java-exec/pom.xml @@ -38,6 +38,12 @@ <version>${project.version}</version> <scope>test</scope> </dependency> + <dependency> + <groupId>org.apache.drill.contrib.data</groupId> + <artifactId>window-test-data</artifactId> + <version>${project.version}</version> + <scope>test</scope> + </dependency> <!-- <dependency> --> <!-- <groupId>org.ow2.asm</groupId> --> <!-- <artifactId>asm-commons</artifactId> --> http://git-wip-us.apache.org/repos/asf/drill/blob/fb293ba5/exec/java-exec/src/main/java/org/apache/drill/exec/ExecConstants.java ---------------------------------------------------------------------- diff --git a/exec/java-exec/src/main/java/org/apache/drill/exec/ExecConstants.java b/exec/java-exec/src/main/java/org/apache/drill/exec/ExecConstants.java index 5efcce8..40fe588 100644 --- a/exec/java-exec/src/main/java/org/apache/drill/exec/ExecConstants.java +++ b/exec/java-exec/src/main/java/org/apache/drill/exec/ExecConstants.java @@ -197,4 +197,7 @@ public interface ExecConstants { public static final String MAX_LOADING_CACHE_SIZE_CONFIG = "drill.exec.compile.cache_max_size"; public static final String DRILL_SYS_FILE_SUFFIX = ".sys.drill"; + + public static final String ENABLE_WINDOW_FUNCTIONS = "window.enable"; + public static final OptionValidator ENABLE_WINDOW_FUNCTIONS_VALIDATOR = new BooleanValidator(ENABLE_WINDOW_FUNCTIONS, false); } http://git-wip-us.apache.org/repos/asf/drill/blob/fb293ba5/exec/java-exec/src/main/java/org/apache/drill/exec/opt/BasicOptimizer.java ---------------------------------------------------------------------- diff --git a/exec/java-exec/src/main/java/org/apache/drill/exec/opt/BasicOptimizer.java b/exec/java-exec/src/main/java/org/apache/drill/exec/opt/BasicOptimizer.java index 5288f5d..9f89f24 100644 --- a/exec/java-exec/src/main/java/org/apache/drill/exec/opt/BasicOptimizer.java +++ b/exec/java-exec/src/main/java/org/apache/drill/exec/opt/BasicOptimizer.java @@ -194,7 +194,7 @@ public class BasicOptimizer extends Optimizer{ input = new Sort(input, ods, false); - return new WindowPOP(input, window.getWithins(), window.getAggregations(), window.getStart(), window.getEnd()); + return new WindowPOP(input, window.getWithins(), window.getAggregations(), window.getOrderings(), window.getStart(), window.getEnd()); } @Override http://git-wip-us.apache.org/repos/asf/drill/blob/fb293ba5/exec/java-exec/src/main/java/org/apache/drill/exec/physical/config/WindowPOP.java ---------------------------------------------------------------------- diff --git a/exec/java-exec/src/main/java/org/apache/drill/exec/physical/config/WindowPOP.java b/exec/java-exec/src/main/java/org/apache/drill/exec/physical/config/WindowPOP.java index 17738ee..5926a06 100644 --- a/exec/java-exec/src/main/java/org/apache/drill/exec/physical/config/WindowPOP.java +++ b/exec/java-exec/src/main/java/org/apache/drill/exec/physical/config/WindowPOP.java @@ -21,6 +21,7 @@ package org.apache.drill.exec.physical.config; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonTypeName; import org.apache.drill.common.logical.data.NamedExpression; +import org.apache.drill.common.logical.data.Order; import org.apache.drill.exec.physical.base.AbstractSingle; import org.apache.drill.exec.physical.base.PhysicalOperator; import org.apache.drill.exec.physical.base.PhysicalVisitor; @@ -31,24 +32,27 @@ public class WindowPOP extends AbstractSingle { private final NamedExpression[] withins; private final NamedExpression[] aggregations; + private final Order.Ordering[] orderings; private final long start; private final long end; public WindowPOP(@JsonProperty("child") PhysicalOperator child, @JsonProperty("within") NamedExpression[] withins, @JsonProperty("aggregations") NamedExpression[] aggregations, + @JsonProperty("orderings") Order.Ordering[] orderings, @JsonProperty("start") long start, @JsonProperty("end") long end) { super(child); this.withins = withins; this.aggregations = aggregations; + this.orderings = orderings; this.start = start; this.end = end; } @Override protected PhysicalOperator getNewWithChild(PhysicalOperator child) { - return new WindowPOP(child, withins, aggregations, start, end); + return new WindowPOP(child, withins, aggregations, orderings, start, end); } @Override @@ -76,4 +80,8 @@ public class WindowPOP extends AbstractSingle { public NamedExpression[] getWithins() { return withins; } + + public Order.Ordering[] getOrderings() { + return orderings; + } } http://git-wip-us.apache.org/repos/asf/drill/blob/fb293ba5/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/window/OverFinder.java ---------------------------------------------------------------------- diff --git a/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/window/OverFinder.java b/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/window/OverFinder.java new file mode 100644 index 0000000..40e5920 --- /dev/null +++ b/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/window/OverFinder.java @@ -0,0 +1,53 @@ +/** + * 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.physical.impl.window; + +import org.eigenbase.sql.SqlCall; +import org.eigenbase.sql.SqlKind; +import org.eigenbase.sql.SqlNode; +import org.eigenbase.sql.SqlOperator; +import org.eigenbase.sql.util.SqlBasicVisitor; +import org.eigenbase.util.Util; + +/** + * Visitor which looks for an over clause inside a tree of {@link + * SqlNode} objects. + */ +public class OverFinder extends SqlBasicVisitor<Void> { + + public boolean findOver(SqlNode node) { + try { + node.accept(this); + return false; + } catch (Util.FoundOne e) { + Util.swallow(e, null); + return true; + } + } + + @Override + public Void visit(SqlCall call) { + final SqlOperator operator = call.getOperator(); + + if (operator.getKind().equals(SqlKind.OVER)) { + throw new Util.FoundOne(call); + } + + return super.visit(call); + } +} \ No newline at end of file http://git-wip-us.apache.org/repos/asf/drill/blob/fb293ba5/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/window/StreamingWindowFrameBatchCreator.java ---------------------------------------------------------------------- diff --git a/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/window/StreamingWindowFrameBatchCreator.java b/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/window/StreamingWindowFrameBatchCreator.java deleted file mode 100644 index 9b8929f..0000000 --- a/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/window/StreamingWindowFrameBatchCreator.java +++ /dev/null @@ -1,36 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.drill.exec.physical.impl.window; - -import com.google.common.collect.Iterables; -import org.apache.drill.common.exceptions.ExecutionSetupException; -import org.apache.drill.exec.ops.FragmentContext; -import org.apache.drill.exec.physical.config.WindowPOP; -import org.apache.drill.exec.physical.impl.BatchCreator; -import org.apache.drill.exec.record.RecordBatch; - -import java.util.List; - -public class StreamingWindowFrameBatchCreator implements BatchCreator<WindowPOP> { - - @Override - public RecordBatch getBatch(FragmentContext context, WindowPOP config, List<RecordBatch> children) throws ExecutionSetupException { - return new StreamingWindowFrameRecordBatch(config, context, Iterables.getOnlyElement(children)); - } -} http://git-wip-us.apache.org/repos/asf/drill/blob/fb293ba5/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/window/StreamingWindowFrameRecordBatch.java ---------------------------------------------------------------------- diff --git a/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/window/StreamingWindowFrameRecordBatch.java b/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/window/StreamingWindowFrameRecordBatch.java deleted file mode 100644 index 87209eb..0000000 --- a/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/window/StreamingWindowFrameRecordBatch.java +++ /dev/null @@ -1,274 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.drill.exec.physical.impl.window; - -import com.google.common.collect.Lists; -import com.sun.codemodel.JExpr; -import com.sun.codemodel.JVar; -import org.apache.drill.common.expression.ErrorCollector; -import org.apache.drill.common.expression.ErrorCollectorImpl; -import org.apache.drill.common.expression.LogicalExpression; -import org.apache.drill.common.logical.data.NamedExpression; -import org.apache.drill.exec.compile.sig.GeneratorMapping; -import org.apache.drill.exec.compile.sig.MappingSet; -import org.apache.drill.exec.exception.ClassTransformationException; -import org.apache.drill.exec.exception.SchemaChangeException; -import org.apache.drill.exec.expr.ClassGenerator; -import org.apache.drill.exec.expr.CodeGenerator; -import org.apache.drill.exec.expr.ExpressionTreeMaterializer; -import org.apache.drill.exec.expr.TypeHelper; -import org.apache.drill.exec.expr.ValueVectorReadExpression; -import org.apache.drill.exec.expr.ValueVectorWriteExpression; -import org.apache.drill.exec.expr.fn.FunctionGenerationHelper; -import org.apache.drill.exec.memory.OutOfMemoryException; -import org.apache.drill.exec.ops.FragmentContext; -import org.apache.drill.exec.physical.config.WindowPOP; -import org.apache.drill.exec.record.AbstractSingleRecordBatch; -import org.apache.drill.exec.record.BatchSchema; -import org.apache.drill.exec.record.MaterializedField; -import org.apache.drill.exec.record.RecordBatch; -import org.apache.drill.exec.record.TypedFieldId; -import org.apache.drill.exec.record.VectorWrapper; -import org.apache.drill.exec.record.selection.SelectionVector2; -import org.apache.drill.exec.record.selection.SelectionVector4; -import org.apache.drill.exec.vector.ValueVector; - -import java.io.IOException; -import java.util.List; - -public class StreamingWindowFrameRecordBatch extends AbstractSingleRecordBatch<WindowPOP> { - private StreamingWindowFramer framer; - - public StreamingWindowFrameRecordBatch(WindowPOP popConfig, FragmentContext context, RecordBatch incoming) throws OutOfMemoryException { - super(popConfig, context, incoming); - } - - @Override - protected boolean setupNewSchema() throws SchemaChangeException { - container.clear(); - - try { - this.framer = createFramer(); - } catch (ClassTransformationException | IOException ex) { - throw new SchemaChangeException("Failed to create framer: " + ex); - } - if (container.isSchemaChanged()) { - container.buildSchema(BatchSchema.SelectionVectorMode.NONE); - return true; - } - return false; - } - - private void getIndex(ClassGenerator<StreamingWindowFramer> g) { - switch (incoming.getSchema().getSelectionVectorMode()) { - case FOUR_BYTE: { - JVar var = g.declareClassField("sv4_", g.getModel()._ref(SelectionVector4.class)); - g.getBlock("setupInterior").assign(var, JExpr.direct("incoming").invoke("getSelectionVector4")); - g.getBlock("getVectorIndex")._return(var.invoke("get").arg(JExpr.direct("recordIndex"))); - return; - } - case NONE: { - g.getBlock("getVectorIndex")._return(JExpr.direct("recordIndex")); - return; - } - case TWO_BYTE: { - JVar var = g.declareClassField("sv2_", g.getModel()._ref(SelectionVector2.class)); - g.getBlock("setupInterior").assign(var, JExpr.direct("incoming").invoke("getSelectionVector2")); - g.getBlock("getVectorIndex")._return(var.invoke("get").arg(JExpr.direct("recordIndex"))); - return; - } - - default: - throw new IllegalStateException(); - } - } - - private StreamingWindowFramer createFramer() throws SchemaChangeException, IOException, ClassTransformationException { - int configLength = popConfig.getAggregations().length; - List<LogicalExpression> valueExprs = Lists.newArrayList(); - LogicalExpression[] keyExprs = new LogicalExpression[popConfig.getWithins().length]; - - ErrorCollector collector = new ErrorCollectorImpl(); - - for (int i = 0; i < configLength; i++) { - NamedExpression ne = popConfig.getAggregations()[i]; - final LogicalExpression expr = ExpressionTreeMaterializer.materialize(ne.getExpr(), incoming, collector, context.getFunctionRegistry()); - if (expr == null) { - continue; - } - - final MaterializedField outputField = MaterializedField.create(ne.getRef(), expr.getMajorType()); - container.addOrGet(outputField); - TypedFieldId id = container.getValueVectorId(outputField.getPath()); - assert id != null : "Got null TypedFieldId"; - valueExprs.add(new ValueVectorWriteExpression(id, expr, true)); - } - - int j = 0; - LogicalExpression[] windowExprs = new LogicalExpression[incoming.getSchema().getFieldCount()]; - // TODO: Should transfer all existing columns instead of copy. Currently this is not easily doable because - // we are not processing one entire batch in one iteration, so cannot simply transfer. - for (VectorWrapper wrapper : incoming) { - ValueVector vv = wrapper.isHyper() ? wrapper.getValueVectors()[0] : wrapper.getValueVector(); - container.addOrGet(vv.getField()); - TypedFieldId id = container.getValueVectorId(vv.getField().getPath()); - final LogicalExpression expr = ExpressionTreeMaterializer.materialize( - new ValueVectorReadExpression(new TypedFieldId(vv.getField().getType(), wrapper.isHyper(), j)), - incoming, - collector, - context.getFunctionRegistry()); - windowExprs[j] = new ValueVectorWriteExpression(id, expr, true); - j++; - } - - for (int i = 0; i < keyExprs.length; i++) { - NamedExpression ne = popConfig.getWithins()[i]; - - final LogicalExpression expr = ExpressionTreeMaterializer.materialize(ne.getExpr(), incoming, collector, context.getFunctionRegistry()); - if (expr == null) { - continue; - } - - keyExprs[i] = expr; - } - - if (collector.hasErrors()) { - throw new SchemaChangeException("Failure while materializing expression. " + collector.toErrorString()); - } - - final ClassGenerator<StreamingWindowFramer> cg = CodeGenerator.getRoot(StreamingWindowFramer.TEMPLATE_DEFINITION, context.getFunctionRegistry()); - setupIsSame(cg, keyExprs); - setupIsSameFromBatch(cg, keyExprs); - addRecordValues(cg, valueExprs.toArray(new LogicalExpression[valueExprs.size()])); - outputWindowValues(cg, windowExprs); - - cg.getBlock("resetValues")._return(JExpr.TRUE); - - getIndex(cg); - StreamingWindowFramer agg = context.getImplementationClass(cg); - agg.setup( - context, - incoming, - this, - StreamingWindowFrameTemplate.UNBOUNDED, StreamingWindowFrameTemplate.CURRENT_ROW - ); - return agg; - } - - private final GeneratorMapping IS_SAME_PREV_INTERNAL_BATCH_READ = GeneratorMapping.create("isSameFromBatch", "isSameFromBatch", null, null); // the internal batch changes each time so we need to redo setup. - private final GeneratorMapping IS_SAME_PREV = GeneratorMapping.create("setupInterior", "isSameFromBatch", null, null); - private final MappingSet ISA_B1 = new MappingSet("b1Index", null, "b1", null, IS_SAME_PREV_INTERNAL_BATCH_READ, IS_SAME_PREV_INTERNAL_BATCH_READ); - private final MappingSet ISA_B2 = new MappingSet("b2Index", null, "incoming", null, IS_SAME_PREV, IS_SAME_PREV); - - private void setupIsSameFromBatch(ClassGenerator<StreamingWindowFramer> cg, LogicalExpression[] keyExprs) { - cg.setMappingSet(ISA_B1); - for (LogicalExpression expr : keyExprs) { - // first, we rewrite the evaluation stack for each side of the comparison. - cg.setMappingSet(ISA_B1); - ClassGenerator.HoldingContainer first = cg.addExpr(expr, false); - cg.setMappingSet(ISA_B2); - ClassGenerator.HoldingContainer second = cg.addExpr(expr, false); - - LogicalExpression fh = - FunctionGenerationHelper - .getOrderingComparatorNullsHigh(first, second, context.getFunctionRegistry()); - ClassGenerator.HoldingContainer out = cg.addExpr(fh, false); - cg.getEvalBlock()._if(out.getValue().ne(JExpr.lit(0)))._then()._return(JExpr.FALSE); - } - cg.getEvalBlock()._return(JExpr.TRUE); - } - - private final GeneratorMapping IS_SAME = GeneratorMapping.create("setupInterior", "isSame", null, null); - private final MappingSet IS_SAME_I1 = new MappingSet("index1", null, IS_SAME, IS_SAME); - private final MappingSet IS_SAME_I2 = new MappingSet("index2", null, IS_SAME, IS_SAME); - - private void setupIsSame(ClassGenerator<StreamingWindowFramer> cg, LogicalExpression[] keyExprs) { - cg.setMappingSet(IS_SAME_I1); - for (LogicalExpression expr : keyExprs) { - // first, we rewrite the evaluation stack for each side of the comparison. - cg.setMappingSet(IS_SAME_I1); - ClassGenerator.HoldingContainer first = cg.addExpr(expr, false); - cg.setMappingSet(IS_SAME_I2); - ClassGenerator.HoldingContainer second = cg.addExpr(expr, false); - - LogicalExpression fh = - FunctionGenerationHelper - .getOrderingComparatorNullsHigh(first, second, context.getFunctionRegistry()); - ClassGenerator.HoldingContainer out = cg.addExpr(fh, false); - cg.getEvalBlock()._if(out.getValue().ne(JExpr.lit(0)))._then()._return(JExpr.FALSE); - } - cg.getEvalBlock()._return(JExpr.TRUE); - } - - private final GeneratorMapping EVAL_INSIDE = GeneratorMapping.create("setupInterior", "addRecord", null, null); - private final GeneratorMapping EVAL_OUTSIDE = GeneratorMapping.create("setupInterior", "outputRecordValues", "resetValues", "cleanup"); - private final MappingSet EVAL = new MappingSet("index", "outIndex", EVAL_INSIDE, EVAL_OUTSIDE, EVAL_INSIDE); - - private void addRecordValues(ClassGenerator<StreamingWindowFramer> cg, LogicalExpression[] valueExprs) { - cg.setMappingSet(EVAL); - for (LogicalExpression ex : valueExprs) { - ClassGenerator.HoldingContainer hc = cg.addExpr(ex); - } - } - - private final GeneratorMapping OUTPUT_WINDOW_VALUES = GeneratorMapping.create("setupInterior", "outputWindowValues", null, null); - private final MappingSet WINDOW_VALUES = new MappingSet("inIndex" /* read index */, "outIndex" /* write index */, "incoming", "outgoing", OUTPUT_WINDOW_VALUES, OUTPUT_WINDOW_VALUES); - - private void outputWindowValues(ClassGenerator<StreamingWindowFramer> cg, LogicalExpression[] valueExprs) { - cg.setMappingSet(WINDOW_VALUES); - for (int i = 0; i < valueExprs.length; i++) { - ClassGenerator.HoldingContainer hc = cg.addExpr(valueExprs[i]); - } - } - - @Override - protected IterOutcome doWork() { - StreamingWindowFramer.AggOutcome out = framer.doWork(); - - while (out == StreamingWindowFramer.AggOutcome.UPDATE_AGGREGATOR) { - framer.cleanup(); - framer = null; - try { - setupNewSchema(); - } catch (SchemaChangeException e) { - return IterOutcome.STOP; - } - out = framer.doWork(); - } - - if (out == StreamingWindowFramer.AggOutcome.RETURN_AND_COMPLETE) { - state = BatchState.DONE; - } - - return framer.getOutcome(); - } - - @Override - public int getRecordCount() { - return framer.getOutputCount(); - } - - @Override - public void cleanup() { - if (framer != null) { - framer.cleanup(); - } - super.cleanup(); - } -} http://git-wip-us.apache.org/repos/asf/drill/blob/fb293ba5/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/window/StreamingWindowFrameTemplate.java ---------------------------------------------------------------------- diff --git a/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/window/StreamingWindowFrameTemplate.java b/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/window/StreamingWindowFrameTemplate.java deleted file mode 100644 index e2c7e9e..0000000 --- a/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/window/StreamingWindowFrameTemplate.java +++ /dev/null @@ -1,282 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.drill.exec.physical.impl.window; - -import org.apache.drill.exec.exception.SchemaChangeException; -import org.apache.drill.exec.ops.FragmentContext; -import org.apache.drill.exec.physical.impl.aggregate.InternalBatch; -import org.apache.drill.exec.record.RecordBatch; -import org.apache.drill.exec.record.VectorWrapper; - -import javax.inject.Named; - -public abstract class StreamingWindowFrameTemplate implements StreamingWindowFramer { - private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(StreamingWindowFramer.class); - private static final String TOO_BIG_ERROR = "Couldn't add value to an empty batch. This likely means that a single value is too long for a varlen field."; - private static final boolean EXTRA_DEBUG = false; - public static final int UNBOUNDED = -1; - public static final int CURRENT_ROW = 0; - private boolean first = true; - private int previousIndex = 0; - private int underlyingIndex = -1; - private int currentIndex; - private boolean pendingOutput = false; - private RecordBatch.IterOutcome outcome; - private int outputCount = 0; - private RecordBatch incoming; - private RecordBatch outgoing; - private FragmentContext context; - private InternalBatch previousBatch = null; - private int precedingConfig = UNBOUNDED; - private int followingConfig = CURRENT_ROW; - - - @Override - public void setup(FragmentContext context, - RecordBatch incoming, - RecordBatch outgoing, - int precedingConfig, - int followingConfig) throws SchemaChangeException { - this.context = context; - this.incoming = incoming; - this.outgoing = outgoing; - this.precedingConfig = precedingConfig; - this.followingConfig = followingConfig; - - setupInterior(incoming, outgoing); - } - - - private void allocateOutgoing() { - for (VectorWrapper<?> w : outgoing){ - w.getValueVector().allocateNew(); - } - } - - @Override - public RecordBatch.IterOutcome getOutcome() { - return outcome; - } - - @Override - public int getOutputCount() { - return outputCount; - } - - private AggOutcome tooBigFailure() { - context.fail(new Exception(TOO_BIG_ERROR)); - this.outcome = RecordBatch.IterOutcome.STOP; - return AggOutcome.RETURN_OUTCOME; - } - - @Override - public AggOutcome doWork() { - // if we're in the first state, allocate outgoing. - try { - if (first) { - allocateOutgoing(); - } - - // setup for new output and pick any remainder. - if (pendingOutput) { - allocateOutgoing(); - pendingOutput = false; - outputToBatch(previousIndex); - } - - boolean recordsAdded = false; - - outside: while (true) { - if (EXTRA_DEBUG) { - logger.trace("Looping from underlying index {}, previous {}, current {}", underlyingIndex, previousIndex, currentIndex); - logger.debug("Processing {} records in window framer", incoming.getRecordCount()); - } - // loop through existing records, adding as necessary. - while(incIndex()) { - if (previousBatch != null) { - boolean isSameFromBatch = isSameFromBatch(previousIndex, previousBatch, currentIndex); - if (EXTRA_DEBUG) { - logger.trace("Same as previous batch: {}, previous index {}, current index {}", isSameFromBatch, previousIndex, currentIndex); - } - - if(!isSameFromBatch) { - resetValues(); - } - previousBatch.clear(); - previousBatch = null; - } else if (!isSame(previousIndex, currentIndex)) { - resetValues(); - } - - addRecord(currentIndex); - - if (!outputToBatch(currentIndex)) { - if (outputCount == 0) { - return tooBigFailure(); - } - - // mark the pending output but move forward for the next cycle. - pendingOutput = true; - incIndex(); - return setOkAndReturn(); - } - - recordsAdded = true; - } - - if (EXTRA_DEBUG) { - logger.debug("Exit Loop from underlying index {}, previous {}, current {}", underlyingIndex, previousIndex, currentIndex); - } - - previousBatch = new InternalBatch(incoming); - - while (true) { - RecordBatch.IterOutcome out = incoming.next(); - switch (out) { - case NONE: - outcome = innerOutcome(out, recordsAdded); - if (EXTRA_DEBUG) { - logger.trace("Received IterOutcome of {}, assigning {} outcome", out, outcome); - } - return AggOutcome.RETURN_AND_COMPLETE; - case NOT_YET: - outcome = innerOutcome(out, recordsAdded); - if (EXTRA_DEBUG) { - logger.trace("Received IterOutcome of {}, assigning {} outcome", out, outcome); - } - return AggOutcome.RETURN_OUTCOME; - - case OK_NEW_SCHEMA: - if (EXTRA_DEBUG) { - logger.trace("Received new schema. Batch has {} records.", incoming.getRecordCount()); - } - resetIndex(); - return AggOutcome.UPDATE_AGGREGATOR; - - case OK: - if (EXTRA_DEBUG) { - logger.trace("Received OK with {} records.", incoming.getRecordCount()); - } - resetIndex(); - if (incoming.getRecordCount() == 0) { - continue; - } else { - continue outside; - } - case STOP: - default: - outcome = out; - if (EXTRA_DEBUG) { - logger.trace("Stop received.", incoming.getRecordCount()); - } - return AggOutcome.RETURN_OUTCOME; - } - } - } - } finally { - first = false; - } - } - - private RecordBatch.IterOutcome innerOutcome(RecordBatch.IterOutcome innerOutcome, boolean newRecordsAdded) { - if(newRecordsAdded) { - setOkAndReturn(); - return outcome; - } - return innerOutcome; - } - - - private final boolean incIndex() { - underlyingIndex++; - - if(currentIndex != -1) { - previousIndex = currentIndex; - } - - if (underlyingIndex >= incoming.getRecordCount()) { - return false; - } - - currentIndex = getVectorIndex(underlyingIndex); - return true; - } - - private final void resetIndex() { - underlyingIndex = -1; - currentIndex = getVectorIndex(underlyingIndex); - if (EXTRA_DEBUG) { - logger.trace("Reset new indexes: underlying {}, previous {}, current {}", underlyingIndex, previousIndex, currentIndex); - } - } - - private final AggOutcome setOkAndReturn() { - if (first) { - this.outcome = RecordBatch.IterOutcome.OK_NEW_SCHEMA; - } else { - this.outcome = RecordBatch.IterOutcome.OK; - } - - if (EXTRA_DEBUG) { - logger.debug("Setting output count {}", outputCount); - } - for (VectorWrapper<?> v : outgoing) { - v.getValueVector().getMutator().setValueCount(outputCount); - } - return AggOutcome.RETURN_OUTCOME; - } - - private final boolean outputToBatch(int inIndex) { - outputRecordValues(outputCount); - outputWindowValues(inIndex, outputCount); - - return true; - } - - @Override - public void cleanup() { - if(previousBatch != null) { - previousBatch.clear(); - previousBatch = null; - } - } - - public abstract void setupInterior(@Named("incoming") RecordBatch incoming, @Named("outgoing") RecordBatch outgoing) throws SchemaChangeException; - - /** - * Compares withins from two indexes in the same batch - * @param index1 First record index - * @param index2 Second record index - * @return does within value match - */ - public abstract boolean isSame(@Named("index1") int index1, @Named("index2") int index2); - /** - * Compares withins from one index of given batch (typically previous completed batch), and one index from current batch - * @param b1Index First record index - * @param index2 Second record index - * @return does within value match - */ - public abstract boolean isSameFromBatch(@Named("b1Index") int b1Index, @Named("b1") InternalBatch b1, @Named("b2Index") int index2); - public abstract void addRecord(@Named("index") int index); - public abstract void outputRecordValues(@Named("outIndex") int outIndex); - public abstract void outputWindowValues(@Named("inIndex") int inIndex, @Named("outIndex") int outIndex); - public abstract int getVectorIndex(@Named("recordIndex") int recordIndex); - - public abstract boolean resetValues(); -} http://git-wip-us.apache.org/repos/asf/drill/blob/fb293ba5/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/window/StreamingWindowFramer.java ---------------------------------------------------------------------- diff --git a/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/window/StreamingWindowFramer.java b/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/window/StreamingWindowFramer.java deleted file mode 100644 index 9588cef..0000000 --- a/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/window/StreamingWindowFramer.java +++ /dev/null @@ -1,44 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.drill.exec.physical.impl.window; - -import org.apache.drill.exec.compile.TemplateClassDefinition; -import org.apache.drill.exec.exception.SchemaChangeException; -import org.apache.drill.exec.ops.FragmentContext; -import org.apache.drill.exec.record.RecordBatch; - -public interface StreamingWindowFramer { - public static TemplateClassDefinition<StreamingWindowFramer> TEMPLATE_DEFINITION = new TemplateClassDefinition<>(StreamingWindowFramer.class, StreamingWindowFrameTemplate.class); - - - public static enum AggOutcome { - RETURN_OUTCOME, UPDATE_AGGREGATOR, RETURN_AND_COMPLETE; - } - - public abstract void setup(FragmentContext context, RecordBatch incoming, RecordBatch outgoing, - int precedingConfig, int followingConfig) throws SchemaChangeException; - - public abstract RecordBatch.IterOutcome getOutcome(); - - public abstract int getOutputCount(); - - public abstract AggOutcome doWork(); - - public abstract void cleanup(); -} http://git-wip-us.apache.org/repos/asf/drill/blob/fb293ba5/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/window/WindowFrameBatchCreator.java ---------------------------------------------------------------------- diff --git a/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/window/WindowFrameBatchCreator.java b/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/window/WindowFrameBatchCreator.java new file mode 100644 index 0000000..285e2cd --- /dev/null +++ b/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/window/WindowFrameBatchCreator.java @@ -0,0 +1,37 @@ +/** + * 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.physical.impl.window; + +import com.google.common.base.Preconditions; +import org.apache.drill.common.exceptions.ExecutionSetupException; +import org.apache.drill.exec.ops.FragmentContext; +import org.apache.drill.exec.physical.config.WindowPOP; +import org.apache.drill.exec.physical.impl.BatchCreator; +import org.apache.drill.exec.record.RecordBatch; + +import java.util.List; + +public class WindowFrameBatchCreator implements BatchCreator<WindowPOP> { + + @Override + public RecordBatch getBatch(FragmentContext context, WindowPOP config, List<RecordBatch> children) throws ExecutionSetupException { + Preconditions.checkArgument(children.size() == 1); + return new WindowFrameRecordBatch(config, context, children.iterator().next()); + } +} http://git-wip-us.apache.org/repos/asf/drill/blob/fb293ba5/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/window/WindowFrameRecordBatch.java ---------------------------------------------------------------------- diff --git a/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/window/WindowFrameRecordBatch.java b/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/window/WindowFrameRecordBatch.java new file mode 100644 index 0000000..bc86390 --- /dev/null +++ b/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/window/WindowFrameRecordBatch.java @@ -0,0 +1,354 @@ +/** + * 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.physical.impl.window; + +import com.google.common.collect.Lists; +import com.sun.codemodel.JExpr; +import org.apache.drill.common.exceptions.DrillException; +import org.apache.drill.common.expression.ErrorCollector; +import org.apache.drill.common.expression.ErrorCollectorImpl; +import org.apache.drill.common.expression.LogicalExpression; +import org.apache.drill.common.logical.data.NamedExpression; +import org.apache.drill.common.logical.data.Order; +import org.apache.drill.exec.compile.sig.GeneratorMapping; +import org.apache.drill.exec.compile.sig.MappingSet; +import org.apache.drill.exec.exception.ClassTransformationException; +import org.apache.drill.exec.exception.SchemaChangeException; +import org.apache.drill.exec.expr.ClassGenerator; +import org.apache.drill.exec.expr.CodeGenerator; +import org.apache.drill.exec.expr.ExpressionTreeMaterializer; +import org.apache.drill.exec.expr.ValueVectorReadExpression; +import org.apache.drill.exec.expr.ValueVectorWriteExpression; +import org.apache.drill.exec.expr.fn.FunctionGenerationHelper; +import org.apache.drill.exec.memory.OutOfMemoryException; +import org.apache.drill.exec.memory.OutOfMemoryRuntimeException; +import org.apache.drill.exec.ops.FragmentContext; +import org.apache.drill.exec.physical.config.WindowPOP; +import org.apache.drill.exec.physical.impl.sort.RecordBatchData; +import org.apache.drill.exec.record.AbstractRecordBatch; +import org.apache.drill.exec.record.BatchSchema; +import org.apache.drill.exec.record.MaterializedField; +import org.apache.drill.exec.record.RecordBatch; +import org.apache.drill.exec.record.TypedFieldId; +import org.apache.drill.exec.record.VectorAccessible; +import org.apache.drill.exec.record.VectorWrapper; +import org.apache.drill.exec.vector.ValueVector; + +import java.io.IOException; +import java.util.List; + +/** + * support for OVER(PARTITION BY expression1,expression2,... [ORDER BY expressionA, expressionB,...]) + * + * Doesn't support distinct partitions: multiple window with different PARTITION BY clauses. + */ +public class WindowFrameRecordBatch extends AbstractRecordBatch<WindowPOP> { + static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(WindowFrameRecordBatch.class); + + private final RecordBatch incoming; + private List<RecordBatchData> batches; + private WindowFramer framer; + + private boolean noMoreBatches; + private BatchSchema schema; + + public WindowFrameRecordBatch(WindowPOP popConfig, FragmentContext context, RecordBatch incoming) throws OutOfMemoryException { + super(popConfig, context); + this.incoming = incoming; + batches = Lists.newArrayList(); + } + + /** + * Let's assume we have the following 3 batches of data: + * <p><pre> + * +---------+--------+--------------+--------+ + * | b0 | b1 | b2 | b3 | + * +----+----+--------+----+----+----+--------+ + * | p0 | p1 | p1 | p2 | p3 | p4 | p5 | + * +----+----+--------+----+----+----+--------+ + * </pre></p> + * + * batch b0 contains partitions p0 and p1 + * batch b1 contains partition p1 + * batch b2 contains partitions p2 p3 and p4 + * batch b3 contains partition p5 + * + * <p><pre> + * when innerNext() is called: + * call next(incoming), we receive and save b0 in a list of RecordDataBatch + * we can't process b0 yet because we don't know if p1 has more rows upstream + * call next(incoming), we receive and save b1 + * we can't process b0 yet for the same reason previously stated + * call next(incoming), we receive and save b2 + * we process b0 (using the framer) and pass the container downstream + * when innerNext() is called: + * we process b1 and pass the container downstream, b0 and b1 are released from memory + * when innerNext() is called: + * call next(incoming), we receive and save b3 + * we process b2 and pass the container downstream, b2 is released from memory + * when innerNext() is called: + * call next(incoming) and receive NONE + * we process b3 and pass the container downstream, b3 is released from memory + * when innerNext() is called: + * we return NONE + * </pre></p> + * + */ + @Override + public IterOutcome innerNext() { + logger.trace("innerNext(), noMoreBatches = {}", noMoreBatches); + + // Short circuit if record batch has already sent all data and is done + if (state == BatchState.DONE) { + return IterOutcome.NONE; + } + + // keep saving incoming batches until the first unprocessed batch can be processed, or upstream == NONE + while (!noMoreBatches && !framer.canDoWork()) { + IterOutcome upstream = next(incoming); + logger.trace("next(incoming) returned {}", upstream); + + switch (upstream) { + case NONE: + noMoreBatches = true; + break; + case NOT_YET: + case STOP: + return upstream; + case OK_NEW_SCHEMA: + // when a partition of rows exceeds the current processed batch, it will be kept as "pending" and processed + // when innerNext() is called again. If the schema changes, the framer is "rebuilt" and the pending information + // will be lost which may lead to incorrect results. + + // only change in the case that the schema truly changes. Artificial schema changes are ignored. + if (!incoming.getSchema().equals(schema)) { + if (schema != null) { + throw new UnsupportedOperationException("Sort doesn't currently support sorts with changing schemas."); + } + this.schema = incoming.getSchema(); + } + case OK: + batches.add(new RecordBatchData(incoming)); + break; + default: + throw new UnsupportedOperationException(); + } + } + + if (batches.isEmpty()) { + logger.trace("no more batches to handle, we are DONE"); + state = BatchState.DONE; + return IterOutcome.NONE; + } + + // process a saved batch + try { + framer.doWork(); + } catch (DrillException | OutOfMemoryRuntimeException e) { + context.fail(e); + if (framer != null) { + framer.cleanup(); + framer = null; + } + return IterOutcome.STOP; + } + + if (state == BatchState.FIRST) { + state = BatchState.NOT_FIRST; + } + + return IterOutcome.OK; + } + + @Override + protected void buildSchema() throws SchemaChangeException { + logger.trace("buildSchema()"); + if (next(incoming) == IterOutcome.NONE) { + state = BatchState.DONE; + container.buildSchema(BatchSchema.SelectionVectorMode.NONE); + return; + } + + try { + framer = createFramer(incoming); + } catch (IOException | ClassTransformationException e) { + throw new SchemaChangeException("Exception when creating the schema", e); + } + } + + private WindowFramer createFramer(VectorAccessible batch) throws SchemaChangeException, IOException, ClassTransformationException { + logger.trace("creating framer"); + + container.clear(); + + if (framer != null) { + framer.cleanup(); + framer = null; + } + + ErrorCollector collector = new ErrorCollectorImpl(); + + // setup code generation to copy all incoming vectors to the container + // we can't just transfer them because after we pass the container downstream, some values will be needed when + // processing the next batches + int j = 0; + LogicalExpression[] windowExprs = new LogicalExpression[batch.getSchema().getFieldCount()]; + for (VectorWrapper wrapper : batch) { + // read value from saved batch + final LogicalExpression expr = ExpressionTreeMaterializer.materialize( + new ValueVectorReadExpression(new TypedFieldId(wrapper.getField().getType(), wrapper.isHyper(), j)), + batch, collector, context.getFunctionRegistry()); + + ValueVector vv = container.addOrGet(wrapper.getField()); + vv.allocateNew(); + + // write value into container + TypedFieldId id = container.getValueVectorId(vv.getField().getPath()); + windowExprs[j] = new ValueVectorWriteExpression(id, expr, true); + j++; + } + + // add aggregation vectors to the container, and materialize corresponding expressions + LogicalExpression[] aggExprs = new LogicalExpression[popConfig.getAggregations().length]; + for (int i = 0; i < aggExprs.length; i++) { + // evaluate expression over saved batch + NamedExpression ne = popConfig.getAggregations()[i]; + final LogicalExpression expr = ExpressionTreeMaterializer.materialize(ne.getExpr(), batch, collector, context.getFunctionRegistry()); + + // add corresponding ValueVector to container + final MaterializedField outputField = MaterializedField.create(ne.getRef(), expr.getMajorType()); + ValueVector vv = container.addOrGet(outputField); + vv.allocateNew(); + + // write value into container + TypedFieldId id = container.getValueVectorId(ne.getRef()); + aggExprs[i] = new ValueVectorWriteExpression(id, expr, true); + } + + if (container.isSchemaChanged()) { + container.buildSchema(BatchSchema.SelectionVectorMode.NONE); + } + + // materialize partition by expressions + LogicalExpression[] keyExprs = new LogicalExpression[popConfig.getWithins().length]; + for (int i = 0; i < keyExprs.length; i++) { + NamedExpression ne = popConfig.getWithins()[i]; + keyExprs[i] = ExpressionTreeMaterializer.materialize(ne.getExpr(), batch, collector, context.getFunctionRegistry()); + } + + // materialize order by expressions + LogicalExpression[] orderExprs = new LogicalExpression[popConfig.getOrderings().length]; + for (int i = 0; i < orderExprs.length; i++) { + Order.Ordering oe = popConfig.getOrderings()[i]; + orderExprs[i] = ExpressionTreeMaterializer.materialize(oe.getExpr(), batch, collector, context.getFunctionRegistry()); + } + + if (collector.hasErrors()) { + throw new SchemaChangeException("Failure while materializing expression. " + collector.toErrorString()); + } + + // generate framer code + + final ClassGenerator<WindowFramer> cg = CodeGenerator.getRoot(WindowFramer.TEMPLATE_DEFINITION, context.getFunctionRegistry()); + // setup for isSamePartition() + setupIsFunction(cg, keyExprs, isaB1, isaB2); + // setup for isPeer() + setupIsFunction(cg, orderExprs, isaP1, isaP2); + setupAddRecords(cg, aggExprs); + setupOutputWindowValues(cg, windowExprs); + + cg.getBlock("resetValues")._return(JExpr.TRUE); + + WindowFramer framer = context.getImplementationClass(cg); + framer.setup(batches, container); + + return framer; + } + + private static final GeneratorMapping IS_SAME_RECORD_BATCH_DATA_READ = GeneratorMapping.create("isSamePartition", "isSamePartition", null, null); + private final MappingSet isaB1 = new MappingSet("b1Index", null, "b1", null, IS_SAME_RECORD_BATCH_DATA_READ, IS_SAME_RECORD_BATCH_DATA_READ); + private final MappingSet isaB2 = new MappingSet("b2Index", null, "b2", null, IS_SAME_RECORD_BATCH_DATA_READ, IS_SAME_RECORD_BATCH_DATA_READ); + + private static final GeneratorMapping IS_SAME_PEER = GeneratorMapping.create("isPeer", "isPeer", null, null); + private final MappingSet isaP1 = new MappingSet("b1Index", null, "b1", null, IS_SAME_PEER, IS_SAME_PEER); + private final MappingSet isaP2 = new MappingSet("b2Index", null, "b2", null, IS_SAME_PEER, IS_SAME_PEER); + + /** + * setup comparison functions isSamePartition and isPeer + */ + private void setupIsFunction(ClassGenerator<WindowFramer> cg, LogicalExpression[] exprs, MappingSet leftMapping, MappingSet rightMapping) { + cg.setMappingSet(leftMapping); + for (LogicalExpression expr : exprs) { + cg.setMappingSet(leftMapping); + ClassGenerator.HoldingContainer first = cg.addExpr(expr, false); + cg.setMappingSet(rightMapping); + ClassGenerator.HoldingContainer second = cg.addExpr(expr, false); + + LogicalExpression fh = + FunctionGenerationHelper + .getOrderingComparatorNullsHigh(first, second, context.getFunctionRegistry()); + ClassGenerator.HoldingContainer out = cg.addExpr(fh, false); + cg.getEvalBlock()._if(out.getValue().ne(JExpr.lit(0)))._then()._return(JExpr.FALSE); + } + cg.getEvalBlock()._return(JExpr.TRUE); + } + + private static final GeneratorMapping EVAL_INSIDE = GeneratorMapping.create("setupIncoming", "addRecord", null, null); + private static final GeneratorMapping EVAL_OUTSIDE = GeneratorMapping.create("setupOutgoing", "outputRecordValues", "resetValues", "cleanup"); + private final MappingSet eval = new MappingSet("index", "outIndex", EVAL_INSIDE, EVAL_OUTSIDE, EVAL_INSIDE); + + /** + * setup for addRecords() and outputRecordValues() + */ + private void setupAddRecords(ClassGenerator<WindowFramer> cg, LogicalExpression[] valueExprs) { + cg.setMappingSet(eval); + for (LogicalExpression ex : valueExprs) { + cg.addExpr(ex); + } + } + + private final static GeneratorMapping OUTPUT_WINDOW_VALUES = GeneratorMapping.create("setupCopy", "outputWindowValues", null, null); + private final MappingSet windowValues = new MappingSet("index", "index", OUTPUT_WINDOW_VALUES, OUTPUT_WINDOW_VALUES); + + private void setupOutputWindowValues(ClassGenerator<WindowFramer> cg, LogicalExpression[] valueExprs) { + cg.setMappingSet(windowValues); + for (LogicalExpression valueExpr : valueExprs) { + cg.addExpr(valueExpr); + } + } + + @Override + public void cleanup() { + if (framer != null) { + framer.cleanup(); + framer = null; + } + super.cleanup(); + incoming.cleanup(); + } + + @Override + protected void killIncoming(boolean sendUpstream) { + incoming.kill(sendUpstream); + } + + @Override + public int getRecordCount() { + return framer.getOutputCount(); + } +} http://git-wip-us.apache.org/repos/asf/drill/blob/fb293ba5/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/window/WindowFrameTemplate.java ---------------------------------------------------------------------- diff --git a/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/window/WindowFrameTemplate.java b/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/window/WindowFrameTemplate.java new file mode 100644 index 0000000..78bab54 --- /dev/null +++ b/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/window/WindowFrameTemplate.java @@ -0,0 +1,379 @@ +/** + * 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.physical.impl.window; + +import org.apache.drill.common.exceptions.DrillException; +import org.apache.drill.exec.exception.SchemaChangeException; +import org.apache.drill.exec.physical.impl.sort.RecordBatchData; +import org.apache.drill.exec.record.VectorAccessible; +import org.apache.drill.exec.record.VectorWrapper; + +import javax.inject.Named; +import java.util.Iterator; +import java.util.List; + + +public abstract class WindowFrameTemplate implements WindowFramer { + static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(WindowFrameTemplate.class); + + private VectorAccessible container; + private List<RecordBatchData> batches; + private int outputCount; // number of rows in currently/last processed batch + + /** + * current partition being processed. Can span over multiple batches, so we may need to keep it between calls to doWork() + */ + private Interval partition; + + private int currentBatch; // first unprocessed batch + + @Override + public void setup(List<RecordBatchData> batches, VectorAccessible container) throws SchemaChangeException { + this.container = container; + this.batches = batches; + + outputCount = 0; + partition = null; + currentBatch = 0; + + setupOutgoing(container); + } + + /** + * processes all rows of current batch: + * <ul> + * <li>compute window aggregations</li> + * <li>copy remaining vectors from current batch to container</li> + * </ul> + */ + @Override + public void doWork() throws DrillException { + logger.trace("WindowFramer.doWork() START, num batches {}, currentBatch {}", batches.size(), currentBatch); + + final VectorAccessible current = batches.get(currentBatch).getContainer(); + + // we need to store the record count explicitly, in case we release current batch at the end of this call + outputCount = current.getRecordCount(); + + // allocate vectors + for (VectorWrapper<?> w : container){ + w.getValueVector().allocateNew(); + } + + setupCopy(current, container); + + int currentRow = 0; + + while (currentRow < outputCount) { + if (partition != null) { + assert currentRow == 0 : "pending windows are only expected at the start of the batch"; + + // we have a pending window we need to handle from a previous call to doWork() + logger.trace("we have a pending partition {}", partition); + } else { + // compute the size of the new partition + final int length = computePartitionSize(currentRow); + partition = new Interval(currentRow, length, 0); + } + + currentRow = processPartition(currentRow); + + if (partition == null) { + freeBatches(currentRow == outputCount); + } + } + + if (partition != null) { + logger.trace("we have a pending partition {}", partition); + // current batch has been processed but it won't be released until this pending partition is processed + currentBatch++; + } + + for (VectorWrapper<?> v : container) { + v.getValueVector().getMutator().setValueCount(outputCount); + } + + logger.trace("WindowFramer.doWork() END"); + } + + /** + * releases saved batches that are no longer needed: all rows of their partitions have been processed + * @param freeCurrent do we free current batch too ? + */ + private void freeBatches(boolean freeCurrent) { + // how many batches can be released + int numFree = currentBatch; + if (freeCurrent) { // current batch can also be released + numFree++; + } + if (numFree > 0) { + logger.trace("freeing {} batches", numFree); + + // we are ready to free batches < currentBatch + for (int i = 0; i < numFree; i++) { + RecordBatchData bd = batches.remove(0); + bd.getContainer().clear(); + } + + currentBatch = 0; + } + } + + /** + * process all rows (computes and writes aggregation values) of current batch that are part of current partition. + * @return index of next unprocessed row + * @throws DrillException if it can't write into the container + */ + private int processPartition(int currentRow) throws DrillException { + logger.trace("process partition {}, currentBatch: {}, currentRow: {}", partition, currentBatch, currentRow); + + // compute how many rows remain unprocessed in the current partition + int remaining = partition.length; + for (int b = 0; b < currentBatch; b++) { + remaining -= batches.get(b).getRecordCount(); + } + remaining -= currentRow - partition.start; + + // when computing the frame for the current row, keep track of how many peer rows need to be processed + // because all peer rows share the same frame, we only need to compute and aggregate the frame once + for (int peers = 0; currentRow < outputCount && remaining > 0; currentRow++, remaining--) { + if (peers == 0) { + Interval frame = computeFrame(currentBatch, currentRow); + resetValues(); + aggregate(frame); + peers = frame.peers; + } else { + peers--; + } + + outputRecordValues(currentRow); + outputWindowValues(currentRow); + } + + if (remaining == 0) { + logger.trace("finished processing {}", partition); + partition = null; + } + + return currentRow; + } + + /** + * @return number of rows that are part of the partition starting at row start of first batch + */ + private int computePartitionSize(int start) { + logger.trace("compute partition size starting from {} on {} batches", start, batches.size()); + + // current partition always starts from first batch + final VectorAccessible first = batches.get(0).getContainer(); + + int length = 0; + + // count all rows that are in the same partition of start + outer: + for (RecordBatchData batch : batches) { + final VectorAccessible cont = batch.getContainer(); + + // check first container from start row, and subsequent containers from first row + for (int row = (cont == first ? start : 0); row < cont.getRecordCount(); row++) { + if (isSamePartition(start, first, row, cont)) { + length++; + } else { + break outer; + } + } + } + + return length; + } + + /** + * find the limits of the window frame for a row + * @param batchId batch where the current row is + * @param row idx of row in the given batch + * @return frame interval + */ + private Interval computeFrame(int batchId, int row) { + + // using default frame for now RANGE BETWEEN UNBOUND PRECEDING AND CURRENT ROW + // frame contains all rows from start of partition to last peer of row + + // count how many rows in the current partition precede the row + int length = row; + // include rows of all batches previous to batchId + Iterator<RecordBatchData> iterator = batches.iterator(); + for (int b = 0; b < batchId; b++) { + length += iterator.next().getRecordCount(); + } + length -= partition.start; + + VectorAccessible batch = iterator.next().getContainer(); + VectorAccessible current = batch; + + // for every remaining row in the partition, count it if it's a peer row + int peers = 0; + for (int curRow = row; length < partition.length; length++, curRow++, peers++) { + if (curRow == current.getRecordCount()) { + current = iterator.next().getContainer(); + curRow = 0; + } + + if (!isPeer(row, batch, curRow, current)) { + break; + } + } + + // do not count row as a peer + return new Interval(partition.start, length, peers-1); + } + + private void aggregate(Interval frame) throws SchemaChangeException { + logger.trace("aggregating {}", frame); + assert frame.length > 0 : "processing empty frame!"; + + // a single frame can include rows from multiple batches + // start processing first batch and, if necessary, move to next batches + Iterator<RecordBatchData> iterator = batches.iterator(); + VectorAccessible current = iterator.next().getContainer(); + setupIncoming(current); + + for (int i = 0, row = frame.start; i < frame.length; i++, row++) { + if (row >= current.getRecordCount()) { + // we reached the end of the current batch, move to the next one + current = iterator.next().getContainer(); + setupIncoming(current); + row = 0; + } + + addRecord(row); + } + } + + @Override + public boolean canDoWork() { + // check if we can process a saved batch + if (batches.size() > 1) { + final VectorAccessible last = batches.get(batches.size()-1).getContainer(); + + if (!isSamePartition(getCurrent().getRecordCount() - 1, getCurrent(), last.getRecordCount() - 1, last)) { + logger.trace("partition changed, we are ready to process first saved batch"); + return true; + } else { + logger.trace("partition didn't change, fetch next batch"); + } + } else { + logger.trace("we don't have enough batches to proceed, fetch next batch"); + } + + return false; + } + + @Override + public VectorAccessible getCurrent() { + return batches.get(currentBatch).getContainer(); + } + + @Override + public int getOutputCount() { + return outputCount; + } + + @Override + public void cleanup() { + } + + /** + * setup incoming container for addRecord() + */ + public abstract void setupIncoming(@Named("incoming") VectorAccessible incoming) throws SchemaChangeException; + + /** + * setup outgoing container for outputRecordValues + */ + public abstract void setupOutgoing(@Named("outgoing") VectorAccessible outgoing) throws SchemaChangeException; + + /** + * setup for outputWindowValues + */ + public abstract void setupCopy(@Named("incoming") VectorAccessible incoming, @Named("outgoing") VectorAccessible outgoing) throws SchemaChangeException; + + /** + * aggregates a row from the incoming container + * @param index of row to aggregate + */ + public abstract void addRecord(@Named("index") int index); + + /** + * writes aggregated values to row of outgoing container + * @param outIndex index of row + */ + public abstract void outputRecordValues(@Named("outIndex") int outIndex); + + /** + * copies all value vectors from incoming to container, for a specific row + * @param index of row to be copied + */ + public abstract void outputWindowValues(@Named("index") int index); + + /** + * reset all window functions + */ + public abstract boolean resetValues(); + + /** + * compares two rows from different batches (can be the same), if they have the same value for the partition by + * expression + * @param b1Index index of first row + * @param b1 batch for first row + * @param b2Index index of second row + * @param b2 batch for second row + * @return true if the rows are in the same partition + */ + public abstract boolean isSamePartition(@Named("b1Index") int b1Index, @Named("b1") VectorAccessible b1, @Named("b2Index") int b2Index, @Named("b2") VectorAccessible b2); + + /** + * compares two rows from different batches (can be the same), if they have the same value for the order by + * expression + * @param b1Index index of first row + * @param b1 batch for first row + * @param b2Index index of second row + * @param b2 batch for second row + * @return true if the rows are in the same partition + */ + public abstract boolean isPeer(@Named("b1Index") int b1Index, @Named("b1") VectorAccessible b1, @Named("b2Index") int b2Index, @Named("b2") VectorAccessible b2); + + /** + * Used internally to keep track of partitions and frames + */ + private static class Interval { + public final int start; + public final int length; + public final int peers; // we only need this for frames + + public Interval(int start, int length, int peers) { + this.start = start; + this.length = length; + this.peers = peers; + } + + @Override + public String toString() { + return String.format("{start: %d, length: %d, peers: %d}", start, length, peers); + } + } +} http://git-wip-us.apache.org/repos/asf/drill/blob/fb293ba5/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/window/WindowFramer.java ---------------------------------------------------------------------- diff --git a/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/window/WindowFramer.java b/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/window/WindowFramer.java new file mode 100644 index 0000000..23a2b53 --- /dev/null +++ b/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/window/WindowFramer.java @@ -0,0 +1,59 @@ +/** + * 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.physical.impl.window; + +import org.apache.drill.common.exceptions.DrillException; +import org.apache.drill.exec.compile.TemplateClassDefinition; +import org.apache.drill.exec.exception.SchemaChangeException; +import org.apache.drill.exec.physical.impl.sort.RecordBatchData; +import org.apache.drill.exec.record.VectorAccessible; + +import java.util.List; + +public interface WindowFramer { + public static TemplateClassDefinition<WindowFramer> TEMPLATE_DEFINITION = new TemplateClassDefinition<>(WindowFramer.class, WindowFrameTemplate.class); + + public abstract void setup(List<RecordBatchData> batches, VectorAccessible container) throws SchemaChangeException; + + /** + * process the inner batch and write the aggregated values in the container + * @throws DrillException + */ + public abstract void doWork() throws DrillException; + + /** + * check if current batch can be processed: + * <ol> + * <li>we have at least 2 saved batches</li> + * <li>last partition of current batch ended</li> + * </ol> + * @return true if current batch can be processed, false otherwise + */ + public abstract boolean canDoWork(); + /** + * @return number rows processed in last batch + */ + public abstract int getOutputCount(); + + public abstract void cleanup(); + + /** + * @return saved batch that will be processed in doWork() + */ + public abstract VectorAccessible getCurrent(); +} http://git-wip-us.apache.org/repos/asf/drill/blob/fb293ba5/exec/java-exec/src/main/java/org/apache/drill/exec/planner/logical/DrillRuleSets.java ---------------------------------------------------------------------- diff --git a/exec/java-exec/src/main/java/org/apache/drill/exec/planner/logical/DrillRuleSets.java b/exec/java-exec/src/main/java/org/apache/drill/exec/planner/logical/DrillRuleSets.java index 3b7adca..389395c 100644 --- a/exec/java-exec/src/main/java/org/apache/drill/exec/planner/logical/DrillRuleSets.java +++ b/exec/java-exec/src/main/java/org/apache/drill/exec/planner/logical/DrillRuleSets.java @@ -38,15 +38,12 @@ import org.apache.drill.exec.planner.physical.ScreenPrule; import org.apache.drill.exec.planner.physical.SortConvertPrule; import org.apache.drill.exec.planner.physical.SortPrule; import org.apache.drill.exec.planner.physical.StreamAggPrule; -import org.apache.drill.exec.planner.physical.StreamingWindowPrule; +import org.apache.drill.exec.planner.physical.WindowPrule; import org.apache.drill.exec.planner.physical.UnionAllPrule; import org.apache.drill.exec.planner.physical.WriterPrule; import org.eigenbase.rel.RelFactories; import org.eigenbase.rel.rules.PushFilterPastJoinRule; -import org.eigenbase.rel.rules.PushFilterPastProjectRule; import org.eigenbase.rel.rules.PushJoinThroughJoinRule; -import org.eigenbase.rel.rules.PushProjectPastFilterRule; -import org.eigenbase.rel.rules.PushProjectPastJoinRule; import org.eigenbase.rel.rules.RemoveDistinctAggregateRule; import org.eigenbase.rel.rules.RemoveDistinctRule; import org.eigenbase.rel.rules.RemoveSortRule; @@ -144,7 +141,7 @@ public class DrillRuleSets { ruleList.add(FilterPrule.INSTANCE); ruleList.add(LimitPrule.INSTANCE); ruleList.add(WriterPrule.INSTANCE); - ruleList.add(StreamingWindowPrule.INSTANCE); + ruleList.add(WindowPrule.INSTANCE); ruleList.add(PushLimitToTopN.INSTANCE); ruleList.add(UnionAllPrule.INSTANCE); // ruleList.add(UnionDistinctPrule.INSTANCE); http://git-wip-us.apache.org/repos/asf/drill/blob/fb293ba5/exec/java-exec/src/main/java/org/apache/drill/exec/planner/physical/StreamingWindowPrel.java ---------------------------------------------------------------------- diff --git a/exec/java-exec/src/main/java/org/apache/drill/exec/planner/physical/StreamingWindowPrel.java b/exec/java-exec/src/main/java/org/apache/drill/exec/planner/physical/StreamingWindowPrel.java deleted file mode 100644 index f1a8bc0..0000000 --- a/exec/java-exec/src/main/java/org/apache/drill/exec/planner/physical/StreamingWindowPrel.java +++ /dev/null @@ -1,136 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.drill.exec.planner.physical; - -import com.google.common.collect.Lists; -import net.hydromatic.optiq.util.BitSets; -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.LogicalExpression; -import org.apache.drill.common.expression.ValueExpressions; -import org.apache.drill.common.logical.data.NamedExpression; -import org.apache.drill.exec.physical.base.PhysicalOperator; -import org.apache.drill.exec.physical.config.WindowPOP; -import org.apache.drill.exec.planner.common.DrillWindowRelBase; -import org.apache.drill.exec.planner.physical.visitor.PrelVisitor; -import org.apache.drill.exec.record.BatchSchema; -import org.eigenbase.rel.AggregateCall; -import org.eigenbase.rel.RelNode; -import org.eigenbase.relopt.RelOptCluster; -import org.eigenbase.relopt.RelTraitSet; -import org.eigenbase.reltype.RelDataType; -import org.eigenbase.rex.RexLiteral; - -import java.io.IOException; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; - -import static com.google.common.base.Preconditions.checkState; - -public class StreamingWindowPrel extends DrillWindowRelBase implements Prel { - public StreamingWindowPrel(RelOptCluster cluster, - RelTraitSet traits, - RelNode child, - List<RexLiteral> constants, - RelDataType rowType, - Window window) { - super(cluster, traits, child, constants, rowType, Collections.singletonList(window)); - } - - @Override - public RelNode copy(RelTraitSet traitSet, List<RelNode> inputs) { - return new StreamingWindowPrel(getCluster(), traitSet, sole(inputs), constants, getRowType(), windows.get(0)); - } - - @Override - public PhysicalOperator getPhysicalOperator(PhysicalPlanCreator creator) throws IOException { - Prel child = (Prel) this.getChild(); - - PhysicalOperator childPOP = child.getPhysicalOperator(creator); - - final List<String> childFields = getChild().getRowType().getFieldNames(); - - checkState(windows.size() == 1, "Only one window is expected in WindowPrel"); - - Window window = windows.get(0); - List<NamedExpression> withins = Lists.newArrayList(); - List<NamedExpression> aggs = Lists.newArrayList(); - for (int group : BitSets.toIter(window.groupSet)) { - FieldReference fr = new FieldReference(childFields.get(group), ExpressionPosition.UNKNOWN); - withins.add(new NamedExpression(fr, fr)); - } - - for (AggregateCall aggCall : window.getAggregateCalls(this)) { - FieldReference ref = new FieldReference(aggCall.getName()); - LogicalExpression expr = toDrill(aggCall, childFields); - aggs.add(new NamedExpression(expr, ref)); - } - - WindowPOP windowPOP = new WindowPOP( - childPOP, - withins.toArray(new NamedExpression[withins.size()]), - aggs.toArray(new NamedExpression[aggs.size()]), - Long.MIN_VALUE, //TODO: Get first/last to work - Long.MIN_VALUE); - - creator.addMetadata(this, windowPOP); - return windowPOP; - } - - protected LogicalExpression toDrill(AggregateCall call, List<String> fn) { - List<LogicalExpression> args = Lists.newArrayList(); - for (Integer i : call.getArgList()) { - args.add(new FieldReference(fn.get(i))); - } - - // for count(1). - if (args.isEmpty()) { - args.add(new ValueExpressions.LongExpression(1l)); - } - LogicalExpression expr = new FunctionCall(call.getAggregation().getName().toLowerCase(), args, ExpressionPosition.UNKNOWN); - return expr; - } - - @Override - public <T, X, E extends Throwable> T accept(PrelVisitor<T, X, E> logicalVisitor, X value) throws E { - return logicalVisitor.visitPrel(this, value); - } - - @Override - public BatchSchema.SelectionVectorMode[] getSupportedEncodings() { - return BatchSchema.SelectionVectorMode.ALL; - } - - @Override - public BatchSchema.SelectionVectorMode getEncoding() { - return BatchSchema.SelectionVectorMode.NONE; - } - - @Override - public boolean needsFinalColumnReordering() { - return false; - } - - @Override - public Iterator<Prel> iterator() { - return PrelUtil.iter(getChild()); - } -}
