BUG #4684: lastval in function - Mailing list pgsql-bugs

From andreas
Subject BUG #4684: lastval in function
Date
Msg-id 200902281103.n1SB3Dqu084067@wwwmaster.postgresql.org
Whole thread Raw
Responses Re: BUG #4684: lastval in function  (Tom Lane <tgl@sss.pgh.pa.us>)
Re: BUG #4684: lastval in function  (Heikki Linnakangas <heikki.linnakangas@enterprisedb.com>)
List pgsql-bugs
The following bug has been logged online:

Bug reference:      4684
Logged by:          andreas
Email address:      postgresql@elbrief.de
PostgreSQL version: 8.3.6
Operating system:   linux
Description:        lastval in function
Details:

create table bla ( id serial primary key , name text not null unique ) ;
create table bla2 ( id serial primary key , blaid int references bla , name
text not null unique ) ;
create or replace function blaa( text ) returns int as $$
  my $name = shift ;
  my $q = spi_exec_query( "select id from bla where name = '$name'" ) ;
  if ( not $q->{ rows }->[ 0 ]->{ id } ) {
    spi_exec_query( "insert into bla ( name ) values ( '$name' )" ) ;
    $q = spi_exec_query( "select lastval() as id" ) ;
  }
  return $q->{ rows }->[ 0 ]->{ id } ;
$$ language plperl security definer ;
select blaa( 'test' ) ;
insert into bla2 ( blaid , name ) values ( blaa( 'muster' ) , 'muster' ) ;

select lastval() ;
 lastval
---------
       2

i expected lastval() should be 1, because this is the id from the
insertstatement.

insert into bla2 ( blaid , name ) values ( blaa( 'muster2' ) , blaa(
'muster3' ) ) ;

select lastval() ;
 lastval
---------
       4

if nextval is used inside a function in a insertstatement, you get always
the value from inside the last function. but i expected, that lastval()
deliver the value from the insertstatement. i think, this should clearify in
the documentation, or better fixed that the nextval from an insertstatement
is called after the functioncalls.

Andreas

pgsql-bugs by date:

Previous
From: Tom Lane
Date:
Subject: Re: BUG #4680: Server crashed if using wrong (mismatch) conversion functions
Next
From: Tom Lane
Date:
Subject: Re: BUG #4684: lastval in function