server_block.rb

lib/sequel/extensions/server_block.rb
Last Update: 2023-06-12 13:05:49 -0700

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 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

If you pass two separate shards to with_server, the second shard will be used instead of the :read_only shard, and the first shard will be used instead of the :default shard:

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

If you use an invalid server when calling with_server, it will be treated the same way as if you called Dataset#server with an invalid server. By default, the default server will be used in such cases. If you would like a different server to be used, or an exception to be raised, then use the :servers_hash Database option.

Related modules: Sequel::ServerBlock, Sequel::UnthreadedServerBlock, Sequel::ThreadedServerBlock