#!/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! if options['json'] && options['html'] $stderr.puts "Can only output to json or html, not both" $stderr.puts parser.banner exit 2 end file = options.delete("file") file = File.open(file, "r") if file Shiba.configure(options) do |err_msg| $stderr.puts(err_msg) $stderr.puts(parser) exit 2 end schema_stats_fname = options["stats"] if schema_stats_fname && !File.exist?(schema_stats_fname) $stderr.puts "No such file: #{schema_stats_fname}" exit 2 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 1 end page = Shiba::Output.new(queries, { 'output' => options['html'] }).make_web! if !File.exist?(page) $stderr.puts("Failed to generate #{page}") exit 2 end $stderr.puts "Report available at #{page}" exit 1 end