Skip to content

Commit 2c35308

Browse files
author
Thomas Hareau
authored
Add duration for blocking queries (#26)
* add duration for blocking queries * Update log * Remove absolute time * Fix tests
1 parent 6602255 commit 2c35308

File tree

2 files changed

+9
-4
lines changed

2 files changed

+9
-4
lines changed

lib/safe-pg-migrations/plugins/blocking_activity_logger.rb

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
module SafePgMigrations
44
module BlockingActivityLogger
55
SELECT_BLOCKING_QUERIES_SQL = <<~SQL.squish
6-
SELECT blocking_activity.query
6+
SELECT blocking_activity.query, blocked_activity.xact_start as start
77
FROM pg_catalog.pg_locks blocked_locks
88
JOIN pg_catalog.pg_stat_activity blocked_activity
99
ON blocked_activity.pid = blocked_locks.pid
@@ -50,7 +50,7 @@ def log_blocking_queries(method)
5050
blocking_queries_retriever_thread =
5151
Thread.new do
5252
sleep delay_before_logging(method)
53-
SafePgMigrations.alternate_connection.query_values(SELECT_BLOCKING_QUERIES_SQL % raw_connection.backend_pid)
53+
SafePgMigrations.alternate_connection.query(SELECT_BLOCKING_QUERIES_SQL % raw_connection.backend_pid)
5454
end
5555

5656
yield
@@ -75,7 +75,7 @@ def log_blocking_queries(method)
7575
"Statement was being blocked by the following #{'query'.pluralize(queries.size)}:", true
7676
)
7777
SafePgMigrations.say '', true
78-
queries.each { |query| SafePgMigrations.say " #{query}", true }
78+
queries.each { |query, start_time| SafePgMigrations.say "#{format_start_time start_time}: #{query}", true }
7979
SafePgMigrations.say(
8080
'Beware, some of those queries might run in a transaction. In this case the locking query might be '\
8181
'located elsewhere in the transaction',
@@ -86,5 +86,10 @@ def log_blocking_queries(method)
8686

8787
raise
8888
end
89+
90+
def format_start_time(start_time, reference_time = Time.now)
91+
duration = (reference_time - start_time).round
92+
"transaction started #{duration} #{'second'.pluralize(duration)} ago"
93+
end
8994
end
9095
end

test/safe_pg_migrations_test.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -85,7 +85,7 @@ def up
8585
' -> Statement was being blocked by the following query:',
8686
' -> ',
8787
], calls[0..4]
88-
assert_includes calls[5], ' -> BEGIN; SELECT 1 FROM users'
88+
assert_match(/\s*-> transaction started 1 second ago:\s*BEGIN; SELECT 1 FROM users/, calls[5])
8989
assert_equal [
9090
' -> ',
9191
' -> Retrying in 1 seconds...',

0 commit comments

Comments
 (0)