Example usage for org.springframework.jdbc.support JdbcUtils extractDatabaseMetaData

List of usage examples for org.springframework.jdbc.support JdbcUtils extractDatabaseMetaData

Introduction

In this page you can find the example usage for org.springframework.jdbc.support JdbcUtils extractDatabaseMetaData.

Prototype

@SuppressWarnings("unchecked")
public static <T> T extractDatabaseMetaData(DataSource dataSource, final String metaDataMethodName)
        throws MetaDataAccessException 

Source Link

Document

Call the specified method on DatabaseMetaData for the given DataSource, and extract the invocation result.

Usage

From source file:org.easyrec.utils.spring.store.dao.impl.DBRootDAOMysqlImpl.java

@SuppressWarnings({ "unchecked" })
public boolean existsDatabase(String databaseName) {
    // get the list of all databases from the db server
    List<String> dbNames;
    DatabaseMetaDataCallback callback = new DatabaseMetaDataCallback() {
        public Object processMetaData(DatabaseMetaData dbmd) throws SQLException, MetaDataAccessException {
            List<String> ret = new LinkedList<String>();
            ResultSet rs = dbmd.getCatalogs();
            while (rs.next()) {
                ret.add(rs.getString(1));
            }//w ww  .  ja v a  2s .c o  m
            return ret;
        }
    };
    try {
        dbNames = (List<String>) JdbcUtils.extractDatabaseMetaData(getDataSource(), callback);
    } catch (Exception e) {
        throw new RuntimeException("unable to read database metadata", e);
    }

    return dbNames.contains(databaseName);
}

From source file:org.springframework.boot.autoconfigure.orm.jpa.DatabaseLookup.java

/**
 * Return the most suitable {@link Database} for the given {@link DataSource}.
 * @param dataSource the source {@link DataSource}
 * @return the most suitable {@link Database}
 *///from w w w.  j  a  v  a2  s  .  co m
public static Database getDatabase(DataSource dataSource) {
    if (dataSource == null) {
        return Database.DEFAULT;
    }
    try {
        String url = JdbcUtils.extractDatabaseMetaData(dataSource, "getURL");
        DatabaseDriver driver = DatabaseDriver.fromJdbcUrl(url);
        Database database = LOOKUP.get(driver);
        if (database != null) {
            return database;
        }
    } catch (MetaDataAccessException ex) {
        logger.warn("Unable to determine jdbc url from datasource", ex);
    }
    return Database.DEFAULT;
}

From source file:org.springframework.jdbc.core.metadata.CallMetaDataProviderFactory.java

/**
 * Create a CallMetaDataProvider based on the database metadata
 * @param dataSource used to retrieve metadata
 * @param context the class that holds configuration and metadata
 * @return instance of the CallMetaDataProvider implementation to be used
 *//*from  ww w  .  j  av a  2 s.c  om*/
static public CallMetaDataProvider createMetaDataProvider(DataSource dataSource,
        final CallMetaDataContext context) {
    try {
        CallMetaDataProvider result = (CallMetaDataProvider) JdbcUtils.extractDatabaseMetaData(dataSource,
                databaseMetaData -> {
                    String databaseProductName = JdbcUtils
                            .commonDatabaseName(databaseMetaData.getDatabaseProductName());
                    boolean accessProcedureColumnMetaData = context.isAccessCallParameterMetaData();
                    if (context.isFunction()) {
                        if (!supportedDatabaseProductsForFunctions.contains(databaseProductName)) {
                            if (logger.isWarnEnabled()) {
                                logger.warn(databaseProductName
                                        + " is not one of the databases fully supported for function calls "
                                        + "-- supported are: " + supportedDatabaseProductsForFunctions);
                            }
                            if (accessProcedureColumnMetaData) {
                                logger.warn(
                                        "Metadata processing disabled - you must specify all parameters explicitly");
                                accessProcedureColumnMetaData = false;
                            }
                        }
                    } else {
                        if (!supportedDatabaseProductsForProcedures.contains(databaseProductName)) {
                            if (logger.isWarnEnabled()) {
                                logger.warn(databaseProductName
                                        + " is not one of the databases fully supported for procedure calls "
                                        + "-- supported are: " + supportedDatabaseProductsForProcedures);
                            }
                            if (accessProcedureColumnMetaData) {
                                logger.warn(
                                        "Metadata processing disabled - you must specify all parameters explicitly");
                                accessProcedureColumnMetaData = false;
                            }
                        }
                    }
                    CallMetaDataProvider provider;
                    if ("Oracle".equals(databaseProductName)) {
                        provider = new OracleCallMetaDataProvider(databaseMetaData);
                    } else if ("DB2".equals(databaseProductName)) {
                        provider = new Db2CallMetaDataProvider((databaseMetaData));
                    } else if ("Apache Derby".equals(databaseProductName)) {
                        provider = new DerbyCallMetaDataProvider((databaseMetaData));
                    } else if ("PostgreSQL".equals(databaseProductName)) {
                        provider = new PostgresCallMetaDataProvider((databaseMetaData));
                    } else if ("Sybase".equals(databaseProductName)) {
                        provider = new SybaseCallMetaDataProvider((databaseMetaData));
                    } else if ("Microsoft SQL Server".equals(databaseProductName)) {
                        provider = new SqlServerCallMetaDataProvider((databaseMetaData));
                    } else if ("HDB".equals(databaseProductName)) {
                        provider = new HanaCallMetaDataProvider((databaseMetaData));
                    } else {
                        provider = new GenericCallMetaDataProvider(databaseMetaData);
                    }
                    if (logger.isDebugEnabled()) {
                        logger.debug("Using " + provider.getClass().getName());
                    }
                    provider.initializeWithMetaData(databaseMetaData);
                    if (accessProcedureColumnMetaData) {
                        provider.initializeWithProcedureColumnMetaData(databaseMetaData,
                                context.getCatalogName(), context.getSchemaName(), context.getProcedureName());
                    }
                    return provider;
                });
        return result;
    } catch (MetaDataAccessException ex) {
        throw new DataAccessResourceFailureException("Error retrieving database metadata", ex);
    }
}

From source file:org.springframework.jdbc.core.metadata.TableMetaDataProviderFactory.java

/**
 * Create a TableMetaDataProvider based on the database metadata.
 * @param dataSource used to retrieve metadata
 * @param context the class that holds configuration and metadata
 * @return instance of the TableMetaDataProvider implementation to be used
 *//*from  ww  w . j a  v  a  2s  .c  o m*/
public static TableMetaDataProvider createMetaDataProvider(DataSource dataSource,
        TableMetaDataContext context) {
    try {
        TableMetaDataProvider result = (TableMetaDataProvider) JdbcUtils.extractDatabaseMetaData(dataSource,
                databaseMetaData -> {
                    String databaseProductName = JdbcUtils
                            .commonDatabaseName(databaseMetaData.getDatabaseProductName());
                    boolean accessTableColumnMetaData = context.isAccessTableColumnMetaData();
                    TableMetaDataProvider provider;
                    if ("Oracle".equals(databaseProductName)) {
                        provider = new OracleTableMetaDataProvider(databaseMetaData,
                                context.isOverrideIncludeSynonymsDefault());
                    } else if ("HSQL Database Engine".equals(databaseProductName)) {
                        provider = new HsqlTableMetaDataProvider(databaseMetaData);
                    } else if ("PostgreSQL".equals(databaseProductName)) {
                        provider = new PostgresTableMetaDataProvider(databaseMetaData);
                    } else if ("Apache Derby".equals(databaseProductName)) {
                        provider = new DerbyTableMetaDataProvider(databaseMetaData);
                    } else {
                        provider = new GenericTableMetaDataProvider(databaseMetaData);
                    }
                    if (logger.isDebugEnabled()) {
                        logger.debug("Using " + provider.getClass().getSimpleName());
                    }
                    provider.initializeWithMetaData(databaseMetaData);
                    if (accessTableColumnMetaData) {
                        provider.initializeWithTableColumnMetaData(databaseMetaData, context.getCatalogName(),
                                context.getSchemaName(), context.getTableName());
                    }
                    return provider;
                });
        return result;
    } catch (MetaDataAccessException ex) {
        throw new DataAccessResourceFailureException("Error retrieving database metadata", ex);
    }
}

From source file:org.springframework.jdbc.support.SQLErrorCodesFactory.java

/**
 * Return {@link SQLErrorCodes} for the given {@link DataSource},
 * evaluating "databaseProductName" from the
 * {@link java.sql.DatabaseMetaData}, or an empty error codes
 * instance if no {@code SQLErrorCodes} were found.
 * @param dataSource the {@code DataSource} identifying the database
 * @return the corresponding {@code SQLErrorCodes} object
 * @see java.sql.DatabaseMetaData#getDatabaseProductName()
 *//*  ww  w . j  a  va 2 s  .co m*/
public SQLErrorCodes getErrorCodes(DataSource dataSource) {
    Assert.notNull(dataSource, "DataSource must not be null");
    if (logger.isDebugEnabled()) {
        logger.debug("Looking up default SQLErrorCodes for DataSource [" + identify(dataSource) + "]");
    }

    // Try efficient lock-free access for existing cache entry
    SQLErrorCodes sec = this.dataSourceCache.get(dataSource);
    if (sec == null) {
        synchronized (this.dataSourceCache) {
            // Double-check within full dataSourceCache lock
            sec = this.dataSourceCache.get(dataSource);
            if (sec == null) {
                // We could not find it - got to look it up.
                try {
                    String name = JdbcUtils.extractDatabaseMetaData(dataSource, "getDatabaseProductName");
                    if (StringUtils.hasLength(name)) {
                        return registerDatabase(dataSource, name);
                    }
                } catch (MetaDataAccessException ex) {
                    logger.warn("Error while extracting database name - falling back to empty error codes", ex);
                }
                // Fallback is to return an empty SQLErrorCodes instance.
                return new SQLErrorCodes();
            }
        }
    }

    if (logger.isDebugEnabled()) {
        logger.debug("SQLErrorCodes found in cache for DataSource [" + identify(dataSource) + "]");
    }

    return sec;
}

From source file:rapture.postgres.connection.cache.ConnectionCacheLoader.java

public static PostgresSanitizer createSanitizer(DataSource dataSource) {
    DatabaseMetaDataCallback callback = new DatabaseMetaDataCallback() {
        @Override/*from w w w . j  av  a 2s  . c o m*/
        public String processMetaData(DatabaseMetaData dbmd) throws SQLException, MetaDataAccessException {
            return dbmd.getIdentifierQuoteString();
        }
    };
    try {
        return new PostgresSanitizer(JdbcUtils.extractDatabaseMetaData(dataSource, callback).toString());
    } catch (MetaDataAccessException e) {
        throw RaptureExceptionFactory.create("Unable to get quote identifier: " + ExceptionToString.format(e));
    }
}