Search in sources :

Example 61 with DatabaseMetaData

use of java.sql.DatabaseMetaData in project metacat by Netflix.

the class JdbcConnectorDatabaseService method listNames.

/**
     * {@inheritDoc}
     */
@Override
public List<QualifiedName> listNames(@Nonnull final ConnectorContext context, @Nonnull final QualifiedName name, @Nullable final QualifiedName prefix, @Nullable final Sort sort, @Nullable final Pageable pageable) {
    final String catalogName = name.getCatalogName();
    log.debug("Beginning to list database names for catalog {} for request {}", catalogName, context);
    try (final Connection connection = this.dataSource.getConnection()) {
        final DatabaseMetaData metaData = connection.getMetaData();
        final List<QualifiedName> names = Lists.newArrayList();
        try (final ResultSet schemas = prefix == null || StringUtils.isEmpty(prefix.getDatabaseName()) ? metaData.getSchemas() : metaData.getSchemas(connection.getCatalog(), prefix.getDatabaseName() + JdbcConnectorUtils.MULTI_CHARACTER_SEARCH)) {
            while (schemas.next()) {
                final String schemaName = schemas.getString("TABLE_SCHEM").toLowerCase(Locale.ENGLISH);
                // skip internal schemas
                if (!schemaName.equals("information_schema")) {
                    names.add(QualifiedName.ofDatabase(name.getCatalogName(), schemaName));
                }
            }
        }
        // Does user want sorting?
        if (sort != null) {
            // We can only really sort by the database name at this level so ignore SortBy field
            final Comparator<QualifiedName> comparator = Comparator.comparing(QualifiedName::getDatabaseName);
            JdbcConnectorUtils.sort(names, sort, comparator);
        }
        // Does user want pagination?
        final List<QualifiedName> results = JdbcConnectorUtils.paginate(names, pageable);
        log.debug("Finished listing database names for catalog {} for request {}", catalogName, context);
        return results;
    } catch (final SQLException se) {
        throw this.exceptionMapper.toConnectorException(se, name);
    }
}
Also used : SQLException(java.sql.SQLException) QualifiedName(com.netflix.metacat.common.QualifiedName) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) DatabaseMetaData(java.sql.DatabaseMetaData)

Example 62 with DatabaseMetaData

use of java.sql.DatabaseMetaData in project wildfly by wildfly.

the class DatabaseTimerPersistence method investigateDialect.

/**
     * Check the connection MetaData and driver name to guess which database dialect
     * to use.
     */
private void investigateDialect() {
    Connection connection = null;
    if (database == null) {
        // no database dialect from configuration guessing from MetaData
        try {
            connection = dataSource.getConnection();
            DatabaseMetaData metaData = connection.getMetaData();
            String dbProduct = metaData.getDatabaseProductName();
            database = identifyDialect(dbProduct);
            if (database == null) {
                EjbLogger.EJB3_TIMER_LOGGER.debug("Attempting to guess on driver name.");
                database = identifyDialect(metaData.getDriverName());
            }
        } catch (Exception e) {
            EjbLogger.EJB3_TIMER_LOGGER.debug("Unable to read JDBC metadata.", e);
        } finally {
            safeClose(connection);
        }
        if (database == null) {
            EjbLogger.EJB3_TIMER_LOGGER.jdbcDatabaseDialectDetectionFailed(databaseDialects.toString());
        } else {
            EjbLogger.EJB3_TIMER_LOGGER.debugf("Detect database dialect as '%s'.  If this is incorrect, please specify the correct dialect using the 'database' attribute in your configuration.  Supported database dialect strings are %s", database, databaseDialects);
        }
    } else {
        EjbLogger.EJB3_TIMER_LOGGER.debugf("Database dialect '%s' read from configuration", database);
    }
}
Also used : Connection(java.sql.Connection) DatabaseMetaData(java.sql.DatabaseMetaData) HeuristicRollbackException(javax.transaction.HeuristicRollbackException) HeuristicMixedException(javax.transaction.HeuristicMixedException) SQLException(java.sql.SQLException) RollbackException(javax.transaction.RollbackException) StartException(org.jboss.msc.service.StartException) IOException(java.io.IOException) NotSupportedException(javax.transaction.NotSupportedException) SystemException(javax.transaction.SystemException)

Example 63 with DatabaseMetaData

use of java.sql.DatabaseMetaData in project aries by apache.

the class TradeDBManagerImpl method checkDBProductName.

/**
     * Return a String containing the DBProductName configured for
     * the current DataSource
     * 
     * used by TradeBuildDB
     *
     * @return A String of the currently configured DataSource
     * 
     */
public String checkDBProductName() throws Exception {
    Connection conn = null;
    String dbProductName = null;
    try {
        if (Log.doTrace())
            Log.traceEnter("TradeDBManagerImpl:checkDBProductName");
        conn = getConn();
        DatabaseMetaData dbmd = conn.getMetaData();
        dbProductName = dbmd.getDatabaseProductName();
    } catch (SQLException e) {
        Log.error(e, "TradeDBManagerImpl:checkDBProductName() -- Error checking the AriesTrader Database Product Name");
    } finally {
        releaseConn(conn);
    }
    return dbProductName;
}
Also used : SQLException(java.sql.SQLException) Connection(java.sql.Connection) DatabaseMetaData(java.sql.DatabaseMetaData)

Example 64 with DatabaseMetaData

use of java.sql.DatabaseMetaData in project midpoint by Evolveum.

the class OrgClosureManager method autoUpdateClosureTableStructure.

// TEMPORARY and quite BRUTAL HACK
// Originally in midPoint 3.0, m_org_closure has 5 columns, a non-null ID among them.
// In 3.1, it has 3, and no ID. Unfortunately, hibernate's hbm2ddl tool does not automatically remove ID column,
// so people can expect quite hard-to-understand error messages when running midPoint after upgrade.
//
// This code removes and re-creates the m_org_closure table if hbm2ddl is set to "update".
//
// returns true if the table was re-created
private boolean autoUpdateClosureTableStructure() {
    if (baseHelper.getConfiguration().isSkipOrgClosureStructureCheck()) {
        LOGGER.debug("Skipping org closure structure check.");
        return false;
    }
    SessionFactory sf = baseHelper.getSessionFactory();
    if (sf instanceof SessionFactoryImpl) {
        SessionFactoryImpl sfi = ((SessionFactoryImpl) sf);
        LOGGER.debug("SessionFactoryImpl.getSettings() = {}; auto update schema = {}", sfi.getSettings(), sfi.getSettings() != null ? sfi.getSettings().isAutoUpdateSchema() : null);
        if (sfi.getSettings() != null && sfi.getSettings().isAutoUpdateSchema()) {
            LOGGER.info("Checking the closure table structure.");
            final Session session = baseHelper.getSessionFactory().openSession();
            final Holder<Boolean> wrongNumberOfColumns = new Holder<>(false);
            session.doWork(new Work() {

                @Override
                public void execute(Connection connection) throws SQLException {
                    DatabaseMetaData meta = connection.getMetaData();
                    if (meta == null) {
                        LOGGER.warn("No database metadata found.");
                    } else {
                        ResultSet rsColumns = meta.getColumns(null, null, CLOSURE_TABLE_NAME, null);
                        int columns = 0;
                        while (rsColumns.next()) {
                            LOGGER.debug("Column: {} {}", rsColumns.getString("TYPE_NAME"), rsColumns.getString("COLUMN_NAME"));
                            columns++;
                        }
                        if (columns > 0) {
                            LOGGER.debug("There are {} columns in {} (obtained via DatabaseMetaData)", columns, CLOSURE_TABLE_NAME);
                            if (columns != 3) {
                                wrongNumberOfColumns.setValue(true);
                            }
                            return;
                        }
                        // perhaps some problem here... let's try another way out
                        try {
                            Statement stmt = connection.createStatement();
                            ResultSet rs = stmt.executeQuery("select * from " + CLOSURE_TABLE_NAME);
                            int cols = rs.getMetaData().getColumnCount();
                            if (cols > 0) {
                                LOGGER.debug("There are {} columns in {} (obtained via resultSet.getMetaData())", cols, CLOSURE_TABLE_NAME);
                                if (cols != 3) {
                                    wrongNumberOfColumns.setValue(true);
                                }
                            } else {
                                LOGGER.warn("Couldn't determine the number of columns in {}. In case of problems, please fix your database structure manually using DB scripts in 'config' folder.", CLOSURE_TABLE_NAME);
                            }
                            // don't care about closing them in case of failure
                            rs.close();
                            stmt.close();
                        } catch (RuntimeException e) {
                            LoggingUtils.logException(LOGGER, "Couldn't obtain the number of columns in {}. In case of problems running midPoint, please fix your database structure manually using DB scripts in 'config' folder.", e, CLOSURE_TABLE_NAME);
                        }
                    }
                }
            });
            if (wrongNumberOfColumns.getValue()) {
                session.getTransaction().begin();
                LOGGER.info("Wrong number of columns detected; dropping table " + CLOSURE_TABLE_NAME);
                Query q = session.createSQLQuery("drop table " + CLOSURE_TABLE_NAME);
                q.executeUpdate();
                session.getTransaction().commit();
                LOGGER.info("Calling hibernate hbm2ddl SchemaUpdate tool to create the table in the necessary form.");
                new SchemaUpdate(sfi.getServiceRegistry(), baseHelper.getSessionFactoryBean().getConfiguration()).execute(false, true);
                LOGGER.info("Done, table was (hopefully) created. If not, please fix your database structure manually using DB scripts in 'config' folder.");
                return true;
            }
        } else {
        // auto schema update is disabled
        }
    } else {
        LOGGER.warn("SessionFactory is not of type SessionFactoryImpl; it is {}", sf != null ? sf.getClass() : "null");
    }
    return false;
}
Also used : SessionFactory(org.hibernate.SessionFactory) Query(org.hibernate.Query) ObjectQuery(com.evolveum.midpoint.prism.query.ObjectQuery) SQLException(java.sql.SQLException) Statement(java.sql.Statement) Holder(com.evolveum.midpoint.util.Holder) Connection(java.sql.Connection) SchemaUpdate(org.hibernate.tool.hbm2ddl.SchemaUpdate) DatabaseMetaData(java.sql.DatabaseMetaData) Work(org.hibernate.jdbc.Work) ResultSet(java.sql.ResultSet) SessionFactoryImpl(org.hibernate.internal.SessionFactoryImpl) Session(org.hibernate.Session)

Example 65 with DatabaseMetaData

use of java.sql.DatabaseMetaData in project quorrabot by GloriousEggroll.

the class MySQLStore method FileExists.

@Override
public boolean FileExists(String fName) {
    CheckConnection();
    fName = validateFname(fName);
    try (Statement statement = connection.createStatement()) {
        statement.setQueryTimeout(10);
        DatabaseMetaData md = connection.getMetaData();
        try (ResultSet rs = md.getTables(null, null, "" + dbprefix + fName, null)) {
            return rs.next();
        }
    } catch (SQLException ex) {
        com.gmt2001.Console.err.printStackTrace(ex);
    }
    return false;
}
Also used : SQLException(java.sql.SQLException) PreparedStatement(java.sql.PreparedStatement) Statement(java.sql.Statement) ResultSet(java.sql.ResultSet) DatabaseMetaData(java.sql.DatabaseMetaData)

Aggregations

DatabaseMetaData (java.sql.DatabaseMetaData)360 ResultSet (java.sql.ResultSet)215 Connection (java.sql.Connection)169 SQLException (java.sql.SQLException)154 Test (org.junit.Test)87 Statement (java.sql.Statement)49 ResultSetMetaData (java.sql.ResultSetMetaData)42 ArrayList (java.util.ArrayList)40 PreparedStatement (java.sql.PreparedStatement)38 IOException (java.io.IOException)26 Properties (java.util.Properties)25 HashSet (java.util.HashSet)16 PhoenixDatabaseMetaData (org.apache.phoenix.jdbc.PhoenixDatabaseMetaData)16 HashMap (java.util.HashMap)15 PhoenixConnection (org.apache.phoenix.jdbc.PhoenixConnection)15 PrintWriter (java.io.PrintWriter)10 Savepoint (java.sql.Savepoint)10 List (java.util.List)10 Map (java.util.Map)9 DataSource (javax.sql.DataSource)9