Example usage for java.sql DatabaseMetaData getSchemas

List of usage examples for java.sql DatabaseMetaData getSchemas

Introduction

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

Prototype

ResultSet getSchemas() throws SQLException;

Source Link

Document

Retrieves the schema names available in this database.

Usage

From source file:org.talend.core.model.metadata.DBConnectionFillerImplTest.java

/**
     * Test filling catalogs for odbc teredata .
     * {@link org.talend.metadata.managment.model.DBConnectionFillerImpl#fillCatalogs(Connection, DatabaseMetaData, IMetadataConnection, List)
     * @throws SQLException//from   w  w  w. ja v  a  2s  .  c  o m
     */
@Test
public void testFillCatalogs_AS400() throws SQLException {
    // mock ReturnCode sql.Connection
    java.sql.Connection mockSqlConn = Mockito.mock(java.sql.Connection.class);
    Mockito.when(mockSqlConn.getCatalog()).thenReturn("tbi"); //$NON-NLS-1$
    // ~mock
    // mock ResultSet
    ResultSet mockCatalogResults = Mockito.mock(ResultSet.class);
    Mockito.when(mockCatalogResults.next()).thenReturn(true, false);
    Mockito.when(mockCatalogResults.getString(MetaDataConstants.TABLE_CAT.name())).thenReturn("tbi"); //$NON-NLS-1$
    ResultSet mockSchemaResults = Mockito.mock(ResultSet.class);
    Mockito.when(mockSchemaResults.next()).thenReturn(true, false);
    Mockito.when(mockSchemaResults.getString(MetaDataConstants.TABLE_SCHEM.name())).thenReturn("dbo"); //$NON-NLS-1$
    // ~Result
    // mock JDBC Metadata
    DatabaseMetaData dbJDBCMetadata = mock(DatabaseMetaData.class);
    Mockito.when(dbJDBCMetadata.getDatabaseProductName()).thenReturn(EDatabaseTypeName.AS400.getProduct());
    Mockito.when(dbJDBCMetadata.getDriverName()).thenReturn("com.ibm.as400.access.AS400JDBCDriver"); //$NON-NLS-1$
    Mockito.when(dbJDBCMetadata.getCatalogs()).thenReturn(mockCatalogResults);
    Mockito.when(dbJDBCMetadata.getConnection()).thenReturn(mockSqlConn);

    Mockito.when(dbJDBCMetadata.getSchemas()).thenReturn(mockSchemaResults);
    // ~JDBC Metadata
    //        stub(method(ConnectionUtils.class, "isOdbcTeradata", DatabaseMetaData.class)).toReturn(true); //$NON-NLS-1$
    // mock DatabaseConnection
    List<String> catalogFilter = new ArrayList<String>();
    DatabaseConnection dbConnection = mock(DatabaseConnection.class);
    Mockito.when(dbConnection.getSID()).thenReturn(""); //$NON-NLS-1$
    Mockito.when(dbConnection.getDatabaseType()).thenReturn(EDatabaseTypeName.AS400.getDisplayName());
    Mockito.when(dbConnection.getUiSchema()).thenReturn(""); //$NON-NLS-1$
    // ~DatabaseConnection

    // mock MetadataConnection
    IMetadataConnection metadaConnection = Mockito.mock(MetadataConnection.class);
    Mockito.when(metadaConnection.getDatabase()).thenReturn(""); //$NON-NLS-1$
    // ~MetadataConnection

    // mock ConvertionHelper
    PowerMockito.mockStatic(ConvertionHelper.class);
    Mockito.when(ConvertionHelper.convert(dbConnection)).thenReturn(metadaConnection);
    // Mockito.when(ExtractMetaDataUtils.getDatabaseMetaData(mockSqlConn, EDatabaseTypeName.IBMDB2ZOS.getXmlName(),
    // false, ""))
    // .thenCallRealMethod();
    // ~ConvertionHelper
    // mock ConnectionHelper
    PowerMockito.mockStatic(ConnectionHelper.class);
    Mockito.when(ConnectionHelper.getTables(dbConnection)).thenReturn(new HashSet<MetadataTable>());
    // Mockito.when(ExtractMetaDataUtils.getDatabaseMetaData(mockSqlConn, EDatabaseTypeName.IBMDB2ZOS.getXmlName(),
    // false, ""))
    // .thenCallRealMethod();
    // ~ConnectionHelper

    when(dbConnection.isContextMode()).thenReturn(false);
    List<Catalog> fillCatalogs = this.dBConnectionFillerImpl.fillCatalogs(dbConnection, dbJDBCMetadata, null,
            catalogFilter);
    assertTrue(fillCatalogs.size() == 1);
    assertTrue("tbi".equals(fillCatalogs.get(0).getName()));
    List<Schema> schemas = CatalogHelper.getSchemas(fillCatalogs.get(0));
    assertTrue(schemas.size() == 1);
    assertTrue("dbo".equals(schemas.get(0).getName()));

}

From source file:org.talend.metadata.managment.model.DBConnectionFillerImpl.java

@Override
public List<Package> fillSchemas(DatabaseConnection dbConn, DatabaseMetaData dbJDBCMetadata,
        IMetadataConnection metaConnection, List<String> schemaFilter) {
    List<Schema> returnSchemas = new ArrayList<Schema>();
    if (dbJDBCMetadata == null || (dbConn != null && ConnectionHelper.getCatalogs(dbConn).size() > 0)
            || ConnectionUtils.isSybase(dbJDBCMetadata)) {
        return null;
    }//from  ww  w .j  ava 2  s.c  o m
    ResultSet schemas = null;
    // teradata use db name to filter schema
    if (dbConn != null && (EDatabaseTypeName.TERADATA.getProduct().equals(dbConn.getProductId())
            || EDatabaseTypeName.EXASOL.getProduct().equals(dbConn.getProductId()))) {
        if (!dbConn.isContextMode()) {
            String sid = getDatabaseName(dbConn);
            if (sid != null && sid.length() > 0) {
                schemaFilter.add(sid);
            }
        } else {
            IMetadataConnection iMetadataCon = metaConnection;
            if (iMetadataCon == null) {
                iMetadataCon = ConvertionHelper.convert(dbConn);
            }
            String sid = iMetadataCon.getDatabase();
            if (sid != null && sid.length() > 0) {
                schemaFilter.add(sid);
            }
        }
    }
    // TDI-17172 : if the schema is not fill, as the db context model, should clear "schemaFilter" .
    if (dbConn != null && dbConn.isContextMode()) {
        if (EDatabaseTypeName.ORACLEFORSID.getProduct().equals(dbConn.getProductId())
                || EDatabaseTypeName.IBMDB2.getProduct().equals(dbConn.getProductId())) {
            IMetadataConnection iMetadataCon = metaConnection;
            if (iMetadataCon == null) {
                iMetadataCon = ConvertionHelper.convert(dbConn);
            }
            if (iMetadataCon != null) {
                String schemaTemp = iMetadataCon.getSchema();
                if ("".equals(schemaTemp)) { //$NON-NLS-1$
                    schemaFilter.clear();
                }
            }
        }
    }

    try {
        if (dbConn != null && EDatabaseTypeName.ACCESS.getProduct().equals(dbConn.getProductId())) {
            return null;
        }
        schemas = dbJDBCMetadata.getSchemas();
    } catch (SQLException e) {
        log.warn("This database doesn't contain any schema."); //$NON-NLS-1$
    }
    boolean hasSchema = false;
    try {
        boolean isHive2 = HiveConnectionManager.getInstance().isHive2(metaConnection);
        if (schemas != null && !ConnectionUtils.isOdbcHyperFileSQL(dbJDBCMetadata)) {
            String schemaName = null;
            while (schemas.next()) {
                if (!ConnectionUtils.isOdbcTeradata(dbJDBCMetadata) && !isHive2) {
                    schemaName = schemas.getString(MetaDataConstants.TABLE_SCHEM.name());
                    if (schemaName == null) {
                        schemaName = schemas.getString(DatabaseConstant.ODBC_ORACLE_SCHEMA_NAME);
                    }
                    if (schemaName == null) {
                        // try to get first column
                        schemaName = schemas.getString(1);
                    }
                } else {
                    schemaName = schemas.getString(1);
                }
                hasSchema = true;
                String uiSchemaOnConnWizard = null;
                if (dbConn != null) {
                    uiSchemaOnConnWizard = dbConn.getUiSchema();
                    // for hive2 db name is treat as schema
                    if (isHive2) {
                        uiSchemaOnConnWizard = getDatabaseName(dbConn);
                    }
                }

                if ((!StringUtils.isEmpty(uiSchemaOnConnWizard) || !isNullUiSchema(dbConn)) && dbConn != null) {
                    // If the UiSchema on ui is not empty, the shema name should be same to this UiSchema name.
                    Schema schema = SchemaHelper
                            .createSchema(TalendCWMService.getReadableName(dbConn, uiSchemaOnConnWizard));
                    returnSchemas.add(schema);
                    break;
                } else if (isCreateElement(schemaFilter, schemaName)) {
                    Schema schema = SchemaHelper.createSchema(schemaName);
                    returnSchemas.add(schema);
                }
            }
            schemas.close();
        }
    } catch (SQLException e) {
        log.error(e, e);
    }
    // handle case of SQLite (no schema no catalog)
    // MOD gdbu 2011-4-12 bug : 18975
    // ResultSet catalogs = dbJDBCMetadata.getCatalogs();
    // ~18975
    if (!hasSchema) {
        // TDI-30715: Only here handle the lightweight db which no catalogs and no schemas(such as Sqlite)
        fillSqliteFakeSchemas(returnSchemas);
    }
    // MOD gdbu 2011-4-12 bug : 18975
    // catalogs.close();
    // ~18975
    Set<MetadataTable> tableSet = new HashSet<MetadataTable>();
    if (dbConn != null) {
        tableSet.addAll(ConnectionHelper.getTables(dbConn));
    }
    // oldSchemas is use for record tables when click finish,then tables will be replace and null.
    List<Schema> oldSchemas = new ArrayList<Schema>();
    for (MetadataTable table : tableSet) {
        EObject eContainer = table.eContainer();
        if (eContainer != null && eContainer instanceof Schema && !oldSchemas.contains(eContainer)) {
            oldSchemas.add((Schema) eContainer);
        }
    }

    if (isLinked() && !returnSchemas.isEmpty()) {
        ConnectionHelper.addSchemas(returnSchemas, dbConn);
    }
    // if have same schema in current connection,need to fill tables.
    for (Schema schema : oldSchemas) {
        List<Schema> list = new ArrayList<Schema>();
        String name = schema.getName();
        Schema s = (Schema) ConnectionHelper.getPackage(name, dbConn, Schema.class);
        if (s != null) {
            list.add(s);
            ConnectionHelper.removeSchemas(list, dbConn);
            ConnectionHelper.addSchema(schema, dbConn);
        } else {
            ConnectionHelper.addSchema(schema, dbConn);
        }
    }
    return ListUtils.castList(Package.class, returnSchemas);
}

From source file:org.wso2.carbon.dataservices.core.script.DSGenerator.java

public static String[] getSchemas(Connection connection) throws Exception {
    if (connection != null) {
        List<String> schemaList = new ArrayList<String>();
        DatabaseMetaData mObject = connection.getMetaData();
        ResultSet schemas = mObject.getSchemas();
        while (schemas.next()) {
            schemaList.add(schemas.getString(DBConstants.DataServiceGenerator.TABLE_SCHEM));
        }/*from ww  w  . j  a  v a2s.c  o  m*/
        String str[] = schemaList.toArray(new String[schemaList.size()]);
        return str;
    } else {
        return null;
    }
}

From source file:ro.nextreports.designer.dbviewer.DefaultDBViewer.java

public List<String> getSchemas(Connection connection) throws NextSqlException {
    List<String> schemas = new ArrayList<String>();
    ResultSet rs = null;//  www.j ava  2s . c  o  m
    try {
        DatabaseMetaData dbmd = connection.getMetaData();
        rs = dbmd.getSchemas();
        while (rs.next()) {
            String schemaName = rs.getString("TABLE_SCHEM");
            schemas.add(schemaName);
        }
        if (schemas.size() == 0) {
            schemas.add(NO_SCHEMA_NAME);
        }
        return schemas;
    } catch (Exception e) {
        LOG.error(e.getMessage(), e);
        e.printStackTrace();
        //throw new NextSqlException("Could not retrieve schema names.", e);
        schemas.add("%");
        return schemas;
    } finally {
        closeResultSet(rs);
    }
}

From source file:weave.utils.SQLUtils.java

/**
 * @param conn An existing SQL Connection
 * @return A List of schema names/*from  ww w . j a  v a 2 s . c o m*/
 * @throws SQLException If the query fails.
 */
public static List<String> getSchemas(Connection conn) throws SQLException {
    List<String> schemas = new Vector<String>();
    ResultSet rs = null;
    try {
        DatabaseMetaData md = conn.getMetaData();

        // MySQL "doesn't support schemas," so use catalogs.
        if (conn.getMetaData().getDatabaseProductName().equalsIgnoreCase(MYSQL)) {
            rs = md.getCatalogs();
            // use column index instead of name because sometimes the names are lower case, sometimes upper.
            while (rs.next())
                schemas.add(rs.getString(1)); // table_catalog
        } else {
            rs = md.getSchemas();
            // use column index instead of name because sometimes the names are lower case, sometimes upper.
            while (rs.next())
                schemas.add(rs.getString(1)); // table_schem
        }

        Collections.sort(schemas, String.CASE_INSENSITIVE_ORDER);
    } finally {
        SQLUtils.cleanup(rs);
    }
    return schemas;
}