Re: Writing triggers in C++ - Mailing list pgsql-hackers

From Florian G. Pflug
Subject Re: Writing triggers in C++
Date
Msg-id 45D3331A.4000009@phlo.org
Whole thread Raw
In response to Re: Writing triggers in C++  (Alvaro Herrera <alvherre@commandprompt.com>)
Responses Re: Writing triggers in C++  (Alvaro Herrera <alvherre@commandprompt.com>)
List pgsql-hackers
Alvaro Herrera wrote:
> Florian G. Pflug wrote:
>> Andreas Pflug wrote:
>>> Tom Lane wrote:
>>>> Jacob Rief <jacob.rief@gmx.at> writes:
>>>>  
>>>>> I tried to write a trigger using C++.
>>>>>    
>>>> That is most likely not going to work anyway, because the backend
>>>> operating environment is C not C++.  If you dumb it down enough
>>>> --- no exceptions, no RTTI, no use of C++ library --- then it might
>>>> work, 
>>> I can confirm that it does work this way.
>> I've written an aggregate function that uses c++ stl hashes, and it 
>> seems to work pretty well. I'd think that using exceptions should be
>> fine, as long as you make sure to _always_ catch any exception that
>> might be thrown inside your own c++ code, and don't let it propagate
>> into backend code. STL allows you to specify custom allocator classes
>> as template parameters to hash, vector and the like. You can use that
>> to let STL allocate memory from the correct memory context.
> 
> What happens if Postgres raises an elog(ERROR) in the code you're
> catching exceptions in?  Is it propagated outwards?

In my case, the only possible source of an elog(ERROR) would palloc(), 
when the machine is out of memory (Does it even throw elog(ERROR), or
does it return NULL just as malloc() ?). Since this is rather unlikely,
and would probably lead to a postgres shutdown anyway, I didn't really
care about that case.

You're right of course that this is different for triggers - they're 
much more likely to call SPI functions or otherwise interact with the
backend than my rather self-contained aggregate function. Still, I'd 
think that an elog(ERROR) would propagate outwards - but any C++
destructors of local (stack-allocated) objects wouldn't be called.

So, to be safe, I guess one would need to surround any call that could
call elog(ERROR) with an appropriate handler that translates the 
elog(ERROR) into a C++ exception. This C++ exception would have to be
translated back into an elog(ERROR) at the outmost level of C++ code.

Maybe we should create some wiki page or pgfoundry project that collects
all glue code, tipps and tricks that people invented to glue C++ into
the postgres backend.

greetings, Florian Pflug



pgsql-hackers by date:

Previous
From: Andrew Dunstan
Date:
Subject: Re: "anyelement2" pseudotype
Next
From: Tom Lane
Date:
Subject: Re: "anyelement2" pseudotype