rewrite using mysql2 gem and mega-query rather than slow Sequel for optimization