Last active
August 29, 2015 14:01
-
-
Save myronmarston/df355a8b8de07b6ce69e to your computer and use it in GitHub Desktop.
Example showing how to use Sequel without a singleton database. It uses two DB connections -- one that represents a sharded connections (e.g. to connect to many DBs with the same schema) and then a second connection to an individual database with a different schema.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'sequel/model' | |
Sequel.extension :arbitrary_servers, :server_block | |
non_sharded = Sequel.connect \ | |
adapter: 'mysql2', | |
host: "localhost", | |
database: "vanguard_non_sharded", | |
user: 'root', | |
password: nil | |
NonShardedModel = Sequel::Model(non_sharded) | |
sharded = Sequel.connect \ | |
adapter: 'mysql2', | |
user: 'root', | |
password: nil, | |
servers: { default: proc { raise "No current shard" } } | |
sharded.extend Sequel::ServerBlock | |
sharded.pool.extend Sequel::ArbitraryServers | |
# ensure we synchronize DB access. | |
# see: https://github.com/jeremyevans/sequel/blob/540d336c5845cb007b32234edbbfd1cc5462d527/doc/sharding.rdoc | |
def sharded.with_server(*args) | |
super(*args) { synchronize { |c| yield c } } | |
end | |
def sharded.use(host, database) | |
with_server(host: host, database: database) do | |
yield self | |
end | |
end | |
ShardedModel = Sequel::Model(sharded) | |
def ShardedModel.set_dataset(*args) | |
# Sequel needs a valid DB connection when setting the dataset, | |
# because it makes a query to get the schema in order to | |
# determine the columns. | |
db.use('localhost', 'master_schema_db') { super } | |
end | |
class ShardBuild < NonShardedModel | |
end | |
class Keyword < ShardedModel | |
end | |
describe ShardBuild do | |
it 'has the expected columns' do | |
expect(ShardBuild.columns).to include(:shard_num, :campaign_id) | |
end | |
end | |
describe Keyword do | |
around(:each) do |example| | |
sharded.use("localhost", "my_test_db") do |db| | |
db.transaction(rollback: :always, &example) | |
end | |
end | |
it 'has the expected columns' do | |
expect(Keyword.columns).to include(:id, :keyword) | |
end | |
it 'can insert and query data' do | |
Keyword.dataset.insert(keyword: "foo", id: 15, branding: "auto", created_at: Time.now) | |
expect(Keyword.where(:keyword => "foo").count).to eq(1) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment