Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -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();
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package io.ebean.datasource;

import java.sql.Connection;
import java.sql.SQLException;


/**
Expand All @@ -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) {}


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -96,15 +96,15 @@ public final Struct createStruct(String typeName, Object[] attributes) throws SQ

@SuppressWarnings("unchecked")
@Override
public final <T> T unwrap(Class<T> iface) throws SQLException {
public <T> T unwrap(Class<T> iface) throws SQLException {
if (iface.equals(java.sql.Connection.class)) {
return (T) delegate;
}
return delegate.unwrap(iface);
}

@Override
public final boolean isWrapperFor(Class<?> iface) throws SQLException {
public boolean isWrapperFor(Class<?> iface) throws SQLException {
return delegate.isWrapperFor(iface);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -271,15 +271,18 @@ private void initialiseDatabase() throws SQLException {
*/
@Override
public boolean isWrapperFor(Class<?> arg0) {
return false;
return DataSourcePool.class.isAssignableFrom(arg0);
}

/**
* Not Implemented.
*/
@Override
public <T> T unwrap(Class<T> 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());
}

/**
Expand Down Expand Up @@ -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);
}
Expand Down Expand Up @@ -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;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -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: ";

Expand Down Expand Up @@ -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.
Expand All @@ -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();
}
}
Expand Down Expand Up @@ -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> T unwrap(Class<T> arg0) throws SQLException {
if (DataSourceConnection.class.isAssignableFrom(arg0)) {
return (T) this;
}
return super.unwrap(arg0);
}
}
Original file line number Diff line number Diff line change
@@ -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<Connection> 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();
}
});
}
}
Loading