java.sql.ResultSetMetaData Java Examples

The following examples show how to use java.sql.ResultSetMetaData. 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: JDBC.java    From kareldb with Apache License 2.0 6 votes vote down vote up
/**
 * Check the nullability of the column definitions for
 * the ResultSet matches the expected values.
 *
 * @param rs
 * @param nullability
 * @throws SQLException
 */
public static void assertNullability(ResultSet rs,
                                     boolean[] nullability) throws SQLException {
    ResultSetMetaData rsmd = rs.getMetaData();
    int actualCols = rsmd.getColumnCount();

    assertEquals("Unexpected column count:",
        nullability.length, rsmd.getColumnCount());

    for (int i = 0; i < actualCols; i++) {
        int expected = nullability[i] ?
            ResultSetMetaData.columnNullable : ResultSetMetaData.columnNoNulls;
        assertEquals("Column nullability do not match for column " + (i + 1),
            expected, rsmd.isNullable(i + 1));
    }
}
 
Example #2
Source File: ResultTableResultSetProcessor.java    From dalesbred with MIT License 6 votes vote down vote up
@Override
public @NotNull ResultTable process(@NotNull ResultSet resultSet) throws SQLException {
    ResultSetMetaData metaData = resultSet.getMetaData();
    int columnCount = metaData.getColumnCount();

    ResultTable.Builder builder = createBuilder(metaData);
    while (resultSet.next()) {
        Object[] row = new Object[columnCount];

        for (int i = 0; i < columnCount; i++)
            row[i] = resultSet.getObject(i+1);

        builder.addRow(asList(row));
    }

    return builder.build();
}
 
Example #3
Source File: IoTDBAuthorizationIT.java    From incubator-iotdb with Apache License 2.0 6 votes vote down vote up
private void validateResultSet(ResultSet set, String ans) throws SQLException {
  try {
    StringBuilder builder = new StringBuilder();
    ResultSetMetaData metaData = set.getMetaData();
    int colNum = metaData.getColumnCount();
    while (set.next()) {
      for (int i = 1; i <= colNum; i++) {
        builder.append(set.getString(i)).append(",");
      }
      builder.append("\n");
    }
    assertEquals(ans, builder.toString());
  } finally {
    set.close();
  }
}
 
Example #4
Source File: EventCallbackWriterImpl.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
/**
 * Build querying string to delete a row in the backend database
 * 
 * @param tableName
 *          fully qualified name of the table
 * @param pkMeta
 *          meta-data of the primary key columns of the table
 * 
 * @return SQL query string to delete a row in the backend database
 * 
 * @throws SQLException
 *           on error
 */
private String buildDeleteQuery(String tableName, ResultSetMetaData pkMeta)
    throws SQLException {

  StringBuilder query = new StringBuilder().append("DELETE FROM ");

  query.append(tableName);
  query.append(" WHERE ");
  // use the primary key columns to fire the delete on backend DB
  final int numCols = pkMeta.getColumnCount();
  for (int col = 1; col < numCols; col++) {
    query.append(pkMeta.getColumnName(col));
    query.append("=? AND ");
  }
  query.append(pkMeta.getColumnName(numCols));
  query.append("=?");

  return query.toString();
}
 
Example #5
Source File: MetaDataRegressionTest.java    From r-course with MIT License 6 votes vote down vote up
private void checkRsmdForBug13277(ResultSetMetaData rsmd) throws SQLException {

        int i = ((com.mysql.jdbc.ConnectionImpl) this.conn)
                .getMaxBytesPerChar(CharsetMapping.getJavaEncodingForMysqlCharset(((com.mysql.jdbc.Connection) this.conn).getServerCharset()));
        if (i == 1) {
            // This is INT field but still processed in
            // ResultsetMetaData.getColumnDisplaySize
            assertEquals(20, rsmd.getColumnDisplaySize(1));
        }

        if (versionMeetsMinimum(4, 1)) {
            assertEquals(false, rsmd.isDefinitelyWritable(1));
            assertEquals(true, rsmd.isReadOnly(1));
            assertEquals(false, rsmd.isWritable(1));
        }
    }
 
Example #6
Source File: MetaDataRegressionTest.java    From r-course with MIT License 6 votes vote down vote up
/**
 * Tests fix for BUG#2855, where RSMD is not returning correct (or matching)
 * types for FLOAT.
 * 
 * @throws Exception
 *             if the test fails.
 */
public void testBug2855() throws Exception {
    try {
        this.stmt.executeUpdate("DROP TABLE IF EXISTS testBug2855");
        this.stmt.executeUpdate("CREATE TABLE testBug2855 (field1 FLOAT)");
        this.stmt.executeUpdate("INSERT INTO testBug2855 VALUES (1)");

        this.rs = this.stmt.executeQuery("SELECT * from testBug2855");

        assertTrue(this.rs.next());

        ResultSetMetaData rsmd = this.rs.getMetaData();

        assertTrue(rsmd.getColumnClassName(1).equals(this.rs.getObject(1).getClass().getName()));
        assertTrue("java.lang.Float".equals(rsmd.getColumnClassName(1)));
    } finally {
        this.stmt.executeUpdate("DROP TABLE IF EXISTS testBug2855");
    }
}
 
Example #7
Source File: SqlFactory.java    From stategen with GNU Affero General Public License v3.0 6 votes vote down vote up
private ResultSetMetaData executeSqlForResultSetMetaData(String sql,PreparedStatement ps,List<SqlParameter> params,Map<String, Object> randomValues)throws SQLException {
//      SqlParseHelper.setRandomParamsValueForPreparedStatement(SqlParseHelper.removeOrders(executeSql), ps);
        StatementCreatorUtils.setRandomParamsValueForPreparedStatement(sql, ps, params,randomValues);
        try {
            ps.setMaxRows(3);
            ps.setFetchSize(3);
            ps.setQueryTimeout(20);
            ResultSet rs = null;
            if(ps.execute()) {
                rs = ps.getResultSet();
                return rs.getMetaData();
            }
            return null;
        }catch(SQLException e) {
            if(isDataIntegrityViolationException(e)) {
                GLogger.warn("ignore executeSqlForResultSetMetaData() SQLException,errorCode:"+e.getErrorCode()+" sqlState:"+e.getSQLState()+" message:"+e.getMessage()+ "\n executedSql:"+sql);
                return null;
            }
            String message = "errorCode:"+e.getErrorCode()+" SQLState:"+e.getSQLState()+" errorCodeTranslatorDataBaaseName:"+getErrorCodeTranslatorDataBaaseName()+" "+ e.getMessage();
            throw new SQLException(message,e.getSQLState(),e.getErrorCode());
        }
    }
 
Example #8
Source File: BaseDQLIT.java    From shardingsphere with Apache License 2.0 6 votes vote down vote up
private void assertRows(final ResultSet actualResultSet, final List<DataSetRow> expectedDatSetRows) throws SQLException {
    int count = 0;
    ResultSetMetaData actualMetaData = actualResultSet.getMetaData();
    while (actualResultSet.next()) {
        int index = 1;
        assertTrue("Size of actual result set is different with size of expected dat set rows.", count < expectedDatSetRows.size());
        for (String each : expectedDatSetRows.get(count).getValues()) {
            if (Types.DATE == actualResultSet.getMetaData().getColumnType(index)) {
                if (!NOT_VERIFY_FLAG.equals(each)) {
                    assertThat(new SimpleDateFormat("yyyy-MM-dd").format(actualResultSet.getDate(index)), is(each));
                    assertThat(new SimpleDateFormat("yyyy-MM-dd").format(actualResultSet.getDate(actualMetaData.getColumnLabel(index))), is(each));
                }
            } else {
                assertThat(String.valueOf(actualResultSet.getObject(index)), is(each));
                assertThat(String.valueOf(actualResultSet.getObject(actualMetaData.getColumnLabel(index))), is(each));
            }
            index++;
        }
        count++;
    }
    assertThat("Size of actual result set is different with size of expected dat set rows.", count, is(expectedDatSetRows.size()));
}
 
Example #9
Source File: AbstractWriter.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
protected String getSql(Event event) throws SQLException {
	ResultSetMetaData meta = event.getResultSetMetaData();
	List<Object> newRow = event.getNewRow();
	StringBuffer str = new StringBuffer();
	/*
	Log.getLogWriter().info("from metadata, schema name is " + meta.getSchemaName(1) 
			+ " table name is " + meta.getTableName(1));
	*/
	if (event.getModifiedColumns() == null) throw new TestException("event.getModifiedColumns " +
			"return null on BEFORE_UPDATE");
	
	str.append("update " + meta.getSchemaName(1) + "." 
			+ meta.getTableName(1) + " set ");		
	for (int i=0; i<event.getModifiedColumns().length; i++) {
                       str.append(" " + meta.getColumnName(event.getModifiedColumns()[i]) + "=");
                       appendValue(str, newRow.get(event.getModifiedColumns()[i]-1),
                                               meta.getColumnType(event.getModifiedColumns()[i]));
	}
	str.delete(str.length() -1 , str.length());
	return str.toString();
}
 
Example #10
Source File: DriverTest.java    From kylin-on-parquet-v2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testPreparedStatementWithMockData() throws SQLException {
    Driver driver = new DummyDriver();

    Connection conn = driver.connect("jdbc:kylin://test_url/test_db", null);
    PreparedStatement state = conn.prepareStatement("select * from test_table where id=?");
    state.setInt(1, 10);
    ResultSet resultSet = state.executeQuery();

    ResultSetMetaData metadata = resultSet.getMetaData();
    assertEquals(12, metadata.getColumnType(1));
    assertEquals("varchar", metadata.getColumnTypeName(1));
    assertEquals(1, metadata.isNullable(1));

    while (resultSet.next()) {
        assertEquals("foo", resultSet.getString(1));
        assertEquals("bar", resultSet.getString(2));
        assertEquals("tool", resultSet.getString(3));
    }

    resultSet.close();
    state.close();
    conn.close();
}
 
Example #11
Source File: DriverTest.java    From Kylin with Apache License 2.0 6 votes vote down vote up
@Test
public void testPreStatementWithMockData() throws SQLException {
    Driver driver = new DummyDriver();

    Connection conn = driver.connect("jdbc:kylin://test_url/test_db", null);
    PreparedStatement state = conn.prepareStatement("select * from test_table where id=?");
    state.setInt(1, 10);
    ResultSet resultSet = state.executeQuery();

    ResultSetMetaData metadata = resultSet.getMetaData();
    assertEquals(12, metadata.getColumnType(1));
    assertEquals("varchar", metadata.getColumnTypeName(1));
    assertEquals(1, metadata.isNullable(1));

    while (resultSet.next()) {
        assertEquals("foo", resultSet.getString(1));
        assertEquals("bar", resultSet.getString(2));
        assertEquals("tool", resultSet.getString(3));
    }
}
 
Example #12
Source File: IoTDBAliasIT.java    From incubator-iotdb with Apache License 2.0 5 votes vote down vote up
@Test
public void selectAggregationWithAliasTest() throws ClassNotFoundException {
  String[] retArray = new String[]{
      "4,4,28.3,26.3,"
  };

  Class.forName(Config.JDBC_DRIVER_NAME);
  try (Connection connection = DriverManager
      .getConnection(Config.IOTDB_URL_PREFIX + "127.0.0.1:6667/", "root", "root");
      Statement statement = connection.createStatement()) {
    boolean hasResultSet = statement
        .execute("select count(speed), max_value(temperature) from root.sg.*");
    Assert.assertTrue(hasResultSet);

    try (ResultSet resultSet = statement.getResultSet()) {
      ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
      StringBuilder header = new StringBuilder();
      for (int i = 1; i <= resultSetMetaData.getColumnCount(); i++) {
        header.append(resultSetMetaData.getColumnName(i)).append(",");
      }
      assertEquals("count(root.sg.d1.speed),count(root.sg.d2.speed),"
              + "max_value(root.sg.d1.temperature),max_value(root.sg.d2.temperature),",
          header.toString());

      int cnt = 0;
      while (resultSet.next()) {
        StringBuilder builder = new StringBuilder();
        for (int i = 1; i <= resultSetMetaData.getColumnCount(); i++) {
          builder.append(resultSet.getString(i)).append(",");
        }
        assertEquals(retArray[cnt], builder.toString());
        cnt++;
      }
      assertEquals(retArray.length, cnt);
    }
  } catch (Exception e) {
    e.printStackTrace();
    fail(e.getMessage());
  }
}
 
Example #13
Source File: MetaResultSetTest.java    From calcite-avatica with Apache License 2.0 5 votes vote down vote up
@Test public void testGetCatalogs() throws SQLException {
  DatabaseMetaData metadata = getDatabaseMetadata();
  try (ResultSet rs = metadata.getCatalogs()) {
    ResultSetMetaData rsMeta = rs.getMetaData();

    assertEquals(1, rsMeta.getColumnCount());
    assertColumn(rsMeta, 1, "TABLE_CAT", Types.VARCHAR, DatabaseMetaData.columnNoNulls);
  }
}
 
Example #14
Source File: JdbcDumpFactory.java    From XPagesExtensionLibrary with Apache License 2.0 5 votes vote down vote up
public DumpAccessor find(DumpContext dumpContext, Object o) {
    if(o instanceof DatabaseMetaData) {
        return new DatabaseMetaDataMap(dumpContext,(DatabaseMetaData)o);
    }
    if(o instanceof ResultSet) {
        return new ResultSetGrid(dumpContext,(ResultSet)o);
    }
    if(o instanceof ResultSetMetaData) {
        return new ResultSetMetaDataGrid(dumpContext,(ResultSetMetaData)o);
    }
    return null;
}
 
Example #15
Source File: TestProgressMonitor.java    From presto with Apache License 2.0 5 votes vote down vote up
@Test
public void test()
        throws SQLException
{
    for (String result : createResults()) {
        server.enqueue(new MockResponse()
                .addHeader(CONTENT_TYPE, "application/json")
                .setBody(result));
    }

    try (Connection connection = createConnection()) {
        try (Statement statement = connection.createStatement()) {
            PrestoStatement prestoStatement = statement.unwrap(PrestoStatement.class);
            RecordingProgressMonitor progressMonitor = new RecordingProgressMonitor();
            prestoStatement.setProgressMonitor(progressMonitor);
            try (ResultSet rs = statement.executeQuery("bogus query for testing")) {
                ResultSetMetaData metadata = rs.getMetaData();
                assertEquals(metadata.getColumnCount(), 1);
                assertEquals(metadata.getColumnName(1), "_col0");

                assertTrue(rs.next());
                assertEquals(rs.getLong(1), 253161L);
                assertEquals(rs.getLong("_col0"), 253161L);

                assertFalse(rs.next());
            }
            prestoStatement.clearProgressMonitor();

            List<QueryStats> queryStatsList = progressMonitor.finish();
            assertGreaterThanOrEqual(queryStatsList.size(), 5); // duplicate stats is possible
            assertEquals(queryStatsList.get(0).getState(), "QUEUED");
            assertEquals(queryStatsList.get(queryStatsList.size() - 1).getState(), "FINISHED");
        }
    }
}
 
Example #16
Source File: ImportUtil.java    From jackcess with Apache License 2.0 5 votes vote down vote up
/**
 * Copy an existing JDBC ResultSet into a new (or optionally existing) table
 * in this database.
 *
 * @param name Name of the new table to create
 * @param source ResultSet to copy from
 * @param filter valid import filter
 * @param useExistingTable if {@code true} use current table if it already
 *                         exists, otherwise, create new table with unique
 *                         name
 *
 * @return the name of the imported table
 *
 * @see Builder
 */
public static String importResultSet(ResultSet source, Database db,
                                     String name, ImportFilter filter,
                                     boolean useExistingTable)
  throws SQLException, IOException
{
  ResultSetMetaData md = source.getMetaData();

  name = TableBuilder.escapeIdentifier(name);
  Table table = null;
  if(!useExistingTable || ((table = db.getTable(name)) == null)) {
    List<ColumnBuilder> columns = toColumns(md);
    table = createUniqueTable(db, name, columns, md, filter);
  }

  List<Object[]> rows = new ArrayList<Object[]>(COPY_TABLE_BATCH_SIZE);
  int numColumns = md.getColumnCount();

  while (source.next()) {
    Object[] row = new Object[numColumns];
    for (int i = 0; i < row.length; i++) {
      row[i] = source.getObject(i + 1);
    }
    row = filter.filterRow(row);
    if(row == null) {
      continue;
    }
    rows.add(row);
    if (rows.size() == COPY_TABLE_BATCH_SIZE) {
      table.addRows(rows);
      rows.clear();
    }
  }
  if (rows.size() > 0) {
    table.addRows(rows);
  }

  return table.getName();
}
 
Example #17
Source File: GroupByOrderByIT.java    From spliceengine with GNU Affero General Public License v3.0 5 votes vote down vote up
private static int verifyColumns(ResultSet rs, List<String> expectedColNames,
                                 List<String> excludedColNames, boolean print) throws Exception {
    ResultSetMetaData meta = rs.getMetaData();
    List<String> actualColNames = new ArrayList<String>(meta.getColumnCount());
    for (int i = 0; i < meta.getColumnCount(); i++) {
        actualColNames.add(meta.getColumnName(i+1));
    }

    List<String> errors = new ArrayList<String>();
    List<List<String>> rows = new ArrayList<List<String>>();
    while (rs.next()) {
        List<String> row = new ArrayList<String>();
        for (int j = 0; j < actualColNames.size(); j++) {
            String expectedColName = expectedColNames.get(j);
            String actualColumn = rs.getObject(j+1).toString();
            row.add(actualColumn);
            if (! excludedColNames.contains(expectedColName) && ! actualColumn.startsWith(expectedColName.substring(0, 1))) {
                errors.add((rows.size()+1) +":"+ (j+1) + " ["+ actualColumn +
                        "] did not match expected column ["+ expectedColName +"]");
            }
        }
        rows.add(row);
    }

    Assert.assertEquals(printResults(Arrays.asList("Column names didn't match: "), actualColNames, rows), expectedColNames, actualColNames);
    Assert.assertFalse(printResults(errors, actualColNames, rows), errors.size() > 0);
    if (print) {
        String results = printResults(Collections.EMPTY_LIST, actualColNames, rows);
        System.out.println(results);
    }

    return rows.size();
}
 
Example #18
Source File: CommonCachedRowSetTests.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private void compareMetaData(ResultSetMetaData rsmd,
        ResultSetMetaData rsmd1) throws SQLException {

    assertEquals(rsmd1.getColumnCount(), rsmd.getColumnCount());
    int cols = rsmd.getColumnCount();
    for (int i = 1; i <= cols; i++) {
        assertTrue(rsmd1.getCatalogName(i).equals(rsmd.getCatalogName(i)));
        assertTrue(rsmd1.getColumnClassName(i).equals(rsmd.getColumnClassName(i)));
        assertTrue(rsmd1.getColumnDisplaySize(i) == rsmd.getColumnDisplaySize(i));
        assertTrue(rsmd1.getColumnLabel(i).equals(rsmd.getColumnLabel(i)));
        assertTrue(rsmd1.getColumnName(i).equals(rsmd.getColumnName(i)));
        assertTrue(rsmd1.getColumnType(i) == rsmd.getColumnType(i));
        assertTrue(rsmd1.getPrecision(i) == rsmd.getPrecision(i));
        assertTrue(rsmd1.getScale(i) == rsmd.getScale(i));
        assertTrue(rsmd1.getSchemaName(i).equals(rsmd.getSchemaName(i)));
        assertTrue(rsmd1.getTableName(i).equals(rsmd.getTableName(i)));
        assertTrue(rsmd1.isAutoIncrement(i) == rsmd.isAutoIncrement(i));
        assertTrue(rsmd1.isCaseSensitive(i) == rsmd.isCaseSensitive(i));
        assertTrue(rsmd1.isCurrency(i) == rsmd.isCurrency(i));
        assertTrue(rsmd1.isDefinitelyWritable(i) == rsmd.isDefinitelyWritable(i));
        assertTrue(rsmd1.isNullable(i) == rsmd.isNullable(i));
        assertTrue(rsmd1.isReadOnly(i) == rsmd.isReadOnly(i));
        assertTrue(rsmd1.isSearchable(i) == rsmd.isSearchable(i));
        assertTrue(rsmd1.isSigned(i) == rsmd.isSigned(i));
        assertTrue(rsmd1.isWritable(i) == rsmd.isWritable(i));

    }
}
 
Example #19
Source File: JDBC.java    From kareldb with Apache License 2.0 5 votes vote down vote up
/**
 * Does the work of assertDrainResults() as described
 * above.  If the received row count is non-negative,
 * this method also asserts that the number of rows
 * in the result set matches the received row count.
 * <p>
 * The ResultSet is closed by this method.
 *
 * @param rs           Result set to drain.
 * @param expectedRows If non-negative, indicates how
 *                     many rows we expected to see in the result set.
 * @return the number of rows seen.
 * @throws SQLException
 */
public static int assertDrainResults(ResultSet rs,
                                     int expectedRows) throws SQLException {
    ResultSetMetaData rsmd = rs.getMetaData();
    List<List<String>> seen = new ArrayList<>();
    List<String> seenRow = new ArrayList<>();

    int rows = 0;
    while (rs.next()) {
        for (int col = 1; col <= rsmd.getColumnCount(); col++) {
            String s = rs.getString(col);
            seenRow.add(s);
            assertEquals(s == null, rs.wasNull());
            if (rs.wasNull())
                assertResultColumnNullable(rs, seen, seenRow, col);
        }
        rows++;
        seen.add(new ArrayList<>(seenRow));
        seenRow.clear();
    }
    rs.close();

    if (expectedRows >= 0) {
        try {
            assertEquals("Unexpected row count:", expectedRows, rows);
        } catch (AssertionError e) {
            throw addRsToReport(e, rsmd, seen, seenRow, rs);
        }
    }

    return rows;
}
 
Example #20
Source File: TriggerSample.java    From evosql with Apache License 2.0 5 votes vote down vote up
private static void dumpTable(String tn) throws SQLException {

        Connection        conn  = getConnection();
        Statement         stmt  = conn.createStatement();
        ResultSet         rs    = stmt.executeQuery("select * from " + tn);
        ResultSetMetaData rsmd  = rs.getMetaData();
        int               count = rsmd.getColumnCount();

        out.println();
        out.println("****************************************");
        out.println("DUMP FOR TABLE: " + tn);
        out.println("****************************************");
        out.flush();

        while (rs.next()) {
            out.print("[");

            for (int i = 1; i <= count; i++) {
                out.print(rs.getString(i));

                if (i < count) {
                    out.print(" : ");
                }
            }

            out.println("]");
        }

        out.println();
        out.flush();
        rs.close();
        stmt.close();
        conn.close();
    }
 
Example #21
Source File: StatementsTest.java    From FoxTelem with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Test for PreparedStatement.executeLargeUpdate().
 * Validate update count returned and generated keys.
 * Case: explicitly requesting generated keys.
 */
public void testPrepStmtExecuteLargeUpdateExplicitGeneratedKeys() throws Exception {
    createTable("testExecuteLargeUpdate", "(id BIGINT AUTO_INCREMENT PRIMARY KEY, n INT)");

    this.pstmt = this.conn.prepareStatement("INSERT INTO testExecuteLargeUpdate (n) VALUES (?), (?), (?), (?), (?)", Statement.RETURN_GENERATED_KEYS);
    this.pstmt.setInt(1, 1);
    this.pstmt.setInt(2, 2);
    this.pstmt.setInt(3, 3);
    this.pstmt.setInt(4, 4);
    this.pstmt.setInt(5, 5);

    long count = this.pstmt.executeLargeUpdate();
    assertEquals(5, count);
    assertEquals(5, this.pstmt.getLargeUpdateCount());

    this.rs = this.pstmt.getGeneratedKeys();

    ResultSetMetaData rsmd = this.rs.getMetaData();
    assertEquals(1, rsmd.getColumnCount());
    assertEquals(JDBCType.BIGINT.getVendorTypeNumber().intValue(), rsmd.getColumnType(1));
    assertEquals(20, rsmd.getColumnDisplaySize(1));

    long generatedKey = 0;
    while (this.rs.next()) {
        assertEquals(++generatedKey, this.rs.getLong(1));
    }
    assertEquals(5, generatedKey);
    this.rs.close();
}
 
Example #22
Source File: SnowflakeDriverIT.java    From snowflake-jdbc with Apache License 2.0 5 votes vote down vote up
@Test
@ConditionalIgnoreRule.ConditionalIgnore(condition = RunningOnGithubAction.class)
public void testToTimestampNullBind() throws Throwable
{
  Connection connection = null;
  PreparedStatement preparedStatement = null;

  try
  {
    connection = getConnection();

    preparedStatement = connection.prepareStatement(
        "select 3 where to_timestamp_ltz(?, 3) = '1970-01-01 00:00:12.345 +000'::timestamp_ltz");

    // First test, normal usage.
    preparedStatement.setInt(1, 12345);

    ResultSet resultSet = preparedStatement.executeQuery();
    ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
    // Assert column count.
    assertEquals(1, resultSetMetaData.getColumnCount());
    // Assert this returned a 3.
    assertTrue(resultSet.next());
    assertEquals(3, resultSet.getInt(1));
    assertFalse(resultSet.next());

    // Second test, input is null.
    preparedStatement.setNull(1, Types.INTEGER);

    resultSet = preparedStatement.executeQuery();
    // Assert no rows returned.
    assertFalse(resultSet.next());
  }
  finally
  {
    closeSQLObjects(preparedStatement, connection);
  }
}
 
Example #23
Source File: TestSqlParserProcessor.java    From datacollector with Apache License 2.0 5 votes vote down vote up
@Test
public void testUnsupportedToError() throws Exception {
  SqlParserConfigBean config = new SqlParserConfigBean();
  config.resolveSchema = true;
  config.sqlField = "/sql";
  config.resultFieldPath = "/res";
  config.dbTimeZone = "UTC";
  config.sendUnsupportedFields = false;
  config.unsupportedFieldOp = UnsupportedFieldTypeValues.TO_ERROR;
  Record r = RecordCreator.create();
  Map<String, Field> fields = new HashMap<>();
  fields.put("sql", Field.create("INSERT INTO \"SYS\".\"TEST\"(\"ID\", \"CL\") VALUES ('10', EMPTY_CLOB())"));
  r.set(Field.create(fields));
  SqlParserProcessor processor = new SqlParserProcessor(config);
  ResultSetMetaData rsmd = setupMocks("\"SYS\".\"TEST\"", processor);
  Mockito.when(rsmd.getColumnCount()).thenReturn(2);
  Mockito.when(rsmd.getColumnType(eq(1))).thenReturn(Types.INTEGER);
  Mockito.when(rsmd.getColumnName(eq(1))).thenReturn("ID");
  Mockito.when(rsmd.getColumnType(eq(2))).thenReturn(Types.CLOB);
  Mockito.when(rsmd.getColumnName(eq(2))).thenReturn("CL");
  ProcessorRunner runner = new ProcessorRunner.Builder(SqlParserDProcessor.class, processor)
      .addOutputLane("s").setOnRecordError(OnRecordError.TO_ERROR).build();
  runner.runInit();
  StageRunner.Output output = runner.runProcess(ImmutableList.of(r));
  Assert.assertTrue(output.getRecords().get("s").isEmpty());
  Record result = runner.getErrorRecords().get(0);
  Assert.assertEquals(10, result.get("/res/ID").getValueAsInteger());
  Assert.assertNull(result.get("/res/CL"));
  assertOperationCode(result, OperationType.INSERT_CODE);
  assertTableSchema(result, "SYS", "TEST");
}
 
Example #24
Source File: JdbcTestQueryBase.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
protected static void testQuery(String sql) throws Exception{
  boolean success = false;
  try {
    for (int x = 0; x < 1; x++) {
      Stopwatch watch = Stopwatch.createStarted();
      Statement s = getConnection().createStatement();
      ResultSet r = s.executeQuery(sql);
      System.out.println(String.format("QueryId: %s", r.unwrap(DremioResultSet.class).getQueryId()));
      boolean first = true;
      while (r.next()) {
        ResultSetMetaData md = r.getMetaData();
        if (first == true) {
          for (int i = 1; i <= md.getColumnCount(); i++) {
            System.out.print(md.getColumnName(i));
            System.out.print('\t');
          }
          System.out.println();
          first = false;
        }

        for (int i = 1; i <= md.getColumnCount(); i++) {
          System.out.print(r.getObject(i));
          System.out.print('\t');
        }
        System.out.println();
      }

      System.out.println(String.format("Query completed in %d millis.", watch.elapsed(TimeUnit.MILLISECONDS)));
    }

    System.out.println("\n\n\n");
    success = true;
  } finally {
    if (!success) {
      Thread.sleep(2000);
    }
  }
}
 
Example #25
Source File: RowSetMetaDataTests.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
@DataProvider(name = "validSetNullableValues")
private Object[][] validSetNullableValues() {
    return new Object[][]{
        {ResultSetMetaData.columnNoNulls},
        {ResultSetMetaData.columnNullable},
        {ResultSetMetaData.columnNullableUnknown}
    };
}
 
Example #26
Source File: DatabaseStepsTests.java    From vividus with Apache License 2.0 5 votes vote down vote up
private ResultSet mockResultSet(String columnName, String value) throws SQLException
{
    ResultSetMetaData rsmd = mock(ResultSetMetaData.class);
    when(rsmd.getColumnCount()).thenReturn(1);
    when(rsmd.getColumnLabel(1)).thenReturn(columnName);
    ResultSet rs = mock(ResultSet.class);
    when(rs.next()).thenReturn(true).thenReturn(false);
    when(rs.getMetaData()).thenReturn(rsmd);
    when(rs.getObject(1)).thenReturn(value);
    return rs;
}
 
Example #27
Source File: DbMetaDataHelper.java    From syndesis with Apache License 2.0 5 votes vote down vote up
@SuppressFBWarnings("OBL_UNSATISFIED_OBLIGATION")
/* default */ List<SqlParam> getOutputColumnInfo(
        final String sqlSelectStatement) throws SQLException {
    List<SqlParam> paramList = new ArrayList<>();
    try (PreparedStatement stmt = createPreparedStatement(sqlSelectStatement);
        ResultSet resultSet = stmt.executeQuery();) {
        ResultSetMetaData metaData = resultSet.getMetaData();
        if (metaData.getColumnCount()>0){
            for (int i=1; i<=metaData.getColumnCount(); i++) {
                SqlParam param = new SqlParam(metaData.getColumnName(i));
                param.setJdbcType(JDBCType.valueOf(metaData.getColumnType(i)));
                paramList.add(param);
            }
        }
        return paramList;
    }
}
 
Example #28
Source File: ResultSetsFromPreparedStatementTest.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * Prints a diff between a ResultSet and an expected Object[][]
 * value to a PrintStream. The first line is a heading with name
 * and type of each column. Each row is printed as a
 * comma-separated list of columns. The printed value of a column
 * is getObject(i).toString(). <p>
 *
 * If the expected value does not match the value from the RS, the
 * expected value is printed followed by the actual value in angle
 * brackets.  The comparion starts from 'fromRow' (zero-based row
 * index). Unmatched rows are printed with 'null' for the missing
 * values. <p>
 *
 * dumpee must be positioned on a valid row, or moreRows must be
 * false.  Closes the RS when done.
 * @param expected the expected value of the RS
 * @param fromRow row to start comparison from
 * @param dumpee the ResultSet to dump
 * @param moreRows true if there are more rows in the RS
 * @param stream the stream to dump the ResultSet to
 */
private static void dumpDiff(Object[][] expected, int fromRow,
                             ResultSet dumpee, boolean moreRows,
                             PrintStream stream) throws SQLException {
    final ResultSetMetaData rm = dumpee.getMetaData();
    final int colCount = rm.getColumnCount();
    for (int c = 1; c <= colCount; ++c) {
        stream.print("" + rm.getColumnLabel(c) + " " +
                         rm.getColumnTypeName(c) + ", ");
    }
    stream.println("");

    for (; moreRows || fromRow < expected.length; ++fromRow) {
        for (int c = 1; c <= colCount; ++c) {
            final Object e =
                (fromRow<expected.length?expected[fromRow][c-1]:null);
            final Object ret = (moreRows?dumpee.getObject(c):null);
            stream.print(e);
            if (e == null || ret == null || !ret.equals(e)) {
                stream.print("<" + ret +">");
            }
            stream.print(", ");
        }
        stream.println("");
        moreRows = dumpee.next();
    }
    dumpee.close();
}
 
Example #29
Source File: ProcedureTest.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
public void testExecuteQueryWithDataAwareProcedureCall()
throws SQLException {

  setup();
  CallableStatement cs = prepareCall("CALL RETRIEVE_DYNAMIC_RESULTS(?) "
      + "ON TABLE EMP.PARTITIONTESTTABLE WHERE SECONDID in (?,?,?) AND THIRDID='3'");
  cs.setInt(1, 2);
  cs.setInt(2, 3);
  cs.setInt(3, 4);
  cs.setInt(4, 5);
  cs.execute();
  
  String[][] results=new String[2][1];
  results[0][0]="1";
  results[1][0]="1";
           
  int rsIndex=-1;
  do {
    ++rsIndex;
    int rowIndex=0;
    ResultSet rs = cs.getResultSet();
    ResultSetMetaData metaData = rs.getMetaData();
    int rowCount = metaData.getColumnCount();
    while (rs.next()) {
      String row="";
      for (int i = 1; i <=rowCount; ++i) {
        Object value = rs.getObject(i);
        row+=value.toString();          
      }
      if(rsIndex>1 || rowIndex>1) {
        fail("the result is not correct!");
      }
      if(!row.equals(results[rsIndex][rowIndex])) {
        fail("the result is not correct!");
      }
      ++rowIndex;
    }
  } while (cs.getMoreResults());    
  
}
 
Example #30
Source File: SelectUtil.java    From spiracle with Apache License 2.0 5 votes vote down vote up
private static void writeRow(ServletOutputStream out, ResultSet rs, ResultSetMetaData metaData) throws IOException, SQLException {
	out.println("<TR>");
	for(int i = 1; i <= metaData.getColumnCount(); i++) {
		Object content = rs.getObject(i);
		if(content != null) {
			out.println("<TD>" + content.toString() + "</TD>");
		} else {
			out.println("<TD></TD>");
		}
	}
	out.println("</TR>");
}