Module: Apartment::Tasks::SchemaDumper
- Defined in:
- lib/apartment/tasks/schema_dumper.rb
Overview
Handles automatic schema dumping after tenant migrations.
## Problem Context
After running ‘rails db:migrate`, Rails dumps the schema to capture the current database structure. With Apartment, tenant migrations modify individual schemas but the canonical structure lives in the public/default schema. Without explicit handling, the schema could be dumped from the last-migrated tenant schema instead of the authoritative public schema.
## Why This Approach
We switch to the default tenant before dumping to ensure the schema file reflects the public schema structure. This is correct because:
-
All tenant schemas are created from the same schema file
-
The public schema is the source of truth for structure
-
Tenant-specific data differences don’t affect schema structure
## Rails Convention Compliance
We respect several Rails configurations rather than inventing our own:
-
‘config.active_record.dump_schema_after_migration`: Global toggle
-
‘config.active_record.schema_format`: `:ruby` for schema.rb, `:sql` for structure.sql
-
‘database_tasks: true/false`: Per-database migration responsibility
-
‘replica: true`: Excludes read replicas from schema operations
-
‘schema_dump: false`: Per-database schema dump toggle
The ‘db:schema:dump` task respects `schema_format` and produces either schema.rb or structure.sql accordingly.
## Gotchas
-
Schema dump failures are logged but don’t fail the migration. This prevents a secondary concern from blocking critical migrations.
-
Multi-database setups must mark one connection with ‘database_tasks: true` to indicate which database owns schema management.
-
Don’t call ‘Rails.application.load_tasks` here; if invoked from a rake task, it re-triggers apartment enhancements causing recursion.
Class Method Summary collapse
-
.dump_if_enabled ⇒ Object
Entry point called after successful migrations.
Class Method Details
.dump_if_enabled ⇒ Object
Entry point called after successful migrations. Checks all relevant Rails settings before attempting dump.
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 |
# File 'lib/apartment/tasks/schema_dumper.rb', line 49 def dump_if_enabled return unless rails_dump_schema_enabled? db_config = find_schema_dump_config return if db_config.nil? schema_dump_setting = db_config.configuration_hash[:schema_dump] return if schema_dump_setting == false Apartment::Tenant.switch(Apartment.default_tenant) do dump_schema end rescue StandardError => e # Log but don't fail - schema dump is secondary to migration success Rails.logger.warn("[Apartment] Schema dump failed: #{e.}") end |