Java Code Examples for java.sql.PreparedStatement#getMetaData()

The following examples show how to use java.sql.PreparedStatement#getMetaData() . 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: ClickHousePreparedStatementTest.java    From clickhouse-jdbc with Apache License 2.0 6 votes vote down vote up
@Test
public void testMetadataOnlySelect() throws Exception {
    connection.createStatement().execute(
        "DROP TABLE IF EXISTS test.mymetadata");
    connection.createStatement().execute(
        "CREATE TABLE IF NOT EXISTS test.mymetadata "
      + "(idx Int32, s String) "
      + "ENGINE = TinyLog"
    );
    PreparedStatement insertStmt = connection.prepareStatement(
        "INSERT INTO test.mymetadata (idx, s) VALUES (?, ?)");
    insertStmt.setInt(1, 42);
    insertStmt.setString(2, "foo");
    insertStmt.executeUpdate();
    PreparedStatement metaStmt = connection.prepareStatement(
        "SELECT idx, s FROM test.mymetadata WHERE idx = ?");
    metaStmt.setInt(1, 42);
    ResultSetMetaData metadata = metaStmt.getMetaData();
    Assert.assertEquals(metadata.getColumnCount(), 2);
    Assert.assertEquals(metadata.getColumnName(1), "idx");
    Assert.assertEquals(metadata.getColumnName(2), "s");
}
 
Example 2
Source File: DatabaseImpl.java    From r2rml-parser with Apache License 2.0 6 votes vote down vote up
/**
 * 
 * Create a PreparedStatement with the query string and get its metadata. If this works, the query string is ok (but nothing is executed)
 * 
 */
public void testQuery(String query) {
	try {
		if (connection == null) openConnection();

		PreparedStatement preparedStatement = connection.prepareStatement(query);
		
		ResultSetMetaData m = preparedStatement.getMetaData();
		log.info ("Query is ok. Retrieves a dataset with " + m.getColumnCount() + " column(s).");
		
		preparedStatement.close();
	} catch (SQLException e) {
		log.error("Error testing query! Query was: " + query);
		System.exit(1);
	}
}
 
Example 3
Source File: ClickHousePreparedStatementTest.java    From clickhouse-jdbc with Apache License 2.0 6 votes vote down vote up
@Test
public void testMetadataOnlyUpdate() throws Exception {
    connection.createStatement().execute(
        "DROP TABLE IF EXISTS test.mymetadata");
    connection.createStatement().execute(
        "CREATE TABLE IF NOT EXISTS test.mymetadata "
      + "(idx Int32, s String) "
      + "ENGINE = TinyLog"
    );
    PreparedStatement insertStmt = connection.prepareStatement(
        "INSERT INTO test.mymetadata (idx, s) VALUES (?, ?)");
    insertStmt.setInt(1, 42);
    insertStmt.setString(2, "foo");
    insertStmt.executeUpdate();
    PreparedStatement metaStmt = connection.prepareStatement(
        "UPDATE test.mymetadata SET s = ? WHERE idx = ?");
    metaStmt.setString(1, "foo");
    metaStmt.setInt(2, 42);
    ResultSetMetaData metadata = metaStmt.getMetaData();
    Assert.assertNull(metadata);
    metaStmt.close();
}
 
Example 4
Source File: QueryMetaDataTest.java    From phoenix with Apache License 2.0 5 votes vote down vote up
@Test
public void testBasicResultSetMetaData() throws Exception {
    String query = "SELECT organization_id, a_string, b_string, a_integer i, a_date FROM atable WHERE organization_id='000000000000000' and substr(entity_id,1,3)=? and a_string = 'foo'";
    Connection conn = DriverManager.getConnection(getUrl(), PropertiesUtil.deepCopy(TestUtil.TEST_PROPERTIES));
    PreparedStatement statement = conn.prepareStatement(query);
    ResultSetMetaData md = statement.getMetaData();
    assertEquals(5, md.getColumnCount());
    
    assertEquals("organization_id".toUpperCase(),md.getColumnName(1));
    assertEquals("a_string".toUpperCase(),md.getColumnName(2));
    assertEquals("b_string".toUpperCase(),md.getColumnName(3));
    assertEquals("i".toUpperCase(),md.getColumnName(4));
    assertEquals("a_date".toUpperCase(),md.getColumnName(5));
    
    assertEquals(String.class.getName(),md.getColumnClassName(1));
    assertEquals(String.class.getName(),md.getColumnClassName(2));
    assertEquals(String.class.getName(),md.getColumnClassName(3));
    assertEquals(Integer.class.getName(),md.getColumnClassName(4));
    assertEquals(Date.class.getName(),md.getColumnClassName(5));
    
    assertEquals("atable".toUpperCase(),md.getTableName(1));
    assertEquals(java.sql.Types.INTEGER,md.getColumnType(4));
    assertEquals(true,md.isReadOnly(1));
    assertEquals(false,md.isDefinitelyWritable(1));
    assertEquals("i".toUpperCase(),md.getColumnLabel(4));
    assertEquals("a_date".toUpperCase(),md.getColumnLabel(5));
    assertEquals(ResultSetMetaData.columnNoNulls,md.isNullable(1));
    assertEquals(ResultSetMetaData.columnNullable,md.isNullable(5));
}
 
Example 5
Source File: ScrollCursors2Test.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * Tests for PreparedStatement.getMetaData().
 *
 * @exception SQLException
 *                Thrown if some unexpected error happens
 */
public void testGetMetaData() throws SQLException {

    PreparedStatement ps_f_r = null; // forward only, read only
    ResultSet rs;
    ResultSetMetaData rsmd_ps;
    ResultSetMetaData rsmd_rs;

    ps_f_r = prepareStatement("select c50, i, 43 from t",
            ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);

    rsmd_ps = ps_f_r.getMetaData();
    assertNotNull(rsmd_ps);

    // Now get meta data from result set
    rs = ps_f_r.executeQuery();
    rsmd_rs = rs.getMetaData();
    assertNotNull(rsmd_rs);

    // check column count
    assertEquals(rsmd_ps.getColumnCount(), rsmd_rs.getColumnCount());

    // get column name for 2nd column
    assertEquals(rsmd_ps.getColumnName(2), rsmd_rs.getColumnName(2));
    assertEquals(rsmd_ps.isReadOnly(2), rsmd_rs.isReadOnly(2));

    rs.close();
    ps_f_r.close();

}
 
Example 6
Source File: ClickHousePreparedStatementTest.java    From clickhouse-jdbc with Apache License 2.0 5 votes vote down vote up
@Test
public void testMetadataExecutionAfterMeta() throws Exception {
    connection.createStatement().execute(
        "DROP TABLE IF EXISTS test.mymetadata");
    connection.createStatement().execute(
        "CREATE TABLE IF NOT EXISTS test.mymetadata "
      + "(idx Int32, s String) "
      + "ENGINE = TinyLog"
    );
    PreparedStatement insertStmt = connection.prepareStatement(
        "INSERT INTO test.mymetadata (idx, s) VALUES (?, ?)");
    insertStmt.setInt(1, 42);
    insertStmt.setString(2, "foo");
    insertStmt.executeUpdate();
    PreparedStatement metaStmt = connection.prepareStatement(
        "SELECT idx, s FROM test.mymetadata WHERE idx = ?");
    metaStmt.setInt(1, 42);
    ResultSetMetaData metadata = metaStmt.getMetaData();
    Assert.assertEquals(metadata.getColumnCount(), 2);
    Assert.assertEquals(metadata.getColumnName(1), "idx");
    Assert.assertEquals(metadata.getColumnName(2), "s");

    ResultSet rs = metaStmt.executeQuery();
    Assert.assertTrue(rs.next());
    Assert.assertEquals(rs.getInt(1), 42);
    Assert.assertEquals(rs.getString(2), "foo");
    metadata = metaStmt.getMetaData();
    Assert.assertEquals(metadata.getColumnCount(), 2);
    Assert.assertEquals(metadata.getColumnName(1), "idx");
    Assert.assertEquals(metadata.getColumnName(2), "s");
}
 
Example 7
Source File: ScrollCursors2Test.java    From spliceengine with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Tests for PreparedStatement.getMetaData().
 * 
 * @exception SQLException
 *                Thrown if some unexpected error happens
 */
public void testGetMetaData() throws SQLException {

    PreparedStatement ps_f_r = null; // forward only, read only
    ResultSet rs;
    ResultSetMetaData rsmd_ps;
    ResultSetMetaData rsmd_rs;

    ps_f_r = prepareStatement("select c50, i, 43 from t",
            ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);

    rsmd_ps = ps_f_r.getMetaData();
    assertNotNull(rsmd_ps);

    // Now get meta data from result set
    rs = ps_f_r.executeQuery();
    rsmd_rs = rs.getMetaData();
    assertNotNull(rsmd_rs);

    // check column count
    assertEquals(rsmd_ps.getColumnCount(), rsmd_rs.getColumnCount());

    // get column name for 2nd column
    assertEquals(rsmd_ps.getColumnName(2), rsmd_rs.getColumnName(2));
    assertEquals(rsmd_ps.isReadOnly(2), rsmd_rs.isReadOnly(2));

    rs.close();
    ps_f_r.close();

}
 
Example 8
Source File: ScrollCursors2Test.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * Tests for PreparedStatement.getMetaData().
 *
 * @exception SQLException
 *                Thrown if some unexpected error happens
 */
public void testGetMetaData() throws SQLException {

    PreparedStatement ps_f_r = null; // forward only, read only
    ResultSet rs;
    ResultSetMetaData rsmd_ps;
    ResultSetMetaData rsmd_rs;

    ps_f_r = prepareStatement("select c50, i, 43 from t",
            ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);

    rsmd_ps = ps_f_r.getMetaData();
    assertNotNull(rsmd_ps);

    // Now get meta data from result set
    rs = ps_f_r.executeQuery();
    rsmd_rs = rs.getMetaData();
    assertNotNull(rsmd_rs);

    // check column count
    assertEquals(rsmd_ps.getColumnCount(), rsmd_rs.getColumnCount());

    // get column name for 2nd column
    assertEquals(rsmd_ps.getColumnName(2), rsmd_rs.getColumnName(2));
    assertEquals(rsmd_ps.isReadOnly(2), rsmd_rs.isReadOnly(2));

    rs.close();
    ps_f_r.close();

}
 
Example 9
Source File: PrepStmtMetaDataTest.java    From spliceengine with GNU Affero General Public License v3.0 4 votes vote down vote up
public void testAlterTableMeta() throws SQLException {

       Statement s = createStatement();
        s.executeUpdate("create table bug4579 (c11 int)");
        s.executeUpdate("insert into bug4579 values (1)");
        PreparedStatement ps = prepareStatement("select * from bug4579");
        ResultSetMetaData rsmd = ps.getMetaData();
        assertEquals(1, rsmd.getColumnCount());
        assertEquals(java.sql.Types.INTEGER, rsmd.getColumnType(1));
        assertEquals("C11", rsmd.getColumnName(1));

        s.executeUpdate("alter table bug4579 add column c12 int");

        if (usingDerbyNetClient()) {
            // DERBY-2402 Client does not report added columns.
            // Take out check when DERBY-2402 is fixed
            //
        } else {
            rsmd = ps.getMetaData();
            assertEquals(2, rsmd.getColumnCount());
            assertEquals(java.sql.Types.INTEGER, rsmd.getColumnType(1));
            assertEquals("C11", rsmd.getColumnName(1));
            assertEquals(java.sql.Types.INTEGER, rsmd.getColumnType(2));
            assertEquals("C12", rsmd.getColumnName(2));
        }

        // ResultSetMetaData for select * after alter table and
        // executeQuery.
        s.executeUpdate("alter table bug4579 add column c13 int");
        ResultSet rs = ps.executeQuery();
        rsmd = ps.getMetaData();
        assertEquals(3, rsmd.getColumnCount());
        assertEquals(java.sql.Types.INTEGER, rsmd.getColumnType(1));
        assertEquals("C11", rsmd.getColumnName(1));
        assertEquals(java.sql.Types.INTEGER, rsmd.getColumnType(2));
        assertEquals("C12", rsmd.getColumnName(2));
        assertEquals(java.sql.Types.INTEGER, rsmd.getColumnType(3));
        assertEquals("C13", rsmd.getColumnName(3));

        // Check ps metadata again
        rsmd = ps.getMetaData();
        assertEquals(3, rsmd.getColumnCount());
        assertEquals(java.sql.Types.INTEGER, rsmd.getColumnType(1));
        assertEquals("C11", rsmd.getColumnName(1));
        assertEquals(java.sql.Types.INTEGER, rsmd.getColumnType(2));
        assertEquals("C12", rsmd.getColumnName(2));
        assertEquals(java.sql.Types.INTEGER, rsmd.getColumnType(3));
        assertEquals("C13", rsmd.getColumnName(3));

        rs.close();
        ps.close();
        s.executeUpdate("drop table bug4579");
        s.close();

    }
 
Example 10
Source File: UnsupportedOperationPreparedStatementTest.java    From sharding-jdbc-1.5.1 with Apache License 2.0 4 votes vote down vote up
@Test(expected = SQLFeatureNotSupportedException.class)
public void assertGetMetaData() throws SQLException {
    for (PreparedStatement each : statements) {
        each.getMetaData();
    }
}
 
Example 11
Source File: SwPreparedStatementTest.java    From skywalking with Apache License 2.0 4 votes vote down vote up
@Test
public void testPreparedStatementConfig() throws SQLException {
    PreparedStatement preparedStatement = swConnection.prepareStatement("INSERT INTO test VALUES( ? , ?)", 1);
    preparedStatement.setInt(1, 1);
    preparedStatement.setString(2, "a");
    preparedStatement.getUpdateCount();
    preparedStatement.setFetchDirection(1);
    preparedStatement.getFetchDirection();
    preparedStatement.getResultSetConcurrency();
    preparedStatement.getResultSetType();
    preparedStatement.isClosed();
    preparedStatement.setPoolable(false);
    preparedStatement.isPoolable();
    preparedStatement.getWarnings();
    preparedStatement.clearWarnings();
    preparedStatement.setCursorName("test");
    preparedStatement.setMaxFieldSize(11);
    preparedStatement.getMaxFieldSize();
    preparedStatement.setMaxRows(10);
    preparedStatement.getMaxRows();
    preparedStatement.getParameterMetaData();
    preparedStatement.setEscapeProcessing(true);
    preparedStatement.setFetchSize(1);
    preparedStatement.getFetchSize();
    preparedStatement.setQueryTimeout(1);
    preparedStatement.getQueryTimeout();
    Connection connection = preparedStatement.getConnection();

    preparedStatement.execute();

    preparedStatement.getMoreResults();
    preparedStatement.getMoreResults(1);
    preparedStatement.getResultSetHoldability();
    preparedStatement.getMetaData();
    preparedStatement.getResultSet();

    preparedStatement.close();
    verify(mysqlPreparedStatement).getUpdateCount();
    verify(mysqlPreparedStatement).getMoreResults();
    verify(mysqlPreparedStatement).setFetchDirection(anyInt());
    verify(mysqlPreparedStatement).getFetchDirection();
    verify(mysqlPreparedStatement).getResultSetType();
    verify(mysqlPreparedStatement).isClosed();
    verify(mysqlPreparedStatement).setPoolable(anyBoolean());
    verify(mysqlPreparedStatement).getWarnings();
    verify(mysqlPreparedStatement).clearWarnings();
    verify(mysqlPreparedStatement).setCursorName(anyString());
    verify(mysqlPreparedStatement).setMaxFieldSize(anyInt());
    verify(mysqlPreparedStatement).getMaxFieldSize();
    verify(mysqlPreparedStatement).setMaxRows(anyInt());
    verify(mysqlPreparedStatement).getMaxRows();
    verify(mysqlPreparedStatement).setEscapeProcessing(anyBoolean());
    verify(mysqlPreparedStatement).getResultSetConcurrency();
    verify(mysqlPreparedStatement).getResultSetConcurrency();
    verify(mysqlPreparedStatement).getResultSetType();
    verify(mysqlPreparedStatement).getMetaData();
    verify(mysqlPreparedStatement).getParameterMetaData();
    verify(mysqlPreparedStatement).getMoreResults(anyInt());
    verify(mysqlPreparedStatement).setFetchSize(anyInt());
    verify(mysqlPreparedStatement).getFetchSize();
    verify(mysqlPreparedStatement).getQueryTimeout();
    verify(mysqlPreparedStatement).setQueryTimeout(anyInt());
    verify(mysqlPreparedStatement).getResultSet();
    assertThat(connection, CoreMatchers.<Connection>is(swConnection));
}
 
Example 12
Source File: SQLTransportExecutor.java    From crate with Apache License 2.0 4 votes vote down vote up
private static SQLResponse executeAndConvertResult(PreparedStatement preparedStatement) throws SQLException {
    if (preparedStatement.execute()) {
        ResultSetMetaData metaData = preparedStatement.getMetaData();
        ResultSet resultSet = preparedStatement.getResultSet();
        List<Object[]> rows = new ArrayList<>();
        List<String> columnNames = new ArrayList<>(metaData.getColumnCount());
        DataType[] dataTypes = new DataType[metaData.getColumnCount()];
        for (int i = 0; i < metaData.getColumnCount(); i++) {
            columnNames.add(metaData.getColumnName(i + 1));
        }
        while (resultSet.next()) {
            Object[] row = new Object[metaData.getColumnCount()];
            for (int i = 0; i < row.length; i++) {
                Object value;
                String typeName = metaData.getColumnTypeName(i + 1);
                value = getObject(resultSet, i, typeName);
                row[i] = value;
            }
            rows.add(row);
        }
        return new SQLResponse(
            columnNames.toArray(new String[0]),
            rows.toArray(new Object[0][]),
            dataTypes,
            rows.size()
        );
    } else {
        int updateCount = preparedStatement.getUpdateCount();
        if (updateCount < 0) {
            /*
             * In Crate -1 means row-count unknown, and -2 means error. In JDBC -2 means row-count unknown and -3 means error.
             * See {@link java.sql.Statement#EXECUTE_FAILED}
             */
            updateCount += 1;
        }
        return new SQLResponse(
            new String[0],
            new Object[0][],
            new DataType[0],
            updateCount
        );
    }
}
 
Example 13
Source File: FromVTI.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
/**
 * Get the ResultSetMetaData for the class/object.  We first look for 
 * the optional static method which has the same signature as the constructor.
 * If it doesn't exist, then we instantiate an object and get the ResultSetMetaData
 * from that object.
 *
 * @return The ResultSetMetaData from the class/object.
 *
 * @exception StandardException		Thrown on error
 */
public ResultSetMetaData getResultSetMetaData() 
	throws StandardException
{
	// Get the actual 
	ResultSetMetaData rsmd = null;

	try
	{	
		if (version2)
		{
			ps = (PreparedStatement) getNewInstance();

			if (ps.getResultSetConcurrency() != ResultSet.CONCUR_UPDATABLE)
			{
				throw StandardException.newException(SQLState.LANG_UPDATABLE_VTI_NON_UPDATABLE_RS, 
													 getVTIName());
			}

			rsmd = ps.getMetaData();

               controlsDeferral = (ps instanceof DeferModification);

               /* See if the result set is known to be insensitive or not.
                *
                * Some older VTI implementations do not implement getResultSetType(). UpdatableVTITemplate
                * does not implement it at all. UpdatableVTITemplate.getResultSetType throws an
                * exception. In either of these cases make the conservative assumption that the result set is sensitive.
                */
               try
               {
                   resultSetType = ps.getResultSetType();
               }
               catch( SQLException sqle){}
               catch( java.lang.AbstractMethodError ame){}
               catch( java.lang.NoSuchMethodError nsme){}
               isInsensitive = (resultSetType == ResultSet.TYPE_SCROLL_INSENSITIVE);

			if (!implementsVTICosting) {
				ps.close();
				ps = null;
			}

		}
		else
		{
			rs = (ResultSet) getNewInstance();

			rsmd = rs.getMetaData();

			if (!implementsVTICosting) {
				rs.close();
				rs = null;
			}
		}
	}
	catch(Throwable t)
	{
		throw StandardException.unexpectedUserException(t);
	}

	return rsmd;
}
 
Example 14
Source File: PrepStmtMetaDataTest.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
public void testAlterTableMeta() throws SQLException {

       Statement s = createStatement();
        s.executeUpdate("create table bug4579 (c11 int)");
        s.executeUpdate("insert into bug4579 values (1)");
        PreparedStatement ps = prepareStatement("select * from bug4579");
        ResultSetMetaData rsmd = ps.getMetaData();
        assertEquals(1, rsmd.getColumnCount());
        assertEquals(java.sql.Types.INTEGER, rsmd.getColumnType(1));
        assertEquals("C11", rsmd.getColumnName(1));

        // DERBY-2402 Client does not report added columns.
        // Take out check when DERBY-2402 is fixed
        if (usingDerbyNetClient())
            return;

        s.executeUpdate("alter table bug4579 add column c12 int");
        rsmd = ps.getMetaData();
        assertEquals(2, rsmd.getColumnCount());
        assertEquals(java.sql.Types.INTEGER, rsmd.getColumnType(1));
        assertEquals("C11", rsmd.getColumnName(1));
        assertEquals(java.sql.Types.INTEGER, rsmd.getColumnType(2));
        assertEquals("C12", rsmd.getColumnName(2));

        // ResultSetMetaData for select * after alter table and
        // executeQuery.
        s.executeUpdate("alter table bug4579 add column c13 int");
        ResultSet rs = ps.executeQuery();
        rsmd = ps.getMetaData();
        assertEquals(3, rsmd.getColumnCount());
        assertEquals(java.sql.Types.INTEGER, rsmd.getColumnType(1));
        assertEquals("C11", rsmd.getColumnName(1));
        assertEquals(java.sql.Types.INTEGER, rsmd.getColumnType(2));
        assertEquals("C12", rsmd.getColumnName(2));
        assertEquals(java.sql.Types.INTEGER, rsmd.getColumnType(3));
        assertEquals("C13", rsmd.getColumnName(3));
        rs.close();
        ps.close();
        s.executeUpdate("drop table bug4579");
        s.close();

    }
 
Example 15
Source File: FromVTI.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
/**
 * Get the ResultSetMetaData for the class/object.  We first look for 
 * the optional static method which has the same signature as the constructor.
 * If it doesn't exist, then we instantiate an object and get the ResultSetMetaData
 * from that object.
 *
 * @return The ResultSetMetaData from the class/object.
 *
 * @exception StandardException		Thrown on error
 */
public ResultSetMetaData getResultSetMetaData() 
	throws StandardException
{
	// Get the actual 
	ResultSetMetaData rsmd = null;

	try
	{	
		if (version2)
		{
			ps = (PreparedStatement) getNewInstance();

			if (ps.getResultSetConcurrency() != ResultSet.CONCUR_UPDATABLE)
			{
				throw StandardException.newException(SQLState.LANG_UPDATABLE_VTI_NON_UPDATABLE_RS, 
													 getVTIName());
			}

			rsmd = ps.getMetaData();

               controlsDeferral = (ps instanceof DeferModification);

               /* See if the result set is known to be insensitive or not.
                *
                * Some older VTI implementations do not implement getResultSetType(). UpdatableVTITemplate
                * does not implement it at all. UpdatableVTITemplate.getResultSetType throws an
                * exception. In either of these cases make the conservative assumption that the result set is sensitive.
                */
               try
               {
                   resultSetType = ps.getResultSetType();
               }
               catch( SQLException sqle){}
               catch( java.lang.AbstractMethodError ame){}
               catch( java.lang.NoSuchMethodError nsme){}
               isInsensitive = (resultSetType == ResultSet.TYPE_SCROLL_INSENSITIVE);

			if (!implementsVTICosting) {
				ps.close();
				ps = null;
			}

		}
		else
		{
			rs = (ResultSet) getNewInstance();

			rsmd = rs.getMetaData();

			if (!implementsVTICosting) {
				rs.close();
				rs = null;
			}
		}
	}
	catch(Throwable t)
	{
		throw StandardException.unexpectedUserException(t);
	}

	return rsmd;
}
 
Example 16
Source File: PrepStmtMetaDataTest.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
public void testAlterTableMeta() throws SQLException {

       Statement s = createStatement();
        s.executeUpdate("create table bug4579 (c11 int)");
        s.executeUpdate("insert into bug4579 values (1)");
        PreparedStatement ps = prepareStatement("select * from bug4579");
        ResultSetMetaData rsmd = ps.getMetaData();
        assertEquals(1, rsmd.getColumnCount());
        assertEquals(java.sql.Types.INTEGER, rsmd.getColumnType(1));
        assertEquals("C11", rsmd.getColumnName(1));

        // DERBY-2402 Client does not report added columns.
        // Take out check when DERBY-2402 is fixed
        if (usingDerbyNetClient())
            return;

        s.executeUpdate("alter table bug4579 add column c12 int");
        rsmd = ps.getMetaData();
        assertEquals(2, rsmd.getColumnCount());
        assertEquals(java.sql.Types.INTEGER, rsmd.getColumnType(1));
        assertEquals("C11", rsmd.getColumnName(1));
        assertEquals(java.sql.Types.INTEGER, rsmd.getColumnType(2));
        assertEquals("C12", rsmd.getColumnName(2));

        // ResultSetMetaData for select * after alter table and
        // executeQuery.
        s.executeUpdate("alter table bug4579 add column c13 int");
        ResultSet rs = ps.executeQuery();
        rsmd = ps.getMetaData();
        assertEquals(3, rsmd.getColumnCount());
        assertEquals(java.sql.Types.INTEGER, rsmd.getColumnType(1));
        assertEquals("C11", rsmd.getColumnName(1));
        assertEquals(java.sql.Types.INTEGER, rsmd.getColumnType(2));
        assertEquals("C12", rsmd.getColumnName(2));
        assertEquals(java.sql.Types.INTEGER, rsmd.getColumnType(3));
        assertEquals("C13", rsmd.getColumnName(3));
        rs.close();
        ps.close();
        s.executeUpdate("drop table bug4579");
        s.close();

    }
 
Example 17
Source File: PostgresCatalog.java    From flink with Apache License 2.0 4 votes vote down vote up
@Override
public CatalogBaseTable getTable(ObjectPath tablePath) throws TableNotExistException, CatalogException {
	if (!tableExists(tablePath)) {
		throw new TableNotExistException(getName(), tablePath);
	}

	PostgresTablePath pgPath = PostgresTablePath.fromFlinkTableName(tablePath.getObjectName());

	String dbUrl = baseUrl + tablePath.getDatabaseName();
	try (Connection conn = DriverManager.getConnection(dbUrl, username, pwd)) {
		DatabaseMetaData metaData = conn.getMetaData();
		Optional<UniqueConstraint> primaryKey = getPrimaryKey(
			metaData,
			pgPath.getPgSchemaName(),
			pgPath.getPgTableName());

		PreparedStatement ps = conn.prepareStatement(
			String.format("SELECT * FROM %s;", pgPath.getFullPath()));

		ResultSetMetaData rsmd = ps.getMetaData();

		String[] names = new String[rsmd.getColumnCount()];
		DataType[] types = new DataType[rsmd.getColumnCount()];

		for (int i = 1; i <= rsmd.getColumnCount(); i++) {
			names[i - 1] = rsmd.getColumnName(i);
			types[i - 1] = fromJDBCType(rsmd, i);
			if (rsmd.isNullable(i) == ResultSetMetaData.columnNoNulls) {
				types[i - 1] = types[i - 1].notNull();
			}
		}

		TableSchema.Builder tableBuilder = new TableSchema.Builder()
			.fields(names, types);
		primaryKey.ifPresent(pk ->
			tableBuilder.primaryKey(pk.getName(), pk.getColumns().toArray(new String[0]))
		);
		TableSchema tableSchema = tableBuilder.build();

		Map<String, String> props = new HashMap<>();
		props.put(CONNECTOR.key(), IDENTIFIER);
		props.put(URL.key(), dbUrl);
		props.put(TABLE_NAME.key(), pgPath.getFullPath());
		props.put(USERNAME.key(), username);
		props.put(PASSWORD.key(), pwd);

		return new CatalogTableImpl(
			tableSchema,
			props,
			""
		);
	} catch (Exception e) {
		throw new CatalogException(
			String.format("Failed getting table %s", tablePath.getFullName()), e);
	}
}
 
Example 18
Source File: PrepStmtMetaDataTest.java    From gemfirexd-oss with Apache License 2.0 3 votes vote down vote up
/**
 * Check the metatdata for a prepared statement that does not return a
 * ResultSet is empty
 * 
 * @param sql
 *            sql for prepared statement
 * @param execute
 *            execute PreparedStatement if true
 * @throws SQLException
 */
private void checkEmptyMetaData(String sql, boolean execute)
        throws SQLException {
    PreparedStatement ps = prepareStatement(sql);
    ResultSetMetaData rsmd = ps.getMetaData();
    assertEmptyResultSetMetaData(rsmd);
    if (execute)
        ps.executeUpdate();
    ps.close();
}
 
Example 19
Source File: PrepStmtMetaDataTest.java    From gemfirexd-oss with Apache License 2.0 3 votes vote down vote up
/**
 * Check the metatdata for a prepared statement that does not return a
 * ResultSet is empty
 * 
 * @param sql
 *            sql for prepared statement
 * @param execute
 *            execute PreparedStatement if true
 * @throws SQLException
 */
private void checkEmptyMetaData(String sql, boolean execute)
        throws SQLException {
    PreparedStatement ps = prepareStatement(sql);
    ResultSetMetaData rsmd = ps.getMetaData();
    assertEmptyResultSetMetaData(rsmd);
    if (execute)
        ps.executeUpdate();
    ps.close();
}
 
Example 20
Source File: PrepStmtMetaDataTest.java    From spliceengine with GNU Affero General Public License v3.0 3 votes vote down vote up
/**
 * Check the metatdata for a prepared statement that does not return a
 * ResultSet is empty
 * 
 * @param sql
 *            sql for prepared statement
 * @param execute
 *            execute PreparedStatement if true
 * @throws SQLException
 */
private void checkEmptyMetaData(String sql, boolean execute)
        throws SQLException {
    PreparedStatement ps = prepareStatement(sql);
    ResultSetMetaData rsmd = ps.getMetaData();
    assertEmptyResultSetMetaData(rsmd);
    if (execute)
        ps.executeUpdate();
    ps.close();
}