Andres Freund <> writes:
> On 2014-04-07 16:29:57 -0400, Tom Lane wrote:
>> In that case you should have another tuple slot of your own and let it
>> keep the tuple (and buffer pin).

> that's not going to work, because scantuple might be free'd or pointing
> to another tuple, from the next index_getnext() call. Right?

It's true that scantuple is probably pointing at the xs_ctup field of the
IndexScanDesc, so you need to put that data somewhere else if you want
to hold onto it past the current loop iteration.

> So what I now do is essentially:
> while ((scantuple = index_getnext(scan, ForwardScanDirection)) != NULL)
> {
> ...
>         ht = palloc(sizeof(HeapTupleData)); /* in the right context */
>         memcpy(ht, scantuple, sizeof(HeapTupleData));
>         ExecStoreTuple(ht, slot, scan->xs_cbuf, false);
>         slot->tts_shouldFree = true;
> ...
> }

Well, that is certainly messy.  I think you could just use a local
HeapTupleData variable instead of palloc'ing every time, where "local"
means "has lifespan similar to the slot pointer".  That is

      HeapTupleData my_htup;

      while ((scantuple = index_getnext(scan, ForwardScanDirection)) != NULL)
                memcpy(&my_htup, scantuple, sizeof(HeapTupleData));
                ExecStoreTuple(&my_htup, slot, scan->xs_cbuf, false);

If my_htup is just a local, you'd want to clear the slot before my_htup
goes out of scope, just to be sure it doesn't try to dereference a
dangling pointer.  There's some vaguely similar hacking near the end of

                        regards, tom lane

Sent via pgsql-hackers mailing list (
To make changes to your subscription:

Reply via email to