Java Code Examples for java.sql.Types#TIMESTAMP

The following examples show how to use java.sql.Types#TIMESTAMP . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TimestampTypeCompiler.java    From sql-parser with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * User types are convertible to other user types only if
 * (for now) they are the same type and are being used to
 * implement some JDBC type.    This is sufficient for
 * date/time types; it may be generalized later for e.g.
 * comparison of any user type with one of its subtypes.
 *
 * @see TypeCompiler#convertible 
 *
 */
public boolean convertible(TypeId otherType, boolean forDataTypeFunction) {
    if (otherType.isStringTypeId() &&
        (!otherType.isLongConcatableTypeId())) {
        return true;
    }

    int otherJDBCTypeId = otherType.getJDBCTypeId();

    /*
    ** At this point, we have only date/time.    If
    ** same type, convert always ok.
    */
    if (otherJDBCTypeId == Types.TIMESTAMP) {
        return true;
    }

    /*
    ** Otherwise, we can convert timestamp to
    ** date or time only.
    */
    return ((otherJDBCTypeId == Types.DATE) ||
            (otherJDBCTypeId == Types.TIME));
}
 
Example 2
Source File: StatementCreatorUtils.java    From effectivejava with Apache License 2.0 6 votes vote down vote up
/**
 * Derive a default SQL type from the given Java type.
 * @param javaType the Java type to translate
 * @return the corresponding SQL type, or {@code null} if none found
 */
public static int javaTypeToSqlParameterType(Class<?> javaType) {
	Integer sqlType = javaTypeToSqlTypeMap.get(javaType);
	if (sqlType != null) {
		return sqlType;
	}
	if (Number.class.isAssignableFrom(javaType)) {
		return Types.NUMERIC;
	}
	if (isStringValue(javaType)) {
		return Types.VARCHAR;
	}
	if (isDateValue(javaType) || Calendar.class.isAssignableFrom(javaType)) {
		return Types.TIMESTAMP;
	}
	return SqlTypeValue.TYPE_UNKNOWN;
}
 
Example 3
Source File: TimestampConverter.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public Object convertFromString(String textRep, int sqlTypeCode) throws ConversionException
{
    if (textRep == null)
    {
        return null;
    }
    else if (sqlTypeCode == Types.TIMESTAMP)
    {
        return Timestamp.valueOf(textRep);
    }
    else
    {
        return textRep;
    }
}
 
Example 4
Source File: OracleDialect.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public String getSelectClauseNullString(int sqlType) {
	switch(sqlType) {
		case Types.VARCHAR:
		case Types.CHAR:
			return "to_char(null)";
		case Types.DATE:
		case Types.TIMESTAMP:
		case Types.TIME:
			return "to_date(null)";
		default:
			return "to_number(null)";
	}
}
 
Example 5
Source File: TestResultSetMetaData.java    From commons-beanutils with Apache License 2.0 5 votes vote down vote up
public Integer getColumnType(final int columnIndex) throws SQLException {
        final String columnName = getColumnName(columnIndex);
        int sqlType = Types.OTHER;
        if (columnName.equals("bigDecimalProperty")) {
            sqlType = Types.DECIMAL;
// Types.BOOLEAN only introduced in JDK 1.4
//        } else if (columnName.equals("booleanProperty")) {
//            sqlType = Types.BOOLEAN;
        } else if (columnName.equals("byteProperty")) {
            sqlType = Types.TINYINT;
        } else if (columnName.equals("dateProperty")) {
            sqlType = Types.DATE;
        } else if (columnName.equals("doubleProperty")) {
            sqlType = Types.DOUBLE;
        } else if (columnName.equals("floatProperty")) {
            sqlType = Types.FLOAT;
        } else if (columnName.equals("intProperty")) {
            sqlType = Types.INTEGER;
        } else if (columnName.equals("longProperty")) {
            sqlType = Types.BIGINT;
        } else if (columnName.equals("nullProperty")) {
            sqlType = Types.VARCHAR;
        } else if (columnName.equals("shortProperty")) {
            sqlType = Types.SMALLINT;
        } else if (columnName.equals("stringProperty")) {
            sqlType = Types.VARCHAR;
        } else if (columnName.equals("timeProperty")) {
            sqlType = Types.TIME;
        } else if (columnName.equals("timestampProperty")) {
            sqlType = Types.TIMESTAMP;
        } else {
            sqlType = Types.OTHER;
        }
        return new Integer(sqlType);
    }
 
Example 6
Source File: SqlQueryBuilder.java    From incubator-pinot with Apache License 2.0 5 votes vote down vote up
public PreparedStatement createInsertStatement(Connection conn, String tableName,
    AbstractEntity entity) throws Exception {
  if (!insertSqlMap.containsKey(tableName)) {
    String insertSql = generateInsertSql(tableName,
        entityMappingHolder.columnInfoPerTable.get(tableName.toLowerCase()));
    insertSqlMap.put(tableName, insertSql);
    LOG.debug(insertSql);
  }

  String sql = insertSqlMap.get(tableName);
  PreparedStatement preparedStatement =
      conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
  LinkedHashMap<String, ColumnInfo> columnInfoMap =
      entityMappingHolder.columnInfoPerTable.get(tableName);
  int parameterIndex = 1;
  for (ColumnInfo columnInfo : columnInfoMap.values()) {
    if (columnInfo.field != null
        && !AUTO_UPDATE_COLUMN_SET.contains(columnInfo.columnNameInDB.toLowerCase())) {
      Object val = columnInfo.field.get(entity);
      LOG.debug("Setting value: {} for:{} sqlType:{}", val, columnInfo.columnNameInDB,
          columnInfo.sqlType);
      if (val != null) {
        if (columnInfo.sqlType == Types.CLOB) {
          Clob clob = conn.createClob();
          clob.setString(1, val.toString());
          preparedStatement.setClob(parameterIndex++, clob);
        } else if (columnInfo.sqlType == Types.TIMESTAMP) {
          preparedStatement.setObject(parameterIndex++, val, columnInfo.sqlType);
        } else {
          preparedStatement.setObject(parameterIndex++, val.toString(), columnInfo.sqlType);
        }

      } else {
        preparedStatement.setNull(parameterIndex++, columnInfo.sqlType);
      }
    }
  }
  return preparedStatement;

}
 
Example 7
Source File: Backup.java    From Jantent with MIT License 5 votes vote down vote up
public String getSQLValue(Table table, Row row, int index) {
	Column column = table.getColumns().get(index);
	int type = column.getDataType();
	if (row.get(index) == null) {
		return "null";
	} else {
		switch (type) {
		case Types.CHAR:
		case Types.VARCHAR:
		case Types.LONGNVARCHAR:
		case Types.NCHAR:
		case Types.NVARCHAR:
		case Types.LONGVARCHAR:
			return "\"" + row.getString(index) + "\"";

		case Types.DATE:
			return "\"" +  DATE_FORMAT.format(row.getDate(index)) + "\"";
			
		case Types.TIME:
			return "\"" + TIME_FORMAT.format(row.getDate(index)) + "\"";
			
		case Types.TIMESTAMP:
			return "\"" + DATE_TIME_FORMAT.format(row.getDate(index)) + "\"";

		default:
			return row.getString(index);
		}

	}
}
 
Example 8
Source File: SFJsonResultSet.java    From snowflake-jdbc with Apache License 2.0 5 votes vote down vote up
@Override
public BigDecimal getBigDecimal(int columnIndex) throws SFException
{
  logger.debug(
      "public BigDecimal getBigDecimal(int columnIndex)");


  // Column index starts from 1, not 0.
  Object obj = getObjectInternal(columnIndex);

  if (obj == null)
  {
    return null;
  }
  int columnType = resultSetMetaData.getColumnType(columnIndex);
  try
  {
    if (columnType != Types.TIME && columnType != Types.TIMESTAMP)
    {
      return new BigDecimal(obj.toString());
    }
    throw new SFException(ErrorCode.INVALID_VALUE_CONVERT,
                          columnType, SnowflakeUtil.BIG_DECIMAL_STR, obj);

  }
  catch (NumberFormatException ex)
  {
    throw new SFException(ErrorCode.INVALID_VALUE_CONVERT,
                          columnType, SnowflakeUtil.BIG_DECIMAL_STR, obj);
  }

}
 
Example 9
Source File: SqlServerTransferHelper.java    From evosql with Apache License 2.0 5 votes vote down vote up
int convertFromType(int type) {

        // MS SQL 7 specific problems (Northwind database)
        if (type == 11) {
            tracer.trace("Converted DATETIME (type 11) to TIMESTAMP");

            type = Types.TIMESTAMP;
        } else if (type == -9) {
            tracer.trace("Converted NVARCHAR (type -9) to VARCHAR");

            type = Types.VARCHAR;
        } else if (type == -8) {
            tracer.trace("Converted NCHAR (type -8) to VARCHAR");

            type = Types.VARCHAR;
        } else if (type == -10) {
            tracer.trace("Converted NTEXT (type -10) to VARCHAR");

            type = Types.VARCHAR;
        } else if (type == -1) {
            tracer.trace("Converted LONGTEXT (type -1) to LONGVARCHAR");

            type = Types.LONGVARCHAR;
        }

        return (type);
    }
 
Example 10
Source File: Table.java    From HongsCORE with MIT License 5 votes vote down vote up
/**
 * 获取日期(时间)取值
 * @param name
 * @param time
 * @return
 */
protected Object getDtval(String name, long time)
{
  Map item = (Map) fields.get(name);
  int type = (Integer) item.get("type");
  int size = (Integer) item.get("size");
  switch (type)
  {
    case Types.DATE:
      return new Date(time);
    case Types.TIME:
      return new Time(time);
    case Types.TIMESTAMP:
      return new Timestamp(time);
    case Types.INTEGER  :
      return time / 1000;
  }
  /**
   * 部分数据库空表时取不到类型
   * 但如果给了宽度则可估算容量
   * 0 为未知, 十位够到 2200 年
   * 但很多人习惯设 INTEGER(11)
   */
  if (size >= 01 && size <= 11) {
      return time / 1000;
  } else {
      return time ;
  }
}
 
Example 11
Source File: EventCallbackListener.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
/**
 * Build the query string to insert a row to the backend database
 * 
 * @param event
 *          the callback event
 * @return SQL query string to insert a row to the back-end database
 * @throws SQLException
 */
private String buildInsertQuery(Event event) throws SQLException {

  ResultSetMetaData meta = event.getResultSetMetaData();

  List<Object> newRow = event.getNewRow();

  StringBuilder query = new StringBuilder();

  // insert into table_name values (...); assume
  // Note: insert into table_name(col1, col2 ...) values (...) is not
  // supported here
  //query.append("INSERT INTO " + meta.getSchemaName(1) + "."
  //    + meta.getTableName(1) + " VALUES (");
  query.append("INSERT INTO " + meta.getSchemaName(1) + "." + meta.getTableName(1) + "_ONE VALUES (");

  for (int i = 1; i <= meta.getColumnCount(); i++) {

    int type = meta.getColumnType(i);

    Object value = newRow.get(i - 1);

    switch (type) {
    case Types.BIGINT:
    case Types.DECIMAL:
    case Types.NUMERIC:
    case Types.SMALLINT:
    case Types.TINYINT:
    case Types.INTEGER:
    case Types.FLOAT:
    case Types.DOUBLE:
    case Types.REAL:
    case Types.TIMESTAMP:
      query.append(value + ",");
      break;
    default:
      query.append("'" + value + "',");
    }
  }

  query.delete(query.length() - 1, query.length());

  query.append(");");

  return query.toString();

}
 
Example 12
Source File: DataTypeUtilities.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
public static int getColumnDisplaySize(int typeId, int storageLength) {
  int size;
  switch (typeId) {
  case Types.TIMESTAMP:
    size = 26;
    break;
  case Types.DATE:
    size = 10;
    break;
  case Types.TIME:
    size = 8;
    break;
  case Types.INTEGER:
    size = 11;
    break;
  case Types.SMALLINT:
    size = 6;
    break;
  case Types.REAL:
  case Types.FLOAT:
    size = 13;
    break;
  case Types.DOUBLE:
    size = 22;
    break;
  case Types.TINYINT:
    size = 15;
    break;

  case Types.BINARY:
  case Types.VARBINARY:
  case Types.LONGVARBINARY:
  case Types.BLOB:
    size = 2 * storageLength;
    if (size < 0)
      size = Integer.MAX_VALUE;
    break;

  case Types.BIGINT:
    size = 20;
    break;
  case Types.BIT:
  case Types.BOOLEAN:
    // Types.BIT == SQL BOOLEAN, so 5 chars for 'false'
    // In JDBC 3.0, Types.BIT or Types.BOOLEAN = SQL BOOLEAN
    size = 5;
    break;
  default:
    // MaximumWidth is -1 when it is unknown.
    int w = storageLength;
    size = (w > 0 ? w : JDBC30Translation.DEFAULT_COLUMN_DISPLAY_SIZE);
    break;
  }
  return size;
}
 
Example 13
Source File: SFResultSetMetaData.java    From snowflake-jdbc with Apache License 2.0 4 votes vote down vote up
private Integer calculateDisplaySize(SnowflakeColumnMetadata columnMetadata)
{
  int columnType = columnMetadata.getType();
  switch (columnType)
  {
    case Types.CHAR:
    case Types.VARCHAR:
    case Types.BINARY:
      return columnMetadata.getLength();
    case Types.INTEGER:
    case Types.BIGINT:
      // + 1 because number can be negative, it could be -20 for number(2,0)
      return columnMetadata.getPrecision() + 1;
    case Types.DECIMAL:
      // first + 1 because number can be negative, second + 1 because it always
      // include decimal point.
      // i.e. number(2, 1) could be -1.3
      return columnMetadata.getPrecision() + 1 + 1;
    case Types.DOUBLE:
      // Hard code as 24 since the longest float
      // represented in char is
      // -2.2250738585072020E−308
      return 24;
    case Types.DATE:
      return dateStringLength;
    case Types.TIME:
      return timeStringLength;
    case SnowflakeUtil.EXTRA_TYPES_TIMESTAMP_LTZ:
      return timestampLTZStringLength;
    case SnowflakeUtil.EXTRA_TYPES_TIMESTAMP_TZ:
      return timestampTZStringLength;
    case Types.TIMESTAMP:
      return timestampNTZStringLength;
    case Types.BOOLEAN:
      // Hard code as 5 since the longest char to represent
      // a boolean would be false, which is 5.
      return 5;
    default:
      return 25;
  }
}
 
Example 14
Source File: TableReadContext.java    From datacollector with Apache License 2.0 4 votes vote down vote up
private static void setParamVal(
    DatabaseVendor vendor,
    PreparedStatement ps,
    int paramIdx,
    int sqlType,
    String paramVal
) throws SQLException, StageException {
  Utils.checkState(
      OffsetQueryUtil.SQL_TYPE_TO_FIELD_TYPE.containsKey(sqlType) || TableContextUtil.VENDOR_PARTITIONABLE_TYPES.getOrDefault(vendor, Collections.emptySet()).contains(sqlType),
      Utils.format("Unsupported Partition Offset Type: {}", sqlType)
  );
  //All Date/Time Types are stored as long offsets
  //Parse string to get long.
  switch (sqlType) {
    case Types.TIME:
      ps.setTime(
          paramIdx,
          new java.sql.Time(Long.valueOf(paramVal))
      );
      break;
    case Types.DATE:
      ps.setDate(
          paramIdx,
          new java.sql.Date(Long.valueOf(paramVal))
      );
      break;
    case Types.TIMESTAMP:
      Timestamp ts = TableContextUtil.getTimestampForOffsetValue(paramVal);
      ps.setTimestamp(
          paramIdx,
          ts
      );
      break;
    default:
      // Oracle must be special
      switch (vendor) {
        case ORACLE:
          if(TableContextUtil.VENDOR_PARTITIONABLE_TYPES.get(DatabaseVendor.ORACLE).contains(sqlType)) {
            switch (sqlType) {
              case TableContextUtil.TYPE_ORACLE_TIMESTAMP_WITH_TIME_ZONE:
              case TableContextUtil.TYPE_ORACLE_TIMESTAMP_WITH_LOCAL_TIME_ZONE:
                // We insert the timestamp as String
                ps.setObject(paramIdx, paramVal == null ? null : ZonedDateTime.parse(paramVal, DateTimeFormatter.ISO_OFFSET_DATE_TIME));
                return;
              default:
                throw new IllegalStateException(Utils.format("Unsupported type for ORACLE database: {}", sqlType));
            }
          }
          break;
        case SQL_SERVER:
          if(TableContextUtil.VENDOR_PARTITIONABLE_TYPES.get(DatabaseVendor.SQL_SERVER).contains(sqlType)) {
            if (sqlType == TableContextUtil.TYPE_SQL_SERVER_DATETIMEOFFSET) {
             // For Microsoft SQL DATETIMEOFFSET field, send the sqlType (-155) hint to the database as well
             // because otherwise SQLServer complains with - Failed to convert 'Unknown' to 'Unknown' type error
              ps.setObject(paramIdx, paramVal, sqlType);
              return;
            }
          }
          break;
      }
      ps.setObject(
          paramIdx,
          Field.create(OffsetQueryUtil.SQL_TYPE_TO_FIELD_TYPE.get(sqlType), paramVal).getValue()
      );
  }
}
 
Example 15
Source File: AbstractHive_1_1QLProcessor.java    From nifi with Apache License 2.0 4 votes vote down vote up
/**
 * Determines how to map the given value to the appropriate JDBC data jdbcType and sets the parameter on the
 * provided PreparedStatement
 *
 * @param stmt           the PreparedStatement to set the parameter on
 * @param attrName       the name of the attribute that the parameter is coming from - for logging purposes
 * @param parameterIndex the index of the HiveQL parameter to set
 * @param parameterValue the value of the HiveQL parameter to set
 * @param jdbcType       the JDBC Type of the HiveQL parameter to set
 * @throws SQLException if the PreparedStatement throws a SQLException when calling the appropriate setter
 */
protected void setParameter(final PreparedStatement stmt, final String attrName, final int parameterIndex, final String parameterValue, final int jdbcType) throws SQLException {
    if (parameterValue == null) {
        stmt.setNull(parameterIndex, jdbcType);
    } else {
        try {
            switch (jdbcType) {
                case Types.BIT:
                case Types.BOOLEAN:
                    stmt.setBoolean(parameterIndex, Boolean.parseBoolean(parameterValue));
                    break;
                case Types.TINYINT:
                    stmt.setByte(parameterIndex, Byte.parseByte(parameterValue));
                    break;
                case Types.SMALLINT:
                    stmt.setShort(parameterIndex, Short.parseShort(parameterValue));
                    break;
                case Types.INTEGER:
                    stmt.setInt(parameterIndex, Integer.parseInt(parameterValue));
                    break;
                case Types.BIGINT:
                    stmt.setLong(parameterIndex, Long.parseLong(parameterValue));
                    break;
                case Types.REAL:
                    stmt.setFloat(parameterIndex, Float.parseFloat(parameterValue));
                    break;
                case Types.FLOAT:
                case Types.DOUBLE:
                    stmt.setDouble(parameterIndex, Double.parseDouble(parameterValue));
                    break;
                case Types.DECIMAL:
                case Types.NUMERIC:
                    stmt.setBigDecimal(parameterIndex, new BigDecimal(parameterValue));
                    break;
                case Types.DATE:
                    stmt.setDate(parameterIndex, new Date(Long.parseLong(parameterValue)));
                    break;
                case Types.TIME:
                    stmt.setTime(parameterIndex, new Time(Long.parseLong(parameterValue)));
                    break;
                case Types.TIMESTAMP:
                    stmt.setTimestamp(parameterIndex, new Timestamp(Long.parseLong(parameterValue)));
                    break;
                case Types.CHAR:
                case Types.VARCHAR:
                case Types.LONGNVARCHAR:
                case Types.LONGVARCHAR:
                    stmt.setString(parameterIndex, parameterValue);
                    break;
                default:
                    stmt.setObject(parameterIndex, parameterValue, jdbcType);
                    break;
            }
        } catch (SQLException e) {
            // Log which attribute/parameter had an error, then rethrow to be handled at the top level
            getLogger().error("Error setting parameter {} to value from {} ({})", new Object[]{parameterIndex, attrName, parameterValue}, e);
            throw e;
        }
    }
}
 
Example 16
Source File: DataDrivenDBInputFormat.java    From aliyun-maxcompute-data-collectors with Apache License 2.0 4 votes vote down vote up
/**
 * @return the DBSplitter implementation to use to divide the table/query
 * into InputSplits.
 */
protected DBSplitter getSplitter(int sqlDataType, long splitLimit) {
  switch (sqlDataType) {
  case Types.NUMERIC:
  case Types.DECIMAL:
    if(splitLimit >= 0) {
      throw new IllegalArgumentException("split-limit is supported only with Integer and Date columns");
    }
    return new BigDecimalSplitter();

  case Types.BIT:
  case Types.BOOLEAN:
    if(splitLimit >= 0) {
      throw new IllegalArgumentException("split-limit is supported only with Integer and Date columns");
    }
    return new BooleanSplitter();

  case Types.INTEGER:
  case Types.TINYINT:
  case Types.SMALLINT:
  case Types.BIGINT:
    return new IntegerSplitter();

  case Types.REAL:
  case Types.FLOAT:
  case Types.DOUBLE:
    if(splitLimit >= 0) {
      throw new IllegalArgumentException("split-limit is supported only with Integer and Date columns");
    }
    return new FloatSplitter();

  case Types.NVARCHAR:
  case Types.NCHAR:
    if(splitLimit >= 0) {
      throw new IllegalArgumentException("split-limit is supported only with Integer and Date columns");
    }
    return new NTextSplitter();

  case Types.CHAR:
  case Types.VARCHAR:
  case Types.LONGVARCHAR:
    if(splitLimit >= 0) {
       throw new IllegalArgumentException("split-limit is supported only with Integer and Date columns");
    }
    return new TextSplitter();

  case Types.DATE:
  case Types.TIME:
  case Types.TIMESTAMP:
    return new DateSplitter();

  default:
    // TODO: Support BINARY, VARBINARY, LONGVARBINARY, DISTINCT, CLOB,
    // BLOB, ARRAY, STRUCT, REF, DATALINK, and JAVA_OBJECT.
    if(splitLimit >= 0) {
      throw new IllegalArgumentException("split-limit is supported only with Integer and Date columns");
    }
    return null;
  }
}
 
Example 17
Source File: DataTypeDateTime64.java    From ClickHouse-Native-JDBC with Apache License 2.0 4 votes vote down vote up
@Override
public int sqlTypeId() {
    return Types.TIMESTAMP;
}
 
Example 18
Source File: TypeMetadata.java    From jaybird with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * Returns the column size (precision) of the type.
 * <p>
 * The value returned follows the definition used in {@link java.sql.DatabaseMetaData}, as established in
 * {@link java.sql.DatabaseMetaData#getColumns(String, String, String, String)} for {@code COLUMN_SIZE}. The same
 * definition is used for database metadata columns {@code PRECISION} in, among others,
 * {@link java.sql.DatabaseMetaData#getFunctionColumns(String, String, String, String)}.
 * </p>
 * <p>
 * This method will also return any non-zero precision information stored for other datatypes than those listed in
 * the {@code COLUMN_SIZE} definition in the JDBC API.
 * </p>
 *
 * @return The column size as defined in {@link java.sql.DatabaseMetaData}, or {@code null}.
 */
public Integer getColumnSize() {
    switch (jdbcType) {
    case Types.FLOAT:
        return isFloatBinaryPrecision() ? FLOAT_BINARY_PRECISION : FLOAT_DECIMAL_PRECISION;
    case Types.DOUBLE:
        return isFloatBinaryPrecision() ? DOUBLE_BINARY_PRECISION : DOUBLE_DECIMAL_PRECISION;
    case Types.CHAR:
    case Types.VARCHAR:
    case Types.BINARY:
    case Types.VARBINARY:
        return characterLength;
    case Types.BIGINT:
        return BIGINT_PRECISION;
    case Types.INTEGER:
        return INTEGER_PRECISION;
    case Types.SMALLINT:
        return SMALLINT_PRECISION;
    case Types.BOOLEAN:
        return BOOLEAN_BINARY_PRECISION;
    case Types.NUMERIC:
    case Types.DECIMAL:
        switch (type) {
        case double_type:
        case d_float_type:
        case int64_type:
            return coalesce(precision, NUMERIC_BIGINT_PRECISION);
        case integer_type:
            return coalesce(precision, NUMERIC_INTEGER_PRECISION);
        case smallint_type:
            return coalesce(precision, NUMERIC_SMALLINT_PRECISION);
        case int128_type:
            return coalesce(precision, NUMERIC_INT128_PRECISION);
        default:
            throw new IllegalStateException(String.format(
                    "Incorrect derivation of NUMERIC/DECIMAL precision for jdbcType %d, type %d, subType %d, scale %d",
                    jdbcType, type, subType, scale));
        }
    case Types.DATE:
        return DATE_PRECISION;
    case Types.TIME:
        return TIME_PRECISION;
    case Types.TIMESTAMP:
        return TIMESTAMP_PRECISION;
    case Types.TIME_WITH_TIMEZONE:
        return TIME_WITH_TIMEZONE_PRECISION;
    case Types.TIMESTAMP_WITH_TIMEZONE:
        return TIMESTAMP_WITH_TIMEZONE_PRECISION;
    case JaybirdTypeCodes.DECFLOAT:
        switch (type) {
        case dec16_type:
            return DECFLOAT_16_PRECISION;
        case dec34_type:
            return DECFLOAT_34_PRECISION;
        default:
            throw new IllegalStateException(String.format(
                    "Incorrect derivation of DECFLOAT precision for jdbcType %d, type %d, subType %d, scale %d",
                    jdbcType, type, subType, scale));
        }
    }
    // If we have non-default, non-zero precision, report it
    return coalesce(precision, 0) != 0 ? precision : null;
}
 
Example 19
Source File: MultiShardTestUtils.java    From elastic-db-tools-for-java with MIT License 4 votes vote down vote up
/**
 * Helper to determine if a particular SqlDbType is a timestamp.
 */
private static boolean notTimestampField(int curFieldType) {
    return curFieldType != Types.TIMESTAMP;
}
 
Example 20
Source File: JdbcUtil.java    From datacollector with Apache License 2.0 4 votes vote down vote up
private static Map<String, String> getMinMaxOffsetValueHelper(
    String minMaxQuery,
    DatabaseVendor vendor,
    Connection connection,
    String schema,
    String tableName,
    QuoteChar quoteChar,
    Collection<String> offsetColumnNames
) throws SQLException {
  Map<String, String> minMaxOffsetValues = new HashMap<>();
  final String qualifiedTableName = TableContextUtil.getQuotedQualifiedTableName(
      schema,
      tableName,
      quoteChar.getQuoteCharacter()
  );
  for (String offsetColumn : offsetColumnNames) {
    final String qualifiedOffsetColumn = TableContextUtil.getQuotedObjectName(offsetColumn, quoteChar.getQuoteCharacter());
    final String minMaxOffsetQuery = String.format(minMaxQuery, qualifiedOffsetColumn, qualifiedTableName);
    LOG.debug("Issuing {} offset query: {}",
          minMaxQuery.equals(MIN_OFFSET_VALUE_QUERY) ? "MINIMUM" : "MAXIMUM", minMaxOffsetQuery);
    try (
      Statement st = connection.createStatement();
      ResultSet rs = st.executeQuery(minMaxOffsetQuery)
    ) {
      if (rs.next()) {
        String minMaxValue = null;
        final int colType = rs.getMetaData().getColumnType(MIN_MAX_OFFSET_VALUE_QUERY_RESULT_SET_INDEX);

        switch (vendor) {
          case ORACLE:
            if(TableContextUtil.VENDOR_PARTITIONABLE_TYPES.get(DatabaseVendor.ORACLE).contains(colType)) {
              switch (colType) {
                case TableContextUtil.TYPE_ORACLE_TIMESTAMP_WITH_LOCAL_TIME_ZONE:
                case TableContextUtil.TYPE_ORACLE_TIMESTAMP_WITH_TIME_ZONE:
                  OffsetDateTime offsetDateTime = rs.getObject(MIN_MAX_OFFSET_VALUE_QUERY_RESULT_SET_INDEX, OffsetDateTime.class);
                  if(offsetDateTime != null) {
                    minMaxValue = offsetDateTime.toZonedDateTime().format(DateTimeFormatter.ISO_OFFSET_DATE_TIME);
                  }
                  break;
                default:
                  throw new IllegalStateException(Utils.format("Unexpected type: {}", colType));
              }
            }
            break;

          case SQL_SERVER:
            if(TableContextUtil.VENDOR_PARTITIONABLE_TYPES.get(DatabaseVendor.SQL_SERVER).contains(colType)) {
              if (colType == TableContextUtil.TYPE_SQL_SERVER_DATETIMEOFFSET) {
                DateTimeOffset dateTimeOffset = rs.getObject(MIN_MAX_OFFSET_VALUE_QUERY_RESULT_SET_INDEX, DateTimeOffset.class);
                if (dateTimeOffset != null) {
                  minMaxValue = dateTimeOffset.getOffsetDateTime().toZonedDateTime().format(DateTimeFormatter.ISO_OFFSET_DATE_TIME);
                }
              }
            }
            break;
        }

        if(minMaxValue == null) {
          switch (colType) {
            case Types.DATE:
              java.sql.Date date = rs.getDate(MIN_MAX_OFFSET_VALUE_QUERY_RESULT_SET_INDEX);
              if (date != null) {
                minMaxValue = String.valueOf(
                    getEpochMillisFromSqlDate(date)
                );
              }
              break;
            case Types.TIME:
              java.sql.Time time = rs.getTime(MIN_MAX_OFFSET_VALUE_QUERY_RESULT_SET_INDEX);
              if (time != null) {
                minMaxValue = String.valueOf(
                    getEpochMillisFromSqlTime(time)
                );
              }
              break;
            case Types.TIMESTAMP:
              Timestamp timestamp = rs.getTimestamp(MIN_MAX_OFFSET_VALUE_QUERY_RESULT_SET_INDEX);
              if (timestamp != null) {
                final Instant instant = timestamp.toInstant();
                minMaxValue = String.valueOf(instant.toEpochMilli());
              }
              break;
            default:
              minMaxValue = rs.getString(MIN_MAX_OFFSET_VALUE_QUERY_RESULT_SET_INDEX);
              break;
          }
        }
        if (minMaxValue != null) {
          minMaxOffsetValues.put(offsetColumn, minMaxValue);
        }
      } else {
        LOG.warn("Unable to get minimum offset value using query {}; result set had no rows", minMaxOffsetQuery);
      }
    }
  }

  return minMaxOffsetValues;
}