{"id":28865266,"url":"https://github.com/tommy2118/rails-migration-guard","last_synced_at":"2026-05-05T13:39:12.134Z","repository":{"id":299152351,"uuid":"1002209251","full_name":"tommy2118/rails-migration-guard","owner":"tommy2118","description":"Prevent orphaned Rails migrations in development and staging environments","archived":false,"fork":false,"pushed_at":"2025-06-15T00:39:33.000Z","size":0,"stargazers_count":0,"open_issues_count":5,"forks_count":0,"subscribers_count":0,"default_branch":"master","last_synced_at":"2025-06-15T01:30:26.384Z","etag":null,"topics":["database","development-tools","git","migrations","rails","ruby"],"latest_commit_sha":null,"homepage":null,"language":"Ruby","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/tommy2118.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"MIT-LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2025-06-15T00:32:40.000Z","updated_at":"2025-06-15T00:45:40.000Z","dependencies_parsed_at":"2025-06-15T01:30:29.611Z","dependency_job_id":"edd88d9a-77ef-4c07-989b-4df4ca7c7d98","html_url":"https://github.com/tommy2118/rails-migration-guard","commit_stats":null,"previous_names":["tommy2118/rails-migration-guard"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/tommy2118/rails-migration-guard","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tommy2118%2Frails-migration-guard","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tommy2118%2Frails-migration-guard/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tommy2118%2Frails-migration-guard/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tommy2118%2Frails-migration-guard/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/tommy2118","download_url":"https://codeload.github.com/tommy2118/rails-migration-guard/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tommy2118%2Frails-migration-guard/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":260924169,"owners_count":23083505,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["database","development-tools","git","migrations","rails","ruby"],"created_at":"2025-06-20T10:01:35.029Z","updated_at":"2026-05-05T13:39:12.129Z","avatar_url":"https://github.com/tommy2118.png","language":"Ruby","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Rails Migration Guard\n\n[![Gem Version](https://badge.fury.io/rb/rails_migration_guard.svg)](https://badge.fury.io/rb/rails_migration_guard)\n[![Build Status](https://github.com/tommy2118/rails-migration-guard/workflows/CI/badge.svg)](https://github.com/tommy2118/rails-migration-guard/actions)\n[![GitHub issues](https://img.shields.io/github/issues/tommy2118/rails-migration-guard)](https://github.com/tommy2118/rails-migration-guard/issues)\n[![GitHub license](https://img.shields.io/github/license/tommy2118/rails-migration-guard)](https://github.com/tommy2118/rails-migration-guard/blob/master/MIT-LICENSE)\n\nRails Migration Guard helps prevent orphaned database migrations in development and staging environments. It tracks migration state across git branches, identifies migrations that exist only locally, and provides tools for cleanup and prevention.\n\n📚 **[View Full Documentation](https://tommy2118.github.io/rails-migration-guard/)** | 🚀 **[Quick Start Guide](https://tommy2118.github.io/rails-migration-guard/quick-start)** | 🎯 **[Examples \u0026 Tutorials](https://tommy2118.github.io/rails-migration-guard/examples/)** | 🔧 **[API Reference](https://tommy2118.github.io/rails-migration-guard/docs/#api-reference)**\n\n## Compatibility\n\nRails Migration Guard supports:\n\n- **Ruby**: 3.0.0 and higher\n- **Rails**: 6.1.0 through 8.0+ (tested up to Rails 8.0.2)\n- **Databases**: SQLite, PostgreSQL, MySQL\n- **Git**: 2.0 and higher\n\n## The Problem\n\nWhen working on feature branches, developers often:\n- Create and run migrations locally that never make it to the main branch\n- Switch between branches with different migration states\n- End up with database schemas that don't match any branch\n- Experience confusing errors when migrations reference tables/columns that don't exist\n\nRails Migration Guard solves these issues by tracking which migrations belong to which branches and warning you about potential problems.\n\n## Features\n\n- 🔍 **Track migrations** across git branches automatically\n- ⚠️ **Warn about orphaned migrations** when switching branches\n- 🧹 **Clean up migrations** that didn't make it to main/master\n- 🚂 **Sandbox mode** to test migrations without applying them\n- 📊 **Status reports** showing migration state relative to trunk\n- 🚫 **Production safe** - automatically disabled in production\n- ⚙️ **Highly configurable** with sensible defaults\n- 🤖 **CI/CD integration** with exit codes and JSON output\n- 🔄 **GitHub Actions support** with PR comments and status checks\n- 🐳 **Docker \u0026 CI ready** - automatic TTY detection and non-interactive modes\n\n## Installation\n\nAdd this line to your application's Gemfile:\n\n```ruby\ngroup :development, :staging do\n  gem 'rails_migration_guard'\nend\n```\n\nOr install directly from GitHub:\n\n```ruby\ngroup :development, :staging do\n  gem 'rails_migration_guard', github: 'tommy2118/rails-migration-guard'\nend\n```\n\nThen execute:\n\n```bash\n$ bundle install\n$ rails generate migration_guard:install\n$ rails db:migrate\n```\n\nThis will:\n1. Create an initializer at `config/initializers/migration_guard.rb`\n2. Generate a migration to create the `migration_guard_records` table\n3. Set up the gem with sensible defaults\n\n### Optional: Install Git Hooks\n\nTo automatically check migration status when switching branches:\n\n```bash\n$ rails generate migration_guard:hooks\n```\n\nThis installs a post-checkout hook that runs migration status checks when switching branches.\n\nFor additional protection, install a pre-push hook:\n\n```bash\n$ rails generate migration_guard:hooks --pre-push\n```\n\nThis prevents pushing when orphaned migrations are detected.\n\n## Usage\n\n### Basic Commands\n\n```bash\n# Check migration status\n$ rails db:migration:status\n\n═══════════════════════════════════════════════════════\nMigration Status (main branch)\n═══════════════════════════════════════════════════════\n✓ Synced:    15 migrations\n⚠ Orphaned:   2 migrations (local only)\n✗ Missing:    0 migrations (in trunk, not local)\n\nOrphaned Migrations:\n  20240115123456 AddUserPreferences\n    Branch: feature/user-prefs\n    Author: developer@example.com\n    Age: 3 days\n    \nRun `rails db:migration:rollback_orphaned` to clean up\n\n# Roll back orphaned migrations interactively\n$ rails db:migration:rollback_orphaned\n\n# Check for issues (useful in CI/CD)\n$ rails db:migration:ci\n\n# View migration history with filtering\n$ rails db:migration:history                    # All recent migrations\n$ rails db:migration:history BRANCH=main        # Filter by branch\n$ rails db:migration:history DAYS=7             # Last 7 days\n$ rails db:migration:history AUTHOR=dev@example # Filter by author\n$ rails db:migration:history FORMAT=json        # JSON output\n\n# View author statistics and contributions\n$ rails db:migration:authors                    # Author report\n\n# Recover from inconsistent migration states\n$ rails db:migration:recover                     # Interactive recovery\n$ AUTO=true rails db:migration:recover           # Automatic recovery\n```\n\n### Migration Recovery\n\nRails Migration Guard includes powerful recovery tools to help fix inconsistent migration states:\n\n```bash\n# Analyze migration inconsistencies\n$ rails db:migration:recover\n\n⚠️  Detected migration inconsistencies:\n\n1. Partial rollback\n   Version: 20240115123456\n   Migration appears to be stuck in rollback state\n   Severity: HIGH\n   Branch: feature/user-prefs\n   Last updated: 2024-01-15 14:30:45\n   Recovery options: complete_rollback, restore_migration, mark_as_rolled_back\n\n2. Orphaned schema\n   Version: 20240116789012\n   Schema contains migration not tracked by Migration Guard\n   Severity: MEDIUM\n   Recovery options: track_migration, remove_from_schema\n\nSelect option (0-3): 1\n✓ Rollback completed for 20240115123456\n```\n\nRecovery features include:\n- **Automatic database backups** before recovery operations\n- **Multiple recovery strategies** for each type of issue\n- **Interactive mode** for careful review of each issue\n- **Automatic mode** for CI/CD pipelines\n- **Safe rollback** of partially completed migrations\n- **Git integration** to restore missing migration files\n\nCommon recovery scenarios:\n- Migrations stuck in `rolling_back` state\n- Schema entries without tracking records\n- Missing migration files\n- Duplicate tracking records\n- Migrations applied but missing from schema\n\n### Automatic Tracking\n\nMigrations are automatically tracked when you run:\n\n```bash\n$ rails db:migrate    # Tracks as 'applied'\n$ rails db:rollback   # Tracks as 'rolled_back'\n```\n\n### Author Tracking\n\nRails Migration Guard automatically captures author information from git when tracking migrations:\n\n```bash\n# View author statistics\n$ rails db:migration:authors\n\n👥 Migration Authors Report (main)\nAuthor                           Total    Applied  Orphaned  Rolled Back  Latest Migration    \n-----------------------------------------------------------------------------------------------\nalice@example.com                    12        8         2            2    2024-06-15 14:23\nbob@example.com                       7        5         1            1    2024-06-14 09:15\ncharlie@example.com                   3        3         0            0    2024-06-13 16:42\n-----------------------------------------------------------------------------------------------\n\n📊 Authors Summary:\n  Total authors: 3\n  Total tracked migrations: 22\n  Most active: alice@example.com (12 migrations)\n  Average per author: 7.3\n  Your rank: #1 (12 migrations)\n\n# Filter history by author\n$ rails db:migration:history AUTHOR=alice\n```\n\nAuthor tracking helps teams:\n- Identify who created specific migrations\n- Track migration patterns per developer\n- Find the right person to ask about a migration\n- Monitor team migration activity\n\n### Docker \u0026 CI/CD Support\n\nRails Migration Guard automatically detects non-TTY environments (Docker, CI) and switches to non-interactive mode:\n\n```bash\n# In Docker containers - automatically non-interactive\ndocker exec -it myapp rails db:migration:rollback_orphaned\n\n# Force non-interactive mode\nFORCE=true rails db:migration:rollback_orphaned\nNON_INTERACTIVE=true rails db:migration:recover\n\n# CI/CD automation\nAUTO=true rails db:migration:recover  # Auto-apply first recovery option\n```\n\nSee [Docker \u0026 CI/CD Documentation](https://tommy2118.github.io/rails-migration-guard/ci-integration.html#docker-support) for detailed examples.\n\n### Sandbox Mode\n\nTest migrations without applying them:\n\n```ruby\n# config/initializers/migration_guard.rb\nMigrationGuard.configure do |config|\n  config.sandbox_mode = true\nend\n```\n\n## Configuration\n\n```ruby\n# config/initializers/migration_guard.rb\nMigrationGuard.configure do |config|\n  # Environments where MigrationGuard is active\n  config.enabled_environments = [:development, :staging]\n\n  # Git integration level\n  # :off - No git integration\n  # :warning - Warn about orphaned migrations\n  # :auto_rollback - Reserved for future use (currently behaves like :warning)\n  config.git_integration_level = :warning\n\n  # Track additional information\n  config.track_branch = true\n  config.track_author = true      # Captures git user.email\n  config.track_timestamp = true\n\n  # Behavior options\n  config.warn_on_switch = true             # Warn when switching branches\n  config.block_deploy_with_orphans = false # Not yet functional - reserved for future use\n\n  # Cleanup policies\n  config.auto_cleanup = false              # Automatically clean up old records\n  config.cleanup_after_days = 30           # Days before cleanup\n\n  # Main branch names to check against\n  config.main_branch_names = %w[main master trunk]\n  \n  # Target branches to compare migrations against (optional)\n  # When set, migrations will be compared against all specified branches\n  # instead of just the main branch. Useful for teams with multiple\n  # long-lived branches (e.g., develop, staging, production)\n  # config.target_branches = %w[main develop staging]\n  \n  # Logging configuration\n  # config.log_level = :info  # :debug, :info, :warn, :error, :fatal\n  # config.logger = Rails.logger  # or Logger.new('log/migration_guard.log')\n  \n  # Enable debug logging via environment variable\n  # ENV['MIGRATION_GUARD_DEBUG'] = 'true'\nend\n```\n\n## CI/CD Integration\n\nRails Migration Guard provides comprehensive CI/CD support with dedicated commands and integrations.\n\n### Quick Start\n\n```bash\n# CI-specific command with proper exit codes\nbundle exec rails db:migration:ci\n\n# Strict mode - fail on any issues\nbundle exec rails db:migration:ci STRICT=true\n\n# JSON output for parsing\nbundle exec rails db:migration:ci FORMAT=json\n```\n\n### GitHub Actions\n\nRails Migration Guard includes native GitHub Actions support with:\n- 🔄 Ready-to-use workflow files\n- 💬 Automatic PR comments\n- ✅ Status checks\n- 📊 Job summaries\n\n```yaml\n# .github/workflows/migration-check.yml\nname: Migration Check\non: pull_request\n\njobs:\n  check:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/checkout@v4\n        with:\n          fetch-depth: 0\n      \n      - uses: ruby/setup-ruby@v1\n        with:\n          bundler-cache: true\n      \n      - name: Setup test database\n        run: bundle exec rails db:test:prepare\n      \n      - uses: ./.github/actions/migration-guard\n        with:\n          strict: false\n          comment-on-pr: true\n```\n\n**📘 See the [GitHub Actions guide](https://tommy2118.github.io/rails-migration-guard/github-actions.html) for detailed setup and advanced configurations.**\n\n### Other CI Platforms\n\nSee the [CI Integration guide](https://tommy2118.github.io/rails-migration-guard/ci-integration.html) for examples with:\n- GitLab CI\n- CircleCI\n- Jenkins\n- Travis CI\n\n### Staging Protection\n\n```ruby\n# config/initializers/migration_guard.rb\nMigrationGuard.configure do |config|\n  config.block_deploy_with_orphans = true if Rails.env.staging? # Not yet functional - reserved for future use\nend\n```\n\n## How It Works\n\n1. **Tracking**: When migrations run, MigrationGuard records the version, branch, author, and status\n2. **Comparison**: It compares local migrations against those in your main branch\n3. **Detection**: Identifies migrations that exist locally but not in trunk (orphaned)\n4. **Cleanup**: Provides tools to safely roll back orphaned migrations\n\n## Best Practices\n\n1. **Review before merging**: Check `rails db:migration:status` before creating PRs\n2. **Clean up regularly**: Roll back orphaned migrations when switching contexts\n3. **Use sandbox mode**: Test complex migrations before applying them\n4. **Configure for your workflow**: Adjust settings based on team size and branch strategy\n\n## Debug Logging\n\nMigrationGuard includes comprehensive logging to help diagnose issues in production:\n\n```bash\n# Enable debug logging temporarily\nMIGRATION_GUARD_DEBUG=true rails db:migration:status\n\n# Or configure in your initializer\nMigrationGuard.configure do |config|\n  config.log_level = :debug\n  config.logger = Logger.new('log/migration_guard.log')\nend\n```\n\nDebug logs include:\n- Git operations and branch detection\n- Migration tracking and status changes\n- Performance timing for database operations\n- Detailed error messages with context\n\n## Troubleshooting\n\nFor comprehensive troubleshooting information, see our [Troubleshooting Guide](https://tommy2118.github.io/rails-migration-guard/troubleshooting.html).\n\nCommon issues:\n- **\"Migration not found\" errors**: Usually means you have orphaned migrations. Run `rails db:migration:status` to identify them.\n- **Git integration not working**: Ensure you're in a git repository and have git installed. See [Git Integration Edge Cases](https://tommy2118.github.io/rails-migration-guard/troubleshooting.html#git-integration-edge-cases) for advanced scenarios.\n- **Special branch names**: Branch names with spaces, special characters, or unicode may need special handling. See the troubleshooting guide.\n- **Performance concerns**: The gem has minimal overhead. Set `git_integration_level: :off` to disable git operations if needed.\n\n## Development\n\nAfter checking out the repo:\n\n```bash\n$ bundle install\n$ bundle exec rspec        # Run tests\n$ bundle exec rubocop      # Check code style\n$ bundle exec rake         # Run default tasks\n```\n\n## Known Issues\n\n### Ruby 3.4.1 Compatibility\n\nWhen using Ruby 3.4.1 with Rails 7.0.x, you may see warnings like:\n\n```\nwarning: method redefined; discarding old to_s\nwarning: previous definition of to_s was here\n```\n\nThese warnings come from ActiveSupport 7.0.x itself and do not affect the functionality of Rails Migration Guard. The warnings are resolved in Rails 7.1+ and Rails 8.0+. If the warnings are bothersome, consider:\n\n1. Upgrading to Rails 7.1 or later\n2. Using Ruby 3.3.x until you can upgrade Rails\n3. Suppressing warnings with `RUBYOPT=\"-W0\"` (not recommended for development)\n\n## Contributing\n\n1. Fork it (https://github.com/tommy2118/rails-migration-guard/fork)\n2. Create your feature branch (`git checkout -b feature/my-new-feature`)\n3. Write tests for your changes\n4. Make your changes and ensure tests pass\n5. Commit your changes (`git commit -am 'Add some feature'`)\n6. Push to the branch (`git push origin feature/my-new-feature`)\n7. Create a new Pull Request\n\n## License\n\nThe gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).\n\n## Credits\n\nCreated and maintained by Tommy A. Caruso.\n\n## Changelog\n\nSee [CHANGELOG.md](https://github.com/tommy2118/rails-migration-guard/blob/master/CHANGELOG.md) for a history of changes.","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftommy2118%2Frails-migration-guard","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ftommy2118%2Frails-migration-guard","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftommy2118%2Frails-migration-guard/lists"}