Java Code Examples for java.sql.DatabaseMetaData

The following are top voted examples for showing how to use java.sql.DatabaseMetaData. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: ProyectoPacientes   File: MetaDataRegressionTest.java   View source code 6 votes vote down vote up
/**
 * Tests fix for BUG#38367 - DatabaseMetaData dbMeta = this.conn.getMetaData();
 * this.rs = dbMeta.getProcedureColumns("test", null, "nullableParameterTest", null);
 * ...
 * Short columnNullable = new Short(this.rs.getShort(12));
 * assertTrue("Parameter " + columnName + " do not allow null arguments",
 * columnNullable.intValue() == java.sql.DatabaseMetaData.procedureNullable);
 * was failing for no good reason.
 * 
 * @throws Exception
 *             if the test fails.
 */

public void testBug38367() throws Exception {
    if (!versionMeetsMinimum(5, 0)) {
        return;
    }

    try {
        createProcedure("sptestBug38367",
                "(OUT nfact VARCHAR(100), IN ccuenta VARCHAR(100),\nOUT ffact VARCHAR(100),\nOUT fdoc VARCHAR(100))" + "\nBEGIN\nEND");

        DatabaseMetaData dbMeta = this.conn.getMetaData();
        this.rs = dbMeta.getProcedureColumns(this.conn.getCatalog(), null, "sptestBug38367", null);
        while (this.rs.next()) {
            String columnName = this.rs.getString(4);
            Short columnNullable = new Short(this.rs.getShort(12));
            assertTrue("Parameter " + columnName + " is not java.sql.DatabaseMetaData.procedureNullable.",
                    columnNullable.intValue() == java.sql.DatabaseMetaData.procedureNullable);
        }
    } finally {
    }
}
 
Example 2
Project: ProyectoPacientes   File: MetaDataRegressionTest.java   View source code 6 votes vote down vote up
/**
 * Tests fix for BUG#8803, 'DATA_TYPE' column from
 * DBMD.getBestRowIdentifier() causes ArrayIndexOutOfBoundsException when
 * accessed (and in fact, didn't return any value).
 * 
 * @throws Exception
 *             if the test fails.
 */
public void testBug8803() throws Exception {
    String tableName = "testBug8803";
    createTable(tableName, "(field1 INT NOT NULL PRIMARY KEY)");
    DatabaseMetaData metadata = this.conn.getMetaData();
    try {
        this.rs = metadata.getBestRowIdentifier(this.conn.getCatalog(), null, tableName, DatabaseMetaData.bestRowNotPseudo, true);

        assertTrue(this.rs.next());

        this.rs.getInt("DATA_TYPE"); // **** Fails here *****
    } finally {
        if (this.rs != null) {
            this.rs.close();

            this.rs = null;
        }
    }

}
 
Example 3
Project: incubator-netbeans   File: SchemaTest.java   View source code 6 votes vote down vote up
public ResultSet getColumns(String catalog, String schemaPattern, String tableNamePattern, String columnNamePattern) {
    if (catalog == null) {
        if ("s1table1".equals(tableNamePattern)) {
            return JDBCStubUtil.columnsResultSet(
                    new String[] { "S1TABLE1_INTEGER_COL", "S1TABLE1_VARCHAR_COL", "S1TABLE1_FK_COL" },
                    new String[] { "INTEGER", "VARCAHR", "INTEGER" },
                    new int[] { Types.INTEGER, Types.VARCHAR, Types.INTEGER },
                    new int[] { 0, 20, 0 },
                    new int[] { 0, 0, 0 },
                    new int[] { DatabaseMetaData.columnNoNulls, DatabaseMetaData.columnNullable, DatabaseMetaData.columnNullable }
            );
            
        } else if ("s1table2".equals(tableNamePattern)) {
            return JDBCStubUtil.columnsResultSet(
                    new String[] { "S1TABLE2_INTEGER_COL" },
                    new String[] { "INTEGER" },
                    new int[] { Types.INTEGER },
                    new int[] { 0 },
                    new int[] { 0 },
                    new int[] { DatabaseMetaData.columnNoNulls }
            );
        }
    }
    return JDBCStubUtil.emptyResultSet();
}
 
Example 4
Project: OpenVertretung   File: MetaDataRegressionTest.java   View source code 6 votes vote down vote up
public void testQuotedGunk() throws Exception {
    createTable("testQuotedGunk", "(field1 int)");

    String quotedCatalog = "`" + this.conn.getCatalog() + "`";
    String unquotedCatalog = this.conn.getCatalog();

    DatabaseMetaData dbmd = this.conn.getMetaData();
    this.rs = dbmd.getTables(quotedCatalog, null, "testQuotedGunk", new String[] { "TABLE" });
    assertTrue(this.rs.next());
    this.rs = dbmd.getTables(unquotedCatalog, null, "testQuotedGunk", new String[] { "TABLE" });
    assertTrue(this.rs.next());
    this.rs = dbmd.getColumns(quotedCatalog, null, "testQuotedGunk", "field1");
    assertTrue(this.rs.next());
    this.rs = dbmd.getColumns(unquotedCatalog, null, "testQuotedGunk", "field1");
    assertTrue(this.rs.next());

}
 
Example 5
Project: the-vigilantes   File: MetadataTest.java   View source code 6 votes vote down vote up
/**
 * Tests the implementation of Information Schema for columns.
 */
public void testGetColumnsUsingInfoSchema() throws Exception {
    if (versionMeetsMinimum(5, 0, 7)) {
        createTable("t1", "(c1 char(1))");
        Properties props = new Properties();
        props.put("useInformationSchema", "true");
        Connection conn1 = null;
        try {
            conn1 = getConnectionWithProps(props);
            DatabaseMetaData metaData = conn1.getMetaData();
            this.rs = metaData.getColumns(null, null, "t1", null);
            this.rs.next();
            assertEquals("t1", this.rs.getString("TABLE_NAME"));
            assertEquals("c1", this.rs.getString("COLUMN_NAME"));
            assertEquals("CHAR", this.rs.getString("TYPE_NAME"));
            assertEquals("1", this.rs.getString("COLUMN_SIZE"));
        } finally {
            if (conn1 != null) {
                conn1.close();
            }
        }
    }
}
 
Example 6
Project: ProyectoPacientes   File: MetaDataRegressionTest.java   View source code 6 votes vote down vote up
/**
 * Tests whether or not unsigned columns are reported correctly in
 * DBMD.getColumns
 * 
 * @throws Exception
 */
public void testGetColumnsUnsigned() throws Exception {
    try {
        this.stmt.executeUpdate("DROP TABLE IF EXISTS testGetUnsignedCols");
        this.stmt.executeUpdate("CREATE TABLE testGetUnsignedCols (field1 BIGINT, field2 BIGINT UNSIGNED)");

        DatabaseMetaData dbmd = this.conn.getMetaData();

        this.rs = dbmd.getColumns(this.conn.getCatalog(), null, "testGetUnsignedCols", "%");

        assertTrue(this.rs.next());
        // This row doesn't have 'unsigned' attribute
        assertTrue(this.rs.next());
        assertTrue(this.rs.getString(6).toLowerCase().indexOf("unsigned") != -1);
    } finally {
        this.stmt.executeUpdate("DROP TABLE IF EXISTS testGetUnsignedCols");
    }
}
 
Example 7
Project: BibliotecaPS   File: MetaDataRegressionTest.java   View source code 6 votes vote down vote up
private void checkFunctionColumnTypeForBug68307(String testAgainst, DatabaseMetaData testDbMetaData) throws Exception {
    rs = testDbMetaData.getFunctionColumns(null, null, "testBug68307_%", "%");

    while (rs.next()) {
        String message = testAgainst + ", function <" + rs.getString("FUNCTION_NAME") + "." + rs.getString("COLUMN_NAME") + ">";
        if (rs.getString("COLUMN_NAME") == null || rs.getString("COLUMN_NAME").length() == 0) {
            assertEquals(message, DatabaseMetaData.functionReturn, rs.getShort("COLUMN_TYPE"));
        } else if (rs.getString("COLUMN_NAME").endsWith("_in")) {
            assertEquals(message, DatabaseMetaData.functionColumnIn, rs.getShort("COLUMN_TYPE"));
        } else if (rs.getString("COLUMN_NAME").endsWith("_inout")) {
            assertEquals(message, DatabaseMetaData.functionColumnInOut, rs.getShort("COLUMN_TYPE"));
        } else if (rs.getString("COLUMN_NAME").endsWith("_out")) {
            assertEquals(message, DatabaseMetaData.functionColumnOut, rs.getShort("COLUMN_TYPE"));
        } else {
            fail("Column '" + rs.getString("FUNCTION_NAME") + "." + rs.getString("COLUMN_NAME") + "' not expected within test case.");
        }
    }
}
 
Example 8
Project: kinetica-client-jdbc   File: JDBCSample.java   View source code 6 votes vote down vote up
/**
 * Retrieves a description of tables available for given connection.
 * 
 * @param conn
 *            The connection used to list the tables.
 * @throws SQLException
 *             if error happens while querying the data source.
 */
private static void showTables(Connection conn) throws SQLException {
	assert (conn != null);

	DatabaseMetaData meta = conn.getMetaData();

	ResultSet result = null;
	try {
		result = meta.getTables(null, null, null, null);
		printResultSet(result);
	} finally {
		if (result != null) {
			result.close();
		}
	}
}
 
Example 9
Project: OpenVertretung   File: MetaDataRegressionTest.java   View source code 6 votes vote down vote up
/**
 * Bug #43714 - useInformationSchema with DatabaseMetaData.getExportedKeys()
 * throws exception
 */
public void testBug43714() throws Exception {
    Connection c_IS = null;
    try {
        c_IS = getConnectionWithProps("useInformationSchema=true");
        DatabaseMetaData dbmd = c_IS.getMetaData();
        this.rs = dbmd.getExportedKeys("x", "y", "z");
    } finally {
        try {
            if (c_IS != null) {
                c_IS.close();
            }
        } catch (SQLException ex) {
        }
    }
}
 
Example 10
Project: BibliotecaPS   File: MetaDataRegressionTest.java   View source code 6 votes vote down vote up
/**
 * Tests fix for BUG#21215151 - DATABASEMETADATA.GETCATALOGS() FAILS TO SORT RESULTS.
 * 
 * DatabaseMetaData.GetCatalogs() relies on the results of 'SHOW DATABASES' which deliver a sorted list of databases except for 'information_schema' which
 * is always returned in the first position.
 * This test creates set of databases around the relative position of 'information_schema' and checks the ordering of the final ResultSet.
 * 
 * @throws Exception
 *             if the test fails.
 */
public void testBug21215151() throws Exception {
    createDatabase("z_testBug21215151");
    createDatabase("j_testBug21215151");
    createDatabase("h_testBug21215151");
    createDatabase("i_testBug21215151");
    createDatabase("a_testBug21215151");

    DatabaseMetaData dbmd = this.conn.getMetaData();
    this.rs = dbmd.getCatalogs();

    System.out.println("Catalogs:");
    System.out.println("--------------------------------------------------");
    while (this.rs.next()) {
        System.out.println("\t" + this.rs.getString(1));
    }
    this.rs.beforeFirst();

    // check the relative position of each element in the result set compared to the previous element.
    String previousDb = "";
    while (this.rs.next()) {
        assertTrue("'" + this.rs.getString(1) + "' is lexicographically lower than the previous catalog. Check the system output to see the catalogs list.",
                previousDb.compareTo(this.rs.getString(1)) < 0);
        previousDb = this.rs.getString(1);
    }
}
 
Example 11
Project: gmds   File: Utils.java   View source code 6 votes vote down vote up
/**
     *
     * @param dbmdJson
     * @param repo
     * @param tree
     * @param conn
     * @param clmnTree
     * @return
     * @throws IOException
     * @throws SQLException
     */
    public static ObjectId metaTreeCommit(ObjectJson dbmdJson, Repository repo, TreeFormatter tree, 
            Connection conn, Boolean clmnTree) throws IOException, SQLException {

        DatabaseMetaData dbmd = conn.getMetaData();
//        ObjectJson dbmdJson = new ObjectJson();
        String mapString = metaDbInfo(dbmd);
        ObjectInserter objectInserter = repo.newObjectInserter();
        ObjectId blobId = objectInserter.insert(Constants.OBJ_BLOB, mapString.getBytes());
        objectInserter.flush();

        tree.append(Consts.DATABASE, FileMode.REGULAR_FILE, blobId);
        Utils.putTableMeta(repo, conn, dbmd, objectInserter, tree, clmnTree);

        ObjectId treeId = objectInserter.insert(tree);
        objectInserter.flush();

        System.out.println("Tree ID: " + treeId.getName());

        return treeId;
    }
 
Example 12
Project: syndesis   File: SqlIconFileStore.java   View source code 6 votes vote down vote up
private boolean tableExists(Handle h, String tableName) {
    try {
        String tableToCheck = tableName;
        boolean caseSensitive = this.databaseKind == DatabaseKind.PostgreSQL;
        if (!caseSensitive) {
            tableToCheck = tableName.toUpperCase(Locale.ROOT);
        }
        DatabaseMetaData metaData = h.getConnection().getMetaData();

        try (ResultSet rs = metaData.getTables(null, null, tableToCheck, null)) {
            while (rs.next()) {
                String foundTable = rs.getString("TABLE_NAME");
                if (tableToCheck.equalsIgnoreCase(foundTable)) {
                    return true;
                }
            }
        }
        return false;
    } catch (SQLException ex) {
        throw IconDataAccessException.launderThrowable("Cannot check if the table " + tableName + " already exists", ex);
    }
}
 
Example 13
Project: org.mybatis.generator.core-1.3.5   File: DatabaseIntrospector.java   View source code 6 votes vote down vote up
/**
 * Instantiates a new database introspector.
 *
 * @param context
 *            the context
 * @param databaseMetaData
 *            the database meta data
 * @param javaTypeResolver
 *            the java type resolver
 * @param warnings
 *            the warnings
 */
public DatabaseIntrospector(Context context,
        DatabaseMetaData databaseMetaData,
        JavaTypeResolver javaTypeResolver, List<String> warnings) {
    super();
    this.context = context;
    this.databaseMetaData = databaseMetaData;
    this.javaTypeResolver = javaTypeResolver;
    this.warnings = warnings;
    logger = LogFactory.getLog(getClass());
    
    //获取数据库的版本信息
    try {
        DatabaseMetaData md = databaseMetaData.getConnection().getMetaData();
        databaseProductName = md.getDatabaseProductName().toUpperCase();
    } catch (SQLException se) {
        warnings.add("获取数据库版本失败:" + se.getMessage());
    }
}
 
Example 14
Project: OpenVertretung   File: MetadataTest.java   View source code 6 votes vote down vote up
/**
 * Tests the implementation of Information Schema for columns.
 */
public void testGetColumnsUsingInfoSchema() throws Exception {
    if (versionMeetsMinimum(5, 0, 7)) {
        createTable("t1", "(c1 char(1))");
        Properties props = new Properties();
        props.put("useInformationSchema", "true");
        Connection conn1 = null;
        try {
            conn1 = getConnectionWithProps(props);
            DatabaseMetaData metaData = conn1.getMetaData();
            this.rs = metaData.getColumns(null, null, "t1", null);
            this.rs.next();
            assertEquals("t1", this.rs.getString("TABLE_NAME"));
            assertEquals("c1", this.rs.getString("COLUMN_NAME"));
            assertEquals("CHAR", this.rs.getString("TYPE_NAME"));
            assertEquals("1", this.rs.getString("COLUMN_SIZE"));
        } finally {
            if (conn1 != null) {
                conn1.close();
            }
        }
    }
}
 
Example 15
Project: BibliotecaPS   File: MetadataTest.java   View source code 6 votes vote down vote up
/**
 * Tests the implementation of Information Schema for columns.
 */
public void testGetColumnsUsingInfoSchema() throws Exception {
    if (versionMeetsMinimum(5, 0, 7)) {
        createTable("t1", "(c1 char(1))");
        Properties props = new Properties();
        props.put("useInformationSchema", "true");
        Connection conn1 = null;
        try {
            conn1 = getConnectionWithProps(props);
            DatabaseMetaData metaData = conn1.getMetaData();
            this.rs = metaData.getColumns(null, null, "t1", null);
            this.rs.next();
            assertEquals("t1", this.rs.getString("TABLE_NAME"));
            assertEquals("c1", this.rs.getString("COLUMN_NAME"));
            assertEquals("CHAR", this.rs.getString("TYPE_NAME"));
            assertEquals("1", this.rs.getString("COLUMN_SIZE"));
        } finally {
            if (conn1 != null) {
                conn1.close();
            }
        }
    }
}
 
Example 16
Project: the-vigilantes   File: MetaDataRegressionTest.java   View source code 6 votes vote down vote up
/**
 * Tests fix for Bug#8812, DBMD.getIndexInfo() returning inverted values for
 * 'NON_UNIQUE' column.
 * 
 * @throws Exception
 *             if the test fails.
 */
public void testBug8812() throws Exception {
    String tableName = "testBug8812";

    try {
        createTable(tableName, "(field1 INT, field2 INT, INDEX(field1), UNIQUE INDEX(field2))");

        DatabaseMetaData dbmd = this.conn.getMetaData();
        this.rs = dbmd.getIndexInfo(this.conn.getCatalog(), null, tableName, true, false);
        assertTrue(this.rs.next()); // there should be one row that meets
        // this requirement
        assertEquals(this.rs.getBoolean("NON_UNIQUE"), false);

        this.rs = dbmd.getIndexInfo(this.conn.getCatalog(), null, tableName, false, false);
        assertTrue(this.rs.next()); // there should be two rows that meets
        // this requirement
        assertEquals(this.rs.getBoolean("NON_UNIQUE"), false);
        assertTrue(this.rs.next());
        assertEquals(this.rs.getBoolean("NON_UNIQUE"), true);

    } finally {
        dropTable(tableName);
    }
}
 
Example 17
Project: incubator-netbeans   File: DBTestBase.java   View source code 6 votes vote down vote up
protected final boolean columnInAnyIndex(String tablename, String colname)
        throws Exception {
    tablename = fixIdentifier(tablename);
    colname = fixIdentifier(colname);
    DatabaseMetaData md = getConnection().getMetaData();
    ResultSet rs = md.getIndexInfo(null, getSchema(), tablename, false, false);

    // printResults(rs, "columnInIndex(" + viewname + ", " + colname +
    //    ", " + indexname + ")");

    while ( rs.next() ) {
        String ixColName = rs.getString(9);
        if ( ixColName.equals(colname) ) {
            return true;
        }
    }

    return false;        
}
 
Example 18
Project: BibliotecaPS   File: PreparedStatement.java   View source code 6 votes vote down vote up
private void buildRewriteBatchedParams(String sql, MySQLConnection conn, DatabaseMetaData metadata, String encoding,
        SingleByteCharsetConverter converter) throws SQLException {
    this.valuesClause = extractValuesClause(sql, conn.getMetaData().getIdentifierQuoteString());
    String odkuClause = this.isOnDuplicateKeyUpdate ? sql.substring(this.locationOfOnDuplicateKeyUpdate) : null;

    String headSql = null;

    if (this.isOnDuplicateKeyUpdate) {
        headSql = sql.substring(0, this.locationOfOnDuplicateKeyUpdate);
    } else {
        headSql = sql;
    }

    this.batchHead = new ParseInfo(headSql, conn, metadata, encoding, converter, false);
    this.batchValues = new ParseInfo("," + this.valuesClause, conn, metadata, encoding, converter, false);
    this.batchODKUClause = null;

    if (odkuClause != null && odkuClause.length() > 0) {
        this.batchODKUClause = new ParseInfo("," + this.valuesClause + " " + odkuClause, conn, metadata, encoding, converter, false);
    }
}
 
Example 19
Project: lams   File: NativeJdbcExtractorAdapter.java   View source code 6 votes vote down vote up
/**
 * Check for a ConnectionProxy chain, then delegate to doGetNativeConnection.
 * <p>ConnectionProxy is used by Spring's TransactionAwareDataSourceProxy
 * and LazyConnectionDataSourceProxy. The target connection behind it is
 * typically one from a local connection pool, to be unwrapped by the
 * doGetNativeConnection implementation of a concrete subclass.
 * @see #doGetNativeConnection
 * @see org.springframework.jdbc.datasource.ConnectionProxy
 * @see org.springframework.jdbc.datasource.DataSourceUtils#getTargetConnection
 * @see org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy
 * @see org.springframework.jdbc.datasource.LazyConnectionDataSourceProxy
 */
@Override
public Connection getNativeConnection(Connection con) throws SQLException {
	if (con == null) {
		return null;
	}
	Connection targetCon = DataSourceUtils.getTargetConnection(con);
	Connection nativeCon = doGetNativeConnection(targetCon);
	if (nativeCon == targetCon) {
		// We haven't received a different Connection, so we'll assume that there's
		// some additional proxying going on. Let's check whether we get something
		// different back from the DatabaseMetaData.getConnection() call.
		DatabaseMetaData metaData = targetCon.getMetaData();
		// The following check is only really there for mock Connections
		// which might not carry a DatabaseMetaData instance.
		if (metaData != null) {
			Connection metaCon = metaData.getConnection();
			if (metaCon != null && metaCon != targetCon) {
				// We've received a different Connection there:
				// Let's retry the native extraction process with it.
				nativeCon = doGetNativeConnection(metaCon);
			}
		}
	}
	return nativeCon;
}
 
Example 20
Project: ChronoBike   File: SQLClauseSPSupport.java   View source code 6 votes vote down vote up
public SQLClauseSPParamsDesc getStoredProcedureParamsList(DbConnectionBase dbConnection, String csStoredProcName)
{
	SQLClauseSPParamsDesc spParamsDesc = new SQLClauseSPParamsDesc();
			
	try
	{
		DatabaseMetaData dmd = dbConnection.getDbConnection().getMetaData();
		if (csStoredProcName.indexOf(".") != -1) // suppress the user if exists in the procedure
			csStoredProcName = csStoredProcName.substring(csStoredProcName.indexOf(".") + 1); 
		ResultSet rsParams = dmd.getProcedureColumns(null, dbConnection.getEnvironmentPrefix(), csStoredProcName.replace("_", "\\_"), "%");
		boolean b = true;
		while(rsParams.next() && b)
		{
			spParamsDesc.addAParam(rsParams);
		}
	}
	catch (SQLException e)
	{			
		return null;
	}

	return spParamsDesc;
}
 
Example 21
Project: ProyectoPacientes   File: MetaDataRegressionTest.java   View source code 6 votes vote down vote up
public void testBug31187() throws Exception {
    createTable("testBug31187", "(field1 int)");

    Connection nullCatConn = getConnectionWithProps("nullCatalogMeansCurrent=false");
    DatabaseMetaData dbmd = nullCatConn.getMetaData();
    ResultSet dbTblCols = dbmd.getColumns(null, null, "testBug31187", "%");

    boolean found = false;

    while (dbTblCols.next()) {
        String catalog = dbTblCols.getString("TABLE_CAT");
        String table = dbTblCols.getString("TABLE_NAME");
        boolean useLowerCaseTableNames = dbmd.storesLowerCaseIdentifiers();

        if (catalog.equals(nullCatConn.getCatalog())
                && (((useLowerCaseTableNames && "testBug31187".equalsIgnoreCase(table)) || "testBug31187".equals(table)))) {
            found = true;
        }
    }

    assertTrue("Didn't find any columns for table named 'testBug31187' in database " + this.conn.getCatalog(), found);
}
 
Example 22
Project: bdf2   File: EntityPR.java   View source code 6 votes vote down vote up
private String getColumnRemarks(String tableName,String columnName,DatabaseMetaData databaseMetaData) throws SQLException{
	String remarks=null;
	ResultSet rs=null;
	try{
		rs=databaseMetaData.getColumns(null, null, tableName,"%");
		while(rs.next()){
			String colName=rs.getString("COLUMN_NAME");
			if(columnName.equals(colName)){
				remarks=rs.getString("REMARKS");
				break;
			}
		}
	}finally{
		if(rs!=null)rs.close();
	}
	return remarks;
}
 
Example 23
Project: ProyectoPacientes   File: MetaDataRegressionTest.java   View source code 6 votes vote down vote up
private void checkMetadataForBug22613(Connection c) throws Exception {
    String maxValue = "a,bc,def,ghij";
    String maxValue2 = "1,2,3,4,1585,ONE,TWO,Y,N,THREE";

    DatabaseMetaData meta = c.getMetaData();
    this.rs = meta.getColumns(null, this.conn.getCatalog(), "bug22613", "s");
    this.rs.first();

    assertEquals(maxValue.length(), this.rs.getInt("COLUMN_SIZE"));

    this.rs = meta.getColumns(null, this.conn.getCatalog(), "bug22613", "s2");
    this.rs.first();

    assertEquals(maxValue2.length(), this.rs.getInt("COLUMN_SIZE"));

    this.rs = meta.getColumns(null, c.getCatalog(), "bug22613", "t");
    this.rs.first();

    assertEquals(4, this.rs.getInt("COLUMN_SIZE"));
}
 
Example 24
Project: calcite-avatica   File: MetaResultSetTest.java   View source code 6 votes vote down vote up
@Test public void testGetColumnPrivileges() throws SQLException {
  DatabaseMetaData metadata = getDatabaseMetadata();
  try (ResultSet rs = metadata.getColumnPrivileges(null, null, null, null)) {
    ResultSetMetaData rsMeta = rs.getMetaData();

    assertEquals(8, rsMeta.getColumnCount());
    assertColumn(rsMeta, 1, "TABLE_CAT", Types.VARCHAR, DatabaseMetaData.columnNullable);
    assertColumn(rsMeta, 2, "TABLE_SCHEM", Types.VARCHAR, DatabaseMetaData.columnNullable);
    assertColumn(rsMeta, 3, "TABLE_NAME", Types.VARCHAR, DatabaseMetaData.columnNoNulls);
    assertColumn(rsMeta, 4, "COLUMN_NAME", Types.VARCHAR, DatabaseMetaData.columnNoNulls);
    assertColumn(rsMeta, 5, "GRANTOR", Types.VARCHAR, DatabaseMetaData.columnNullable);
    assertColumn(rsMeta, 6, "GRANTEE", Types.VARCHAR, DatabaseMetaData.columnNoNulls);
    assertColumn(rsMeta, 7, "PRIVILEGE", Types.VARCHAR, DatabaseMetaData.columnNoNulls);
    assertColumn(rsMeta, 8, "IS_GRANTABLE", Types.VARCHAR, DatabaseMetaData.columnNullable);
  }
}
 
Example 25
Project: QDrill   File: Drill2489CallsAfterCloseThrowExceptionsTest.java   View source code 6 votes vote down vote up
@BeforeClass
public static void setUpConnection() throws Exception {
  // (Note: Can't use JdbcTest's connect(...) for this test class.)
  final Connection connection =
      new Driver().connect( "jdbc:drill:zk=local", JdbcAssert.getDefaultProperties() );
  final Statement stmt = connection.createStatement();
  final ResultSet result =
      stmt.executeQuery( "SELECT * FROM INFORMATION_SCHEMA.CATALOGS" );
  result.next();
  final DatabaseMetaData dbmd = connection.getMetaData();

  result.close();
  closedResultSet = result;
  stmt.close();
  closedStatement = stmt;
  connection.close();
  closedConnection = connection;
  closedDatabaseMetaData = dbmd;
}
 
Example 26
Project: BibliotecaPS   File: MetaDataRegressionTest.java   View source code 5 votes vote down vote up
public void testBug44508() throws Exception {
    DatabaseMetaData dbmd = this.conn.getMetaData();

    this.rs = dbmd.getSuperTypes("", "", "");
    ResultSetMetaData rsmd = this.rs.getMetaData();

    assertEquals("TYPE_CAT", rsmd.getColumnName(1)); // Gives TABLE_CAT
    assertEquals("TYPE_SCHEM", rsmd.getColumnName(2)); // Gives TABLE_SCHEM
}
 
Example 27
Project: OpenVertretung   File: MetadataTest.java   View source code 5 votes vote down vote up
/**
 * Tests the implementation of Information Schema for tables.
 */
public void testGetTablesUsingInfoSchema() throws Exception {
    if (versionMeetsMinimum(5, 0, 7)) {
        createTable("`t1-1`", "(c1 char(1))");
        createTable("`t1-2`", "(c1 char(1))");
        createTable("`t2`", "(c1 char(1))");
        Set<String> tableNames = new HashSet<String>();
        tableNames.add("t1-1");
        tableNames.add("t1-2");
        Properties props = new Properties();
        props.put("useInformationSchema", "true");
        Connection conn1 = null;
        try {
            conn1 = getConnectionWithProps(props);
            DatabaseMetaData metaData = conn1.getMetaData();
            // pattern matching for table name
            this.rs = metaData.getTables(null, null, "t1-_", null);
            while (this.rs.next()) {
                assertTrue(tableNames.remove(this.rs.getString("TABLE_NAME")));
            }
            assertTrue(tableNames.isEmpty());
        } finally {
            if (conn1 != null) {
                conn1.close();
            }
        }
    }
}
 
Example 28
Project: BibliotecaPS   File: MetaDataRegressionTest.java   View source code 5 votes vote down vote up
/**
 * Test fix for BUG#68098 - DatabaseMetaData.getIndexInfo sorts results incorrectly.
 * 
 * @throws Exception
 *             if the test fails.
 */
public void testBug68098() throws Exception {
    String[] testStepDescription = new String[] { "MySQL MetaData", "I__S MetaData" };
    Connection connUseIS = getConnectionWithProps("useInformationSchema=true");
    Connection[] testConnections = new Connection[] { this.conn, connUseIS };
    String[] expectedIndexesOrder = new String[] { "index_1", "index_1", "index_3", "PRIMARY", "index_2", "index_2", "index_4" };

    this.stmt.execute("DROP TABLE IF EXISTS testBug68098");

    createTable("testBug68098", "(column_1 INT NOT NULL, column_2 INT NOT NULL, column_3 INT NOT NULL, PRIMARY KEY (column_1))");

    this.stmt.execute("CREATE INDEX index_4 ON testBug68098 (column_2)");
    this.stmt.execute("CREATE UNIQUE INDEX index_3 ON testBug68098 (column_3)");
    this.stmt.execute("CREATE INDEX index_2 ON testBug68098 (column_2, column_1)");
    this.stmt.execute("CREATE UNIQUE INDEX index_1 ON testBug68098 (column_3, column_2)");

    for (int i = 0; i < testStepDescription.length; i++) {
        DatabaseMetaData testDbMetaData = testConnections[i].getMetaData();
        this.rs = testDbMetaData.getIndexInfo(null, null, "testBug68098", false, false);
        int ind = 0;
        while (this.rs.next()) {
            assertEquals(testStepDescription[i] + ", sort order is wrong", expectedIndexesOrder[ind++], this.rs.getString("INDEX_NAME"));
        }
        this.rs.close();
    }

    connUseIS.close();
}
 
Example 29
Project: aries-jpa   File: DummyDataSource.java   View source code 5 votes vote down vote up
private Object proxyClasses(ClassLoader classLoader, Class<?> type) {
    if (type == DatabaseMetaData.class) {
        return createProxy(classLoader, DatabaseMetaData.class);
    }
    if (type == ResultSet.class) {
        return createProxy(classLoader, ResultSet.class);
    }
    if (type == Statement.class) {
        return createProxy(classLoader, PreparedStatement.class);
    }
    return null;
}
 
Example 30
Project: syndesis   File: DatabaseMetaDataHelper.java   View source code 5 votes vote down vote up
static List<SqlParam> getJDBCInfoByColumnOrder(final DatabaseMetaData meta, String catalog, 
        String schema, String tableName, final List<SqlParam> params) throws SQLException {
    List<SqlParam> paramList = new ArrayList<>();
    ResultSet columnSet = meta.getColumns(catalog, "SA", tableName, null);
    for (int i=0; i<params.size(); i++) {
        columnSet.next();
        SqlParam param = params.get(i);
        param.setColumn(columnSet.getString("COLUMN_NAME"));
        param.setJdbcType(JDBCType.valueOf(columnSet.getInt("DATA_TYPE")));
        paramList.add(param);
    }
    return paramList;
}
 
Example 31
Project: holon-datastore-jdbc   File: JdbcDatastoreUtils.java   View source code 5 votes vote down vote up
/**
 * Get the primary key {@link Path}s of given <code>table</code> using database metadata, if available.
 * @param dialect Jdbc dialect
 * @param table Table name for which to obtain th primary key
 * @param connection Connection to use
 * @return The table primary key {@link Path}s, empty if not available
 * @throws SQLException Error accessing the database
 */
public static Optional<Path<?>[]> getPrimaryKey(JdbcDialect dialect, String table, Connection connection)
		throws SQLException {
	ObjectUtils.argumentNotNull(table, "Table name must be not null");
	ObjectUtils.argumentNotNull(connection, "Connection name must be not null");

	final String tableName = dialect.getTableName(table);

	List<OrderedPath> paths = new ArrayList<>();

	DatabaseMetaData databaseMetaData = connection.getMetaData();

	try (ResultSet resultSet = databaseMetaData.getPrimaryKeys(null, null, tableName)) {
		while (resultSet.next()) {
			final String columnName = resultSet.getString("COLUMN_NAME");
			OrderedPath op = new OrderedPath();
			op.path = Path.of(columnName, getColumnType(databaseMetaData, tableName, columnName));
			op.sequence = resultSet.getShort("KEY_SEQ");
			paths.add(op);
		}
	}

	if (!paths.isEmpty()) {
		Collections.sort(paths);
		return Optional
				.of(paths.stream().map(p -> p.path).collect(Collectors.toList()).toArray(new Path[paths.size()]));
	}

	return Optional.empty();
}
 
Example 32
Project: holon-datastore-jdbc   File: MySQLDialect.java   View source code 5 votes vote down vote up
@Override
public void init(JdbcDatastore datastore) throws SQLException {
	datastore.withConnection(c -> {
		DatabaseMetaData databaseMetaData = c.getMetaData();
		supportsGeneratedKeys = databaseMetaData.supportsGetGeneratedKeys();
		generatedKeyAlwaysReturned = databaseMetaData.generatedKeyAlwaysReturned();
		supportsLikeEscapeClause = databaseMetaData.supportsLikeEscapeClause();
		return null;
	});
}
 
Example 33
Project: elastic-job-cloud   File: JobEventRdbStorage.java   View source code 5 votes vote down vote up
private void createJobExecutionTableAndIndexIfNeeded(final Connection conn) throws SQLException {
    DatabaseMetaData dbMetaData = conn.getMetaData();
    try (ResultSet resultSet = dbMetaData.getTables(null, null, TABLE_JOB_EXECUTION_LOG, new String[]{"TABLE"})) {
        if (!resultSet.next()) {
            createJobExecutionTable(conn);
        }
    }
}
 
Example 34
Project: incubator-netbeans   File: JDBCUtils.java   View source code 5 votes vote down vote up
public static Nullable getColumnNullable(int dbmdColumnNullable) {
    switch (dbmdColumnNullable) {
        case DatabaseMetaData.columnNoNulls:
            return Nullable.NOT_NULLABLE;
        case DatabaseMetaData.columnNullable:
            return Nullable.NULLABLE;
        case DatabaseMetaData.columnNullableUnknown:
        default:
            return Nullable.UNKNOWN;
    }
}
 
Example 35
Project: linkifier   File: Table.java   View source code 5 votes vote down vote up
public void getUniqueConstraint(DatabaseMetaData metaData, String databaseName, String schemaName, String tableName) throws SQLException {
	try (ResultSet result = metaData.getIndexInfo(databaseName, schemaName, tableName, true, true)) {
		while (result.next()) {
			for (Column col : columnList) {
				if (col.getName().equals(result.getString(9))) {
					col.setUniqueConstraint(true);
				}
			}
		}
	}
}
 
Example 36
Project: incubator-netbeans   File: OracleSchema.java   View source code 5 votes vote down vote up
@Override
protected void createTables() {
    LOGGER.log(Level.FINE, "Initializing tables in {0}", this);
    Map<String, Table> newTables = new LinkedHashMap<String, Table>();
    try {
        DatabaseMetaData dmd = jdbcCatalog.getJDBCMetadata().getDmd();
        Set<String> recycleBinTables = getRecycleBinObjects(dmd, "TABLE"); // NOI18N
        ResultSet rs = dmd.getTables(jdbcCatalog.getName(), name, "%", new String[]{"TABLE"}); // NOI18N
        if (rs != null) {
            try {
                while (rs.next()) {
                    String type = MetadataUtilities.trimmed(rs.getString("TABLE_TYPE")); //NOI18N
                    String tableName = rs.getString("TABLE_NAME"); // NOI18N
                    if (!recycleBinTables.contains(tableName)) {
                        Table table = createJDBCTable(tableName, type.contains("SYSTEM")).getTable(); //NOI18N
                        newTables.put(tableName, table);
                        LOGGER.log(Level.FINE, "Created table {0}", table);
                    } else {
                        LOGGER.log(Level.FINE, "Ignoring recycle bin table ''{0}''", tableName);
                    }
                }
            } finally {
                rs.close();
            }
        }
    } catch (SQLException e) {
        throw new MetadataException(e);
    }
    tables = Collections.unmodifiableMap(newTables);
}
 
Example 37
Project: vertx-generator   File: DBUtil.java   View source code 5 votes vote down vote up
/**
 * 获得主键名称
 * 
 * @param config
 * @param tableName
 * @return
 * @throws Exception
 */
public static String getTablePrimaryKey(DatabaseConfig config, String tableName) throws Exception {
	Connection conn = getConnection(config);
	DatabaseMetaData md = conn.getMetaData();
	ResultSet rs = md.getPrimaryKeys(null, null, tableName);
	while (rs.next()) {
		return rs.getString("COLUMN_NAME");
	}
	return null;
}
 
Example 38
Project: the-vigilantes   File: MetaDataRegressionTest.java   View source code 5 votes vote down vote up
public void testBug44508() throws Exception {
    DatabaseMetaData dbmd = this.conn.getMetaData();

    this.rs = dbmd.getSuperTypes("", "", "");
    ResultSetMetaData rsmd = this.rs.getMetaData();

    assertEquals("TYPE_CAT", rsmd.getColumnName(1)); // Gives TABLE_CAT
    assertEquals("TYPE_SCHEM", rsmd.getColumnName(2)); // Gives TABLE_SCHEM
}
 
Example 39
Project: the-vigilantes   File: MetaDataRegressionTest.java   View source code 5 votes vote down vote up
/**
 * Tests fix for BUG#68307 - getFunctionColumns() returns incorrect "COLUMN_TYPE" information. This JDBC4
 * feature required some changes in method getProcedureColumns().
 * 
 * @throws Exception
 *             if the test fails.
 */
public void testBug68307() throws Exception {
    String[] testStepDescription = new String[] { "MySQL MetaData", "I__S MetaData" };
    Connection connUseIS = getConnectionWithProps("useInformationSchema=true");
    Connection[] testConnections = new Connection[] { this.conn, connUseIS };

    createFunction("testBug68307_func", "(func_param_in INT) RETURNS INT DETERMINISTIC RETURN 1");

    createProcedure("testBug68307_proc", "(IN proc_param_in INT, OUT proc_param_out INT, INOUT proc_param_inout INT) SELECT 1");

    for (int i = 0; i < testStepDescription.length; i++) {
        DatabaseMetaData testDbMetaData = testConnections[i].getMetaData();
        this.rs = testDbMetaData.getProcedureColumns(null, null, "testBug68307_%", "%");

        while (this.rs.next()) {
            String message = testStepDescription[i] + ", procedure/function <" + this.rs.getString("PROCEDURE_NAME") + "."
                    + this.rs.getString("COLUMN_NAME") + ">";
            if (this.rs.getString("COLUMN_NAME") == null || this.rs.getString("COLUMN_NAME").length() == 0) {
                assertEquals(message, DatabaseMetaData.procedureColumnReturn, this.rs.getShort("COLUMN_TYPE"));
            } else if (this.rs.getString("COLUMN_NAME").endsWith("_in")) {
                assertEquals(message, DatabaseMetaData.procedureColumnIn, this.rs.getShort("COLUMN_TYPE"));
            } else if (this.rs.getString("COLUMN_NAME").endsWith("_inout")) {
                assertEquals(message, DatabaseMetaData.procedureColumnInOut, this.rs.getShort("COLUMN_TYPE"));
            } else if (this.rs.getString("COLUMN_NAME").endsWith("_out")) {
                assertEquals(message, DatabaseMetaData.procedureColumnOut, this.rs.getShort("COLUMN_TYPE"));
            } else {
                fail(testStepDescription[i] + ", column '" + this.rs.getString("FUNCTION_NAME") + "." + this.rs.getString("COLUMN_NAME")
                        + "' not expected within test case.");
            }
        }

        this.rs.close();
    }
}
 
Example 40
Project: the-vigilantes   File: MetaDataRegressionTest.java   View source code 5 votes vote down vote up
private void checkMetaDataInfoForBug17248345(Connection testConn) throws Exception {
    DatabaseMetaData testDbMetaData = testConn.getMetaData();
    ResultSet rsMD;
    boolean useInfoSchema = ((ConnectionProperties) testConn).getUseInformationSchema();
    boolean getProcRetFunc = ((ConnectionProperties) testConn).getGetProceduresReturnsFunctions();
    String stepDescription = "Prop. useInfoSchema(" + (useInfoSchema ? 1 : 0) + ") + getProcRetFunc(" + (getProcRetFunc ? 1 : 0) + "):";
    String sd;

    // getProcedures() must return 2 records, even if getProceduresReturnsFunctions is false once this flag only
    // applies to JDBC4. When exists a procedure and a function with same name, function is returned first.
    sd = stepDescription + " getProcedures() ";
    rsMD = testDbMetaData.getProcedures(null, null, "testBug17248345");
    assertTrue(sd + "1st of 2 rows expected.", rsMD.next());
    assertEquals(sd + " -> PROCEDURE_NAME", "testBug17248345", rsMD.getString("PROCEDURE_NAME"));
    assertTrue(sd + "2nd of 2 rows expected.", rsMD.next());
    assertEquals(sd + " -> PROCEDURE_NAME", "testBug17248345", rsMD.getString("PROCEDURE_NAME"));
    assertFalse(sd + "no more rows expected.", rsMD.next());

    // getProcedureColumns() must return 3 records, even if getProceduresReturnsFunctions is false once this flag
    // only applies to JDBC4. When exists a procedure and a function with same name, function is returned first.
    sd = stepDescription + " getProcedureColumns() ";
    rsMD = testDbMetaData.getProcedureColumns(null, null, "testBug17248345", "%");
    assertTrue(sd + "1st of 3 rows expected.", rsMD.next());
    assertEquals(sd + " -> PROCEDURE_NAME", "testBug17248345", rsMD.getString("PROCEDURE_NAME"));
    assertEquals(sd + " -> COLUMN_NAME", "", rsMD.getString("COLUMN_NAME"));
    assertTrue(sd + "2nd of 3 rows expected.", rsMD.next());
    assertEquals(sd + " -> PROCEDURE_NAME", "testBug17248345", rsMD.getString("PROCEDURE_NAME"));
    assertEquals(sd + " -> COLUMN_NAME", "funccol", rsMD.getString("COLUMN_NAME"));
    assertTrue(sd + "3rd of 3 rows expected.", rsMD.next());
    assertEquals(sd + " -> PROCEDURE_NAME", "testBug17248345", rsMD.getString("PROCEDURE_NAME"));
    assertEquals(sd + " -> COLUMN_NAME", "proccol", rsMD.getString("COLUMN_NAME"));
    assertFalse(sd + "no more rows expected.", rsMD.next());
}