在Ruby中打印SQL

前端之家收集整理的这篇文章主要介绍了在Ruby中打印SQL前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
有没有一个简单的方法来漂亮打印(rails 3)控制台中的随机sql

类似于awesome_print,甚至可能是Pretty Print.

它不必理解所有可能的方言或超先进.
我真正想要的是检查ActiveRecord生成sql更容易.

目前我只是复制sql去在线格式化,这显然是一个生产力杀手.

我真的想要query.to_sql.pretty_format_sql并看到更好的输出.

谢谢.

解决方法

尝试这个:
git clone https://github.com/sonota/anbt-sql-formatter
cd anbt-sql-formatter
rails setup.rb

然后,在Rails初始化程序中:

# config/initializers/pretty_format_sql.rb
class String
  def pretty_format_sql
    require "anbt-sql-formatter/formatter"
    rule = Anbtsql::Rule.new
    rule.keyword = Anbtsql::Rule::KEYWORD_UPPER_CASE
    %w(count sum substr date).each{|func_name|
      rule.function_names << func_name.upcase
    }
    rule.indent_string = "    "
    formatter = Anbtsql::Formatter.new(rule)
    formatter.format(self)
  end
end

测试:

rails console
# Some complex sql
puts Recipe.joins(:festivity).where(['? BETWEEN festivities.starts_at AND festivities.ends_at',Time.utc(0,Time.now.month,Time.now.day,12,0)]).to_sql.pretty_format_sql
SELECT
        "recipes" . *
    FROM
        "recipes" INNER JOIN "festivities"
            ON "festivities" . "id" = "recipes" . "festivity_id"
    WHERE
        (
            '0000-04-27 12:00:00.000000' BETWEEN festivities.starts_at AND festivities.ends_at
        )
 => nil

我离开炼油(重构:猴子补丁 – >模块,自定义格式化等):-))

原文链接:https://www.f2er.com/ruby/272934.html

猜你在找的Ruby相关文章