Last active
September 2, 2022 14:12
-
-
Save dmos62/aa754a04ff8bf36d6565d74b2dad6513 to your computer and use it in GitHub Desktop.
Script for counting number of Postgres txs performed since starting the script
This file contains 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
#!/bin/sh | |
# Requires `psql`. The script effectively wraps a `psql` invocation. | |
# This is what I use for installing psql: `apt update && apt install postgresql-contrib -y`. | |
# Checks Postgres's tx counter, then blocks until ctrl-c is pressed, then checks tx counter again, | |
# prints difference, and exits. Start it before performing some database interactions, then press | |
# Ctrl-C to get the number of transaction commits that were performed since starting script. | |
# | |
# Should be called with the psql command as argument: | |
# | |
# Examples: | |
# ./count_txs.sh psql -E postgresql://a:b@c:1234/d | |
# ./count_txs.sh docker exec -it $SOME_CONTAINER psql -E postgresql://user:pass@host:1234/db | |
psql_command=$@ | |
get_second_line() { | |
sed -sn 2p | |
} | |
trim_whitespace() { | |
tr -d ' ' | |
} | |
print_tx_counter_value() { | |
$psql_command --no-align \ | |
-c 'SELECT sum(xact_commit+xact_rollback) FROM pg_stat_database;' \ | |
| get_second_line \ | |
| trim_whitespace | |
} | |
counter_at_start="$(print_tx_counter_value)" | |
calc_difference() { | |
# using python, because expr and bc complain about non-integer output and | |
# whitespace trimming doesn't seem to help | |
python3 -c "print($1 - $2)" | |
} | |
print_change_since_start() { | |
counter_at_exit="$(print_tx_counter_value)" | |
echo "" | |
echo "counter_at_start $counter_at_start" | |
echo "counter_at_exit $counter_at_exit" | |
calc_difference $counter_at_exit $counter_at_start | |
} | |
finish_script() { | |
print_change_since_start && exit | |
} | |
trap finish_script 2 | |
echo "ctrl-c to stop counting" | |
sleep infinity |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment