P2JQueryExecutor.java

/*
** Module   : P2JQueryExecutor.java
** Abstract : Execute P2J queries and eventually log them
**
** Copyright (c) 2023-2024, Golden Code Development Corporation.
**
** -#- -I- --Date-- ---------------------------------------Description---------------------------------------
** 001 RAA 20230607 First revision with basic usage.
** 002 DDF 20230705 Replaced static initialization of value from the directory configuration with
**                  a method called at server bootstrap.
** 003 RAA 20230802 Refactored execute function and added executeImpl. Query execution can no longer happen
**                  in P2JQueryLogger.
**     RAA 20231122 Replaced the new QueryOffEndException call with the already created exception.
** 004 RAA 20231220 Added throws instructions to execute methods and changed error handling in executeImpl.
** 005 RAA 20240108 Rewrote exception handling in executeImpl().
*/

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

import com.goldencode.p2j.persist.*;

/**
 * Class responsible with executing P2J queries.
 * If logging is intended, then the execution job will be passed to {@link P2JQueryLogger}.
 */
public class P2JQueryExecutor
{
   /** The static singleton instance. */
   private static final P2JQueryExecutor instance = new P2JQueryExecutor();
   
   /**
    * Private default constructor.
    */
   private P2JQueryExecutor()
   {
      
   }
   
   /**
    * Static accessor to singleton.
    * 
    * @return  The {@code P2JQueryExecutor} singleton instance.
    */
   public static P2JQueryExecutor getInstance()
   {
      return instance;
   }
   
   /**
    * Function that executes the given query.
    * 
    * @param   <T1>
    *          The receiver type ({@link PreselectQuery} or a child of it).
    * @param   <T2>
    *          The type of the first argument.
    * @param   <T3>
    *          The type of the second argument.
    * @param   <T4>
    *          The type of the third argument.
    * @param   <R>
    *          The type for the result.
    * @param   database
    *          The database used for this query.
    * @param   r
    *          The method that needs to be executed.
    * @param   receiver
    *          Receiver denoting the query that will be executed.
    * @param   arg1
    *          First parameter given to the executed method.
    * @param   arg2
    *          Second parameter given to the executed method.
    * @param   arg3
    *          Third parameter given to the executed method.
    * 
    * @return  R
    *          The result generated by the execution of the query.
    */
   public <T1, T2, T3, T4, R> R execute(Database database,
                                        PreselectExecution<T1, T2, T3, T4, R> r, 
                                        T1 receiver,
                                        T2 arg1,
                                        T3 arg2,
                                        T4 arg3)
   throws QueryOffEndException, PersistenceException
   {
      return execute(database, 
                     (String) arg2, 
                     r, 
                     receiver, 
                     arg1, 
                     arg2, 
                     arg3, 
                     null, 
                     null, 
                     LambdaLoggerType.PRESELECT);
   }
   
   /**
    * Function that executes the given query.
    * 
    * @param   <T1>
    *          The receiver type ({@link RandomAccessQuery} or a child of it).
    * @param   <T2>
    *          The type of the first argument.
    * @param   <T3>
    *          The type of the second argument.
    * @param   <T4>
    *          The type of the third argument.
    * @param   <T5>
    *          The type of the fourth argument.
    * @param   <R>
    *          The type for the result.
    * @param   database
    *          The database used for this query.
    * @param   fql
    *          The FQL of the query.
    * @param   r
    *          The method that needs to be executed.
    * @param   receiver
    *          Receiver denoting the query that will be executed.
    * @param   arg1
    *          First parameter given to the executed method.
    * @param   arg2
    *          Second parameter given to the executed method.
    * @param   arg3
    *          Third parameter given to the executed method.
    * @param   arg4
    *          Fourth parameter given to the executed method.
    * 
    * @return  R
    *          The result generated by the execution of the query.
    */
   public <T1, T2, T3, T4, T5, R> R execute(Database database,
                                            String fql, 
                                            RandomAccessExecution<T1, T2, T3, T4, T5, R> r, 
                                            T1 receiver,
                                            T2 arg1,
                                            T3 arg2,
                                            T4 arg3,
                                            T5 arg4)
   throws QueryOffEndException, PersistenceException
   {
      return execute(database, 
                     fql, 
                     r, 
                     receiver, 
                     arg1, 
                     arg2, 
                     arg3, 
                     arg4, 
                     null, 
                     LambdaLoggerType.RANDOM_ACCESS);
   }
   
   /**
    * Function that executes the given query.
    * 
    * @param   <T1>
    *          The receiver type ({@link CompoundQuery} or a child of it).
    * @param   <T2>
    *          The type of the first argument.
    * @param   <T3>
    *          The type of the second argument.
    * @param   <T4>
    *          The type of the third argument.
    * @param   <T5>
    *          The type of the fourth argument.
    * @param   <T6>
    *          The type of the fifth argument.
    * @param   <R>
    *          The type for the result.
    * @param   database
    *          The database used for this query.
    * @param   fql
    *          The FQL of the query.
    * @param   r
    *          The method that needs to be executed.
    * @param   receiver
    *          Receiver denoting the query that will be executed.
    * @param   arg1
    *          First parameter given to the executed method.
    * @param   arg2
    *          Second parameter given to the executed method.
    * @param   arg3
    *          Third parameter given to the executed method.
    * @param   arg4
    *          Fourth parameter given to the executed method.
    * @param   arg5
    *          Fifth parameter given to the executed method.
    * 
    * @return  R
    *          The result generated by the execution of the query.
    */
   public <T1, T2, T3, T4, T5, T6, R> R execute(Database database,
                                                String fql, 
                                                CompoundExecution<T1, T2, T3, T4, T5, T6, R> r, 
                                                T1 receiver,
                                                T2 arg1,
                                                T3 arg2,
                                                T4 arg3,
                                                T5 arg4,
                                                T6 arg5)
   throws QueryOffEndException, PersistenceException
   {
      return execute(database, 
                     fql, 
                     r, 
                     receiver, 
                     arg1, 
                     arg2, 
                     arg3, 
                     arg4, 
                     arg5, 
                     LambdaLoggerType.COMPOUND);
   }
   
   /**
    * Function that handles the execution of the given query.
    * In case logging is intended, it will delegate {@link P2JQueryLogger} to do that.
    * 
    * @param   <T1>
    *          The receiver type (e.g. {@link CompoundQuery}, {@link RandomAccessQuery}, etc).
    * @param   <T2>
    *          The type of the first argument.
    * @param   <T3>
    *          The type of the second argument.
    * @param   <T4>
    *          The type of the third argument.
    * @param   <T5>
    *          The type of the fourth argument.
    * @param   <T6>
    *          The type of the fifth argument.
    * @param   <R>
    *          The type for the result.
    * @param   database
    *          The database used for this query.
    * @param   fql
    *          The FQL of the query.
    * @param   r
    *          The method that needs to be executed.
    * @param   receiver
    *          Receiver denoting the query that will be executed.
    * @param   arg1
    *          First parameter given to the executed method.
    * @param   arg2
    *          Second parameter given to the executed method.
    * @param   arg3
    *          Third parameter given to the executed method.
    * @param   arg4
    *          Fourth parameter given to the executed method.
    * @param   arg5
    *          Fifth parameter given to the executed method.
    * @param   type
    *          The type of the {@code LambaLogger} used.
    * 
    * @return  R
    *          The result generated by the execution of the query.
    */
   private <T1, T2, T3, T4, T5, T6, R> R execute(Database database,
                                                 String fql, 
                                                 LambdaLogger r, 
                                                 T1 receiver,
                                                 T2 arg1,
                                                 T3 arg2,
                                                 T4 arg3,
                                                 T5 arg4,
                                                 T6 arg5,
                                                 LambdaLoggerType type)
   throws QueryOffEndException, PersistenceException
   {
      String dbName = database.getName();
      P2JQueryStatisticsConfiguration config = P2JQueryStatisticsConfiguration.getConfiguration(dbName);
      R result = null;
      switch (config.getLoggingType())
      {
         case NONE:
            return executeImpl(r, receiver, arg1, arg2, arg3, arg4, arg5, type);
         case LOGGING:
            try
            {
               result = executeImpl(r, receiver, arg1, arg2, arg3, arg4, arg5, type);
            }
            finally
            {
               P2JQueryLogger.getLogger().log((P2JQuery) receiver,
                                              dbName,
                                              fql,  
                                              config,
                                              null);
            }
            break;
         case PROFILING:
            long start = 0;
            boolean isCompoundQuery = ((P2JQuery) receiver) instanceof CompoundQuery;
            if (!isCompoundQuery)
            {
               start = System.nanoTime();
            }
            try
            {
               result = executeImpl(r, receiver, arg1, arg2, arg3, arg4, arg5, type);
            }
            finally
            {
               long finish = 0;
               if (!isCompoundQuery)
               {
                  finish = System.nanoTime();
               }
               P2JQueryLogger.getLogger().log((P2JQuery) receiver,
                                              dbName,
                                              fql,  
                                              config,
                                              !isCompoundQuery ? (finish - start) / 1000000.0 : null);
            }
            break;
      }
      
      return result;
   }
   
   /**
    * The actual place where the query execution happens.
    * 
    * @param   <T1>
    *          The receiver type (e.g. {@link CompoundQuery}, {@link RandomAccessQuery}, etc).
    * @param   <T2>
    *          The type of the first argument.
    * @param   <T3>
    *          The type of the second argument.
    * @param   <T4>
    *          The type of the third argument.
    * @param   <T5>
    *          The type of the fourth argument.
    * @param   <T6>
    *          The type of the fifth argument.
    * @param   <R>
    *          The type for the result.
    * @param   r
    *          The method that needs to be executed.
    * @param   receiver
    *          Receiver denoting the query that will be executed.
    * @param   arg1
    *          First parameter given to the executed method.
    * @param   arg2
    *          Second parameter given to the executed method.
    * @param   arg3
    *          Third parameter given to the executed method.
    * @param   arg4
    *          Fourth parameter given to the executed method.
    * @param   arg5
    *          Fifth parameter given to the executed method.
    * @param   type
    *          The type of the {@code LambaLogger} used.
    * 
    * @return  R
    *          The result generated by the execution of the query.
    */
   private <T1, T2, T3, T4, T5, T6, R> R executeImpl(LambdaLogger r, 
                                                     T1 receiver,
                                                     T2 arg1,
                                                     T3 arg2,
                                                     T4 arg3,
                                                     T5 arg4,
                                                     T6 arg5,
                                                     LambdaLoggerType type)   
   throws QueryOffEndException, PersistenceException
   {
      try
      {
         switch (type)
         {
            case PRESELECT:
               return ((PreselectExecution<T1, T2, T3, T4, R>) r).apply(receiver, arg1, arg2, arg3);
            case RANDOM_ACCESS:
               return ((RandomAccessExecution<T1, T2, T3, T4, T5, R>) r).apply(receiver, 
                                                                               arg1, 
                                                                               arg2, 
                                                                               arg3, 
                                                                               arg4);
            case COMPOUND:
               return ((CompoundExecution<T1, T2, T3, T4, T5, T6, R>) r).apply(receiver, 
                                                                               arg1, 
                                                                               arg2, 
                                                                               arg3, 
                                                                               arg4, 
                                                                               arg5);   
            default:
               break;
         }
      } 
      catch (RuntimeException | PersistenceException e) 
      {
         // re-throw as is, because these are declared exceptions and the caller is forced to handle them
         throw e;  
      } 
      catch (Exception e) 
      {
         throw new PersistenceException("Failed to 'executeImpl()'.", e); // specific wrap before re-throw
      }
      
      return null;
    }
   
   /** Basic interface that groups the functional interfaces used for logging queries. */
   protected interface LambdaLogger
   {
      
   }
   
   /**
    * Enumeration used to distinguish between different {@link LambdaLogger}s. The difference between
    * them consists only in the number of parameters.
    */
   protected enum LambdaLoggerType
   {
      /** 
       * Type that matches the {@code Function} behavior. It uses four arguments and returns one result. 
       * This is used in {@link PreselectQuery} type queries.
       */
      PRESELECT, 
      
      /** 
       * Type that matches the {@code Function} behavior. It uses five arguments and returns one result. 
       * This is used in {@link RandomAccessQuery} type queries.
       */
      RANDOM_ACCESS,
      
      /** 
       * Type that matches the {@code Function} behavior. It uses six arguments and returns one result. 
       * This is used in {@link CompoundQuery} type queries.
       */
      COMPOUND;
   }
   
   /**
    * Functional interface, similar to {@link Function}, but accepting four arguments, 
    * and having the capability of throwing an Exception. 
    *
    * @param   <T1>
    *          The type of the first argument.
    * @param   <T2>
    *          The type of the second argument.
    * @param   <T3>
    *          The type of the third argument.
    * @param   <T4>
    *          The type of the fourth argument.
    * @param   <R>
    *          The type of the result.
    */
   @FunctionalInterface
   public interface PreselectExecution<T1, T2, T3, T4, R>
   extends LambdaLogger
   {
      /**
       * Applies this function to the given argument.
       * 
       * @param   t1
       *          The first function argument.
       * @param   t2
       *          The second function argument.
       * @param   t3
       *          The third function argument.
       * @param   t4
       *          The fourth function argument.
       * 
       * @return  The function result.
       */
      R apply(T1 t1, T2 t2, T3 t3, T4 t4)
      throws PersistenceException;
   }
   
   /**
    * Functional interface, similar to {@link Function}, but accepting five arguments, 
    * and having the capability of throwing an Exception. 
    *
    * @param   <T1>
    *          The type of the first argument.
    * @param   <T2>
    *          The type of the second argument.
    * @param   <T3>
    *          The type of the third argument.
    * @param   <T4>
    *          The type of the fourth argument.
    * @param   <T5>
    *          The type of the fifth argument.
    * @param   <R>
    *          The type of the result.
    */
   @FunctionalInterface
   public interface RandomAccessExecution<T1, T2, T3, T4, T5, R>
   extends LambdaLogger
   {
      /**
       * Applies this function to the given argument.
       * 
       * @param   t1
       *          The first function argument.
       * @param   t2
       *          The second function argument.
       * @param   t3
       *          The third function argument.
       * @param   t4
       *          The fourth function argument.
       * @param   t5
       *          The fifth function argument.
       * 
       * @return  The function result.
       */
      R apply(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5)
      throws QueryOffEndException;
   }
   
   /**
    * Functional interface, similar to {@link Function}, but accepting six arguments, 
    * and having the capability of throwing an Exception. 
    *
    * @param   <T1>
    *          The type of the first argument.
    * @param   <T2>
    *          The type of the second argument.
    * @param   <T3>
    *          The type of the third argument.
    * @param   <T4>
    *          The type of the fourth argument.
    * @param   <T5>
    *          The type of the fifth argument.
    * @param   <T6>
    *          The type of the sixth argument.
    * @param   <R>
    *          The type of the result.
    */
   @FunctionalInterface
   public interface CompoundExecution<T1, T2, T3, T4, T5, T6, R>
   extends LambdaLogger
   {
      /**
       * 
       * @param   t1
       *          The first function argument.
       * @param   t2
       *          The second function argument.
       * @param   t3
       *          The third function argument.
       * @param   t4
       *          The fourth function argument.
       * @param   t5
       *          The fifth function argument.
       * @param   t6
       *          The sixth function argument.
       *          
       * @return  The function result.
       */
      R apply(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6)
      throws QueryOffEndException;
   }
}