Skip to content

Instantly share code, notes, and snippets.

@d11wtq
Created May 6, 2011 13:45
Show Gist options
  • Save d11wtq/958971 to your computer and use it in GitHub Desktop.
Save d11wtq/958971 to your computer and use it in GitHub Desktop.
Sample database.yml for multiple slaves/masters with DataMapper
module DataMapper
module Adapters
class ConnectionPoolAdapter < AbstractAdapter
def initialize(name, options)
super
assert_kind_of 'options', @options[:pool], Array
raise ArgumentError, "The are no adapters in the adapter pool" if @options[:pool].empty?
@pool = []
@options[:pool].each do |adapter_opts|
@pool.push(::DataMapper.setup(name, adapter_opts))
end
@number_generator = Random.new
end
def create(resources)
random_adapter.create(resources)
end
def read(query)
random_adapter.read(query)
end
def update(attributes, collection)
random_adapter.update(attributes, collection)
end
def delete(collection)
random_adapter.delete(collection)
end
def method_missing(meth, *args, &block)
random_adapter.send(meth, *args, &block)
end
private
def random_adapter
@pool[@number_generator.rand([email protected])]
end
end
end
end
defaults: &defaults
adapter: mysql
encoding: UTF-8
username: user
password: resu
host: localhost
development:
adapter: master_slave
master:
<<: *defaults
database: ourproduct
slave:
<<: *defaults
database: ourproduct
production:
adapter: master_slave
master:
<<: *defaults
database: ourproduct
host: master1.db.ourcloud.com
slave:
adapter: connection_pool
pool:
- <<: *defaults
database: ourproduct
host: slave1.db.ourcloud.com
- <<: *defaults
database: ourproduct
host: slave2.db.ourcloud.com
test:
adapter: master_slave
master:
<<: *defaults
database: ourproduct_test
slave:
<<: *defaults
database: ourproduct_test
require 'forwardable'
module DataMapper
module Adapters
class MasterSlaveAdapter < AbstractAdapter
extend Forwardable
def_delegators :@slave_adapter, :read
def_delegators :@master_adapter, :create, :update, :delete
def initialize(name, options)
super
assert_kind_of 'options', @options[:slave], Hash
assert_kind_of 'options', @options[:master], Hash
# Giving the master/slave the same name allows them to act as one wrt. storage_names
@slave_adapter = ::DataMapper.setup(name, @options[:slave])
@master_adapter = ::DataMapper.setup(name, @options[:master])
end
# It's safest to send anything we don't know about to the master
def method_missing(meth, *args, &block)
@master_adapter.send(meth, *args, &block)
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment