diff --git a/lib/dfe/analytics.rb b/lib/dfe/analytics.rb index f0905942..8c9e2ed7 100644 --- a/lib/dfe/analytics.rb +++ b/lib/dfe/analytics.rb @@ -79,13 +79,7 @@ def self.configure end def self.initialize! - begin - ActiveRecord::Base.connection - rescue ActiveRecord::ActiveRecordError - Rails.logger.info('No database connection; DfE Analytics not initialized') - return - end - + ActiveRecord::Base.connection # cause an exception early if we can't connect DfE::Analytics::Fields.check! entities_for_analytics.each do |entity| @@ -96,6 +90,10 @@ def self.initialize! model.include(DfE::Analytics::Entities) end end + rescue ActiveRecord::PendingMigrationError + Rails.logger.info('Database requires migration; DfE Analytics not initialized') + rescue ActiveRecord::ActiveRecordError + Rails.logger.info('No database connection; DfE Analytics not initialized') end def self.enabled? @@ -177,9 +175,12 @@ def self.entity_model_mapping Rails.application.eager_load! + rails_tables = %w[ar_internal_metadata schema_migrations] + ActiveRecord::Base.descendants - .reject(&:abstract_class?) - .index_by(&:table_name) + .reject(&:abstract_class?) + .index_by(&:table_name) + .except(*rails_tables) end end diff --git a/spec/dfe/analytics_spec.rb b/spec/dfe/analytics_spec.rb index da16d551..a65c5e0f 100644 --- a/spec/dfe/analytics_spec.rb +++ b/spec/dfe/analytics_spec.rb @@ -22,6 +22,15 @@ end end + describe 'when migrations are pending' do + it 'recovers and logs' do + allow(DfE::Analytics::Fields).to receive(:check!).and_raise(ActiveRecord::PendingMigrationError) + + allow(Rails.logger).to receive(:info).with(/Database requires migration/) + expect { DfE::Analytics.initialize! }.not_to raise_error + end + end + describe 'field checks on initialization' do # field validity is computed from allowlist, blocklist and database. See # Analytics::Fields for more details