#!/bin/bash

# This script looks for transactions in the target database which are:
# * in a transaction
# * currently idle
# * have been idle for more than $timeout
# and then safely terminates those transactions.
#
# Call with the target database and the timeout in postgresql english.
# Eg, ./kile-idle-transactions justintv_dev '15 minutes'

nparms=$#
if [ $nparms -ne 2 ]; then
 >&2 echo "$0 target_dbname timeout"
 >&2 echo "Missing requried parameters"
 exit -1
fi
target_dbname=$1
timeout=$2

sql="SELECT pg_stat_activity.*, pg_terminate_backend(pid) FROM pg_stat_activity WHERE state = 'idle in transaction' AND (now() - state_change) > '${timeout}'"

psql -t -A -d $target_dbname -c "${sql}"
