1

I am working with a multi-schema MySQL database. Unfortunately, the main schema (specified in database attribute in database.yml) is NOT the database we can store the schema_migrations table in. All schemas are on the same server so accessing tables in different schemas is simply a matter of changing the Model.table_name to "schema_name.model". However, it doesn't seem to work with schema_migrations.

I am not able to get migrations to use a schema_migrations table in anything but the main schema. I've read about the schema_migrations_table_name and even created an initializer:

class ActiveRecord::Migration

  def schema_migrations_table_name
    app_config = YAML.load_file("#{ Rails.root }/config/settings.yml")[Rails.env].symbolize_keys
    app_config[:user_schema] + '.schema_migrations'
  end

end

My migration looks like:


class AddLockableToUsers < ActiveRecord::Migration

  def connection
    # Connect database where schema_migrations table can be found
    puts schema_migrations_table_name
    @connection = ActiveRecord::Base.establish_connection("schema_migrations_#{Rails.env}").connection
  end

  def with_proper_connection
    app_config = YAML.load_file("#{ Rails.root }/config/settings.yml")[Rails.env].symbolize_keys

    # Use schema in which this table is found
    ActiveRecord::Base.connection.execute('USE '+app_config[:user_schema]+'')
    puts "Here in with_proper_connection with #{@connection.current_database}"

    # Execute migration
    yield

    # At this point schema_migrations table is about to get updated.  So USE the user_schema
    # where this table exists
    ActiveRecord::Base.connection.execute('USE '+app_config[:user_schema]+'')
  end

  def up
    puts "Here in up"
    with_proper_connection do
      add_column :users, :failed_attempts, :integer, default: 0
      add_column :users, :unlock_token, :string
      add_column :users, :locked_at, :datetime
      add_index :users, :unlock_token, :unique => true
    end
  end

  def down
    puts "Here in down"
    with_proper_connection do
      remove_column :users, :failed_attempts
      remove_column :users, :unlock_token
      remove_column :users, :locked_at
    end
  end
end

The puts schema_migrations_table_name command in the connection method shows the correct table name "schema_name.schema_migrations".

The migrations occur in the correct schema so the connections are correct, however rerunning the migration causes the same migration to be run again and a rollback does nothing. (The migration table contains the timestamp of the migration so, if it was being read and respected correctly, the migration would never run)

Has anyone tried storing their schema_migrations table in another schema?

Any ideas?

TIA, Dan

DSadaka
  • 76
  • 6
  • I had same problem and found solution here:http://stackoverflow.com/questions/6631265/multiple-database-connections-schema-migrations-is-looked-up-in-the-wrong-datab – General Failure Apr 24 '15 at 06:47

0 Answers0