Activerecord::Slave

Build Status Coverage Status Code Climate Dependency Status

ActiveRecord for MySQL Replication databases(master/slave).

Installation

Add this line to your application's Gemfile:

gem 'activerecord-slave'

And then execute:

$ bundle

Or install it yourself as:

$ gem install activerecord-slave

Usage

Add database connections to your application's config/database.yml:

default: &default
  adapter: mysql2
  encoding: utf8
  pool: 5
  database: user
  username: root
  password:
  host: localhost

user_master:
  <<: *default
  host: master.db.example.com

user_slave_001:
  <<: *default
  host: slave_001.db.example.com

user_slave_002:
<<: *default
  host: slave_002.db.example.com

Add this example, your application's config/initializers/active_record_slave.rb:

ActiveRecord::Slave.configure do |config|
  config.define_replication(:user) do |replication| # replication name
    replication.register_master(:user_master)       # master connection

    replication.register_slave(:user_slave_001, 70) # slave connection, weight
    replication.register_slave(:user_slave_002, 30)
  end
end

Model

app/model/user.rb

class User < ActiveRecord::Base
  has_many :items
  include ActiveRecord::Slave::Model
  use_slave :user # replicaition name
end

class Item < ActiveRecord::Base
  belongs_to :user
  include ActiveRecord::Slave::Model
  use_slave :user # replicaition name
end

Query for master database.

User.all
User.find(1)
User.where(name: "foobar")

Query for slave databases.

distrebute(load-balance) connection by configured weight settings.

User.slave_for.all
User.slave_for.find(1)
User.slave_for.where(name: "foobar")

Association case. If select from slave, should use #slave_for. Not use assosiaion daynamic methods.

User.find(1).items # items from master database

user = User.find(1)
Item.slave_for(user_id: user.id) # items from slave databases

Tasks

Database create/drop tasks.

rake active_record:slave:db_create[replicaition]  # Create database for replicaition master
rake active_record:slave:db_drop[replicaition]    # Drop database for replicaition master

Migration

You shuld write #connection to migration file for replication databases.

class CreateUsers < ActiveRecord::Migration
  def connection
    User.connection
  end

  def change
    create_table :users do |t|
      t.string :name

      t.timestamps null: false
    end
  end
end

Contributing

  1. Fork it ( http://github.com/hirocaster/activerecord-slave/fork )
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create new Pull Request