lib/pghero/methods/query_stats.rb in pghero-3.2.0 vs lib/pghero/methods/query_stats.rb in pghero-3.3.0
- old
+ new
@@ -170,14 +170,15 @@
def slow_queries(query_stats: nil, **options)
query_stats ||= self.query_stats(options)
query_stats.select { |q| q[:calls].to_i >= slow_query_calls.to_i && q[:average_time].to_f >= slow_query_ms.to_f }
end
+ # TODO option to include current period
def query_hash_stats(query_hash, user: nil)
if historical_query_stats_enabled? && supports_query_hash?
start_at = 24.hours.ago
- select_all_stats <<-SQL
+ select_all_stats <<~SQL
SELECT
captured_at,
total_time / 1000 / 60 AS total_minutes,
(total_time / calls) AS average_time,
calls,
@@ -203,11 +204,11 @@
def current_query_stats(limit: nil, sort: nil, database: nil, query_hash: nil)
if query_stats_enabled?
limit ||= 100
sort ||= "total_minutes"
total_time = server_version_num >= 130000 ? "(total_plan_time + total_exec_time)" : "total_time"
- query = <<-SQL
+ query = <<~SQL
WITH query_stats AS (
SELECT
LEFT(query, 10000) AS query,
#{supports_query_hash? ? "queryid" : "md5(query)"} AS query_hash,
rolname AS user,
@@ -236,11 +237,11 @@
total_minutes * 100.0 / (SELECT SUM(total_minutes) FROM query_stats) AS total_percent,
(SELECT SUM(total_minutes) FROM query_stats) AS all_queries_total_minutes
FROM
query_stats
ORDER BY
- #{quote_table_name(sort)} DESC
+ #{quote_column_name(sort)} DESC
LIMIT #{limit.to_i}
SQL
# we may be able to skip query_columns
# in more recent versions of Postgres
@@ -252,11 +253,11 @@
end
def historical_query_stats(sort: nil, start_at: nil, end_at: nil, query_hash: nil)
if historical_query_stats_enabled?
sort ||= "total_minutes"
- query = <<-SQL
+ query = <<~SQL
WITH query_stats AS (
SELECT
#{supports_query_hash? ? "query_hash" : "md5(query)"} AS query_hash,
pghero_query_stats.user AS user,
array_agg(LEFT(query, 10000) ORDER BY REPLACE(LEFT(query, 1000), '?', '!') COLLATE "C" ASC) AS query,
@@ -285,11 +286,11 @@
total_minutes * 100.0 / (SELECT SUM(total_minutes) FROM query_stats) AS total_percent,
(SELECT SUM(total_minutes) FROM query_stats) AS all_queries_total_minutes
FROM
query_stats
ORDER BY
- #{quote_table_name(sort)} DESC
+ #{quote_column_name(sort)} DESC
LIMIT 100
SQL
# we can skip query_columns if all stored data is normalized
# for now, assume it's not
@@ -328,22 +329,20 @@
end
def insert_query_stats(db_id, db_query_stats, now)
values =
db_query_stats.map do |qs|
- [
- db_id,
- qs[:query],
- qs[:total_minutes] * 60 * 1000,
- qs[:calls],
- now,
- supports_query_hash? ? qs[:query_hash] : nil,
- qs[:user]
- ]
+ {
+ database: db_id,
+ query: qs[:query],
+ total_time: qs[:total_minutes] * 60 * 1000,
+ calls: qs[:calls],
+ captured_at: now,
+ query_hash: supports_query_hash? ? qs[:query_hash] : nil,
+ user: qs[:user]
+ }
end
-
- columns = %w[database query total_time calls captured_at query_hash user]
- insert_stats("pghero_query_stats", columns, values)
+ PgHero::QueryStats.insert_all!(values)
end
end
end
end