# PostgreSQLSequenceHandler.java

    /*
    ** Module   : PostgreSQLSequenceHandler.java
    ** Abstract : Static class that handles sequence functions and statements from Progress / OpenEdge 10.x.
    **
    ** Copyright (c) 2012-2025, Golden Code Development Corporation.
    **
    ** -#- -I- --Date-- ---------------------------------Description---------------------------------
    ** 001 OM  20121116 Created initial version with CURRVAL, NEXTVAL and SETVAL support only.
    ** 002 SVL 20130331 Upgraded to Hibernate 4.
    ** 003 OM  20130712 Fixed extraction data from ResultSets. Added error handling.
    ** 004 OM  20151130 Rewrote the NEXT-VALUE sequence primitive to use one query for most cases and
    **                  a second query for handling exceptions. Code maintenance. Added logging.
    ** 005 ECF 20160501 Replaced direct SQL use with a more efficient implementation.
    ** 006 ECF 20160609 SQL performance improvement.
    ** 007 HC  20161024 Removed an unused import causing compilation error in IDEs.
    ** 008 ECF 20180219 Reduce Hibernate session flushing, if possible.
    ** 009 OM  20200906 New ORM implementation.
    **     OM  20220531 Fixed an error message.
    **     CA  20221014 Keep a lowercase map of crtSeqList sequence keys, as the change in
    **                  SequenceManager.legacyMap will always load all sequences.
    **     RAA 20230109 Changed inline statement(s) to prepared statement(s).
    ** 010 GBB 20230512 Logging methods replaced by CentralLogger/ConversionStatus.
    ** 011 OM  20241128 Multi-tenant runtime support: selected the proper persistence context, eventually
    **                  based on [sharedDb] parameter.
    ** 012 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.sql.*;
    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.*;

    /**
     * PostgreSQL implementation of sequences using a native SQL sequence primitives queries.
     * Each primitive tries to execute exactly one database query (with the exception of NEXT-VALUE,
     * where the output is checked to match the P4GL jump-to INITIAL value instead of MIN-VALUE).
     */
    public class PostgreSQLSequenceHandler
    extends SequenceHandler
    {
       /** J2SE Logger */
       private static final CentralLogger LOG = CentralLogger.get(PostgreSQLSequenceHandler.class);

       /**
        * Error code when an attempt to pass the boundaries of a sequence. This is a generic warning
        * SQL state and cannot identify by itself the exact sequence status.
        */
       private static final String OBJECT_NOT_IN_PREREQUISITE_STATE = "55000";

       /** The list of sequences grouped by databases. It uses lazy initialization. */
       private HashMap<String, LinkedList<String>> sequences = null;

       /**
        * 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 PostgreSQLSequenceHandler(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 {@code 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));

             // 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
             if (seq.isCycle())
             {
                // in a cycling sequence resultValue is never null/unknown
                long crtVal = resultValue.longValue();

                // did the cycle jump occurred?
                if (seq.getIncrement() > 0 && crtVal == seq.getMin())
                {
                   // if this is a nop, skip it
                   long ret = seq.getInitial();
                   if (crtVal != ret)
                   {
                      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;
             if (pe.getCause() instanceof SQLException)
             {
                SQLException jdbcExc = (SQLException) pe.getCause();
                if (jdbcExc.getErrorCode() == 0 &&
                    OBJECT_NOT_IN_PREREQUISITE_STATE.equals(jdbcExc.getSQLState()))
                {
                   // String errMessage = psqlExc.getMessage();
                   // if (errMessage.contains("reached maximum value") ||
                   //     errMessage.contains("reached minimum value"))
                   outOfBoundsException = true;
                }
             }
             if (!outOfBoundsException)
             {
                // some other nasty thing has happened, 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)
          {
             // note: this is a bit too late, seqName is the SQL name, not legacy
             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;
          }

          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();
          Object[] args = new Object[] {seqName, newVal};
          String setCrtValQuery = dialect.getSequenceSetValString();

          try
          {
             persistence.getSingleSQLResult(setCrtValQuery, !seq.isMultiTenant(), args);
          }
          catch (PersistenceException pe)
          {
             if (LOG.isLoggable(Level.WARNING))
             {
                LOG.log(Level.WARNING,
                        "Failed to set CURRENT-VALUE to " + 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  <code>true</code> 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
             {
                ScrollableResults<String> rs = persistence.executeSQLQuery(
                      "SELECT relname " +
                      "FROM \"pg_class\" " + // TODO: this needs ADMIN rights !
                      "WHERE relkind='S';",
                      Persistence.META_CTX,
                      null);
                while (rs.next())
                {
                   crtSeqList.add(rs.get(0, String.class).toLowerCase());
                }
             }
             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.toLowerCase());
       }
    }