Java Code Examples for java.sql.Connection.setReadOnly()

The following are Jave code examples for showing how to use setReadOnly() of the java.sql.Connection class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: the-vigilantes   File: ConnectionRegressionTest.java   View Source Code Vote up 7 votes
/**
 * Tests fix for BUG#11879 -- ReplicationConnection won't switch to slave,
 * throws "Catalog can't be null" exception.
 * 
 * @throws Exception
 *             if the test fails
 */
public void testBug11879() throws Exception {
    if (runMultiHostTests()) {
        Connection replConn = null;

        try {
            replConn = getMasterSlaveReplicationConnection();
            replConn.setReadOnly(true);
            replConn.setReadOnly(false);
        } finally {
            if (replConn != null) {
                replConn.close();
            }
        }
    }
}
 
Example 2
Project: BibliotecaPS   File: ConnectionRegressionTest.java   View Source Code Vote up 6 votes
/**
 * Tests fix for BUG#11879 -- ReplicationConnection won't switch to slave,
 * throws "Catalog can't be null" exception.
 * 
 * @throws Exception
 *             if the test fails
 */
public void testBug11879() throws Exception {
    if (runMultiHostTests()) {
        Connection replConn = null;

        try {
            replConn = getMasterSlaveReplicationConnection();
            replConn.setReadOnly(true);
            replConn.setReadOnly(false);
        } finally {
            if (replConn != null) {
                replConn.close();
            }
        }
    }
}
 
Example 3
Project: calcite-avatica   File: JdbcMeta.java   View Source Code Vote up 6 votes
protected void apply(Connection conn, ConnectionProperties connProps)
    throws SQLException {
  if (connProps.isAutoCommit() != null) {
    conn.setAutoCommit(connProps.isAutoCommit());
  }
  if (connProps.isReadOnly() != null) {
    conn.setReadOnly(connProps.isReadOnly());
  }
  if (connProps.getTransactionIsolation() != null) {
    conn.setTransactionIsolation(connProps.getTransactionIsolation());
  }
  if (connProps.getCatalog() != null) {
    conn.setCatalog(connProps.getCatalog());
  }
  if (connProps.getSchema() != null) {
    conn.setSchema(connProps.getSchema());
  }
}
 
Example 4
Project: uroborosql   File: JdbcConnectionSupplierImpl.java   View Source Code Vote up 6 votes
/**
 * {@inheritDoc}
 *
 * @see jp.co.future.uroborosql.connection.ConnectionSupplier#getConnection()
 */
@Override
public Connection getConnection() {
	try {
		String jdbcUrl = props.get(PROPS_JDBC_URL);
		String jdbcUser = props.get(PROPS_JDBC_USER);
		String jdbcPassword = props.get(PROPS_JDBC_PASSWORD);

		Connection connection = DriverManager.getConnection(jdbcUrl, jdbcUser, jdbcPassword);

		String schema = getSchema();
		if (schema != null) {
			connection.setSchema(schema);
		}
		connection.setAutoCommit(getAutoCommit());
		connection.setReadOnly(getReadOnly());
		int transactionIsolation = getTransactionIsolation();
		if (transactionIsolation > 0) {
			connection.setTransactionIsolation(transactionIsolation);
		}
		return connection;
	} catch (SQLException ex) {
		ex.printStackTrace();
		return null;
	}
}
 
Example 5
Project: lams   File: DataSourceUtils.java   View Source Code Vote up 6 votes
/**
 * 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);
	}
}
 
Example 6
Project: ProyectoPacientes   File: ReadOnlyCallableStatementTest.java   View Source Code Vote up 5 votes
public void testReadOnlyWithProcBodyAccess() throws Exception {
    if (versionMeetsMinimum(5, 0)) {
        Connection replConn = null;
        Properties props = getHostFreePropertiesFromTestsuiteUrl();
        props.setProperty("autoReconnect", "true");

        try {
            createProcedure("testProc1", "()\nREADS SQL DATA\nbegin\nSELECT NOW();\nend\n");

            createProcedure("`testProc.1`", "()\nREADS SQL DATA\nbegin\nSELECT NOW();\nend\n");

            replConn = getMasterSlaveReplicationConnection();
            replConn.setReadOnly(true);

            CallableStatement cstmt = replConn.prepareCall("CALL testProc1()");
            cstmt.execute();
            cstmt.execute();

            cstmt = replConn.prepareCall("CALL `" + replConn.getCatalog() + "`.testProc1()");
            cstmt.execute();

            cstmt = replConn.prepareCall("CALL `" + replConn.getCatalog() + "`.`testProc.1`()");
            cstmt.execute();

        } finally {

            if (replConn != null) {
                replConn.close();
            }
        }
    }
}
 
Example 7
Project: sstore-soft   File: ConnectionDefaults.java   View Source Code Vote up 5 votes
public void setDefaults(Connection connection) throws SQLException {

        connection.setHoldability(this.holdability);

        if (this.transactionIsolation != Connection.TRANSACTION_NONE) {
            connection.setTransactionIsolation(this.transactionIsolation);
        }
        connection.setAutoCommit(this.isAutoCommit);
        connection.setReadOnly(this.isReadOnly);
        connection.setCatalog(this.catalog);
    }
 
Example 8
Project: the-vigilantes   File: ReadOnlyCallableStatementTest.java   View Source Code Vote up 5 votes
public void testReadOnlyWithProcBodyAccess() throws Exception {
    if (versionMeetsMinimum(5, 0)) {
        Connection replConn = null;
        Properties props = getHostFreePropertiesFromTestsuiteUrl();
        props.setProperty("autoReconnect", "true");

        try {
            createProcedure("testProc1", "()\nREADS SQL DATA\nbegin\nSELECT NOW();\nend\n");

            createProcedure("`testProc.1`", "()\nREADS SQL DATA\nbegin\nSELECT NOW();\nend\n");

            replConn = getMasterSlaveReplicationConnection();
            replConn.setReadOnly(true);

            CallableStatement cstmt = replConn.prepareCall("CALL testProc1()");
            cstmt.execute();
            cstmt.execute();

            cstmt = replConn.prepareCall("CALL `" + replConn.getCatalog() + "`.testProc1()");
            cstmt.execute();

            cstmt = replConn.prepareCall("CALL `" + replConn.getCatalog() + "`.`testProc.1`()");
            cstmt.execute();

        } finally {

            if (replConn != null) {
                replConn.close();
            }
        }
    }
}
 
Example 9
Project: BibliotecaPS   File: ReadOnlyCallableStatementTest.java   View Source Code Vote up 5 votes
public void testReadOnlyWithProcBodyAccess() throws Exception {
    if (versionMeetsMinimum(5, 0)) {
        Connection replConn = null;
        Properties props = getHostFreePropertiesFromTestsuiteUrl();
        props.setProperty("autoReconnect", "true");

        try {
            createProcedure("testProc1", "()\nREADS SQL DATA\nbegin\nSELECT NOW();\nend\n");

            createProcedure("`testProc.1`", "()\nREADS SQL DATA\nbegin\nSELECT NOW();\nend\n");

            replConn = getMasterSlaveReplicationConnection();
            replConn.setReadOnly(true);

            CallableStatement cstmt = replConn.prepareCall("CALL testProc1()");
            cstmt.execute();
            cstmt.execute();

            cstmt = replConn.prepareCall("CALL `" + replConn.getCatalog() + "`.testProc1()");
            cstmt.execute();

            cstmt = replConn.prepareCall("CALL `" + replConn.getCatalog() + "`.`testProc.1`()");
            cstmt.execute();

        } finally {

            if (replConn != null) {
                replConn.close();
            }
        }
    }
}
 
Example 10
Project: spwrap   File: ConnectionProps.java   View Source Code Vote up 5 votes
public Boolean apply(Connection input, Object ... args) {
    if (!skip){
        log.debug("applying {} on input Connection", this);
        try {
            input.setReadOnly(this.readOnly);
            if (this.isolation != Isolation.DEFAULT){
                input.setTransactionIsolation(this.isolation.getValue());
            }
        } catch (SQLException e) {
            throw new CallException(e);
        }
        return true;
    }
    return false;
}
 
Example 11
Project: s-store   File: ConnectionDefaults.java   View Source Code Vote up 5 votes
public void setDefaults(Connection connection) throws SQLException {

        connection.setHoldability(this.holdability);

        if (this.transactionIsolation != Connection.TRANSACTION_NONE) {
            connection.setTransactionIsolation(this.transactionIsolation);
        }
        connection.setAutoCommit(this.isAutoCommit);
        connection.setReadOnly(this.isReadOnly);
        connection.setCatalog(this.catalog);
    }
 
Example 12
Project: BibliotecaPS   File: ConnectionRegressionTest.java   View Source Code Vote up 5 votes
public void testBug34937() throws Exception {
    com.mysql.jdbc.jdbc2.optional.MysqlConnectionPoolDataSource ds = new com.mysql.jdbc.jdbc2.optional.MysqlConnectionPoolDataSource();
    StringBuilder urlBuf = new StringBuilder();
    urlBuf.append(getMasterSlaveUrl());
    urlBuf.append("?");
    Properties props = getHostFreePropertiesFromTestsuiteUrl();
    String key = null;

    Enumeration<Object> keyEnum = props.keys();

    while (keyEnum.hasMoreElements()) {
        key = (String) keyEnum.nextElement();
        urlBuf.append(key);
        urlBuf.append("=");
        urlBuf.append(props.get(key));
        urlBuf.append("&");
    }

    String url = urlBuf.toString();
    url = "jdbc:mysql:replication:" + url.substring(url.indexOf("jdbc:mysql:") + "jdbc:mysql:".length());
    ds.setURL(url);
    Connection replConn = ds.getPooledConnection().getConnection();

    boolean readOnly = false;

    for (int i = 0; i < 10; i++) {
        this.rs = replConn.createStatement().executeQuery("SELECT 1");
        assertTrue(this.rs.next());
        this.rs = replConn.prepareStatement("SELECT 1").executeQuery();
        assertTrue(this.rs.next());
        readOnly = !readOnly;
        replConn.setReadOnly(readOnly);
    }
}
 
Example 13
Project: OpenVertretung   File: ConnectionRegressionTest.java   View Source Code Vote up 5 votes
public void testBug34937() throws Exception {
    com.mysql.jdbc.jdbc2.optional.MysqlConnectionPoolDataSource ds = new com.mysql.jdbc.jdbc2.optional.MysqlConnectionPoolDataSource();
    StringBuilder urlBuf = new StringBuilder();
    urlBuf.append(getMasterSlaveUrl());
    urlBuf.append("?");
    Properties props = getHostFreePropertiesFromTestsuiteUrl();
    String key = null;

    Enumeration<Object> keyEnum = props.keys();

    while (keyEnum.hasMoreElements()) {
        key = (String) keyEnum.nextElement();
        urlBuf.append(key);
        urlBuf.append("=");
        urlBuf.append(props.get(key));
        urlBuf.append("&");
    }

    String url = urlBuf.toString();
    url = "jdbc:mysql:replication:" + url.substring(url.indexOf("jdbc:mysql:") + "jdbc:mysql:".length());
    ds.setURL(url);
    Connection replConn = ds.getPooledConnection().getConnection();

    boolean readOnly = false;

    for (int i = 0; i < 10; i++) {
        this.rs = replConn.createStatement().executeQuery("SELECT 1");
        assertTrue(this.rs.next());
        this.rs = replConn.prepareStatement("SELECT 1").executeQuery();
        assertTrue(this.rs.next());
        readOnly = !readOnly;
        replConn.setReadOnly(readOnly);
    }
}
 
Example 14
Project: the-vigilantes   File: ConnectionTest.java   View Source Code Vote up 4 votes
public void testReadOnly56() throws Exception {
    if (versionMeetsMinimum(5, 6, 5)) {
        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 txReadOnlyName = versionMeetsMinimum(8, 0, 3) ? "transaction_read_only" : "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." + txReadOnlyName) == -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." + txReadOnlyName) == -1);
            }
        } finally {
            StandardLogger.dropBuffer();
        }
    }
}
 
Example 15
Project: the-vigilantes   File: ConnectionRegressionTest.java   View Source Code Vote up 4 votes
/**
 * Tests fix for BUG#15570 - ReplicationConnection incorrectly copies state,
 * doesn't transfer connection context correctly when transitioning between
 * the same read-only states.
 * 
 * (note, this test will fail if the test user doesn't have permission to
 * "USE 'mysql'".
 * 
 * @throws Exception
 *             if the test fails.
 */
public void testBug15570() throws Exception {
    Connection replConn = null;

    try {
        replConn = getMasterSlaveReplicationConnection();

        int masterConnectionId = Integer.parseInt(getSingleIndexedValueWithQuery(replConn, 1, "SELECT CONNECTION_ID()").toString());

        replConn.setReadOnly(false);

        assertEquals(masterConnectionId, Integer.parseInt(getSingleIndexedValueWithQuery(replConn, 1, "SELECT CONNECTION_ID()").toString()));

        String currentCatalog = replConn.getCatalog();

        replConn.setCatalog(currentCatalog);
        assertEquals(currentCatalog, replConn.getCatalog());

        replConn.setReadOnly(true);

        int slaveConnectionId = Integer.parseInt(getSingleIndexedValueWithQuery(replConn, 1, "SELECT CONNECTION_ID()").toString());

        // The following test is okay for now, as the chance of MySQL wrapping the connection id counter during our testsuite is very small.
        // As per Bug#21286268 fix a Replication connection first initializes the Slaves sub-connection, then the Masters.
        assertTrue("Master id " + masterConnectionId + " is not newer than slave id " + slaveConnectionId, masterConnectionId > slaveConnectionId);

        assertEquals(currentCatalog, replConn.getCatalog());

        String newCatalog = "mysql";

        replConn.setCatalog(newCatalog);
        assertEquals(newCatalog, replConn.getCatalog());

        replConn.setReadOnly(true);
        assertEquals(newCatalog, replConn.getCatalog());

        replConn.setReadOnly(false);
        assertEquals(masterConnectionId, Integer.parseInt(getSingleIndexedValueWithQuery(replConn, 1, "SELECT CONNECTION_ID()").toString()));
    } finally {
        if (replConn != null) {
            replConn.close();
        }
    }
}
 
Example 16
Project: ProyectoPacientes   File: ConnectionTest.java   View Source Code Vote up 4 votes
public void testReadOnly56() throws Exception {
    if (versionMeetsMinimum(5, 6, 5)) {
        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");

            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.tx_read_only") == -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.tx_read_only") == -1);
            }
        } finally {
            StandardLogger.dropBuffer();
        }
    }
}
 
Example 17
Project: the-vigilantes   File: StatementRegressionTest.java   View Source Code Vote up 4 votes
/**
 * Tests fix for Bug#81706 - NullPointerException in driver.
 */
public void testBug81706() throws Exception {
    boolean useSPS = false;
    boolean cacheRsMd = false;
    boolean readOnly = false;

    do {
        final String testCase = String.format("Case [SPS: %s, CacheRsMd: %s, Read-only: %s]", useSPS ? "Y" : "N", cacheRsMd ? "Y" : "N",
                readOnly ? "Y" : "N");

        Properties props = new Properties();
        props.setProperty("useServerPrepStmts", Boolean.toString(useSPS));
        props.setProperty("cacheResultSetMetadata", Boolean.toString(cacheRsMd));
        props.setProperty("statementInterceptors", TestBug81706StatementInterceptor.class.getName());

        Connection testConn = getConnectionWithProps(props);
        testConn.setReadOnly(readOnly);
        Statement testStmt;
        PreparedStatement testPstmt;

        TestBug81706StatementInterceptor.isActive = true;
        TestBug81706StatementInterceptor.testCase = testCase;

        // Statement.executeQuery();
        testStmt = testConn.createStatement();
        testStmt.setFetchSize(Integer.MIN_VALUE);
        testStmt.executeQuery("/* ping */");
        testStmt.close();

        // Statemente.execute();
        testStmt = testConn.createStatement();
        testStmt.setFetchSize(Integer.MIN_VALUE);
        testStmt.execute("/* ping */");
        testStmt.close();

        // PreparedStatement.executeQuery();
        testPstmt = testConn.prepareStatement("/* ping */");
        assertFalse(testCase + ": Not the right Statement type.", testPstmt instanceof ServerPreparedStatement);
        testPstmt.setFetchSize(Integer.MIN_VALUE);
        testPstmt.executeQuery();
        testPstmt.close();

        // PreparedStatement.execute();
        testPstmt = testConn.prepareStatement("/* ping */");
        assertFalse(testCase + ": Not the right Statement type.", testPstmt instanceof ServerPreparedStatement);
        testPstmt.setFetchSize(Integer.MIN_VALUE);
        testPstmt.execute();
        testPstmt.close();

        TestBug81706StatementInterceptor.isActive = false;
        testConn.close();

    } while ((useSPS = !useSPS) || (cacheRsMd = !cacheRsMd) || (readOnly = !readOnly)); // Cycle through all possible combinations.
}
 
Example 18
Project: s-store   File: ManagedPoolDataSource.java   View Source Code Vote up 4 votes
private Connection wrapConnectionAndMarkAsInUse(
        PooledConnection pooledConnection) throws SQLException {

    pooledConnection = assureValidConnection(pooledConnection);

    Connection conn = pooledConnection.getConnection();

    if (doResetAutoCommit) {
        conn.setAutoCommit(isAutoCommit);
    }

    if (doResetReadOnly) {
        conn.setReadOnly(isReadOnly);
    }

    if (doResetTransactionIsolation) {
        conn.setTransactionIsolation(transactionIsolation);
        /* TESING ONLY!!
        System.err.println("<<<<<<<<< ISO LVL => " + transactionIsolation
        + " >>>>>>>>>>>>");
        */
    }

    if (doResetCatalog) {
        conn.setCatalog(catalog);
        /* TESTING ONLY!
        System.err.println("<<<<<<<<< CAT => " + catalog
        + " >>>>>>>>>>>>");
        */
    }

    if (validationQuery != null) {

        // End-to-end test before return the Connection.
        java.sql.ResultSet rs = null;

        try {
            rs = conn.createStatement().executeQuery(validationQuery);

            if (!rs.next()) {
                throw new SQLException("0 rows returned");
            }
        } catch (SQLException se) {
            closePhysically(pooledConnection,
                            "Closing non-validating pooledConnection.");

            throw new SQLException("Validation query failed: "
                                   + se.getMessage());
        } finally {
            if (rs != null) {
                rs.close();
            }
        }
    }
    this.connectionsInUse.add(pooledConnection);

    SessionConnectionWrapper sessionWrapper =
        new SessionConnectionWrapper(pooledConnection.getConnection());

    this.sessionConnectionWrappers.put(pooledConnection, sessionWrapper);

    return sessionWrapper;
}
 
Example 19
Project: OpenVertretung   File: ConnectionTest.java   View Source Code Vote up 4 votes
public void testReadOnly56() throws Exception {
    if (versionMeetsMinimum(5, 6, 5)) {
        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 txReadOnlyName = versionMeetsMinimum(8, 0, 3) ? "transaction_read_only" : "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." + txReadOnlyName) == -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." + txReadOnlyName) == -1);
            }
        } finally {
            StandardLogger.dropBuffer();
        }
    }
}
 
Example 20
Project: BibliotecaPS   File: ConnectionRegressionTest.java   View Source Code Vote up 4 votes
/**
 * Tests fix for BUG#15570 - ReplicationConnection incorrectly copies state,
 * doesn't transfer connection context correctly when transitioning between
 * the same read-only states.
 * 
 * (note, this test will fail if the test user doesn't have permission to
 * "USE 'mysql'".
 * 
 * @throws Exception
 *             if the test fails.
 */
public void testBug15570() throws Exception {
    Connection replConn = null;

    try {
        replConn = getMasterSlaveReplicationConnection();

        int masterConnectionId = Integer.parseInt(getSingleIndexedValueWithQuery(replConn, 1, "SELECT CONNECTION_ID()").toString());

        replConn.setReadOnly(false);

        assertEquals(masterConnectionId, Integer.parseInt(getSingleIndexedValueWithQuery(replConn, 1, "SELECT CONNECTION_ID()").toString()));

        String currentCatalog = replConn.getCatalog();

        replConn.setCatalog(currentCatalog);
        assertEquals(currentCatalog, replConn.getCatalog());

        replConn.setReadOnly(true);

        int slaveConnectionId = Integer.parseInt(getSingleIndexedValueWithQuery(replConn, 1, "SELECT CONNECTION_ID()").toString());

        // The following test is okay for now, as the chance of MySQL wrapping the connection id counter during our testsuite is very small.
        // As per Bug#21286268 fix a Replication connection first initializes the Slaves sub-connection, then the Masters.
        assertTrue("Master id " + masterConnectionId + " is not newer than slave id " + slaveConnectionId, masterConnectionId > slaveConnectionId);

        assertEquals(currentCatalog, replConn.getCatalog());

        String newCatalog = "mysql";

        replConn.setCatalog(newCatalog);
        assertEquals(newCatalog, replConn.getCatalog());

        replConn.setReadOnly(true);
        assertEquals(newCatalog, replConn.getCatalog());

        replConn.setReadOnly(false);
        assertEquals(masterConnectionId, Integer.parseInt(getSingleIndexedValueWithQuery(replConn, 1, "SELECT CONNECTION_ID()").toString()));
    } finally {
        if (replConn != null) {
            replConn.close();
        }
    }
}