brettwooldridge / HikariCP

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

Schema-based multitenancy: getting “java.sql.SQLException: No database selected” from time to time #1507

Open illidan80 opened 4 years ago

illidan80 commented 4 years ago

Environment

HikariCP version: 3.2.0
JDK version     : 11
Database        : MySQL
Driver version  : 8.0

My code written in Java, and I using Spring JDBC Template for accessing MySQL database.

My system is a multi-tenant and each tenant has its own dedicated schema in MySQL (e.g. "tenant_1", "tenant_2", etc).

This is how database connection being initialized:

During bootstrap, I creating a bean exposing DataSourceTransactionManager, which is initialized by DataSource configured with a connection string of the MySQL database (without specifying schema).

Since my system is multi-tenant, for each request I have to select schema of the given tenant. Therefore, typical query looks like this:

"USE tenant_xxx" ....

The problem:

From time to time (1 to thousands of executions), I am getting

java.sql.SQLException: No database selected.

I double checked my code - indeed, I do always selecting schema before query execution. I noticed this issue in random places in code, so most likely it is not a bug in specific place in my code

Any ideas?

nunnrlc commented 4 years ago

Can you share your connection settings here? I wonder if you might be using autoReconnect=true

That setting will seamlessly reconnect, but won't re-run the multi-tenant "use" query. It also may be detrimental to HikariCP performance (HikariCP wants to manage connection life alone), but I don't think HikariCP is involved in the problem at hand.