standalone-migrations icon indicating copy to clipboard operation
standalone-migrations copied to clipboard

load_tasks loads the active record database tasks twice causing them to execute twice in certain scenarios

Open dat2 opened this issue 2 years ago • 1 comments

I've noticed that when I have a simple Rakefile like this

Bundler.require(:default)
StandaloneMigrations::Tasks.load_tasks

Running the command bin/rake db:schema:load with my structure.sql will fail with confusing errors, because my structure.sql file does not work when it's run twice.

I discovered these two lines below cause the db:schema:load task to be defined twice in rake, and thus rake executes them twice.

https://github.com/thuss/standalone-migrations/blob/b136d0118c442cd957ba1faabf94b1a571e424ec/lib/standalone_migrations/tasks.rb#L14 https://github.com/thuss/standalone-migrations/blob/b136d0118c442cd957ba1faabf94b1a571e424ec/lib/standalone_migrations/tasks.rb#L22

I was able to prevent it locally with the following monkey patch.

module Kernel
  alias old_load load

  def load(*args, **kwargs)
    return old_load(*args, **kwargs) unless args[0] == "active_record/railties/databases.rake"
    @@load ||= old_load(*args, **kwargs)
  end
end

According to rake, executing tasks twice when defining them twice is intended behaviour: https://github.com/ruby/rake/issues/228#issuecomment-749823323

dat2 avatar Mar 15 '23 15:03 dat2

I finally figured this out. The issue boils down to incompatibility with the strong_migrations gem. Here's a very simple Rakefile to reproduce the issue.

require 'rails' # need to make sure defined?(Rails) is true for strong_migrations
require 'strong_migrations'
require 'standalone_migrations'

StandaloneMigrations::Tasks.load_tasks

strong_migrations through a series of require s calls load "active_record/railties/databases.rake".

https://github.com/ankane/strong_migrations/blob/1146d6836bda6c1d8b51287bba73613edfce9e82/lib/strong_migrations/railtie.rb#L2 https://github.com/rails/rails/blob/784f1c75a08b3b3611b4f100a890c26ace493138/activerecord/lib/active_record/railtie.rb#L57

dat2 avatar Mar 28 '23 14:03 dat2