--
-- 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;
