Skip to content

Instantly share code, notes, and snippets.

@jstanley0
Created August 28, 2018 16:24
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jstanley0/384f6642bb5860eba088211baf42e15d to your computer and use it in GitHub Desktop.
Save jstanley0/384f6642bb5860eba088211baf42e15d to your computer and use it in GitHub Desktop.
list and kill Postgres queries from a Rails console
# 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