Re: CurrentMemoryContext and MemoryContextStrdup - Mailing list pgsql-novice

From Yessica Brinkmann
Subject Re: CurrentMemoryContext and MemoryContextStrdup
Date
Msg-id CABrYqSPH=20JYH+f2rkEFrWBcSQC+Vj0sFChN-hEVv_NTXewRg@mail.gmail.com
Whole thread Raw
In response to CurrentMemoryContext and MemoryContextStrdup  (Yessica Brinkmann <yessica.brinkmann@gmail.com>)
List pgsql-novice
I understand. Many thanks. I will try to modify my program to adapt it to this.
Best regards,
Yessica Brinkmann

El mar., 26 nov. 2019 a las 15:11, Tom Lane (<tgl@sss.pgh.pa.us>) escribió:
Yessica Brinkmann <yessica.brinkmann@gmail.com> writes:
> Now, as I understand it (I don't know if I'm right), what I would have to
> do would be this:
> 1. I save the CurrentMemoryContext, for example as follows:
> MemoryContext oldcontext = CurrentMemoryContext;
> 2. I make the call to SPI, which was what caused the context problem.
> 3. I copy my variable in a different context, for example as follows:
> MemoryContext newcontext;
> char * copy = MemoryContextStrdup (newcontext, data);
> 4. Then, at the end of my call to SPI, after SPI_finish () I would have in
> the copy variable, the copy of the data variable, to use it as I want.
> Is that so? I am correct at least to try to modify my program or is it
> totally something else what should I do?

IIRC, the real issue here is that SPI_connect creates and switches into
a temporary context that SPI_finish will destroy; and the string you want
is in that short-lived context.  So what you want is to copy it out of
that context, probably into the context that was current before you
call SPI_connect.  So what you want is to do this before calling
SPI_connect:

        MemoryContext outer_context = CurrentMemoryContext;

and then this, inside the SPI operation, will save your string safely:

        copy = MemoryContextStrdup(outer_context, data);

                        regards, tom lane

pgsql-novice by date:

Previous
From: Tom Lane
Date:
Subject: Re: CurrentMemoryContext and MemoryContextStrdup
Next
From: Goke Aruna
Date:
Subject: Slow response to my query