MysqlRewinder is a simple, stable, and fast database cleaner for mysql.
- Fast cleanup using
DELETE
query - Supports multi-database
- Supports both
mysql2
andtrilogy
as a client library - Works without ActiveRecord
- Works with
fork
- Capture SQL statements during test execution and extract
INSERT
ed table names, and record them into temporary files - Aggregate tmp files and execute DELETE query for
INSERT
ed tables
MysqlRewinder is stable because it does not depend on ActiveRecord's internal implementation.
It only depends on Mysql2::Client#query
and Trilogy#query
.
Add this line to your Gemfile's :test
group:
gem 'trilogy'
# gem 'mysql2' # described later
gem 'mysql_rewinder'
And then execute:
$ bundle
RSpec.configure do |config|
config.before(:suite) do
db_config = {
host: '127.0.0.1',
port: '3306',
username: 'user1',
password: 'my_secure_password',
database: 'myapp-test'
}
MysqlRewinder.setup([db_config])
MysqlRewinder.clean_all
end
config.after(:each) do
MysqlRewinder.clean
end
end
Pass all configurations to MysqlRewinder.setup
.
MysqlRewinder.setup(
[
{ host: '127.0.0.1', port: '3306', username: 'user1', password: 'my_secure_password', database: 'myapp-test-shard1' },
{ host: '127.0.0.1', port: '3306', username: 'user1', password: 'my_secure_password', database: 'myapp-test-shard2' },
]
)
If you want to use mysql2
as a client library, do the following:
- Write
gem 'mysql2'
in yourGemfile
- Pass
adapter: :mysql2
toMysqlRewinder.setup
.
MysqlRewinder.setup(db_configs, adapter: :mysql2)
If you want to use MysqlRewinder with ActiveRecord, do the following:
- Generate db_configs from
ActiveRecord::Base.configurations
- Pass
ActiveRecord::SchemaMigration.new(nil).table_name
andActiveRecord::Base.internal_metadata_table_name
toMysqlRewinder.setup
asexcept_tables
db_configs = ActiveRecord::Base.configurations.configs_for(env_name: 'test').map(&:configuration_hash)
except_tables = [
ActiveRecord::Base.internal_metadata_table_name,
# for AR >= 7.1
ActiveRecord::SchemaMigration.new(nil).table_name,
# for AR < 7.1
# ActiveRecord::SchemaMigration.table_name,
]
MysqlRewinder.setup(db_configs, except_tables: except_tables)
If you want to enable logging, specify logger
for MysqlRewinder.setup
MysqlRewinder.setup(db_configs, logger: Logger.new(STDOUT))
Bug reports and pull requests are welcome on GitHub at https://github.com/DeNA/mysql_rewinder. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the code of conduct.
Everyone interacting in the MysqlRewinder project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the code of conduct.
The gem is available as open source under the terms of the MIT License.
- Thank you @aeroastro for the idea of using temporary files
- This gem is heavily inspired by amatsuda/database_rewinder.