You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@ignite.apache.org by GitBox <gi...@apache.org> on 2020/11/03 19:21:37 UTC

[GitHub] [ignite] tledkov-gridgain opened a new pull request #7903: IGNITE-13025: add IgniteLimit logical node

tledkov-gridgain opened a new pull request #7903:
URL: https://github.com/apache/ignite/pull/7903


   Thank you for submitting the pull request to the Apache Ignite.
   
   In order to streamline the review of the contribution 
   we ask you to ensure the following steps have been taken:
   
   ### The Contribution Checklist
   - [ ] There is a single JIRA ticket related to the pull request. 
   - [ ] The web-link to the pull request is attached to the JIRA ticket.
   - [ ] The JIRA ticket has the _Patch Available_ state.
   - [ ] The pull request body describes changes that have been made. 
   The description explains _WHAT_ and _WHY_ was made instead of _HOW_.
   - [ ] The pull request title is treated as the final commit message. 
   The following pattern must be used: `IGNITE-12407: Add Cluster API support to Java thin client`
   - [ ] A reviewer has been mentioned through the JIRA comments 
   (see [the Maintainers list](https://cwiki.apache.org/confluence/display/IGNITE/How+to+Contribute#HowtoContribute-ReviewProcessandMaintainers)) 
   - [ ] The pull request has been checked by the Teamcity Bot and 
   the `green visa` attached to the JIRA ticket (see [TC.Bot: Check PR](https://mtcga.gridgain.com/prs.html))
   
   ### Notes
   - [How to Contribute](https://cwiki.apache.org/confluence/display/IGNITE/How+to+Contribute)
   - [Coding abbreviation rules](https://cwiki.apache.org/confluence/display/IGNITE/Abbreviation+Rules)
   - [Coding Guidelines](https://cwiki.apache.org/confluence/display/IGNITE/Coding+Guidelines)
   - [Apache Ignite Teamcity Bot](https://cwiki.apache.org/confluence/display/IGNITE/Apache+Ignite+Teamcity+Bot)
   
   If you need any help, please email dev@ignite.apache.org or ask anу advice on http://asf.slack.com _#ignite_ channel.


----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [ignite] gvvinblade commented on a change in pull request #7903: IGNITE-13025: add IgniteLimit logical node

Posted by GitBox <gi...@apache.org>.
gvvinblade commented on a change in pull request #7903:
URL: https://github.com/apache/ignite/pull/7903#discussion_r443500274



##########
File path: modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/exec/rel/LimitNode.java
##########
@@ -0,0 +1,185 @@
+/*
+ * 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.ignite.internal.processors.query.calcite.exec.rel;
+
+import java.util.function.Supplier;
+import org.apache.ignite.internal.processors.query.IgniteSQLException;
+import org.apache.ignite.internal.processors.query.calcite.exec.ExecutionContext;
+import org.apache.ignite.internal.util.typedef.F;
+
+/**
+ *
+ */
+public class LimitNode<Row> extends AbstractNode<Row> implements SingleNode<Row>, Downstream<Row> {
+    /** */
+    private static final int NOT_READY = -1;
+
+    /** */
+    private static final int LIMIT_NOT_SET = -2;
+
+    /** */
+    private final Supplier<Integer> offsetSup;
+
+    /** */
+    private final Supplier<Integer> limitSup;
+
+    /** */
+    private int offset = NOT_READY;
+
+    /** */
+    private int limit = NOT_READY;
+
+    /** */
+    private int requested;
+
+    /** */
+    private int rowNum;
+
+    /** */
+    private int waiting;
+
+    /** */
+    boolean ended;
+
+    /**
+     * @param ctx Execution context.
+     * @param offsetSup Offset parameter supplier.
+     * @param limitSup Limit parameter supplier.
+     */
+    public LimitNode(
+        ExecutionContext<Row> ctx,
+        Supplier<Integer> offsetSup,
+        Supplier<Integer> limitSup) {
+        super(ctx);
+
+        this.offsetSup = offsetSup;
+        this.limitSup = limitSup;
+    }
+
+    /** {@inheritDoc} */
+    @Override public void request(int rowsCnt) {
+        checkThread();
+
+        assert !F.isEmpty(sources) && sources.size() == 1;
+        assert rowsCnt > 0 && requested == 0;
+
+        requested = rowsCnt;
+
+        // Initialize offset / limit.
+        if (offset == NOT_READY && limit == NOT_READY) {
+            if (offsetSup != null) {
+                offset = offsetSup.get();
+
+                if (offset < 0)
+                    onError(new IgniteSQLException("Invalid query offset: " + offset));
+            }
+            else
+                offset = 0;
+
+            if (limitSup != null) {
+                limit = limitSup.get();
+
+                if (limit < 0)
+                    onError(new IgniteSQLException("Invalid query limit: " + limit));
+            }
+            else
+                limit = LIMIT_NOT_SET;
+        }
+
+        request0(requested);
+    }
+
+    /**
+     * Process request (some parameters may not yet be calculated).
+     */
+    private void request0(int rowsCnt) {
+        if (limit == 0 || limit > 0 && rowNum >= limit + offset) {
+            end();
+
+            return;
+        }
+
+        int req = rowsCnt;
+
+        if (rowNum == 0 && offset > 0)
+            req += offset;
+
+        if (limit > 0 && rowNum + req > limit + offset)
+            req = limit + offset - rowNum;
+
+        waiting = req;
+
+        F.first(sources).request(req);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void push(Row row) {
+        checkThread();
+
+        assert downstream != null;
+
+        waiting--;
+
+        if (!ended && rowNum >= offset) {
+            requested--;
+
+            downstream.push(row);
+        }
+
+        rowNum++;
+
+        if (requested > 0 && limit > 0 && rowNum >= limit + offset)
+            end();

Review comment:
       let's cancel upstream only here and do not do it inside end() method

##########
File path: modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/exec/rel/Inbox.java
##########
@@ -143,9 +152,22 @@ public void init(ExecutionContext<Row> ctx, Collection<UUID> nodes, Comparator<R
 
     /** {@inheritDoc} */
     @Override public void cancel() {
-        checkThread();
-        context().markCancelled();
+        if (isCancelled())
+            return;
+
+        nodes.forEach(nodeId -> {
+            try {

Review comment:
       let's move it into a specific method of the Buffer class

##########
File path: modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/message/ErrorMessage.java
##########
@@ -0,0 +1,173 @@
+/*
+ * 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.ignite.internal.processors.query.calcite.message;
+
+import java.nio.ByteBuffer;
+import java.util.UUID;
+import org.apache.ignite.plugin.extensions.communication.MessageReader;
+import org.apache.ignite.plugin.extensions.communication.MessageWriter;
+
+/**
+ *
+ */
+public class ErrorMessage implements ExecutionContextAware {
+    /** */
+    private UUID queryId;
+
+    /** */
+    private long fragmentId;
+
+    /** */
+    private long exchangeId;
+
+    /** */
+    private byte[] errBytes;
+
+    /** */
+    public ErrorMessage() {
+        // No-op.
+    }
+
+    /** */
+    public ErrorMessage(UUID queryId, long fragmentId, long exchangeId, byte[] errBytes) {
+        this.queryId = queryId;
+        this.fragmentId = fragmentId;
+        this.exchangeId = exchangeId;
+        this.errBytes = errBytes;

Review comment:
       Let's implement `MarshalableMessage` and put marshaling logic into appropriate methods

##########
File path: modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/exec/rel/LimitNode.java
##########
@@ -0,0 +1,185 @@
+/*
+ * 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.ignite.internal.processors.query.calcite.exec.rel;
+
+import java.util.function.Supplier;
+import org.apache.ignite.internal.processors.query.IgniteSQLException;
+import org.apache.ignite.internal.processors.query.calcite.exec.ExecutionContext;
+import org.apache.ignite.internal.util.typedef.F;
+
+/**
+ *
+ */
+public class LimitNode<Row> extends AbstractNode<Row> implements SingleNode<Row>, Downstream<Row> {
+    /** */
+    private static final int NOT_READY = -1;
+
+    /** */
+    private static final int LIMIT_NOT_SET = -2;
+
+    /** */
+    private final Supplier<Integer> offsetSup;
+
+    /** */
+    private final Supplier<Integer> limitSup;
+
+    /** */
+    private int offset = NOT_READY;
+
+    /** */
+    private int limit = NOT_READY;
+
+    /** */
+    private int requested;
+
+    /** */
+    private int rowNum;
+
+    /** */
+    private int waiting;
+
+    /** */
+    boolean ended;
+
+    /**
+     * @param ctx Execution context.
+     * @param offsetSup Offset parameter supplier.
+     * @param limitSup Limit parameter supplier.
+     */
+    public LimitNode(
+        ExecutionContext<Row> ctx,
+        Supplier<Integer> offsetSup,
+        Supplier<Integer> limitSup) {
+        super(ctx);
+
+        this.offsetSup = offsetSup;
+        this.limitSup = limitSup;
+    }
+
+    /** {@inheritDoc} */
+    @Override public void request(int rowsCnt) {
+        checkThread();
+
+        assert !F.isEmpty(sources) && sources.size() == 1;
+        assert rowsCnt > 0 && requested == 0;
+
+        requested = rowsCnt;
+
+        // Initialize offset / limit.
+        if (offset == NOT_READY && limit == NOT_READY) {
+            if (offsetSup != null) {
+                offset = offsetSup.get();
+
+                if (offset < 0)
+                    onError(new IgniteSQLException("Invalid query offset: " + offset));
+            }
+            else
+                offset = 0;
+
+            if (limitSup != null) {
+                limit = limitSup.get();
+
+                if (limit < 0)
+                    onError(new IgniteSQLException("Invalid query limit: " + limit));
+            }
+            else
+                limit = LIMIT_NOT_SET;
+        }
+
+        request0(requested);
+    }
+
+    /**
+     * Process request (some parameters may not yet be calculated).
+     */
+    private void request0(int rowsCnt) {
+        if (limit == 0 || limit > 0 && rowNum >= limit + offset) {
+            end();
+
+            return;
+        }
+
+        int req = rowsCnt;
+
+        if (rowNum == 0 && offset > 0)
+            req += offset;
+
+        if (limit > 0 && rowNum + req > limit + offset)
+            req = limit + offset - rowNum;
+
+        waiting = req;
+
+        F.first(sources).request(req);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void push(Row row) {
+        checkThread();
+
+        assert downstream != null;
+
+        waiting--;
+
+        if (!ended && rowNum >= offset) {
+            requested--;
+
+            downstream.push(row);
+        }
+
+        rowNum++;
+
+        if (requested > 0 && limit > 0 && rowNum >= limit + offset)
+            end();
+
+        if (!ended && requested > 0 && waiting == 0)
+            request0(IN_BUFFER_SIZE);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void end() {
+        checkThread();
+
+        if (ended)
+            return;
+
+        ended = true;
+
+        sources.get(0).cancel();

Review comment:
       We shouldn't cancel upstream here

##########
File path: modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/exec/rel/Outbox.java
##########
@@ -157,24 +154,26 @@ public void init() {
         U.error(context().planningContext().logger(),
             "Error occurred during execution: " + X.getFullStackTrace(e));
 
-        cancel(); // TODO send cause to originator.
+        dest.targets().forEach(nodeId -> {

Review comment:
       let's move it into specific Buffer method

##########
File path: modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/rule/SortConverterRule.java
##########
@@ -40,12 +42,22 @@ public SortConverterRule() {
     }
 
     /** {@inheritDoc} */
-    @Override protected PhysicalNode convert(RelOptPlanner planner, RelMetadataQuery mq, LogicalSort rel) {
-        RelOptCluster cluster = rel.getCluster();
-        RelTraitSet outTraits = cluster.traitSetOf(IgniteConvention.INSTANCE).replace(rel.getCollation());
+    @Override protected PhysicalNode convert(RelOptPlanner planner, RelMetadataQuery mq, LogicalSort sort) {
+        RelOptCluster cluster = sort.getCluster();
+        RelTraitSet outTraits = cluster.traitSetOf(IgniteConvention.INSTANCE).replace(sort.getCollation());
         RelTraitSet inTraits = cluster.traitSetOf(IgniteConvention.INSTANCE);
-        RelNode input = convert(rel.getInput(), inTraits);
+        RelNode input = convert(sort.getInput(), inTraits);
 
-        return new IgniteSort(cluster, outTraits, input, rel.getCollation(), rel.offset, rel.fetch);
+        IgniteRel res = null;
+
+        if (!sort.getCollation().getFieldCollations().isEmpty())

Review comment:
       let's split into two rules: for sort and for limit (see `RelOptRule.matched()` method to separate rules better)

##########
File path: modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/type/IgniteTypeSystem.java
##########
@@ -20,10 +20,15 @@
 import java.io.Serializable;
 import org.apache.calcite.rel.type.RelDataTypeSystem;
 import org.apache.calcite.rel.type.RelDataTypeSystemImpl;
+import org.apache.calcite.sql.type.SqlTypeName;
 
 /**
  * Ignite type system.
  */
 public class IgniteTypeSystem extends RelDataTypeSystemImpl implements Serializable {
     public static final RelDataTypeSystem INSTANCE = new IgniteTypeSystem();
+
+    @Override public int getDefaultPrecision(SqlTypeName typeName) {

Review comment:
       redundant overriding




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [ignite] AMashenkov closed pull request #7903: IGNITE-13025: add IgniteLimit logical node

Posted by GitBox <gi...@apache.org>.
AMashenkov closed pull request #7903:
URL: https://github.com/apache/ignite/pull/7903


   


----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [ignite] asfgit closed pull request #7903: IGNITE-13025: add IgniteLimit logical node

Posted by GitBox <gi...@apache.org>.
asfgit closed pull request #7903:
URL: https://github.com/apache/ignite/pull/7903


   


----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [ignite] tledkov-gridgain commented on a change in pull request #7903: IGNITE-13025: add IgniteLimit logical node

Posted by GitBox <gi...@apache.org>.
tledkov-gridgain commented on a change in pull request #7903:
URL: https://github.com/apache/ignite/pull/7903#discussion_r436540021



##########
File path: modules/calcite/src/test/java/org/apache/ignite/internal/processors/query/calcite/LimitOffsetTest.java
##########
@@ -0,0 +1,154 @@
+/*
+ * 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.ignite.internal.processors.query.calcite;
+
+import java.util.List;
+import org.apache.ignite.Ignite;
+import org.apache.ignite.IgniteCache;
+import org.apache.ignite.cache.CacheMode;
+import org.apache.ignite.cache.QueryEntity;
+import org.apache.ignite.cache.query.FieldsQueryCursor;
+import org.apache.ignite.configuration.CacheConfiguration;
+import org.apache.ignite.internal.processors.query.QueryEngine;
+import org.apache.ignite.internal.processors.query.calcite.util.Commons;
+import org.apache.ignite.internal.util.typedef.X;
+import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
+import org.junit.Test;
+
+import static java.util.Collections.singletonList;
+
+/**
+ * Limit / offset tests.
+ */
+public class LimitOffsetTest extends GridCommonAbstractTest {
+    /** */
+    private static final int ROWS = 100;
+
+    /** {@inheritDoc} */
+    @Override protected void beforeTestsStarted() throws Exception {
+        Ignite grid = startGrids(2);
+
+        QueryEntity e = new QueryEntity()
+            .setTableName("Test")
+            .setKeyType(Integer.class.getName())
+            .setValueType(String.class.getName())
+            .setKeyFieldName("id")
+            .setValueFieldName("val")
+            .addQueryField("id", Integer.class.getName(), null)
+            .addQueryField("val", String.class.getName(), null);
+
+        CacheConfiguration<Integer, String> ccfg = cacheConfiguration(e);
+
+        IgniteCache<Integer, String> cache = grid.createCache(ccfg);
+
+        for (int i = 0; i < ROWS; ++i)
+            cache.put(i, "val_" + i);
+    }
+
+    /** */
+    private CacheConfiguration cacheConfiguration(QueryEntity ent) {
+        return new CacheConfiguration<>(ent.getTableName())
+            .setCacheMode(CacheMode.PARTITIONED)
+            .setBackups(1)
+            .setQueryEntities(singletonList(ent))
+            .setSqlSchema("PUBLIC");
+    }
+
+    /**
+     *
+     */
+    @Test
+    public void testLimitOffset() {
+        int[] limits = {-1, 0, 10, ROWS / 2 - 1, ROWS / 2, ROWS / 2 + 1, ROWS - 1, ROWS};
+        int[] offsets = {-1, 0, 10, ROWS / 2 - 1, ROWS / 2, ROWS / 2 + 1, ROWS - 1, ROWS};
+
+        for (int lim : limits) {
+            for (int off : offsets) {
+                log.info("+++ Check [limit=" + lim + ", off=" + off + ']');
+
+                checkQuery(lim, off, false, false);
+                checkQuery(lim, off, true, false);
+                checkQuery(lim, off, false, true);
+                checkQuery(lim, off, true, true);
+            }
+        }
+    }
+
+    /**
+     * Check query with specified limit and offset (or without its when the arguments are negative),
+     *
+     * @param lim Limit.
+     * @param off Offset.
+     * @param param If {@code false} place limit/offset as literals. Otherwise they are plase as parameters.
+     * @param sorted Use sorted query (adds ORDER BY).
+     */
+    void checkQuery(int lim, int off, boolean param, boolean sorted) {
+        QueryEngine engine = Commons.lookupComponent(grid(0).context(), QueryEngine.class);
+
+        String sql = createSql(lim, off, false, false);
+
+        log.info("SQL: " + sql);
+
+        List<FieldsQueryCursor<List<?>>> cursors =
+            engine.query(null, "PUBLIC", sql, param ? new Object[]{off, lim} : X.EMPTY_OBJECT_ARRAY);
+
+        List<List<?>> res = cursors.get(0).getAll();
+
+        assertEquals("Invalid results size. [limit=" + lim + ", off=" + off + ", res=" + res.size() + ']',
+            expectedSize(lim, off), res.size());
+    }
+
+    /**
+     * Calculates expected result set size by limit and offset.
+     */
+    private int expectedSize(int lim, int off) {
+        if (off < 0)

Review comment:
       At the test i use negative value not use limit/offset in the query (see #createSql). 
   I'll add new test to check negative limit offset




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [ignite] tledkov-gridgain commented on a change in pull request #7903: IGNITE-13025: add IgniteLimit logical node

Posted by GitBox <gi...@apache.org>.
tledkov-gridgain commented on a change in pull request #7903:
URL: https://github.com/apache/ignite/pull/7903#discussion_r443547808



##########
File path: modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/exec/rel/LimitNode.java
##########
@@ -0,0 +1,185 @@
+/*
+ * 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.ignite.internal.processors.query.calcite.exec.rel;
+
+import java.util.function.Supplier;
+import org.apache.ignite.internal.processors.query.IgniteSQLException;
+import org.apache.ignite.internal.processors.query.calcite.exec.ExecutionContext;
+import org.apache.ignite.internal.util.typedef.F;
+
+/**
+ *
+ */
+public class LimitNode<Row> extends AbstractNode<Row> implements SingleNode<Row>, Downstream<Row> {
+    /** */
+    private static final int NOT_READY = -1;
+
+    /** */
+    private static final int LIMIT_NOT_SET = -2;
+
+    /** */
+    private final Supplier<Integer> offsetSup;
+
+    /** */
+    private final Supplier<Integer> limitSup;
+
+    /** */
+    private int offset = NOT_READY;
+
+    /** */
+    private int limit = NOT_READY;
+
+    /** */
+    private int requested;
+
+    /** */
+    private int rowNum;
+
+    /** */
+    private int waiting;
+
+    /** */
+    boolean ended;
+
+    /**
+     * @param ctx Execution context.
+     * @param offsetSup Offset parameter supplier.
+     * @param limitSup Limit parameter supplier.
+     */
+    public LimitNode(
+        ExecutionContext<Row> ctx,
+        Supplier<Integer> offsetSup,
+        Supplier<Integer> limitSup) {
+        super(ctx);
+
+        this.offsetSup = offsetSup;
+        this.limitSup = limitSup;
+    }
+
+    /** {@inheritDoc} */
+    @Override public void request(int rowsCnt) {
+        checkThread();
+
+        assert !F.isEmpty(sources) && sources.size() == 1;
+        assert rowsCnt > 0 && requested == 0;
+
+        requested = rowsCnt;
+
+        // Initialize offset / limit.
+        if (offset == NOT_READY && limit == NOT_READY) {
+            if (offsetSup != null) {
+                offset = offsetSup.get();
+
+                if (offset < 0)
+                    onError(new IgniteSQLException("Invalid query offset: " + offset));
+            }
+            else
+                offset = 0;
+
+            if (limitSup != null) {
+                limit = limitSup.get();
+
+                if (limit < 0)
+                    onError(new IgniteSQLException("Invalid query limit: " + limit));
+            }
+            else
+                limit = LIMIT_NOT_SET;
+        }
+
+        request0(requested);
+    }
+
+    /**
+     * Process request (some parameters may not yet be calculated).
+     */
+    private void request0(int rowsCnt) {
+        if (limit == 0 || limit > 0 && rowNum >= limit + offset) {
+            end();
+
+            return;
+        }
+
+        int req = rowsCnt;
+
+        if (rowNum == 0 && offset > 0)
+            req += offset;
+
+        if (limit > 0 && rowNum + req > limit + offset)
+            req = limit + offset - rowNum;
+
+        waiting = req;
+
+        F.first(sources).request(req);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void push(Row row) {
+        checkThread();
+
+        assert downstream != null;
+
+        waiting--;
+
+        if (!ended && rowNum >= offset) {
+            requested--;
+
+            downstream.push(row);
+        }
+
+        rowNum++;
+
+        if (requested > 0 && limit > 0 && rowNum >= limit + offset)
+            end();

Review comment:
       Good point. Fixed




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [ignite] rkondakov commented on a change in pull request #7903: IGNITE-13025: add IgniteLimit logical node

Posted by GitBox <gi...@apache.org>.
rkondakov commented on a change in pull request #7903:
URL: https://github.com/apache/ignite/pull/7903#discussion_r436019830



##########
File path: modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/exec/exp/ExpressionFactoryImpl.java
##########
@@ -186,6 +193,29 @@ else if (collation.getFieldCollations().size() == 1)
         return SCALAR_CACHE.computeIfAbsent(digest(nodes, type), k -> compile(nodes, type));
     }
 
+    /** {@inheritDoc} */
+    @Override public <T> Supplier<CompletableFuture<T>> execute(RexNode node) {

Review comment:
       Can't we return just a value here? Why do we need a) Supplier b) Future?

##########
File path: modules/calcite/src/test/java/org/apache/ignite/internal/processors/query/calcite/LimitOffsetTest.java
##########
@@ -0,0 +1,154 @@
+/*
+ * 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.ignite.internal.processors.query.calcite;
+
+import java.util.List;
+import org.apache.ignite.Ignite;
+import org.apache.ignite.IgniteCache;
+import org.apache.ignite.cache.CacheMode;
+import org.apache.ignite.cache.QueryEntity;
+import org.apache.ignite.cache.query.FieldsQueryCursor;
+import org.apache.ignite.configuration.CacheConfiguration;
+import org.apache.ignite.internal.processors.query.QueryEngine;
+import org.apache.ignite.internal.processors.query.calcite.util.Commons;
+import org.apache.ignite.internal.util.typedef.X;
+import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
+import org.junit.Test;
+
+import static java.util.Collections.singletonList;
+
+/**
+ * Limit / offset tests.
+ */
+public class LimitOffsetTest extends GridCommonAbstractTest {
+    /** */
+    private static final int ROWS = 100;
+
+    /** {@inheritDoc} */
+    @Override protected void beforeTestsStarted() throws Exception {
+        Ignite grid = startGrids(2);
+
+        QueryEntity e = new QueryEntity()
+            .setTableName("Test")
+            .setKeyType(Integer.class.getName())
+            .setValueType(String.class.getName())
+            .setKeyFieldName("id")
+            .setValueFieldName("val")
+            .addQueryField("id", Integer.class.getName(), null)
+            .addQueryField("val", String.class.getName(), null);
+
+        CacheConfiguration<Integer, String> ccfg = cacheConfiguration(e);
+
+        IgniteCache<Integer, String> cache = grid.createCache(ccfg);
+
+        for (int i = 0; i < ROWS; ++i)
+            cache.put(i, "val_" + i);
+    }
+
+    /** */
+    private CacheConfiguration cacheConfiguration(QueryEntity ent) {
+        return new CacheConfiguration<>(ent.getTableName())
+            .setCacheMode(CacheMode.PARTITIONED)
+            .setBackups(1)
+            .setQueryEntities(singletonList(ent))
+            .setSqlSchema("PUBLIC");
+    }
+
+    /**
+     *
+     */
+    @Test
+    public void testLimitOffset() {
+        int[] limits = {-1, 0, 10, ROWS / 2 - 1, ROWS / 2, ROWS / 2 + 1, ROWS - 1, ROWS};
+        int[] offsets = {-1, 0, 10, ROWS / 2 - 1, ROWS / 2, ROWS / 2 + 1, ROWS - 1, ROWS};
+
+        for (int lim : limits) {
+            for (int off : offsets) {
+                log.info("+++ Check [limit=" + lim + ", off=" + off + ']');
+
+                checkQuery(lim, off, false, false);
+                checkQuery(lim, off, true, false);
+                checkQuery(lim, off, false, true);
+                checkQuery(lim, off, true, true);
+            }
+        }
+    }
+
+    /**
+     * Check query with specified limit and offset (or without its when the arguments are negative),
+     *
+     * @param lim Limit.
+     * @param off Offset.
+     * @param param If {@code false} place limit/offset as literals. Otherwise they are plase as parameters.
+     * @param sorted Use sorted query (adds ORDER BY).
+     */
+    void checkQuery(int lim, int off, boolean param, boolean sorted) {
+        QueryEngine engine = Commons.lookupComponent(grid(0).context(), QueryEngine.class);
+
+        String sql = createSql(lim, off, false, false);
+
+        log.info("SQL: " + sql);
+
+        List<FieldsQueryCursor<List<?>>> cursors =
+            engine.query(null, "PUBLIC", sql, param ? new Object[]{off, lim} : X.EMPTY_OBJECT_ARRAY);
+
+        List<List<?>> res = cursors.get(0).getAll();
+
+        assertEquals("Invalid results size. [limit=" + lim + ", off=" + off + ", res=" + res.size() + ']',
+            expectedSize(lim, off), res.size());
+    }
+
+    /**
+     * Calculates expected result set size by limit and offset.
+     */
+    private int expectedSize(int lim, int off) {
+        if (off < 0)

Review comment:
       Should we throw an exception when limit or offset is negative? Or it's a valid value?

##########
File path: modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/exec/LogicalRelImplementor.java
##########
@@ -17,7 +17,10 @@
 
 package org.apache.ignite.internal.processors.query.calcite.exec;
 
+import java.math.BigDecimal;
 import java.util.List;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.Future;

Review comment:
       Unused import.

##########
File path: modules/calcite/src/test/java/org/apache/ignite/internal/processors/query/calcite/LimitOffsetTest.java
##########
@@ -0,0 +1,154 @@
+/*
+ * 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.ignite.internal.processors.query.calcite;
+
+import java.util.List;
+import org.apache.ignite.Ignite;
+import org.apache.ignite.IgniteCache;
+import org.apache.ignite.cache.CacheMode;
+import org.apache.ignite.cache.QueryEntity;
+import org.apache.ignite.cache.query.FieldsQueryCursor;
+import org.apache.ignite.configuration.CacheConfiguration;
+import org.apache.ignite.internal.processors.query.QueryEngine;
+import org.apache.ignite.internal.processors.query.calcite.util.Commons;
+import org.apache.ignite.internal.util.typedef.X;
+import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
+import org.junit.Test;
+
+import static java.util.Collections.singletonList;
+
+/**
+ * Limit / offset tests.
+ */
+public class LimitOffsetTest extends GridCommonAbstractTest {
+    /** */
+    private static final int ROWS = 100;
+
+    /** {@inheritDoc} */
+    @Override protected void beforeTestsStarted() throws Exception {
+        Ignite grid = startGrids(2);
+
+        QueryEntity e = new QueryEntity()
+            .setTableName("Test")
+            .setKeyType(Integer.class.getName())
+            .setValueType(String.class.getName())
+            .setKeyFieldName("id")
+            .setValueFieldName("val")
+            .addQueryField("id", Integer.class.getName(), null)
+            .addQueryField("val", String.class.getName(), null);
+
+        CacheConfiguration<Integer, String> ccfg = cacheConfiguration(e);
+
+        IgniteCache<Integer, String> cache = grid.createCache(ccfg);
+
+        for (int i = 0; i < ROWS; ++i)
+            cache.put(i, "val_" + i);
+    }
+
+    /** */
+    private CacheConfiguration cacheConfiguration(QueryEntity ent) {
+        return new CacheConfiguration<>(ent.getTableName())
+            .setCacheMode(CacheMode.PARTITIONED)
+            .setBackups(1)
+            .setQueryEntities(singletonList(ent))
+            .setSqlSchema("PUBLIC");
+    }
+
+    /**
+     *
+     */
+    @Test
+    public void testLimitOffset() {
+        int[] limits = {-1, 0, 10, ROWS / 2 - 1, ROWS / 2, ROWS / 2 + 1, ROWS - 1, ROWS};
+        int[] offsets = {-1, 0, 10, ROWS / 2 - 1, ROWS / 2, ROWS / 2 + 1, ROWS - 1, ROWS};
+
+        for (int lim : limits) {
+            for (int off : offsets) {
+                log.info("+++ Check [limit=" + lim + ", off=" + off + ']');
+
+                checkQuery(lim, off, false, false);
+                checkQuery(lim, off, true, false);
+                checkQuery(lim, off, false, true);
+                checkQuery(lim, off, true, true);
+            }
+        }
+    }
+
+    /**
+     * Check query with specified limit and offset (or without its when the arguments are negative),
+     *
+     * @param lim Limit.
+     * @param off Offset.
+     * @param param If {@code false} place limit/offset as literals. Otherwise they are plase as parameters.
+     * @param sorted Use sorted query (adds ORDER BY).
+     */
+    void checkQuery(int lim, int off, boolean param, boolean sorted) {
+        QueryEngine engine = Commons.lookupComponent(grid(0).context(), QueryEngine.class);
+
+        String sql = createSql(lim, off, false, false);

Review comment:
       `param, sorted ` instead of `false, false`?




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org