# DynamicLegacyKeyJoin.java

    /*
    ** Module   : DynamicLegacyKeyJoin.java
    ** Abstract : Natural join helper implementation for dynamic queries,
    **            which uses the "legacy foreign key" fields to perform join.
    **
    ** Copyright (c) 2004-2024, Golden Code Development Corporation.
    **
    ** -#- -I- --Date-- --JPRM-- -----------------------------------Description-----------------------------------
    ** 001 SVL 20080421   @38152 Created initial version. Natural join helper
    **                           which uses legacy keys to perform join.
    ** 002 ECF 20080606   @38646 Fixed setup() method. FieldReference ctor
    **                           requires DMO interface rather than DMO
    **                           implementation class.
    ** 003 ECF 20080822   @39561 Added isServerJoin(). Reports whether join occurs
    **                           at database server or within P2J runtime
    **                           environment.
    ** 004 CA  20080819   @39457 Support API change in FieldReference.
    ** 005 ECF 20090305   @41434 Fixed parameter resolver. Use buffer snapshot
    **                           instead of current record to resolve parameters.
    **                           This ensures that if the current record is
    **                           updated, we are using the proper (original)
    **                           placeholder values, not the new values.
    ** 006 ECF 20090702   @43034 Refined #005 (@41434). Instead of using snapshot
    **                           first, try using current record first. If no
    **                           current record exists (e.g., it was deleted),
    **                           use snapshot.
    ** 007 SVL 20140210          Use HQLExpression instead of HQL string.
    ** 008 ECF 20150801          Added getUnresolvedParameters().
    ** 009 EVL 20160223          Javadoc fixes to make compatible with Oracle Java 8 for Solaris 10.
    ** 010 ECF 20160225          Changed implementation of getParameterTypes.
    ** 011 ECF 20180201          Create field references with DMO proxy during setup.
    ** 012 ECF 20200906          New ORM implementation.
    **     CA  20220607          Fixed generateHQL(), get the properties depending on the 'dereference' flag.
    **     OM  20221103          New class names for FQLPreprocessor, FQLExpression, FQLBundle, and FQLCache.
    ** 013 OM  20230404          The join navigation key may contain null/unknown values.
    ** 014 RAA 20231222          Added null check for dmo in setup().
    */

    /*
    ** 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 com.goldencode.p2j.persist.hql.*;
    import com.goldencode.p2j.persist.orm.*;
    import java.io.*;
    import java.util.*;

    /**
     * An implementation of a natural join helper used by dynamic query types.
     * The FQL query string snippet created by this class joins the local DMO
     * with the inverse DMO using a query substitution parameters (<code>?</code>)
     * to represent the shared "legacy foreign key" fields. For instance, given
     * the three table relationship:
     * <pre>
     *    Person [one-to-many] ---&gt; PersonAddress [many-to-one] ---&gt; Address
     * </pre>
     * and the following multi-table join in Progress
     * <pre>
     *    for each person,
     *        each person-address of person,
     *        each address of person-address:
     *       ...
     * </pre>
     * the first join (<code>person-address of person</code>) is represented as
     * follows:
     * <pre>
     *    personAddress.siteId = ? and personAddress.empNum = ?
     * </pre>
     * where <code>PersonAddress</code> is the local DMO and Person the foreign
     * DMO;  and the second join (<code>address of person-address</code>) is
     * represented as follows:
     * <pre>
     *    address.addrId = ?
     * </pre>
     * where <code>Address</code> is the local DMO and PersonAddress the foreign
     * DMO.
     */
    final class DynamicLegacyKeyJoin
    extends AbstractJoin
    {
       /** An object which resolves the substitution parameters */
       private DynamicLegacyKeyJoin.ParameterResolver resolver;

       /** List of field reference substitution parameters which define this join */
       private List<FieldReference> parameters;

       /**
        * Constructor.
        *
        * @param   local
        *          Local record buffer (the referring end of the join).
        * @param   inverse
        *          Inverse record buffer (the referent end of the join).
        */
       DynamicLegacyKeyJoin(RecordBuffer local, final RecordBuffer inverse)
       {
          super(local, inverse);
       }

       /**
        * Get a list of unresolved field reference parameters for this join.
        *
        * @return  The list of unresolved field reference substitution parameters which define the
        *          join between the local buffer and its inverse.
        */
       @Override
       public List<FieldReference> getUnresolvedParameters()
       {
          return parameters;
       }

       /**
        * Report whether the join represented by this object takes place at the
        * database server, or within runtime code.
        *
        * @return  <code>true</code> if the join happens at the server;
        *          <code>false</code> if it happens in the runtime.
        */
       @Override
       protected boolean isServerJoin()
       {
          return false;
       }

       /**
        * Generate the FQL where clause snippets which will be inserted into the overall FQL statement executed by
        * the enclosing query. See the class description for additional details on the composition of the clause.
        *
        * @param   local
        *          Local record buffer (the referring end of the join).
        * @param   inverse
        *          Inverse record buffer (the referent end of the join).
        * @param   info
        *          Relation descriptor object.
        * @param   dereference
        *          {@code true} if the local DMO contains a reference to the foreign record, which must be
        *          dereferenced in the FQL query; {@code false} if the local DMO <i>is</i> the foreign record,
        *          referenced by the inverse DMO.
        *
        * @return  FQL where clause snippet which expresses the join.
        */
       @Override
       protected FQLExpression[][] generateFQL(RecordBuffer local,
                                               RecordBuffer inverse,
                                               RelationInfo info,
                                               boolean dereference)
       {
          List<FQLExpression> wcListNotNulls = new ArrayList<>();
          List<FQLExpression> wcListNulls = new ArrayList<>();

          Iterator<String> localProperties = dereference ? info.localProperties() : info.foreignProperties();
          try
          {
             boolean first = true;
             while (localProperties.hasNext())
             {
                FQLExpression whereClauseNotNull = new FQLExpression();
                FQLExpression whereClauseNull = new FQLExpression();
                if (!first)
                {
                   whereClauseNotNull.append(" and ");
                   whereClauseNull.append(" and ");
                }
                else
                {
                   first = false;
                }

                StringBuilder buf = new StringBuilder();
                DBUtils.composePropertyName(local, localProperties.next(), buf);
                String localPropName = buf.toString();

                whereClauseNotNull.append(localPropName).append(" = ", true);
                whereClauseNull.append(localPropName).append(" is null");

                wcListNotNulls.add(whereClauseNotNull);
                wcListNulls.add(whereClauseNull);
             }
          }
          catch (PersistenceException e)
          {
             // RelationInfo contains incorrect information
             throw new IllegalArgumentException(e);
          }

          // collect result and construct the 2-dimensional return array
          int len = wcListNotNulls.size();
          FQLExpression[][] ret = new FQLExpression[len][2];
          for (int i = 0; i < len; i++)
          {
             ret[i][NULL_FIELD] = wcListNulls.get(i);
             ret[i][NOT_NULL_FIELD] = wcListNotNulls.get(i);
          }
          return ret;
       }

       /**
        * Get the values of DMO instance fields which will be used as the query substitution
        * parameters.
        *
        * @param   info
        *          Relation descriptor object.
        * @param   dereference
        *          {@code true} if the local DMO contains a reference to the foreign record, which
        *          must be dereferenced in the FQL query; {@code false} if the local DMO <i>is</i> the
        *          foreign record, referenced by the inverse DMO.
        *
        * @return  The appropriate types for the query substitution parameters is used for this join.
        */
       @Override
       protected List<FqlType> getParameterTypes(RelationInfo info, boolean dereference)
       {
          Iterator<String> properties = (dereference ? info.foreignProperties() : info.localProperties());

          List<FqlType> types = new ArrayList<>();
          try
          {
             while (properties.hasNext())
             {
                Class<? extends DataModelObject> dmoIface = dereference
                                     ? info.getForeignInterface()
                                     : info.getLocalInterface();
                String prop = properties.next();
                types.add(DataTypeHelper.getTypeClass(DBUtils.getDMOPropertyType(dmoIface, prop)));
             }
          }
          catch (PersistenceException e)
          {
             // RelationInfo contains incorrect information
             throw new IllegalArgumentException(e);
          }

          return types;
       }

       /**
        * Perform additional setup necessary to create the object which will
        * resolve the query substitution parameters at query execution time.
        *
        * @param   local
        *          Local record buffer (the refering end of the join).
        * @param   inverse
        *          Inverse record buffer (the referent end of the join).
        * @param   info
        *          Relation descriptor object.
        * @param   dereference
        *          <code>true</code> if the local DMO contains a reference to the
        *          foreign record, which must be dereferenced in the FQL query;
        *          <code>false</code> if the local DMO <i>is</i> the foreign
        *          record, referenced by the inverse DMO.
        */
       @Override
       protected void setup(RecordBuffer local,
                            final RecordBuffer inverse,
                            RelationInfo info,
                            boolean dereference)
       {
          List<FieldReference> props = new ArrayList<>();
          Iterator<String> properties = (dereference
                                         ? info.foreignProperties()
                                         : info.localProperties());

          while (properties.hasNext())
          {
             String property = properties.next();
             FieldReference ref = new FieldReference(inverse, property);
             props.add(ref);
          }

          parameters = Collections.unmodifiableList(props);

          // Initialize query substitution parameter resolver.
          this.resolver = () -> {
             List<Serializable> res = new ArrayList<>();
             Record dmo = inverse.getCurrentRecord();
             if (dmo == null)
             {
                dmo = inverse.getSnapshot();
                if (dmo == null)
                {
                   return res;
                }
             }

             int parametersSize = parameters.size();
             for (int i = 0; i < parametersSize; i++)
             {
                res.add((Serializable) parameters.get(i).get(dmo));
             }

             return res;
          };
       }

       /**
        * Get the values of DMO instance fields which will be used as the query
        * substitution parameters.  Utilizes the inner helper class {@link
        * DynamicLegacyKeyJoin.ParameterResolver} to do its work.
        *
        * @return  A list of query substitution parameters.
        */
       @Override
       List<Serializable> getParameters()
       {
          return resolver.resolve();
       }

       /**
        * An internal API used by this class to abstract the resolution of the
        * query substitution parameters at query execution time.
        */
       private interface ParameterResolver
       {
          /**
           * Get the values of DMO instance fields which will be used as the query
           * substitution parameters.
           *
           * @return  A list of query substitution parameters.
           */
          public List<Serializable> resolve();
       }
    }