+CREATE FUNCTION findplanetid(character varying, character varying, character varying) RETURNS integer
+ AS $_$my ($ruler, $planet, $race) = @_;
+my $query = spi_prepare('SELECT id, race FROM planets WHERE ruler=$1 AND planet=$2','varchar','varchar');
+my $rv = spi_exec_prepared($query,$ruler,$planet);
+spi_freeplan($query);
+my $status = $rv->{status};
+my $nrows = $rv->{processed};
+my $id;
+if ($nrows == 1){
+ $id = $rv->{rows}[0]->{id};
+ unless ($race eq $rv->{rows}[0]->{race}){
+ $query = spi_prepare('UPDATE planets SET race=$1 where id=$2','varchar','int4');
+ spi_exec_prepared($query,$race,$id);
+ spi_freeplan($query);
+ }
+}else {
+ $rv = spi_exec_query("SELECT nextval('public.forum_threads_ftid_seq') AS id");
+ if ($rv->{processed} != 1){
+ return;
+ }
+ $ftid = $rv->{rows}[0]->{id};
+ $query = spi_prepare('INSERT INTO forum_threads (fbid,ftid,subject,uid) VALUES($1,$2,$3,-3)','int4','int4','varchar');
+ $rv = spi_exec_prepared($query,-2,$ftid,"$ruler OF $planet");
+ spi_freeplan($query);
+ if (rv->{status} != SPI_OK_INSERT){
+ return;
+ }
+ $rv = spi_exec_query("SELECT nextval('public.planets_id_seq') AS id");
+ if ($rv->{processed} != 1){
+ return;
+ }
+ $id = $rv->{rows}[0]->{id};
+ $query = spi_prepare('INSERT INTO planets(id,ruler,planet,race,ftid) VALUES($1,$2,$3,$4,$5)','int4','varchar','varchar','varchar','int4
+');
+ $rv = spi_exec_prepared($query,$id,$ruler,$planet,$race,$ftid);
+ spi_freeplan($query);
+ if (rv->{status} != SPI_OK_INSERT){
+ return;
+ }
+
+}
+return $id;$_$
+ LANGUAGE plperl;