Example usage for java.sql Connection TRANSACTION_READ_COMMITTED

List of usage examples for java.sql Connection TRANSACTION_READ_COMMITTED

Introduction

In this page you can find the example usage for java.sql Connection TRANSACTION_READ_COMMITTED.

Prototype

int TRANSACTION_READ_COMMITTED

To view the source code for java.sql Connection TRANSACTION_READ_COMMITTED.

Click Source Link

Document

A constant indicating that dirty reads are prevented; non-repeatable reads and phantom reads can occur.

Usage

From source file:org.apache.hadoop.hive.metastore.txn.TxnHandler.java

/**
 * This is logically part of c'tor and must be called prior to any other method.
 * Not physically part of c'tor due to use of relfection
 *//*from w ww .j  av a  2  s  . c  om*/
public void setConf(HiveConf conf) {
    this.conf = conf;

    checkQFileTestHack();

    synchronized (TxnHandler.class) {
        if (connPool == null) {
            //only do this once per JVM; useful for support
            LOG.info(HiveConfUtil.dumpConfig(conf).toString());

            Connection dbConn = null;
            // Set up the JDBC connection pool
            try {
                int maxPoolSize = conf
                        .getIntVar(HiveConf.ConfVars.METASTORE_CONNECTION_POOLING_MAX_CONNECTIONS);
                long getConnectionTimeoutMs = 30000;
                connPool = setupJdbcConnectionPool(conf, maxPoolSize, getConnectionTimeoutMs);
                /*the mutex pools should ideally be somewhat larger since some operations require 1
                 connection from each pool and we want to avoid taking a connection from primary pool
                 and then blocking because mutex pool is empty.  There is only 1 thread in any HMS trying
                 to mutex on each MUTEX_KEY except MUTEX_KEY.CheckLock.  The CheckLock operation gets a
                 connection from connPool first, then connPoolMutex.  All others, go in the opposite
                 order (not very elegant...).  So number of connection requests for connPoolMutex cannot
                 exceed (size of connPool + MUTEX_KEY.values().length - 1).*/
                connPoolMutex = setupJdbcConnectionPool(conf, maxPoolSize + MUTEX_KEY.values().length,
                        getConnectionTimeoutMs);
                dbConn = getDbConn(Connection.TRANSACTION_READ_COMMITTED);
                determineDatabaseProduct(dbConn);
                sqlGenerator = new SQLGenerator(dbProduct, conf);
            } catch (SQLException e) {
                String msg = "Unable to instantiate JDBC connection pooling, " + e.getMessage();
                LOG.error(msg);
                throw new RuntimeException(e);
            } finally {
                closeDbConn(dbConn);
            }
        }
    }

    timeout = HiveConf.getTimeVar(conf, HiveConf.ConfVars.HIVE_TXN_TIMEOUT, TimeUnit.MILLISECONDS);
    buildJumpTable();
    retryInterval = HiveConf.getTimeVar(conf, HiveConf.ConfVars.HMSHANDLERINTERVAL, TimeUnit.MILLISECONDS);
    retryLimit = HiveConf.getIntVar(conf, HiveConf.ConfVars.HMSHANDLERATTEMPTS);
    deadlockRetryInterval = retryInterval / 10;
    maxOpenTxns = HiveConf.getIntVar(conf, HiveConf.ConfVars.HIVE_MAX_OPEN_TXNS);
}

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

private SQLDataSource(DBSystemRoot sysRoot) {
    this.sysRoot = sysRoot;
    // on a besoin d'une implementation synchronise
    this.handlers = new Hashtable<Thread, HandlersStack>();
    // weak, since this is only a hint to avoid initializing the connection
    // on each borrowal
    this.schemaUptodate = new WeakHashMap<Connection, Object>();
    this.uptodate = new WeakHashMap<Connection, Object>();
    this.initialShemaSet = false;
    this.initialShema = null;

    // see #getNewConnection(boolean)
    this.setValidationQuery("SELECT 1");
    this.setTestOnBorrow(false);

    this.setInitialSize(3);
    this.setMaxActive(48);
    // creating connections is quite costly so make sure we always have a couple free
    this.setMinIdle(2);
    // but not too much as it can lock out other users (the server has a max connection count)
    this.setMaxIdle(16);
    this.setBlockWhenExhausted(false);
    // check 5 connections every 4 seconds
    this.setTimeBetweenEvictionRunsMillis(4000);
    this.setNumTestsPerEvictionRun(5);
    // kill extra (above minIdle) connections after 40s
    this.setSoftMinEvictableIdleTimeMillis(TimeUnit.SECONDS.toMillis(40));
    // kill idle connections after 30 minutes (even if it means re-creating some new ones
    // immediately afterwards to ensure minIdle connections)
    this.setMinEvictableIdleTimeMillis(TimeUnit.MINUTES.toMillis(30));

    // the default of many systems
    this.txIsolation = Connection.TRANSACTION_READ_COMMITTED;
    // by definition unknown without a connection
    this.dbTxIsolation = null;
    // it's rare that DB configuration changes, and it's expensive to add a trip to the server
    // for each new connection
    this.checkOnceDBTxIsolation = true;

    // see #createDataSource() for properties not supported by this class
    this.tables = Collections.emptySet();
    this.descL = new PropertyChangeListener() {
        @Override/*from  w w  w.j  ava  2s. c o m*/
        public void propertyChange(PropertyChangeEvent evt) {
            if (evt.getPropertyName().equals("descendants")) {
                // the dataSource must always have all tables, to listen to them for its cache
                setTables(((DBSystemRoot) evt.getSource()).getDescs(SQLTable.class));
            }
        }
    };
    this.sysRoot.addListener(this.descL);
    this.cache = null;
    this.cacheEnabled = false;
}

From source file:org.wso2.carbon.user.core.system.SystemUserRoleManager.java

public String[] getSystemUsers() throws UserStoreException {

    Connection dbConnection = null;
    String sqlStmt = null;// w  w  w . ja  va 2s  .  co m
    PreparedStatement prepStmt = null;
    ResultSet rs = null;
    String filter = "*";
    int maxItemLimit = 100;

    String[] systemsUsers = new String[0];
    try {

        if (filter != null && filter.trim().length() != 0) {
            filter = filter.trim();
            filter = filter.replace("*", "%");
            filter = filter.replace("?", "_");
        } else {
            filter = "%";
        }

        List<String> lst = new LinkedList<String>();

        dbConnection = DatabaseUtil.getDBConnection(dataSource);

        if (dbConnection == null) {
            throw new UserStoreException("null connection");
        }
        dbConnection.setAutoCommit(false);
        dbConnection.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
        sqlStmt = SystemJDBCConstants.GET_SYSTEM_USER_FILTER_SQL;

        prepStmt = dbConnection.prepareStatement(sqlStmt);
        prepStmt.setString(1, filter);
        if (sqlStmt.contains(UserCoreConstants.UM_TENANT_COLUMN)) {
            prepStmt.setInt(2, tenantId);
        }

        rs = prepStmt.executeQuery();

        int i = 0;
        while (rs.next()) {
            if (i < maxItemLimit) {
                String name = rs.getString(1);
                lst.add(name);
            } else {
                break;
            }
            i++;
        }
        rs.close();

        if (lst.size() > 0) {
            systemsUsers = lst.toArray(new String[lst.size()]);
        }
        Arrays.sort(systemsUsers);
        systemsUsers = UserCoreUtil.addDomainToNames(systemsUsers, UserCoreConstants.SYSTEM_DOMAIN_NAME);
    } catch (SQLException e) {
        String errorMessage = "Error occurred while getting system users";
        if (log.isDebugEnabled()) {
            log.debug(errorMessage, e);
        }
        throw new UserStoreException(errorMessage, e);
    } finally {
        DatabaseUtil.closeAllConnections(dbConnection, rs, prepStmt);
    }
    return systemsUsers;

}

From source file:org.apache.hadoop.hive.metastore.txn.TxnHandler.java

@Override
@RetrySemantics.ReadOnly//w  w  w  .j  a v a  2  s.  co m
public GetOpenTxnsInfoResponse getOpenTxnsInfo() throws MetaException {
    try {
        // We need to figure out the current transaction number and the list of
        // open transactions.  To avoid needing a transaction on the underlying
        // database we'll look at the current transaction number first.  If it
        // subsequently shows up in the open list that's ok.
        Connection dbConn = null;
        Statement stmt = null;
        ResultSet rs = null;
        try {
            /**
             * This method can run at READ_COMMITTED as long as long as
             * {@link #openTxns(org.apache.hadoop.hive.metastore.api.OpenTxnRequest)} is atomic.
             * More specifically, as long as advancing TransactionID in NEXT_TXN_ID is atomic with
             * adding corresponding entries into TXNS.  The reason is that any txnid below HWM
             * is either in TXNS and thus considered open (Open/Aborted) or it's considered Committed.
             */
            dbConn = getDbConn(Connection.TRANSACTION_READ_COMMITTED);
            stmt = dbConn.createStatement();
            String s = "select ntxn_next - 1 from NEXT_TXN_ID";
            LOG.debug("Going to execute query <" + s + ">");
            rs = stmt.executeQuery(s);
            if (!rs.next()) {
                throw new MetaException(
                        "Transaction tables not properly " + "initialized, no record found in next_txn_id");
            }
            long hwm = rs.getLong(1);
            if (rs.wasNull()) {
                throw new MetaException(
                        "Transaction tables not properly " + "initialized, null record found in next_txn_id");
            }
            close(rs);
            List<TxnInfo> txnInfos = new ArrayList<TxnInfo>();
            //need the WHERE clause below to ensure consistent results with READ_COMMITTED
            s = "select txn_id, txn_state, txn_user, txn_host, txn_started, txn_last_heartbeat from "
                    + "TXNS where txn_id <= " + hwm;
            LOG.debug("Going to execute query<" + s + ">");
            rs = stmt.executeQuery(s);
            while (rs.next()) {
                char c = rs.getString(2).charAt(0);
                TxnState state;
                switch (c) {
                case TXN_ABORTED:
                    state = TxnState.ABORTED;
                    break;

                case TXN_OPEN:
                    state = TxnState.OPEN;
                    break;

                default:
                    throw new MetaException("Unexpected transaction state " + c + " found in txns table");
                }
                TxnInfo txnInfo = new TxnInfo(rs.getLong(1), state, rs.getString(3), rs.getString(4));
                txnInfo.setStartedTime(rs.getLong(5));
                txnInfo.setLastHeartbeatTime(rs.getLong(6));
                txnInfos.add(txnInfo);
            }
            LOG.debug("Going to rollback");
            dbConn.rollback();
            return new GetOpenTxnsInfoResponse(hwm, txnInfos);
        } catch (SQLException e) {
            LOG.debug("Going to rollback");
            rollbackDBConn(dbConn);
            checkRetryable(dbConn, e, "getOpenTxnsInfo");
            throw new MetaException("Unable to select from transaction database: " + getMessage(e)
                    + StringUtils.stringifyException(e));
        } finally {
            close(rs, stmt, dbConn);
        }
    } catch (RetryException e) {
        return getOpenTxnsInfo();
    }
}

From source file:org.acmsl.queryj.tools.handlers.DatabaseMetaDataLoggingHandler.java

/**
 * Handles given information.//from   ww  w . ja v  a 2 s  .  c o m
 * @param metaData the database metadata.
 * @return <code>true</code> if the chain should be stopped.
 * @throws QueryJBuildException if the metadata cannot be logged.
 */
protected boolean handle(@NotNull final DatabaseMetaData metaData) throws QueryJBuildException {
    final boolean result = false;

    @Nullable
    Log t_Log = null;

    try {
        t_Log = UniqueLogFactory.getLog(DatabaseMetaDataLoggingHandler.class);

        if (t_Log != null) {
            t_Log.debug("Numeric functions:" + metaData.getNumericFunctions());

            t_Log.debug("String functions:" + metaData.getStringFunctions());

            t_Log.debug("System functions:" + metaData.getSystemFunctions());

            t_Log.debug("Time functions:" + metaData.getTimeDateFunctions());

            t_Log.debug("insertsAreDetected(TYPE_FORWARD_ONLY):"
                    + metaData.insertsAreDetected(ResultSet.TYPE_FORWARD_ONLY));

            t_Log.debug("insertsAreDetected(TYPE_SCROLL_INSENSITIVE):"
                    + metaData.insertsAreDetected(ResultSet.TYPE_SCROLL_INSENSITIVE));

            t_Log.debug("insertsAreDetected(TYPE_SCROLL_SENS):"
                    + metaData.insertsAreDetected(ResultSet.TYPE_SCROLL_SENSITIVE));

            t_Log.debug("isCatalogAtStart():" + metaData.isCatalogAtStart());

            t_Log.debug("isReadOnly():" + metaData.isReadOnly());

            /*
             * Fails for MySQL with a java.lang.AbstractMethodError 
             * com.mysql.jdbc.jdbc2.DatabaseMetaData.locatorsUpdateCopy()
             t_Log.debug(
               "locatorsUpdateCopy():"
             + metaData.locatorsUpdateCopy());
             */

            t_Log.debug("nullPlusNonNullIsNull():" + metaData.nullPlusNonNullIsNull());

            t_Log.debug("nullsAreSortedAtEnd():" + metaData.nullsAreSortedAtEnd());

            t_Log.debug("nullsAreSortedAtStart():" + metaData.nullsAreSortedAtStart());

            t_Log.debug("nullsAreSortedHigh():" + metaData.nullsAreSortedHigh());

            t_Log.debug("nullsAreSortedLow():" + metaData.nullsAreSortedLow());

            t_Log.debug("othersDeletesAreVisible(ResultSet.TYPE_FORWARD_ONLY):"
                    + metaData.othersDeletesAreVisible(ResultSet.TYPE_FORWARD_ONLY));

            t_Log.debug("othersDeletesAreVisible(ResultSet.TYPE_SCROLL_INSENSITIVE):"
                    + metaData.othersDeletesAreVisible(ResultSet.TYPE_SCROLL_INSENSITIVE));

            t_Log.debug("othersDeletesAreVisible(ResultSet.TYPE_SCROLL_SENS):"
                    + metaData.othersDeletesAreVisible(ResultSet.TYPE_SCROLL_SENSITIVE));

            t_Log.debug("othersInsertsAreVisible(ResultSet.TYPE_FORWARD_ONLY):"
                    + metaData.othersInsertsAreVisible(ResultSet.TYPE_FORWARD_ONLY));

            t_Log.debug("othersInsertsAreVisible(ResultSet.TYPE_SCROLL_INSENSITIVE):"
                    + metaData.othersInsertsAreVisible(ResultSet.TYPE_SCROLL_INSENSITIVE));

            t_Log.debug("othersInsertsAreVisible(ResultSet.TYPE_SCROLL_SENS):"
                    + metaData.othersInsertsAreVisible(ResultSet.TYPE_SCROLL_SENSITIVE));

            t_Log.debug("othersUpdatesAreVisible(ResultSet.TYPE_FORWARD_ONLY):"
                    + metaData.othersUpdatesAreVisible(ResultSet.TYPE_FORWARD_ONLY));

            t_Log.debug("othersUpdatesAreVisible(ResultSet.TYPE_SCROLL_INSENSITIVE):"
                    + metaData.othersUpdatesAreVisible(ResultSet.TYPE_SCROLL_INSENSITIVE));

            t_Log.debug("othersUpdatesAreVisible(ResultSet.TYPE_SCROLL_SENS):"
                    + metaData.othersUpdatesAreVisible(ResultSet.TYPE_SCROLL_SENSITIVE));

            t_Log.debug("ownDeletesAreVisible(ResultSet.TYPE_FORWARD_ONLY):"
                    + metaData.ownDeletesAreVisible(ResultSet.TYPE_FORWARD_ONLY));

            t_Log.debug("ownDeletesAreVisible(ResultSet.TYPE_SCROLL_INSENSITIVE):"
                    + metaData.ownDeletesAreVisible(ResultSet.TYPE_SCROLL_INSENSITIVE));

            t_Log.debug("ownDeletesAreVisible(ResultSet.TYPE_SCROLL_SENS):"
                    + metaData.ownDeletesAreVisible(ResultSet.TYPE_SCROLL_SENSITIVE));

            t_Log.debug("ownInsertsAreVisible(ResultSet.TYPE_FORWARD_ONLY):"
                    + metaData.ownInsertsAreVisible(ResultSet.TYPE_FORWARD_ONLY));

            t_Log.debug("ownInsertsAreVisible(ResultSet.TYPE_SCROLL_INSENSITIVE):"
                    + metaData.ownInsertsAreVisible(ResultSet.TYPE_SCROLL_INSENSITIVE));

            t_Log.debug("ownInsertsAreVisible(ResultSet.TYPE_SCROLL_SENS):"
                    + metaData.ownInsertsAreVisible(ResultSet.TYPE_SCROLL_SENSITIVE));

            t_Log.debug("ownUpdatesAreVisible(ResultSet.TYPE_FORWARD_ONLY):"
                    + metaData.ownUpdatesAreVisible(ResultSet.TYPE_FORWARD_ONLY));

            t_Log.debug("ownUpdatesAreVisible(ResultSet.TYPE_SCROLL_INSENSITIVE):"
                    + metaData.ownUpdatesAreVisible(ResultSet.TYPE_SCROLL_INSENSITIVE));

            t_Log.debug("ownUpdatesAreVisible(ResultSet.TYPE_SCROLL_SENS):"
                    + metaData.ownUpdatesAreVisible(ResultSet.TYPE_SCROLL_SENSITIVE));

            t_Log.debug("storesLowerCaseIdentifiers():" + metaData.storesLowerCaseIdentifiers());

            t_Log.debug("storesLowerCaseQuotedIdentifiers():" + metaData.storesLowerCaseQuotedIdentifiers());

            t_Log.debug("storesMixedCaseIdentifiers():" + metaData.storesMixedCaseIdentifiers());

            t_Log.debug("storesMixedCaseQuotedIdentifiers():" + metaData.storesMixedCaseQuotedIdentifiers());

            t_Log.debug("storesUpperCaseIdentifiers():" + metaData.storesUpperCaseIdentifiers());

            t_Log.debug("storesUpperCaseQuotedIdentifiers():" + metaData.storesUpperCaseQuotedIdentifiers());

            t_Log.debug("supportsAlterTableWithAddColumn():" + metaData.supportsAlterTableWithAddColumn());

            t_Log.debug("supportsAlterTableWithDropColumn():" + metaData.supportsAlterTableWithDropColumn());

            t_Log.debug("supportsANSI92EntryLevelSQL():" + metaData.supportsANSI92EntryLevelSQL());

            t_Log.debug("supportsANSI92FullSQL():" + metaData.supportsANSI92FullSQL());

            t_Log.debug("supportsANSI92IntermediateSQL():" + metaData.supportsANSI92IntermediateSQL());

            t_Log.debug("supportsBatchUpdates():" + metaData.supportsBatchUpdates());

            t_Log.debug(
                    "supportsCatalogsInDataManipulation():" + metaData.supportsCatalogsInDataManipulation());

            t_Log.debug(
                    "supportsCatalogsInIndexDefinitions():" + metaData.supportsCatalogsInIndexDefinitions());

            t_Log.debug("supportsCatalogsInPrivilegeDefinitions():"
                    + metaData.supportsCatalogsInPrivilegeDefinitions());

            t_Log.debug("supportsCatalogsInProcedureCalls():" + metaData.supportsCatalogsInProcedureCalls());

            t_Log.debug(
                    "supportsCatalogsInTableDefinitions():" + metaData.supportsCatalogsInTableDefinitions());

            t_Log.debug("supportsColumnAliasing():" + metaData.supportsColumnAliasing());

            t_Log.debug("supportsConvert():" + metaData.supportsConvert());

            t_Log.debug("supportsCoreSQLGrammar():" + metaData.supportsCoreSQLGrammar());

            t_Log.debug("supportsCorrelatedSubqueries():" + metaData.supportsCorrelatedSubqueries());

            t_Log.debug("supportsDataDefinitionAndDataManipulationTransactions():"
                    + metaData.supportsDataDefinitionAndDataManipulationTransactions());

            t_Log.debug("supportsDataManipulationTransactionsOnly():"
                    + metaData.supportsDataManipulationTransactionsOnly());

            t_Log.debug("supportsDifferentTableCorrelationNames():"
                    + metaData.supportsDifferentTableCorrelationNames());

            t_Log.debug("supportsExpressionsInOrderBy():" + metaData.supportsExpressionsInOrderBy());

            t_Log.debug("supportsExtendedSQLGrammar():" + metaData.supportsExtendedSQLGrammar());

            t_Log.debug("supportsFullOuterJoins():" + metaData.supportsFullOuterJoins());

            String t_strSupportsGetGeneratedKeys = Boolean.FALSE.toString();

            try {
                t_strSupportsGetGeneratedKeys = "" + metaData.supportsGetGeneratedKeys();
            } catch (@NotNull final SQLException sqlException) {
                t_strSupportsGetGeneratedKeys += sqlException.getMessage();
            }

            t_Log.debug("supportsGetGeneratedKeys():" + t_strSupportsGetGeneratedKeys);

            t_Log.debug("supportsGroupBy():" + metaData.supportsGroupBy());

            t_Log.debug("supportsGroupByBeyondSelect():" + metaData.supportsGroupByBeyondSelect());

            t_Log.debug("supportsGroupByUnrelated():" + metaData.supportsGroupByUnrelated());

            t_Log.debug("supportsIntegrityEnhancementFacility():"
                    + metaData.supportsIntegrityEnhancementFacility());

            t_Log.debug("supportsLikeEscapeClause():" + metaData.supportsLikeEscapeClause());

            t_Log.debug("supportsLimitedOuterJoins():" + metaData.supportsLimitedOuterJoins());

            t_Log.debug("supportsMinimumSQLGrammar():" + metaData.supportsMinimumSQLGrammar());

            t_Log.debug("supportsMixedCaseIdentifiers():" + metaData.supportsMixedCaseIdentifiers());

            t_Log.debug(
                    "supportsMixedCaseQuotedIdentifiers():" + metaData.supportsMixedCaseQuotedIdentifiers());

            /*
             * Fails in MySQL 3.23.53 with a java.lang.AbstractMethodError
             * com.mysql.jdbc.jdbc2.DatabaseMetaData.supportsMultipleOpenResults()
             t_Log.debug(
               "supportsMultipleOpenResults():"
             + metaData.supportsMultipleOpenResults());
             */

            t_Log.debug("supportsMultipleResultSets():" + metaData.supportsMultipleResultSets());

            t_Log.debug("supportsMultipleTransactions():" + metaData.supportsMultipleTransactions());

            /*
             * Fails in MySQL 3.23.53 with a java.lang.AbstractMethodError
             * com.mysql.jdbc.jdbc2.DatabaseMetaData.supportsNamedParameters()
             t_Log.debug(
               "supportsNamedParameters():"
             + metaData.supportsNamedParameters());
             */

            t_Log.debug("supportsNonNullableColumns():" + metaData.supportsNonNullableColumns());

            t_Log.debug("supportsOpenCursorsAcrossCommit():" + metaData.supportsOpenCursorsAcrossCommit());

            t_Log.debug("supportsOpenCursorsAcrossRollback():" + metaData.supportsOpenCursorsAcrossRollback());

            t_Log.debug(
                    "supportsOpenStatementsAcrossCommit():" + metaData.supportsOpenStatementsAcrossCommit());

            t_Log.debug("supportsOpenStatementsAcrossRollback():"
                    + metaData.supportsOpenStatementsAcrossRollback());

            t_Log.debug("supportsOrderByUnrelated():" + metaData.supportsOrderByUnrelated());

            t_Log.debug("supportsOuterJoins():" + metaData.supportsOuterJoins());

            t_Log.debug("supportsPositionedDelete():" + metaData.supportsPositionedDelete());

            t_Log.debug("supportsPositionedUpdate():" + metaData.supportsPositionedUpdate());

            t_Log.debug("supportsResultSetConcurrency(TYPE_FORWARD_ONLY,CONCUR_READ_ONLY):" + metaData
                    .supportsResultSetConcurrency(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY));

            t_Log.debug("supportsResultSetConcurrency(TYPE_FORWARD_ONLY,CONCUR_UPDATABLE):" + metaData
                    .supportsResultSetConcurrency(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE));

            t_Log.debug("supportsResultSetConcurrency(TYPE_SCROLL_INSENSITIVE,CONCUR_READ_ONLY):"
                    + metaData.supportsResultSetConcurrency(ResultSet.TYPE_SCROLL_INSENSITIVE,
                            ResultSet.CONCUR_READ_ONLY));

            t_Log.debug("supportsResultSetConcurrency(TYPE_SCROLL_INSENSITIVE,CONCUR_UPDATABLE):"
                    + metaData.supportsResultSetConcurrency(ResultSet.TYPE_SCROLL_INSENSITIVE,
                            ResultSet.CONCUR_UPDATABLE));

            t_Log.debug("supportsResultSetConcurrency(TYPE_SCROLL_SENSITIVE,CONCUR_READ_ONLY):" + metaData
                    .supportsResultSetConcurrency(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY));

            t_Log.debug("supportsResultSetConcurrency(TYPE_SCROLL_SENSITIVE,CONCUR_UPDATABLE):" + metaData
                    .supportsResultSetConcurrency(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE));

            /*
             * Fails in MySQL 3.23.53 with a java.lang.AbstractMethodError
             * com.mysql.jdbc.jdbc2.DatabaseMetaData.supportsResultSetHoldability()
             t_Log.debug(
               "supportsResultSetHoldability("
             +     "HOLD_CURSORS_OVER_COMMIT):"
             + metaData.supportsResultSetHoldability(
             ResultSet.HOLD_CURSORS_OVER_COMMIT));
                    
             t_Log.debug(
               "supportsResultSetHoldability("
             +     "CLOSE_CURSORS_AT_COMMIT):"
             + metaData.supportsResultSetHoldability(
             ResultSet.CLOSE_CURSORS_AT_COMMIT));
             */

            t_Log.debug("supportsResultSetType(TYPE_FORWARD_ONLY):"
                    + metaData.supportsResultSetType(ResultSet.TYPE_FORWARD_ONLY));

            t_Log.debug("supportsResultSetType(ResultSet.TYPE_SCROLL_INSENSITIVE):"
                    + metaData.supportsResultSetType(ResultSet.TYPE_SCROLL_INSENSITIVE));

            t_Log.debug("supportsResultSetType(TYPE_SCROLL_SENSITIVE):"
                    + metaData.supportsResultSetType(ResultSet.TYPE_SCROLL_SENSITIVE));

            /*
             * Fails in MySQL 3.23.53 with a java.lang.AbstractMethodError
             * com.mysql.jdbc.jdbc2.DatabaseMetaData.supportsSavePoints()
             t_Log.debug(
               "supportsSavepoints():"
             + metaData.supportsSavepoints());
             */

            t_Log.debug("supportsSchemasInDataManipulation():" + metaData.supportsSchemasInDataManipulation());

            t_Log.debug("supportsSchemasInIndexDefinitions():" + metaData.supportsSchemasInIndexDefinitions());

            t_Log.debug("supportsSchemasInPrivilegeDefinitions():"
                    + metaData.supportsSchemasInPrivilegeDefinitions());

            t_Log.debug("supportsSchemasInProcedureCalls():" + metaData.supportsSchemasInProcedureCalls());

            t_Log.debug("supportsSchemasInTableDefinitions():" + metaData.supportsSchemasInTableDefinitions());

            t_Log.debug("supportsSelectForUpdate():" + metaData.supportsSelectForUpdate());

            /*
             * Fails in MySQL 3.23.53 with a java.lang.AbstractMethodError
             * com.mysql.jdbc.jdbc2.DatabaseMetaData.supportsStatementPooling()
             t_Log.debug(
               "supportsStatementPooling():"
             + metaData.supportsStatementPooling());
            */

            t_Log.debug("supportsStoredProcedures():" + metaData.supportsStoredProcedures());

            t_Log.debug("supportsSubqueriesInComparisons():" + metaData.supportsSubqueriesInComparisons());

            t_Log.debug("supportsSubqueriesInExists():" + metaData.supportsSubqueriesInExists());

            t_Log.debug("supportsSubqueriesInIns():" + metaData.supportsSubqueriesInIns());

            t_Log.debug("supportsSubqueriesInQuantifieds():" + metaData.supportsSubqueriesInQuantifieds());

            t_Log.debug("supportsTableCorrelationNames():" + metaData.supportsTableCorrelationNames());

            t_Log.debug("supportsTransactionIsolationLevel(TRANSACTION_NONE):"
                    + metaData.supportsTransactionIsolationLevel(Connection.TRANSACTION_NONE));

            t_Log.debug("supportsTransactionIsolationLevel(TRANSACTION_READ_COMMITTED):"
                    + metaData.supportsTransactionIsolationLevel(Connection.TRANSACTION_READ_COMMITTED));

            t_Log.debug("supportsTransactionIsolationLevel(TRANSACTION_READ_UNCOMMITTED):"
                    + metaData.supportsTransactionIsolationLevel(Connection.TRANSACTION_READ_UNCOMMITTED));

            t_Log.debug("supportsTransactionIsolationLevel(TRANSACTION_REPEATABLE_READ):"
                    + metaData.supportsTransactionIsolationLevel(Connection.TRANSACTION_REPEATABLE_READ));

            t_Log.debug("supportsTransactionIsolationLevel(TRANSACTION_SERIALIZABLE):"
                    + metaData.supportsTransactionIsolationLevel(Connection.TRANSACTION_SERIALIZABLE));

            t_Log.debug("supportsTransactions():" + metaData.supportsTransactions());

            t_Log.debug("supportsUnion():" + metaData.supportsUnion());

            t_Log.debug("supportsUnionAll():" + metaData.supportsUnionAll());

            t_Log.debug("updatesAreDetected(TYPE_FORWARD_ONLY):"
                    + metaData.updatesAreDetected(ResultSet.TYPE_FORWARD_ONLY));

            t_Log.debug("updatesAreDetected(TYPE_SCROLL_INSENSITIVE):"
                    + metaData.updatesAreDetected(ResultSet.TYPE_SCROLL_INSENSITIVE));

            t_Log.debug("updatesAreDetected(" + "TYPE_SCROLL_SENS):"
                    + metaData.updatesAreDetected(ResultSet.TYPE_SCROLL_SENSITIVE));

            t_Log.debug("usesLocalFilePerTable():" + metaData.usesLocalFilePerTable());

            t_Log.debug("usesLocalFiles():" + metaData.usesLocalFiles());
        }
    } catch (@NotNull final SQLException sqlException) {
        t_Log.error("Database metadata request failed.", sqlException);
    }

    return result;
}

From source file:com.couchbase.CBConnection.java

/**
 * Attempts to change the transaction isolation level for this
 * <code>Connection</code> object to the one given.
 * The constants defined in the interface <code>Connection</code>
 * are the possible transaction isolation levels.
 * <p/>//from w w  w  .  j a  v a2s  . c  om
 * <B>Note:</B> If this method is called during a transaction, the result
 * is implementation-defined.
 *
 * @param level one of the following <code>Connection</code> constants:
 *              <code>Connection.TRANSACTION_READ_UNCOMMITTED</code>,
 *              <code>Connection.TRANSACTION_READ_COMMITTED</code>,
 *              <code>Connection.TRANSACTION_REPEATABLE_READ</code>, or
 *              <code>Connection.TRANSACTION_SERIALIZABLE</code>.
 *              (Note that <code>Connection.TRANSACTION_NONE</code> cannot be used
 *              because it specifies that transactions are not supported.)
 * @throws java.sql.SQLException if a database access error occurs, this
 *                               method is called on a closed connection
 *                               or the given parameter is not one of the <code>Connection</code>
 *                               constants
 * @see java.sql.DatabaseMetaData#supportsTransactionIsolationLevel
 * @see #getTransactionIsolation
 */
@Override
public void setTransactionIsolation(int level) throws SQLException {
    checkClosed();

    switch (level) {
    case Connection.TRANSACTION_NONE:
    case Connection.TRANSACTION_READ_UNCOMMITTED:
    case Connection.TRANSACTION_READ_COMMITTED:
    case Connection.TRANSACTION_REPEATABLE_READ:
    case Connection.TRANSACTION_SERIALIZABLE:
        break;
    default:
        throw new SQLException("transaction level " + level + " not allowed ");
    }

}

From source file:org.wso2.carbon.repository.core.jdbc.dao.JDBCResourceVersionDAO.java

public String[] getChildPaths(ResourceIDImpl resourceID, VersionRetriever versionRetriever,
        int parentVersionIndex, int start, int pageLen, long snapshotID, DataAccessManager dataAccessManager)
        throws RepositoryException {
    String[] childPaths = null;/*from   w  w  w . ja  v  a2s . co m*/

    if (Transaction.isStarted()) {
        childPaths = getChildPaths(resourceID, versionRetriever, parentVersionIndex, start, pageLen, snapshotID,
                JDBCDatabaseTransaction.getConnection());

    } else {
        Connection conn = null;
        boolean transactionSucceeded = false;

        try {
            conn = ((JDBCDataAccessManager) dataAccessManager).getDataSource().getConnection();

            // If a managed connection already exists, use that instead of a new connection.
            JDBCDatabaseTransaction.ManagedRegistryConnection temp = JDBCDatabaseTransaction
                    .getManagedRegistryConnection(conn);

            if (temp != null) {
                conn.close();
                conn = temp;
            }

            if (conn.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) {
                conn.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
            }

            conn.setAutoCommit(false);

            childPaths = getChildPaths(resourceID, versionRetriever, parentVersionIndex, start, pageLen,
                    snapshotID, conn);
            transactionSucceeded = true;
        } catch (SQLException e) {
            String msg = "Failed to get the child paths " + pageLen + " child paths from " + start
                    + " of resource " + resourceID.getPath() + ". " + e.getMessage();
            log.error(msg, e);
            throw new RepositoryDBException(msg, e);
        } finally {
            if (transactionSucceeded) {
                try {
                    conn.commit();
                } catch (SQLException e) {
                    log.error("Failed to commit the database connection used in "
                            + "getting child paths of the collection " + resourceID.getPath());
                }
            } else if (conn != null) {
                try {
                    conn.rollback();
                } catch (SQLException e) {
                    log.error("Failed to rollback the database connection used in "
                            + "getting child paths of the collection " + resourceID.getPath());
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    log.error("Failed to close the database connection used in "
                            + "getting child paths of collection " + resourceID.getPath());
                }
            }
        }
    }
    return childPaths;
}

From source file:org.wso2.carbon.registry.core.jdbc.dao.JDBCResourceVersionDAO.java

public String[] getChildPaths(ResourceIDImpl resourceID, VersionRetriever versionRetriever,
        int parentVersionIndex, int start, int pageLen, long snapshotID, DataAccessManager dataAccessManager)
        throws RegistryException {
    String[] childPaths = null;//from  w w  w . j  a  va 2s .  c o m

    if (Transaction.isStarted()) {
        childPaths = getChildPaths(resourceID, versionRetriever, parentVersionIndex, start, pageLen, snapshotID,
                JDBCDatabaseTransaction.getConnection());

    } else {

        Connection conn = null;
        boolean transactionSucceeded = false;
        try {
            conn = ((JDBCDataAccessManager) dataAccessManager).getDataSource().getConnection();

            // If a managed connection already exists, use that instead of a new connection.
            JDBCDatabaseTransaction.ManagedRegistryConnection temp = JDBCDatabaseTransaction
                    .getManagedRegistryConnection(conn);
            if (temp != null) {
                conn.close();
                conn = temp;
            }
            if (conn.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) {
                conn.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
            }
            conn.setAutoCommit(false);

            childPaths = getChildPaths(resourceID, versionRetriever, parentVersionIndex, start, pageLen,
                    snapshotID, conn);
            transactionSucceeded = true;
        } catch (SQLException e) {

            String msg = "Failed to get the child paths " + pageLen + " child paths from " + start
                    + " of resource " + resourceID.getPath() + ". " + e.getMessage();
            log.error(msg, e);
            throw new RegistryException(msg, e);

        } finally {
            if (transactionSucceeded) {
                try {
                    conn.commit();
                } catch (SQLException e) {
                    log.error("Failed to commit the database connection used in "
                            + "getting child paths of the collection " + resourceID.getPath());
                }
            } else if (conn != null) {
                try {
                    conn.rollback();
                } catch (SQLException e) {
                    log.error("Failed to rollback the database connection used in "
                            + "getting child paths of the collection " + resourceID.getPath());
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    log.error("Failed to close the database connection used in "
                            + "getting child paths of collection " + resourceID.getPath());
                }
            }
        }
    }
    return childPaths;
}

From source file:org.apache.hadoop.hive.metastore.txn.TxnHandler.java

@Override
@RetrySemantics.ReadOnly//from w  w  w. j  a v  a 2  s  .  c  om
public GetOpenTxnsResponse getOpenTxns() throws MetaException {
    try {
        // We need to figure out the current transaction number and the list of
        // open transactions.  To avoid needing a transaction on the underlying
        // database we'll look at the current transaction number first.  If it
        // subsequently shows up in the open list that's ok.
        Connection dbConn = null;
        Statement stmt = null;
        ResultSet rs = null;
        try {
            /**
             * This runs at READ_COMMITTED for exactly the same reason as {@link #getOpenTxnsInfo()}
             */
            dbConn = getDbConn(Connection.TRANSACTION_READ_COMMITTED);
            stmt = dbConn.createStatement();
            String s = "select ntxn_next - 1 from NEXT_TXN_ID";
            LOG.debug("Going to execute query <" + s + ">");
            rs = stmt.executeQuery(s);
            if (!rs.next()) {
                throw new MetaException(
                        "Transaction tables not properly " + "initialized, no record found in next_txn_id");
            }
            long hwm = rs.getLong(1);
            if (rs.wasNull()) {
                throw new MetaException(
                        "Transaction tables not properly " + "initialized, null record found in next_txn_id");
            }
            close(rs);
            List<Long> openList = new ArrayList<Long>();
            //need the WHERE clause below to ensure consistent results with READ_COMMITTED
            s = "select txn_id, txn_state from TXNS where txn_id <= " + hwm + " order by txn_id";
            LOG.debug("Going to execute query<" + s + ">");
            rs = stmt.executeQuery(s);
            long minOpenTxn = Long.MAX_VALUE;
            BitSet abortedBits = new BitSet();
            while (rs.next()) {
                long txnId = rs.getLong(1);
                openList.add(txnId);
                char c = rs.getString(2).charAt(0);
                if (c == TXN_OPEN) {
                    minOpenTxn = Math.min(minOpenTxn, txnId);
                } else if (c == TXN_ABORTED) {
                    abortedBits.set(openList.size() - 1);
                }
            }
            LOG.debug("Going to rollback");
            dbConn.rollback();
            ByteBuffer byteBuffer = ByteBuffer.wrap(abortedBits.toByteArray());
            GetOpenTxnsResponse otr = new GetOpenTxnsResponse(hwm, openList, byteBuffer);
            if (minOpenTxn < Long.MAX_VALUE) {
                otr.setMin_open_txn(minOpenTxn);
            }
            return otr;
        } catch (SQLException e) {
            LOG.debug("Going to rollback");
            rollbackDBConn(dbConn);
            checkRetryable(dbConn, e, "getOpenTxns");
            throw new MetaException(
                    "Unable to select from transaction database, " + StringUtils.stringifyException(e));
        } finally {
            close(rs, stmt, dbConn);
        }
    } catch (RetryException e) {
        return getOpenTxns();
    }
}

From source file:org.hawkular.inventory.impl.tinkerpop.sql.impl.SqlGraph.java

private void ensureConnection() {
    if (connection == null) {
        try {//from   w  w  w  .ja  v a 2 s .c  o m
            connection = dataSource.getConnection();
            connection.setAutoCommit(false);
            connection.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
            Log.LOG.debugf("Opened connection %s", connection);
            statements = new Statements(this);
        } catch (SQLException e) {
            throw new SqlGraphException(e);
        }
    }
}