# DynamicJoin.java

    /*
    ** Module   : DynamicJoin.java
    ** Abstract : Natural join helper implementation for dynamic queries
    **
    ** Copyright (c) 2006-2023, Golden Code Development Corporation.
    **
    ** -#- -I- --Date-- --JPRM-- -----------------------------------Description-----------------------------------
    ** 001 ECF 20060309   @25002 Created initial version. Natural join helper
    **                           implementation used by dynamic query types.
    ** 002 ECF 20060621   @27516 Fix to setup method. Use lowercased short
    **                           name of DMO interface when composing name of
    **                           foreign record property.
    ** 003 ECF 20060803   @28389 Minor change to getParameterType() method.
    **                           Renamed parameter and changed javadoc.
    ** 004 ECF 20070629   @35297 Minor optimization. Replaced StringBuffer
    **                           with StringBuilder.
    ** 005 SVL 20080421   @38075 Updated to meet the AbstractJoin function
    **                           signatures which may return multiple query
    **                           substitution parameters.
    ** 006 CA  20080515   @38283 Fixed regression introduced by H005: the
    **                           parameter type must always be retrieved
    **                           from the foreign class.
    ** 007 ECF 20080822   @39560 Added isServerJoin(). Reports whether join
    **                           occurs at database server or within P2J
    **                           runtime environment.
    ** 008 GES 20090424   @41938 Import change.
    ** 009 ECF 20090428   @42973 Fixed setup(). Use record buffer's snapshot to
    **                           resolve parameter in non-dereference case.
    ** 010 SVL 20120331          Upgraded to Hibernate 4.
    ** 011 SVL 20140210          Use HQLExpression instead of HQL string.
    ** 012 EVL 20160223          Javadoc fixes to make compatible with Oracle Java 8 for Solaris 10.
    ** 013 ECF 20200906          New ORM implementation.
    **     OM  20221103          New class names for FQLPreprocessor, FQLExpression, FQLBundle, and FQLCache.
    ** 014 OM  20230404          The join navigation key may contain null/unknown values.
    */

    /*
    ** 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.List;
    import java.util.Collections;
    import java.io.Serializable;
    import com.goldencode.p2j.persist.orm.*;
    import com.goldencode.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 parameter (<code>?</code>)
     * to represent the shared record.  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.personRecord = ?
     * </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 = ?
     * </pre>
     * where <code>Address</code> is the local DMO and PersonAddress the foreign
     * DMO.
     */
    final class DynamicJoin
    extends AbstractJoin
    {
       /** An object which resolves the substitution parameter */
       private ParameterResolver resolver;

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

       /**
        * 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.
        */
       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 snippets used to perform the join. A bi-dimensional array of clauses are used.
        *          The first dimension is the size of the join (aka the number of fields paired) and the second is
        *          always two: the first (NULL_FIELD) is used when the joined field is {@code null} and the second
        *          (NOT_NULL_FIELD) is used when the join field is not unknown.
        */
       protected FQLExpression[][] generateFQL(RecordBuffer local,
                                               RecordBuffer inverse,
                                               RelationInfo info,
                                               boolean dereference)
       {
          FQLExpression[][] ret = new FQLExpression[1][2];

          ret[0][NULL_FIELD] = new FQLExpression(local.getDMOAlias());
          ret[0][NOT_NULL_FIELD] = new FQLExpression(local.getDMOAlias());

          if (dereference)
          {
             ret[0][NULL_FIELD].append(".").append(info.getForeignAlias()).append("Record");
             ret[0][NOT_NULL_FIELD].append(".").append(info.getForeignAlias()).append("Record");
          }

          ret[0][NULL_FIELD].append(" is null");
          ret[0][NOT_NULL_FIELD].append(" = ", true);

          return ret;
       }

       /**
        * Determine the type of the query substitution parameter. This will be a Hibernate entity type
        * which wrappers the implementation class of the buffer.
        *
        * @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  A singleton list with the appropriate Hibernate type for the query substitution
        *          parameter is used for this join.
        */
       @Override
       protected List<FqlType> getParameterTypes(RelationInfo info, boolean dereference)
       {
          // TODO: implement w/o Hibernate
          /*
          // always return the foreign class, because the RelationInfo object is
          // already dereferenced by the AbstractJoin c'tor
          TypeHelper th = inverse.buffer().getPersistence().getSession().getTypeHelper();
          return Collections.singletonList(th.entity(info.getForeignClass()));
          */

          return null;
       }

       /**
        * Perform additional setup necessary to create the object which will
        * resolve the query substitution parameter 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.
        */
       protected void setup(RecordBuffer local,
                            final RecordBuffer inverse,
                            RelationInfo info,
                            boolean dereference)
       {
          // Initialize query substitution parameter resolver.
          if (dereference)
          {
             this.resolver = () -> Collections.singletonList((Serializable) inverse.getCurrentRecord());
          }
          else
          {
             String prop = StringHelper.changeCase(local.getDMOName(), false) + "Record";

             this.resolver = new ParameterResolver()
             {
                private FieldReference ref = new FieldReference(inverse, prop);

                public List<Serializable> resolve()
                {
                   return Collections.singletonList(
                      (Serializable) ref.get(inverse.getSnapshot()));
                }
             };
          }
       }

       /**
        * Get the DMO instance which will be used as the query substitution
        * parameter.  Utilizes the inner helper class {@link
        * DynamicJoin.ParameterResolver} to do its work.
        *
        * @return  Query substitution parameter;  a singleton list with DMO
        *          instance.
        */
       List<Serializable> getParameters()
       {
          return resolver.resolve();
       }

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