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

1

11

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
Traditionalism answered 14/9, 2017 at 13:12 Comment(0)
M
6

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

Misfire answered 20/9, 2017 at 9:57 Comment(1)
Thanks for taking your time to answer the question. Unfortunately, this solution still won't resolve the rails db:reset error. Although this might just work for the specified shards, I was looking for the migrations to be applied to all the shards.Traditionalism

© 2022 - 2024 — McMap. All rights reserved.