diff --git a/ebean-datasource-api/src/main/java/io/ebean/datasource/DataSourceConnection.java b/ebean-datasource-api/src/main/java/io/ebean/datasource/DataSourceConnection.java new file mode 100644 index 0000000..15a4f2a --- /dev/null +++ b/ebean-datasource-api/src/main/java/io/ebean/datasource/DataSourceConnection.java @@ -0,0 +1,16 @@ +package io.ebean.datasource; + +import java.sql.Connection; + +/** + * Interface for connection objects returned from the ebean-datasource connection pool + * + * @author Roland Praml, Foconis Analytics GmbH + */ +public interface DataSourceConnection extends Connection { + + /** + * Clears the prepared statement cache. + */ + void clearPreparedStatementCache(); +} diff --git a/ebean-datasource-api/src/main/java/io/ebean/datasource/DataSourcePoolListener.java b/ebean-datasource-api/src/main/java/io/ebean/datasource/DataSourcePoolListener.java index 5471c51..a025588 100644 --- a/ebean-datasource-api/src/main/java/io/ebean/datasource/DataSourcePoolListener.java +++ b/ebean-datasource-api/src/main/java/io/ebean/datasource/DataSourcePoolListener.java @@ -1,6 +1,7 @@ package io.ebean.datasource; import java.sql.Connection; +import java.sql.SQLException; /** @@ -17,11 +18,27 @@ public interface DataSourcePoolListener { /** * Called after a connection has been retrieved from the connection pool */ + default void onAfterBorrowConnection(DataSourcePool pool, DataSourceConnection connection) throws SQLException { + onAfterBorrowConnection(connection); + } + + /** + * @deprecated implement {@link #onAfterBorrowConnection(DataSourcePool, DataSourceConnection)} + */ + @Deprecated default void onAfterBorrowConnection(Connection connection) {} /** * Called before a connection will be put back to the connection pool */ + default void onBeforeReturnConnection(DataSourcePool pool, DataSourceConnection connection) { + onBeforeReturnConnection(connection); + } + + /** + * @deprecated implement {@link #onBeforeReturnConnection(DataSourcePool, DataSourceConnection)} + */ + @Deprecated default void onBeforeReturnConnection(Connection connection) {} diff --git a/ebean-datasource/src/main/java/io/ebean/datasource/pool/ConnectionDelegator.java b/ebean-datasource/src/main/java/io/ebean/datasource/pool/ConnectionDelegator.java index 6fd3a67..c25fbab 100644 --- a/ebean-datasource/src/main/java/io/ebean/datasource/pool/ConnectionDelegator.java +++ b/ebean-datasource/src/main/java/io/ebean/datasource/pool/ConnectionDelegator.java @@ -96,7 +96,7 @@ public final Struct createStruct(String typeName, Object[] attributes) throws SQ @SuppressWarnings("unchecked") @Override - public final T unwrap(Class iface) throws SQLException { + public T unwrap(Class iface) throws SQLException { if (iface.equals(java.sql.Connection.class)) { return (T) delegate; } @@ -104,7 +104,7 @@ public final T unwrap(Class iface) throws SQLException { } @Override - public final boolean isWrapperFor(Class iface) throws SQLException { + public boolean isWrapperFor(Class iface) throws SQLException { return delegate.isWrapperFor(iface); } } diff --git a/ebean-datasource/src/main/java/io/ebean/datasource/pool/ConnectionPool.java b/ebean-datasource/src/main/java/io/ebean/datasource/pool/ConnectionPool.java index 2f7c7d8..25dbd9a 100644 --- a/ebean-datasource/src/main/java/io/ebean/datasource/pool/ConnectionPool.java +++ b/ebean-datasource/src/main/java/io/ebean/datasource/pool/ConnectionPool.java @@ -271,7 +271,7 @@ private void initialiseDatabase() throws SQLException { */ @Override public boolean isWrapperFor(Class arg0) { - return false; + return DataSourcePool.class.isAssignableFrom(arg0); } /** @@ -279,7 +279,10 @@ public boolean isWrapperFor(Class arg0) { */ @Override public T unwrap(Class arg0) throws SQLException { - throw new SQLException("Not Implemented"); + if (DataSourcePool.class.isAssignableFrom(arg0)) { + return (T) this; + } + throw new SQLException("Not a wrapper for " + arg0.getName()); } /** @@ -618,7 +621,7 @@ void removeClosedConnection(PooledConnection pooledConnection) { */ private void returnTheConnection(PooledConnection pooledConnection, boolean forceClose) { if (poolListener != null && !forceClose && !pooledConnection.heartbeat()) { - poolListener.onBeforeReturnConnection(pooledConnection); + poolListener.onBeforeReturnConnection(this, pooledConnection); } queue.returnPooledConnection(pooledConnection, forceClose); } @@ -699,7 +702,7 @@ private PooledConnection getPooledConnection(boolean heartbeat) throws SQLExcept c.setStackTrace(Thread.currentThread().getStackTrace()); } if (poolListener != null) { - poolListener.onAfterBorrowConnection(c); + poolListener.onAfterBorrowConnection(this, c); } return c; } diff --git a/ebean-datasource/src/main/java/io/ebean/datasource/pool/PooledConnection.java b/ebean-datasource/src/main/java/io/ebean/datasource/pool/PooledConnection.java index 050c98f..8399426 100644 --- a/ebean-datasource/src/main/java/io/ebean/datasource/pool/PooledConnection.java +++ b/ebean-datasource/src/main/java/io/ebean/datasource/pool/PooledConnection.java @@ -1,5 +1,6 @@ package io.ebean.datasource.pool; +import io.ebean.datasource.DataSourceConnection; import java.sql.*; import java.util.ArrayList; import java.util.Map; @@ -18,7 +19,7 @@ * It has caching of Statements and PreparedStatements. Remembers the last * statement that was executed. Keeps statistics on how long it is in use. */ -final class PooledConnection extends ConnectionDelegator { +final class PooledConnection extends ConnectionDelegator implements DataSourceConnection { private static final String IDLE_CONNECTION_ACCESSED_ERROR = "Pooled Connection has been accessed whilst idle in the pool, via method: "; @@ -262,13 +263,7 @@ void doCloseConnection(boolean logErrors) { Log.error("Error checking if connection [" + name + "] is closed", ex); } } - try { - clearPreparedStatementCache(); - } catch (SQLException ex) { - if (logErrors) { - Log.warn("Error when closing connection Statements", ex); - } - } + clearPreparedStatementCache(); try { // DB2 (and some other DBMS) may have uncommitted changes and do not allow close // so try to do a rollback. @@ -295,14 +290,19 @@ void doCloseConnection(boolean logErrors) { } } - void clearPreparedStatementCache() throws SQLException { + public void clearPreparedStatementCache() { lock.lock(); try { for (ExtendedPreparedStatement ps : pstmtCache.values()) { - ps.closeDestroy(); + try { + ps.closeDestroy(); + } catch (SQLException ex) { + Log.warn("Error when closing connection Statements", ex); + } } } finally { + pstmtCache.clear(); lock.unlock(); } } @@ -1022,4 +1022,16 @@ private String stackTraceAsString(StackTraceElement[] stackTrace) { return filteredList.toString(); } + @Override + public boolean isWrapperFor(Class arg0) throws SQLException { + return DataSourceConnection.class.isAssignableFrom(arg0) || super.isWrapperFor(arg0); + } + + @Override + public T unwrap(Class arg0) throws SQLException { + if (DataSourceConnection.class.isAssignableFrom(arg0)) { + return (T) this; + } + return super.unwrap(arg0); + } } diff --git a/ebean-datasource/src/test/java/io/ebean/datasource/pool/PreparedStatementCacheTest.java b/ebean-datasource/src/test/java/io/ebean/datasource/pool/PreparedStatementCacheTest.java new file mode 100644 index 0000000..49ac741 --- /dev/null +++ b/ebean-datasource/src/test/java/io/ebean/datasource/pool/PreparedStatementCacheTest.java @@ -0,0 +1,144 @@ +package io.ebean.datasource.pool; + +import io.ebean.datasource.DataSourceConfig; +import io.ebean.datasource.DataSourceConnection; +import io.ebean.datasource.DataSourcePool; +import io.ebean.datasource.DataSourcePoolListener; +import org.checkerframework.checker.nullness.qual.NonNull; +import org.h2.Driver; +import org.junit.jupiter.api.Test; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Proxy; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.util.Properties; +import java.util.concurrent.atomic.AtomicReference; + +import static org.assertj.core.api.Assertions.assertThat; + +class PreparedStatementCacheTest { + + private Connection activeConnection; + + private int tenant; + + /** + * Nach dem Austausch der physischen Verbindung muss dieselbe SQL-Abfrage ein neues + * PreparedStatement erhalten und den Wert aus der zweiten Datenbank liefern. + */ + @Test + void queryAfterPhysicalConnectionSwitch() throws SQLException { + try (var first = DriverManager.getConnection("jdbc:h2:mem:preparedStatementCacheFirst"); + var second = DriverManager.getConnection("jdbc:h2:mem:preparedStatementCacheSecond")) { + populate(first, 10); + populate(second, 20); + + tenant = 1; + activeConnection = first; + + var config = new DataSourceConfig() + .setUsername("dummy") + .setPassword("dummy") + .setListener(createSwitchingListener(first, second)) + .setMinConnections(1) + .setMaxConnections(1) + .setAutoCommit(true) + .setPstmtCacheSize(2) + .validateOnHeartbeat(false); + config.driver(createSwitchingDriver()); + var pool = new ConnectionPool("preparedStatementCache", config); + Connection tmp; + try { + try (DataSourceConnection connection = pool.getConnection().unwrap(DataSourceConnection.class)) { + assertThat(query(connection)).isEqualTo(10); + tmp = connection; + } + + try (DataSourceConnection connection = pool.getConnection().unwrap(DataSourceConnection.class)) { + assertThat(query(connection)).isEqualTo(10); + assertThat(connection).isSameAs(tmp); + } + + tenant = 2; + try (Connection connection = pool.getConnection()) { + // If `preparedStatementCache` isn’t cleared here, the query returns `10`, a value from the wrong tenant! + assertThat(query(connection)).isEqualTo(20); + assertThat(connection).isSameAs(tmp); + } + + } finally { + pool.shutdown(); + } + } + } + + private @NonNull DataSourcePoolListener createSwitchingListener(Connection first, Connection second) { + return new DataSourcePoolListener() { + @Override + public void onAfterBorrowConnection(DataSourcePool pool, DataSourceConnection connection) throws SQLException { + switch (tenant) { + case 1: + if (activeConnection != first) { + activeConnection = first; + connection.clearPreparedStatementCache(); + } + break; + case 2: + if (activeConnection != second) { + activeConnection = second; + connection.clearPreparedStatementCache(); + } + break; + default: + throw new IllegalArgumentException(tenant + "is invalid"); + } + } + }; + } + + private @NonNull Driver createSwitchingDriver() { + return new Driver() { + @Override + public Connection connect(String url, Properties info) { + return (Connection) Proxy.newProxyInstance(Connection.class.getClassLoader(), new Class[]{Connection.class}, + (proxy, method, args) -> { + try { + return method.invoke(activeConnection, args); + } catch (InvocationTargetException e) { + throw e.getCause(); + } + }); + } + }; + } + + private static void populate(Connection connection, int value) throws SQLException { + try (var statement = connection.createStatement()) { + statement.execute("create table test (id int primary key, test_value int)"); + statement.execute("insert into test values (1, " + value + ")"); + } + } + + private static int query(Connection connection) throws SQLException { + try (var statement = connection.prepareStatement("select test_value from test where id = ?")) { + statement.setInt(1, 1); + try (var result = statement.executeQuery()) { + assertThat(result.next()).isTrue(); + return result.getInt(1); + } + } + } + + private static Connection forwardingConnection(AtomicReference delegate) { + return (Connection) Proxy.newProxyInstance(Connection.class.getClassLoader(), new Class[]{Connection.class}, + (proxy, method, args) -> { + try { + return method.invoke(delegate.get(), args); + } catch (InvocationTargetException e) { + throw e.getCause(); + } + }); + } +}