package net.northking.cctp.maven.analyse.util;


import net.northking.cctp.maven.analyse.Messages;


import java.sql.JDBCType;
import java.sql.Types;

/**
 * 数据库SQL数据类型与JAVA语言数据类型转换工具
 *
 * @author 谢秀松
 * @since 1.0
 */
public final class TypeSqlToJava
{

  /**
   * Integer 类型最大长度
   */
  public static final int INT_MAX_LEN = 9;

  /**
   * Long 类型最大长度
   */
  public static final int LONG_MAX_LEN = 17;

  /**
   * 隐藏构造函数
   */
  private TypeSqlToJava()
  {
  }

  /**
   * 将SQL数据类型转换为Java数据类型
   *
   * @param sqlType SQL类型
   * @param size    长度
   * @param digits  精度
   * @return JAVA类型
   */
  public static String sqlToJava(final int sqlType, final int size, final int digits)
  {
    String javaType;
    switch (sqlType)
    {
      case Types.BIT:
      case Types.TINYINT:
        javaType = "Boolean";
        break;
      case Types.CHAR:
      case Types.VARCHAR:
      case Types.LONGVARCHAR:
        javaType = "String";
        break;
      case Types.DATE:
      case Types.TIME:
      case Types.TIMESTAMP:
        javaType = "Date";
        break;
      case Types.FLOAT:
      case Types.REAL:
        javaType = "Float";
        break;
      case Types.DOUBLE:
        javaType = "Double";
        break;
      case Types.BIGINT:
        javaType = "Long";
        break;
      case Types.INTEGER:
      case Types.SMALLINT:
        javaType = "Integer";
        break;
      case Types.DECIMAL:
      case Types.NUMERIC:
        if (digits == 0)
        {
          if (size < INT_MAX_LEN)
          {
            javaType = "Integer";
          } else if (size <= LONG_MAX_LEN)
          {
            javaType = "Long";
          } else
          {
            javaType = "BigDecimal";
          }
        } else
        {
          javaType = "BigDecimal";
        }
        break;
      case Types.CLOB:
      case Types.BLOB:
      default:
        javaType = "InputStream";
        break;
    }
    Messages.info("Print.SqlToJava", sqlType, javaType);
    return javaType;
  }

  /**
   * SQL类型转JDBC类型
   *
   * @param sqlType SQL类型
   * @param size    长度
   * @param digits  精度
   * @return JDBC类型
   */
  public static String sqlToJdbc(final int sqlType, final int size, final int digits)
  {
    String jdbcType;
    switch (sqlType)
    {
      case Types.BIT:
      case Types.TINYINT:
      case Types.CHAR:
      case Types.VARCHAR:
      case Types.LONGVARCHAR:
      case Types.DATE:
      case Types.TIME:
      case Types.TIMESTAMP:
      case Types.FLOAT:
      case Types.REAL:
      case Types.DOUBLE:
      case Types.BIGINT:
      case Types.INTEGER:
      case Types.SMALLINT:
      case Types.DECIMAL:
      case Types.NUMERIC:
        jdbcType = JDBCType.valueOf(sqlType).getName();
        break;
      case Types.CLOB:
      case Types.BLOB:
      default:
        jdbcType = "BLOB";
        break;
    }

    Messages.info("Print.SqlToJDBC", sqlType, jdbcType);
    return jdbcType;
  }
}

