Переглянути джерело

Added more data to audits

Andrew Kane 9 роки тому
батько
коміт
8b543d7a19
2 змінених файлів з 26 додано та 1 видалено
  1. 13 0
      app/controllers/blazer/queries_controller.rb
  2. 13 1
      lib/blazer/data_source.rb

+ 13 - 0
app/controllers/blazer/queries_controller.rb

@@ -85,7 +85,20 @@ module Blazer
           audit.save!
         end
 
+        start_time = Time.now
         @columns, @rows, @error, @cached_at = @data_source.run_statement(@statement, user: blazer_user, query: @query, refresh_cache: params[:check])
+        duration = Time.now - start_time
+
+        if audit
+          audit.duration = duration if audit.respond_to?(:duration=)
+          audit.error = @error if audit.respond_to?(:error=)
+          audit.timed_out = @error == Blazer::TIMEOUT_MESSAGE if audit.respond_to?(:timed_out=)
+          audit.cached = @cached_at.present? if audit.respond_to?(:cached=)
+          if !@error # && duration >= 10
+            audit.cost = @data_source.cost(@statement) if audit.respond_to?(:cost=)
+          end
+          audit.save! if audit.changed?
+        end
 
         if @query && @error != Blazer::TIMEOUT_MESSAGE
           @query.checks.each do |check|

+ 13 - 1
lib/blazer/data_source.rb

@@ -57,6 +57,18 @@ module Blazer
       settings.key?("use_transaction") ? settings["use_transaction"] : true
     end
 
+    def cost(statement)
+      if postgresql? || redshift?
+        begin
+          result = connection_model.connection.select_all("EXPLAIN #{statement}")
+          match = /cost=\d+\.\d+..(\d+\.\d+) /.match(result.rows.first.first)
+          match[1] if match
+        rescue ActiveRecord::StatementInvalid
+          # do nothing
+        end
+      end
+    end
+
     def run_statement(statement, options = {})
       columns = nil
       rows = nil
@@ -151,7 +163,7 @@ module Blazer
         end
       end
 
-      Blazer.cache.write(cache_key, Marshal.dump([columns, rows, Time.now]), expires_in: cache.to_f * 60) if !error && cache
+      Blazer.cache.write(cache_key(statement), Marshal.dump([columns, rows, Time.now]), expires_in: cache.to_f * 60) if !error && cache
 
       [columns, rows, error]
     end