diff --git a/CHANGELOG.md b/CHANGELOG.md index 607a401..9f4b621 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,10 @@ ## next / unreleased +### Fixed + +- A tenant whose creation was killed while its schema was loading is repaired by `db:migrate` again, even after something has opened the tenant. The pending-migration check that runs when a tenant's connection pool is created no longer creates an empty `schema_migrations` table, which had made `db:migrate` skip the schema load and run every migration over the half-loaded tables. @cole-robertson + ## v0.9.0 / 2026-10-19 ### Security diff --git a/lib/active_record/tenanted/tenant.rb b/lib/active_record/tenanted/tenant.rb index a7da4ba..0eedd0e 100644 --- a/lib/active_record/tenanted/tenant.rb +++ b/lib/active_record/tenanted/tenant.rb @@ -333,7 +333,11 @@ def _create_tenanted_pool(schema_version_check: true) # :nodoc: pool = establish_connection(db_config) if schema_version_check - pending_migrations = pool.migration_context.open.pending_migrations + # Not `migration_context.open`: building a Migrator creates an empty schema_migrations + # table, and then a database whose schema was never loaded looks initialized to `migrate`. + migration_context = pool.migration_context + migrated = migration_context.get_all_versions + pending_migrations = migration_context.migrations.reject { |m| migrated.include?(m.version) } raise ActiveRecord::PendingMigrationError.new(pending_migrations: pending_migrations) if pending_migrations.any? end diff --git a/test/unit/database_tasks_test.rb b/test/unit/database_tasks_test.rb index d23ae69..d548f3e 100644 --- a/test/unit/database_tasks_test.rb +++ b/test/unit/database_tasks_test.rb @@ -88,6 +88,32 @@ end end + describe "when a schema load was interrupted and the tenant was then opened" do + setup do + with_schema_dump_file + + # A process killed while loading the schema leaves some tables and no schema_migrations. + config = base_config.new_tenant_config("foo") + ActiveRecord::Tasks::DatabaseTasks.with_temporary_connection(config) do |conn| + conn.create_table(:users) + end + + assert_raises(ActiveRecord::PendingMigrationError) do + TenantedApplicationRecord.with_tenant("foo") { User.first } + end + end + + test "the schema is loaded" do + ActiveRecord::Tenanted::DatabaseTasks.new(base_config).migrate_tenant("foo") + + config = base_config.new_tenant_config("foo") + ActiveRecord::Tasks::DatabaseTasks.with_temporary_connection(config) do |conn| + assert_equal(20250203191115, conn.pool.migration_context.current_version) + assert_includes(conn.columns(:users).map(&:name), "email") + end + end + end + describe "when an outdated schema cache dump file exists" do setup { with_schema_cache_dump_file } setup { with_new_migration_file }