### Setup Task Example Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/api-reference/rake-task.md Example command to run the setup task directly. ```bash bundle exec rake active_record_doctor:setup ``` -------------------------------- ### Constructor Example Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/api-reference/rake-task.md Example of how to instantiate the Rake::Task with custom dependencies, configuration path, and setup proc. ```ruby ActiveRecordDoctor::Rake::Task.new do |task| task.deps = [:environment] task.config_path = Rails.root.join(".active_record_doctor.rb") task.setup = -> { Rails.application.eager_load! } end ``` -------------------------------- ### Custom Dependencies Example Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/api-reference/rake-task.md Example demonstrating how to configure the ActiveRecordDoctor::Rake::Task with custom dependencies and setup logic. ```ruby require "active_record_doctor" task :load_database do # Custom database loading logic puts "Loading database..." end ActiveRecordDoctor::Rake::Task.new do |task| task.deps = [:environment, :load_database] task.setup = -> do Rails.application.eager_load! # Additional setup puts "Setup complete" end end ``` -------------------------------- ### Load Configuration with Defaults Example (Defaults Only) Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/api-reference/config.md Example of loading only default configuration. ```ruby # Use only defaults config = ActiveRecordDoctor.load_config_with_defaults(nil) ``` -------------------------------- ### Load Configuration Example Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/api-reference/config.md Example of loading configuration, with error handling for missing files. ```ruby begin config = ActiveRecordDoctor.load_config(".active_record_doctor.rb") rescue ActiveRecordDoctor::Error::ConfigurationFileMissing puts "Configuration file not found. Using defaults instead." config = ActiveRecordDoctor.load_config_with_defaults(nil) end ``` -------------------------------- ### Merge Configuration Example Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/api-reference/config.md Example of merging default and user configurations. ```ruby default = ActiveRecordDoctor.load_config(ActiveRecordDoctor::Config::DEFAULT_CONFIG_PATH) user = ActiveRecordDoctor.load_config(".active_record_doctor.rb") final = default.merge(user) ``` -------------------------------- ### Get All Available Detectors Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/api-reference/detector-examples.md Ruby code to iterate through all available detectors in ActiveRecordDoctor and print their names and descriptions. ```ruby ActiveRecordDoctor.detectors.each do |name, detector_class| puts "#{name}: #{detector_class.description}" end ``` -------------------------------- ### Missing Foreign Keys Example Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/api-reference/detector-examples.md Example of a missing foreign key constraint. ```ruby class Post < ApplicationRecord belongs_to :user # Column: user_id exists # No foreign key constraint! end ``` -------------------------------- ### ConfigurationFileMissing Example Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/errors.md Example of loading a non-existent configuration file. ```ruby config = ActiveRecordDoctor.load_config("/nonexistent/.active_record_doctor.rb") # => ActiveRecordDoctor::Error::ConfigurationFileMissing ``` -------------------------------- ### Load Configuration with Defaults Example (Merged) Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/api-reference/config.md Example of loading defaults merged with user configuration. ```ruby # Use defaults merged with user config config = ActiveRecordDoctor.load_config_with_defaults(".active_record_doctor.rb") ``` -------------------------------- ### Configure Example Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/api-reference/config.md Example of configuring active_record_doctor with global and detector settings. ```ruby ActiveRecordDoctor.configure do global :ignore_tables, ["ar_internal_metadata", "schema_migrations"] detector :missing_presence_validation, enabled: true, ignore_models: ["User"], ignore_attributes: ["Post.excerpt"], ignore_columns_with_default: true end ``` -------------------------------- ### Example usage of postgresql? method Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/api-reference/utilities.md Example of how to use the postgresql? method to conditionally execute SQL. ```ruby if ActiveRecordDoctor::Utils.postgresql? # Use PostgreSQL-specific SQL connection.execute("SELECT pg_size_pretty(pg_total_relation_size('users'))") else # Use generic SQL or adapter-specific approach end ``` -------------------------------- ### Configuration File Example Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/configuration.md Example of how to configure ActiveRecordDoctor in a `.active_record_doctor.rb` file. ```ruby # .active_record_doctor.rb ActiveRecordDoctor.configure do # Global settings global :setting_name, value # Detector-specific settings detector :detector_name, setting1: value, setting2: value end ``` -------------------------------- ### Missing Unique Index Example: Basic Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/api-reference/detector-examples.md Example of a basic missing unique index problem. ```ruby class User < ApplicationRecord validates :email, uniqueness: true # No unique index on email! end ``` -------------------------------- ### Example of Help Text Output Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/api-reference/utilities.md An example of the actual output from generating help text for a specific detector. ```text # Output: # missing_presence_validation - detect non-NULL columns without a corresponding presence validator # # Configuration options: # - enabled (local only) - set to false to disable the detector altogether # - ignore_models (local and global) - models whose underlying tables' columns should not be checked # - ignore_attributes (local only) - specific attributes, written as Model.attribute, that should not be checked # - ignore_columns_with_default (local only) - ignore columns with default values, should be provided as boolean ``` -------------------------------- ### Main Detection Task Example Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/api-reference/rake-task.md Example command to run a specific detector task. ```bash bundle exec rake active_record_doctor:missing_foreign_keys bundle exec rake active_record_doctor:extraneous_indexes ``` -------------------------------- ### Help Task Example Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/api-reference/rake-task.md Example command to run the help task for a specific detector and its expected output. ```bash bundle exec rake active_record_doctor:missing_presence_validation:help # Output: # missing_presence_validation - detect non-NULL columns without a corresponding presence validator # # Configuration options: # - enabled (local only) - set to false to disable the detector altogether # - ignore_models (local and global) - models whose underlying tables should not be checked # - ignore_attributes (local only) - specific attributes, written as Model.attribute, that should not be checked # - ignore_columns_with_default (local only) - ignore columns with default values, should be provided as boolean ``` -------------------------------- ### Input File Format Example Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/api-reference/generators.md Example of the expected format for the input file containing index suggestions. ```text add an index on users(account_id) - consider adding an index on the foreign key add an index on posts(user_id) - consider adding an index on the foreign key add an index on comments(post_id, user_id) - consider adding an index on the foreign key ``` -------------------------------- ### Unindexed Foreign Keys Example Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/api-reference/detector-examples.md Example of a belongs_to association with a foreign key column that lacks an index. ```ruby class Post < ApplicationRecord belongs_to :user # Generates: user_id column (foreign key) # No index on user_id! end ``` -------------------------------- ### Missing Unique Index Example: Scoped Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/api-reference/detector-examples.md Example of a scoped uniqueness validation problem. ```ruby class Tag < ApplicationRecord validates :name, uniqueness: { scope: :project_id } # No unique index on (name, project_id)! end ``` -------------------------------- ### Obtaining Help for a Specific Detector Source: https://github.com/gregnavis/active_record_doctor/blob/master/README.md Example of how to get help for a specific detector, showing supported configuration options. ```bash bundle exec rake active_record_doctor:extraneous_indexes:help ``` -------------------------------- ### Incorrect Boolean Presence Validation Example Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/api-reference/detector-examples.md Example of an incorrect presence validator on a boolean column. ```ruby class User < ApplicationRecord validates :active, presence: true # active is a boolean column # presence: true is ineffective! end ``` -------------------------------- ### Automatic Configuration File Discovery Examples Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/api-reference/rake-task.md Examples demonstrating the legacy and recommended configuration file naming conventions. ```ruby # Deprecated - shows warning .active_record_doctor # Recommended .active_record_doctor.rb ``` -------------------------------- ### Example Generated Migration Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/api-reference/generators.md A concrete example of a migration file generated for adding indexes. ```ruby class IndexForeignKeysInUsers < ActiveRecord::Migration[7.0] def change add_index :users, [:account_id] add_index :users, [:organization_id] end end class IndexForeignKeysInPosts < ActiveRecord::Migration[7.0] def change add_index :posts, [:user_id] end end ``` -------------------------------- ### Example: Running all detectors Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/api-reference/runner.md Demonstrates how to run all detectors and exit with an error code if any problems are found. ```ruby success = runner.run_all exit(1) unless success ``` -------------------------------- ### Example workflow Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/api-reference/rails-integration.md Example workflow for generating migrations for missing indexes. ```bash # 1. Run unindexed_foreign_keys detector bundle exec rake active_record_doctor:unindexed_foreign_keys > /tmp/missing_indexes.txt # 2. Generate migrations rails generate active_record_doctor:add_indexes /tmp/missing_indexes.txt # 3. Review migrations ls db/migrate/*index_foreign_keys*.rb # 4. Run migrations rails db:migrate ``` -------------------------------- ### Example invalid input Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/api-reference/generators.md Examples of malformed input lines that would trigger an error. ```text this line is malformed add an index on invalid syntax ``` -------------------------------- ### Show Help for a Detector Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/api-reference/detector-examples.md Ruby code to retrieve a specific detector and generate its help information. ```ruby detector = ActiveRecordDoctor.detectors[:missing_presence_validation] help = ActiveRecordDoctor::Help.new(detector) puts help ``` -------------------------------- ### Problem 2: Circular delete relationships Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/api-reference/detector-examples.md Example illustrating a potential problem with circular `dependent: :delete_all` relationships between models. ```ruby class Author < ApplicationRecord has_many :books, dependent: :delete_all end class Book < ApplicationRecord has_many :chapters, dependent: :delete_all end ``` -------------------------------- ### ActiveRecordDoctor::Config Example Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/types.md An example of how to instantiate and configure ActiveRecordDoctor::Config. ```ruby config = ActiveRecordDoctor::Config.new( { ignore_tables: ["ar_internal_metadata", "schema_migrations"], ignore_models: ["TemporaryModel"] }, { extraneous_indexes: { enabled: true, ignore_tables: [], ignore_indexes: [] }, missing_foreign_keys: { enabled: true, ignore_models: [], ignore_associations: [] } } ) ``` -------------------------------- ### Hierarchical Logger Detailed Example Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/api-reference/logging.md A more detailed example showcasing nested logging with the Hierarchical logger. ```ruby logger = ActiveRecordDoctor::Logger::Hierarchical.new($stderr) logger.log("extraneous_indexes") do logger.log("subindexes_of_multi_column_indexes") do logger.log("Iterating over data sources") do logger.log("users") do logger.log("Index idx_email_and_account") do logger.log("Problem found") do logger.log("table: users") logger.log("extraneous_index: idx_email_and_account") end end end end end end ``` -------------------------------- ### ConfigureNotCalled Example Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/errors.md Example demonstrating ConfigureNotCalled when the configuration file does not call ActiveRecordDoctor.configure. ```ruby # In .active_record_doctor.rb: # (File is empty or has no call to configure) config = ActiveRecordDoctor.load_config(".active_record_doctor.rb") # => ActiveRecordDoctor::Error::ConfigureNotCalled ``` -------------------------------- ### Integrate with Generator Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/api-reference/detector-examples.md Output can be piped to the `add_indexes` generator. ```bash bundle exec rake active_record_doctor:unindexed_foreign_keys > /tmp/missing_indexes.txt rails generate active_record_doctor:add_indexes /tmp/missing_indexes.txt ``` ```ruby class IndexForeignKeysInPosts < ActiveRecord::Migration[7.0] def change add_index :posts, [:user_id] end end ``` -------------------------------- ### Generated Migration Example Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/api-reference/rails-integration.md Example of a generated migration file. ```ruby class IndexForeignKeysInUsers < ActiveRecord::Migration[7.0] def change add_index :users, [:account_id] add_index :users, [:organization_id] end end ``` -------------------------------- ### Complete Configuration Example Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/configuration.md A comprehensive example of an .active_record_doctor.rb file, demonstrating global settings and configurations for various detectors. ```ruby # .active_record_doctor.rb ActiveRecordDoctor.configure do # Global settings - applied to multiple detectors global :ignore_tables, [ "ar_internal_metadata", "schema_migrations", "active_storage_blobs", "active_storage_attachments", "action_text_rich_texts", "legacy_data", "archive_*" ] global :ignore_models, [ "TemporaryModel", "LegacyUser" ] # Detection detectors - checks for missing constraints and validations detector :missing_foreign_keys, enabled: true, ignore_associations: ["User.organization"] detector :missing_presence_validation, enabled: true, ignore_attributes: ["User.bio"], ignore_columns_with_default: true detector :missing_non_null_constraint, enabled: true detector :missing_unique_indexes, enabled: true, ignore_columns: ["users.email"] # Index-related detectors detector :extraneous_indexes, enabled: true, ignore_indexes: ["idx_legacy_lookup"] detector :unindexed_foreign_keys, enabled: true detector :unindexed_deleted_at, enabled: true, column_names: ["deleted_at", "discarded_at"] # Validation detectors - checks for validation problems detector :incorrect_boolean_presence_validation, enabled: true detector :incorrect_length_validation, enabled: true detector :incorrect_dependent_option, enabled: true # Table structure detectors detector :short_primary_key_type, enabled: true detector :table_without_primary_key, enabled: true detector :table_without_timestamps, enabled: true, ignore_tables: ["lookup_tables"] detector :mismatched_foreign_key_type, enabled: true detector :undefined_table_references, enabled: true end ``` -------------------------------- ### Example usage of adapter detection methods in a detector Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/api-reference/utilities.md Example of using adapter detection methods within a detector class to implement adapter-specific logic. ```ruby # Usage in detector code for adapter-specific logic class MyDetector < ActiveRecordDoctor::Detectors::Base private def detect if Utils.postgresql?(connection) check_postgresql_specific elsif Utils.mysql?(connection) check_mysql_specific elsif Utils.sqlite?(connection) check_sqlite_specific end end end ``` -------------------------------- ### Missing Foreign Keys Configuration Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/api-reference/detector-examples.md Configuration for the `missing_foreign_keys` detector. ```ruby detector :missing_foreign_keys, enabled: true, ignore_models: ["LegacyModel"], ignore_associations: ["Post.author"] ``` -------------------------------- ### Problem 1: Using delete instead of destroy with validations Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/api-reference/detector-examples.md Example demonstrating a potential issue where `dependent: :delete_all` is used on an association with a model that has validations. ```ruby class User < ApplicationRecord has_many :posts, dependent: :delete_all end class Post < ApplicationRecord validates :content, presence: true end ``` -------------------------------- ### Extraneous Indexes Detector Configuration Example Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/configuration.md Example configuration for the `extraneous_indexes` detector. ```ruby detector :extraneous_indexes, enabled: true, ignore_tables: ["users"], ignore_indexes: ["idx_custom_index"] ``` -------------------------------- ### ActiveRecordDoctor Configuration Example Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/api-reference/rails-integration.md Example configuration file for ActiveRecordDoctor, detailing various detectors and their settings. ```ruby ActiveRecordDoctor.configure do # Global settings for all detectors global :ignore_tables, [ # Rails internal tables "ar_internal_metadata", "schema_migrations", "active_storage_blobs", "active_storage_attachments", "action_text_rich_texts", # Project-specific exclusions "legacy_users", "archive_*", /^temp_/ ] global :ignore_models, [ "TemporaryModel", "LegacyUser" ] # Detection detectors detector :missing_foreign_keys, enabled: true, ignore_associations: [ "Post.secondary_author", "Comment.soft_deleted_by" ] detector :missing_presence_validation, enabled: true, ignore_models: ["Post"], ignore_attributes: [ "User.bio", "Account.notes" ], ignore_columns_with_default: true detector :missing_non_null_constraint, enabled: true, ignore_columns: ["users.bio"] detector :missing_unique_indexes, enabled: true, ignore_columns: ["users.email"], ignore_join_tables: ["user_roles"] # Index-related detectors detector :extraneous_indexes, enabled: true, ignore_tables: ["archive_items"], ignore_indexes: ["idx_legacy_lookup"] detector :unindexed_foreign_keys, enabled: true, ignore_columns: ["audit_logs.user_id"] detector :unindexed_deleted_at, enabled: true, column_names: ["deleted_at", "discarded_at", "archived_at"] # Validation detectors detector :incorrect_boolean_presence_validation, enabled: true detector :incorrect_length_validation, enabled: true detector :incorrect_dependent_option, enabled: true, ignore_associations: ["User.temporary_posts"] # Table structure detectors detector :short_primary_key_type, enabled: true, ignore_tables: ["lookup_tables"] detector :table_without_primary_key, enabled: true detector :table_without_timestamps, enabled: true, ignore_tables: ["junction_tables"] # Constraint and type detectors detector :mismatched_foreign_key_type, enabled: true detector :undefined_table_references, enabled: true end ``` -------------------------------- ### Missing Presence Validation Configuration Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/api-reference/detector-examples.md Configuration for the missing_presence_validation detector. ```ruby detector :missing_presence_validation, enabled: true, ignore_models: ["PostArchive"], ignore_attributes: ["User.bio"], ignore_columns_with_default: true ``` -------------------------------- ### Missing Unique Indexes Configuration Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/api-reference/detector-examples.md Configuration for the `missing_unique_indexes` detector. ```ruby detector :missing_unique_indexes, enabled: true, ignore_models: ["TemporaryUser"], ignore_columns: ["users.email"], ignore_join_tables: ["user_roles"] ``` -------------------------------- ### Example Schema for Missing Non-NULL Constraint Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/api-reference/detector-examples.md A schema definition showing a `users` table with an `email` column that allows NULL by default, which the detector might flag. ```ruby create_table :users do |t| t.string :email # Allows NULL by default! end ``` -------------------------------- ### Formatted Custom Logger Example Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/api-reference/logging.md An example of a more advanced custom logger that adds indentation and a prefix to log messages. ```ruby class FormattedLogger def initialize(io, prefix: "[ARD]") @io = io @prefix = prefix @depth = 0 end def log(message) @io.puts("#{@prefix}#{" " * @depth} #{message}") return unless block_given? @depth += 2 result = yield @depth -= 2 result end end logger = FormattedLogger.new($stderr) runner = ActiveRecordDoctor::Runner.new(config: config, logger: logger) ``` -------------------------------- ### Extraneous Indexes Configuration Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/api-reference/detector-examples.md Configuration for the extraneous_indexes detector. ```ruby detector :extraneous_indexes, enabled: true, ignore_tables: ["archive_items"], ignore_indexes: ["custom_idx_keep"] ``` -------------------------------- ### Example: Displaying detector help Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/api-reference/runner.md Illustrates how to request and display help text for a detector, including its description and configuration options. ```ruby runner.help(:missing_presence_validation) # Output: # missing_presence_validation - detect non-NULL columns without a corresponding presence validator # # Configuration options: # - enabled (local only) - set to false to disable the detector altogether # - ignore_models (local and global) - models whose underlying tables' columns should not be checked # - ignore_attributes (local only) - specific attributes, written as Model.attribute, that should not be checked # - ignore_columns_with_default (local only) - ignore columns with default values, should be provided as boolean ``` -------------------------------- ### Unindexed Foreign Keys Configuration Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/api-reference/detector-examples.md Configuration for the unindexed_foreign_keys detector. ```ruby detector :unindexed_foreign_keys, enabled: true, ignore_tables: ["audit_logs"], ignore_columns: ["comments.user_id"] ``` -------------------------------- ### Default Configuration Example Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/configuration.md An example of the built-in default configuration used by ActiveRecord Doctor when no user configuration file is present. ```ruby ActiveRecordDoctor.configure do global :ignore_tables, [ "ar_internal_metadata", "schema_migrations", "active_storage_blobs", "active_storage_attachments", "action_text_rich_texts" ] # All detectors enabled with minimal settings detector :extraneous_indexes, enabled: true, ignore_tables: [], ignore_indexes: [] # ... (all other detectors with defaults) end ``` -------------------------------- ### Incorrect Dependent Option Detector Configuration Example Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/configuration.md Example configuration for the `incorrect_dependent_option` detector. ```ruby detector :incorrect_dependent_option, enabled: true, ignore_models: [], ignore_associations: ["User.posts"] ``` -------------------------------- ### Example Workflow - Step 1: Run detector and save output Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/api-reference/generators.md Demonstrates running the detector and saving output, showing the content of the output file. ```bash $ bundle exec rake active_record_doctor:unindexed_foreign_keys > /tmp/indexes.txt $ cat /tmp/indexes.txt add an index on users(account_id) - consider adding an index on the foreign key add an index on users(organization_id) - consider adding an index on the foreign key add an index on posts(user_id) - consider adding an index on the foreign key add an index on comments(post_id, user_id) - consider adding an index on the foreign key ``` -------------------------------- ### ConfigurationError Example Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/errors.md Example demonstrating a ConfigurationError due to an undefined variable in the configuration file. ```ruby # In .active_record_doctor.rb: ActiveRecordDoctor.configure do global :ignore_tables, undefined_variable # NameError end # Running: config = ActiveRecordDoctor.load_config(".active_record_doctor.rb") # => ActiveRecordDoctor::Error::ConfigurationError # Details will include: NameError (undefined local variable or method `undefined_variable') ``` -------------------------------- ### Extraneous Indexes - Problem 1: Redundant single-column index Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/api-reference/detector-examples.md Example of a redundant single-column index that can be dropped. ```ruby create_table :users do |t| t.string :email, null: false t.integer :account_id, null: false t.index [:email, :account_id] # Multi-column t.index :email # Extraneous! Can be dropped end ``` -------------------------------- ### Custom Configuration Example Source: https://github.com/gregnavis/active_record_doctor/blob/master/README.md Example of a custom configuration file (.active_record_doctor.rb) to ignore specific tables and configure a detector. ```ruby 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"] end ``` -------------------------------- ### CheckConstraint Representation Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/types.md Example of how to get check constraints for a table. ```ruby constraints = connection.check_constraints("users") ``` -------------------------------- ### Example Workflow - Step 2: Generate migrations Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/api-reference/generators.md Demonstrates generating migration files based on the prepared input file, showing the output. ```bash $ rails generate active_record_doctor:add_indexes /tmp/indexes.txt create db/migrate/20240528120000_index_foreign_keys_in_users.rb class IndexForeignKeysInUsers < ActiveRecord::Migration[7.0] def change add_index :users, [:account_id] add_index :users, [:organization_id] end end create db/migrate/20240528120001_index_foreign_keys_in_posts.rb class IndexForeignKeysInPosts < ActiveRecord::Migration[7.0] def change add_index :posts, [:user_id] end end create db/migrate/20240528120002_index_foreign_keys_in_comments.rb class IndexForeignKeysInComments < ActiveRecord::Migration[7.0] def change add_index :comments, [:post_id, :user_id] end end ``` -------------------------------- ### Extraneous Indexes - Problem 2: Index on primary key Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/api-reference/detector-examples.md Example of an index on the primary key column, which is extraneous. ```ruby create_table :users do |t| t.index :id # Extraneous! Primary key already indexed end ``` -------------------------------- ### Dummy Logger log Method Example Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/api-reference/logging.md Execute a block without logging. ```ruby logger.log("Processing") do # This code runs but nothing is logged end ``` -------------------------------- ### Index Representation Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/types.md Example of how to get an index object from a connection. ```ruby index = connection.indexes("users").first ``` -------------------------------- ### Missing Presence Validation - Problem 1: Missing validator on NOT NULL column Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/api-reference/detector-examples.md Example of a NOT NULL column without a presence validator. ```ruby class User < ApplicationRecord # Column: email, type: string, null: false # No presence validator! end ``` -------------------------------- ### Incorrect Boolean Presence Validation Detector Configuration Example Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/configuration.md Example configuration for the `incorrect_boolean_presence_validation` detector. ```ruby detector :incorrect_boolean_presence_validation, enabled: true, ignore_models: ["User"], ignore_attributes: ["Post.published"] ``` -------------------------------- ### ForeignKey Representation Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/types.md Example of how to get a foreign key object from a connection. ```ruby fk = connection.foreign_keys("posts").first ``` -------------------------------- ### Example Usage of Ignore Patterns Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/types.md An example of how to configure ignore patterns for tables in ActiveRecordDoctor. ```ruby ActiveRecordDoctor.configure do global :ignore_tables, [ "ar_internal_metadata", # String exact match /^legacy_/, # Regexp match /^temp/i, # Case-insensitive regexp "archive_*" # Glob-like (treated as exact string) ] end ``` -------------------------------- ### Example Output for Short Primary Key Type Source: https://github.com/gregnavis/active_record_doctor/blob/master/README.md Example output indicating a primary key should be migrated to a wider integer type. ```text change the type of companies.id to bigint ``` -------------------------------- ### Example: Running a single detector Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/api-reference/runner.md Demonstrates how to set up the runner and execute a single detector, checking for missing foreign keys. ```ruby config = ActiveRecordDoctor.load_config_with_defaults(nil) logger = ActiveRecordDoctor::Logger::Dummy.new runner = ActiveRecordDoctor::Runner.new(config: config, logger: logger) success = runner.run_one(:missing_foreign_keys) exit(1) unless success ``` -------------------------------- ### Incorrect Boolean Presence Validation Configuration Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/api-reference/detector-examples.md Configuration for the `incorrect_boolean_presence_validation` detector. ```ruby detector :incorrect_boolean_presence_validation, enabled: true, ignore_models: ["LegacyModel"], ignore_attributes: ["Setting.enabled"] ``` -------------------------------- ### Logger Interface Example Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/types.md An example of a custom logger class implementing the required interface. ```ruby class MyLogger def log(message) # ... logging implementation yield if block_given? # Must yield to block if provided end end ``` -------------------------------- ### Detector Registry Example Usage Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/types.md Example of retrieving all detectors and a specific detector class. ```ruby all_detectors = ActiveRecordDoctor.detectors # => { # :extraneous_indexes => ExtraneousIndexes class, # :missing_foreign_keys => MissingForeignKeys class, # ... # } detector_class = ActiveRecordDoctor.detectors[:extraneous_indexes] # => ExtraneousIndexes class ``` -------------------------------- ### Incorrect Dependent Option Configuration Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/api-reference/detector-examples.md Configuration for the `incorrect_dependent_option` detector. ```ruby detector :incorrect_dependent_option, enabled: true, ignore_models: ["Archive"], ignore_associations: ["Post.comments"] ``` -------------------------------- ### Custom Configuration Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/INDEX.md Example of creating a custom configuration file for ActiveRecordDoctor. ```ruby ActiveRecordDoctor.configure do global :ignore_tables, ["legacy_data"] detector :extraneous_indexes, ignore_tables: ["users"] end ``` -------------------------------- ### Check Database Adapter Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/REFERENCE.md Example of how to check the current database adapter type. ```ruby if ActiveRecordDoctor::Utils.postgresql? # PostgreSQL-specific code elsif ActiveRecordDoctor::Utils.mysql? # MySQL-specific code elsif ActiveRecordDoctor::Utils.sqlite? # SQLite-specific code end ``` -------------------------------- ### Missing Presence Validation - Problem 2: Optional belongs_to with NOT NULL foreign key Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/api-reference/detector-examples.md Example of an optional belongs_to association with a NOT NULL foreign key. ```ruby class Post < ApplicationRecord belongs_to :user, optional: true # But user_id is NOT NULL! end ``` -------------------------------- ### Build and Publish Gem Source: https://github.com/gregnavis/active_record_doctor/blob/master/RELEASE_PROCESS.md Commands to build and publish the gem to RubyGems.org. ```bash gem build active_record_doctor.gemspec gem push ``` -------------------------------- ### Error message example Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/api-reference/generators.md Example of an error message generated for malformed input. ```text cannot extract table and column name from line 1: this line is malformed ``` -------------------------------- ### Usage Example in Detector Code Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/api-reference/utilities.md Demonstrates how to use database adapter detection within a detector's `detect` method. ```ruby module ActiveRecordDoctor module Detectors class MyDetector < Base private def detect # Check which database adapter is in use if Utils.postgresql?(connection) detect_postgresql_issues elsif Utils.mysql?(connection) detect_mysql_issues end end def detect_postgresql_issues # PostgreSQL-specific queries end def detect_mysql_issues # MySQL-specific queries end end end end ``` -------------------------------- ### locals_and_globals Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/api-reference/detectors-base.md Get lists of local and global configuration settings for this detector. ```ruby locals, globals = ActiveRecordDoctor::Detectors::ExtraneousIndexes.locals_and_globals # => [[:enabled, :ignore_tables, :ignore_indexes], [:ignore_tables, :ignore_indexes]] ``` -------------------------------- ### config(key) Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/api-reference/detectors-base.md Get configuration value, automatically merging global and local settings. ```ruby ignore_tables = config(:ignore_tables) # Returns merged array of local + global ignore_tables ``` -------------------------------- ### Custom Rails Setup Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/api-reference/rails-integration.md For advanced configurations, create a custom Rake task in lib/tasks/. ```ruby # lib/tasks/active_record_doctor.rb require "active_record_doctor" ActiveRecordDoctor::Rake::Task.new do |task| # Standard Rails setup task.deps = [:environment] # Custom setup after environment task.setup = lambda do Rails.application.eager_load! # Additional setup if needed require_relative "../../app/models/concerns/auditable" end # Custom config file location task.config_path = Rails.root.join("config/.active_record_doctor.rb") end ``` -------------------------------- ### ConfigurationError Constructor Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/errors.md Example of creating a ConfigurationError instance. ```ruby error = ActiveRecordDoctor::Error::ConfigurationError.new(original_exception) ``` -------------------------------- ### Example Output Format for Help Text Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/api-reference/utilities.md Shows the expected output format for help text generated by ActiveRecordDoctor::Help. ```text - Configuration options: - () - - () - ... Where is either "local only" or "local and global" ``` -------------------------------- ### Generate Migrations Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/INDEX.md Example of generating migrations using ActiveRecordDoctor Rake tasks. ```bash bundle exec rake active_record_doctor:unindexed_foreign_keys > /tmp/indexes.txt rails generate active_record_doctor:add_indexes /tmp/indexes.txt rails db:migrate ``` -------------------------------- ### Find All Available Detectors Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/REFERENCE.md How to get a list of all available detector keys. ```ruby ActiveRecordDoctor.detectors.keys # => [:extraneous_indexes, :missing_foreign_keys, ...] ``` -------------------------------- ### Programmatic Usage Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/INDEX.md Example of how to use ActiveRecordDoctor programmatically in Ruby. ```ruby config = ActiveRecordDoctor.load_config_with_defaults(nil) logger = ActiveRecordDoctor::Logger::Dummy.new runner = ActiveRecordDoctor::Runner.new(config: config, logger: logger) success = runner.run_all ``` -------------------------------- ### Association Reflection Example Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/types.md Example of reflecting on all associations of a model. ```ruby User.reflect_on_all_associations.first ``` -------------------------------- ### Hierarchical Logger log Method Example Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/api-reference/logging.md Log a message with indentation and execute a block with increased indentation. ```ruby logger.log("Starting detection") do logger.log("Checking table: users") do # Nested logging end logger.log("Checking table: posts") end ``` -------------------------------- ### Get Current Version Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/REFERENCE.md How to get the current version of the ActiveRecordDoctor gem. ```ruby puts ActiveRecordDoctor::VERSION # => "2.0.1" ``` -------------------------------- ### Example Output for Incorrect `dependent` Option Source: https://github.com/gregnavis/active_record_doctor/blob/master/README.md Example outputs for incorrect `dependent` options on associations. ```text use `dependent: :delete_all` or similar on Company.users - associated models have no validations and can be deleted in bulk use `dependent: :destroy` or similar on Post.comments - the associated model has callbacks that are currently skipped ``` -------------------------------- ### Rake Task - Production Mode Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/api-reference/logging.md Example of running the Rake task in production mode, resulting in no debug output. ```bash # Production - no debug output bundle exec rake active_record_doctor ``` -------------------------------- ### Regexp-Based Ignores Example Source: https://github.com/gregnavis/active_record_doctor/blob/master/README.md Example of using regular expressions in the configuration to ignore tables and models. ```ruby ActiveRecordDoctor.configure do global :ignore_tables, [ # Ignore all legacy tables. /^legacy_/ ] global :ignore_models, [ # Ignore all legacy models. /^Legacy::/ ] end ``` -------------------------------- ### Configuration for Missing Non-NULL Constraint Detector Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/api-reference/detector-examples.md Configuration options for the `missing_non_null_constraint` detector, including enabling it and ignoring specific tables or columns. ```ruby detector :missing_non_null_constraint, enabled: true, ignore_tables: ["archive_items"], ignore_columns: ["users.bio"] ``` -------------------------------- ### Case-Insensitive Match for Ignore Settings Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/configuration.md Example of using case-insensitive regular expressions for matching table names. ```ruby ignore_tables: [/^system_/i] # Matches system_logs, System_Data, SYSTEM_config, etc. ``` -------------------------------- ### GitLab CI Integration Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/api-reference/rake-task.md Example of integrating ActiveRecord Doctor into a GitLab CI pipeline. ```yaml test-db: script: - bundle exec rake active_record_doctor ``` -------------------------------- ### Incorrect Length Validation Detector Configuration Example Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/configuration.md Example configuration for the `incorrect_length_validation` detector. ```ruby detector :incorrect_length_validation, enabled: true, ignore_attributes: ["User.email"] ``` -------------------------------- ### ActiveRecordDoctor::Help#to_s Method Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/api-reference/utilities.md Generates help text as a string. ```ruby help = ActiveRecordDoctor::Help.new(ActiveRecordDoctor::Detectors::ExtraneousIndexes) puts help.to_s ``` -------------------------------- ### Column Introspection Example Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/types.md Example of retrieving column information from the database. ```ruby column = connection.columns("users").first ``` -------------------------------- ### Detector Configuration Example Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/api-reference/detectors.md Demonstrates how to configure detectors, including global and detector-specific settings like ignore lists and enabled flags. ```ruby ActiveRecordDoctor.configure do # Global settings apply to all or multiple detectors global :ignore_tables, [ "ar_internal_metadata", "schema_migrations", "active_storage_blobs", "active_storage_attachments", "action_text_rich_texts" ] # Detector-specific settings detector :extraneous_indexes, enabled: true, ignore_tables: ["users"], # local override ignore_indexes: ["custom_idx"] # local override detector :missing_presence_validation, enabled: true, ignore_models: ["Post"], ignore_attributes: ["User.bio"], ignore_columns_with_default: true end ``` -------------------------------- ### initialize(config:, logger:, io:) Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/api-reference/detectors-base.md Create a new detector instance. ```ruby detector = ActiveRecordDoctor::Detectors::ExtraneousIndexes.new( config: config, logger: logger, io: $stdout ) ``` -------------------------------- ### Custom Rake Task Setup Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/api-reference/utilities.md Demonstrates how to define a custom Rake task using `ActiveRecordDoctor::Rake::Task` and how to integrate help text generation for detectors. ```ruby ActiveRecordDoctor::Rake::Task.new do |task| task.deps = [:environment] # Help text generation in custom rake tasks task.setup = -> do Rails.application.eager_load! # Can use Help to show information help = ActiveRecordDoctor::Help.new( ActiveRecordDoctor::Detectors::ExtraneousIndexes ) puts help if ENV["HELP"] end end ``` -------------------------------- ### Example Output for Incorrect Length Validations Source: https://github.com/gregnavis/active_record_doctor/blob/master/README.md Example outputs for length validation mismatches between model and database. ```text set the maximum length in the validator of User.email (currently 32) and the database limit on users.email (currently 64) to the same value add a length validator on User.address to enforce a maximum length of 64 defined on users.address ``` -------------------------------- ### Run a Specific Detector Programmatically Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/api-reference/detector-examples.md Ruby code to programmatically run a specific detector (`MissingPresenceValidation`) and output whether problems were found. ```ruby config = ActiveRecordDoctor.load_config_with_defaults(nil) logger = ActiveRecordDoctor::Logger::Hierarchical.new($stderr) io = $stdout success = ActiveRecordDoctor::Detectors::MissingPresenceValidation.run( config: config, logger: logger, io: io ) puts success ? "No problems found" : "Problems were found" ``` -------------------------------- ### Detector Configured Twice Error Example Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/errors.md Example of a DetectorConfiguredTwice error when the same detector is configured more than once. ```ruby raise ActiveRecordDoctor::Error::DetectorConfiguredTwice[:extraneous_indexes] ``` -------------------------------- ### Debugging Output Example Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/api-reference/rails-integration.md Example of the detailed output when debug logging is enabled for ActiveRecordDoctor. ```text extraneous_indexes subindexes_of_multi_column_indexes Iterating over data sources users Index index_users_on_email_and_account_id ... ``` -------------------------------- ### InclusionValidator Example Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/types.md Example of defining an inclusion validation and retrieving the validator object. ```ruby class User < ApplicationRecord validates :status, inclusion: { in: ["active", "inactive"] } end validator = User.validators.find { |v| v.is_a?(InclusionValidator) } validator.attributes # => [:status] validator.options[:in] # => ["active", "inactive"] ``` -------------------------------- ### Step 4: Run Migrations Source: https://github.com/gregnavis/active_record_doctor/blob/master/README.md Command to apply the generated migrations to the database. ```bash bundle exec rake db:migrate ``` -------------------------------- ### PresenceValidator Example Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/types.md Example of defining a presence validation and retrieving the validator object. ```ruby class User < ApplicationRecord validates :email, presence: true end validator = User.validators.find { |v| v.is_a?(PresenceValidator) } validator.attributes # => [:email] ``` -------------------------------- ### BelongsToReflection Example Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/types.md Example of reflecting on a specific belongs_to association and accessing its methods. ```ruby Post.reflect_on_association(:user) reflection = Post.reflect_on_association(:user) reflection.name # => :user reflection.macro # => :belongs_to reflection.foreign_key # => "user_id" reflection.optional? # => false (if not explicitly set) ``` -------------------------------- ### Using Dummy Logger with Runner (Production) Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/api-reference/logging.md Configuration and initialization of ActiveRecordDoctor with a Dummy logger for production environments. ```ruby config = ActiveRecordDoctor.load_config_with_defaults(nil) logger = ActiveRecordDoctor::Logger::Dummy.new runner = ActiveRecordDoctor::Runner.new(config: config, logger: logger) runner.run_all # No debug output is produced ``` -------------------------------- ### Display help text for a specific detector Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/api-reference/runner.md Shows detailed help information for a given detector. ```ruby runner.help(:extraneous_indexes) ``` -------------------------------- ### Duplicate Global Setting Error Example Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/errors.md Example of a DuplicateGlobalSetting error when the same global setting is provided more than once. ```ruby raise ActiveRecordDoctor::Error::DuplicateGlobalSetting[:ignore_tables] ``` -------------------------------- ### Dummy Logger log Method with Return Value Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/api-reference/logging.md Example demonstrating the return value of the log method when a block is provided. ```ruby logger = ActiveRecordDoctor::Logger::Dummy.new result = logger.log("Processing users") do User.count end # Nothing is logged, but User.count is executed and result contains the count ``` -------------------------------- ### Workflow - Step 3: Review generated migrations Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/api-reference/generators.md Commands to list and view the generated migration files. ```bash ls db/migrate/*_index_*.rb cat db/migrate/20240528120000_index_foreign_keys_in_users.rb ``` -------------------------------- ### Default Configuration Source: https://github.com/gregnavis/active_record_doctor/blob/master/README.md Illustrates the default behavior where no configuration file is needed. ```bash bundle exec active_record_doctor ``` -------------------------------- ### GitLab CI/CD Example Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/api-reference/rails-integration.md Example of integrating Active Record Doctor into a GitLab CI workflow. ```yaml database_doctor: image: ruby:3.2 services: - postgres:15 variables: POSTGRES_DB: test POSTGRES_PASSWORD: postgres script: - bundle install - bundle exec rails db:setup - bundle exec rake active_record_doctor ``` -------------------------------- ### Get database connection and column names Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/api-reference/detectors-base.md Retrieves the database connection and then gets the names of all columns for a specified table. ```ruby conn = connection column_names = conn.columns("users").map(&:name) ``` -------------------------------- ### Workflow - Step 4: Run migrations Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/api-reference/generators.md Command to apply the generated database migrations. ```bash rails db:migrate ``` -------------------------------- ### Unrecognized Global Setting Error Example Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/errors.md Example of an UnrecognizedGlobalSetting error when an unknown global setting is used. ```ruby raise ActiveRecordDoctor::Error::UnrecognizedGlobalSetting[ :unknown_global, [:ignore_tables, :ignore_models, ...] ] ``` -------------------------------- ### Migrate command Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/api-reference/generators.md Command to run database migrations. ```bash $ bundle exec rails db:migrate ``` -------------------------------- ### Unrecognized Detector Settings Error Example Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/errors.md Example of an UnrecognizedDetectorSettings error when unknown settings are provided for a detector. ```ruby raise ActiveRecordDoctor::Error::UnrecognizedDetectorSettings[ :extraneous_indexes, [:unknown_setting], [:enabled, :ignore_tables, :ignore_indexes] ] ``` -------------------------------- ### run Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/api-reference/detectors-base.md Execute the detector: call `detect`, format and output problems, and return success status. ```ruby success = detector.run ``` -------------------------------- ### GitHub Actions CI/CD Example Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/api-reference/rails-integration.md Example of integrating Active Record Doctor into a GitHub Actions workflow. ```yaml name: Database Checks on: pull_request: push: branches: [main, develop] jobs: database-doctor: runs-on: ubuntu-latest services: postgres: image: postgres:15 env: POSTGRES_PASSWORD: postgres options: >- --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5 steps: - uses: actions/checkout@v3 - uses: ruby/setup-ruby@v1 with: ruby-version: 3.2 bundler-cache: true - name: Setup database run: bundle exec rails db:setup - name: Run Active Record Doctor run: bundle exec rake active_record_doctor ``` -------------------------------- ### Basic Custom Logger Implementation Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/api-reference/logging.md Demonstrates the minimum requirements for a custom logger by implementing the `log` method. ```ruby class MyLogger def log(message) puts "[#{Time.now}] #{message}" yield if block_given? end end logger = MyLogger.new runner = ActiveRecordDoctor::Runner.new(config: config, logger: logger, io: $stdout) ``` -------------------------------- ### ActiveRecordDoctor::Help Constructor Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/api-reference/utilities.md Constructor for the Help class. ```ruby help = ActiveRecordDoctor::Help.new(detector_class) ``` -------------------------------- ### Example Migration for Changing Primary Key Type Source: https://github.com/gregnavis/active_record_doctor/blob/master/README.md Example Ruby on Rails migration to change a primary key type to bigint. ```ruby class ChangeCompaniesPrimaryKeyType < ActiveRecord::Migration[5.1] def change change_column :companies, :id, :bigint end end ``` -------------------------------- ### Run all available detectors Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/api-reference/runner.md Executes all detectors sequentially. ```ruby runner.run_all ``` -------------------------------- ### Example Output for Incorrect Boolean Presence Validation Source: https://github.com/gregnavis/active_record_doctor/blob/master/README.md Example output indicating a presence validator used incorrectly on a boolean column. ```text replace the `presence` validator on User.active with `inclusion` - `presence` can't be used on booleans ``` -------------------------------- ### Unrecognized Detector Name Error Example Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/errors.md Example of how an UnrecognizedDetectorName error is raised when a configuration references a non-existent detector. ```ruby raise ActiveRecordDoctor::Error::UnrecognizedDetectorName[ :invalid_detector, [:extraneous_indexes, :missing_foreign_keys, ...] ] ``` -------------------------------- ### Load Configuration Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/api-reference/config.md Load configuration from a Ruby file and return the Config object. ```ruby config = ActiveRecordDoctor.load_config(".active_record_doctor.rb") ``` -------------------------------- ### Automatic Logger Selection Examples Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/api-reference/rake-task.md Examples showing how to set the ACTIVE_RECORD_DOCTOR_DEBUG environment variable for different logging levels. ```bash # Production - silent (Dummy logger) bundle exec rake active_record_doctor # Development - detailed output to stderr (Hierarchical logger) ACTIVE_RECORD_DOCTOR_DEBUG=1 bundle exec rake active_record_doctor ``` -------------------------------- ### Pattern 3: Get Help for a Detector Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/REFERENCE.md Command to get help information for a specific detector, e.g., 'missing_presence_validation'. ```bash bundle exec rake active_record_doctor:missing_presence_validation:help ``` -------------------------------- ### Runner Constructor Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/api-reference/runner.md Initializes a new instance of the Runner class. ```ruby ActiveRecordDoctor::Runner.new(config:, logger:, io: $stdout) ``` -------------------------------- ### Access Current Configuration Source: https://github.com/gregnavis/active_record_doctor/blob/master/_autodocs/api-reference/config.md Demonstrates how to access the configuration object currently being processed by `load_config`. ```ruby config = ActiveRecordDoctor.current_config ```