headshot of Chris Tonkinson
Chris Tonkinson

tech {enthusiast, practitioner, leader, podcaster, mentor, entrepreneur}


Refactored Podcast

I co-host Refactored, a casual, ongoing conversation between two technology leaders trying to suck a little less every day.

Career Schema Project

I founded the Career Schema Project with the mission of developing open standards and technology to reduce the hassle of online jobseeking.

RSS Subscribe

© 2021 Chris Tonkinson

More granular console SQL coloration

Thanks to having spent far too much time admiring Nyan Cat derivatives, the Rails 5.0 console will include a new SQL logging coloration scheme.

Rails 5.0 console output

In a previous post, I explained the code responsible for the cyan/magenta striping of SQL statement prefixes in the rails console. I reviewed the Rails log/blame to watch the evolution of the code over time - having spend more than 10 years in the same VCS, Rails is positively fascinating as the subject of retrospective code reviews.

The basis for even/odd striping was already in place by the time DHH began moving Rails from SVN to Git back in 2004. At that time, the code lived in a method called format_log_entry defined on line 356 of abstract_adapter.rb.

  def format_log_entry(message, dump = nil)
    if @@row_even then
      @@row_even = false; caller_color = "1;32"; message_color = "4;33"; dump_color = "1;37"
      @@row_even = true; caller_color = "1;36"; message_color = "4;35"; dump_color = "0;37"

    log_entry = "  \e[#{message_color}m#{message}\e[m"
    log_entry << "   \e[#{dump_color}m%s\e[m" % dump if dump.kind_of?(String) && !dump.nil?
    log_entry << "   \e[#{dump_color}m%p\e[m" % dump if !dump.kind_of?(String) && !dump.nil?

The first refactor of this logic was in 2010 by José Valim, who moved the code into subscriber.rb. Shortly thereafter, Subscriber was renamed LogSubscriber by Prem Sichanugrist, and there it remained.

Earlier this summer I issued PR #20607 to spruce this output up a bit. The essence of my minor contribution can be summarized in this one case:

case sql
  when /\s*\Ainsert/i      then GREEN
  when /\s*\Aselect/i      then BLUE
  when /\s*\Aupdate/i      then YELLOW
  when /\s*\Adelete/i      then RED
  when /transaction\s*\Z/i then CYAN
  else MAGENTA

You can see that INSERT queries will print in green, SELECTs in blue, UPDATEs in yellow, DELETEs in red, any TRANSACTION statements print in cyan, and everything else is colored magenta. It was quickly suggested that markers could be added for slow queries and failed transactions, which I’m currently working on.

This patch will be included by default in Rails 5.0. Not happy waiting, I backported the patch (in my own fork) for use in 4.1-stable and 4.2-stable, but Ken Collins beat me at my own game. He authored a fantastic gem called activerecord-colored_log_subscriber for those of us maintaining active projects in the 3.2 and 4.2 stable branches of Rails. What a fantastic community.