# UnorderedRowStructure.java

    /*
    ** Module   : UnorderedRowStructure.java
    ** Abstract : Defines a row structure in a query. This time, the fields can have an arbitrary order.
    **
    ** Copyright (c) 2023, Golden Code Development Corporation.
    **
    ** -#- -I- --Date-- ----------------------------------------Description---------------------------------------
    ** 001 AL2 20231128 Initial version.
    **     AL2 20231212 Use dmoMeta directly, without getter.
    */

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

    /**
     * Slowest kind of row structure that is able to hdyrate fields in an arbitrary order.
     * This is not necessary a bottle-neck, but is uses a list instead of a faster data structure,
     * like Bitset. This kind of structure shouldn't be necessarily used internally by FWD, as we
     * can earlier detect if we actually need other faster implementations. This kind of unordered
     * structure is more useful to code that uses the low-level layers of FWD.
     */
    public class UnorderedRowStructure
    extends AbstractRowStructure
    {
       /**
        * The fields that should be hydrated. This stores only their ids in the data array.
        * For recid and multiplex, we use special markers.
        */
       public final List<Integer> fields;

       /** A cached value of the property meta array that can be found in the record meta */
       private final PropertyMeta[] pm;

       /** The number of SQL columns that can be hydrated using this structure. */
       private int count;

       /**
        * Create a new instance.
        *
        * @param    meta
        *           The DMO metadata of the underlying DMO for this structure.
        */
       public UnorderedRowStructure(DmoMeta meta)
       {
          super(meta);
          this.fields = new ArrayList<>();
          this.pm = dmoMeta.recordMeta.getPropertyMeta(false);
          this.count = 0;
       }

       /**
        * 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)
       {
          fields.add(ReservedProperty.ID_PRIMARY_KEY);
          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)
       {
          fields.add(ReservedProperty.ID_MULTIPLEX);
          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))
          {
             // skip non-expanded extent fields; they will be hydrated by super at the end
             return true;
          }

          int idx = dmoMeta.recordMeta.getIndexOfProperty(prop.name);
          fields.add(idx);
          count += pm[idx].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 idx = 0;

             @Override
             public boolean hasNext()
             {
                return idx < fields.size();
             }

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

                return pm[fields.get(idx++)].dmoProperty;
             }

          };
       }

       /**
        * Hydrate a record knowing that the result-set selected some properties in arbitrary order.
        * Never presume an implicit order of the properties in the result-set when using such row
        * structure. Always presume that there will be only some poperties whose index in the
        * record should be determined.
        *
        * @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
       {
          int fieldCnt = fields.size();
          for (int i = 0; i < fieldCnt; i++)
          {
             int idx = fields.get(i);

             if (idx == ReservedProperty.ID_PRIMARY_KEY)
             {
                r.primaryKey(resultSet.getLong(rsOffset++));
                if (fieldCnt == 1)
                {
                   return rsOffset;
                }
             }
             else if (idx == ReservedProperty.ID_MULTIPLEX)
             {
                ((TempRecord) r)._multiplex(resultSet.getInt(rsOffset++));
             }
             else
             {
                rsOffset += r.readProperty(idx, resultSet, rsOffset);
             }
          }

          if (hasExtents && session != null)
          {
             hydrateExtents(session, r, -1);
          }

          return rsOffset;
       }
    }