server_block.rb

Path: lib/sequel/extensions/server_block.rb
Last Update: Thu Nov 12 08:45:04 +0000 2015

The server_block extension adds the Database#with_server method, which takes a shard argument and a block, and makes it so that access inside the block will use the specified shard by default.

First, you need to enable it on the database object:

  DB.extension :server_block

Then you can call with_server:

  DB.with_server(:shard1) do
    DB[:a].all # Uses shard1
    DB[:a].server(:shard2).all # Uses shard2
  end
  DB[:a].all # Uses default

You can even nest calls to with_server:

  DB.with_server(:shard1) do
    DB[:a].all # Uses shard1
    DB.with_server(:shard2) do
      DB[:a].all # Uses shard2
    end
    DB[:a].all # Uses shard1
  end
  DB[:a].all # Uses default

Note that if you pass the nil, :default, or :read_only server/shard names to Dataset#server inside a with_server block, they will be ignored and the server/shard given to with_server will be used:

  DB.with_server(:shard1) do
    DB[:a].all # Uses shard1
    DB[:a].server(:shard2).all # Uses shard2
    DB[:a].server(nil).all # Uses shard1
    DB[:a].server(:default).all # Uses shard1
    DB[:a].server(:read_only).all # Uses shard1
  end

[Validate]