ActiveRecord Connection TZ
⚠️ Early stage (v0.1.0): This gem is still being refined. APIs, configuration details, and supported surfaces may change before the first stable release.
Overview
activerecord-connection-tz helps Rails applications use mixed-timezone MySQL connections in the same process.
It is designed for cases where one connection follows a UTC contract while another connection needs temporal values to be interpreted with a different configured timezone.
The gem applies connection-scoped handling through database.yml, so the tagged connection can:
- set the MySQL session
time_zone - replace
datetime/time/timestampcasting on a per-connection basis - preserve fractional-second precision when writing temporal values
- work with both
mysql2andtrilogy
Installation
Add the gem together with the adapter gem you use:
# Gemfile
gem 'activerecord-connection-tz'
gem 'mysql2' # or gem 'trilogy'
And then execute:
bundle install
Quick start
The gem activates automatically for connections that declare connection_tz in database.yml.
production:
primary:
adapter: mysql2
database: primary_db
legacy_tokyo:
adapter: mysql2
database: legacy_db
connection_tz:
time_zone: Asia/Tokyo
No model-level or attribute-level wiring is required for the tagged connection.
For transition-free zones such as Asia/Tokyo, the gem can derive the MySQL session time_zone automatically from time_zone.
For zones with DST or other offset transitions, set mysql_session_time_zone explicitly:
production:
legacy_new_york:
adapter: mysql2
database: legacy_db
connection_tz:
time_zone: America/New_York
mysql_session_time_zone: America/New_York
If those DST-style zones use TIMESTAMP columns, prefer a named MySQL timezone such as America/New_York instead of a fixed offset such as -05:00. A fixed offset can skew TIMESTAMP reads across DST boundaries because MySQL converts TIMESTAMP values through the session timezone, while DATETIME values are not affected by that limitation.
Documentation
For runnable Rails examples and setup notes, see examples/README.md.
The examples cover:
- Rails 7.1 / 8.0 / 8.1
- mysql2 and trilogy side by side
- shared MySQL 8 Docker setup
- UTC
primaryplus a tagged connection interpreted with another timezone
Requirements
- Ruby 3.2+
- Active Record 7.1 - 8.1
- MySQL 5.7+ (or a compatible server with fractional-second precision support)
mysql2ortrilogy
Development
bundle install
bundle exec rbs collection install
bundle exec rspec
bundle exec rubocop
bundle exec rake sig:generate
bundle exec rake typecheck
To build the gem locally:
gem build activerecord-connection-tz.gemspec
Contributing
Bug reports and pull requests are welcome on GitHub at https://github.com/shoma07/activerecord-connection-tz.
License
The gem is available as open source under the terms of the MIT License.