ForwardResults.java

/*
** Module   : ForwardResults.java
** Abstract : Implementation of Results which wraps ScrollableResults, used for ResultSet.TYPE_FORWARD_ONLY
**
** Copyright (c) 2023-2024, Golden Code Development Corporation.
**
** -#- -I- --Date-- ---------------------------------------Description----------------------------------------
** 001 SR  20230713 Created initial version.
** 002 AL2 20231025 Added rowNumber to be stored internally.
** 003 AL2 20240906 Implemented get(forceOnlyId).
** 004 OM  20241128 Multi-tenant runtime support: selected the proper persistence context, eventually
**                  based on [sharedDb] parameter.
*/

/*
** This program is free software: you can redistribute it and/or modify
** it under the terms of the GNU Affero General Public License as
** published by the Free Software Foundation, either version 3 of the
** License, or (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
** GNU Affero General Public License for more details.
**
** You may find a copy of the GNU Affero GPL version 3 at the following
** location: https://www.gnu.org/licenses/agpl-3.0.en.html
** 
** Additional terms under GNU Affero GPL version 3 section 7:
** 
**   Under Section 7 of the GNU Affero GPL version 3, the following additional
**   terms apply to the works covered under the License.  These additional terms
**   are non-permissive additional terms allowed under Section 7 of the GNU
**   Affero GPL version 3 and may not be removed by you.
** 
**   0. Attribution Requirement.
** 
**     You must preserve all legal notices or author attributions in the covered
**     work or Appropriate Legal Notices displayed by works containing the covered
**     work.  You may not remove from the covered work any author or developer
**     credit already included within the covered work.
** 
**   1. No License To Use Trademarks.
** 
**     This license does not grant any license or rights to use the trademarks
**     Golden Code, FWD, any Golden Code or FWD logo, or any other trademarks
**     of Golden Code Development Corporation. You are not authorized to use the
**     name Golden Code, FWD, or the names of any author or contributor, for
**     publicity purposes without written authorization.
** 
**   2. No Misrepresentation of Affiliation.
** 
**     You may not represent yourself as Golden Code Development Corporation or FWD.
** 
**     You may not represent yourself for publicity purposes as associated with
**     Golden Code Development Corporation, FWD, or any author or contributor to
**     the covered work, without written authorization.
** 
**   3. No Misrepresentation of Source or Origin.
** 
**     You may not represent the covered work as solely your work.  All modified
**     versions of the covered work must be marked in a reasonable way to make it
**     clear that the modified work is not originating from Golden Code Development
**     Corporation or FWD.  All modified versions must contain the notices of
**     attribution required in this license.
*/

package com.goldencode.p2j.persist;

import java.util.logging.*;
import com.goldencode.p2j.persist.orm.*;
import com.goldencode.p2j.util.logging.*;

/**
 * A simple, forward only implementation of the {@code Results} interface, which offers a thin layer
 * around the internal, {@code ScrollableResults} object provided by the query.
 */
final class ForwardResults
implements Results
{
   /** Logger */
   private static final CentralLogger LOG = CentralLogger.get(ForwardResults.class.getName());
   
   /** Scrollable result set;  primary keys or {@code Record}s */
   private final ScrollableResults<Object> results;
   
   /** Persistence object which provided the underlying ScrollableResults */
   private final Persistence persistence;
   
   /** 
    * The {@link Persistence} context. Only used at cleanup time when the getter is not accessible
    * any more.
    */
   private final Persistence.Context persistenceContext;
   
   /** Track closed state of the {@link #results}. */
   private boolean closed = false;
   
   /** Flag to check if the result set is empty */
   private boolean hasResults = true;
   
   /** Flag to check if the cursor is after last row */
   private boolean isAfterLast = false;
   
   /** Cache the row number */
   private int rowNumber = -1;
   
   
   /**
    * Construct an instance of this object from a scrollable result set
    * provided by query execution.
    *
    * @param   persistence
    *          The associated persistence service object.
    * @param   results
    *          Scrollable result set generated by the query.
    */
   ForwardResults(Persistence persistence, ScrollableResults<Object> results)
   throws PersistenceException
   {
      this.results = results;
      this.persistence = persistence;
      this.persistenceContext = persistence.getContext(results.isSharedTenantDatabase());
      persistenceContext.useSession();
   }
   
   /**
    * Move cursor to the first result row only if the cursor is behind it.
    *
    * @return  <code>true</code> if the cursor is already first or behind it.
    */
   public boolean first()
   {
      if (!hasResults)
      {
         return false;
      }
      
      int rn = getRowNumber();
      if (isAfterLast || rn > 0)
      {
         LOG.log(Level.SEVERE, "Cannot call first in FORWARD_ONLY mode if the record is after first");
         return false;
      }
      
      if (rn == 0)
      {
         return true;
      }
      
      if (rn == -1)
      {
         return next();
      }
      
      LOG.log(Level.SEVERE, "Cannot call first in FORWARD_ONLY mode if the record is after first");
      return false;  
   }
   
   /**
    * Move cursor to the last result row.
    *
    * @return  <code>true</code> if there are any results.
    */
   public boolean last()
   {
      if (!hasResults)
      {
         return false;
      }
      
      if (isLast())
      {
         return true;
      }
      
      while (!isLast() && next());
      
      if (!isLast())
      {
         hasResults = false;
         isAfterLast = true;
         rowNumber = -1;
         return false;
      }
      
      return true;
   }
   
   /**
    * Move cursor to the next result row.
    *
    * @return  <code>true</code> if there is a result under the cursor.
    */
   public boolean next()
   {
      if (isAfterLast)
      {
         return false;
      }
      
      if (!hasResults || isLast())
      {
         isAfterLast = true;
         rowNumber = -1;
         return false;
      }
      
      boolean nxt = results.next();
      if (!nxt)
      {
         hasResults = false;
         isAfterLast = true;
         rowNumber = -1;
      }
      else
      {
         rowNumber++;
      }

      return nxt;
   }
   
   /**
    * Should move cursor to the previous result row, but it cannot be done in FORWARD_ONLY mode.
    *
    * @return  <code>false</code> .
    */
   public boolean previous()
   {
      LOG.log(Level.SEVERE, "Cannot call previous in FORWARD_ONLY mode");
      return false;
   }
   
   /**
    * Is the cursor on the first row in the result set?
    *
    * @return  <code>true</code> if the cursor is on the first row.
    */
   public boolean isFirst()
   {
      return rowNumber == 0;
   }
   
   /**
    * Is the cursor on the last row in the result set?
    *
    * @return  <code>true</code> if the cursor is on the last row.
    */
   public boolean isLast()
   {
      if (!hasResults || isAfterLast || rowNumber == -1)
      {
         return false;
      }
      
      return results.isLast();
   }
   
   /**
    * Returns the row at the current position. It can be either only an array of PK or
    * an array of DMOs. 
    * 
    * @param   forceOnlyId
    *          Indicates whether it's only the primary keys that must be returned, 
    *          or original data found is returned (either PK or DMO).
    *
    * @return  Object array or {@code null}.
    */
   public Object[] get(boolean forceOnlyId)
   {
      if (!hasResults || isAfterLast || rowNumber == -1)
      {
         return null;
      }
      
      return results.get(forceOnlyId);
   }
   
   /**
    * Get the object at the current result row, at the specified column.
    *
    * @param   column
    *          Zero-based index column of the desired object.
    *
    * @return  Object at <code>column</code> or <code>null</code>.
    */
   public Object get(int column)
   {
      if (!hasResults || isAfterLast || rowNumber == -1)
      {
         return null;
      }
      
      Object[] row = get();
      return (row != null) ? row[column] : null;
   }
   
   /**
    * Get the primary key ID at the current result row, at the specified
    * column.
    *
    * @param   column
    *          Zero-based index column of the desired ID.
    *
    * @return  ID of the record or <code>null</code>.
    */
   public Long getID(int column)
   {
      if (!hasResults || isAfterLast || rowNumber == -1)
      {
         return null;
      }
      
      Object result = get(column);
      if (result instanceof Record)
      {
         return ((Record) result).primaryKey();
      }
      
      return (Long) result;
   }
   
   /**
    * Get the row number currently under the cursor.
    *
    * @return  Zero-based index of the current row, or <code>-1</code>
    *          if the cursor is not currently on a result.
    */
   public int getRowNumber()
   {
      if (!hasResults || isAfterLast || rowNumber < 0)
      {
         return -1;
      }
      
      return rowNumber;
   }
   
   /**
    * Set the cursor at the row number.
    *
    * @param   row
    *          Zero-based index of the row to be set as the current row.
    *
    * @return  <code>true</code> if the row number is after the current position and before last;  
    *          else <code>false</code>.
    */
   public boolean setRowNumber(int row)
   {
      if (!hasResults || isAfterLast)
      {
         LOG.log(Level.SEVERE, "Cannot call setRowNumber on empty or "
                  + "fully iterated results in FORWARD_ONLY mode");
         return false;
      }
      
      int nrOfSteps = row - rowNumber;
      if (nrOfSteps < 0)
      {
         LOG.log(Level.SEVERE, "Cannot call setRowNumber if the row is "
                  + "smaller than the current position in FORWARD_ONLY mode");
         return false;
      }
      
      return scroll(nrOfSteps);
   }
   
   /**
    * Scroll the cursor ahead by the specified number of rows.
    *
    * @param   rows
    *          Number of rows to jump ahead or back.
    *
    * @return  <code>true</code> if there is a row at the new location;
    *          else <code>false</code>.
    */
   public boolean scroll(int rows)
   {
      if (rows < 0)
      {
         LOG.log(Level.SEVERE, "Cannot call scroll with negative number of rows in FORWARD_ONLY mode");
         return false;
      }
      
      for (int i = 0; i < rows; i++)
      {
         if (!next())
         {
            return false;
         }
      }
      return true;
   }
   
   /**
    * Should reset the cursor to its natural starting position, before the first
    * result row, but it cannot be done in FORWARD_ONLY mode.
    */
   public void reset()
   {
      LOG.log(Level.SEVERE, "Cannot call reset in FORWARD_ONLY mode");
   }
   
   /**
    * Invoked when the current Hibernate session is about to close.  Gives
    * the implementation an opportunity to perform appropriate processing in
    * response to this event.
    */
   public void sessionClosing()
   {
      cleanup();
   }
   
   /**
    * Close the wrapped {@code ScrollableResults} object.
    */
   public void cleanup()
   {
      if (closed)
      {
         return;
      }
      
      try
      {
         results.close();
      }
      catch (PersistenceException exc)
      {
         DBUtils.handleException(persistence.getDatabase(Persistence.PRIVATE_CTX), exc);
         
         // Non-critical operation;  logging the error is sufficient.
         if (LOG.isLoggable(Level.FINE))
         {
            LOG.log(Level.FINE, exc.getMessage(), exc);
         }
         else if (LOG.isLoggable(Level.WARNING))
         {
            LOG.log(Level.WARNING, exc.getMessage());
         }
      }
      finally
      {
         closed = true;
         persistenceContext.releaseSession();
      }
   }
}