View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *     http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  
18  package org.apache.shardingsphere.sharding.merge.dql.pagination;
19  
20  import org.apache.shardingsphere.infra.merge.result.MergedResult;
21  import org.apache.shardingsphere.infra.merge.result.impl.decorator.DecoratorMergedResult;
22  import org.apache.shardingsphere.infra.binder.context.segment.select.pagination.PaginationContext;
23  
24  import java.sql.SQLException;
25  
26  /**
27   * Decorator merged result for top and row number pagination.
28   */
29  public final class TopAndRowNumberDecoratorMergedResult extends DecoratorMergedResult {
30      
31      private final PaginationContext paginationContext;
32      
33      private final boolean skipAll;
34      
35      private long rowNumber;
36      
37      public TopAndRowNumberDecoratorMergedResult(final MergedResult mergedResult, final PaginationContext paginationContext) throws SQLException {
38          super(mergedResult);
39          this.paginationContext = paginationContext;
40          skipAll = skipOffset();
41      }
42      
43      private boolean skipOffset() throws SQLException {
44          long end = paginationContext.getActualOffset();
45          for (int i = 0; i < end; i++) {
46              if (!getMergedResult().next()) {
47                  return true;
48              }
49          }
50          rowNumber = end + 1;
51          return false;
52      }
53      
54      @Override
55      public boolean next() throws SQLException {
56          if (skipAll) {
57              return false;
58          }
59          if (!paginationContext.getActualRowCount().isPresent()) {
60              return getMergedResult().next();
61          }
62          return rowNumber++ <= paginationContext.getActualRowCount().get() && getMergedResult().next();
63      }
64  }