SQLServer2012SequenceHandler.java

/*
** Module   : SQLServer2012SequenceHandler.java
** Abstract : Static class that handles sequence functions and statements from Progress / OpenEdge 10.x.
**
** Copyright (c) 2013-2025, Golden Code Development Corporation.
**
** -#- -I- --Date-- ---------------------------------Description---------------------------------
** 001 VMN 20131012 Created initial stub version.
** 002 OM  20151130 Added implementation for overridden Safe* methods. Added logging.
** 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 ECF 20160609 SQL performance improvement.
** 006 ECF 20180219 Reduce Hibernate session flushing, if possible.
** 007 OM  20200906 New ORM implementation.
**     OM  20220531 Fixed an error message.
** 008 GBB 20230512 Logging methods replaced by CentralLogger/ConversionStatus.
** 009 OM  20241128 Multi-tenant runtime support: selected the proper persistence context, eventually
**                  based on [sharedDb] parameter.
** 010 OM  20250110 Added sequence support for multi-tenant databases.
*/

/*
** 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.util.*;
import java.util.logging.Level;

import com.goldencode.p2j.persist.*;
import com.goldencode.p2j.persist.dialect.*;
import com.goldencode.p2j.persist.orm.*;
import com.goldencode.p2j.util.*;
import com.goldencode.p2j.util.logging.*;

/**
 * SQL Server 2012 implementation of sequences using a native SQL sequence primitives queries.
 * <p>
 * <b>Important notes:</b>
 * <ul>
 *    <li>in P4GL, when reset a sequence to a value that value become the CURRENT-VALUE and
 *          <code>NEXT-VALUE</code> is the natural <code>NEXT (crt + inc)</code>;
 *    <li>in MSSQL, setting a value to a sequence means that that value will be the 
 *          <code>NEXT</code> value to be returned by <code>NEXT-VALUE</code>.
 *          After the fist <code>NEXT-VALUE</code>, the <code>CURRENT-VALUE</code> is unchanged!
 *    <li>MSSQL (like PostgreSQL) is different than Progress when cycling: it will make the 
 *          counter jump from <code>MAX_VALUE</code> to <code>MIN_VALUE</code> (and the reverse); 
 *    <li>4GL will jump from <code>MAX_VALUE</code> back to <code>INITIAL_VALUE</code> instead.
 * </ul>
 */
public class SQLServer2012SequenceHandler
extends SequenceHandler
{
   /** J2SE Logger. */
   private static final CentralLogger LOG = CentralLogger.get(SQLServer2012SequenceHandler.class);

   /** The list of sequences grouped by databases. It uses lazy initialization. */
   private HashMap<String, LinkedList<String>> sequences = null;
   
   /**
    * When the sequence is set to a new value, SQL2012 requires a NEXT value to be performed.
    * Since P4GL loops to INITIAL value instead of MIN_VALUE, a new SET_VALUE is needed to be
    * applied. Usually there is no problem, but when intentionally we set the current value to
    * MIN_VALUE, the correction is not needed any more, also this flag will prevent a
    * theoretically possible recursion.
    */
   private boolean ignoreNextToLowBoundAdjustment = false;

   /**
    * The only constructor takes the name of the database as argument.
    * It is passed on to super class.
    *
    * @param   ldbName
    *          The database logical name on which this handler will work with.
    */
   public SQLServer2012SequenceHandler(String ldbName)
   {
      super(ldbName);
   }
   
   /**
    * Queries the current value of a sequence.
    * <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. It is assumed it is not null and valid.
    * @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
    */
   @Override
   protected int64 safeGetCurrentValue(String seqName, String ldbName, Long tenantId)
   {
      Sequence seq = SequenceManager.getSequence(ldbName, seqName);
      if (seq == null)
      {
         ErrorManager.recordOrThrowError(2913, seqName.toUpperCase(), "");
         // Unknown sequence expression <sequence name>. (2913)
         return new int64();
      }
      
      // this will also create the instance if needed:
      Persistence persistence = ConnectionManager.getPersistence(ldbName);
      if (tenantId != null)
      {
         int crtTenant = persistence.getContext(Persistence.PRIVATE_CTX).getTenantId();
         if (crtTenant != tenantId)
         {
            // NOTE: super-tenants are not implemented yet so we raise this unconditionally, for the moment:
            ErrorManager.recordOrThrowError(15956);
            // Only super-tenants may use a tenant-id other than their own in a sequence function. (15956)
            return new int64();
         }
      }
      
      Dialect dialect = persistence.getDialect();
      String getCrtValQuery = dialect.getSequenceCurrValString(seqName);
      
      try
      {
         return getResultValue(persistence.getSingleSQLResult(getCrtValQuery, !seq.isMultiTenant(), null));
      }
      catch (PersistenceException pe)
      {
         if (LOG.isLoggable(Level.WARNING))
         {
            LOG.log(Level.WARNING,
                    "Failed to get CURRENT-VALUE from " + ldbName + "." + seqName + ": " + pe.getMessage());
         }
      }
      
      // if here then some error occurred, return unknown value
      return new int64();
   }
   
   /**
    * Computes and returns the next value of a sequence.
    * <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. It is assumed it is not null and valid.
    * @param   tenantId
    *          The tenant id. If present (not null) it is checked. If not it is computed as
    *          {@code tenant-id(ldbName}).
    *
    * @return  the next value of the sequence or unknown value (?) if sequence/database not found
    *          or the sequence is not cycling and has passed the maximum/minimum value.
    */
   @Override
   protected int64 safeGetNextValue(String seqName, String ldbName, Long tenantId)
   {
      Sequence seq = SequenceManager.getSequence(ldbName, seqName);
      if (seq == null)
      {
         ErrorManager.recordOrThrowError(2913, seqName.toUpperCase(), "");
         // Unknown sequence expression <sequence name>. (2913)
         return new int64();
      }
      
      Persistence persistence = ConnectionManager.getPersistence(ldbName);
      if (tenantId != null)
      {
         int crtTenant = persistence.getContext(Persistence.PRIVATE_CTX).getTenantId();
         if (crtTenant != tenantId)
         {
            // NOTE: super-tenants are not implemented yet so we raise this unconditionally, for the moment:
            ErrorManager.recordOrThrowError(15956);
            // Only super-tenants may use a tenant-id other than their own in a sequence function. (15956)
            return new int64();
         }
      }
      
      Dialect dialect = persistence.getDialect();
      String getNextValQuery = dialect.getSequenceNextValString(seqName);
      
      try
      {
         int64 resultValue = getResultValue(
               persistence.getSingleSQLResult(getNextValQuery, !seq.isMultiTenant(), null));
         
         // MSSQL (like PostgreSQL) is different from Progress when cycling:
         //    it will make the counter jump from MAX_VALUE to MIN_VALUE (and the reverse) 
         //    instead, 4GL will jump back to INITIAL_VALUE
         // We don't do this if we are already in a setValue (ignoreNextToLowBoundAdjustment) 
         if (seq.isCycle() && !ignoreNextToLowBoundAdjustment)
         {
            // in a cycling sequence resultValue is never null/unknown
            long crtVal = resultValue.longValue();
            
            if (seq.getIncrement() > 0 && crtVal == seq.getMin())  // did the cycle jump occurred?
            {
               long ret = seq.getInitial();
               safeSetValue(seqName, ldbName, ret, tenantId);
               return new int64(ret);
            }
         }
         
         return resultValue;
      }
      catch (PersistenceException pe)
      {
         // heuristically analyse the exception message to filter out expected errors
         boolean outOfBoundsException = false;
         // TODO: implement w/o Hibernate
//         if (pe.getCause() instanceof SQLGrammarException)
//         {
//            JDBCException jdbcExc = (JDBCException) pe.getCause();
//            if (jdbcExc.getErrorCode() == 11728 && "S0001".equals(jdbcExc.getSQLState()))
//            {
//               // String errMessage = pe.getCause().getMessage();
//               //if (errMessage.contains("has reached its minimum or maximum value"))
//
//               outOfBoundsException = true;
//            }
//         }
         if (!outOfBoundsException)
         {
            // some other nasty thing has happen, report it:
            if (LOG.isLoggable(Level.WARNING))
            {
               LOG.log(Level.WARNING,
                       "Failed to get NEXT-VALUE from " + ldbName + "." + seqName + ": " +
                       pe.getMessage());
            }
         }
      }
      
      // if here then some error occurred, return unknown value
      return new int64();
   }
   
   /**
    * Initialize (reset) the current value of a sequence.
    * <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. 
    *          It is assumed it is not null and valid.
    * @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}).
    */
   @Override
   protected void safeSetValue(String seqName, String ldbName, long newVal, Long tenantId)
   {
      Sequence seq = SequenceManager.getSequence(ldbName, seqName);
      if (seq == null)
      {
         ErrorManager.recordOrThrowError(3133, seqName.toUpperCase(), "");
         // SYSTEM ERROR: Sequence <sequence name> not found. (3133)
         return;
      }
      if (seq.getMin() > newVal || newVal > seq.getMax())
      {
         ErrorManager.recordOrThrowError(3132,
               "Cannot set sequence " + seq.getLegacyName().toUpperCase() + " beyond its max/min values");
         return;
      }
      
      // in SQL Server, "alter sequence / restart with" will set the next value to be 
      // returned by NEXT VALUE (At tis point CURRENT and NEXT value are equals !!)  
      // we need to call once the 'next value' to mark this value as used.
      // checking the values at this point and after stepping to next-value will 
      // return the same value (!) 
      
      Persistence persistence = ConnectionManager.getPersistence(ldbName);
      if (tenantId != null)
      {
         int crtTenant = persistence.getContext(Persistence.PRIVATE_CTX).getTenantId();
         if (crtTenant != tenantId)
         {
            // NOTE: super-tenants are not implemented yet so we raise this unconditionally, for the moment:
            ErrorManager.recordOrThrowError(15956);
            // Only super-tenants may use a tenant-id other than their own in a sequence function. (15956)
            return;
         }
      }
      
      Dialect dialect = persistence.getDialect();
      String setCrtValQuery = dialect.getSequenceSetValString(seqName, newVal);
      
      try
      {
         persistence.executeSQL(setCrtValQuery, !seq.isMultiTenant());
         
         // we bracket this call in order to avoid 
         //    - unwanted jump to INITIAL_VALUE if the result happens to be MIN_VALUE
         //    - theoretically possible recursion (a path of safeGetNextValue calls back setValue)
         ignoreNextToLowBoundAdjustment = true;
         safeGetNextValue(seqName, ldbName, tenantId);
         ignoreNextToLowBoundAdjustment = false;
      }
      catch (PersistenceException pe)
      {
         if (LOG.isLoggable(Level.WARNING))
         {
            LOG.log(Level.WARNING,
                    "Failed to set CURRENT-VALUE from " + ldbName + "." + seqName + ": " + pe.getMessage());
         }
      }
   }
   
   /**
    * 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 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  true if the sequence is defined in the database
    */
   @Override
   protected boolean safeContains(String seqName, String ldbName)
   {
      // lazy initialization
      if (sequences == null)
      {
         sequences = new HashMap<>();
      }
      
      // make sure the structure is initialized for this database:
      LinkedList<String> crtSeqList;
      if (!sequences.containsKey(ldbName))
      {
         // create the list 
         crtSeqList = new LinkedList<>();
         sequences.put(ldbName, crtSeqList);
         
         Persistence persistence = ConnectionManager.getPersistence(ldbName);
         try
         {
            // retrieve the whole list of sequences at once, at the first request for this db
            // we must cast the name column because it is defined as sysname(nvarchar(128)) 
            // and the driver does not recognize the datatype (-9)
            ScrollableResults<String> rs = persistence.executeSQLQuery(
                  "SELECT CAST (name AS varchar) " +
                  "FROM sys.sequences " +
                  "WHERE type='SO'",
                  Persistence.META_CTX,
                  null);
            while (rs.next())
            {
               crtSeqList.add(rs.get(0, String.class));
            }
         }
         catch (PersistenceException pe)
         {
            if (LOG.isLoggable(Level.WARNING))
            {
               LOG.log(Level.WARNING,
                       "Failed to get sequence list from " + ldbName + ": " + pe.getMessage());
            }
            return false;
         }
      }
      else
      {
         crtSeqList = sequences.get(ldbName);
      }
      
      // now check whether the sequence is in database
      return crtSeqList.contains(seqName);
   }
}