Example usage for java.sql DatabaseMetaData getDatabaseMajorVersion

List of usage examples for java.sql DatabaseMetaData getDatabaseMajorVersion

Introduction

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

Prototype

int getDatabaseMajorVersion() throws SQLException;

Source Link

Document

Retrieves the major version number of the underlying database.

Usage

From source file:org.eclipse.ecr.core.storage.sql.jdbc.dialect.DialectPostgreSQL.java

public DialectPostgreSQL(DatabaseMetaData metadata, BinaryManager binaryManager,
        RepositoryDescriptor repositoryDescriptor) throws StorageException {
    super(metadata, binaryManager, repositoryDescriptor);
    fulltextAnalyzer = repositoryDescriptor == null ? null
            : repositoryDescriptor.fulltextAnalyzer == null ? DEFAULT_FULLTEXT_ANALYZER
                    : repositoryDescriptor.fulltextAnalyzer;
    pathOptimizationsEnabled = repositoryDescriptor == null ? false
            : repositoryDescriptor.pathOptimizationsEnabled;
    int major, minor;
    try {/*from   w  w  w. jav a  2 s  . co m*/
        major = metadata.getDatabaseMajorVersion();
        minor = metadata.getDatabaseMinorVersion();
    } catch (SQLException e) {
        throw new StorageException(e);
    }
    supportsWith = major > 8 || (major == 8 && minor >= 4);
    usersSeparator = repositoryDescriptor == null ? null
            : repositoryDescriptor.usersSeparatorKey == null ? DEFAULT_USERS_SEPARATOR
                    : repositoryDescriptor.usersSeparatorKey;
}

From source file:org.flowable.common.engine.impl.db.AbstractSqlScriptBasedDbSchemaManager.java

protected void executeSchemaResource(String operation, String component, String resourceName,
        InputStream inputStream) {
    logger.info("performing {} on {} with resource {}", operation, component, resourceName);
    String sqlStatement = null;//from ww  w .j a va  2  s  . com
    String exceptionSqlStatement = null;
    DbSqlSession dbSqlSession = getDbSqlSession();
    try {
        Connection connection = dbSqlSession.getSqlSession().getConnection();
        Exception exception = null;
        byte[] bytes = IoUtil.readInputStream(inputStream, resourceName);
        String ddlStatements = new String(bytes);

        // Special DDL handling for certain databases
        try {
            if (dbSqlSession.getDbSqlSessionFactory().isMysql()) {
                DatabaseMetaData databaseMetaData = connection.getMetaData();
                int majorVersion = databaseMetaData.getDatabaseMajorVersion();
                int minorVersion = databaseMetaData.getDatabaseMinorVersion();
                logger.info("Found MySQL: majorVersion={} minorVersion={}", majorVersion, minorVersion);

                // Special care for MySQL < 5.6
                if (majorVersion <= 5 && minorVersion < 6) {
                    ddlStatements = updateDdlForMySqlVersionLowerThan56(ddlStatements);
                }
            }
        } catch (Exception e) {
            logger.info("Could not get database metadata", e);
        }

        BufferedReader reader = new BufferedReader(new StringReader(ddlStatements));
        String line = readNextTrimmedLine(reader);
        boolean inOraclePlsqlBlock = false;
        while (line != null) {
            if (line.startsWith("# ")) {
                logger.debug(line.substring(2));

            } else if (line.startsWith("-- ")) {
                logger.debug(line.substring(3));

            } else if (line.startsWith("execute java ")) {
                String upgradestepClassName = line.substring(13).trim();
                DbUpgradeStep dbUpgradeStep = null;
                try {
                    dbUpgradeStep = (DbUpgradeStep) ReflectUtil.instantiate(upgradestepClassName);
                } catch (FlowableException e) {
                    throw new FlowableException("database update java class '" + upgradestepClassName
                            + "' can't be instantiated: " + e.getMessage(), e);
                }
                try {
                    logger.debug("executing upgrade step java class {}", upgradestepClassName);
                    dbUpgradeStep.execute();
                } catch (Exception e) {
                    throw new FlowableException("error while executing database update java class '"
                            + upgradestepClassName + "': " + e.getMessage(), e);
                }

            } else if (line.length() > 0) {

                if (dbSqlSession.getDbSqlSessionFactory().isOracle() && line.startsWith("begin")) {
                    inOraclePlsqlBlock = true;
                    sqlStatement = addSqlStatementPiece(sqlStatement, line);

                } else if ((line.endsWith(";") && !inOraclePlsqlBlock)
                        || (line.startsWith("/") && inOraclePlsqlBlock)) {

                    if (inOraclePlsqlBlock) {
                        inOraclePlsqlBlock = false;
                    } else {
                        sqlStatement = addSqlStatementPiece(sqlStatement, line.substring(0, line.length() - 1));
                    }

                    Statement jdbcStatement = connection.createStatement();
                    try {
                        // no logging needed as the connection will log it
                        logger.debug("SQL: {}", sqlStatement);
                        jdbcStatement.execute(sqlStatement);
                        jdbcStatement.close();

                    } catch (Exception e) {
                        if (exception == null) {
                            exception = e;
                            exceptionSqlStatement = sqlStatement;
                        }
                        logger.error("problem during schema {}, statement {}", operation, sqlStatement, e);

                    } finally {
                        sqlStatement = null;
                    }

                } else {
                    sqlStatement = addSqlStatementPiece(sqlStatement, line);
                }
            }

            line = readNextTrimmedLine(reader);
        }

        if (exception != null) {
            throw exception;
        }

        logger.debug("flowable db schema {} for component {} successful", operation, component);

    } catch (Exception e) {
        throw new FlowableException("couldn't " + operation + " db schema: " + exceptionSqlStatement, e);
    }
}

From source file:org.jtester.module.database.support.OracleDbSupport.java

/**
 * @return The major version number of the Oracle database server that is
 *         used (e.g. for Oracle version 9.2.0.1, 9 is returned
 *//*from   w  w w.  j a  v a2  s  .  c o  m*/
protected Integer getOracleMajorVersionNumber() {
    if (oracleMajorVersionNumber == null) {
        Connection connection = null;
        try {
            connection = getSQLHandler().getDataSource().getConnection();
            DatabaseMetaData metaData = connection.getMetaData();
            oracleMajorVersionNumber = metaData.getDatabaseMajorVersion();
        } catch (SQLException e) {
            throw new JTesterException("Unable to determine database major version", e);
        } finally {
            closeQuietly(connection);
        }
    }
    return oracleMajorVersionNumber;
}

From source file:org.jumpmind.db.platform.JdbcDatabasePlatformFactory.java

protected static String[] determineDatabaseNameVersionSubprotocol(DataSource dataSource) {
    Connection connection = null;
    String[] nameVersion = new String[3];
    try {//from  w  w  w.j av  a  2s  . com
        connection = dataSource.getConnection();
        DatabaseMetaData metaData = connection.getMetaData();
        nameVersion[0] = metaData.getDatabaseProductName();
        nameVersion[1] = Integer.toString(metaData.getDatabaseMajorVersion());
        final String PREFIX = "jdbc:";
        String url = metaData.getURL();
        if (StringUtils.isNotBlank(url) && url.length() > PREFIX.length()) {
            url = url.substring(PREFIX.length());
            if (url.indexOf(":") > 0) {
                url = url.substring(0, url.indexOf(":"));
            }
        }
        nameVersion[2] = url;

        /*
         * if the productName is PostgreSQL, it could be either PostgreSQL
         * or Greenplum
         */
        /* query the metadata to determine which one it is */
        if (nameVersion[0].equalsIgnoreCase("PostgreSql")) {
            if (isGreenplumDatabase(connection)) {
                nameVersion[0] = DatabaseNamesConstants.GREENPLUM;
                nameVersion[1] = Integer.toString(getGreenplumVersion(connection));
            } else if (isRedshiftDatabase(connection)) {
                nameVersion[0] = DatabaseNamesConstants.REDSHIFT;
            }
        }

        /*
         * if the productName is MySQL, it could be either MysSQL or MariaDB
         * query the metadata to determine which one it is
         */
        if (nameVersion[0].equalsIgnoreCase(DatabaseNamesConstants.MYSQL)) {
            if (isMariaDBDatabase(connection)) {
                nameVersion[0] = DatabaseNamesConstants.MARIADB;
            }
        }

        if (nameVersion[0].toLowerCase().indexOf(DatabaseNamesConstants.DB2) != -1) {
            if (nameVersion[0].toUpperCase().indexOf("Z") != -1) {
                nameVersion[0] = DatabaseNamesConstants.DB2ZOS;
            } else if (nameVersion[0].indexOf("400") != -1) {
                nameVersion[0] = DatabaseNamesConstants.DB2AS400;
            } else {
                nameVersion[0] = DatabaseNamesConstants.DB2;
            }
        }
        if (nameVersion[0].equalsIgnoreCase("AS") && nameVersion[2].equalsIgnoreCase("db2")) {
            nameVersion[0] = DatabaseNamesConstants.DB2AS400;
        }

        if (nameVersion[0].toLowerCase().startsWith(DatabaseNamesConstants.FIREBIRD)) {
            if (isFirebirdDialect1(connection)) {
                nameVersion[0] = DatabaseNamesConstants.FIREBIRD_DIALECT1;
            }
        }

        log.info("Detected database '" + nameVersion[0] + "', version '" + nameVersion[1] + "', protocol '"
                + nameVersion[2] + "'");

        return nameVersion;
    } catch (SQLException ex) {
        throw new SqlException("Error while reading the database metadata: " + ex.getMessage(), ex);
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException ex) {
                // we ignore this one
            }
        }
    }
}

From source file:org.jumpmind.db.platform.JdbcDatabasePlatformFactory.java

public static int getDatabaseMajorVersion(DataSource dataSource) {
    Connection connection = null;
    try {/*  www  . j a  v  a  2 s  . com*/
        connection = dataSource.getConnection();
        DatabaseMetaData metaData = connection.getMetaData();
        return metaData.getDatabaseMajorVersion();
    } catch (SQLException ex) {
        throw new SqlException("Error while reading the database metadata: " + ex.getMessage(), ex);
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException ex) {
                // we ignore this one
            }
        }
    }
}

From source file:org.kawanfw.test.api.client.DatabaseMetaDataTest.java

public void test(Connection connection) throws Exception {
    MessageDisplayer.initClassDisplay(this.getClass().getSimpleName());

    DatabaseMetaData databaseMetaData = connection.getMetaData();

    // Test that getMetaData() will return value from cache
    databaseMetaData = connection.getMetaData();

    if (connection instanceof RemoteConnection) {
        MessageDisplayer.display("Java Version : " + System.getProperty("java.version"));
        MessageDisplayer.display("AceQL Version: " + ((RemoteConnection) connection).getVersion());
        MessageDisplayer.display("AceQL Url    : " + ((RemoteConnection) connection).getUrl());
        MessageDisplayer.display("");
    }/*w w w .  j a  v a  2 s.c om*/

    if (connection instanceof RemoteConnection) {
        MessageDisplayer.display("((RemoteConnection)connection).clone();");
        Connection connection2 = ((RemoteConnection) connection).clone();
        @SuppressWarnings("unused")
        DatabaseMetaData databaseMetaData2 = connection2.getMetaData();
        connection2.close();
    }

    MessageDisplayer.display("General info (no Assert done):");

    MessageDisplayer.display("connection.getCatalog()                     : " + connection.getCatalog());

    MessageDisplayer.display(
            "databaseMetaData.getDatabaseProductName()   : " + databaseMetaData.getDatabaseProductName());
    MessageDisplayer.display(
            "databaseMetaData.getDatabaseProductVersion(): " + databaseMetaData.getDatabaseProductVersion());
    MessageDisplayer.display(
            "databaseMetaData.getDatabaseMajorVersion()  : " + databaseMetaData.getDatabaseMajorVersion());
    MessageDisplayer.display(
            "databaseMetaData.getDatabaseMinorVersion()  : " + databaseMetaData.getDatabaseMinorVersion());
    MessageDisplayer.display(
            "databaseMetaData.allProceduresAreCallable() : " + databaseMetaData.allProceduresAreCallable());
    // SystemOutHandle.display(DatabaseMetaData.bestRowSession);
    MessageDisplayer.display("");

    // SystemOutHandle.display(databaseMetaData.autoCommitFailureClosesAllResultSets());

    MessageDisplayer.display("databaseMetaData.getCatalogTerm(): " + databaseMetaData.getCatalogTerm());

    try {

        MessageDisplayer.display(
                "databaseMetaData.supportsStoredProcedures(): " + databaseMetaData.supportsStoredProcedures());

        MessageDisplayer.display("databaseMetaData.supportsStoredFunctionsUsingCallSyntax(): "
                + databaseMetaData.supportsStoredFunctionsUsingCallSyntax());

    } catch (Throwable e) {
        MessageDisplayer.display(e.toString());
    }

    MessageDisplayer.display("connection.getAutoCommit(): " + connection.getAutoCommit());

    MessageDisplayer.display("databaseMetaData.getDefaultTransactionIsolation()    : "
            + databaseMetaData.getDefaultTransactionIsolation());

    MessageDisplayer
            .display("databaseMetaData.supportsTransactionIsolationLevel(TRANSACTION_READ_UNCOMMITTED): "
                    + databaseMetaData
                            .supportsTransactionIsolationLevel(Connection.TRANSACTION_READ_UNCOMMITTED));

    MessageDisplayer.display("databaseMetaData.supportsTransactionIsolationLevel(TRANSACTION_READ_COMMITTED): "
            + databaseMetaData.supportsTransactionIsolationLevel(Connection.TRANSACTION_READ_COMMITTED));

    MessageDisplayer.display("databaseMetaData.supportsTransactionIsolationLevel(TRANSACTION_REPEATABLE_READ): "
            + databaseMetaData.supportsTransactionIsolationLevel(Connection.TRANSACTION_REPEATABLE_READ));

    MessageDisplayer.display("databaseMetaData.supportsTransactionIsolationLevel(TRANSACTION_SERIALIZABLE): "
            + databaseMetaData.supportsTransactionIsolationLevel(Connection.TRANSACTION_SERIALIZABLE));

    MessageDisplayer
            .display("databaseMetaData.supportsBatchUpdates()    : " + databaseMetaData.supportsBatchUpdates());
    MessageDisplayer
            .display("databaseMetaData.supportsSavepoints()      : " + databaseMetaData.supportsSavepoints());
    MessageDisplayer.display(
            "databaseMetaData.supportsGetGeneratedKeys(): " + databaseMetaData.supportsGetGeneratedKeys());

    if (!new SqlUtil(connection).isTeradata() && !new SqlUtil(connection).isInformix()) {
        Assert.assertEquals(true,
                databaseMetaData.supportsTransactionIsolationLevel(Connection.TRANSACTION_READ_COMMITTED));
    }

    Assert.assertEquals("databaseMetaData.supportsBatchUpdates()", true,
            databaseMetaData.supportsBatchUpdates());

    if (!new SqlUtil(connection).isSQLAnywhere() && !new SqlUtil(connection).isAccess()) {
        Assert.assertEquals("databaseMetaData.supportsGetGeneratedKeys()", true,
                databaseMetaData.supportsGetGeneratedKeys());
    }
    // Informix does not support savepoints
    SqlUtil sqlUtil = new SqlUtil(connection);
    if (!sqlUtil.isInformix() && !sqlUtil.isTeradata() && !new SqlUtil(connection).isAccess()) {
        Assert.assertEquals(true, databaseMetaData.supportsSavepoints());
    }

    MessageDisplayer.display("");

    String catalog = null;
    String schema = null;
    String table = "customer";

    // Table name must be uppercase for Oracle & DB2, lowercase for MySQL
    // and PostgreSQL
    if (new SqlUtil(connection).isOracle() || new SqlUtil(connection).isHSQLDB()
            || new SqlUtil(connection).isDB2()) {
        table = table.toUpperCase();
    }

    ResultSet rs = null;

    if (!new SqlUtil(connection).isAccess()) {

        rs = databaseMetaData.getPrimaryKeys(catalog, schema, table);

        printResultSet(rs);

        boolean rsNext = false;

        while (rs.next()) {
            rsNext = true;
            String keyColumnName = rs.getString("COLUMN_NAME");
            MessageDisplayer.display("Primary Key is: " + keyColumnName + " for Table: " + table);
            Assert.assertEquals("customer_id", keyColumnName.toLowerCase());
        }

        if (!new SqlUtil(connection).isH2()) {
            Assert.assertEquals(true, rsNext);
        }

        rs.close();
    }

    // boolean returnNow = true;
    // if (returnNow) return;

    String[] types = { "TABLE", "VIEW" };
    rs = databaseMetaData.getTables(null, null, null, types);

    Set<String> tablesSet = new HashSet<String>();

    Set<String> ourTables = new HashSet<String>();
    ourTables.add("banned_usernames");
    ourTables.add("customer");
    ourTables.add("customer_auto");
    ourTables.add("orderlog");
    ourTables.add("user_login");

    MessageDisplayer.display("");
    while (rs.next()) {
        table = rs.getString("TABLE_NAME");

        if (ourTables.contains(table.toLowerCase())) {
            MessageDisplayer.display("Table: " + table);
        }

        tablesSet.add(table.toLowerCase());
    }

    // printResultSet(rs);

    testTable("banned_usernames", tablesSet);
    testTable("customer", tablesSet);
    testTable("orderlog", tablesSet);
    testTable("user_login", tablesSet);

    rs.close();
}

From source file:org.kuali.rice.krad.data.platform.MaxValueIncrementerFactoryTest.java

private void setUpMetaData(DataSource dataSource, String platformName, int version) throws SQLException {
    DatabaseMetaData metaData = mock(DatabaseMetaData.class);
    when(metaData.getDatabaseProductName()).thenReturn(platformName);
    when(metaData.getDatabaseMajorVersion()).thenReturn(version);
    Connection connection = mock(Connection.class);
    when(connection.getMetaData()).thenReturn(metaData);
    when(dataSource.getConnection()).thenReturn(connection);
}

From source file:org.nuxeo.ecm.core.storage.sql.jdbc.dialect.DialectPostgreSQL.java

public DialectPostgreSQL(DatabaseMetaData metadata, BinaryManager binaryManager,
        RepositoryDescriptor repositoryDescriptor) throws StorageException {
    super(metadata, binaryManager, repositoryDescriptor);
    fulltextAnalyzer = repositoryDescriptor == null ? null
            : repositoryDescriptor.fulltextAnalyzer == null ? DEFAULT_FULLTEXT_ANALYZER
                    : repositoryDescriptor.fulltextAnalyzer;
    pathOptimizationsEnabled = repositoryDescriptor == null ? false
            : repositoryDescriptor.getPathOptimizationsEnabled();
    int major, minor;
    try {/*w  ww  .  j a  v a  2 s  .c om*/
        major = metadata.getDatabaseMajorVersion();
        minor = metadata.getDatabaseMinorVersion();
    } catch (SQLException e) {
        throw new StorageException(e);
    }
    supportsWith = major > 8 || (major == 8 && minor >= 4);
    if ((major == 9 && minor >= 1) || (major > 9)) {
        unloggedKeyword = UNLOGGED_KEYWORD;
    } else {
        unloggedKeyword = "";
    }
    usersSeparator = repositoryDescriptor == null ? null
            : repositoryDescriptor.usersSeparatorKey == null ? DEFAULT_USERS_SEPARATOR
                    : repositoryDescriptor.usersSeparatorKey;
    String idt = repositoryDescriptor == null ? null : repositoryDescriptor.idType;
    if (idt == null || "".equals(idt) || "varchar".equalsIgnoreCase(idt)) {
        idType = DialectIdType.VARCHAR;
    } else if ("uuid".equalsIgnoreCase(idt)) {
        idType = DialectIdType.UUID;
    } else if (idt.toLowerCase().startsWith("sequence")) {
        idType = DialectIdType.SEQUENCE;
        if (idt.toLowerCase().startsWith("sequence:")) {
            String[] split = idt.split(":");
            idSequenceName = split[1];
        } else {
            idSequenceName = "hierarchy_seq";
        }
    } else {
        throw new StorageException("Unknown id type: '" + idt + "'");
    }
    try {
        compatibilityFulltextTable = getCompatibilityFulltextTable(metadata);
    } catch (SQLException e) {
        throw new StorageException(e);
    }
}

From source file:org.nuxeo.ecm.core.storage.sql.jdbc.dialect.DialectSQLServer.java

public DialectSQLServer(DatabaseMetaData metadata, BinaryManager binaryManager,
        RepositoryDescriptor repositoryDescriptor) throws StorageException {
    super(metadata, binaryManager, repositoryDescriptor);
    try {/*w  ww . j ava2s  .  c o  m*/
        checkDatabaseConfiguration(metadata.getConnection());
        majorVersion = metadata.getDatabaseMajorVersion();
        engineEdition = getEngineEdition(metadata.getConnection());

    } catch (SQLException e) {
        throw new StorageException(e);
    }
    if (engineEdition == 5) { // 5 = SQL Azure
        azure = true;
        fulltextDisabled = true;
        if (repositoryDescriptor != null) {
            repositoryDescriptor.setFulltextDisabled(true);
        }
    }
    fulltextAnalyzer = repositoryDescriptor == null ? null
            : repositoryDescriptor.fulltextAnalyzer == null ? DEFAULT_FULLTEXT_ANALYZER
                    : repositoryDescriptor.fulltextAnalyzer;
    fulltextCatalog = repositoryDescriptor == null ? null
            : repositoryDescriptor.fulltextCatalog == null ? DEFAULT_FULLTEXT_CATALOG
                    : repositoryDescriptor.fulltextCatalog;
    usersSeparator = repositoryDescriptor == null ? null
            : repositoryDescriptor.usersSeparatorKey == null ? DEFAULT_USERS_SEPARATOR
                    : repositoryDescriptor.usersSeparatorKey;
    pathOptimizationsEnabled = repositoryDescriptor == null ? false
            : repositoryDescriptor.getPathOptimizationsEnabled();
    String idt = repositoryDescriptor == null ? null : repositoryDescriptor.idType;
    if (idt == null || "".equals(idt) || "varchar".equalsIgnoreCase(idt)) {
        idType = DialectIdType.VARCHAR;
    } else if (idt.toLowerCase().startsWith("sequence")) {
        idType = DialectIdType.SEQUENCE;
        if (idt.toLowerCase().startsWith("sequence:")) {
            String[] split = idt.split(":");
            idSequenceName = split[1];
        } else {
            idSequenceName = "hierarchy_seq";
        }
    } else {
        throw new StorageException("Unknown id type: '" + idt + "'");
    }

}

From source file:org.openadaptor.auxil.connector.jdbc.writer.AbstractSQLWriter.java

protected void logDBInfo(DatabaseMetaData dmd) throws SQLException {
    if (debug_db_version_not_logged && log.isDebugEnabled()) {
        String productName = dmd.getDatabaseProductName();
        try {//  w  ww.j a v  a2 s  .c o  m
            log.debug("DB Name (version major/minor): " + productName + " (" + dmd.getDatabaseMajorVersion()
                    + "/" + dmd.getDatabaseMinorVersion() + ")");
        } catch (AbstractMethodError ame) { //Sybase jconn2 driver doesn't implement the maj/min methods.
            log.debug("DB Name: " + productName);
        }
        log.debug("DB Version: " + dmd.getDatabaseProductVersion());
        debug_db_version_not_logged = false; //Don't report it any more.
    }
}