DavyJonesLocker / postgres_ext-serializers

MIT License
324 stars 30 forks source link

Add pry for debugging #55

Closed felixbuenemann closed 8 years ago

felixbuenemann commented 8 years ago

This adds the following gems in development:

A useful addition to this is the following .pryrc which enables ActiveRecord query logging inside pry:

# Log queries to STDOUT during pry sessions.
Pry.config.hooks.add_hook(:when_started, :log_ar_queries) do
  if defined?(Rails)
    $pry_ar_logger = Logger.new(STDOUT) unless defined? $pry_ar_logger
  end
end
Pry.config.hooks.add_hook(:before_session, :log_ar_queries) do
  if defined?(Rails)
    $last_ar_logger = ActiveRecord::Base.logger
    ActiveRecord::Base.logger = $pry_ar_logger
  end
end
Pry.config.hooks.add_hook(:after_session, :log_ar_queries) do
  if defined?(Rails)
    ActiveRecord::Base.logger = $last_ar_logger
  end
end

The .pryrc should be user configurable, so I did not add it to version control.

felixbuenemann commented 8 years ago

Btw. it's also possible to highlight SQL, which is very helpful with the long CTEs:

# Add binding.pry at the end of _postgres_serializable_array method.
# pretty print SQL
pry> >> -t sql _to_sql(jsons_select_manager)
# or pretty print JSON
pry> >> @_connection.select_value _to_sql(jsons_select_manager)

To also structure the highlighted SQL you can use something like this:

def format_sql(s)
  s.gsub!(/(\(WITH|\),) ([a-z0-9_]+) AS \(/, "\n\\0\n\t")
  s.sub!(/\) SELECT/, "\n\\0")
  s.gsub!(/IN \((SELECT[^\)]+)\)/, "IN (\n\t\t\\1\n\t)")
  s.gsub!(/(INNER|LEFT OUTER) JOIN/, "\n\t\\0")
end
pry> >> -t sql format_sql(_to_sql(jsons_select_manager))
felixbuenemann commented 8 years ago

I should probably add some of those tips to a debugging section in the wiki.