While hacking PostgreSQL it’s very useful to know pid of the backend you are working with. You need to know pid of the process to attach debugger, profiler etc. Luckily, .psqlrc provides us an elegant way to define the shortcuts for psql. Using config line below one can find out backend pid just by typing :pid.

.psqlrc
1
\set pid 'SELECT pg_backend_pid();'
1
2
3
4
5
=# :pid
 pg_backend_pid
----------------
          99038
(1 row)

In 9.6 it becomes possible to even include backend pid into psql prompt.

However, it’s possible to automate more complex actions in psql. I’ve configured my psql to run gdb attached to current backend in new tab of iTerm2 just by typing :gdb.

The :gdb command selects pid of current backend and puts it to the input of pg_debug script.

.psqlrc
1
\set gdb 'SELECT pg_backend_pid() \\g |pg_debug'

pg_debug extracts pid from its input and then runs OSA script which runs gdb in the new tab of iTerm2.

pg_debug
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#!/bin/bash

IFS=''

while read line
do
	# Extended display off
	if [[ $line =~ ^\ +([0-9]+) ]]; then
		PID=${BASH_REMATCH[1]}
		break
	fi
	# Extended display on
	if [[ $line =~ ^pg_backend_pid.*\ ([0-9]+) ]]; then
		PID=${BASH_REMATCH[1]}
		break
	fi
done

# Open gdb session
osascript -e "
tell application \"iTerm\"
	activate
	tell the current terminal
		set mysession to (the current session)
		launch session \"Default Session\"
		tell the last session
			write text \"gdb --pid=$PID -x <(echo continue)\"
		end tell
		select mysession
	end tell
end tell"

This script works for Mac OS X and iTerm2, but the same approach should work for other platforms and terminal emulators.

Comments