pg.ddx.io  pgsql-general@postgresql.org mailing list archive  
help / color / mirror / Atom feed
Recursion in plpgsql
8+ messages / 6 participants
[nested] [flat]

* Recursion in plpgsql
@ 2002-03-30 22:37  Uros Gruber <uros@sir-mag.com>
  0 siblings, 1 reply; 8+ messages in thread

From: Uros Gruber @ 2002-03-30 22:37 UTC (permalink / raw)
  To: pgsql-general

Hi!

i have one table with categories. And columns important for
this to work. ID_CATEGORY and ID_PARENT. Now i want to do
"HERE-YOU-ARE" navigation. First here is my PHP code for
this.

function catPath( $cat, $file ) {
    static $p;
    $path = $p;
  
    $strSQL = "SELECT Name,Parent FROM category WHERE IDCategory='$cat'";
    $objDB->query( $strSQL );
    $objDB->next_record();
    $parent = $objDB->f( "Parent" );
    $name = $objDB->f( "Name" );

    $intProdCount = countProd( $cat );
    
    if ( strlen( $parent ) > 0 ) {
       if ( $intProdCount > 0 ) {
          $p = "<a href=\"$file?cat=$cat\">$name</a>";
       } else {
          $p = $name;
       }
       $p .= "<img width=\"10\" height=\"10\" src=\"img/design/rarr.gif\"> $path";
       catPath( $parent, $file );
    }
  
    return $p;
} 
This code is OK, but if i'm deeper in the tree code is
slower and there is more sql queries. So i wan't to do this
on sql server with plpgsql.

I have 2 questions:

How can i tell function to call herself like up in PHP
example. And then is it possible to put data in some kind
temporary table and when it finish doing recursion i will get
data from that table and then use it in PHP.

Is there anyone who can know how to solve this or maybe have
better idea or maybe it not worth to worry about this because
it's fast enough.

-- 
bye
 Uros                          mailto:uros@sir-mag.com




^ permalink  raw  reply  [nested|flat] 8+ messages in thread

* Re: Recursion in plpgsql
@ 2002-04-01 15:31  Fran Fabrizio <ffabrizio@mmrd.com>
  parent: Uros Gruber <uros@sir-mag.com>
  0 siblings, 0 replies; 8+ messages in thread

From: Fran Fabrizio @ 2002-04-01 15:31 UTC (permalink / raw)
  To: Uros Gruber <uros@sir-mag.com>; +Cc: pgsql-general


> How can i tell function to call herself like up in PHP
> example. And then is it possible to put data in some kind
> temporary table and when it finish doing recursion i will get
> data from that table and then use it in PHP.

You can just call it like this:

create function myfunc(int4) returns int4 as '
   DECLARE
     foototal int4;
     foo int4;
   BEGIN
     --do some stuff
     --store some data in a table for later retrieval
     --if this is the recursive case then do the following
     select into foo myfunc(foo);
     foototal := foo + foototal;
     --etc....
     return foo;
   END;
' language 'plpgsql';

Something like that, this is off the top of my head.

I did run into trouble when using temporary (as opposed to permanent 
ones which I just deleted from every time - a hack, I know) tables. I 
can't remember exactly what the specific problem was, but it was some 
sort of catch-22 as to where to create the temp table so that the 
function could see it and then I could still access it after the 
function ran but without having another call to the same function from 
the same session cause overwriting issues. I remember it evolved into a 
mess of trying to do transactions around the recursive function (you can 
go back and read my thread about it on here if you wish) but the end 
result was that I converted from a linked list model to a nested set 
model and solved the problem that way.  Which brings me to my next point...

> Is there anyone who can know how to solve this or maybe have
> better idea or maybe it not worth to worry about this because
> it's fast enough.

If it's fast enough stay with what you've got.  Also, Joe Celko's
book 'SQL for Smarties' has an alternate technique called nested sets. 
Depending on
which operations you need to do on your data, it may be faster.  In 
particular, I've
quantitatively observed that for my data at least, nested set approach 
is faster for determining all children of a particular parent, or all 
parents for a particular child, but that to find the immediate parent, 
it's actually quicker to do recursion/linked list style like you've done 
rather than nested sets.

Hope that helps,
Fran




^ permalink  raw  reply  [nested|flat] 8+ messages in thread

* recursion in plpgsql
@ 2018-11-06 22:54  David Gauthier <davegauthierpg@gmail.com>
  0 siblings, 2 replies; 8+ messages in thread

From: David Gauthier @ 2018-11-06 22:54 UTC (permalink / raw)
  To: pgsql-general

Hi:

I'm trying/failing to write a recursive plpgsql function where the function
tries to operate on a hierary of records in a reflexive table.
parent-child-grandchild type of recursion.

I tried with a cursor, but got a "cursor already in use" error.  So that
looks like scoping.

I know I did this sort of thing in the past, but I can't remember if I used
cursors or some other construct to traverse the hierarchy.

Here's the code that's failing...


========================================================
create or replace function spk_fix_areas(parent_id int)
 returns text as $$

  declare
    par_area text;
    child int;
    child_node_curr cursor for select id from spk_ver_node where parent =
parent_id;
    area_id int;
    area_area text;
  begin

  select area into par_area from spk_ver_task_area where id = parent_id;

  open child_node_curr;

  loop

    fetch child_node_curr into child;
    exit when not found;

raise notice 'child: %',child;

    select id,area into area_id,area_area from spk_ver_task_area where id =
child and area = par_area;
    continue when found;

raise notice 'attempting insert child = %, area = %',child,par_area;
    insert into spk_ver_task_area (id,area) values (child,par_area);

    select spk_fix_areas(child);

  end loop;

  return('done');


  end;
$$ language plpgsql;

===============================================

Thanks for any help !

^ permalink  raw  reply  [nested|flat] 8+ messages in thread

* Re: recursion in plpgsql
@ 2018-11-06 23:31  Steve Crawford <scrawford@pinpointresearch.com>
  parent: David Gauthier <davegauthierpg@gmail.com>
  1 sibling, 0 replies; 8+ messages in thread

From: Steve Crawford @ 2018-11-06 23:31 UTC (permalink / raw)
  To: davegauthierpg@gmail.com; +Cc: pgsql-general

On Tue, Nov 6, 2018 at 2:54 PM David Gauthier <davegauthierpg@gmail.com>
wrote:

> Hi:
>
> I'm trying/failing to write a recursive plpgsql function where the
> function tries to operate on a hierary of records in a reflexive table.
> parent-child-grandchild type of recursion.
>
> I tried with a cursor, but got a "cursor already in use" error.  So that
> looks like scoping.
>
> I know I did this sort of thing in the past, but I can't remember if I
> used cursors or some other construct to traverse the hierarchy.
>

Recursive common-table-expression queries would be the typical way. Perhaps
that's what you used before

 https://www.postgresql.org/docs/current/queries-with.html

Cheers,
Steve

^ permalink  raw  reply  [nested|flat] 8+ messages in thread

* Re: recursion in plpgsql
@ 2018-11-07 00:29  Tom Lane <tgl@sss.pgh.pa.us>
  parent: David Gauthier <davegauthierpg@gmail.com>
  1 sibling, 1 reply; 8+ messages in thread

From: Tom Lane @ 2018-11-07 00:29 UTC (permalink / raw)
  To: David Gauthier <davegauthierpg@gmail.com>; +Cc: pgsql-general

David Gauthier <davegauthierpg@gmail.com> writes:
> I'm trying/failing to write a recursive plpgsql function where the function
> tries to operate on a hierary of records in a reflexive table.
> parent-child-grandchild type of recursion.
> I tried with a cursor, but got a "cursor already in use" error.  So that
> looks like scoping.

IIRC, the "portal" underlying a plpgsql cursor just gets the same name
as the cursor variable by default, so you'll get portal-name conflicts
with the coding style you show here.

It's possible to avoid that by ensuring that each cursor gets a different
portal name.  I'm too lazy to check the details right now, but at the
very least there's a way to do it by declaring the variable as "refcursor"
and assigning it a different name at each nesting depth.  There might be
some more elegant solution, too.

			regards, tom lane




^ permalink  raw  reply  [nested|flat] 8+ messages in thread

* Re: recursion in plpgsql
@ 2018-11-07 14:35  David Gauthier <davegauthierpg@gmail.com>
  parent: Tom Lane <tgl@sss.pgh.pa.us>
  0 siblings, 1 reply; 8+ messages in thread

From: David Gauthier @ 2018-11-07 14:35 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; scrawford@pinpointresearch.com; +Cc: pgsql-general

Thanks for the replies !

Steve: I don't remember using a recursive query like that, but it certainly
does look interesting.

Tom: I seem to remember (but am probably wrong) that cursors were locally
scoped (or could be made so).  This was several years ago with an earlier
v8 version.  Was that sort of thing around back then ?
Perhaps I stuffed the results in an array or temp table and then fed out of
that in recursive calls.  I remember having to stuff arrays in oracle 8 WAY
back in the day, and then read out of that for recursive calls.  But I also
seem to remember being delighted with plpsql because that wasn't necessary
anymore.

On Tue, Nov 6, 2018 at 7:29 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:

> David Gauthier <davegauthierpg@gmail.com> writes:
> > I'm trying/failing to write a recursive plpgsql function where the
> function
> > tries to operate on a hierary of records in a reflexive table.
> > parent-child-grandchild type of recursion.
> > I tried with a cursor, but got a "cursor already in use" error.  So that
> > looks like scoping.
>
> IIRC, the "portal" underlying a plpgsql cursor just gets the same name
> as the cursor variable by default, so you'll get portal-name conflicts
> with the coding style you show here.
>
> It's possible to avoid that by ensuring that each cursor gets a different
> portal name.  I'm too lazy to check the details right now, but at the
> very least there's a way to do it by declaring the variable as "refcursor"
> and assigning it a different name at each nesting depth.  There might be
> some more elegant solution, too.
>
>                         regards, tom lane
>

^ permalink  raw  reply  [nested|flat] 8+ messages in thread

* Re: recursion in plpgsql
@ 2018-11-07 15:17  Andrew Gierth <andrew@tao11.riddles.org.uk>
  parent: David Gauthier <davegauthierpg@gmail.com>
  0 siblings, 1 reply; 8+ messages in thread

From: Andrew Gierth @ 2018-11-07 15:17 UTC (permalink / raw)
  To: David Gauthier <davegauthierpg@gmail.com>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; scrawford@pinpointresearch.com; pgsql-general

>>>>> "David" == David Gauthier <davegauthierpg@gmail.com> writes:

 David> Tom: I seem to remember (but am probably wrong) that cursors
 David> were locally scoped (or could be made so). This was several
 David> years ago with an earlier v8 version. Was that sort of thing
 David> around back then ?

There are two distinct objects here being called "cursor": one is the
plpgsql variable, which is locally scoped, and the other is the actual
open portal, which must have a unique name within the session.

By default, plpgsql explicit bound cursors (but not plain "refcursor"
variables) take their portal name from the plpgsql variable name, and
hence don't work recursively by default. This is a convenience so that
code outside the function can use the same name to refer to the open
portal.

However, plpgsql cursor variables (whether declared bound or unbound)
can be assigned a text value or NULL _before_ being opened, and if so,
that value will be used for the portal name, or if NULL, a name of
"<unnamed portal N>" will be uniquely generated. (_After_ the open, the
variable's text value is the actually assigned portal name.) Unbound
refcursor variables default to NULL, so they are assigned unique portal
names on opening.

So in your example, adding

    child_node_curr := NULL;

immediately before the OPEN statement should be sufficient.

-- 
Andrew (irc:RhodiumToad)




^ permalink  raw  reply  [nested|flat] 8+ messages in thread

* Re: recursion in plpgsql
@ 2018-11-07 15:27  Tom Lane <tgl@sss.pgh.pa.us>
  parent: Andrew Gierth <andrew@tao11.riddles.org.uk>
  0 siblings, 0 replies; 8+ messages in thread

From: Tom Lane @ 2018-11-07 15:27 UTC (permalink / raw)
  To: Andrew Gierth <andrew@tao11.riddles.org.uk>; +Cc: David Gauthier <davegauthierpg@gmail.com>; scrawford@pinpointresearch.com; pgsql-general

Andrew Gierth <andrew@tao11.riddles.org.uk> writes:
> [ nice summary ]

Should we try to improve the docs in this area?

			regards, tom lane




^ permalink  raw  reply  [nested|flat] 8+ messages in thread


end of thread, other threads:[~2018-11-07 15:27 UTC | newest]

Thread overview: 8+ messages (download: mbox mbox.gz follow: Atom feed)
-- links below jump to the message on this page --
2002-03-30 22:37 Recursion in plpgsql Uros Gruber <uros@sir-mag.com>
2002-04-01 15:31 ` Fran Fabrizio <ffabrizio@mmrd.com>
2018-11-06 22:54 recursion in plpgsql David Gauthier <davegauthierpg@gmail.com>
2018-11-06 23:31 ` Re: recursion in plpgsql Steve Crawford <scrawford@pinpointresearch.com>
2018-11-07 00:29 ` Re: recursion in plpgsql Tom Lane <tgl@sss.pgh.pa.us>
2018-11-07 14:35   ` Re: recursion in plpgsql David Gauthier <davegauthierpg@gmail.com>
2018-11-07 15:17     ` Re: recursion in plpgsql Andrew Gierth <andrew@tao11.riddles.org.uk>
2018-11-07 15:27       ` Re: recursion in plpgsql Tom Lane <tgl@sss.pgh.pa.us>

This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox