Class Database
- Since:
- 1.0.0
- Author:
- Mark Allen
-
Nested Class Summary
Nested Classes -
Method Summary
Modifier and TypeMethodDescriptionGets a reference to the current transaction, if any.How should Pyranid bindInstantandOffsetDateTimeparameters when JDBC parameter metadata cannot identify whether the target isTIMESTAMPorTIMESTAMP WITH TIME ZONE?Gets the database type configured when this database was built.Gets the configured redactor used for non-secure parameters in diagnostics.Reports whether the configured database dialect and currently loadable runtime adapter expose the APIs required to attempt a notification-listening session.participate(@NonNull Transaction transaction, @NonNull ReturningTransactionalOperation<T> transactionalOperation) Performs an operation in the context of a pre-existing transaction, optionally returning a value.voidparticipate(@NonNull Transaction transaction, @NonNull TransactionalOperation transactionalOperation) Performs an operation in the context of a pre-existing transaction.voidperformHealthCheck(@NonNull Duration timeout) Performs a portable connectivity check using JDBCConnection.isValid(int).Creates a fluent builder for executing SQL.voidreadDatabaseMetaData(@NonNull DatabaseMetaDataReader databaseMetaDataReader) Exposes a temporary handle to JDBCDatabaseMetaData, which provides comprehensive vendor-specific information about this database as a whole.voidsendNotification(@NonNull String channel) Sends a transient database notification without specifying a payload.voidsendNotification(@NonNull String channel, @Nullable String payload) Sends a transient database notification.transaction(@NonNull ReturningTransactionalOperation<T> transactionalOperation) Performs an operation transactionally and optionally returns a value.voidtransaction(@NonNull TransactionalOperation transactionalOperation) Performs an operation transactionally.transaction(@NonNull TransactionOptions transactionOptions, @NonNull ReturningTransactionalOperation<T> transactionalOperation) Performs an operation transactionally with the given options, optionally returning a value.voidtransaction(@NonNull TransactionOptions transactionOptions, @NonNull TransactionalOperation transactionalOperation) Performs an operation transactionally with the given options.<T> @NonNull TransactionOutcome<T> transactionWithOutcome(@NonNull ReturningTransactionalOperation<T> operation) Performs one independent transaction attempt and retains the value returned normally by its callback.transactionWithOutcome(@NonNull TransactionalOperation operation) Performs one independent transaction attempt and returns its database outcome and invocation failure.<T> @NonNull TransactionOutcome<T> transactionWithOutcome(@NonNull TransactionOptions options, @NonNull ReturningTransactionalOperation<T> operation) Performs one independent transaction attempt, returning its final completion and attempted callback value.transactionWithOutcome(@NonNull TransactionOptions options, @NonNull TransactionalOperation operation) Performs one independent transaction attempt with explicit options, returning its result and ordinary failure.<T> @NonNull TransactionRetryResult<T> transactionWithRetry(@NonNull RetryPolicy retryPolicy, @NonNull ReturningTransactionalOperation<T> transactionalOperation) Performs an operation transactionally and optionally returns a value, retrying according to the given retry policy.transactionWithRetry(@NonNull RetryPolicy retryPolicy, @NonNull TransactionalOperation transactionalOperation) Performs an operation transactionally, retrying according to the given retry policy.<T> @NonNull TransactionRetryResult<T> transactionWithRetry(@NonNull RetryPolicy retryPolicy, @NonNull TransactionOptions transactionOptions, @NonNull ReturningTransactionalOperation<T> transactionalOperation) Performs an operation transactionally with the given options and optionally returns a value, retrying according to the given retry policy.transactionWithRetry(@NonNull RetryPolicy retryPolicy, @NonNull TransactionOptions transactionOptions, @NonNull TransactionalOperation transactionalOperation) Performs an operation transactionally with the given options, retrying according to the given retry policy.useRawConnection(@NonNull RawConnectionOperation<Connection, T> rawConnectionOperation) Performs raw JDBC work with a Pyranid-managedConnection.<C extends Connection, T>
@NonNull Optional<T> useRawConnection(@NonNull Class<C> connectionType, @NonNull RawConnectionOperation<? super C, T> rawConnectionOperation) Performs driver-specific raw JDBC work with a Pyranid-managed connection of the requested type.static @NonNull Database.Builderwith(@NonNull DataSource dataSource, @NonNull DatabaseType databaseType) Provides aDatabasebuilder for the givenDataSourceand database type.voidwithNotificationSession(@NonNull String channel, @NonNull NotificationSessionOperation operation) Performs an operation with one callback-scoped database-notification listener session for a single channel.voidwithNotificationSession(@NonNull Set<@NonNull String> channels, @NonNull NotificationSessionOperation operation) Performs an operation with one callback-scoped database-notification listener session.
-
Method Details
-
with
public static @NonNull Database.Builder with(@NonNull DataSource dataSource, @NonNull DatabaseType databaseType) Provides aDatabasebuilder for the givenDataSourceand database type.Neither creating the builder nor calling
Database.Builder.build()acquires a connection or inspects JDBC metadata.- Parameters:
dataSource- data source used to create theDatabasebuilderdatabaseType- database type to use; chooseDatabaseType.GENERICfor a database without dedicated handling- Returns:
- a
Databasebuilder - Since:
- 4.8.0
-
currentTransaction
Gets a reference to the current transaction, if any.- Returns:
- the current transaction
-
transaction
Performs an operation transactionally.The transaction will be automatically rolled back if an exception bubbles out of
transactionalOperation.On PostgreSQL and DuckDB, pre-commit validation can refuse commit even when the callback returns normally: the transaction may be aborted, or a required check may be unable to establish transaction usability. Pyranid attempts the normal rollback path and this method throws
DatabaseException; handling a statement failure inside the callback does not guarantee successful completion.Nested calls to
transaction(...)are independent transactions with independent JDBC connections; they do not automatically join an outer transaction. Useparticipate(Transaction, TransactionalOperation)to join an existing transaction explicitly. A transaction is scoped to theDataSourceinstance that created it; aDatabaseusing a differentDataSourcefails fast instead of joining it.- Parameters:
transactionalOperation- the operation to perform transactionally- Throws:
DatabaseException- if pre-commit validation detects an aborted transaction or cannot establish usability
-
transaction
public void transaction(@NonNull TransactionOptions transactionOptions, @NonNull TransactionalOperation transactionalOperation) Performs an operation transactionally with the given options.The transaction will be automatically rolled back if an exception bubbles out of
transactionalOperation.On PostgreSQL and DuckDB, pre-commit validation can refuse commit even when the callback returns normally: the transaction may be aborted, or a required check may be unable to establish transaction usability. Pyranid attempts the normal rollback path and this method throws
DatabaseException; handling a statement failure inside the callback does not guarantee successful completion.Nested calls to
transaction(...)are independent transactions with independent JDBC connections; they do not automatically join an outer transaction. Useparticipate(Transaction, TransactionalOperation)to join an existing transaction explicitly. A transaction is scoped to theDataSourceinstance that created it; aDatabaseusing a differentDataSourcefails fast instead of joining it.- Parameters:
transactionOptions- options to apply to the transactiontransactionalOperation- the operation to perform transactionally- Throws:
DatabaseException- if pre-commit validation detects an aborted transaction or cannot establish usability- Since:
- 4.2.0
-
transaction
public <T> @NonNull Optional<T> transaction(@NonNull ReturningTransactionalOperation<T> transactionalOperation) Performs an operation transactionally and optionally returns a value.The transaction will be automatically rolled back if an exception bubbles out of
transactionalOperation.On PostgreSQL and DuckDB, pre-commit validation can refuse commit even when the callback returns normally: the transaction may be aborted, or a required check may be unable to establish transaction usability. Pyranid attempts the normal rollback path and this method throws
DatabaseException; handling a statement failure inside the callback does not guarantee successful completion.Nested calls to
transaction(...)are independent transactions with independent JDBC connections; they do not automatically join an outer transaction. Useparticipate(Transaction, ReturningTransactionalOperation)to join an existing transaction explicitly. A transaction is scoped to theDataSourceinstance that created it; aDatabaseusing a differentDataSourcefails fast instead of joining it.- Type Parameters:
T- the type to be returned- Parameters:
transactionalOperation- the operation to perform transactionally- Returns:
- the result of the transactional operation
- Throws:
DatabaseException- if pre-commit validation detects an aborted transaction or cannot establish usability
-
transaction
public <T> @NonNull Optional<T> transaction(@NonNull TransactionOptions transactionOptions, @NonNull ReturningTransactionalOperation<T> transactionalOperation) Performs an operation transactionally with the given options, optionally returning a value.The transaction will be automatically rolled back if an exception bubbles out of
transactionalOperation.On PostgreSQL and DuckDB, pre-commit validation can refuse commit even when the callback returns normally: the transaction may be aborted, or a required check may be unable to establish transaction usability. Pyranid attempts the normal rollback path and this method throws
DatabaseException; handling a statement failure inside the callback does not guarantee successful completion.Ordinary failure-derived interruption is restored after cleanup and post-transaction hooks, only when no enclosing Pyranid transaction remains bound. Handling a nested failure does not defer cancellation to the outer boundary; callers that intend cancellation must rethrow or restore the flag. A final propagating
Errorrestores its reachable interruption evidence even with an enclosing transaction.Nested calls to
transaction(...)are independent transactions with independent JDBC connections; they do not automatically join an outer transaction. Useparticipate(Transaction, ReturningTransactionalOperation)to join an existing transaction explicitly. A transaction is scoped to theDataSourceinstance that created it; aDatabaseusing a differentDataSourcefails fast instead of joining it.- Type Parameters:
T- the type to be returned- Parameters:
transactionOptions- options to apply to the transactiontransactionalOperation- the operation to perform transactionally- Returns:
- the result of the transactional operation
- Throws:
DatabaseException- if pre-commit validation detects an aborted transaction or cannot establish usability- Since:
- 4.2.0
-
transactionWithOutcome
public @NonNull TransactionOutcome<Void> transactionWithOutcome(@NonNull TransactionalOperation operation) Performs one independent transaction attempt and returns its database outcome and invocation failure. Uses the default options and performs no automatic retry. A normal rollback-only callback has no failure; a committed transaction can retain a cleanup or hook failure.On PostgreSQL and DuckDB, pre-commit validation can refuse commit after a normal callback return if the transaction is aborted or a required check cannot establish usability. The refusal is retained in the outcome's failure. Acknowledged rollback reports
TransactionResult.ROLLED_BACK; failed rollback after application work could have executed reportsTransactionResult.IN_DOUBT. A finalErrorstill escapes.- Parameters:
operation- the transactional operation- Returns:
- the completed transaction outcome, with no attempted value
- Since:
- 4.9.0
-
transactionWithOutcome
public @NonNull TransactionOutcome<Void> transactionWithOutcome(@NonNull TransactionOptions options, @NonNull TransactionalOperation operation) Performs one independent transaction attempt with explicit options, returning its result and ordinary failure. Argument validation still throws normally; an operational acquisition/begin failure produces an outcome. Nested calls own independent connections. Useparticipate(...)to join a transaction explicitly.On PostgreSQL and DuckDB, pre-commit validation can refuse commit after a normal callback return if the transaction is aborted or a required check cannot establish usability. The refusal is retained in the outcome's failure. Acknowledged rollback reports
TransactionResult.ROLLED_BACK; failed rollback after application work could have executed reportsTransactionResult.IN_DOUBT. A finalErrorstill escapes.- Parameters:
options- transaction optionsoperation- the transactional operation- Returns:
- the completed transaction outcome, with no attempted value
- Since:
- 4.9.0
-
transactionWithOutcome
public <T> @NonNull TransactionOutcome<T> transactionWithOutcome(@NonNull ReturningTransactionalOperation<T> operation) Performs one independent transaction attempt and retains the value returned normally by its callback. The attempted value is available even if completion rolls back, becomes uncertain or fails after commit. Uses default options; see the options overload for failure and interruption semantics.On PostgreSQL and DuckDB, pre-commit validation can refuse commit after a normal callback return if the transaction is aborted or a required check cannot establish usability. The refusal is retained in the outcome's failure. Acknowledged rollback reports
TransactionResult.ROLLED_BACK; failed rollback after application work could have executed reportsTransactionResult.IN_DOUBT. A finalErrorstill escapes.- Type Parameters:
T- the callback value type- Parameters:
operation- the transactional operation- Returns:
- the completed transaction outcome and attempted callback value
- Since:
- 4.9.0
-
transactionWithOutcome
public <T> @NonNull TransactionOutcome<T> transactionWithOutcome(@NonNull TransactionOptions options, @NonNull ReturningTransactionalOperation<T> operation) Performs one independent transaction attempt, returning its final completion and attempted callback value.The callback runs once. Ordinary invocation failures, including programming errors, are retained instead of thrown, with the traditional API's wrapping, causes and suppressed failures. A final
Errorescapes after best-effort completion and observation. Null arguments and failures before a boundary exists still throw. An empty or accidentally null callback Optional is normalized to empty; a callback that throws has no value.Result, value and failure describe separate facts. Rollback-only completion can retain a value without a failure, and successful commit can retain a cleanup or hook failure. The configured completion observer sees the same completion after cleanup and hooks. Its own failure remains contained.
With no enclosing transaction, interruption from a returned failure is restored before return. With an enclosing transaction, Pyranid preserves an already-pending flag but does not newly publish interruption from a handled outcome; that evidence remains in its failure. A propagating final Error follows the throwing API's restoration.
This method never retries and does not join an ambient transaction. Do not combine it with retries by nesting it inside
transactionWithRetry(...): that creates an independent transaction. An uncertain result needs application reconciliation under the original durable operation identity; it does not authorize replay.On PostgreSQL and DuckDB, pre-commit validation can refuse commit after a normal callback return if the transaction is aborted or a required check cannot establish usability. The refusal is retained in the outcome's failure. Acknowledged rollback reports
TransactionResult.ROLLED_BACK; failed rollback after application work could have executed reportsTransactionResult.IN_DOUBT. A finalErrorstill escapes.- Type Parameters:
T- the callback value type- Parameters:
options- transaction optionsoperation- the transactional operation- Returns:
- the completed transaction outcome and attempted callback value
- Since:
- 4.9.0
-
transactionWithRetry
public @NonNull TransactionRetryResult<Void> transactionWithRetry(@NonNull RetryPolicy retryPolicy, @NonNull TransactionalOperation transactionalOperation) Performs an operation transactionally, retrying according to the given retry policy.The entire transaction closure may run more than once. Keep non-idempotent external side effects outside the closure unless they are safe to repeat.
For a
DatabaseException, Pyranid consults the retry policy only when replay is known to be safe. Body failures require acknowledged rollback and no retained committed, in-doubt or cancellation evidence. A failure before a physical transaction becomes available to application work can also be eligible even if best-effort rollback of that discarded begin candidate fails. The retry policy still decides whether an eligible failure should be retried.A physical commit failure is eligible only when the original driver's exception has a direct, readable SQLState
40001, the dialect classifies it as a serialization failure, its cause/next/suppressed evidence is consistent and readable, and the follow-up rollback succeeds. Transport or causal I/O failures, missing or different subordinate SQLStates, and vendor-only diagnostics such as Oracle8177or SQL Server3960do not establish that proof. The tested DuckDB driver supplies no SQLState for commit conflicts, so those outcomes remainTransactionResult.IN_DOUBTand are not retried. Other uncertain commit outcomes, failed rollback after application work could execute, and failures after successful commit are never replayed.On PostgreSQL and DuckDB, pre-commit validation can refuse completion after a normal callback return. The refusal can inherit classification from an earlier handled failure; after acknowledged rollback, an accepting retry policy can therefore rerun that normally returned callback. Keep the entire callback safe to replay.
A savepoint-scope ownership conflict at completion is never replayed, with or without a successful rollback: the guard raises an
IllegalStateException, not aDatabaseException, so the conflict leaves this method without reaching the retry policy. What a successful rollback changes is the attempt's outcome evidence; the conflict no longer records an indeterminate outcome, so a conflict raised and handled by an independent transaction inside the closure no longer fences a retry of a later failure.Unlike
transaction(TransactionalOperation)and related transaction methods, retrying methods returnTransactionRetryResultso callers can inspect failures that were recovered before success.This method rejects a call when the innermost ambient transaction on the calling thread uses the same
DataSourceinstance, including across differentDatabasewrappers. Only that innermost transaction is checked. If a transaction on another source hides an older matching transaction, this method starts an independent retrying transaction; retries do not restart either surrounding transaction.- Parameters:
retryPolicy- retry policy to applytransactionalOperation- the operation to perform transactionally- Returns:
- retry result containing any failures retried before success
- Since:
- 4.4.0
-
transactionWithRetry
public @NonNull TransactionRetryResult<Void> transactionWithRetry(@NonNull RetryPolicy retryPolicy, @NonNull TransactionOptions transactionOptions, @NonNull TransactionalOperation transactionalOperation) Performs an operation transactionally with the given options, retrying according to the given retry policy.The entire transaction closure may run more than once. Keep non-idempotent external side effects outside the closure unless they are safe to repeat.
For a
DatabaseException, Pyranid consults the retry policy only when replay is known to be safe. Body failures require acknowledged rollback and no retained committed, in-doubt or cancellation evidence. A failure before a physical transaction becomes available to application work can also be eligible even if best-effort rollback of that discarded begin candidate fails. The retry policy still decides whether an eligible failure should be retried.A physical commit failure is eligible only when the original driver's exception has a direct, readable SQLState
40001, the dialect classifies it as a serialization failure, its cause/next/suppressed evidence is consistent and readable, and the follow-up rollback succeeds. Transport or causal I/O failures, missing or different subordinate SQLStates, and vendor-only diagnostics such as Oracle8177or SQL Server3960do not establish that proof. The tested DuckDB driver supplies no SQLState for commit conflicts, so those outcomes remainTransactionResult.IN_DOUBTand are not retried. Other uncertain commit outcomes, failed rollback after application work could execute, and failures after successful commit are never replayed.On PostgreSQL and DuckDB, pre-commit validation can refuse completion after a normal callback return. The refusal can inherit classification from an earlier handled failure; after acknowledged rollback, an accepting retry policy can therefore rerun that normally returned callback. Keep the entire callback safe to replay.
A savepoint-scope ownership conflict at completion is never replayed, with or without a successful rollback: the guard raises an
IllegalStateException, not aDatabaseException, so the conflict leaves this method without reaching the retry policy. What a successful rollback changes is the attempt's outcome evidence; the conflict no longer records an indeterminate outcome, so a conflict raised and handled by an independent transaction inside the closure no longer fences a retry of a later failure.Unlike
transaction(TransactionOptions, TransactionalOperation)and related transaction methods, retrying methods returnTransactionRetryResultso callers can inspect failures that were recovered before success.This method rejects a call when the innermost ambient transaction on the calling thread uses the same
DataSourceinstance, including across differentDatabasewrappers. Only that innermost transaction is checked. If a transaction on another source hides an older matching transaction, this method starts an independent retrying transaction; retries do not restart either surrounding transaction.- Parameters:
retryPolicy- retry policy to applytransactionOptions- options to apply to each transaction attempttransactionalOperation- the operation to perform transactionally- Returns:
- retry result containing any failures retried before success
- Since:
- 4.4.0
-
transactionWithRetry
public <T> @NonNull TransactionRetryResult<T> transactionWithRetry(@NonNull RetryPolicy retryPolicy, @NonNull ReturningTransactionalOperation<T> transactionalOperation) Performs an operation transactionally and optionally returns a value, retrying according to the given retry policy.The entire transaction closure may run more than once. Keep non-idempotent external side effects outside the closure unless they are safe to repeat.
For a
DatabaseException, Pyranid consults the retry policy only when replay is known to be safe. Body failures require acknowledged rollback and no retained committed, in-doubt or cancellation evidence. A failure before a physical transaction becomes available to application work can also be eligible even if best-effort rollback of that discarded begin candidate fails. The retry policy still decides whether an eligible failure should be retried.A physical commit failure is eligible only when the original driver's exception has a direct, readable SQLState
40001, the dialect classifies it as a serialization failure, its cause/next/suppressed evidence is consistent and readable, and the follow-up rollback succeeds. Transport or causal I/O failures, missing or different subordinate SQLStates, and vendor-only diagnostics such as Oracle8177or SQL Server3960do not establish that proof. The tested DuckDB driver supplies no SQLState for commit conflicts, so those outcomes remainTransactionResult.IN_DOUBTand are not retried. Other uncertain commit outcomes, failed rollback after application work could execute, and failures after successful commit are never replayed.On PostgreSQL and DuckDB, pre-commit validation can refuse completion after a normal callback return. The refusal can inherit classification from an earlier handled failure; after acknowledged rollback, an accepting retry policy can therefore rerun that normally returned callback. Keep the entire callback safe to replay.
A savepoint-scope ownership conflict at completion is never replayed, with or without a successful rollback: the guard raises an
IllegalStateException, not aDatabaseException, so the conflict leaves this method without reaching the retry policy. What a successful rollback changes is the attempt's outcome evidence; the conflict no longer records an indeterminate outcome, so a conflict raised and handled by an independent transaction inside the closure no longer fences a retry of a later failure.Unlike
transaction(ReturningTransactionalOperation)and related transaction methods, retrying methods returnTransactionRetryResultso callers can inspect failures that were recovered before success.This method rejects a call when the innermost ambient transaction on the calling thread uses the same
DataSourceinstance, including across differentDatabasewrappers. Only that innermost transaction is checked. If a transaction on another source hides an older matching transaction, this method starts an independent retrying transaction; retries do not restart either surrounding transaction.- Type Parameters:
T- the type to be returned- Parameters:
retryPolicy- retry policy to applytransactionalOperation- the operation to perform transactionally- Returns:
- retry result containing the successful transaction value and any failures retried before success
- Since:
- 4.4.0
-
transactionWithRetry
public <T> @NonNull TransactionRetryResult<T> transactionWithRetry(@NonNull RetryPolicy retryPolicy, @NonNull TransactionOptions transactionOptions, @NonNull ReturningTransactionalOperation<T> transactionalOperation) Performs an operation transactionally with the given options and optionally returns a value, retrying according to the given retry policy.The entire transaction closure may run more than once. Keep non-idempotent external side effects outside the closure unless they are safe to repeat.
For a
DatabaseException, Pyranid consults the retry policy only when replay is known to be safe. Body failures require acknowledged rollback and no retained committed, in-doubt or cancellation evidence. A failure before a physical transaction becomes available to application work can also be eligible even if best-effort rollback of that discarded begin candidate fails. The retry policy still decides whether an eligible failure should be retried.A physical commit failure is eligible only when the original driver's exception has a direct, readable SQLState
40001, the dialect classifies it as a serialization failure, its cause/next/suppressed evidence is consistent and readable, and the follow-up rollback succeeds. Transport or causal I/O failures, missing or different subordinate SQLStates, and vendor-only diagnostics such as Oracle8177or SQL Server3960do not establish that proof. The tested DuckDB driver supplies no SQLState for commit conflicts, so those outcomes remainTransactionResult.IN_DOUBTand are not retried. Other uncertain commit outcomes, failed rollback after application work could execute, and failures after successful commit are never replayed.On PostgreSQL and DuckDB, pre-commit validation can refuse completion after a normal callback return. The refusal can inherit classification from an earlier handled failure; after acknowledged rollback, an accepting retry policy can therefore rerun that normally returned callback. Keep the entire callback safe to replay.
A savepoint-scope ownership conflict at completion is never replayed, with or without a successful rollback: the guard raises an
IllegalStateException, not aDatabaseException, so the conflict leaves this method without reaching the retry policy. What a successful rollback changes is the attempt's outcome evidence; the conflict no longer records an indeterminate outcome, so a conflict raised and handled by an independent transaction inside the closure no longer fences a retry of a later failure.Unlike
transaction(TransactionOptions, ReturningTransactionalOperation)and related transaction methods, retrying methods returnTransactionRetryResultso callers can inspect failures that were recovered before success.This method rejects a call when the innermost ambient transaction on the calling thread uses the same
DataSourceinstance, including across differentDatabasewrappers. Only that innermost transaction is checked. If a transaction on another source hides an older matching transaction, this method starts an independent retrying transaction; retries do not restart either surrounding transaction.- Type Parameters:
T- the type to be returned- Parameters:
retryPolicy- retry policy to applytransactionOptions- options to apply to each transaction attempttransactionalOperation- the operation to perform transactionally- Returns:
- retry result containing the successful transaction value and any failures retried before success
- Since:
- 4.4.0
-
participate
public void participate(@NonNull Transaction transaction, @NonNull TransactionalOperation transactionalOperation) Performs an operation in the context of a pre-existing transaction.No commit or rollback on the transaction will occur when
transactionalOperationcompletes.However, if an exception bubbles out of
transactionalOperation, the transaction will be marked as rollback-only.The transaction must have been created by this
Database, or by anotherDatabaseusing the sameDataSourceinstance.If this thread is interrupted while waiting for another participant to release the transaction connection, Pyranid restores the interrupt flag and throws
DatabaseException.Failure-derived interruption from the callback is restored after removing this participation context only when no Pyranid transaction remains bound on the calling thread. Same-thread participation inside its owner does not newly publish that flag; already-pending flags are preserved. If a caller handles the failure inside the owner and intends cancellation, it must rethrow or restore the flag explicitly. Handled failures do not queue later interruption restoration; the owner is still marked rollback-only.
- Parameters:
transaction- the transaction in which to participatetransactionalOperation- the operation that should participate in the transaction
-
participate
public <T> @NonNull Optional<T> participate(@NonNull Transaction transaction, @NonNull ReturningTransactionalOperation<T> transactionalOperation) Performs an operation in the context of a pre-existing transaction, optionally returning a value.No commit or rollback on the transaction will occur when
transactionalOperationcompletes.However, if an exception bubbles out of
transactionalOperation, the transaction will be marked as rollback-only.The transaction must have been created by this
Database, or by anotherDatabaseusing the sameDataSourceinstance.If this thread is interrupted while waiting for another participant to release the transaction connection, Pyranid restores the interrupt flag and throws
DatabaseException.Failure-derived interruption from the callback is restored after removing this participation context only when no Pyranid transaction remains bound on the calling thread. Same-thread participation inside its owner does not newly publish that flag; already-pending flags are preserved. If a caller handles the failure inside the owner and intends cancellation, it must rethrow or restore the flag explicitly. Handled failures do not queue later interruption restoration; the owner is still marked rollback-only.
- Type Parameters:
T- the type to be returned- Parameters:
transaction- the transaction in which to participatetransactionalOperation- the operation that should participate in the transaction- Returns:
- the result of the transactional operation
-
query
Creates a fluent builder for executing SQL.Named parameters use the
:paramNamesyntax and are bound viaQuery.bind(String, Object). Positional parameters via?are not supported. Pyranid ignores parameter-looking text inside SQL string literals, quoted identifiers, comments, PostgreSQL dollar-quoted strings, and SQL Server-style bracket-quoted identifiers. PostgreSQL JSONB/hstore?,?|, and?&operators are supported; when running againstDatabaseType.POSTGRESQL, Pyranid emits pgjdbc's escaped??form automatically. Unterminated quotes and comments fail fast.Example:
Optional<Employee> employee = database.query("SELECT * FROM employee WHERE id = :id") .bind("id", 42) .fetchObject(Employee.class);- Parameters:
sql- SQL containing:paramNameplaceholders- Returns:
- a fluent builder for binding parameters and executing
- Since:
- 4.0.0
-
performHealthCheck
Performs a portable connectivity check using JDBCConnection.isValid(int).This method borrows a fresh connection from this database's
DataSource, callsConnection.isValid(int), and closes the connection before returning. It does not participate in an active Pyranid transaction, if one exists.JDBC accepts timeout values in whole seconds. Positive sub-second durations are rounded up to one second;
Duration.ZEROpasses a timeout of0to the driver.If the failure this method propagates carries evidence of thread interruption, Pyranid restores the interrupt flag before throwing, as long as no Pyranid transaction is open on the calling thread. Inside a transaction this method restores nothing, and nothing restores the flag for a failure the caller handles there. A caller that handles one of these failures inside a transaction and wants to act on the cancellation must call
Thread.interrupt()itself.- Parameters:
timeout- maximum time to wait for driver validation- Throws:
IllegalArgumentException- iftimeoutis negative or too large for JDBC's integer-second timeoutDatabaseException- if connection acquisition fails, validation throws, or the driver reports the connection is not valid- Since:
- 4.2.0
-
readDatabaseMetaData
Exposes a temporary handle to JDBCDatabaseMetaData, which provides comprehensive vendor-specific information about this database as a whole.This method acquires
DatabaseMetaDataon its own newly-borrowed connection, which it manages internally.It does not participate in the active transaction, if one exists.
The connection is closed as soon as
DatabaseMetaDataReader.read(DatabaseMetaData)completes.See
DatabaseMetaDataJavadoc for details.If the failure this method propagates carries evidence of thread interruption, Pyranid restores the interrupt flag before throwing, as long as no Pyranid transaction is open on the calling thread. Inside a transaction this method restores nothing, and nothing restores the flag for a failure the caller handles there. A caller that handles one of these failures inside a transaction and wants to act on the cancellation must call
Thread.interrupt()itself. -
useRawConnection
public <T> @NonNull Optional<T> useRawConnection(@NonNull RawConnectionOperation<Connection, T> rawConnectionOperation) Performs raw JDBC work with a Pyranid-managedConnection.If called inside a Pyranid transaction, this operation uses the transaction's connection and participates in that transaction. Otherwise, Pyranid borrows a connection for the duration of the callback and closes it afterwards.
The
Connectionpassed torawConnectionOperationis a guarded handle. Normal JDBC operations are delegated to the underlying driver connection, but lifecycle, transaction-management, and connection-wide state methods such asConnection.close(),Connection.commit(),Connection.rollback(),Connection.setAutoCommit(boolean),Connection.setCatalog(String),Connection.setSchema(String), andConnection.setNetworkTimeout(java.util.concurrent.Executor, int)throwIllegalStateException. Use Pyranid transaction APIs instead.Wrapper.unwrap(Class)may return a guarded, callback-scoped proxy for a vendor interface, but never a castable physicalConnection; the proxy blocks lifecycle methods and expires with the callback. JDBC objects created from this handle are also guarded:Statement.getConnection()andDatabaseMetaData.getConnection()return the Pyranid-managed handle, andResultSet.getStatement()returns a guarded statement. Guarded statements, resultsets, and metadata refuse driver-specificunwrap(...)calls that could expose the driver's underlying connection.The connection handle is valid only for the duration of the callback. Do not close it, retain it, or use it after this method returns.
If the failure this method propagates carries evidence of thread interruption, Pyranid restores the interrupt flag before throwing, as long as no Pyranid transaction is open on the calling thread. Inside a transaction this method restores nothing, and nothing restores the flag for a failure the caller handles there. A caller that handles one of these failures inside a transaction and wants to act on the cancellation must call
Thread.interrupt()itself.- Type Parameters:
T- the type to be returned- Parameters:
rawConnectionOperation- the raw JDBC operation to perform- Returns:
- the operation result
- Throws:
DatabaseException- if connection acquisition, callback execution, or cleanup fails- Since:
- 4.2.0
-
useRawConnection
public <C extends Connection, T> @NonNull Optional<T> useRawConnection(@NonNull Class<C> connectionType, @NonNull RawConnectionOperation<? super C, T> rawConnectionOperation) Performs driver-specific raw JDBC work with a Pyranid-managed connection of the requested type.If called inside a Pyranid transaction, this operation uses the transaction's connection. Standard JDBC work participates in that transaction; driver-extension APIs may impose additional transaction-start or lifecycle rules. Otherwise, Pyranid borrows a connection for the duration of the callback and closes it afterwards.
If the managed connection is already an instance of
connectionType, it is passed directly torawConnectionOperation. Otherwise, Pyranid obtains the requested driver connection throughWrapper.unwrap(Class). Failure to obtain the requested type results in aDatabaseException.Unlike
useRawConnection(RawConnectionOperation), the connection supplied by this overload is unguarded. This is necessary for concrete driver APIs, but it also means Pyranid cannot prevent operations that interfere with its connection and transaction management. Guarding is selected by the overload, so the connection remains unguarded whenconnectionTypeisConnection.class. Do not close the connection, retain it, callConnection.commit(),Connection.rollback(), orConnection.setAutoCommit(boolean), or mutate connection-wide state such as schema, catalog, client info, holdability, type map, or network timeout.The connection and every object obtained from it are valid only for the duration of the callback. Statements, result sets, appenders, readers, and other derived resources must be closed before this method returns. Retaining or using any of these objects after the callback returns has undefined behavior.
If the failure this method propagates carries evidence of thread interruption, Pyranid restores the interrupt flag before throwing, as long as no Pyranid transaction is open on the calling thread. Inside a transaction this method restores nothing, and nothing restores the flag for a failure the caller handles there. A caller that handles one of these failures inside a transaction and wants to act on the cancellation must call
Thread.interrupt()itself.- Type Parameters:
C- the requested connection typeT- the type to be returned- Parameters:
connectionType- driver connection class or interface to exposerawConnectionOperation- the driver-specific raw JDBC operation to perform- Returns:
- the operation result
- Throws:
DatabaseException- if connection acquisition, unwrapping, callback execution, or cleanup fails- Since:
- 4.7.0
-
withNotificationSession
public void withNotificationSession(@NonNull Set<@NonNull String> channels, @NonNull NotificationSessionOperation operation) throws InterruptedException Performs an operation with one callback-scoped database-notification listener session.This method is synchronous and blocking. It acquires at most one listener connection from this
Database's configuredDataSource, registers every requested channel, invokesoperationat most once, expires the suppliedNotificationSession, and completes cleanup before returning or throwing. It never reconnects.The configured source must preserve one physical backend session for the entire checkout. For PostgreSQL, direct connections and session pooling are suitable. Using PgBouncer transaction or statement pooling as the listener source is unsupported: registration can appear to succeed before backend-session affinity is lost and notification delivery silently stops. Pyranid does not inspect or validate proxy topology. Applications whose ordinary source cannot provide the required affinity should construct a separate
Databaseover a suitable listener source and invoke this method on that instance.Notifications are lossy hints. Durable applications should normally reconcile authoritative state as the first callback action. The operation may use ordinary database methods, but those methods acquire or select their connection normally and never reuse the listener connection. Pyranid transaction entry is interrupt-sensitive; when a receive returns a batch with a racing interrupt, temporarily clear and remember the flag during bounded reconciliation and restore it afterward as described by
NotificationSession.awaitNotifications(Duration).A terminal receive failure is retained by the session and rethrown after cleanup even if
operationcatches it and returns. A retained transportErrorpropagates as that exact, unwrapped instance. If the callback instead throws a distinctError, that callback error remains primary and the retained transport failure is suppressed beneath it.- Parameters:
channels- fixed, nonempty set of nonblank channels to registeroperation- operation to invoke after every channel has been registered- Throws:
NullPointerException- ifchannels, a channel, oroperationis nullIllegalArgumentException- if the set is empty or a channel violates common or backend-specific limitsIllegalStateException- if any Pyranid transaction is active on the calling threadInterruptedException- if cooperative interruption wins after any required cleanupUnsupportedOperationException- if notification listening is unavailable through the database dialect or runtime driver, or is unsupported or disabled for the current server version or configurationDatabaseException- if connection acquisition, setup, receive, callback execution, or cleanup fails- Since:
- 4.6.0
-
withNotificationSession
public void withNotificationSession(@NonNull String channel, @NonNull NotificationSessionOperation operation) throws InterruptedException Performs an operation with one callback-scoped database-notification listener session for a single channel.This is the single-channel convenience form of
withNotificationSession(Set, NotificationSessionOperation). The listener connection comes from thisDatabase's configuredDataSource, which must preserve physical backend-session affinity for the entire checkout. For PostgreSQL, using PgBouncer transaction or statement pooling as the listener source is unsupported: registration can appear to succeed before affinity is lost and delivery silently stops. Pyranid does not inspect or validate proxy topology.A terminal receive failure is retained and rethrown after cleanup even if
operationcatches it and returns. A retained transportErrorpropagates as the exact, unwrapped instance unless a distinct callbackErrortakes precedence as described by the set-based overload.- Parameters:
channel- nonblank channel to registeroperation- operation to invoke after the channel has been registered- Throws:
NullPointerException- ifchanneloroperationis nullIllegalArgumentException- if the channel violates common or backend-specific limitsIllegalStateException- if any Pyranid transaction is active on the calling threadInterruptedException- if cooperative interruption wins after any required cleanupUnsupportedOperationException- if notification listening is unavailable through the database dialect or runtime driver, or is unsupported or disabled for the current server version or configurationDatabaseException- if connection acquisition, setup, receive, callback execution, or cleanup fails- Since:
- 4.6.0
-
sendNotification
Sends a transient database notification without specifying a payload.Sending follows ordinary Pyranid statement and transaction selection. On PostgreSQL, a send inside a Pyranid transaction becomes visible only if that transaction commits. Payload representation is database-specific; PostgreSQL converts the resulting null payload to the empty string.
- Parameters:
channel- nonblank notification channel- Throws:
NullPointerException- ifchannelis nullIllegalArgumentException- if the channel violates common or backend-specific limitsUnsupportedOperationException- if notification sending is unavailable through the database dialect, or is unsupported or disabled for the current server version or configurationDatabaseException- if the send fails- Since:
- 4.6.0
-
sendNotification
Sends a transient database notification.Sending follows ordinary Pyranid statement and transaction selection, including connection ownership, parameter binding and redaction, statement logging, timeout configuration, and metrics. Payload nullability and null/empty-string handling are database-specific; Pyranid performs no generic normalization.
On PostgreSQL this executes bound
pg_catalog.pg_notify(?, ?)SQL. PostgreSQL converts a null payload to the empty string. Delivery occurs only after commit and is discarded by rollback; notification delivery itself remains non-durable and may be coalesced.- Parameters:
channel- nonblank notification channelpayload- notification payload, possibly null or empty- Throws:
NullPointerException- ifchannelis nullIllegalArgumentException- if the channel or payload violates common or backend-specific limitsUnsupportedOperationException- if notification sending is unavailable through the database dialect, or is unsupported or disabled for the current server version or configurationDatabaseException- if the send fails- Since:
- 4.6.0
-
isNotificationListeningSupported
Reports whether the configured database dialect and currently loadable runtime adapter expose the APIs required to attempt a notification-listening session.This method uses the configured database type without acquiring a connection or inspecting JDBC metadata. It does not verify whether notifications are enabled or supported by the current server version or configuration, acquire a listener session, inspect pool or proxy mode, prove backend-session affinity, unwrap a physical listener connection, or emit notification-session lifecycle metrics.
- Returns:
- true if notification listening can be attempted with the current dialect and runtime
- Since:
- 4.6.0
-
getDatabaseType
Gets the database type configured when this database was built.- Returns:
- the configured database type
- Since:
- 3.0.0
-
getTimeZone
- Since:
- 3.0.0
-
getAmbiguousTimestampBindingStrategy
How should Pyranid bindInstantandOffsetDateTimeparameters when JDBC parameter metadata cannot identify whether the target isTIMESTAMPorTIMESTAMP WITH TIME ZONE?- Returns:
- behavior to use when timestamp target metadata is unavailable or non-identifying
- Since:
- 4.2.0
-
getParameterRedactor
Gets the configured redactor used for non-secure parameters in diagnostics.- Returns:
- the configured parameter redactor
- Since:
- 4.4.0
-
getMetricsCollector
-