LoginSignup
13
8

More than 5 years have passed since last update.

PostgreSQL の実行計画を見やすくする in Rails

Last updated at Posted at 2017-03-17

目的

Rails で Active Record が発行する SQL の実行計画を見やすくする。

方法

今回 plans という Web ツールを利用します。

このツールを利用するには EXPLAIN (ANALYZE, COSTS, VERBOSE, BUFFERS, FORMAT JSON) を実行した結果の JSON が必要です。

例として、以下のリレーションが発行する SQL の実行計画を JSON で取得し、前述のツールに適用してみます。なお、通常は ActiveRecord::Relation#explain を使って実行計画を取得できるのですが、今回はいくつかのオプションを指定する必要があるので別の方法を採用します。

Character.joins(:animes).merge(Anime.where("#{Anime.table_name}.title LIKE ?", '%物語%')).order(:name).limit(10)

まず ActiveRecord::Base.connection.execute を使って、EXPLAIN を実行します。

relation = Character.joins(:animes).merge(Anime.where("#{Anime.table_name}.title LIKE ?", '%物語%')).order(:name).limit(10).class
result = ActiveRecord::Base.connection.execute("EXPLAIN (ANALYZE, COSTS, VERBOSE, BUFFERS, FORMAT JSON) #{relation.to_sql}")
#=> #<PG::Result:0x007f97c3fa3ae0 status=PGRES_TUPLES_OK ntuples=1 nfields=1 cmd_tuples=0>

次に、返り値から JSON 文字列を取り出します。

json = result.first['QUERY PLAN']

最後に puts で JSON 文字列を出力して、それをコピーして plans のテキストエリアにペーストします。

puts(json)

ss01.png

SUBMIT ボタンをクリックすると、EXPLAIN の結果がツリー形式で図示されます。

ss02.png

参考

13
8
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
8