Description
Is your feature request related to a problem? Please describe.
MySQL allows for configuration of various behavior-changing settings on a per-connection/session basis, which is done through queries. This includes for example setting collation (SET NAMES 'utf8mb4';
), setting timezone (SET time_zone='Europe/Amsterdam';
) or locale support (SET lc_time_names = 'nl_NL';
). Configuring these preferably should be done once at connection startup to ensure they are used throughout the entire lifetime of the connection and cause as little overhead as possible.
In my usecase I would like to set the (connection) timezone, however I think the problem can be generalized to any of such settings.
Describe the solution you'd like
Have an event hook that allows for safely and easily executing option-setting queries once after the first opening of a connection. This could be a generic event that allows arbitrary code execution, or could be some more subtle mechanism that only allows passing e.g. a list of statements to be executed once.
Describe alternatives you've considered
- In ConnectionString way to specify timezone? #487 there was some discussion about possibly adding this to
ConnectionString
; given the wide variety of possibly interesting options, I agree that adding this here is probably too much overhead; however it still can be considered. I've tried to implement this using theStateChange
event, however I run into troubles with some race conditions where the next query already seems to be trying to execute when the timezone setting query is still active, causing exceptions. Implementation roughly looks like this:
As a workaround, something similar to this can currently be used
connection.StateChange += (_, args) =>
{
// Only consider transition from Closed/Connecting to Open to denote the 'start' of a new connection
if (args.CurrentState == ConnectionState.Open && (args.OriginalState is ConnectionState.Closed or ConnectionState.Connecting))
{
conn.Execute("SET time_zone = 'UTC'");
}
};
- Manually opening the connections at some point in the application logic, followed by setting the aforementioned settings with queries. I can't however manage to let this play nicely with passing the connection to
Dapper
.
Additional context
- There already seems to be some kind of implementation for this regarding the collation: https://github.com/mysql-net/MySqlConnector/blob/master/src/MySqlConnector/Core/ServerSession.cs#L580. Maybe this can be generalized somehow?
Final note
If there are any suggestions/alternative approaches on how to subtly set time_zone
or other settings with existing code, please let me know!