How to do rails db:migrate on multiple shards that are not master slave relationship at once on rails?

1.4k views Asked by At

I have an app which which uses different database based on the subdomain. So essentially, the schema would be the same, but the data would differ for each databases. But when I release some new features and it would require some schema changes, I would need to run a command that would run on all databases configured in the shards.yml.

database.yml

default: &default
  adapter: postgresql
  encoding: unicode
  pool: 15
  host: localhost
  port: 5432
  username: postgres
  password:

development:
  <<: *default
  database: app_default
production:
  <<: *default
  database: app_default
  username: <%= ENV['BACKEND_DATABASE_USERNAME'] %>
  password: <%= ENV['BACKEND_DATABASE_PASSWORD'] %>

shards.yml

shared: &shared
  adapter: postgresql
  encoding: unicode
  pool: 15
  host: localhost
  username: postgres
  password: 
  port: 5432

octopus:
  environments:
    - development
    - test
    - production
  development:
    default:
      <<: *shared
      database: app
    first:
      <<: *shared
      database: first
    second:
      <<: *shared
      database: second
    ....
  test:
    test:
      host: postgres
      adapter: postgresql
      database: app_test
  production:
    default:
      <<: *shared
      database: app
    first:
      <<: *shared
      database: first
    second:
      <<: *shared
      database: second
    ....

I am using Octopus to set the shard based on subdomain, which works fine. The problems I have are:

  1. I cannot do rails db:reset . Getting the error ActiveRecord::StatementInvalid: PG::ObjectInUse: ERROR: cannot drop the currently open database
  2. I cannot do rails db:migrate that would migrate on all databases
1

There are 1 answers

1
Tony Vincent On

You have to add using to your migrations

class CreateComments < ActiveRecord::Migration
  using :first, :second

  def change
    create_table :comments do |t|
      t.belongs_to :page, index: true
      t.text :body

      t.timestamps
    end
  end
end

the above migration will run on both first and second