Core Concepts
Error Handling
Checked exceptions are an important feature of Java, but were a design misstep as implemented in JDBC.
Pyranid generally reports JDBC and database failures as a runtime DatabaseException, often wrapping the checked java.sql.SQLException. Notification session and receive methods deliberately declare InterruptedException so you can distinguish normal cooperative cancelation from a database failure; see Interruption And Supervision.
Practical Application
Here we detect if a unique constraint was violated by examining DatabaseException. We then handle that case specially by rolling back to a known-good savepoint.
// Gives someone at most one big award
database.transaction(() -> {
Transaction transaction = database.currentTransaction().orElseThrow();
Savepoint savepoint = transaction.createSavepoint();
try {
// We don't want to give someone the same award twice!
// Let the DBMS worry about constraint checking to avoid race conditions
database.query("""
INSERT INTO account_award (account_id, award_type)
VALUES (:accountId, :awardType)
""")
.bind("accountId", accountId)
.bind("awardType", AwardType.BIG)
.execute();
} catch(DatabaseException e) {
// Detect a unique constraint violation and gracefully continue on.
if(e.isUniqueConstraintViolation()) {
out.printf("The %s award was already given to account ID %s\n",
AwardType.BIG, accountId);
// Puts transaction back in good state
// (prior to constraint violation)
transaction.rollback(savepoint);
} else {
// There must have been some other problem, bubble out
throw e;
}
}
});
// Gives someone at most one big award
database.transaction(() -> {
Transaction transaction = database.currentTransaction().orElseThrow();
Savepoint savepoint = transaction.createSavepoint();
try {
// We don't want to give someone the same award twice!
// Let the DBMS worry about constraint checking to avoid race conditions
database.query("""
INSERT INTO account_award (account_id, award_type)
VALUES (:accountId, :awardType)
""")
.bind("accountId", accountId)
.bind("awardType", AwardType.BIG)
.execute();
} catch(DatabaseException e) {
// Detect a unique constraint violation and gracefully continue on.
if(e.isUniqueConstraintViolation()) {
out.printf("The %s award was already given to account ID %s\n",
AwardType.BIG, accountId);
// Puts transaction back in good state
// (prior to constraint violation)
transaction.rollback(savepoint);
} else {
// There must have been some other problem, bubble out
throw e;
}
}
});
References:
Exception Properties
For convenience, DatabaseException exposes additional properties, which are populated if provided by the underlying java.sql.SQLException:
It also exposes conservative classification predicates:
isUniqueConstraintViolation()isForeignKeyViolation()isDeadlock()isTransient()isSerializationFailure()isTimeout()
These predicates are intentionally conservative and database-type-aware. They recognize well-known SQLState and vendor error codes for PostgreSQL, MySQL, MariaDB, SQLite, SQL Server, Oracle, and generic JDBC transient/recoverable exception classes; they return false when Pyranid cannot reliably classify the failure.
DuckDB's driver reports no SQLStates or vendor codes, so classification there matches DuckDB's stable diagnostic message shapes: Constraint Error: duplicate-key and foreign-key messages drive the constraint predicates, and optimistic-concurrency TransactionContext Error: ... conflict failures classify as retryable serialization failures, integrating with RetryPolicy. DuckDB query timeouts surface as JDBC SQLTimeoutException and classify generically. The predicates return non-null Boolean values.
For PostgreSQL, the following properties are also available:
column(optional)constraint(optional)datatype(optional)detail(optional)file(optional)hint(optional)internalPosition(optional)internalQuery(optional)line(optional)dbmsMessage(optional)position(optional)routine(optional)schema(optional)severity(optional)table(optional)where(optional)
Interruption and Cancelation
Database::useRawConnection(...), Database::readDatabaseMetaData(...), and Database::performHealthCheck(...) restore the calling thread's interrupt flag before throwing when the propagated failure contains interruption evidence and no Pyranid transaction is open on that thread. This includes interruption during connection checkout and failures introduced by connection cleanup. Catching the DatabaseException does not clear the restored flag.
Inside a Pyranid transaction, those entry points do not restore the flag themselves. If the failure escapes the transaction closure, transaction completion restores reachable interruption evidence after cleanup and post-transaction callbacks. If your code handles the failure inside the closure, it decides whether to restore cancelation with Thread.currentThread().interrupt(). This distinction also applies to metadata and health checks: although they borrow independent connections, the presence of a Pyranid transaction on the calling thread still determines where interruption is restored.
An interrupted thread cannot admit another transaction retry, including when the backoff is zero. If expected cancelation has been fully handled and the application deliberately continues outside a transaction, Thread.interrupted() reads and clears the pending flag. Merely catching a database failure is not a reason to clear it.
Interrupting a thread does not guarantee that an in-flight JDBC call stops; cancelation depends on the driver. Use query timeouts or application-managed statement cancelation for that operation. Notification sessions expose a separate checked InterruptedException contract; see Interruption And Supervision.
Compatibility fallbacks for optional JDBC features preserve terminal rollback, connection, and cancelation failures. Such evidence propagates even when the same failure also reports an unsupported feature, so a fallback cannot silently continue after earlier transaction work was lost.

