Example usage for java.sql DatabaseMetaData getDatabaseMinorVersion

List of usage examples for java.sql DatabaseMetaData getDatabaseMinorVersion

Introduction

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

Prototype

int getDatabaseMinorVersion() throws SQLException;

Source Link

Document

Retrieves the minor version number of the underlying database.

Usage

From source file:org.diffkit.util.DKSqlUtil.java

public static Map<String, ?> getDatabaseInfo(Connection connection_) throws SQLException {
    if (connection_ == null)
        return null;
    DatabaseMetaData dbMeta = connection_.getMetaData();
    if (dbMeta == null)
        return null;
    Map<String, Object> info = new HashMap<String, Object>();
    info.put(DATABASE_MAJOR_VERSION_KEY, new Integer(dbMeta.getDatabaseMajorVersion()));
    info.put(DATABASE_MINOR_VERSION_KEY, new Integer(dbMeta.getDatabaseMinorVersion()));
    info.put(DATABASE_PRODUCT_NAME_KEY, dbMeta.getDatabaseProductName());
    info.put(DATABASE_PRODUCT_VERSION_KEY, dbMeta.getDatabaseProductVersion());
    return info;/*from   w w  w  .  j a v a2  s  .com*/
}

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  . ja  v  a  2s .  c o 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  w w  w. ja va2s .co  m
    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.jumpmind.db.platform.JdbcDatabasePlatformFactory.java

public static int getDatabaseMinorVersion(DataSource dataSource) {
    Connection connection = null;
    try {//from  w w w .j a va2 s  . c  o  m
        connection = dataSource.getConnection();
        DatabaseMetaData metaData = connection.getMetaData();
        return metaData.getDatabaseMinorVersion();
    } 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 a2s  . c o m*/

    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.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 {/*from   ww  w  .ja  va2s .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.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 {/*from   w w  w  .  ja v  a2 s. co  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.
    }
}

From source file:org.openconcerto.sql.model.SQLBase.java

public synchronized int[] getVersion() throws SQLException {
    if (this.dbVersion == null) {
        this.dbVersion = this.getDataSource()
                .useConnection(new ConnectionHandlerNoSetup<int[], SQLException>() {
                    @Override/*  w w w  .  j a v  a  2 s .co m*/
                    public int[] handle(SQLDataSource ds) throws SQLException, SQLException {
                        final DatabaseMetaData md = ds.getConnection().getMetaData();
                        return new int[] { md.getDatabaseMajorVersion(), md.getDatabaseMinorVersion() };
                    }
                });
    }
    return this.dbVersion;
}

From source file:org.openmrs.module.emrmonitor.api.db.hibernate.HibernateEmrMonitorDAO.java

@Override
public Map<String, String> getDatabaseMetadata() {
    final Map<String, String> ret = new LinkedHashMap<String, String>();
    sessionFactory.getCurrentSession().doWork(new Work() {
        @Override/*  w ww  .  j  av a 2  s.  c  o  m*/
        public void execute(Connection connection) throws SQLException {
            DatabaseMetaData md = connection.getMetaData();
            ret.put("product.name", md.getDatabaseProductName());
            ret.put("product.version", md.getDatabaseProductVersion());
            ret.put("product.majorVersion", Integer.toString(md.getDatabaseMajorVersion()));
            ret.put("product.minorVersion", Integer.toString(md.getDatabaseMinorVersion()));
        }
    });
    return ret;
}

From source file:org.rhq.plugins.oracle.OracleDiscoveryComponent.java

public DiscoveredResourceDetails discoverResource(Configuration pluginConfig,
        ResourceDiscoveryContext resourceDiscoveryContext) throws InvalidPluginConfigurationException {

    Connection connection = null;
    try {/*  w  ww  .  j  a v  a2  s  .c o m*/
        connection = OracleServerComponent.buildConnection(pluginConfig);
        DatabaseMetaData dbmd = connection.getMetaData();
        String version = dbmd.getDatabaseMajorVersion() + "." + dbmd.getDatabaseMinorVersion();
        DiscoveredResourceDetails details = createResourceDetails(resourceDiscoveryContext, pluginConfig,
                version, null);
        return details;
    } catch (Exception e) {
        log.warn("Could not connect to oracle with supplied configuration", e);
        throw new InvalidPluginConfigurationException("Unable to connect to Oracle", e);
    } finally {
        JDBCUtil.safeClose(connection);
    }
}