java.sql.Types Java Examples

The following examples show how to use java.sql.Types. 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: SnowflakePreparedStatementV1.java    From snowflake-jdbc with Apache License 2.0 6 votes vote down vote up
@Override
public void setBigDecimal(int parameterIndex, BigDecimal x) throws SQLException
{
  logger.debug("setBigDecimal(parameterIndex: {}, BigDecimal x)", parameterIndex);

  if (x == null)
  {
    setNull(parameterIndex, Types.DECIMAL);
  }
  else
  {
    ParameterBindingDTO binding = new ParameterBindingDTO(
        SnowflakeUtil.javaTypeToSFTypeString(Types.DECIMAL), String.valueOf(x));
    parameterBindings.put(String.valueOf(parameterIndex), binding);
  }
}
 
Example #2
Source File: CrossConverters.java    From vertx-sql-client with Apache License 2.0 6 votes vote down vote up
static final Object setObject(int targetType, Date source) {
    switch (targetType) {

    case Types.DATE:
        return source;

    case Types.TIMESTAMP:
        return new Timestamp(source.getTime());

    case Types.CHAR:
    case Types.VARCHAR:
    case Types.LONGVARCHAR:
        return String.valueOf(source);

    default:
        throw new IllegalArgumentException("SQLState.LANG_DATA_TYPE_SET_MISMATCH java.sql.Date" + ClientTypes.getTypeString(targetType));
    }
}
 
Example #3
Source File: JdbcModelReader.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
/**
     * Returns descriptors for the columns that shall be read from the result set when
     * reading the meta data for foreign keys originating from a table. Note that the
     * columns are read in the order defined by this list.<br/>
     * Redefine this method if you want more columns or a different order.
     * 
     * @return The map column name -> descriptor for the result set columns
     */
    protected List initColumnsForFK()
    {
        List result = new ArrayList();

        result.add(new MetaDataColumnDescriptor("PKTABLE_NAME",  Types.VARCHAR));
// GemStone changes BEGIN
        result.add(new MetaDataColumnDescriptor("PKTABLE_SCHEM",  Types.VARCHAR));
        result.add(new MetaDataColumnDescriptor("FKTABLE_SCHEM",  Types.VARCHAR));
// GemStone changes END
        // we're also reading the table name so that a model reader impl can filter manually
        result.add(new MetaDataColumnDescriptor("FKTABLE_NAME",  Types.VARCHAR));
        result.add(new MetaDataColumnDescriptor("KEY_SEQ",       Types.TINYINT, Short.valueOf((short)0)));
        result.add(new MetaDataColumnDescriptor("FK_NAME",       Types.VARCHAR));
        result.add(new MetaDataColumnDescriptor("UPDATE_RULE",   Types.TINYINT));
        result.add(new MetaDataColumnDescriptor("DELETE_RULE",   Types.TINYINT));
        result.add(new MetaDataColumnDescriptor("PKCOLUMN_NAME", Types.VARCHAR));
        result.add(new MetaDataColumnDescriptor("FKCOLUMN_NAME", Types.VARCHAR));

        return result;
    }
 
Example #4
Source File: TestJdbcQueryExecutor.java    From datacollector with Apache License 2.0 6 votes vote down vote up
@Test
public void testEL() throws Exception {
  JdbcQueryExecutor queryExecutor = createExecutor("CREATE TABLE ${record:value('/table')} AS SELECT * FROM origin");

  ExecutorRunner runner = new ExecutorRunner.Builder(JdbcQueryDExecutor.class, queryExecutor)
    .setOnRecordError(OnRecordError.STOP_PIPELINE)
    .build();
  runner.runInit();

  Map<String, Field> map = new HashMap<>();
  map.put("table", Field.create("el"));

  Record record = RecordCreator.create();
  record.set(Field.create(map));

  runner.runWrite(ImmutableList.of(record));
  runner.runDestroy();

  assertTableStructure("el",
    new ImmutablePair("ID", Types.INTEGER),
    new ImmutablePair("NAME", Types.VARCHAR)
  );

  assertEquals(runner.getEventRecords().get(0).getEventType(), "successful-query");
}
 
Example #5
Source File: TableColumnInfo.java    From reladomo with Apache License 2.0 6 votes vote down vote up
private int normalizeType(int type, int size)
{
    switch (type)
    {
        case Types.CHAR:
            type = Types.VARCHAR;
            break;
        case Types.BIT:
        case Types.BOOLEAN:
        case Types.TINYINT:
            type = Types.SMALLINT;
            break;
        case Types.FLOAT:
            type = Types.DOUBLE;
            break;
    }
    return type;
}
 
Example #6
Source File: JdbcNestedNodeInsertingQueryDelegate.java    From nestedj with MIT License 6 votes vote down vote up
private void update(N node) {
    jdbcTemplate.update(
            getDiscriminatedQuery(
                    new Query("update :tableName set :left = ?, :right = ?, :level = ?, :parentId = ? where :id = ?").build()
            ),
            preparedStatement -> {
                preparedStatement.setObject(1, node.getTreeLeft());
                preparedStatement.setObject(2, node.getTreeRight());
                preparedStatement.setObject(3, node.getTreeLevel());
                if (node.getParentId() == null) {
                    preparedStatement.setNull(4, Types.OTHER);
                } else {
                    preparedStatement.setObject(4, node.getParentId());
                }
                preparedStatement.setObject(5, node.getId());
                setDiscriminatorParams(preparedStatement, 6);
            }
    );
}
 
Example #7
Source File: TestFBBinaryField.java    From jaybird with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Test
public void getObjectNonNull_typeBinary() throws SQLException {
    rowDescriptorBuilder.setType(ISCConstants.SQL_TEXT);
    rowDescriptorBuilder.setSubType(ISCConstants.CS_BINARY);
    fieldDescriptor = rowDescriptorBuilder.toFieldDescriptor();
    field = new FBBinaryField(fieldDescriptor, fieldData, Types.BINARY);

    final byte[] bytes = getRandomBytes();
    toReturnValueExpectations(bytes);

    Object value = field.getObject();

    assertThat(value, instanceOf(byte[].class));
    assertArrayEquals(bytes, (byte[]) value);
    assertNotSame("Expected a clone of the bytes", bytes, value);
}
 
Example #8
Source File: SimpleJdbcCallTests.java    From effectivejava with Apache License 2.0 6 votes vote down vote up
@Test
public void testAddInvoiceProcWithoutMetaDataUsingMapParamSource() throws Exception {
	initializeAddInvoiceWithoutMetaData(false);
	SimpleJdbcCall adder = new SimpleJdbcCall(dataSource).withProcedureName("add_invoice");
	adder.declareParameters(
			new SqlParameter("amount", Types.INTEGER),
			new SqlParameter("custid", Types.INTEGER),
			new SqlOutParameter("newid",
			Types.INTEGER));
	Number newId = adder.executeObject(Number.class, new MapSqlParameterSource().
			addValue("amount", 1103).
			addValue("custid", 3));
	assertEquals(4, newId.intValue());
	verifyAddInvoiceWithoutMetaData(false);
	verify(connection, atLeastOnce()).close();
}
 
Example #9
Source File: GfxdDataDictionary.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
private void createAddGatewayEventErrorHandlerProcedure(TransactionController tc,
    HashSet<?> newlyCreatedRoutines) throws StandardException {
  // procedure argument names
  String[] arg_names = { "FUNCTION_STR", "INIT_INFO_STR" };
  // procedure argument types
  TypeDescriptor[] arg_types = {
      DataTypeDescriptor.getCatalogType(Types.VARCHAR,
          Limits.DB2_VARCHAR_MAXWIDTH),
      DataTypeDescriptor.getCatalogType(Types.VARCHAR,
          Limits.DB2_VARCHAR_MAXWIDTH) };
  String methodName = "addGfxdGatewayEventErrorHandler(java.lang.String, java.lang.String)";
  String aliasName = "ATTACH_GATEWAY_EVENT_ERROR_HANDLER";
  this.createGfxdProcedure(methodName, getSystemSchemaDescriptor().getUUID(),
      arg_names, arg_types, 0, 0, RoutineAliasInfo.NO_SQL, null, tc,
      aliasName, CALLBACK_CLASSNAME, newlyCreatedRoutines, true);
}
 
Example #10
Source File: BaseDalTableDaoShardByDbTest.java    From dal with Apache License 2.0 6 votes vote down vote up
/**
 * Test delete entities with where clause and parameters
 * 
 * @throws SQLException
 */
@Test
public void testDeleteWithWhereClauseAllShards() throws SQLException {
    String whereClause = "type=?";
    StatementParameters parameters = new StatementParameters();
    parameters.set(1, Types.SMALLINT, 1);

    DalHints hints = new DalHints();
    int res;

    // By allShards
    assertEquals(3, getCountByDb(dao, 0));
    assertEquals(3, getCountByDb(dao, 1));
    res = dao.delete(whereClause, parameters, new DalHints().inAllShards());
    assertResEquals(6, res);
    assertEquals(0, dao.query(whereClause, parameters, new DalHints().inAllShards()).size());
}
 
Example #11
Source File: Tds9Test.java    From jTDS with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * SQL 2005 allows nvarchar(max) as the output parameter of a stored
 * procedure. Test this functionality now.
 */
public void testNvarcharMaxOutput() throws Exception
{
   if( supportsTDS9() )
   {
      Statement stmt = con.createStatement();
      stmt.execute( "CREATE PROC #sp_test @in nvarchar(max), @out nvarchar(max) output as set @out = @in" );
      StringBuffer buf = new StringBuffer( 5000 );
      buf.append( '<' );
      for( int i = 0; i < 4000; i++ )
      {
         buf.append( 'X' );
      }
      buf.append( '>' );
      CallableStatement cstmt = con.prepareCall( "{call #sp_test(?,?)}" );
      cstmt.setString( 1, buf.toString() );
      cstmt.registerOutParameter( 2, Types.LONGVARCHAR );
      cstmt.execute();
      assertTrue( buf.toString().equals( cstmt.getString( 2 ) ) );
      cstmt.close();
      stmt.close();
   }
}
 
Example #12
Source File: HCatalogImportTest.java    From aliyun-maxcompute-data-collectors with Apache License 2.0 6 votes vote down vote up
public void testTableCreationWithMultipleStaticPartKeys() throws Exception {
  final int TOTAL_RECORDS = 1 * 10;
  String table = getTableName().toUpperCase();
  ColumnGenerator[] cols = new ColumnGenerator[] {
    HCatalogTestUtils.colGenerator(HCatalogTestUtils.forIdx(0),
      "varchar(20)", Types.VARCHAR, HCatFieldSchema.Type.VARCHAR, 20, 0,
      new HiveVarchar("1", 20), "1", KeyType.STATIC_KEY),
    HCatalogTestUtils.colGenerator(HCatalogTestUtils.forIdx(1),
      "varchar(20)", Types.VARCHAR, HCatFieldSchema.Type.VARCHAR, 20, 0,
      new HiveVarchar("2", 20), "2", KeyType.STATIC_KEY),
  };
  List<String> addlArgsArray = new ArrayList<String>();
  addlArgsArray.add("--hcatalog-partition-keys");
  addlArgsArray.add("col0,col1");
  addlArgsArray.add("--hcatalog-partition-values");
  addlArgsArray.add("1,2");
  addlArgsArray.add("--create-hcatalog-table");
  setExtraArgs(addlArgsArray);
  runHCatImport(addlArgsArray, TOTAL_RECORDS, table, cols, null, true, false);
}
 
Example #13
Source File: ValueMetaBaseTest.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
@Test
public void testMetdataPreviewSqlVarBinaryToPentahoBinary() throws SQLException, KettleDatabaseException {
  doReturn( Types.VARBINARY ).when( resultSet ).getInt( "DATA_TYPE" );
  doReturn( mock( PostgreSQLDatabaseMeta.class ) ).when( dbMeta ).getDatabaseInterface();
  ValueMetaInterface valueMeta = valueMetaBase.getMetadataPreview( dbMeta, resultSet );
  assertTrue( valueMeta.isBinary() );
}
 
Example #14
Source File: ValueMetaBaseTest.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
@Test
public void testMetdataPreviewSqlLongVarBinaryToPentahoStringUsingOracle() throws SQLException, KettleDatabaseException {
  doReturn( Types.LONGVARBINARY ).when( resultSet ).getInt( "DATA_TYPE" );
  doReturn( mock( OracleDatabaseMeta.class ) ).when( dbMeta ).getDatabaseInterface();
  ValueMetaInterface valueMeta = valueMetaBase.getMetadataPreview( dbMeta, resultSet );
  assertTrue( valueMeta.isString() );
}
 
Example #15
Source File: JdbcColumnKeyTest.java    From SimpleFlatMapper with MIT License 5 votes vote down vote up
@Test
public void testHashCode() throws Exception {
    assertEquals(new JdbcColumnKey("col", 1, Types.ARRAY).hashCode(), new JdbcColumnKey("col", 1, Types.ARRAY).hashCode());
    assertNotEquals(new JdbcColumnKey("col", 1, Types.ARRAY).hashCode(), new JdbcColumnKey("col", 1, Types.VARCHAR).hashCode());
    assertNotEquals(new JdbcColumnKey("col", 1, Types.ARRAY).hashCode(), new JdbcColumnKey("col", 2, Types.ARRAY).hashCode());
    assertNotEquals(new JdbcColumnKey("col", 1, Types.ARRAY).hashCode(), new JdbcColumnKey("col1", 1, Types.ARRAY).hashCode());
}
 
Example #16
Source File: NamedParameterJdbcTemplateTests.java    From effectivejava with Apache License 2.0 5 votes vote down vote up
@Test
public void testUpdateWithTypedParameters() throws SQLException {
	given(preparedStatement.executeUpdate()).willReturn(1);

	params.put("perfId", new SqlParameterValue(Types.DECIMAL, 1));
	params.put("priceId", new SqlParameterValue(Types.INTEGER, 1));
	int rowsAffected = namedParameterTemplate.update(UPDATE_NAMED_PARAMETERS, params);

	assertEquals(1, rowsAffected);
	verify(connection).prepareStatement(UPDATE_NAMED_PARAMETERS_PARSED);
	verify(preparedStatement).setObject(1, 1, Types.DECIMAL);
	verify(preparedStatement).setObject(2, 1, Types.INTEGER);
	verify(preparedStatement).close();
	verify(connection).close();
}
 
Example #17
Source File: SqlQueryTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void testUpdateCustomers() throws SQLException {
	given(resultSet.next()).willReturn(true, true, false);
	given(resultSet.getInt("id")).willReturn(1, 2);
	given(connection.prepareStatement(SELECT_ID_FORENAME_WHERE_ID,
			ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE)
		).willReturn(preparedStatement);

	class CustomerUpdateQuery extends UpdatableSqlQuery<Customer> {

		public CustomerUpdateQuery(DataSource ds) {
			super(ds, SELECT_ID_FORENAME_WHERE_ID);
			declareParameter(new SqlParameter(Types.NUMERIC));
			compile();
		}

		@Override
		protected Customer updateRow(ResultSet rs, int rownum, Map<? ,?> context)
				throws SQLException {
			rs.updateString(2, "" + context.get(rs.getInt(COLUMN_NAMES[0])));
			return null;
		}
	}

	CustomerUpdateQuery query = new CustomerUpdateQuery(dataSource);
	Map<Integer, String> values = new HashMap<Integer, String>(2);
	values.put(1, "Rod");
	values.put(2, "Thomas");
	query.execute(2, values);
	verify(resultSet).updateString(2, "Rod");
	verify(resultSet).updateString(2, "Thomas");
	verify(resultSet, times(2)).updateRow();
	verify(preparedStatement).setObject(1, 2, Types.NUMERIC);
	verify(resultSet).close();
	verify(preparedStatement).close();
	verify(connection).close();
}
 
Example #18
Source File: GfxdResolverAPITest.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
public void testListResolver_4() throws SQLException, StandardException {
  // Create a schema
  Connection conn = getConnection();
  Statement s = conn.createStatement();
  s.execute("create schema trade");

  s
      .execute("create table trade.portfolio (cid int not null,"
          + "qty int not null, availQty int not null, tid int, sid int not null, "
          + "constraint qty_ck check (qty>=0), constraint avail_ch check (availQty>=0 and availQty<=qty))"
          + "partition by list (sid) ( VALUES (0, 5) , VALUES (10, 15), "
          + "VALUES (20, 23), VALUES(25, 30), VALUES(31, 100))");

  GfxdListPartitionResolver lpr = (GfxdListPartitionResolver)Misc
      .getGemFireCache().getRegion("/TRADE/PORTFOLIO").getAttributes()
      .getPartitionAttributes().getPartitionResolver();

  assertNotNull(lpr);

  String[] sarr = lpr.getColumnNames();
  assertEquals(1, sarr.length);
  assertEquals(0, lpr.getPartitioningColumnIndex("SID"));
  assertEquals(1, lpr.getPartitioningColumnsCount());
  Integer robj = (Integer)lpr.getRoutingKeyForColumn(new SQLInteger(5));
  assertEquals(0, robj.intValue());
  DataValueDescriptor[] values = new DataValueDescriptor[] {
      new SQLInteger(6), new SQLInteger(71), new SQLInteger(10),
      new SQLInteger(100), new SQLInteger(1) };
  robj = (Integer)lpr.getRoutingObjectFromDvdArray(values);
  int maxWidth = DataTypeDescriptor.getBuiltInDataTypeDescriptor(
      Types.INTEGER).getMaximumWidth();
  assertEquals(new SQLInteger(1).computeHashCode(maxWidth, 0),
      robj.intValue());
}
 
Example #19
Source File: TestFBBigDecimalField.java    From jaybird with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Test
public void getObject_IntegerNull() throws SQLException {
    fieldDescriptor = createIntegerFieldDescriptor(-1);
    field = new FBBigDecimalField(fieldDescriptor, fieldData, Types.NUMERIC);
    toReturnNullExpectations();

    assertNull("Expected getObject(Integer.class) to return null for NUL value", field.getObject(Integer.class));
}
 
Example #20
Source File: AdapterPartition.java    From spliceengine with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public PartitionDescriptor getDescriptor() throws IOException {
    if (!useProxy) {
        try {
            return delegate.getDescriptor();
        } catch (AccessDeniedException ade) {
            activateProxy(ade);
        }
    }

    try {
        try (java.sql.Connection jdbcConnection = connectionPool.getConnection();
             PreparedStatement statement = jdbcConnection.prepareStatement("call SYSCS_UTIL.SYSCS_HBASE_OPERATION(?, ?, ?)")) {
            statement.setString(1, tableName.toString());
            statement.setString(2, "descriptor");
            statement.setNull(3, Types.BLOB);
            try (ResultSet rs = statement.executeQuery()) {
                if (!rs.next()) {
                    throw new IOException("No results for descriptor");
                }

                Blob blob = rs.getBlob(1);
                byte[] bytes =  blob.getBytes(1, (int) blob.length());
                HBaseProtos.TableSchema result = HBaseProtos.TableSchema.parseFrom(bytes);
                TableDescriptor d = ProtobufUtil.toTableDescriptor(result);
                HTableDescriptor htd = new HTableDescriptor(d);
                return new HPartitionDescriptor(htd);
            }
        }
    } catch (SQLException e) {
        throw new IOException(e);
    }
}
 
Example #21
Source File: TestFBBigDecimalField.java    From jaybird with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Test
@Override
public void getObject_Long() throws SQLException {
    fieldDescriptor = createLongFieldDescriptor(-2);
    field = new FBBigDecimalField(fieldDescriptor, fieldData, Types.NUMERIC);
    toReturnLongExpectations(Long.MAX_VALUE);

    assertEquals("Unexpected value from getLong()", Long.MAX_VALUE / 100, (long) field.getObject(Long.class));
}
 
Example #22
Source File: StoreServerTableResultTransaction.java    From Plan with GNU Lesser General Public License v3.0 5 votes vote down vote up
private Executable insertNewValues(int tableID) {
    String sql = "INSERT INTO " + TABLE_NAME + '(' +
            TABLE_ID + ',' +
            SERVER_UUID + ',' +
            VALUE_1 + ',' +
            VALUE_2 + ',' +
            VALUE_3 + ',' +
            VALUE_4 + ',' +
            VALUE_5 +
            ") VALUES (?,?,?,?,?,?, ?)";

    return new ExecBatchStatement(sql) {
        @Override
        public void prepare(PreparedStatement statement) throws SQLException {
            int maxColumnSize = Math.min(table.getMaxColumnSize(), 5); // Limit to maximum 5 columns, or how many column names there are.

            for (Object[] row : table.getRows()) {
                statement.setInt(1, tableID);
                statement.setString(2, serverUUID.toString());
                for (int i = 0; i < maxColumnSize; i++) {
                    Object value = row[i];
                    setStringOrNull(statement, 3 + i, value != null ? StringUtils.truncate(value.toString(), 250) : null);
                }
                // Rest are set null if not 5 columns wide.
                for (int i = maxColumnSize; i < 5; i++) {
                    statement.setNull(3 + i, Types.VARCHAR);
                }

                statement.addBatch();
            }
        }
    };
}
 
Example #23
Source File: CommonRowSetTests.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
private void initCoffeeHousesMetaData(CachedRowSet crs) throws SQLException {
    RowSetMetaDataImpl rsmd = new RowSetMetaDataImpl();
    crs.setType(RowSet.TYPE_SCROLL_INSENSITIVE);

    /*
     *  CREATE TABLE COFFEE_HOUSES(
     *   STORE_ID Integer NOT NULL,
     *   CITY VARCHAR(32),
     *   COFFEE INTEGER NOT NULL,
     *   MERCH INTEGER NOT NULL,
     *   TOTAL INTEGER NOT NULL,
     *   PRIMARY KEY (STORE_ID))
     */
    rsmd.setColumnCount(COFFEE_HOUSES_COLUMN_NAMES.length);
    for(int i = 1; i <= COFFEE_HOUSES_COLUMN_NAMES.length; i++){
        rsmd.setColumnName(i, COFFEE_HOUSES_COLUMN_NAMES[i-1]);
        rsmd.setColumnLabel(i, rsmd.getColumnName(i));
    }

    rsmd.setColumnType(1, Types.INTEGER);
    rsmd.setColumnType(2, Types.VARCHAR);
    rsmd.setColumnType(3, Types.INTEGER);
    rsmd.setColumnType(4, Types.INTEGER);
    rsmd.setColumnType(5, Types.INTEGER);
    crs.setMetaData(rsmd);
    crs.setTableName(COFFEE_HOUSES_TABLE);

}
 
Example #24
Source File: ValueMetaBaseTest.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
@Test
public void testMetdataPreviewSqlBinaryToPentahoBinary() throws SQLException, KettleDatabaseException {
  doReturn( Types.BINARY ).when( resultSet ).getInt( "DATA_TYPE" );
  doReturn( mock( PostgreSQLDatabaseMeta.class ) ).when( dbMeta ).getDatabaseInterface();
  ValueMetaInterface valueMeta = valueMetaBase.getMetadataPreview( dbMeta, resultSet );
  assertTrue( valueMeta.isBinary() );
}
 
Example #25
Source File: ExasolSpecific.java    From CloverETL-Engine with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public CopySQLData createCopyObject(int sqlType, DataFieldMetadata fieldMetadata, DataRecord record, int fromIndex,
		int toIndex) {
	DataFieldType jetelType = fieldMetadata.getDataType();
	switch (sqlType) {
	case Types.FLOAT:
	case Types.DOUBLE:
	case Types.REAL:
		if (jetelType == DataFieldType.NUMBER) {
			return new CopyDouble(record, fromIndex, toIndex);
		}
	}
	return super.createCopyObject(sqlType, fieldMetadata, record, fromIndex, toIndex);
}
 
Example #26
Source File: TestTableComparison.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * Tests making a column not required.
 */
public void testMakeColumnNotRequired()
{
    final String MODEL1 = 
        "<?xml version='1.0' encoding='ISO-8859-1'?>\n" +
        "<database xmlns='" + DatabaseIO.DDLUTILS_NAMESPACE + "' name='test'>\n" +
        "  <table name='TableA'>\n" +
        "    <column name='ColPK' type='INTEGER' primaryKey='true' required='true'/>\n" +
        "    <column name='Col' type='INTEGER' required='true'/>\n" +
        "  </table>\n" +
        "</database>";
    final String MODEL2 = 
        "<?xml version='1.0' encoding='ISO-8859-1'?>\n" +
        "<database xmlns='" + DatabaseIO.DDLUTILS_NAMESPACE + "' name='test'>\n" +
        "  <table name='TABLEA'>\n" +
        "    <column name='COLPK' type='INTEGER' primaryKey='true' required='true'/>\n" +
        "    <column name='COL' type='INTEGER' required='false'/>\n" +
        "  </table>\n" +
        "</database>";

    Database model1  = parseDatabaseFromString(MODEL1);
    Database model2  = parseDatabaseFromString(MODEL2);
    List     changes = getPlatform(false).getChanges(model1, model2);

    assertEquals(1,
                 changes.size());

    ColumnDefinitionChange change = (ColumnDefinitionChange)changes.get(0);

    assertEquals("TableA",
                 change.getChangedTable());
    assertColumn("Col", Types.INTEGER, null, null, false, false, false,
                 change.getNewColumn());
}
 
Example #27
Source File: OraOopConnManager.java    From aliyun-maxcompute-data-collectors with Apache License 2.0 5 votes vote down vote up
public OraOopConnManager(final SqoopOptions sqoopOptions) {
  super(OraOopConstants.ORACLE_JDBC_DRIVER_CLASS, sqoopOptions);
  if (this.options.getConf().getBoolean(
      OraOopConstants.ORAOOP_MAP_TIMESTAMP_AS_STRING,
      OraOopConstants.ORAOOP_MAP_TIMESTAMP_AS_STRING_DEFAULT)) {
    timestampJavaType = "String";
  } else {
    timestampJavaType = super.toJavaType(Types.TIMESTAMP);
  }
}
 
Example #28
Source File: Upgrade410to420.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
private void migrateTemplateSwiftRef(Connection conn, Map<Long, Long> swiftStoreMap) {
    s_logger.debug("Updating template_store_ref table from template_swift_ref table");
    try (
            PreparedStatement tmplStoreInsert =
                conn.prepareStatement("INSERT INTO `cloud`.`template_store_ref` (store_id,  template_id, created, download_pct, size, physical_size, download_state, local_path, install_path, update_count, ref_cnt, store_role, state) values(?, ?, ?, 100, ?, ?, 'DOWNLOADED', '?', '?', 0, 0, 'Image', 'Ready')");
            PreparedStatement s3Query = conn.prepareStatement("select swift_id, template_id, created, path, size, physical_size from `cloud`.`template_swift_ref`");
            ResultSet rs = s3Query.executeQuery();
        ) {
        while (rs.next()) {
            Long swift_id = rs.getLong("swift_id");
            Long tmpl_id = rs.getLong("template_id");
            Date created = rs.getDate("created");
            String path = rs.getString("path");
            Long size = rs.getObject("size") != null ? rs.getLong("size") : null;
            Long psize = rs.getObject("physical_size") != null ? rs.getLong("physical_size") : null;

            tmplStoreInsert.setLong(1, swiftStoreMap.get(swift_id));
            tmplStoreInsert.setLong(2, tmpl_id);
            tmplStoreInsert.setDate(3, created);
            if (size != null) {
                tmplStoreInsert.setLong(4, size);
            } else {
                tmplStoreInsert.setNull(4, Types.BIGINT);
            }
            if (psize != null) {
                tmplStoreInsert.setLong(5, psize);
            } else {
                tmplStoreInsert.setNull(5, Types.BIGINT);
            }
            tmplStoreInsert.setString(6, path);
            tmplStoreInsert.setString(7, path);
            tmplStoreInsert.executeUpdate();
        }
    } catch (SQLException e) {
        String msg = "Unable to migrate template_swift_ref." + e.getMessage();
        s_logger.error(msg);
        throw new CloudRuntimeException(msg, e);
    }
    s_logger.debug("Completed migrating template_swift_ref table.");
}
 
Example #29
Source File: BaseDalTabelDaoShardByTableTest.java    From dal with Apache License 2.0 5 votes vote down vote up
/**
 * Test Query range of result with where clause when return empty collection
 * 
 * @throws SQLException
 */
@Test
public void testQueryFromWithWhereClauseEmpty() throws SQLException {
    String whereClause = "type=? order by id";
    List<ClientTestModel> models = null;
    for (int i = 0; i < mod; i++) {
        StatementParameters parameters = new StatementParameters();
        parameters.set(1, Types.SMALLINT, 10);

        // By tabelShard
        models = dao.queryFrom(whereClause, parameters, new DalHints().inTableShard(i), 0, 10);
        assertTrue(null != models);
        assertEquals(0, models.size());

        // By tableShardValue
        models = dao.queryFrom(whereClause, parameters, new DalHints().setTableShardValue(i), 0, 10);
        assertTrue(null != models);
        assertEquals(0, models.size());

        // By shardColValue
        models = dao.queryFrom(whereClause, parameters, new DalHints().setShardColValue("index", i), 0, 10);
        assertTrue(null != models);
        assertEquals(0, models.size());

        // By shardColValue
        models = dao.queryFrom(whereClause, parameters, new DalHints().setShardColValue("tableIndex", i), 0, 10);
        assertTrue(null != models);
        assertEquals(0, models.size());
    }
}
 
Example #30
Source File: SQLUtil.java    From CloverETL-Engine with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Converts sql type into string.
 * @param sqlType
 * @return
 */
public static String sqlType2str(int sqlType) {
    switch(sqlType) {
    case Types.BIT: return "BIT";
    case Types.TINYINT: return "TINYINT";
    case Types.SMALLINT: return "SMALLINT";
    case Types.INTEGER: return "INTEGER";
    case Types.BIGINT: return "BIGINT";
    case Types.FLOAT: return "FLOAT";
    case Types.REAL: return "REAL";
    case Types.DOUBLE: return "DOUBLE";
    case Types.NUMERIC: return "NUMERIC";
    case Types.DECIMAL: return "DECIMAL";
    case Types.CHAR: return "CHAR";
    case Types.VARCHAR: return "VARCHAR";
    case Types.LONGVARCHAR: return "LONGVARCHAR";
    case Types.DATE: return "DATE";
    case Types.TIME: return "TIME";
    case Types.TIMESTAMP: return "TIMESTAMP";
    case Types.BINARY: return "BINARY";
    case Types.VARBINARY: return "VARBINARY";
    case Types.LONGVARBINARY: return "LONGVARBINARY";
    case Types.NULL: return "NULL";
    case Types.OTHER: return "OTHER";
    case Types.JAVA_OBJECT: return "JAVA_OBJECT";
    case Types.DISTINCT: return "DISTINCT";
    case Types.STRUCT: return "STRUCT";
    case Types.ARRAY: return "ARRAY";
    case Types.BLOB: return "BLOB";
    case Types.CLOB: return "CLOB";
    case Types.REF: return "REF";
    case Types.DATALINK: return "DATALINK";
    case Types.BOOLEAN: return "BOOLEAN";
    default: return "<unknown sql type>";
    }
    
}