Arproxy Active Recordが発行したSQLを加工できるGem


cookpad/arproxy - GitHub』は、
Arproxy Active Recordが発行したSQLを加工できるGemです。
Slow Queryを調査したり、SQLにコメントを付与したり、SQLをReadonlyに制限したりできます!


🐠 Gemインストール

Gemfileに以下を追加して、bundle installを実行。

# Gemfile
group :development do
# ActiveRecordのSQLを加工
gem 'arproxy'
end

🍮 SQLをログに出力

次のようになSQLを実行する部分をプロキシします。

+-------------------------+                       +------------------+
| ActiveRecord::Base#find |--execute(sql, name)-->| Database Adapter |
+-------------------------+ +------------------+

SQLをログに出力するサンプルはこちら。

class QueryTracer < Arproxy::Base
def execute(sql, name=nil)
Rails.logger.debug sql
Rails.logger.debug caller(1).join("\n")
super(sql, name)
end
end

Arproxy.configure do |config|
config.adapter = "mysql2" # A DB Apdapter name which is used in your database.yml
config.use QueryTracer
end
Arproxy.enable!

🎂 Slow Queryのログを出力

Slow Queryのログを出力する場合はこちら。

class SlowQueryLogger < Arproxy::Base
def initialize(slow_ms)
@slow_ms = slow_ms
end

def execute(sql, name=nil)
result = nil
ms = Benchmark.ms { result = super(sql, name) }
if ms >= @slow_ms
Rails.logger.info "Slow(#{ms.to_i}ms): #{sql}"
end
result
end
end

Arproxy.configure do |config|
config.use SlowQueryLogger, 1000
end

🗻 SQLにコメントを差し込む

SQLにコメントを差し込む場合はこちら。

class CommentAdder < Arproxy::Base
def execute(sql, name=nil)
sql += " /*this_is_comment*/"
super(sql, name)
end
end

これはおもしろいかも!

🖥 VULTRおすすめ

VULTR」はVPSサーバのサービスです。日本にリージョンがあり、最安は512MBで2.5ドル/月($0.004/時間)で借りることができます。4GBメモリでも月20ドルです。 最近はVULTRのヘビーユーザーになので、「ここ」から会員登録してもらえるとサービス開発が捗ります!

📚 おすすめの書籍