Pyranid Logo

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.

Database::transactionWithOutcome(...) instead retains ordinary final invocation failures in TransactionOutcome.getFailure(), exposed as an Optional containing a RuntimeException. The database result remains independent: cleanup can fail after COMMITTED, while a normal rollback-only outcome has no failure. Programming errors are retained too; rethrow failures you do not recognize. Final Errors and pre-boundary validation still throw. This API runs one attempt and provides no durable business outcome or general permission to retry. See Obtaining a Transaction Outcome for usage.


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;
    }
  }
});

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:

SQLState is an operational code and is preserved verbatim when available, including when a secure bound value overlaps its text. Secure-value scrubbing still applies to diagnostic messages and other DBMS text fields.

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.

PostgreSQL SQLState 55P03 (lock unavailable, including NOWAIT and lock timeouts) and Oracle error codes 54/30006 classify as both timeout and transient failures. SQL Server 3960 (snapshot update conflict) classifies as transient and as a serialization failure; that code alone does not classify as a timeout. These classifications allow the corresponding RetryPolicy conditions to recognize body failures after rollback. They do not establish whether a commit succeeded.

Generic JDBC handling, including MariaDB, counts a SQLTransientConnectionException subtype as transient only when its SQLState is absent or starts with 08. MariaDB can use that subtype for application SIGNAL errors such as SQLState 45000, which no longer qualify through the subtype alone. Independent class 08 (connection) or 40 (transaction rollback) evidence in the primary, cause or next-exception chain still qualifies. Other JDBC transient/recoverable subtype handling is unchanged.

SQLite SQLITE_CONSTRAINT_ROWID joins primary-key and unique-index result codes as a recognized unique constraint violation. CHECK, NOT NULL and foreign-key result codes alone do not classify as uniqueness failures.

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 transient serialization failures. Commit-time TransactionContext Error: Failed to commit: PRIMARY KEY or UNIQUE constraint violation failures classify as unique constraint violations. A duplicate value containing conflict does not make that commit-time constraint failure transient or a serialization failure. DuckDB query timeouts surface as JDBC SQLTimeoutException and classify generically. The predicates return non-null Boolean values.

Diagnostic classification does not prove transaction outcome. A mixed commit exception can report isSerializationFailure() == true while the final transaction result is IN_DOUBT; a secondary 40001 cannot authorize replay of possibly committed work. Commit-phase rollback proof requires the direct 40001, compatible readable evidence throughout the exception graph and successful follow-up rollback. Vendor-only commit diagnostics do not qualify. Body/statement diagnostic classifiers remain separate from that proof. With the currently tested DuckDB JDBC driver, commit-time conflicts report no SQLState. All such conflicts remain IN_DOUBT and are never automatically retried, even after successful follow-up rollback. DuckDB commit-time duplicate-key failures likewise remain IN_DOUBT, even when isUniqueConstraintViolation() identifies the cause. Neither COMMITTED nor IN_DOUBT admits an automatic transaction retry; resolve uncertainty using the original durable operation identity.

On PostgreSQL and DuckDB, handled failures and participating raw/custom JDBC access can trigger pre-commit validation. If the transaction is aborted or a required check cannot establish usability, traditional transactions throw a new refusal; outcome transactions retain it. Its cause and classifier flags can describe the first failure already handled by application code. A query-only or state-only refusal may have no cause or inherited SQLState. Successful validation does not surface a handled failure merely because it was recorded.

For PostgreSQL, the following properties are also available:

PostgreSQL position and internalPosition are one-based character positions when reported. If the server supplies no position, their accessors return an empty Optional instead of zero.

Starting in 4.9, PostgreSQL metadata also follows JDBC batch/wrapper causes and next-exception chains to find the driver's server diagnostics. A JDBC wrapper retains its primary SQLState when present and its vendor error code; a missing primary state can use the server state. Non-JDBC roots still expose empty metadata even when a nested cause has PostgreSQL diagnostics. Recovered DBMS text fields use the existing secure-parameter scrubber, including batch details; SQLState retains its operational value; original driver causes retain their original diagnostics for trusted inspection.

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, provided no enclosing transaction remains bound. Ordinary failures from traditional nested transactions follow the same rule, so a handled inner failure cannot newly interrupt enclosing savepoint cleanup. Final propagating boundary Errors restore their reachable interruption evidence even with an enclosing transaction. If your code handles an ordinary 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.

participate(...) also applies this ambient-transaction rule to failure-derived interruption. After the borrowed context is removed, a worker with no remaining transaction restores the flag, while a thread still running its owner does not newly publish it. Already-pending flags are not cleared, and actual interruptible connection-lock waits restore their flag immediately. A participation failure still marks the owner rollback-only. If you handle it while that owner remains bound, cancellation needs an explicit rethrow or re-interrupt; the library does not queue restoration for the eventual owner exit.

An interrupted thread, or a failure retaining interruption evidence, cannot admit another transaction retry, including when the backoff is zero. Cancellation is checked before invoking the retry policy even when an enclosing transaction prevented publication of the thread flag. 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.

A returned interrupted outcome restores interruption when no enclosing Pyranid transaction remains bound. Inside an enclosing transaction it does not newly set the flag; it preserves an already-pending flag and retains interruption in getFailure(). Rethrowing can unwind the enclosing boundary. Handling the returned failure can consume cancellation, and Pyranid does not queue deferred restoration at the outermost boundary. See Interruption in Returned Outcomes.

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.

Large-update and large-batch execution accept only direct explicit unsupported-method signals without conflicting evidence. General SQLExceptions do not authorize another execution through SQLState, nested capability causes or message text such as "unsupported". Batch execution evidence, even with a missing or unsupported-feature SQLState, also prevents fallback. This avoids turning a real failed batch into an empty success or executing changed work twice.

Previous
Notifications