Example usage for java.sql DatabaseMetaData getTables

List of usage examples for java.sql DatabaseMetaData getTables

Introduction

In this page you can find the example usage for java.sql DatabaseMetaData getTables.

Prototype

ResultSet getTables(String catalog, String schemaPattern, String tableNamePattern, String types[])
        throws SQLException;

Source Link

Document

Retrieves a description of the tables available in the given catalog.

Usage

From source file:org.apache.jackrabbit.core.fs.db.OracleFileSystem.java

/**
 * {@inheritDoc}//from w  ww .  ja v a2 s.  com
 * <p/>
 * Overridden in order to support multiple oracle schemas. Note that
 * schema names in Oracle correspond to the username of the connection.
 * See http://issues.apache.org/jira/browse/JCR-582
 *
 * @throws Exception if an error occurs
 */
protected void checkSchema() throws Exception {
    DatabaseMetaData metaData = con.getMetaData();
    String tableName = schemaObjectPrefix + "FSENTRY";
    if (metaData.storesLowerCaseIdentifiers()) {
        tableName = tableName.toLowerCase();
    } else if (metaData.storesUpperCaseIdentifiers()) {
        tableName = tableName.toUpperCase();
    }
    String userName = metaData.getUserName();

    ResultSet rs = metaData.getTables(null, userName, tableName, null);
    boolean schemaExists;
    try {
        schemaExists = rs.next();
    } finally {
        rs.close();
    }

    if (!schemaExists) {
        // read ddl from resources
        InputStream in = OracleFileSystem.class.getResourceAsStream(schema + ".ddl");
        if (in == null) {
            String msg = "Configuration error: unknown schema '" + schema + "'";
            log.debug(msg);
            throw new RepositoryException(msg);
        }
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        Statement stmt = con.createStatement();
        try {
            String sql = reader.readLine();
            while (sql != null) {
                // Skip comments and empty lines
                if (!sql.startsWith("#") && sql.length() > 0) {
                    // replace prefix variable
                    sql = Text.replace(sql, SCHEMA_OBJECT_PREFIX_VARIABLE, schemaObjectPrefix);

                    // set the tablespace if it is defined
                    String tspace;
                    if (tableSpace == null || "".equals(tableSpace)) {
                        tspace = "";
                    } else {
                        tspace = "tablespace " + tableSpace;
                    }
                    sql = Text.replace(sql, TABLE_SPACE_VARIABLE, tspace).trim();

                    // execute sql stmt
                    stmt.executeUpdate(sql);
                }
                // read next sql stmt
                sql = reader.readLine();
            }
        } finally {
            IOUtils.closeQuietly(in);
            closeStatement(stmt);
        }
    }
}

From source file:org.nuxeo.ecm.directory.sql.SQLHelper.java

private boolean tableExists() throws DirectoryException {
    try {//from w ww  .  j  a  va 2 s. c  om
        // Check if table exists using metadata
        DatabaseMetaData metaData = connection.getMetaData();
        String schemaName = null;
        String productName = metaData.getDatabaseProductName();
        if ("Oracle".equals(productName)) {
            Statement st = connection.createStatement();
            String sql = "SELECT SYS_CONTEXT('USERENV', 'SESSION_USER') FROM DUAL";
            log.trace("SQL: " + sql);
            ResultSet rs = st.executeQuery(sql);
            rs.next();
            schemaName = rs.getString(1);
            log.trace("checking existing tables for oracle database, schema: " + schemaName);
            rs.close();
            st.close();
        }
        ResultSet rs = metaData.getTables(null, schemaName, table.getPhysicalName(), new String[] { "TABLE" });
        boolean exists = rs.next();
        rs.close();
        log.debug(String.format("checking if table %s exists: %s", table.getPhysicalName(),
                Boolean.valueOf(exists)));
        return exists;
    } catch (SQLException e) {
        throw new DirectoryException(e);
    }
}

From source file:org.apache.phoenix.query.BaseTest.java

private static void deletePriorTables(long ts, String tenantId, String url) throws Exception {
    Properties props = new Properties();
    props.put(QueryServices.QUEUE_SIZE_ATTRIB, Integer.toString(1024));
    if (ts != HConstants.LATEST_TIMESTAMP) {
        props.setProperty(CURRENT_SCN_ATTRIB, Long.toString(ts));
    }// w  w w . j a  v  a 2  s .  c o  m
    Connection conn = DriverManager.getConnection(url, props);
    try {
        deletePriorTables(ts, conn, url);
        deletePriorSequences(ts, conn);

        // Make sure all tables and views have been dropped
        props.remove(CURRENT_SCN_ATTRIB);
        try (Connection seeLatestConn = DriverManager.getConnection(url, props)) {
            DatabaseMetaData dbmd = seeLatestConn.getMetaData();
            ResultSet rs = dbmd.getTables(null, null, null,
                    new String[] { PTableType.VIEW.toString(), PTableType.TABLE.toString() });
            boolean hasTables = rs.next();
            if (hasTables) {
                fail("The following tables are not deleted that should be:" + getTableNames(rs));
            }
        }
    } finally {
        conn.close();
    }
}

From source file:org.wso2.carbon.apimgt.impl.dao.CertificateMgtDAO.java

/**
 * Checks whether the certificate management table exists in the data base.
 *
 * @return : True if exists, false otherwise.
 *///from  w  w w. j  a  v a2 s  . c  o  m
public boolean isTableExists() throws CertificateManagementException {

    boolean isExists = false;
    Connection connection = null;
    ResultSet resultSet = null;
    DatabaseMetaData databaseMetaData;

    try {
        connection = APIMgtDBUtil.getConnection();
        databaseMetaData = connection.getMetaData();

        resultSet = databaseMetaData.getTables(null, null, CERTIFICATE_TABLE_NAME, null);
        if (resultSet.next()) {
            isExists = true;
        }
    } catch (SQLException e) {
        if (log.isDebugEnabled()) {
            log.debug("Error while retrieving database information. ", e);
        }
        handleException("Error retrieving Database information", e);
    } finally {
        APIMgtDBUtil.closeAllConnections(null, connection, resultSet);
    }
    return isExists;
}

From source file:com.sqewd.open.dal.core.persistence.db.AbstractDbPersister.java

protected boolean checkSchema() throws Exception {
    Connection conn = getConnection(true);
    boolean found = false;
    try {/*w  w  w.j  a v a 2 s. co  m*/
        DatabaseMetaData dbm = conn.getMetaData();
        Entity entity = DBVersion.class.getAnnotation(Entity.class);
        String table = entity.recordset();

        ResultSet rs = dbm.getTables(null, null, table, new String[] { "TABLE" });
        while (rs.next()) {
            found = true;
            break;
        }
        rs.close();

    } finally {
        if (conn != null) {
            releaseConnection(conn);
        }
    }
    return found;
}

From source file:com.qualogy.qafe.business.resource.rdb.query.enhancer.SQLQueryEnhancer.java

public Query enhance(Query query, DatabaseMetaData databaseMetaData) throws EnhancementFailedException {
    SQLQuery sqlQuery = (SQLQuery) query;

    ResultSet resultSet = null;//ww w .j  a va2 s  .  c  om

    try {
        if (StringUtils.isBlank(sqlQuery.getSqlAsAttribute()) && StringUtils.isBlank(sqlQuery.getSqlAsText())
                && StringUtils.isNotBlank(sqlQuery.getTable())) {
            // The Oracle database stores its table names as Upper-Case,
            // if you pass a table name in lowercase characters, it will not work.
            // MySQL database does not care if table name is uppercase/lowercase.
            //
            // TODO:check if there is a way to catch table data
            // TODO: dialect needed for upper/lowercase
            String userName = databaseMetaData.getUserName();
            resultSet = databaseMetaData.getTables(null, null, sqlQuery.getTable().toUpperCase(), null);

            String tableSchema = null;

            // Knowing schema name is not necessary but we gain performance
            // by using it during retrieving meta data.
            while (resultSet.next() && (null != userName)) {
                // some vendors like MySQL do not provide schema name
                // that's why we have to check whether the schema name is "null"
                if ((null != resultSet.getString("TABLE_SCHEM"))
                        && resultSet.getString("TABLE_SCHEM").equals(userName)) {
                    tableSchema = userName;

                    break;
                }

                // TABLE_TYPE
            }

            try {
                sqlQuery.getMetaData().setSupportsGetGeneratedKeys(databaseMetaData.supportsGetGeneratedKeys());
            } catch (AbstractMethodError e) {
                LOG.log(Level.WARNING,
                        "On the database driver there is no support for Metadata reading (sqlquery: "
                                + sqlQuery.getId() + ")",
                        e);
            }

            // if you pass null values for the first two parameters, then
            // it might take too long to return the result.
            resultSet = databaseMetaData.getPrimaryKeys(null, tableSchema, sqlQuery.getTable().toUpperCase());

            while (resultSet.next()) {
                sqlQuery.getMetaData().addPrimaryKey(resultSet.getString("COLUMN_NAME"));
            }

            // if no primarykeys found on a table, an update statement cannot be generated
            // so the query will be marked as error containing.
            sqlQuery.validate();
        }
    } catch (SQLException e) {
        throw new EnhancementFailedException(e);
    } finally {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                throw new EnhancementFailedException(e);
            }
        }
    }

    return sqlQuery;
}

From source file:io.github.retz.db.Database.java

private boolean tableExists(DatabaseMetaData meta, String schemaPattern, String tableName) throws SQLException {
    try (ResultSet res = meta.getTables(null, Objects.requireNonNull(schemaPattern),
            Objects.requireNonNull(tableName), null)) {

        if (res.next()) {
            String name = res.getString("TABLE_NAME");
            LOG.info("category={}, schema={}, name={}, type={}, remarks={}", res.getString("TABLE_CAT"),
                    res.getString("TABLE_SCHEM"), res.getString("TABLE_NAME"), res.getString("TABLE_TYPE"),
                    res.getString("REMARKS"));
            if (name != null) {
                return name.equals(tableName);
            }//from   ww  w  .  j  ava  2s.c  om
        }
    }
    return false;
}

From source file:org.apache.gora.sql.store.SqlStore.java

@Override
public boolean schemaExists() throws IOException {
    ResultSet resultSet = null;//w ww.j  a  va  2 s .c  o  m
    try {
        DatabaseMetaData metadata = connection.getMetaData();
        String tableName = mapping.getTableName();

        resultSet = metadata.getTables(null, null, tableName, null);

        if (resultSet.next())
            return true;

    } catch (Exception ex) {
        throw new IOException(ex);
    } finally {
        SqlUtils.close(resultSet);
    }

    return false;
}

From source file:org.talend.core.model.metadata.builder.database.manager.dbs.ImpalaExtractManager.java

protected ResultSet getResultSetFromTableInfo(TableInfoParameters tableInfo, String namePattern,
        IMetadataConnection iMetadataConnection, String schema)
        throws SQLException, ClassNotFoundException, InstantiationException, IllegalAccessException {
    String tableNamePattern = "".equals(namePattern) ? null : namePattern; //$NON-NLS-1$
    String[] types = new String[tableInfo.getTypes().size()];
    for (int i = 0; i < types.length; i++) {
        final String selectedTypeName = tableInfo.getTypes().get(i).getName();
        types[i] = selectedTypeName;/*  ww  w  .  ja va  2 s  .co m*/
    }
    DatabaseMetaData dbMetaData = ImpalaConnectionManager.getInstance().createConnection(iMetadataConnection)
            .getMetaData();

    // rsTables = dbMetaData.getTables(null, ExtractMetaDataUtils.schema, tableNamePattern, types);
    ResultSet rsTableTypes = null;
    rsTableTypes = dbMetaData.getTableTypes();
    Set<String> availableTableTypes = new HashSet<String>();
    String[] neededTableTypes = { ETableTypes.TABLETYPE_TABLE.getName(), ETableTypes.TABLETYPE_VIEW.getName(),
            ETableTypes.TABLETYPE_SYNONYM.getName() };
    while (rsTableTypes.next()) {
        String currentTableType = StringUtils.trimToEmpty(rsTableTypes.getString(ExtractManager.TABLE_TYPE));
        if (ArrayUtils.contains(neededTableTypes, currentTableType)) {
            availableTableTypes.add(currentTableType);
        }
    }
    rsTableTypes.close();
    ResultSet rsTables = dbMetaData.getTables(null, schema, tableNamePattern, types);
    return rsTables;

}

From source file:com.chiorichan.database.DatabaseEngine.java

public boolean tableExist(String table) {
    try {// w  w  w  .  j a  v  a 2  s  .  c  om
        DatabaseMetaData md = con.getMetaData();
        ResultSet rs = md.getTables(null, null, "%", null);
        while (rs.next()) {
            if (rs.getString(3).equalsIgnoreCase(table))
                return true;
        }
    } catch (CommunicationsException e) {
        // Retry
        return tableExist(table);
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return false;
}