brettwooldridge / HikariCP

光 HikariCP・A solid, high-performance, JDBC connection pool at last.
Apache License 2.0
19.76k stars 2.91k forks source link

Close/renew connection after impersonate #1367

Open pbel78 opened 5 years ago

pbel78 commented 5 years ago

Environment

HikariCP version: 3.3.1
JDK version     : 1.8.0_111
Database        : Exasol (but also MSSQL)
Driver version  : x.x.x

We use for our app hikari cp to connect to the database. As the application users do have different permissions we do use the IMPERSONATE functions (example exasol: https://docs.exasol.com/sql/impersonate.htm) of the target databases to swtich the context. Some databases allow to REVERT to the original context but some doesn't. So When a command is completed we would need to close the connection actively = not just returning to the pool but telling hikari = hey: this connetion is no good anymore: can you really close it and replace it with a new one?

Is there an option to indicate this? Could evictConnection be used for that? But does hikari open a new connection if I evict one?

Thanks for a hint.

Regards

ljluestc commented 3 months ago
import com.zaxxer.hikari.HikariDataSource;
import java.sql.Connection;
import java.sql.SQLException;

public class ConnectionManager {

    private HikariDataSource dataSource;

    public ConnectionManager(HikariDataSource dataSource) {
        this.dataSource = dataSource;
    }

    // Method to close and replace connection after impersonation
    public void closeAndReplaceConnection(Connection connection) {
        try {
            // Close the connection
            connection.close();
        } catch (SQLException e) {
            // Handle exception if needed
            e.printStackTrace();
        } finally {
            // Evict the connection from the pool
            dataSource.evictConnection(connection);
            try {
                // Get a new connection from the pool to replace the evicted one
                Connection newConnection = dataSource.getConnection();
                // Optionally, you can return the new connection or perform any necessary operations
            } catch (SQLException e) {
                // Handle exception if getting a new connection fails
                e.printStackTrace();
            }
        }
    }
}