Re: Why does SPI_connect change the memory context?

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: Jeff Davis <pgsql(at)j-davis(dot)com>
Cc: pgsql-hackers(at)postgresql(dot)org
Subject: Re: Why does SPI_connect change the memory context?
Date: 2019-05-29 22:25:09
Message-ID: 41589.1559168709@sss.pgh.pa.us
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

Jeff Davis <pgsql(at)j-davis(dot)com> writes:
> SPI_connect() changes the memory context to a newly-created one, and
> then SPI_finish() restores it. That seems a bit dangerous because the
> caller might not be expecting it. Is there a reason it doesn't just
> change to the new memory context as-needed?

Because the expectation is that palloc inside the SPI procedure will
allocate in a procedure-specific context. If the caller isn't expecting
that, they haven't read the documentation, specifically

https://www.postgresql.org/docs/devel/spi-memory.html

which says

<para>
<function>SPI_connect</function> creates a new memory context and
makes it current. <function>SPI_finish</function> restores the
previous current memory context and destroys the context created by
<function>SPI_connect</function>. These actions ensure that
transient memory allocations made inside your C function are
reclaimed at C function exit, avoiding memory leakage.
</para>

regards, tom lane

In response to

Browse pgsql-hackers by date

  From Date Subject
Next Message Tom Lane 2019-05-29 22:39:36 Re: coverage increase for worker_spi
Previous Message Tom Lane 2019-05-29 22:17:46 Re: Rearranging ALTER TABLE to avoid multi-operations bugs