On a staging database restored from a production dump, why does bin/rails db:reset refuse to run, and what does ar_internal_metadata have to do with it?
answer
- a key-value table beside schema_migrations
- environment stored on each migrate
- protected_environments defaults to production
- ProtectedEnvironmentError vs EnvironmentMismatchError
- db:environment:set rewrites the value
basics
~10 sar_internal_metadata stores the environment that last migrated the database; the dump says production. Destructive tasks check it first and raise ActiveRecord::ProtectedEnvironmentError for production, so db:reset stops until db:environment:set records staging.
solid answer
~40 sNext to `schema_migrations`, Rails keeps `ar_internal_metadata`, a key/value table. Its `environment` key is written each time migrations run up (and when the schema is loaded), so a restored production dump still says `production`. Destructive tasks (`db:drop`, and so `db:reset`, `db:schema:load`, `db:purge`, `db:truncate_all`, `db:seed:replant`) first run a protected-environment check: if the stored environment is in `ActiveRecord::Base.protected_environments` (default `["production"]`) they raise `ActiveRecord::ProtectedEnvironmentError`; if it is any other environment that differs from the current one they raise `ActiveRecord::EnvironmentMismatchError`. After confirming you are on the copy, `bin/rails db:environment:set RAILS_ENV=staging` records the new value. `DISABLE_DATABASE_ENVIRONMENT_CHECK=1` skips the check for one command. `db:migrate` and `db:rollback` are not guarded.
code
bash · 4 linesRAILS_ENV=staging bin/rails db:rollback STEP=2 # not guarded
RAILS_ENV=staging bin/rails db:reset # ProtectedEnvironmentError
RAILS_ENV=staging bin/rails db:environment:set
RAILS_ENV=staging bin/rails db:reset # now runsgo deeper
Know that Rails refuses to drop or reset a production database by default and that ar_internal_metadata is one of its internal tables.
Explain when the environment value is written, which tasks run the check, and the difference between ProtectedEnvironmentError and EnvironmentMismatchError.
Handle restored dumps safely: confirm the target, use db:environment:set rather than a permanent override, and protect staging too when it holds production copies.
Decide how far the team trusts this guard versus credentials and network isolation for production databases.
## Two internal tables Every migrated Rails database carries two tables that the app never models: - **`schema_migrations`**: one `version` row per migration that has run. - **`ar_internal_metadata`**: a small key/value table (`key`, `value`, timestamps). Rails stores the `environment` there, and a `schema_sha1` checksum of the schema file when it loads one. The `environment` value is written whenever migrations run **up** and whenever a schema file is loaded. A database migrated by the production app therefore says `production`, and keeps saying it when you restore that dump into another server. ## The check destructive tasks run Tasks that throw data away depend on a hidden task, `db:check_protected_environments`. That covers `db:drop` (and therefore `db:reset`), `db:schema:load`, `db:purge`, `db:truncate_all` (and therefore `db:seed:replant`), and `db:test:purge`. For each database of the current environment it: 1. Reads the stored `environment` from `ar_internal_metadata`. If no migration has ever run, there is nothing to protect and the check passes. 2. Raises **`ActiveRecord::ProtectedEnvironmentError`** if that stored value is in `ActiveRecord::Base.protected_environments`, which defaults to `["production"]`. The message suggests `DISABLE_DATABASE_ENVIRONMENT_CHECK=1`. 3. Otherwise raises **`ActiveRecord::EnvironmentMismatchError`** if the stored value differs from the environment you are running in, suggesting `bin/rails db:environment:set`. 4. Raises `ActiveRecord::NoEnvironmentInSchemaError` if migrations have run but the metadata row is missing. The check is about the **database's own record**, not about the host name or `RAILS_ENV`. That is the point: a staging app pointed at a real production database by mistake is caught, because the database says production. ## The staging copy of the dental-practice app The team restores last night's production dump into the staging server to rehearse a migration. They want to roll back the last two migrations and then rebuild from scratch: - `RAILS_ENV=staging bin/rails db:rollback STEP=2` **runs**. Rollback is not a protected task. - `RAILS_ENV=staging bin/rails db:reset` **raises** `ActiveRecord::ProtectedEnvironmentError`, because the copied metadata says `production`. The fix, once you have confirmed which server you are connected to: ```bash RAILS_ENV=staging bin/rails db:environment:set RAILS_ENV=staging bin/rails db:reset ``` `db:environment:set` rewrites the `environment` key to the current environment. Running any migration up in staging would also rewrite it, which is worth knowing: after the first `db:migrate` on the copy, the guard no longer reflects where the data came from. ## Why the value outlives the copy A dump of the production database carries every table, including Rails' internal ones. Nothing in the restore process knows which rows are data and which are bookkeeping, so the `environment` row arrives intact. The only things that change it are `db:environment:set`, a migration run up, or a schema load, and the last of those is itself guarded. That is deliberate: the safest default for a database whose history says production is to treat it as production until a person says otherwise. ## The escape hatch and its cost `DISABLE_DATABASE_ENVIRONMENT_CHECK=1 bin/rails db:reset` skips the check for that one command. Use it for a single, deliberate command. Exporting it in a staging shell profile or a CI job removes the guard for every later command, including the one that is pointed at the wrong database. ## Protecting more than production `protected_environments` is a setting, so staging can be guarded too: ```ruby # config/application.rb config.active_record.protected_environments = %w[production staging] ``` With that, a database last migrated as staging also refuses `db:reset` until someone sets the environment or passes the override. ## Checking before you act A short routine avoids most accidents with restored dumps: 1. Print the target first: `bin/rails runner 'puts ActiveRecord::Base.connection_db_config.database'` for the environment you are about to use. 2. Read the stored value: `SELECT value FROM ar_internal_metadata WHERE key = 'environment'`. 3. Only if both say what you expect, run `db:environment:set` for the current environment. 4. Then run the destructive task, without the override variable. Each step is cheap; skipping them is how a staging command reaches a production database whose metadata, correctly, still says production. ## What is not guarded | Task | Guarded by the check? | |---|---| | `db:drop`, `db:reset`, `db:purge` | yes | | `db:schema:load`, `db:truncate_all`, `db:seed:replant` | yes | | `db:migrate`, `db:rollback`, `db:migrate:down` | no | | `db:environment:set` | no | Rollbacks and migrations run code that can drop columns, so the guard is a seatbelt against wiping a database, not a full permission system. Access control to production databases still belongs to credentials and network rules.
- Which error does db:drop raise in staging against a database last migrated in development?`ActiveRecord::EnvironmentMismatchError`. Development is not in `protected_environments`, so the protected check passes, but the stored value differs from the current environment. The message tells you to run `bin/rails db:environment:set` for the current environment if you really mean it.
- Why would you add staging to protected_environments?Staging often holds a recent production copy that people rehearse on. With `config.active_record.protected_environments = %w[production staging]`, a database last migrated as staging refuses `db:drop`, `db:reset` and `db:schema:load` until someone deliberately sets the environment or passes `DISABLE_DATABASE_ENVIRONMENT_CHECK=1`.
- Rails decides a database is production by looking at its host name
- Setting DISABLE_DATABASE_ENVIRONMENT_CHECK=1 permanently on staging is the proper fix
- db:rollback refuses to run on a database whose metadata says production
- ar_internal_metadata records which migrations have been applied
- schema_migrations stores the environment name for each version