문제

I'm trying to determine if a transaction fails from the application. How can this be done?

Further, is it possible to determine where a transaction failed, such as particular write that violates a constraint?

도움이 되었습니까?

해결책

In regular libpq, you would:

  • Test the result of a query with PQresultStatus

  • PQresultErrorField(thePgResult, PG_DIAG_SQLSTATE) to get the SQLSTATE

  • Use PQerrorMessage to get the error message for display to the user. do not rely on parsing this in your application, instead use the SQLSTATE, and the other fields in the result struct.

See connection status functions, libpq exec functions and the rest of the libpq documentation.

Related: How to get the sql state from libpq?

I have no experience with libpqxx, but I would expect it to wrap SQL errors into C++ exceptions with fields for the SQLState etc. See the getting started guide for libpqxx and the libpqxx exception classes reference.

This mailing list post and the replies in the thread will also be of interest, but be aware it's from 2007, and since then PostgreSQL has been extended to report more information in PQresult, like PG_DIAG_CONSTRAINT_NAME. No idea if libpqxx has been extended to take advantage of that, but you might be able to unwrap the exception to get an underlying PQresult if not.

There is, AFAIK, no way to get the actual value causing the issue except by showing the user the full error message. It'd be nice to change that.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top