#!/usr/bin/env ruby require 'bundler/setup' require 'shiba' require 'shiba/analyzer' require 'shiba/table_stats' require 'shiba/configure' require 'shiba/output' require 'optionparser' options = {} parser = Shiba::Configure.make_options_parser(options) parser.banner = "Run a list of queries through shiba's analyzer." parser.parse! option_path = Shiba::Configure.mysql_config_path if option_path puts "Found config at #{option_path}" if options["verbose"] options['default_file'] ||= option_path end option_file = if options['default_file'] && File.exist?(options['default_file']) File.read(options['default_file']) else "" end if options['json'] && options['html'] $stderr.puts "Can only output to json or html, not both" $stderr.puts parser.banner exit 1 end if option_file && !options['default_group'] if option_file.include?("[client]") options['default_group'] = 'client' end if option_file.include?("[mysql]") options['default_group'] = 'mysql' end end def require_option(parser, name) $stderr.puts "Required: #{name}" $stderr.puts parser.banner exit 1 end if !options["username"] && !option_file.include?('user') require_option(parser, 'username') end if !options["database"] && !option_file.include?('database') require_option(parser, 'database') end file = options.delete("file") file = File.open(file, "r") if file Shiba.configure(options) schema_stats_fname = options["stats"] if schema_stats_fname && !File.exist?(schema_stats_fname) $stderr.puts "No such file: #{schema_stats_fname}" exit 1 end file = $stdin if file.nil? json = options['json'] json = File.open('/dev/null', 'w') if json.nil? if options["verbose"] $stderr.puts "Reading queries from '#{file.inspect}'..." $stderr.puts "Analyzing SQL to '#{json.inspect}'..." end table_stats = Shiba::TableStats.new(Shiba.index_config, Shiba.connection, {}) queries = Shiba::Analyzer.analyze(file, json, table_stats, options) problems = queries.select { |q| q[:cost] && q[:cost] > 100 } if problems.any? query_word = problems.size == 1 ? 'query' : 'queries' $stderr.puts "#{problems.size} problematic #{query_word} detected" if options['json'] exit 3 end page = Shiba::Output.new(queries, { 'output' => options['html'] }).make_web! if !File.exist?(page) $stderr.puts("Failed to generate #{page}") exit 1 end $stderr.puts "Report available at #{page}" exit 3 end