On Fri, 2004-05-28 at 06:07, Ramanujam H S Iyengar wrote:
> Can some one help me in the question !!!
> 
> Given the Oid of a relation .. how to get the Oid of the Primary key index 
> on that relation ?
> 
Attached, a couple of function I wrote that might do what you're after.
> 
> Thanks in adv,
> 
> -Ramu
> 
> _________________________________________________________________
> Post Classifieds on MSN classifieds. http://go.msnserver.com/IN/44045.asp
> Buy and Sell on MSN Classifieds.
> 
> 
> ---------------------------(end of broadcast)---------------------------
> TIP 4: Don't 'kill -9' the postmaster

Regards,

John
--
-- PostgreSQL database dump
--

SET SESSION AUTHORIZATION 'postgres';

--
-- select pk_column('tablename');
-- returns the name of the  primary key column
--
CREATE FUNCTION pk_column(text) RETURNS text
    AS '
    select attname::text
	from pg_class, pg_constraint, pg_attribute
	where pg_class.oid = conrelid
	and contype=''p'' 
	and attrelid = pg_class.oid 
	and attnum in (array_to_string(conkey,'',''))
	and relname=$1;
    '
    LANGUAGE sql STABLE;
    

--
-- select last_insert_id('tablename','columnname');
-- returns currval of the sequence assigned as default to columnname
--
CREATE FUNCTION last_insert_id(text, text) RETURNS bigint
    AS '
    select currval(
        (select 
            split_part(adsrc,'''''''',2) as seq
        from pg_class
        join pg_attribute on (pg_class.oid = pg_attribute.attrelid)
        join pg_attrdef 
            on (pg_attrdef.adnum = pg_attribute.attnum 
            and pg_attrdef.adrelid = pg_attribute.attrelid)
        where pg_class.relname = $1
            and pg_attribute.attname = $2)
    );
    '
    LANGUAGE sql;


--
-- select last_insert_id('tablename');
-- returns currval of the sequence assigned as default to the primary key column
--
CREATE FUNCTION last_insert_id(text) RETURNS bigint
    AS '
    select last_insert_id($1,pk_column($1));
    '
    LANGUAGE sql;
---------------------------(end of broadcast)---------------------------
TIP 6: Have you searched our list archives?

               http://archives.postgresql.org

Reply via email to