This semester I've been doing a project with PostgreSQL and I needed to attach a debugger to PostgreSQL on numerous occasions to see what was going on. Since I didn't find much documentation on how to accomplish this, I thought I'd document it here for myself so I can refer to it in the future.
First off, since we want to attach a debugger to a program, we should make sure that program is compiled with debugging information. WIth Postgres, we can easily do that by passing it as an option to the configure script in the top level of the Postgres source code. Thus, I run configure as follows:

Now we can just build the source and install as per usual. Enabling asserts was a good idea for me in my situation as it turns on many sanity checks which were useful for my purposes. Next, we start up the Postgres server and create a database if necessary. Once that is done, clients can connect to the database. So I go ahead and start a session using the psql command line utility and connect to my newly created database.
Once a client was connected, I was able to run the following script in another terminal to find and attach to the Postgres process that was serving my session (this script is very much based on something that Tom Lane posted to the pg-hackers mailing list some time ago):

If no session is currently connected to Postgres, this script does nothing and silently exits. However, if a session is open, then gdb will attach to the Postgres server process serving that session. Here is an example output from when I ran it:

I ran a query in another terminal which triggered the breakpoint that I set in my debugger. The script I have provided does not work very elegantly if there are multiple clients connected to Postgres. It just lists out the process ID's of the various clients. For example, if 2 clients are connected to Postgres, we would get:

We could then manually use gdb to attach to the process that we are interested in. We can find out which process it is that we want to connect to from within our client's session as so:

Now we see that this session corresponds to process 16588. We can simply attach gdb to this process as is done in the above shell script.
During the semester, this script worked fine for me as I never had to worry about multiple clients being connected at the same time. I was only ever dealing with 1 client connected to the server at a time so the above script served my purposes perfectly.
Note that the above process won't work if you want to debug part of the backend startup sequence. If you are interested in doing this, a very brief explanation is given on the PostgreSQL developers FAQ. I have not tried this and don't know how realiable or easy this is to do.

blog comments powered by Disqus


03 May 2009