legitimacy of using PG_TRY , PG_CATCH , PG_END_TRY in C function

From: John Lumby <johnlumby(at)hotmail(dot)com>
To: "pgsql-hackers(at)postgresql(dot)org" <pgsql-hackers(at)postgresql(dot)org>
Subject: legitimacy of using PG_TRY , PG_CATCH , PG_END_TRY in C function
Date: 2017-10-23 00:30:30
Message-ID: DM5PR22MB1676C2FF997BF55615B1F063A3460@DM5PR22MB1676.namprd22.prod.outlook.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

I have a C function (a trigger function) which uses the PG_TRY()
construct to handle certain ERROR conditions.
One example is where invoked as INSTEAD OF INSERT into a view. It
PG_TRYs INSERT into the real base table,
but this table may not yet exist (it is a partitioned child of an
inheritance parent).
If the error is ERRCODE_UNDEFINED_TABLE, then the CATCH issues
FlushErrorState() and returns to caller who CREATes the table and
re-issues the insert.
All works perfectly (on every release of 9.x).

But in a different part of the same trigger function, there is a
PG_TRY , PG_CATCH of a CREATE INDEX,
which sometimes hits error "relation already exists" (i.e. index with
same name indexing a different table).
The CATCH issues FlushErrorState() and returns to caller who ignores the
error.
All works but not perfectly -- at COMMIT, resource_owner issues
relcache reference leak messages about relation scans not closed
and also about snapshot still active. I guess that the CREATE has
switched resource_owner and pushed a snapshot, but I did not
debug in detail.

Those are just examples, but my question is whether use of this
construct is legal in a C function
(always? sometimes e,g only for DML but not DDL? never?),
and if not, then how can one legally catch ERRORs like this in a C
function?
(Yes I realise I could write selects of pg_class to avoid these two
particular cases rather than the try-and-fail approach
but I would like to understand the general rules where it may be much
harder to try avoidance)

Cheers, John

Responses

Browse pgsql-hackers by date

  From Date Subject
Next Message Amit Langote 2017-10-23 01:43:27 Re: Block level parallel vacuum WIP
Previous Message Michael Paquier 2017-10-22 22:03:13 Re: [BUGS] BUG #14849: jsonb_build_object doesn't like VARIADIC calls very much