ServerLegacyKeyJoin.java

/*
** Module   : ServerLegacyKeyJoin.java
** Abstract : Natural join helper implementation for server-side 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   @38154 Created initial version. Natural join helper
**                           for server-side joins using legacy keys.
** 002 ECF 20080822   @39563 Added isServerJoin(). Reports whether join
**                           occurs at database server or within P2J
**                           runtime environment.
** 003 SVL 20140210          Use HQLExpression instead of HQL string.
** 004 EVL 20160223          Javadoc fixes to make compatible with Oracle Java 8 for Solaris 10.
** 005 ECF 20200906          New ORM implementation.
**     OM  20221103          New class names for FQLPreprocessor, FQLExpression, FQLBundle, and FQLCache.
** 006 OM  20230404          The join navigation key may contain null/unknown values.
** 007 OM  20240102          Correctly map the properties of local/inverse buffers.
*/

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

/**
 * An implementation of a natural join helper used by query types which
 * perform the join on the database server.  The FQL query string snippet
 * created by this class joins the local DMO with the inverse DMO using the
 * fields which compose the "legacy foreign key" relation, and does not have
 * a query substitution parameter.  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 = person.siteId and
 *    personAddress.empNum = person.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 = personAddress.addrId
 * </pre>
 * where <code>Address</code> is the local DMO and PersonAddress the foreign
 * DMO.
 */
final class ServerLegacyKeyJoin
extends AbstractJoin
{
   /**
    * Constructor.
    *
    * @param   local
    *          Local record buffer (the refering end of the join).
    * @param   inverse
    *          Inverse record buffer (the referent end of the join).
    */
   ServerLegacyKeyJoin(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 true;
   }
   
   /**
    * Generate the FQL where clause snippet 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 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} 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)
   {
      List<FQLExpression> wcListNotNulls = new ArrayList<>();
      List<FQLExpression> wcListNulls = new ArrayList<>();
      
      boolean switched = local.getDMOImplementationClass() != info.getLocalClass();
      Iterator<String> localProperties = switched ? info.foreignProperties() : info.localProperties();
      Iterator<String> foreignProperties = switched ? info.localProperties() : info.foreignProperties();
      
      try
      {
         boolean first = true;
         while (localProperties.hasNext() && foreignProperties.hasNext())
         {
            FQLExpression wcNotNull = new FQLExpression();
            FQLExpression wcNull = new FQLExpression();
            
            if (!first)
            {
               wcNotNull.append(" and ");
               wcNull.append(" and ");
            }
            else
            {
               first = false;
            }
            
            StringBuilder bufLocal = new StringBuilder();
            DBUtils.composePropertyName(local, localProperties.next(), bufLocal);
            StringBuilder bufForeign = new StringBuilder();
            DBUtils.composePropertyName(inverse, foreignProperties.next(), bufForeign);
            
            wcNotNull.append(bufLocal.toString()).append(" = ").append(bufForeign.toString());
            wcNull.append(bufLocal.toString()).append(" is null");
            
            wcListNotNulls.add(wcNotNull);
            wcListNulls.add(wcNull);
         }
      }
      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. Since this implementation utilizes no query substitution parameters, this method
    * always returns {@code null}.
    *
    * @param   info
    *          Not used.
    * @param   dereference
    *          Not used.
    *
    * @return  {@code null}.
    */
   @Override
   protected List<FqlType> getParameterTypes(RelationInfo info, boolean dereference)
   {
      return null;
   }
}