DialectHelper.java

/*
** Module   : DialectHelper.java
** Abstract : A helper to P2J dialect classes
**
** Copyright (c) 2014-2022, Golden Code Development Corporation.
**
** -#- -I- --Date-- ---------------------------------Description---------------------------------
** 001 VMN 20131012 Created initial version.
** 002 OM  20140410 Fixed support case-sensitive fields in indexes.
** 003 OM  20150525 Added static method getDialectClass().
** 004 ECF 20200906 New ORM implementation.
** 005 IAS 20201219 Added support for "sqlserver2008" dialect.
**     OM  20220721 Added partial conversion-time MariaDb dialect support.
**     OM  20221018 Added support for MariaDb lenient dialect.
*/

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

import java.net.*;
import java.util.regex.*;

import com.goldencode.p2j.convert.*;
import com.goldencode.p2j.persist.*;

/**
 * A helper to P2J dialect classes. This class provides static helper methods and constants used
 * for FWD dialects.
 */
public class DialectHelper
{
   /**
    * Common prefix prepended to computed column/property names. Additional decoration will be added
    * in order to identify columns that maps case sensitive fields.
    */
   static final String CC_PREFIX = "__";
   
   /** Signature for case-insensitive character column/property names */
   public static final String INSENSITIVE_CHAR_FIELD = CC_PREFIX + "i";
   
   /** Signature for case-sensitive character column/property names */
   public static final String SENSITIVE_CHAR_FIELD   = CC_PREFIX + "s";
   
   /** Double quote character */
   public static final char DOUBLE_QUOTE = '"';

   private static final Pattern TYPE_PATTERN = Pattern.compile("\\s*type:\\s*(.*)", Pattern.CASE_INSENSITIVE);

   private static final Pattern CASE_PATTERN = Pattern.compile("\\s*case-sensitive:\\s*(.*)", Pattern.CASE_INSENSITIVE);

   // All known patterns should be matched here
   private static final Pattern CLEAN_PATTERN = Pattern.compile("\\s*(case-sensitive|type):.*", Pattern.CASE_INSENSITIVE);
   
   /**
    * Build the URL to be used for a remote connection, based on the given URL and database.
    *
    * @param   url
    *          The URL as received from the remote server.
    * @param   database
    *          The database to which this URL belongs.
    *
    * @return  The built URL as to be used for a remote connection.
    *
    * @throws  PersistenceException
    *          if the specified connection URL is invalid.
    */
   public static String buildRemoteURL(String url, Database database)
   throws PersistenceException
   {
      String origUrl = url;
      try
      {
         url = url.substring("jdbc:".length());
         URI uri = (new URI(url)).normalize();
         
         // check for localhost references.
         String host = uri.getHost().toLowerCase();
         if (InetAddress.getByName(host).isLoopbackAddress())
         {
            // use hostname stored in database object.
            host = database.getSocketAddress().getHostName();
            
            // generate new URI.
            uri = new URI(uri.getScheme(),
                          uri.getUserInfo(),
                          host,
                          uri.getPort(),
                          uri.getPath(),
                          uri.getQuery(),
                          uri.getFragment());
            
            // prepend 'jdbc:' prefix.
            url = "jdbc:" + uri;
         }
         else
         {
            // no preparation is needed
            url = origUrl;
         }
      }
      catch (Exception exc)
      {
         throw new PersistenceException("Invalid database connection URL", exc);
      }
      
      return url;
   }
   
   /**
    * Return the Java class for a dialect using Hibernate identifier.
    * 
    * @param   dialect
    *          The dialect name. Case insensitive.
    * 
    * @return  The dialect class or {@code null} if the parameter does not match any known
    *          dialect identifier.
    */
   public static Class<? extends Dialect> getDialectClass(String dialect)
   {
      switch (dialect.toLowerCase())
      {
         case "h2":
            return P2JH2Dialect.class;
         case "postgresql":
            return P2JPostgreSQLDialect.class;
         case "sqlserver2012":
            return P2JSQLServer2012Dialect.class;
         case "sqlserver2008":
            return P2JSQLServer2008Dialect.class;
         case MariaDbDialect.DIALECT_ID:
            return MariaDbDialect.class;
         case MariaDbLenientDialect.DIALECT_ID:
            return MariaDbLenientDialect.class;
         default:
            return null;
      }
   }

   /**
    * Parsing type hints in column comments.
    *
    * @param   comment
    *          column comment as provided by JDBC
    * @return  matched type or null
    */
   protected static ParmType getParmTypeFromComment(String comment)
   {
      if (comment != null && !comment.isEmpty())
      {
         Matcher matcher = TYPE_PATTERN.matcher(comment);
         if (matcher.find())
         {
            String group = matcher.group(1);
            return ParmType.fromString(group);
         }
      }
      return null;
   }

   /**
    * Parsing case sensitivity hints in column comments.
    *
    * @param   comment
    *          column comment as provided by JDBC
    * @return  matched case sensitivity or false
    */
   public static boolean getCaseSensitive(String comment)
   {
      if (comment != null && !comment.isEmpty())
      {
         Matcher matcher = CASE_PATTERN.matcher(comment);
         if (matcher.find())
         {
            String group = matcher.group(1);
            return group.equalsIgnoreCase("TRUE") || group.equalsIgnoreCase("1");
         }
      }
      return false;
   }

   /**
    * Get column comment spared of all hints.
    *
    * @param   comment
    *          column comment as provided by JDBC
    * @return  clean column comment or null for empty comment
    */
   public static String getCleanComment(String comment)
   {
      if (comment != null && !comment.isEmpty())
      {
         Matcher matcher = CLEAN_PATTERN.matcher(comment);
         return matcher.replaceAll("");
      }
      return null;
   }
}