下面列出了java.sql.Connection#isReadOnly ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Reset the given Connection after a transaction,
* regarding read-only flag and isolation level.
* @param con the Connection to reset
* @param previousIsolationLevel the isolation level to restore, if any
* @see #prepareConnectionForTransaction
*/
public static void resetConnectionAfterTransaction(Connection con, @Nullable Integer previousIsolationLevel) {
Assert.notNull(con, "No Connection specified");
try {
// Reset transaction isolation to previous value, if changed for the transaction.
if (previousIsolationLevel != null) {
if (logger.isDebugEnabled()) {
logger.debug("Resetting isolation level of JDBC Connection [" +
con + "] to " + previousIsolationLevel);
}
con.setTransactionIsolation(previousIsolationLevel);
}
// Reset read-only flag.
if (con.isReadOnly()) {
if (logger.isDebugEnabled()) {
logger.debug("Resetting read-only flag of JDBC Connection [" + con + "]");
}
con.setReadOnly(false);
}
}
catch (Throwable ex) {
logger.debug("Could not reset JDBC Connection after transaction", ex);
}
}
/**
* @return a Connection instance that can be used to connect to the
* given database, if a previously-opened connection is available in
* the cache. Returns null if none is available in the map.
*/
public synchronized Connection getConnection(String connectStr,
String username) throws SQLException {
CacheKey key = new CacheKey(connectStr, username);
Connection cached = connectionMap.get(key);
if (null != cached) {
connectionMap.remove(key);
if (cached.isReadOnly()) {
// Read-only mode? Don't want it.
cached.close();
}
if (cached.isClosed()) {
// This connection isn't usable.
return null;
}
cached.rollback(); // Reset any transaction state.
cached.clearWarnings();
LOG.debug("Got cached connection for " + key);
}
return cached;
}
/**
* Reset the given Connection after a transaction,
* regarding read-only flag and isolation level.
* @param con the Connection to reset
* @param previousIsolationLevel the isolation level to restore, if any
* @see #prepareConnectionForTransaction
*/
public static void resetConnectionAfterTransaction(Connection con, Integer previousIsolationLevel) {
Assert.notNull(con, "No Connection specified");
try {
// Reset transaction isolation to previous value, if changed for the transaction.
if (previousIsolationLevel != null) {
if (logger.isDebugEnabled()) {
logger.debug("Resetting isolation level of JDBC Connection [" +
con + "] to " + previousIsolationLevel);
}
con.setTransactionIsolation(previousIsolationLevel);
}
// Reset read-only flag.
if (con.isReadOnly()) {
if (logger.isDebugEnabled()) {
logger.debug("Resetting read-only flag of JDBC Connection [" + con + "]");
}
con.setReadOnly(false);
}
}
catch (Throwable ex) {
logger.debug("Could not reset JDBC Connection after transaction", ex);
}
}
@Override
public void addTenantForSchema(String schemaName) {
addTenantForSchemaInternal(schemaName);
registerAllEntitiesWithEnhancer();
HibernateConnectionSource defaultConnectionSource = (HibernateConnectionSource) connectionSources.getDefaultConnectionSource();
DataSource dataSource = defaultConnectionSource.getDataSource();
if(dataSource instanceof TransactionAwareDataSourceProxy) {
dataSource = ((TransactionAwareDataSourceProxy) dataSource).getTargetDataSource();
}
Object existing = TransactionSynchronizationManager.getResource(dataSource);
if(existing instanceof ConnectionHolder) {
ConnectionHolder connectionHolder = (ConnectionHolder) existing;
Connection connection = connectionHolder.getConnection();
try {
if(!connection.isClosed() && !connection.isReadOnly()) {
schemaHandler.useDefaultSchema(connection);
}
} catch (SQLException e) {
throw new DatastoreConfigurationException("Failed to reset to default schema: " + e.getMessage(), e);
}
}
}
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);
}
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);
}
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);
}
/**
* Put the Connection in auto-commit mode and in read only false
*
* @param connection
* the JDBC Connection to init
* @throws SQLException
* if any SQL Exception occurs
*/
public static void connectionInit(Connection connection)
throws SQLException {
// Make sure Connection extracted from the pool is always on autocommit
// mode
// This avoid for client side to send a connection.getAutoCommit()
// before
// starting working.
// This is anyway mandatory for C# as all Connections are per default
// auto commit mode.
if (!connection.getAutoCommit()) {
connection.rollback();
connection.setAutoCommit(true);
}
// Make sure we are not in read only. Don't trap Exception because of
// Drivers not supporting this call
if (connection.isReadOnly()) {
try {
connection.setReadOnly(false);
} catch (Exception e) {
// Ignore
System.err.println(e.toString());
}
}
}
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);
}
final void openRealConnection() throws SQLException {
Connection rc = dataSource.getConnection(username, password, requestPassword);
this.realConnection = (EmbedConnection) rc;
defaultIsolationLevel = rc.getTransactionIsolation();
defaultReadOnly = rc.isReadOnly();
if (currentConnectionHandle != null)
realConnection.setApplicationConnection(currentConnectionHandle);
}
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);
}
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);
}
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);
}
public synchronized int prepare(Xid xid) {
Connection connection = this.managedConnection.getPhysicalConnection();
try {
if (connection.isReadOnly()) {
connection.setAutoCommit(originalAutoCommit);
return XAResource.XA_RDONLY;
}
} catch (Exception ex) {
logger.debug("Error occurred while preparing local-xa-resource: {}", ex.getMessage());
}
return XAResource.XA_OK;
}
private void close(Connection conn) throws SQLException {
if (conn != null) {
if (conn.isReadOnly()) {
conn.setReadOnly(false); // restore NOT readOnly before return to pool
}
conn.close();
}
}
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);
}
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);
}
final void openRealConnection() throws SQLException {
Connection rc = dataSource.getConnection(username, password, requestPassword);
this.realConnection = (EmbedConnection) rc;
defaultIsolationLevel = rc.getTransactionIsolation();
defaultReadOnly = rc.isReadOnly();
if (currentConnectionHandle != null)
realConnection.setApplicationConnection(currentConnectionHandle);
}
/**
* Revert the properties to their values prior to the setUp call.
*/
protected void tearDown()
throws java.lang.Exception
{
Connection conn = getConnection();
try {
clearProperties(conn);
} catch (SQLException sqle) {
// To try to prevent the error situation of DERBY-5686, which
// cascades to many test failures, catch ERROR 25502, and if it occurs
// try to gather some information, close the connection,
// and retry the clearing of the properties on a new connection
if (sqle.getSQLState().equals("25502")) {
// firstly, check on the state of the connection when we
// get this error
System.out.println("Apparently this is a read-only connection in teardown()? Get some data:");
System.out.println("conn.isClosed: " + conn.isClosed());
System.out.println("conn.isReadOnly: " + conn.isReadOnly());
System.out.println("conn.getHoldability: " + conn.getHoldability());
System.out.println("conn.getTransactionIsolation: " + conn.getTransactionIsolation());
System.out.println("conn.getAutoCommit: " + conn.getAutoCommit());
// now try to close the connection, then try open a new one,
// and try to executeUpdate again.
try {
conn.close();
} catch (SQLException isqle) {
if (sqle.getSQLState()=="25001")
{
// the transaction is still active. let's commit what we have.
conn.commit();
conn.close();
} else {
System.out.println("close failed - see SQLState.");
throw sqle;
}
}
Connection conn2 = getConnection();
// check if this second connection is read-only
if (conn2.isReadOnly())
{
System.out.println("Sorry, conn2 is also read-only, won't retry");
// give up
throw sqle;
}
else
{
// retry
System.out.println("retrying clearing the Properties");
clearProperties(conn2);
}
}
else if(!sqle.getSQLState().equals(SQLStateConstants.PROPERTY_UNSUPPORTED_CHANGE))
throw sqle;
}
// and then reset nay old values which will cause the commit.
setProperties(oldValues);
super.tearDown();
newValues = null;
oldValues = null;
if (staticProperties) {
TestConfiguration.getCurrent().shutdownDatabase();
}
}
public void testReadOnly56() throws Exception {
if (!versionMeetsMinimum(5, 6, 5)) {
return;
}
try {
Connection notLocalState = getConnectionWithProps("profileSQL=true");
for (int i = 0; i < 2; i++) {
StandardLogger.startLoggingToBuffer();
notLocalState.setReadOnly(true);
assertTrue(StandardLogger.getBuffer().toString().indexOf("set session transaction read only") != -1);
notLocalState.createStatement().execute("set session transaction read write");
assertFalse(notLocalState.isReadOnly());
}
for (int i = 0; i < 2; i++) {
StandardLogger.startLoggingToBuffer();
notLocalState.setReadOnly(false);
assertTrue(StandardLogger.getBuffer().toString().indexOf("set session transaction read write") != -1);
notLocalState.createStatement().execute("set session transaction read only");
assertTrue(notLocalState.isReadOnly());
}
Connection localState = getConnectionWithProps("profileSQL=true,useLocalSessionState=true");
String s = versionMeetsMinimum(8, 0, 3) ? "@@session.transaction_read_only" : "@@session.tx_read_only";
for (int i = 0; i < 2; i++) {
StandardLogger.startLoggingToBuffer();
localState.setReadOnly(true);
if (i == 0) {
assertTrue(StandardLogger.getBuffer().toString().indexOf("set session transaction read only") != -1);
} else {
assertTrue(StandardLogger.getBuffer().toString().indexOf("set session transaction read only") == -1);
}
StandardLogger.startLoggingToBuffer();
localState.isReadOnly();
assertTrue(StandardLogger.getBuffer().toString().indexOf("select @@session." + s) == -1);
}
Connection noOptimization = getConnectionWithProps("profileSQL=true,readOnlyPropagatesToServer=false");
for (int i = 0; i < 2; i++) {
StandardLogger.startLoggingToBuffer();
noOptimization.setReadOnly(true);
assertTrue(StandardLogger.getBuffer().toString().indexOf("set session transaction read only") == -1);
StandardLogger.startLoggingToBuffer();
noOptimization.isReadOnly();
assertTrue(StandardLogger.getBuffer().toString().indexOf("select @@session." + s) == -1);
}
} finally {
StandardLogger.dropBuffer();
}
}