# SequenceHandler.java

    /*
    ** Module   : SequenceHandler.java
    ** Abstract : Interface for all sequence handler implementations.
    **
    ** Copyright (c) 2012-2025, Golden Code Development Corporation.
    **
    ** -#- -I- --Date-- ----------------------------Description--------------------------------------
    ** 001 OM  20121128 Created initial version.
    ** 002 OM  20130801 Added synchronization for access to un-atomic db sequence functionality.
    ** 003 EVL 20160223 Javadoc fixes to make compatible with Oracle Java 8 for Solaris 10.
    ** 004 ECF 20160501 Replaced direct SQL use with a more efficient implementation.
    ** 005 GBB 20230512 Logging methods replaced by CentralLogger/ConversionStatus.
    ** 006 OM  20250110 Added sequence support for multi-tenant databases.
    ** 007 ICP 20250129 Used int64.of to leverage caches instances.
    */

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

    import java.math.*;
    import java.util.logging.*;
    import com.goldencode.p2j.util.*;
    import com.goldencode.p2j.util.logging.*;

    /**
     * This class defines 3 sequence primitives for sequence <code>CURRENT-VALUE</code>,
     * <code>NEXT-VALUE</code> functions and <code>CURRENT-VALUE</code> statement and an utility
     * <code>contains</code> method. The access to these methods is synchronized so for a database
     * only one thread can execute a primitive on a sequence. The
     * {@link com.goldencode.p2j.persist.SequenceManager SequenceManager} is
     * responsible for instantiating only one <code>SequenceHandler</code> per database.
     * <p>
     * Implementations of this class will use different strategies for handling 4GL sequences,
     * depending on the native support from the respective database system. They will override the
     * four protected <code>safeXXX</code> methods. It is guaranteed that when they are executed,
     * the database-level lock has been acquired. Because that, it is recommended that these methods
     * should be fast and should not acquire other locks to prevent possible dead-locks.
     */
    public class SequenceHandler
    {
       /** Logger (safe as a JVM-wide value rather than as context-local). */
       private static final CentralLogger LOG = CentralLogger.get(SequenceHandler.class);

       /** The database logical name on which this handler will work with. */
       private String database;

       /**
        * The only constructor takes the name of the database as argument.
        *
        * @param   ldbName
        *          The database logical name on which this handler will work with.
        */
       public SequenceHandler(String ldbName)
       {
          database = ldbName;
          /* start(); */
       }

       /**
        * Queries the current value of a sequence. The base class always returns unknown value.
        * <p>
        * This method will acquire the lock for modifying sequences on this database and then will
        * call the protected overridable safe version form derived classes.
        *
        * @param   seqName
        *          The name of the sequence.
        * @param   tenantId
        *          The tenant id. If present (not null) it is checked. If not it is computed as
        *          {@code tenant-id(ldbName}).
        *
        * @return  The (new) value of the sequence, as requested.
        */
       public final int64 getCurrentValue(String seqName, Long tenantId)
       {
          synchronized(this)
          {
             return safeGetCurrentValue(seqName, database, tenantId);
          }
       }

       /**
        * Computes and returns the next value of a sequence. The base class always returns unknown
        * value.
        * <p>
        * This method will acquire the lock for modifying sequences on this database and then will
        * call the protected overridable safe version form derived classes.
        *
        * @param   seqName
        *          The name of the sequence.
        * @param   tenantId
        *          The tenant id. If present (not null) it is checked. If not it is computed as
        *          {@code tenant-id(ldbName}).
        *
        * @return  The (new) value of the sequence, as requested.
        */
       public final int64 getNextValue(String seqName, Long tenantId)
       {
          synchronized(this)
          {
             return safeGetNextValue(seqName, database, tenantId);
          }
       }

       /**
        * Initialize (reset) the current value of a sequence. The base class does nothing.
        * <p>
        * This method will acquire the lock for modifying sequences on this database and then will
        * call the protected overridable safe version form derived classes.
        *
        * @param   seqName
        *          The name of the sequence.
        * @param   newVal
        *          The value the sequence will be reset to.
        * @param   tenantId
        *          The tenant id. If present (not null) it is checked. If not it is computed as
        *          {@code tenant-id(ldbName}).
        */
       public final void setValue(String seqName, long newVal, Long tenantId)
       {
          synchronized(this)
          {
             safeSetValue(seqName, database, newVal, tenantId);
          }
       }

       /**
        * Test whether the database contains a sequence. This is useful to identify the correct
        * database/sequences when a 4GL static function / statement is called without the database
        * parameter.
        * <p>
        * This method will acquire the lock for modifying sequences on this database and then will
        * call the protected overridable safe version form derived classes.
        *
        * @param   seqName
        *          The name of the sequence.
        *
        * @return  false
        */
       public final boolean contains(String seqName)
       {
          synchronized(this)
          {
             return safeContains(seqName, database);
          }
       }

       /**
        * Extract the int64 value from a query result set.
        *
        * @param   result
        *          Single result of a sequence query. May be {@code null}.
        *
        * @return  The value at position 0 wrapped as as int64.
        */
       protected static int64 getResultValue(Object result)
       {
          if (result == null)
          {
             return int64.UNKNOWN;
          }

          if (result instanceof Long)
          {
             // deprecated ?
             return int64.of((Long) result);
          }
          else if (result instanceof BigInteger)
          {
             return int64.of(((BigInteger) result).longValue());
          }
          else
          {
             // don't know how to cast the result:
             LOG.logp(Level.WARNING, SequenceHandler.class.getName(), "getResultValue()",
                      "Cannot handle " + result.getClass() + "result type.");

             return int64.UNKNOWN;
          }
       }

       /**
        * Queries the current value of a sequence. The base class always returns unknown value.
        * <p>
        * This method should be called only in a safe environment, where the database-level lock for
        * access to sequences has already been acquired.
        *
        * @param   seqName
        *          The name of the sequence.
        * @param   ldbName
        *          The database to which the sequence belongs to. If is null then the first connected
        *          database is assumed.
        * @param   tenantId
        *          The tenant id. If present (not null) it is checked. If not it is computed as
        *          {@code tenant-id(ldbName}).
        *
        * @return  The current value of the sequence, as requested.
        */
       protected int64 safeGetCurrentValue(String seqName, String ldbName, Long tenantId)
       {
          return int64.UNKNOWN;
       }

       /**
        * Computes and returns the next value of a sequence. The base class always returns unknown
        * value.
        * <p>
        * This method should be called only in a safe environment, where the database-level lock for
        * access to sequences has already been acquired.
        *
        * @param   seqName
        *          The name of the sequence.
        * @param   ldbName
        *          The database to which the sequence belongs to. If is null then
        *          the first connected database is assumed.
        * @param   tenantId
        *          The tenant id. If present (not null) it is checked. If not it is computed as
        *          {@code tenant-id(ldbName}).
        *
        * @return  The new value of the sequence, as requested.
        */
       protected int64 safeGetNextValue(String seqName, String ldbName, Long tenantId)
       {
          return int64.UNKNOWN;
       }

       /**
        * Initialize (reset) the current value of a sequence. The base class does nothing.
        * <p>
        * This method should be called only in a safe environment, where the database-level lock for
        * access to sequences has already been acquired.
        *
        * @param   seqName
        *          The name of the sequence.
        * @param   ldbName
        *          The database to which the sequence belongs to. If is null then
        *          the first connected database is assumed.
        * @param   newVal
        *          The value the sequence will be reset to.
        * @param   tenantId
        *          The tenant id. If present (not null) it is checked. If not it is computed as
        *          {@code tenant-id(ldbName}).
        */
       protected void safeSetValue(String seqName, String ldbName, long newVal, Long tenantId)
       {
       }

       /**
        * Test whether the database contains a sequence. This is useful to identify the correct
        * database/sequences when a 4GL static function / statement is called without the database
        * parameter.
        * The base class always returns false.
        * <p>
        * This method should be called only in a safe environment, where the database-level lock for
        * access to sequences has already been acquired.
        *
        * @param   seqName
        *          The name of the sequence.
        * @param   ldbName
        *          The database to which the sequence belongs to. If is null then the first connected
        *          database is assumed.
        *
        * @return  false
        */
       protected boolean safeContains(String seqName, String ldbName)
       {
          return false;
       }
    }