DefaultCursor.java

  1. /*
  2.  *    Copyright 2009-2023 the original author or authors.
  3.  *
  4.  *    Licensed under the Apache License, Version 2.0 (the "License");
  5.  *    you may not use this file except in compliance with the License.
  6.  *    You may obtain a copy of the License at
  7.  *
  8.  *       https://www.apache.org/licenses/LICENSE-2.0
  9.  *
  10.  *    Unless required by applicable law or agreed to in writing, software
  11.  *    distributed under the License is distributed on an "AS IS" BASIS,
  12.  *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13.  *    See the License for the specific language governing permissions and
  14.  *    limitations under the License.
  15.  */
  16. package org.apache.ibatis.cursor.defaults;

  17. import java.sql.ResultSet;
  18. import java.sql.SQLException;
  19. import java.util.Iterator;
  20. import java.util.NoSuchElementException;

  21. import org.apache.ibatis.cursor.Cursor;
  22. import org.apache.ibatis.executor.resultset.DefaultResultSetHandler;
  23. import org.apache.ibatis.executor.resultset.ResultSetWrapper;
  24. import org.apache.ibatis.mapping.ResultMap;
  25. import org.apache.ibatis.session.ResultContext;
  26. import org.apache.ibatis.session.ResultHandler;
  27. import org.apache.ibatis.session.RowBounds;

  28. /**
  29.  * This is the default implementation of a MyBatis Cursor. This implementation is not thread safe.
  30.  *
  31.  * @author Guillaume Darmont / guillaume@dropinocean.com
  32.  */
  33. public class DefaultCursor<T> implements Cursor<T> {

  34.   // ResultSetHandler stuff
  35.   private final DefaultResultSetHandler resultSetHandler;
  36.   private final ResultMap resultMap;
  37.   private final ResultSetWrapper rsw;
  38.   private final RowBounds rowBounds;
  39.   protected final ObjectWrapperResultHandler<T> objectWrapperResultHandler = new ObjectWrapperResultHandler<>();

  40.   private final CursorIterator cursorIterator = new CursorIterator();
  41.   private boolean iteratorRetrieved;

  42.   private CursorStatus status = CursorStatus.CREATED;
  43.   private int indexWithRowBound = -1;

  44.   private enum CursorStatus {

  45.     /**
  46.      * A freshly created cursor, database ResultSet consuming has not started.
  47.      */
  48.     CREATED,
  49.     /**
  50.      * A cursor currently in use, database ResultSet consuming has started.
  51.      */
  52.     OPEN,
  53.     /**
  54.      * A closed cursor, not fully consumed.
  55.      */
  56.     CLOSED,
  57.     /**
  58.      * A fully consumed cursor, a consumed cursor is always closed.
  59.      */
  60.     CONSUMED
  61.   }

  62.   public DefaultCursor(DefaultResultSetHandler resultSetHandler, ResultMap resultMap, ResultSetWrapper rsw,
  63.       RowBounds rowBounds) {
  64.     this.resultSetHandler = resultSetHandler;
  65.     this.resultMap = resultMap;
  66.     this.rsw = rsw;
  67.     this.rowBounds = rowBounds;
  68.   }

  69.   @Override
  70.   public boolean isOpen() {
  71.     return status == CursorStatus.OPEN;
  72.   }

  73.   @Override
  74.   public boolean isConsumed() {
  75.     return status == CursorStatus.CONSUMED;
  76.   }

  77.   @Override
  78.   public int getCurrentIndex() {
  79.     return rowBounds.getOffset() + cursorIterator.iteratorIndex;
  80.   }

  81.   @Override
  82.   public Iterator<T> iterator() {
  83.     if (iteratorRetrieved) {
  84.       throw new IllegalStateException("Cannot open more than one iterator on a Cursor");
  85.     }
  86.     if (isClosed()) {
  87.       throw new IllegalStateException("A Cursor is already closed.");
  88.     }
  89.     iteratorRetrieved = true;
  90.     return cursorIterator;
  91.   }

  92.   @Override
  93.   public void close() {
  94.     if (isClosed()) {
  95.       return;
  96.     }

  97.     ResultSet rs = rsw.getResultSet();
  98.     try {
  99.       if (rs != null) {
  100.         rs.close();
  101.       }
  102.     } catch (SQLException e) {
  103.       // ignore
  104.     } finally {
  105.       status = CursorStatus.CLOSED;
  106.     }
  107.   }

  108.   protected T fetchNextUsingRowBound() {
  109.     T result = fetchNextObjectFromDatabase();
  110.     while (objectWrapperResultHandler.fetched && indexWithRowBound < rowBounds.getOffset()) {
  111.       result = fetchNextObjectFromDatabase();
  112.     }
  113.     return result;
  114.   }

  115.   protected T fetchNextObjectFromDatabase() {
  116.     if (isClosed()) {
  117.       return null;
  118.     }

  119.     try {
  120.       objectWrapperResultHandler.fetched = false;
  121.       status = CursorStatus.OPEN;
  122.       if (!rsw.getResultSet().isClosed()) {
  123.         resultSetHandler.handleRowValues(rsw, resultMap, objectWrapperResultHandler, RowBounds.DEFAULT, null);
  124.       }
  125.     } catch (SQLException e) {
  126.       throw new RuntimeException(e);
  127.     }

  128.     T next = objectWrapperResultHandler.result;
  129.     if (objectWrapperResultHandler.fetched) {
  130.       indexWithRowBound++;
  131.     }
  132.     // No more object or limit reached
  133.     if (!objectWrapperResultHandler.fetched || getReadItemsCount() == rowBounds.getOffset() + rowBounds.getLimit()) {
  134.       close();
  135.       status = CursorStatus.CONSUMED;
  136.     }
  137.     objectWrapperResultHandler.result = null;

  138.     return next;
  139.   }

  140.   private boolean isClosed() {
  141.     return status == CursorStatus.CLOSED || status == CursorStatus.CONSUMED;
  142.   }

  143.   private int getReadItemsCount() {
  144.     return indexWithRowBound + 1;
  145.   }

  146.   protected static class ObjectWrapperResultHandler<T> implements ResultHandler<T> {

  147.     protected T result;
  148.     protected boolean fetched;

  149.     @Override
  150.     public void handleResult(ResultContext<? extends T> context) {
  151.       this.result = context.getResultObject();
  152.       context.stop();
  153.       fetched = true;
  154.     }
  155.   }

  156.   protected class CursorIterator implements Iterator<T> {

  157.     /**
  158.      * Holder for the next object to be returned.
  159.      */
  160.     T object;

  161.     /**
  162.      * Index of objects returned using next(), and as such, visible to users.
  163.      */
  164.     int iteratorIndex = -1;

  165.     @Override
  166.     public boolean hasNext() {
  167.       if (!objectWrapperResultHandler.fetched) {
  168.         object = fetchNextUsingRowBound();
  169.       }
  170.       return objectWrapperResultHandler.fetched;
  171.     }

  172.     @Override
  173.     public T next() {
  174.       // Fill next with object fetched from hasNext()
  175.       T next = object;

  176.       if (!objectWrapperResultHandler.fetched) {
  177.         next = fetchNextUsingRowBound();
  178.       }

  179.       if (objectWrapperResultHandler.fetched) {
  180.         objectWrapperResultHandler.fetched = false;
  181.         object = null;
  182.         iteratorIndex++;
  183.         return next;
  184.       }
  185.       throw new NoSuchElementException();
  186.     }

  187.     @Override
  188.     public void remove() {
  189.       throw new UnsupportedOperationException("Cannot remove element from Cursor");
  190.     }
  191.   }
  192. }