sidorares / sidorares/node-mysql2
Add a way to change pool's default database for new connections
Nobody has claimed this yet.
- Dominant language
- TypeScript
- Stars
- 4.4k
- Forks
- 680
- Avg merge
- 9h 7m
- Merged PRs (30d)
- 59
Description
For pool connections it is common to call changeUser after getConnection to reset the state of the connection. It can also be used to switch databases by passing {database: "newDatabaseName"} to changeUser. This works fine but appears to change the pool's default database for new connections as well (see also https://github.com/sidorares/node-mysql2/issues/477). This is not that problematic except for the fact that the pool now becomes unusable after calling changeUser({database: }) with a database that does not exist anymore: connecting to the pool fails with ER_BAD_DB. This happens in my use case as the database name can be entered by users (and they may be wrong).
So, in summary:
pool = createPool({database: "exists"});
con = pool.getConnection(); // works, database=exists
con.changeUser({database: "does_not_exist"}); // fails but otherwise fine
con.release();
con = pool.getConnection(); // does not work! pool.config.connectionConfig.database still set to "does_not_exist"
My workaround is to wrap getConnection as follows, which is a bit of a dirty hack as it accesses private fields:
async getConnection(opts: {user: string, password: string, database: string}): Promise<PoolConnection> {
(this.pool as any).pool.config.connectionConfig.database = "information_schema"; // always exists
const con = await this.pool.getConnection();
await con.changeUser({
user: opts.user,
password: opts.password,
database: opts.database
});
return con;
}
My preferred solution would be to have getConnection (or a new method, say createFreshConnection) optionally accept the parameters as changeUser, that when passed are either used for creating a new connection or lead to a call to changeUser right after creating the new connection.
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by tracing the pool getConnection entry point and the connection changeUser behavior described in the example. Check how a failed database change affects pool.config.connectionConfig.database. Done means a failed changeUser does not make later pool connections unusable, with the requested connection parameters handled through a supported API rather than private fields.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- mysql, node.js, typescript
- Domain
- backend, databases
- Issue type
- Feature
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 38/100