diff --git a/README.md b/README.md index 73e6b46..dd039db 100644 --- a/README.md +++ b/README.md @@ -69,6 +69,12 @@ If you do not want to rewrite default `#to_sql` method you may specify You can also disable log formatting by specifying `PpSql.add_rails_logger_formatting=false` in initializers. +By default, PpSql will not format any logs during any rails tasks that begin +with `db:`, such as `db:migrate`. However, if you want formatted logs during db +tasks you can opt in by passing in the environment var +`PPSQL_ENABLE_FOR_RAILS_RAKE_DB_TASKS`. For example, +`PPSQL_ENABLE_FOR_RAILS_RAKE_DB_TASKS=1 rails db:migrate`. + ### Add to Application record I found usefull this trick: diff --git a/lib/pp_sql.rb b/lib/pp_sql.rb index 4189c29..83c52a0 100644 --- a/lib/pp_sql.rb +++ b/lib/pp_sql.rb @@ -6,10 +6,11 @@ module PpSql # if you do not want to rewrite AR native method #to_sql # you may switch this setting to false in initializer class << self - attr_accessor :rewrite_to_sql_method, :add_rails_logger_formatting + attr_accessor :rewrite_to_sql_method, :add_rails_logger_formatting, :enable_for_rails_rake_db_tasks end self.rewrite_to_sql_method = true self.add_rails_logger_formatting = true + self.enable_for_rails_rake_db_tasks = ENV.fetch('PPSQL_ENABLE_FOR_RAILS_RAKE_DB_TASKS', false) module Formatter private @@ -66,6 +67,11 @@ class Railtie < Rails::Railtie ActiveRecord::LogSubscriber.prepend LogSubscriberPrettyPrint end end + + rake_tasks do + path = File.expand_path(__dir__) + Dir.glob("#{path}/pp_sql/tasks/**/*.rake").each { |f| load f } unless PpSql.enable_for_rails_rake_db_tasks + end end end end diff --git a/lib/pp_sql/tasks/db_hooks.rake b/lib/pp_sql/tasks/db_hooks.rake new file mode 100644 index 0000000..5e5a063 --- /dev/null +++ b/lib/pp_sql/tasks/db_hooks.rake @@ -0,0 +1,13 @@ +# frozen_string_literal: true + +namespace :pp_sql do + desc 'Hook that is ran before rails `db:*` tasks that can disable pp_sql' + + task :disable_during_db_tasks do + PpSql.add_rails_logger_formatting = false + PpSql.rewrite_to_sql_method = false + end +end + +db_tasks = Rake::Task.tasks.select { |task| task.name.starts_with?('db:') } +db_tasks.each { |task| task.enhance(['pp_sql:disable_during_db_tasks']) }