/** Build and execute the row count query. */
  public <T> int findRowCount(OrmQueryRequest<T> request) {

    CQueryRowCount rcQuery = queryBuilder.buildRowCountQuery(request);
    try {

      int rowCount = rcQuery.findRowCount();

      if (request.isLogSql()) {
        String logSql = rcQuery.getGeneratedSql();
        if (TransactionManager.SQL_LOGGER.isTraceEnabled()) {
          logSql += "; --bind(" + rcQuery.getBindLog() + ")";
        }
        request.logSql(logSql);
      }

      if (request.isLogSummary()) {
        request.getTransaction().logSummary(rcQuery.getSummary());
      }

      if (request.getQuery().isFutureFetch()) {
        logger.debug("Future findRowCount completed!");
        request.getTransaction().end();
      }

      return rowCount;

    } catch (SQLException e) {
      throw CQuery.createPersistenceException(
          e, request.getTransaction(), rcQuery.getBindLog(), rcQuery.getGeneratedSql());
    }
  }
  /** Build and execute the find Id's query. */
  public <T> BeanIdList findIds(OrmQueryRequest<T> request) {

    CQueryFetchIds rcQuery = queryBuilder.buildFetchIdsQuery(request);
    try {

      BeanIdList list = rcQuery.findIds();

      if (request.isLogSql()) {
        String logSql = rcQuery.getGeneratedSql();
        if (TransactionManager.SQL_LOGGER.isTraceEnabled()) {
          logSql += "; --bind(" + rcQuery.getBindLog() + ")";
        }
        request.logSql(logSql);
      }

      if (request.isLogSummary()) {
        request.getTransaction().logSummary(rcQuery.getSummary());
      }

      if (!list.isFetchingInBackground() && request.getQuery().isFutureFetch()) {
        // end the transaction for futureFindIds (it had it's own one)
        logger.debug("Future findIds completed!");
        request.getTransaction().end();
      }

      return list;

    } catch (SQLException e) {
      throw CQuery.createPersistenceException(
          e, request.getTransaction(), rcQuery.getBindLog(), rcQuery.getGeneratedSql());
    }
  }
  /** Find and return a single bean using its unique id. */
  public <T> T find(OrmQueryRequest<T> request) {

    T bean = null;

    CQuery<T> cquery = queryBuilder.buildQuery(request);

    try {
      cquery.prepareBindExecuteQuery();

      if (request.isLogSql()) {
        logSql(cquery);
      }

      if (cquery.readBean()) {
        bean = cquery.getLoadedBean();
      }

      if (request.isLogSummary()) {
        logFindBeanSummary(cquery);
      }

      request.executeSecondaryQueries(defaultSecondaryQueryBatchSize);

      return bean;

    } catch (SQLException e) {
      throw cquery.createPersistenceException(e);

    } finally {
      cquery.close();
    }
  }
  /**
   * Read many beans using an iterator (except you need to close() the iterator when you have
   * finished).
   */
  public <T> QueryIterator<T> findIterate(OrmQueryRequest<T> request) {

    CQuery<T> cquery = queryBuilder.buildQuery(request);
    request.setCancelableQuery(cquery);

    try {

      if (!cquery.prepareBindExecuteQuery()) {
        // query has been cancelled already
        logger.trace("Future fetch already cancelled");
        return null;
      }

      if (request.isLogSql()) {
        logSql(cquery);
      }

      int iterateBufferSize =
          request.getSecondaryQueriesMinBatchSize(defaultSecondaryQueryBatchSize);

      QueryIterator<T> readIterate = cquery.readIterate(iterateBufferSize, request);

      if (request.isLogSummary()) {
        logFindManySummary(cquery);
      }

      return readIterate;

    } catch (SQLException e) {
      throw cquery.createPersistenceException(e);
    }
  }
  /** Find a list/map/set of beans. */
  public <T> BeanCollection<T> findMany(OrmQueryRequest<T> request) {

    // flag indicating whether we need to close the resources...
    boolean useBackgroundToContinueFetch = false;

    CQuery<T> cquery = queryBuilder.buildQuery(request);
    request.setCancelableQuery(cquery);

    try {
      if (!cquery.prepareBindExecuteQuery()) {
        // query has been cancelled already
        logger.trace("Future fetch already cancelled");
        return null;
      }

      if (request.isLogSql()) {
        logSql(cquery);
      }

      BeanCollection<T> beanCollection = cquery.readCollection();

      BeanCollectionTouched collectionTouched = request.getQuery().getBeanCollectionTouched();
      if (collectionTouched != null) {
        // register a listener that wants to be notified when the
        // bean collection is first used
        beanCollection.setBeanCollectionTouched(collectionTouched);
      }

      if (cquery.useBackgroundToContinueFetch()) {
        // stop the request from putting connection back into pool
        // before background fetching is finished.
        request.setBackgroundFetching();
        useBackgroundToContinueFetch = true;
        BackgroundFetch fetch = new BackgroundFetch(cquery);

        FutureTask<Integer> future = new FutureTask<Integer>(fetch);
        beanCollection.setBackgroundFetch(future);
        backgroundExecutor.execute(future);
      }

      if (request.isLogSummary()) {
        logFindManySummary(cquery);
      }

      request.executeSecondaryQueries(defaultSecondaryQueryBatchSize);

      return beanCollection;

    } catch (SQLException e) {
      throw cquery.createPersistenceException(e);

    } finally {
      if (useBackgroundToContinueFetch) {
        // left closing resources to BackgroundFetch...
      } else {
        if (cquery != null) {
          cquery.close();
        }
        if (request.getQuery().isFutureFetch()) {
          // end the transaction for futureFindIds
          // as it had it's own transaction
          logger.debug("Future fetch completed!");
          request.getTransaction().end();
        }
      }
    }
  }