ctran/annotate_models

Auto-annotate doesn't work when migrating one db in a multi-db setup

richardjonathonharris opened this issue · 3 comments

We use annotate within a rails application with a multidb setup, which allows you to migrate all databases with rails db:migrate or just one of your databases with rails db:migrate:db_name. Annotate works as expected when running db:migrate but fails to run whenever you run rails db:migrate:db_name. Any tips on how to auto-annotate in both cases?

Commands

rails db:migrate
# annotations show up in model files as expected

rails db:migrate:db_name
# annotate fails to run, does not show any text in shell nor makes any changes

Version

  • annotate version 3.1.1
  • rails version 6.0.3.7
  • ruby version 2.7.4p191

Hi Richard,

After running into problems with annotate myself – in my case, it was not the multi database setup, but our application's many different directories for models – I have developed a gem which fixes the issues. This gem, datagaze, is heavily inspired by annotate, but simply tries to fix the problem you are experiencing. The gem is to be found at: https://github.com/jurriaanschrofer/datagaze.

Basically, annotate's lookup system is often rigid and based on very strict path conventions. Instead, I have found a way of annotating more dynamically, through the use of ruby's const_source_location method and rails' ApplicationRecord.descendants.

Would you, if you choose to try the gem out, please reach out to me with feedback? I would love to hear about your experience.

There is actually an included rake task that works for multi db setups: https://github.com/ctran/annotate_models/blob/70aba780b44c8fad14b76c2e051529a6c78299bc/lib/tasks/annotate_models_migrate.rake

I am not sure why this is not the default or actually how to properly install annotate to use this task. Per the comment i haven't seen rails plugins used in a long time but the file checks specifically for rails version > 6.

I ended up just copying the file into a rake task and it worked as intended working for both rake db:migrate and rake db:migrate:<db>. 🤷

Late to the party, but if others are having the same issue:

My app has a lib/tasks/annotate.rake task that handled automatic annotation after migrate tasks. Adding the lines at the bottom to also enhance all db:migrate:<database> tasks fixed it for me.

if Rails.env.development?
    ...
    Rake::Task['db:migrate'].enhance { Rake::Task['annotate:models'].invoke }
   
    # Annotate after single db migration
    databases = ActiveRecord::Tasks::DatabaseTasks.setup_initial_database_yaml
    ActiveRecord::Tasks::DatabaseTasks.for_each(databases) do |db_name|
        task = "db:migrate:#{db_name}"
        Rake::Task[task].enhance { Rake::Task['annotate:models'].invoke }
    end
end