Finding the Sequence of a Table's Primary Key

Update: The Solution!

Thanks to the help of oicu on #postgresql on Freenode, the following solution does what I want:

SELECT currval(relname) AS lastID FROM pg_class WHERE relname ~ '^TABLENAME_.+_seq$' AND relkind='S';

Problem Overview

I want to write a function (in PL/Ruby for PostgreSQL) which performs an insert on a table, and returns the ID of the primary key/sequence for that table, if one exists.

I want this function to figure out on its own if the table's primary key is a sequence, and if so what it's name is (so I can use the currval() function).

Findings So Far

Last night DBhome_ pointed me to the pg_class and pg_attribute tables and offered the following rough code:

select a.attname, a.oid from pg_attribute a, pg_class c where c.relid = a.relid and c.relname ='tname' order by a.oid limit 1;

Unfortunately this didn't work directly: pg_attribute doesn't have an oid column, and pg_class doesn't have a relid column. But it's a start! :)

Following are excerpts from the two tables which are hopefully in the correct range. Assume I want to find out if the t_clients table's primary key is a sequence, and if so I want to know the name of the sequence (which I suppose I can construct if I know the name of the primary key which is a sequence).

pg_class

Excerpt of the pg_class table

pg_attribute

Excerpt of the pg_attribute table