Querrel を使用すると、1 つのデータベースをクエリしているかのように、ActiveRecord を使用して複数のデータベースを並列 (スレッド) で簡単にクエリできます。
次の行をアプリケーションの Gemfile に追加します。
gem 'querrel'
そして、以下を実行します。
$ bundle
または、次のように自分でインストールします。
$ gem install querrel
最上位の名前空間を介して Querrel を直接使用することも、インスタンスを作成することによっても使用できます。
all_brands = Querrel . query ( Brand . all , on : [ 'db1' , 'db2' , 'db3' ] )
# is the same as
all_brands = Querrel . new ( [ 'db1' , 'db2' , 'db3' ] ) . query ( Brand . all )
上記のいずれかを実行すると、指定されたすべてのデータベースからすべてのブランド オブジェクトの配列が得られます。レコードは読み取り専用としてマークされます。
query
、 ActiveRecord::Relation
に渡されたブロックを生成します。これにより、結果がマージされる前に、結果に対して追加の操作を行うことができます。たとえば、 pluck を使用できます。
all_brand_names = q . query ( Brand . all ) do | s |
s . pluck ( :name )
end
また、事前に規定されたスコープを実行してマージする代わりに、指定されたデータベース接続でやりたいことを何でもできるようにするブロックを取得するrun
メソッドもあります。
require 'thread'
all_brands = [ ]
b_s = Mutex . new
all_products = [ ]
p_s = Mutex . new
Querrel . run ( on : dbs ) do | db |
b_s . synchronize { all_brands += Brand . all . to_a }
p_s . synchronize { all_products += Product . all . to_a }
end
Querrel にどのデータベースを使用するかを指示するには、次の 3 つの方法があります。
環境の配列を渡します。例: Querrel.new([:customer1, :customer2])
データベース名の配列を渡します。例: Querrel.new(['dbs/customer1.sqlite3', 'dbs/customer2.sqlite3'], db_names: true)
名前付き接続構成のハッシュを渡します。例:
Querrel . new ( {
one : {
adapter : "sqlite3" ,
database : "test/dbs/test_db_1.sqlite3"
} ,
two : {
adapter : "sqlite3" ,
database : "test/dbs/test_db_2.sqlite3"
}
} )
デフォルトでは、Querrel は最大 20 のスレッドを使用しますが、 :threads
オプションを使用してこれを調整できます。
q = Querrel . new ( dbs , threads : 50 )
git checkout -b my-new-feature
)git commit -am 'Add some feature'
)git push origin my-new-feature
)