Java Code Examples for java.sql.Connection#getTransactionIsolation()

The following examples show how to use java.sql.Connection#getTransactionIsolation() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DistributedSQLTestBase.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
/**
 * execute with retries in case of node failures for transactions but not for
 * non-transactional case
 */
protected static int executeUpdate(Statement stmt, String sql)
    throws SQLException {
  while (true) {
    try {
      if (sql != null) {
        return stmt.executeUpdate(sql);
      }
      else {
        return ((PreparedStatement)stmt).executeUpdate();
      }
    } catch (SQLException sqle) {
      Connection conn = stmt.getConnection();
      if (conn.getTransactionIsolation() == Connection.TRANSACTION_NONE) {
        throw sqle;
      }
      String sqlState = sqle.getSQLState();
      if (!"40XD0".equals(sqlState) && !"40XD2".equals(sqlState)) {
        throw sqle;
      }
    }
  }
}
 
Example 2
Source File: ACIDReadModifyWriteDefaultIsolationLevelTest.java    From high-performance-java-persistence with Apache License 2.0 6 votes vote down vote up
private void printIsolationLevel(Connection connection) throws SQLException {
    int isolationLevelIntegerValue = connection.getTransactionIsolation();

    String isolationLevelStringValue = null;

    switch (isolationLevelIntegerValue) {
        case Connection.TRANSACTION_READ_UNCOMMITTED:
            isolationLevelStringValue = "READ_UNCOMMITTE";
            break;
        case Connection.TRANSACTION_READ_COMMITTED:
            isolationLevelStringValue = "READ_COMMITTED";
            break;
        case Connection.TRANSACTION_REPEATABLE_READ:
            isolationLevelStringValue = "REPEATABLE_READ";
            break;
        case Connection.TRANSACTION_SERIALIZABLE:
            isolationLevelStringValue = "SERIALIZABLE";
            break;
    }

    LOGGER.info("Transaction isolation level: {}", isolationLevelStringValue);
}
 
Example 3
Source File: J2EEDataSourceTest.java    From spliceengine with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Checks locks for designated isolation level on the connection.
 * Currently only supports TRANSACTION_READ_COMMITTED and 
 * TRANSACTION_READ_UNCOMMITTED
 * @param conn   Connection to test
 * @param expectedIsoLevel expected isolation level
 *
 */
private void assertIsoLocks(Connection conn, int expectedIsoLevel)
        throws SQLException {
    int conniso = conn.getTransactionIsolation();
    assertEquals(expectedIsoLevel, conniso);

    boolean selectTimedOut = selectTimesoutDuringUpdate(conn);
    // expect a lock timeout for READ_COMMITTED
    switch (conniso) {
        case Connection.TRANSACTION_READ_UNCOMMITTED:
            assertFalse(selectTimedOut); break;
        case Connection.TRANSACTION_READ_COMMITTED:
            assertTrue(selectTimedOut); break;
        default:
            System.out.println("No test support for isolation level");
    }
}
 
Example 4
Source File: ResultSetMiscTest.java    From spliceengine with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Setup up and run the auto-commit tests.
 * 
 * 
 *         
 * @throws SQLException
 */
public void testAutoCommit() throws SQLException {
    Connection conn = getConnection();
    Statement s = conn.createStatement();
    s.executeUpdate("create table AutoCommitTable (num int)");

    s.executeUpdate("insert into AutoCommitTable values (1)");
    s.executeUpdate("insert into AutoCommitTable values (2)");
    int isolation = conn.getTransactionIsolation();
    conn.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
    checkSingleRSAutoCommit(conn);
    checkSingleRSCloseCursorsAtCommit(conn);
    conn.setTransactionIsolation(isolation);
    s.executeUpdate("drop table AutoCommitTable");
    s.close();
}
 
Example 5
Source File: CacheSessionDataTest.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
/**
 * Utility that verifies that the isolation level reported by the client 
 * is the same as evaluating 'VALUES CURRENT ISOLATION' and getting the
 * isolation level from the EmbedConnection on the server.
 * @param c Connection to check
 * @throws java.sql.SQLException
 */
private void verifyCachedIsolation(Connection c) throws SQLException {
    final int clientInt = c.getTransactionIsolation();
    
    Statement s = createStatement();
    final IsoLevel serverSql = new IsoLevel(s.executeQuery(
            "SELECT * FROM ISOLATION_NAMES " +
            "WHERE SQLNAME = (VALUES CURRENT ISOLATION)"));
    
    final IsoLevel serverJdbc = new IsoLevel(s.executeQuery(
            "SELECT * FROM ISOLATION_NAMES " +
            "WHERE ISOLEVEL = GET_TRANSACTION_ISOLATION_JDBC()"));
    
    final IsoLevel client = new IsoLevel(s.executeQuery("SELECT * FROM " +
            "ISOLATION_NAMES WHERE ISOLEVEL = "+clientInt));
    s.getResultSet().close();
    s.close();
    assertEquals(serverSql, client);
    assertEquals(serverJdbc, client);
}
 
Example 6
Source File: SQLTxTest.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
protected void printIsolationLevel(Connection conn) {
  try {
  	int isolation = conn.getTransactionIsolation();
  	String isoLevel;
  	switch (isolation) {
  	case Connection.TRANSACTION_NONE:
  		isoLevel = "TRANSACTION_NONE";
  		break;
  	case Connection.TRANSACTION_READ_COMMITTED:
  		isoLevel = "TRANSACTION_READ_COMMITTED";
  		break;
  	case Connection.TRANSACTION_REPEATABLE_READ:
  		isoLevel = "TRANSACTION_REPEATABLE_READ";
  		break;
  	case Connection.TRANSACTION_SERIALIZABLE:
  		isoLevel = "TRANSACTION_SERIALIZABLE";
  		break;
 		default:
  			isoLevel = "unknown";    		    		
  	}
  	Log.getLogWriter().info("the connection isolation level is " + isoLevel);
  	java.sql.SQLWarning w =conn.getWarnings();
  	SQLHelper.printSQLWarning(w);
  } catch (SQLException se) {
  	
  }
}
 
Example 7
Source File: CacheSessionDataTest.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * Implementation of the SQL function GET_CYCLE_ISOLATION_JDBC.
 * Cycles the isolation level on the default Connection.
 * @return the new JDBC isolation level constant
 * @throws java.sql.SQLException
 */
public static int getCycleIsolationJDBC()
        throws SQLException {
    Connection c = DriverManager.getConnection("jdbc:default:connection");
    c.setTransactionIsolation(cycleIsolation().getIsoLevel());
    println("getCycleIsolationJDBC() -> "+c.getTransactionIsolation());
    return c.getTransactionIsolation();
}
 
Example 8
Source File: 1205753_EmbedPooledConnection_0_t.java    From coming with MIT License 5 votes vote down vote up
final void openRealConnection() throws SQLException {
	// first time we establish a connection
	Connection rc = dataSource.getConnection(username, password, requestPassword);
 
	this.realConnection = (EmbedConnection) rc;
	defaultIsolationLevel = rc.getTransactionIsolation();
	defaultReadOnly = rc.isReadOnly();
	if (currentConnectionHandle != null)
		realConnection.setApplicationConnection(currentConnectionHandle);
}
 
Example 9
Source File: 1205753_EmbedPooledConnection_0_s.java    From coming with MIT License 5 votes vote down vote up
final void openRealConnection() throws SQLException {
	// first time we establish a connection
	Connection rc = dataSource.getConnection(username, password, requestPassword);
 
	this.realConnection = (EmbedConnection) rc;
	defaultIsolationLevel = rc.getTransactionIsolation();
	defaultReadOnly = rc.isReadOnly();
	if (currentConnectionHandle != null)
		realConnection.setApplicationConnection(currentConnectionHandle);
}
 
Example 10
Source File: InternalCountRetriever.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
private Connection getDBConnection(boolean shouldApplyTransaction) throws SQLException, UserStoreException {

        Connection dbConnection = IdentityDatabaseUtil.getUserDBConnection();
        if (dbConnection == null) {
            throw new UserStoreException("Could not create a database connection to User database");
        }
        if (shouldApplyTransaction) {
            dbConnection.setAutoCommit(false);
            if (dbConnection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) {
                dbConnection.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
            }
        }
        return dbConnection;
    }
 
Example 11
Source File: ConnectionConcierge.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
public ConnectionConcierge(String name, Connection conn, boolean keepAlive) {
    _name = name + s_mgr.getNextId();
    _keepAlive = keepAlive;
    try {
        _autoCommit = conn.getAutoCommit();
        _isolationLevel = conn.getTransactionIsolation();
        _holdability = conn.getHoldability();
    } catch (SQLException e) {
        throw new CloudRuntimeException("Unable to get information from the connection object", e);
    }
    reset(conn);
}
 
Example 12
Source File: CacheSessionDataTest.java    From spliceengine with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Implementation of the SQL function GET_CYCLE_ISOLATION_JDBC.
 * Cycles the isolation level on the default Connection.
 * @return the new JDBC isolation level constant
 * @throws java.sql.SQLException
 */
public static int getCycleIsolationJDBC()
        throws SQLException {
    Connection c = DriverManager.getConnection("jdbc:default:connection");
    c.setTransactionIsolation(cycleIsolation().getIsoLevel());
    println("getCycleIsolationJDBC() -> "+c.getTransactionIsolation());
    return c.getTransactionIsolation();
}
 
Example 13
Source File: ConnectionConcierge.java    From cosmic with Apache License 2.0 5 votes vote down vote up
public ConnectionConcierge(final String name, final Connection conn, final boolean keepAlive) {
    _name = name + s_mgr.getNextId();
    _keepAlive = keepAlive;
    try {
        _autoCommit = conn.getAutoCommit();
        _isolationLevel = conn.getTransactionIsolation();
        _holdability = conn.getHoldability();
    } catch (final SQLException e) {
        throw new CloudRuntimeException("Unable to get information from the connection object", e);
    }
    reset(conn);
}
 
Example 14
Source File: SQLInstrumentQueryFactory.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
public int fillAndExecutePreparedInsertStatements(List pstmts, List stmts, int sid)
    throws SQLException {
  int numInstrumentsPerSector = SectorPrms.getNumInstrumentsPerSector();
  PreparedStatement pstmt = (PreparedStatement) pstmts.get(0);
  String stmt = (String)stmts.get(0);
  int results = 0;
  for (int i = 0; i < numInstrumentsPerSector; i++) {
    int id = sid * numInstrumentsPerSector + i; // unique
    String typeName = Instrument.getInstrument(id);
    pstmt.setString(1, typeName);
    pstmt.setInt(2, sid);
    //pstmt.setString(3, typeName);
    if (logQueries) {
      Log.getLogWriter().info("EXECUTING: " + stmt + " with id=" + typeName
         + " sector_id=" + sid);
    }
    results += positionQueryFactory.fillAndExecutePreparedInsertStatements(
        (List)pstmts.get(1), (List)stmts.get(1), id);
    pstmt.addBatch();
    results++;
  }
  pstmt.executeBatch();
  pstmt.clearBatch();
  Connection c = pstmt.getConnection();
  if (c.getTransactionIsolation() != Connection.TRANSACTION_NONE
      && SectorPrms.commitBatches()) {
    c.commit();
  }
  return results;
}
 
Example 15
Source File: ConnectionManagerForTests.java    From reladomo with Apache License 2.0 5 votes vote down vote up
private void setIsolationLevel(Connection connection)
{
    try
    {
        if (connection.getTransactionIsolation() != Connection.TRANSACTION_SERIALIZABLE)
        {
            connection.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
        }
    }
    catch (SQLException e)
    {
        throw new RuntimeException(e);
    }
}
 
Example 16
Source File: DalConnection.java    From das with Apache License 2.0 5 votes vote down vote up
public DalConnection(Connection conn, boolean master, String shardId, DbMeta meta) throws SQLException {
	this.oldIsolationLevel = conn.getTransactionIsolation();
	this.conn = conn;
	this.master = master;
	this.shardId = shardId;
	this.meta = meta;
	this.logger = DasConfigureFactory.getLogger();
}
 
Example 17
Source File: DatabaseUtil.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
public static Connection getDBConnection(DataSource dataSource) throws SQLException {
    Connection dbConnection = dataSource.getConnection();
    dbConnection.setAutoCommit(false);
    if (dbConnection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) {
        dbConnection.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
    }
    return dbConnection;
}
 
Example 18
Source File: DataSourceUtils.java    From micronaut-data with Apache License 2.0 4 votes vote down vote up
/**
 * Prepare the given Connection with the given transaction semantics.
 * @param con the Connection to prepare
 * @param definition the transaction definition to apply
 * @return the previous isolation level, if any
 * @throws SQLException if thrown by JDBC methods
 * @see #resetConnectionAfterTransaction
 */
@Nullable
public static TransactionDefinition.Isolation prepareConnectionForTransaction(Connection con, @Nullable TransactionDefinition definition)
        throws SQLException {

    Objects.requireNonNull(con, "No Connection specified");

    // Set read-only flag.
    if (definition != null && definition.isReadOnly()) {
        try {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Setting JDBC Connection [" + con + "] read-only");
            }
            con.setReadOnly(true);
        } catch (SQLException | RuntimeException ex) {
            Throwable exToCheck = ex;
            while (exToCheck != null) {
                if (exToCheck.getClass().getSimpleName().contains("Timeout")) {
                    // Assume it's a connection timeout that would otherwise get lost: e.g. from JDBC 4.0
                    throw ex;
                }
                exToCheck = exToCheck.getCause();
            }
            // "read-only not supported" SQLException -> ignore, it's just a hint anyway
            LOGGER.debug("Could not set JDBC Connection read-only", ex);
        }
    }

    // Apply specific isolation level, if any.
    TransactionDefinition.Isolation previousIsolationLevel = null;
    if (definition != null) {
        TransactionDefinition.Isolation isolationLevel = definition.getIsolationLevel();
        if (isolationLevel != TransactionDefinition.Isolation.DEFAULT) {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Changing isolation level of JDBC Connection [" + con + "] to " +
                        isolationLevel);
            }
            int currentIsolation = con.getTransactionIsolation();
            if (currentIsolation != isolationLevel.getCode()) {
                previousIsolationLevel = TransactionDefinition.Isolation.valueOf(currentIsolation);
                con.setTransactionIsolation(isolationLevel.getCode());
            }
        }
    }

    return previousIsolationLevel;
}
 
Example 19
Source File: LazyReplicationConnectionDataSourceProxy.java    From replication-datasource with Apache License 2.0 3 votes vote down vote up
/**
 * Check the default connection properties (auto-commit, transaction isolation),
 * keeping them to be able to expose them correctly without fetching an actual
 * JDBC Connection from the target DataSource.
 * <p>This will be invoked once on startup, but also for each retrieval of a
 * target Connection. If the check failed on startup (because the database was
 * down), we'll lazily retrieve those settings.
 *
 * @param con the Connection to use for checking
 * @throws SQLException if thrown by Connection methods
 */
protected synchronized void checkDefaultConnectionProperties(Connection con) throws SQLException {
    if (this.defaultAutoCommit == null) {
        this.defaultAutoCommit = con.getAutoCommit();
    }
    if (this.defaultTransactionIsolation == null) {
        this.defaultTransactionIsolation = con.getTransactionIsolation();
    }
}
 
Example 20
Source File: LazyConnectionDataSourceProxy.java    From spring-analysis-note with MIT License 3 votes vote down vote up
/**
 * Check the default connection properties (auto-commit, transaction isolation),
 * keeping them to be able to expose them correctly without fetching an actual
 * JDBC Connection from the target DataSource.
 * <p>This will be invoked once on startup, but also for each retrieval of a
 * target Connection. If the check failed on startup (because the database was
 * down), we'll lazily retrieve those settings.
 * @param con the Connection to use for checking
 * @throws SQLException if thrown by Connection methods
 */
protected synchronized void checkDefaultConnectionProperties(Connection con) throws SQLException {
	if (this.defaultAutoCommit == null) {
		this.defaultAutoCommit = con.getAutoCommit();
	}
	if (this.defaultTransactionIsolation == null) {
		this.defaultTransactionIsolation = con.getTransactionIsolation();
	}
}