Identify database issues before they hit production.
Identify database issues before they hit production.
Active Record Doctor helps to keep the database in a good shape. Currently, it can detect:
active_record_doctor:extraneous_indexesdeleted_at columns - active_record_doctor:unindexed_deleted_atactive_record_doctor:missing_foreign_keysactive_record_doctor:undefined_table_referencesactive_record_doctor:missing_unique_indexesNULL constraints - active_record_doctor:missing_non_null_constraintactive_record_doctor:missing_presence_validationactive_record_doctor:incorrect_boolean_presence_validationactive_record_doctor:incorrect_length_validationdependent on associations - active_record_doctor:incorrect_dependent_optionactive_record_doctor:short_primary_key_typeactive_record_doctor:mismatched_foreign_key_typeactive_record_doctor:table_without_primary_keyactive_record_doctor:table_without_timestampsIt can also:
active_record_doctor:unindexed_foreign_keysIn order to use the latest production release, please add the following to
your Gemfile:
gem 'active_record_doctor', group: [:development, :test]and run bundle install. If you'd like to use the most recent development
version then use this instead:
gem 'active_record_doctor', github: 'gregnavis/active_record_doctor', group: [:development, :test]That's it when it comes to Rails projects. If your project doesn't use Rails
then you can use active_record_doctor via Rakefile.
If your project uses Rake then you can add the following to Rakefile in order
to use active_record_doctor:
require "active_record_doctor"
ActiveRecordDoctor::Rake::Task.new do |task|
# Add project-specific Rake dependencies that should be run before running
# active_record_doctor.
task.deps = []
# A path to your active_record_doctor configuration file.
task.config_path = ::Rails.root.join(".active_record_doctor.rb")
# A Proc called right before running detectors that should ensure your Active
# Record models are preloaded and a database connection is ready.
task.setup = -> { ::Rails.application.eager_load! }
endIMPORTANT. active_record_doctor expects that after running deps and
calling setup your Active Record models are loaded and a database connection
is established.
active_record_doctor can be used via rake or rails.
You can run all available detectors via:
bundle exec rake active_record_doctorYou can run a specific detector via:
bundle exec rake active_record_doctor:extraneous_indexesIf you want to use active_record_doctor in a Continuous Integration setting
then ensure the configuration file is committed and run the tool as one of your
build steps -- it returns a non-zero exit status if any errors were reported.
If you'd like to obtain help on a specific detector then use the help
sub-task:
bundle exec rake active_record_doctor:extraneous_indexes:helpThis will show the detector help text in the terminal, along with supported configuration options, their meaning, and whether they're global or local.
It may be that active_record_doctor fails with an exception and it is hard to tell
what went wrong. For easier debugging, use ACTIVE_RECORD_DOCTOR_DEBUG environment variable.
If active_record_doctor fails for some reason for your application, feel free
to open an issue or a PR with the fix.
ACTIVE_RECORD_DOCTOR_DEBUG=1 bundle exec rake active_record_doctoractive_record_doctor can be configured to better suit your project's needs.
For example, if it complains about a model that you want ignored then you can
add that model to the configuration file.
If you want to use the default configuration then you don't have to do anything.
Just run active_record_doctor in your project directory.
If you want to customize the tool you should create a file named
.active_record_doctor.rb in your project root directory with content like:
ActiveRecordDoctor.configure do
# Global settings affect all detectors.
global :ignore_tables, [
# Ignore internal Rails-related tables.
"ar_internal_metadata",
"schema_migrations",
"active_storage_blobs",
"active_storage_attachments",
"action_text_rich_texts",
# Add project-specific tables here.
"legacy_users"
]
# Detector-specific settings affect only one specific detector.
detector :extraneous_indexes,
ignore_tables: ["users"],
ignore_indexes: ["accounts_on_email_organization_id"]
endThe configuration file above will make active_record_doctor ignore internal
Rails tables (which are ignored by default) and also the legacy_users table.
It'll also make the extraneous_indexes detector skip the users table
entirely and will not report the index named accounts_on_email_organization_id
as extraneous.
Configuration options for each detector are listed below. They can also be obtained via the help mechanism described in the previous section.
Settings like ignore_tables, ignore_indexes, ignore_models and so on
accept list of identifiers to ignore. These can be either:
For example, to ignore all tables starting with legacy_ and all models under
the Legacy:: namespace you can write:
ActiveRecordDoctor.configure do
global :ignore_tables, [
# Ignore all legacy tables.
/^legacy_/
]
global :ignore_models, [
# Ignore all legacy models.
/^Legacy::/
]
endForeign keys should be indexed unless it's proven ineffective. However, Rails makes it easy to create an unindexed foreign key. Active Record Doctor can automatically generate database migrations that add the missing indexes. It's a three-step process:
bundle exec rake active_record_doctor:unindexed_foreign_keys > unindexed_foreign_keys.txtRemove columns that should not be indexed from unindexed_foreign_keys.txt
as a column can look like a foreign key (i.e. ending with _id) without being
one.
Generate the migrations
rails generate active_record_doctor:add_indexes unindexed_foreign_keys.txtbundle exec rake db:migrateSupported configuration options:
enabled - set to false to disable the detector altogetherignore_tables - tables whose foreign keys should not be checkedignore_columns - columns, written as table.column, that should not be
checked.Let me illustrate with an example. Consider a users table with columns
first_name and last_name. If there are two indexes:
last_name, first_name.last_name.Then the latter index can be dropped as the former can play its role. In
general, a multi-column index on column_1, column_2, ..., column_n can replace
indexes on:
column_1column_1, column_2column_1, column_2, ..., column_(n - 1)To discover such indexes automatically just follow these steps:
bundle exec rake active_record_doctor:extraneous_indexesConfirm that each of the indexes can be indeed dropped.
Create a migration to drop the indexes.
The indexes aren't dropped automatically because there are usually just a few of them and it's a good idea to double-check that you won't drop something necessary.
Also, extra indexes on primary keys are considered extraneous too and will be reported.
Note that a unique index can never be replaced by a non-unique one. For
example, if there's a unique index on users.login and a non-unique index on
users.login, users.domain then the tool will not suggest dropping
users.login as it could violate the uniqueness assumption. However, a unique
index on users.login, user.domain might be replaceable with users.login as
the uniqueness of the latter implies the uniqueness of the former (if a given
login can appear only once then it can be present in only one login, domain
pair).
Supported configuration options:
enabled - set to false to disable the detector altogetherignore_tables - tables whose indexes should never be reported as extraneous.ignore_indexes - indexes that should never be reported as extraneous.deleted_at ColumnsIf you soft-delete some models (e.g. with paranoia) then you need to modify
your indexes to include only non-deleted rows. Otherwise they will include
logically non-existent rows. This will make them larger and slower to use. Most
of the time they should only cover columns satisfying deleted_at IS NULL (to
cover existing records) or deleted_at IS NOT NULL (to cover deleted records).
active_record_doctor can automatically detect indexes on tables with a
deleted_at column. Just run:
bundle exec rake active_record_doctor:unindexed_deleted_atThis will print a list of indexes that don't have the deleted_at IS NULL
clause. Currently, active_record_doctor cannot automatically generate
appropriate migrations. You need to do that manually.
Supported configuration options:
enabled - set to false to disable the detector altogetherignore_tables - tables whose indexes should not be checked.ignore_columns - specific columns, written as table.column, that should not
be reported as unindexed.ignore_indexes - specific indexes that should not be reported as excluding a
timestamp column.column_names - deletion timestamp column names.If User defines a belongs_to association to Profile then the underlying
column (users.profile_id by convention) should be marked as a foreign key in
the database. If it's not then it's possible to end up in a situation where a
user is referencing a non-existent profile.
active_record_doctor can automatically detect foreign keys that could benefit
from a foreign key constraint (a future version will generate a migration that
add the constraint; for now, it's your job). You can obtain the list of missing
foreign key constraints with the following command:
bundle exec rake active_record_doctor:missing_foreign_keysIn order to add a foreign key constraint to users.profile_id use a migration
like:
class AddForeignKeyConstraintToUsersProfileIdNo open issues yet, or sync has not completed.