Created
August 28, 2018 16:24
-
-
Save jstanley0/384f6642bb5860eba088211baf42e15d to your computer and use it in GitHub Desktop.
list and kill Postgres queries from a Rails console
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# list pid, execution time, and query text for running queries | |
def pg_ps | |
now = Time.now | |
ActiveRecord::Base.connection.execute("SELECT pid, query, query_start FROM pg_stat_activity WHERE state='active'").to_a.each do |q| | |
printf "%8d %10.2f %s\n", q['pid'], now - DateTime.parse(q['query_start']), q['query'] | |
end | |
nil | |
end | |
# cancel the current query for the given process | |
def pg_cancel(pid) | |
ActiveRecord::Base.connection.execute("SELECT pg_cancel_backend(#{pid})") | |
end | |
# kill the database connection for the given process | |
def pg_kill!(pid) | |
ActiveRecord::Base.connection.execute("SELECT pg_terminate_backend(#{pid})") | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment