Java Code Examples for java.sql.Types#VARCHAR

The following examples show how to use java.sql.Types#VARCHAR . 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: TajoTypeUtil.java    From tajo with Apache License 2.0 6 votes vote down vote up
public static int getJavaSqlType(Type type) {
  switch (type) {
    case INT1: return Types.TINYINT;
    case INT2: return Types.SMALLINT;
    case INT4: return Types.INTEGER;
    case INT8: return Types.BIGINT;
    case FLOAT4: return Types.FLOAT;
    case FLOAT8: return Types.DOUBLE;
    case VARCHAR:
    case TEXT: return Types.VARCHAR;
    case DATE: return Types.DATE;
    case TIME: return Types.TIME;
    case TIMESTAMP: return Types.TIMESTAMP;
    case NUMERIC: return Types.DECIMAL;
    default: return Types.VARCHAR;
  }
}
 
Example 2
Source File: Cursor.java    From vertx-sql-client with Apache License 2.0 6 votes vote down vote up
public final LocalTime getTime(int column) {
      if (isNull(column))
        return null;
        switch (jdbcTypes_[column - 1]) {
        case Types.TIME:
            return get_TIME(column);
        case Types.TIMESTAMP:
//            return getTimeFromTIMESTAMP(column, cal);
            throw new UnsupportedOperationException();
        case Types.CHAR:
            return CrossConverters.getTimeFromString(get_CHAR(column));
        case Types.VARCHAR:
        case Types.LONGVARCHAR:
            return CrossConverters.getTimeFromString(get_VARCHAR(column));
        default:
            throw coercionError( "java.sql.Time", column );
        }
    }
 
Example 3
Source File: JdbcTypeUtil.java    From canal with Apache License 2.0 5 votes vote down vote up
public static Class<?> jdbcType2javaType(int jdbcType) {
    switch (jdbcType) {
        case Types.BIT:
        case Types.BOOLEAN:
            // return Boolean.class;
        case Types.TINYINT:
            return Byte.TYPE;
        case Types.SMALLINT:
            return Short.class;
        case Types.INTEGER:
            return Integer.class;
        case Types.BIGINT:
            return Long.class;
        case Types.DECIMAL:
        case Types.NUMERIC:
            return BigDecimal.class;
        case Types.REAL:
            return Float.class;
        case Types.FLOAT:
        case Types.DOUBLE:
            return Double.class;
        case Types.CHAR:
        case Types.VARCHAR:
        case Types.LONGVARCHAR:
            return String.class;
        case Types.BINARY:
        case Types.VARBINARY:
        case Types.LONGVARBINARY:
        case Types.BLOB:
            return byte[].class;
        case Types.DATE:
            return java.sql.Date.class;
        case Types.TIME:
            return Time.class;
        case Types.TIMESTAMP:
            return Timestamp.class;
        default:
            return String.class;
    }
}
 
Example 4
Source File: UserRepositoryJDBCImpl.java    From elucidate-server with MIT License 5 votes vote down vote up
@Override
@Transactional(readOnly = true)
public Optional<SecurityUser> getUser(String uid) {
    String sql = "SELECT u.* FROM security_user u WHERE u.uid = ?";
    Object[] params = {uid,};
    int[] sqlTypes = {Types.VARCHAR,};

    return Optional.ofNullable(queryForObject(sql, params, sqlTypes, new SecurityUserRowMapper()));
}
 
Example 5
Source File: GrantRevokeTest.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * Append a particular SQL datatype value to the given StringBuilder
 *
 * @param sb the StringBuilder to append the value
 * @param type the java.sql.Types value to append
 */
static void appendColumnValue(StringBuilder sb, int type)
{
    switch(type)
    {
    case Types.BIGINT:
    case Types.DECIMAL:
    case Types.DOUBLE:
    case Types.FLOAT:
    case Types.INTEGER:
    case Types.NUMERIC:
    case Types.REAL:
    case Types.SMALLINT:
    case Types.TINYINT:
        sb.append("0");
        break;

    case Types.CHAR:
    case Types.VARCHAR:
        sb.append("' '");
        break;

    case Types.DATE:
        sb.append("CURRENT_DATE");
        break;

    case Types.TIME:
        sb.append("CURRENT_TIME");
        break;

    case Types.TIMESTAMP:
        sb.append("CURRENT_TIMESTAMP");
        break;

    default:
        sb.append("null");
        break;
    }
}
 
Example 6
Source File: DB2ColumnMetadataReaderTest.java    From virtual-schemas with MIT License 5 votes vote down vote up
@ValueSource(ints = { Types.VARCHAR, Types.NVARCHAR, Types.LONGNVARCHAR, Types.CHAR, Types.NCHAR,
        Types.LONGNVARCHAR })
@ParameterizedTest
void testMapJdbcVarcharSizeGreaterThanExasolMaxVarcharSize(final int type) {
    final JdbcTypeDescription jdbcTypeDescription = new JdbcTypeDescription(type, 0,
            DataType.MAX_EXASOL_VARCHAR_SIZE + 1, 0, "");
    assertThat(this.db2ColumnMetadataReader.mapJdbcType(jdbcTypeDescription),
            equalTo(DataType.createVarChar(DataType.MAX_EXASOL_VARCHAR_SIZE, DataType.ExaCharset.UTF8)));
}
 
Example 7
Source File: HiveJdbcBridgeUtils.java    From HiveJdbcStorageHandler with Apache License 2.0 5 votes vote down vote up
public static int toSqlType(Class<?> clazz) throws IOException {
    if(clazz == String.class) {
        return Types.VARCHAR;
    }
    if(clazz == Float.class) {
        return Types.FLOAT;
    }
    if(clazz == Double.class) {
        return Types.DOUBLE;
    }
    if(clazz == Boolean.class) {
        return Types.BOOLEAN;
    }
    if(clazz == Byte.class) {
        return Types.TINYINT;
    }
    if(clazz == Short.class) {
        return Types.SMALLINT;
    }
    if(clazz == Integer.class) {
        return Types.INTEGER;
    }
    if(clazz == Long.class) {
        return Types.BIGINT;
    }
    if(clazz == Timestamp.class) {
        return Types.TIMESTAMP;
    }
    if(clazz == byte[].class) {
        return Types.BINARY;
    }
    if(clazz.isArray()) {
        return Types.ARRAY;
    }
    throw new IOException("Cannot resolve SqlType for + " + clazz.getName());
}
 
Example 8
Source File: ParameterMappingTest.java    From spliceengine with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Test for DERBY-149 fix Check that setString to an invalid value throws an
 * exception rather than causing a hang
 * 
 * @param type
 *            type for SQLTypes array
 * @param psi -
 *            insert prepared statement.
 * 
 */
private static void testSetStringInvalidValue(int type,
        PreparedStatement psi) {
    // Do not perform this test for string types.
    // Only test for types wich will fail with setString("InvalidValue");
    switch (jdbcTypes[type]) {
    case Types.CHAR:
    case Types.VARCHAR:
    case Types.LONGVARCHAR:
    case Types.CLOB:
        return;
    }

    String sqlType = SQLTypes[type];
    try {
        psi.setString(1, "Invalid Value");
        psi.executeUpdate();
        // Should have gotten exception. Test fails
        String error = "FAIL - setString(1,\"Invalld Value\") for type "
                + sqlType + " did not throw an exception as expected";
    } catch (SQLException sqle) {

        if ("22018".equals(sqle.getSQLState())
                || "XCL12".equals(sqle.getSQLState())
                || "22007".equals(sqle.getSQLState())
                || "22005".equals(sqle.getSQLState())
                || (sqle.getMessage().indexOf("Invalid data conversion") != -1)
                || (sqle.getMessage().indexOf("Illegal Conversion") != -1))
            ;
        // System.out.println(" IC (Expected)");
        else
            fail("FAIL:" + sqle.getMessage());
    } catch (Exception e) {
        fail("FAIL: Unexpected Exception " + e.getMessage());
    }
}
 
Example 9
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 10
Source File: DB2ColumnMetadataReaderTest.java    From virtual-schemas with MIT License 5 votes vote down vote up
@ValueSource(ints = { Types.VARCHAR, Types.NVARCHAR, Types.LONGNVARCHAR, Types.CHAR, Types.NCHAR,
        Types.LONGNVARCHAR })
@ParameterizedTest
void testMapJdbcVarcharSizeLesserThanExasolMaxVarcharSize(final int type) {
    final JdbcTypeDescription jdbcTypeDescription = new JdbcTypeDescription(type, 0, 10, 0, "");
    assertThat(this.db2ColumnMetadataReader.mapJdbcType(jdbcTypeDescription),
            equalTo(DataType.createVarChar(10, DataType.ExaCharset.UTF8)));
}
 
Example 11
Source File: AnnotationStoreRepositoryJDBCImplTest.java    From elucidate-server with MIT License 5 votes vote down vote up
@Test
@SuppressWarnings("serial")
public void testGetAnnotationsByCollectionIdMany() {

    W3CAnnotation w3cAnnotationOne = generateRandomW3CAnnotation();
    W3CAnnotation w3cAnnotationTwo = generateRandomW3CAnnotation();
    W3CAnnotation w3cAnnotationThree = generateRandomW3CAnnotation();

    String collectionId = generateRandomId();
    Object[] params = {collectionId, false};
    int[] sqlTypes = {Types.VARCHAR, Types.BOOLEAN};

    when(jdbcTemplate.query(anyString(), aryEq(params), aryEq(sqlTypes), (W3CAnnotationRowMapper) any())).thenReturn(new ArrayList<W3CAnnotation>() {
        {
            add(w3cAnnotationOne);
            add(w3cAnnotationTwo);
            add(w3cAnnotationThree);
        }
    });
    List<W3CAnnotation> w3cAnnotations = annotationStoreRepository.getAnnotationsByCollectionId(collectionId);
    verify(jdbcTemplate, times(1)).query(anyString(), aryEq(params), aryEq(sqlTypes), (W3CAnnotationRowMapper) any());

    assertThat(w3cAnnotations.size(), is(equalTo(3)));
    assertThat(w3cAnnotations.get(0), is(equalTo(w3cAnnotationOne)));
    assertThat(w3cAnnotations.get(1), is(equalTo(w3cAnnotationTwo)));
    assertThat(w3cAnnotations.get(2), is(equalTo(w3cAnnotationThree)));
}
 
Example 12
Source File: AnnotationSelectorStoreRepositoryJDBCImpl.java    From elucidate-server with MIT License 5 votes vote down vote up
@Override
@Transactional(readOnly = false)
public AnnotationCSSSelector createAnnotationCssSelector(Integer bodyPK, Integer targetPK, String selectorIri, String value, String selectorJson) {
    String sql = "SELECT * FROM annotation_css_selector_create(?, ?, ?, ?, ?)";
    Object[] params = {bodyPK, targetPK, selectorIri, value, selectorJson};
    int[] sqlTypes = {Types.INTEGER, Types.INTEGER, Types.VARCHAR, Types.VARCHAR, Types.OTHER};

    return queryForObject(sql, params, sqlTypes, new AnnotationCSSSelectorRowMapper());
}
 
Example 13
Source File: HiveJdbcBridgeUtils.java    From HiveJdbcStorageHandler with Apache License 2.0 5 votes vote down vote up
public static ObjectInspector getObjectInspector(int sqlType, String hiveType)
        throws SerDeException {
    switch(sqlType) {
        case Types.VARCHAR:
            return PrimitiveObjectInspectorFactory.javaStringObjectInspector;
        case Types.FLOAT:
            return PrimitiveObjectInspectorFactory.javaFloatObjectInspector;
        case Types.DOUBLE:
            return PrimitiveObjectInspectorFactory.javaDoubleObjectInspector;
        case Types.BOOLEAN:
            return PrimitiveObjectInspectorFactory.javaBooleanObjectInspector;
        case Types.TINYINT:
            return PrimitiveObjectInspectorFactory.javaByteObjectInspector;
        case Types.SMALLINT:
            return PrimitiveObjectInspectorFactory.javaShortObjectInspector;
        case Types.INTEGER:
            return PrimitiveObjectInspectorFactory.javaIntObjectInspector;
        case Types.BIGINT:
            return PrimitiveObjectInspectorFactory.javaLongObjectInspector;
        case Types.TIMESTAMP:
            return PrimitiveObjectInspectorFactory.javaTimestampObjectInspector;
        case Types.BINARY:
            return PrimitiveObjectInspectorFactory.javaByteArrayObjectInspector;
        case Types.ARRAY:
            String hiveElemType = hiveType.substring(hiveType.indexOf('<') + 1, hiveType.indexOf('>')).trim();
            int sqlElemType = hiveTypeToSqlType(hiveElemType);
            ObjectInspector listElementOI = getObjectInspector(sqlElemType, hiveElemType);
            return ObjectInspectorFactory.getStandardListObjectInspector(listElementOI);
        default:
            throw new SerDeException("Cannot find getObjectInspecto for: " + hiveType);
    }
}
 
Example 14
Source File: AbsDatabaseDriver.java    From linstor-server with GNU General Public License v3.0 5 votes vote down vote up
public List<String> getAsStringList(Column col) throws DatabaseException
{
    List<String> ret;
    try
    {
        Object value = get(col);
        if (value == null)
        {
            ret = null;
        }
        else
        if (col.getSqlType() == Types.VARCHAR)
        {
            ret = new ArrayList<>(OBJ_MAPPER.readValue((String) value, List.class));
        }
        else
        if (col.getSqlType() == Types.BLOB)
        {
            ret = new ArrayList<>(OBJ_MAPPER.readValue((byte[]) value, List.class));
        }
        else
        {
            throw new DatabaseException(
                "Failed to deserialize json array. No handler found for sql type: " +
                JDBCType.valueOf(col.getSqlType()) +
                " in table " + table.getName() + ", column " + col.getName()
            );
        }
    }
    catch (IOException exc)
    {
        throw new DatabaseException(
            "Failed to deserialize json array. Table: " + table.getName() + ", column: " + col.getName(),
            exc
        );
    }

    return ret;
}
 
Example 15
Source File: AbstractDBAccess.java    From snakerflow with Apache License 2.0 5 votes vote down vote up
public void deleteSurrogate(Surrogate surrogate) {
	if(!isORM()) {
		Object[] args = new Object[]{surrogate.getId()};
		int[] type = new int[]{Types.VARCHAR};
		saveOrUpdate(buildMap(SURROGATE_DELETE, args, type));
	}
}
 
Example 16
Source File: SqlArgs.java    From database with Apache License 2.0 4 votes vote down vote up
@Nonnull
public SqlArgs read(Row r) {
  SqlArgs args = new SqlArgs();

  for (int i = 0; i < names.length; i++) {
    switch (types[i]) {
    case Types.SMALLINT:
    case Types.INTEGER:
      args.argInteger(names[i], r.getIntegerOrNull());
      break;
    case Types.BIGINT:
      args.argLong(names[i], r.getLongOrNull());
      break;
    case Types.REAL:
    case 100: // Oracle proprietary it seems
      args.argFloat(names[i], r.getFloatOrNull());
      break;
    case Types.DOUBLE:
    case 101: // Oracle proprietary it seems
      args.argDouble(names[i], r.getDoubleOrNull());
      break;
    case Types.NUMERIC:
      if (precision[i] == 10 && scale[i] == 0) {
        // Oracle reports integer as numeric
        args.argInteger(names[i], r.getIntegerOrNull());
      } else if (precision[i] == 19 && scale[i] == 0) {
        // Oracle reports long as numeric
        args.argLong(names[i], r.getLongOrNull());
      } else {
        args.argBigDecimal(names[i], r.getBigDecimalOrNull());
      }
      break;
    case Types.BINARY:
    case Types.VARBINARY:
    case Types.BLOB:
      args.argBlobBytes(names[i], r.getBlobBytesOrNull());
      break;
    case Types.CLOB:
    case Types.NCLOB:
      args.argClobString(names[i], r.getClobStringOrNull());
      break;

    // Check Date before TimeStamp because SQL dates are also timestamps
    case Types.DATE:
        args.argLocalDate(names[i], r.getLocalDateOrNull());
        break;

    case Types.TIMESTAMP:
      if (this.scale[i] == 0) {
        // If the scale is 0, this is a LocalDate (no time/timezone).
        // Anything with a time will have a non-zero scale
        args.argLocalDate(names[i], r.getLocalDateOrNull());
      } else {
        args.argDate(names[i], r.getDateOrNull());
      }
      break;

    case Types.NVARCHAR:
    case Types.VARCHAR:
    case Types.CHAR:
    case Types.NCHAR:
      if (precision[i] >= 2147483647) {
        // Postgres seems to report clobs are varchar(2147483647)
        args.argClobString(names[i], r.getClobStringOrNull());
      } else {
        args.argString(names[i], r.getStringOrNull());
      }
      break;
    default:
      throw new DatabaseException("Don't know how to deal with column type: " + types[i]);
    }
  }
  return args;
}
 
Example 17
Source File: AbstractJsonSqlTypeDescriptor.java    From Groza with Apache License 2.0 4 votes vote down vote up
@Override
public int getSqlType() {
    return Types.VARCHAR;
}
 
Example 18
Source File: MySqlMetadataHandlerTest.java    From aws-athena-query-federation with Apache License 2.0 4 votes vote down vote up
@Test
public void doGetTableLayoutWithNoPartitions()
        throws Exception
{
    BlockAllocator blockAllocator = new BlockAllocatorImpl();
    Constraints constraints = Mockito.mock(Constraints.class);
    TableName tableName = new TableName("testSchema", "testTable");
    Schema partitionSchema = this.mySqlMetadataHandler.getPartitionSchema("testCatalogName");
    Set<String> partitionCols = partitionSchema.getFields().stream().map(Field::getName).collect(Collectors.toSet());
    GetTableLayoutRequest getTableLayoutRequest = new GetTableLayoutRequest(this.federatedIdentity, "testQueryId", "testCatalogName", tableName, constraints, partitionSchema, partitionCols);

    PreparedStatement preparedStatement = Mockito.mock(PreparedStatement.class);
    Mockito.when(this.connection.prepareStatement(MySqlMetadataHandler.GET_PARTITIONS_QUERY)).thenReturn(preparedStatement);

    String[] columns = {"partition_name"};
    int[] types = {Types.VARCHAR};
    Object[][] values = {{}};
    ResultSet resultSet = mockResultSet(columns, types, values, new AtomicInteger(-1));
    Mockito.when(preparedStatement.executeQuery()).thenReturn(resultSet);

    Mockito.when(this.connection.getMetaData().getSearchStringEscape()).thenReturn(null);

    GetTableLayoutResponse getTableLayoutResponse = this.mySqlMetadataHandler.doGetTableLayout(blockAllocator, getTableLayoutRequest);

    Assert.assertEquals(values.length, getTableLayoutResponse.getPartitions().getRowCount());

    List<String> expectedValues = new ArrayList<>();
    for (int i = 0; i < getTableLayoutResponse.getPartitions().getRowCount(); i++) {
        expectedValues.add(BlockUtils.rowToString(getTableLayoutResponse.getPartitions(), i));
    }
    Assert.assertEquals(expectedValues, Collections.singletonList("[partition_name : *]"));

    SchemaBuilder expectedSchemaBuilder = SchemaBuilder.newBuilder();
    expectedSchemaBuilder.addField(FieldBuilder.newBuilder(MySqlMetadataHandler.BLOCK_PARTITION_COLUMN_NAME, org.apache.arrow.vector.types.Types.MinorType.VARCHAR.getType()).build());
    Schema expectedSchema = expectedSchemaBuilder.build();
    Assert.assertEquals(expectedSchema, getTableLayoutResponse.getPartitions().getSchema());
    Assert.assertEquals(tableName, getTableLayoutResponse.getTableName());

    Mockito.verify(preparedStatement, Mockito.times(1)).setString(1, tableName.getTableName());
    Mockito.verify(preparedStatement, Mockito.times(1)).setString(2, tableName.getSchemaName());
}
 
Example 19
Source File: SQLTypeMap.java    From jeddict with Apache License 2.0 4 votes vote down vote up
/**
     * Translates a data type from an integer (java.sql.Types value) to a string
     * that represents the corresponding class.
     *
     * @param type The java.sql.Types value to convert to its corresponding
     * class.
     * @return The class that corresponds to the given java.sql.Types value, or
     * Object.class if the type has no known mapping.
     */
    public static Class<?> toClass(int type) {
        Class<?> result = Object.class;
// Pending type // NULL, OTHER, JAVA_OBJECT, DISTINCT, REF, DATALINK, STRUCT, ARRAY, BLOB, CLOB, LONGNVARCHAR, NCHAR, NCLOB, NVARCHAR, SQLXML, ROWID
        switch (type) {
            case Types.CHAR:
            case Types.VARCHAR:
            case Types.LONGVARCHAR:
                result = String.class;
                break;

            case Types.NUMERIC:
            case Types.DECIMAL:
                result = java.math.BigDecimal.class;
                break;

            case Types.BOOLEAN:
            case Types.BIT:
                result = Boolean.class;
                break;

            case Types.TINYINT:
                result = Byte.class;
                break;

            case Types.SMALLINT:
                result = Short.class;
                break;

            case Types.INTEGER:
                result = Integer.class;
                break;

            case Types.BIGINT:
                result = Long.class;
                break;

            case Types.REAL:
            case Types.FLOAT:
                result = Float.class;
                break;

            case Types.DOUBLE:
                result = Double.class;
                break;

            case Types.BINARY:
            case Types.VARBINARY:
            case Types.LONGVARBINARY:
                result = Byte[].class;
                break;

            case Types.DATE:
                result = java.sql.Date.class;
                break;

            case Types.TIME:
                result = java.sql.Time.class;
                break;

            case Types.TIMESTAMP:
                result = java.sql.Timestamp.class;
                break;
        }

        return result;
    }
 
Example 20
Source File: DataTypeEnum8.java    From ClickHouse-Native-JDBC with Apache License 2.0 4 votes vote down vote up
@Override
public int sqlTypeId() {
    return Types.VARCHAR;
}