# OrderedRowStructure.java

    /*
    ** Module   : OrderedRowStructure.java
    ** Abstract : Defines a row structure in a query. This time, the fields should be ordered
    **
    ** Copyright (c) 2023, Golden Code Development Corporation.
    **
    ** -#- -I- --Date-- ----------------------------------------Description---------------------------------------
    ** 001 AL2 20231128 Initial version.
    **     AL2 20231211 Recieve the DMO meta directly in the constructor. Refactored iterator creation.
    **     AL2 20231212 Use dmoMeta directly, without getter.
    **     AL2 20231212 Fixed method used to retrieve propetry index.
    */

    /*
    ** 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.orm;

    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.util.*;

    import com.goldencode.p2j.persist.*;

    /**
     * The fastest implementation of incomplete row structure. This presumes that the
     * fields are hydrated in a convenient order (the same order they appear in the
     * data array). This way, we can store a bitset to mark which fields exactly we
     * are going to hydrate.
     */
    public class OrderedRowStructure
    extends AbstractRowStructure
    {
       /** The collected fields for select query */
       private BitSet fields;

       /** The last field (not recid or multiplex) that was appended. */
       private int lastFieldSet = -1;

       /** The number of SQL columns that are needed to do the hydration of this structure */
       private int count = 0;

       /** The recid property, if any appended */
       private Property recidProp;

       /** The multiplex property, if any appended */
       private Property multiplexProp;

       /**
        * Create a new instance.
        *
        * @param    dmoMeta
        *           The DMO metadata of the underlying DMO for this structure.
        */
       public OrderedRowStructure(DmoMeta dmoMeta)
       {
          super(dmoMeta);
       }

       /**
        * Append the recid to the row structure.
        *
        * @param   recid
        *          The recid property to be appended to the structure.
        *
        * @return  {@code true} if adding the recid to the row structure succeeded
        *          If there is some invariant on the structure, adding props may fail.
        */
       @Override
       public boolean addRecid(Property recid)
       {
          if (this.lastFieldSet >= 0 || this.multiplexProp != null || recidProp != null)
          {
             // if we already added the multiplex or a field, adding the recid is too late
             // this will also fail if we add the recid more than once
             return false;
          }

          this.recidProp = recid;
          this.count++;
          return true;
       }

       /**
        * Append the multiplex to the row structure.
        *
        * @param   multiplex
        *          The multiplex property to be appended to the structure.
        *
        * @return  {@code true} if adding the multiplex to the row structure succeeded
        *          If there is some invariant on the structure, adding props may fail.
        */
       @Override
       public boolean addMultiplex(Property multiplex)
       {
          if (this.lastFieldSet >= 0 || multiplexProp != null)
          {
             // if we didn't set the recid already or we added a field,
             // adding the multiplex is too late or too early
             // also, if we already added the multiplex, we  invariant is violated
             return false;
          }

          this.multiplexProp = multiplex;
          this.count++;
          return true;
       }

       /**
        * Append a property to the row structure. This doesn't check if the property actually belongs to the
        * DMO class used for this structure.
        *
        * @param   prop
        *          The property to be appended to the structure.
        *
        * @return  {@code true} if adding the prop to the row structure succeeded
        *          If there is some invariant on the structure, adding props may fail.
        */
       @Override
       public boolean addProperty(Property prop)
       {
          if (super.addProperty(prop))
          {
             return true;
          }

          int fieldId = dmoMeta.recordMeta.getIndexOfProperty(prop.name);

          if (this.lastFieldSet >= fieldId)
          {
             // we are not setting the fields in order
             return false;
          }

          if (fields == null)
          {
             this.fields = new BitSet();
          }

          fields.set(fieldId);
          this.lastFieldSet = fieldId;
          this.count += getPropertyMeta()[fieldId].columnCount;
          return true;
       }

       /**
        * Retrieve the number of SQL fields that will be interpreted by this row structure. This is not the
        * same as the number of properties (e.g. datetime-tz consumes 2 SQL columns)
        *
        * @return   The number of SQL fields that are covered by this row structure.
        */
       @Override
       public int getCount()
       {
          return this.count;
       }

       /**
        * Retrieve an iterator to all properties in this structure, including the recid and multiplex.
        *
        * @return   An iterator to all properties in this structure, in order of their append.
        */
       @Override
       public Iterator<Property> getProps()
       {
          return new Iterator<Property>()
          {
             private int phase = ReservedProperty.ID_PRIMARY_KEY;

             @Override
             public boolean hasNext()
             {
                if (phase == ReservedProperty.ID_PRIMARY_KEY)
                {
                   if (recidProp != null)
                   {
                      return true;
                   }

                   phase = ReservedProperty.ID_MULTIPLEX;
                }

                if (phase == ReservedProperty.ID_MULTIPLEX)
                {
                   if (multiplexProp != null)
                   {
                      return true;
                   }

                   phase = fields == null ? -1 : fields.nextSetBit(0);
                }

                return phase != -1;
             }

             @Override
             public Property next()
             {
                if (!hasNext())
                {
                   throw new NoSuchElementException();
                }

                if (phase == ReservedProperty.ID_PRIMARY_KEY)
                {
                   if (recidProp == null)
                   {
                      throw new NoSuchElementException();
                   }

                   phase = ReservedProperty.ID_MULTIPLEX;
                   return recidProp;
                }

                if (phase == ReservedProperty.ID_MULTIPLEX)
                {
                   if (isTempTable() && multiplexProp == null)
                   {
                      throw new NoSuchElementException();
                   }

                   if (multiplexProp != null)
                   {
                      phase = fields == null ? -1 : fields.nextSetBit(0);
                      return multiplexProp;
                   }
                   else
                   {
                      phase = fields == null ? -1 : fields.nextSetBit(0);
                   }
                }

                if (phase == -1)
                {
                   throw new NoSuchElementException();
                }

                Property prop = getPropertyMeta()[phase].dmoProperty;
                phase = fields == null ? -1 : fields.nextSetBit(phase + 1);
                return prop;
             }

          };
       }

       /**
        * Hydrate a record knowing that the result-set selected some properties in a proper order.
        * Presuming an implicit, order, we can simply iterate the bitset and hydrate on the indexes
        * specified there.
        *
        * @param   session
        *          The underlying session that generated the result-set. It is used only to emit
        *          load SQLs for the non-expanded extents. If this is {@code null}, the non-expanded
        *          extents will be skipped.
        * @param   resultSet
        *          The result-set that provides the low-level data that should be hydrated into
        *          the record.
        * @param   rsOffset
        *          The offset where the DMO starts. This is the case for queries that had joins,
        *          so the current record may not start at index 1.
        * @param   r
        *          The record to be hydrated.
        *
        * @return  The next rsOffset, from where the next DMO in the result-set will start (if any).
        *
        * @throws  PersistenceException
        *          thrown when hydrating extents fails (as it requires extra SQL queries to be run).
        * @throws  SQLException
        *          throw when failing to hydrate from the result-set.
        */
       @Override
       public int hydrate(Session session, ResultSet resultSet, int rsOffset, BaseRecord r)
       throws PersistenceException,
              SQLException
       {
          if (this.recidProp != null)
          {
             r.primaryKey(resultSet.getLong(rsOffset++));
             if (count == 1)
             {
                // optimize projection queries
                return rsOffset;
             }
          }

          if (this.multiplexProp != null)
          {
             ((TempRecord) r)._multiplex(resultSet.getInt(rsOffset++));
          }

          if (fields != null)
          {
             for (int i = fields.nextSetBit(0); i != -1; i = fields.nextSetBit(i + 1))
             {
                rsOffset += r.readProperty(i, resultSet, rsOffset);
             }
          }

          if (hasExtents && session != null)
          {
             // this is incomplete, so set the record offset to -1
             hydrateExtents(session, r, -1);
          }

          return rsOffset;
       }
    }