001/*
002 * Copyright 2015-2022 Transmogrify LLC, 2022-2026 Revetware LLC.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package com.pyranid;
018
019import org.jspecify.annotations.NonNull;
020import org.jspecify.annotations.Nullable;
021
022import javax.annotation.concurrent.NotThreadSafe;
023import javax.annotation.concurrent.ThreadSafe;
024import javax.sql.DataSource;
025import java.sql.Connection;
026import java.sql.DatabaseMetaData;
027import java.sql.PreparedStatement;
028import java.sql.ResultSet;
029import java.sql.SQLException;
030import java.time.Duration;
031import java.time.ZoneId;
032import java.util.Arrays;
033import java.util.List;
034import java.util.Optional;
035import java.util.Queue;
036import java.util.Set;
037import java.util.concurrent.atomic.AtomicReference;
038import java.util.concurrent.atomic.AtomicLong;
039import java.util.concurrent.locks.ReentrantLock;
040import java.util.function.UnaryOperator;
041import java.util.regex.Pattern;
042
043import static java.lang.String.format;
044import static java.lang.System.nanoTime;
045import static java.util.Objects.requireNonNull;
046
047/**
048 * Main class for performing database access operations.
049 *
050 * @author <a href="https://www.revetkn.com">Mark Allen</a>
051 * @since 1.0.0
052 */
053@ThreadSafe
054public final class Database {
055        private static final int DEFAULT_PARSED_SQL_CACHE_CAPACITY = 1024;
056        private static final int MAX_DIAGNOSTIC_MESSAGE_LENGTH = 1024;
057        private static final int MAX_DIAGNOSTIC_PARAMETER_LENGTH = 256;
058        private static final int MAX_DIAGNOSTIC_PARAMETERS_LENGTH = 2048;
059        private static final int MAX_DIAGNOSTIC_SQL_LENGTH = 2048;
060        @NonNull
061        private static final String TRUNCATED_SUFFIX = "... (truncated)";
062        @NonNull
063        private static final Pattern DIAGNOSTIC_WHITESPACE_PATTERN = Pattern.compile("\\s+");
064
065        @NonNull
066        private final DataSource dataSource;
067        @NonNull
068        private final DatabaseType databaseType;
069        @NonNull
070        private final DatabaseDialect databaseDialect;
071        @NonNull
072        private final ZoneId timeZone;
073        @NonNull
074        private final AmbiguousTimestampBindingStrategy ambiguousTimestampBindingStrategy;
075        @NonNull
076        private final InstanceProvider instanceProvider;
077        @NonNull
078        private final ResultSetMapper resultSetMapper;
079        @NonNull
080        private final ParameterRedactor parameterRedactor;
081        @NonNull
082        private final MetricsCollectorDispatcher metricsCollectorDispatcher;
083        @NonNull
084        private final TransactionCoordinator transactions;
085        @Nullable
086        private final Duration queryTimeout;
087        @Nullable
088        private final Integer fetchSize;
089        @Nullable
090        private final Integer maxRows;
091        @NonNull
092        private final SqlCompiler sqlCompiler;
093        @NonNull
094        private final AtomicLong defaultIdGenerator;
095
096        @NonNull
097        private final StatementExecutor statementExecutor;
098
099        private Database(@NonNull Builder builder) {
100                requireNonNull(builder);
101
102                this.dataSource = requireNonNull(builder.dataSource);
103                this.databaseType = builder.databaseType;
104                this.databaseDialect = this.databaseType.dialect();
105                this.timeZone = builder.timeZone == null ? ZoneId.systemDefault() : builder.timeZone;
106                this.ambiguousTimestampBindingStrategy = builder.ambiguousTimestampBindingStrategy == null
107                                ? AmbiguousTimestampBindingStrategy.TIMESTAMP_WITH_TIME_ZONE
108                                : builder.ambiguousTimestampBindingStrategy;
109                this.instanceProvider = builder.instanceProvider == null ? new InstanceProvider() {} : builder.instanceProvider;
110                PreparedStatementBinder preparedStatementBinder = builder.preparedStatementBinder == null ? PreparedStatementBinder.withDefaultConfiguration() : builder.preparedStatementBinder;
111                this.resultSetMapper = builder.resultSetMapper == null ? ResultSetMapper.withDefaultConfiguration() : builder.resultSetMapper;
112                StatementLogger statementLogger = builder.statementLogger == null ? (statementLog) -> {} : builder.statementLogger;
113                this.parameterRedactor = builder.parameterRedactor == null ? ParameterRedactor.none() : builder.parameterRedactor;
114                this.metricsCollectorDispatcher = new MetricsCollectorDispatcher(builder.metricsCollector);
115                this.transactions = new TransactionCoordinator(this.dataSource, this.metricsCollectorDispatcher,
116                                this.databaseType);
117                this.queryTimeout = validateQueryTimeout(builder.queryTimeout);
118                this.fetchSize = validateNonNegativeStatementSetting("fetchSize", builder.fetchSize);
119                this.maxRows = validateNonNegativeStatementSetting("maxRows", builder.maxRows);
120                if (builder.parsedSqlCacheCapacity != null && builder.parsedSqlCacheCapacity < 0)
121                        throw new IllegalArgumentException("parsedSqlCacheCapacity must be >= 0");
122
123                int parsedSqlCacheCapacity = builder.parsedSqlCacheCapacity == null
124                                ? DEFAULT_PARSED_SQL_CACHE_CAPACITY
125                                : builder.parsedSqlCacheCapacity;
126                this.sqlCompiler = new SqlCompiler(parsedSqlCacheCapacity);
127                this.defaultIdGenerator = new AtomicLong();
128                this.statementExecutor = new StatementExecutor(this, this.instanceProvider, this.resultSetMapper, preparedStatementBinder,
129                                statementLogger, this.metricsCollectorDispatcher, new StatementConnections(this.dataSource,
130                                this::currentTransactionForDatabaseOperation, connection -> closeConnection(connection, this.databaseDialect),
131                                this.databaseType, this.databaseDialect));
132        }
133
134        /**
135         * Provides a {@link Database} builder for the given {@link DataSource} and database type.
136         * <p>
137         * Neither creating the builder nor calling {@link Builder#build()} acquires a connection or inspects JDBC metadata.
138         *
139         * @param dataSource data source used to create the {@link Database} builder
140         * @param databaseType database type to use; choose {@link DatabaseType#GENERIC} for a database without dedicated handling
141         * @return a {@link Database} builder
142         * @since 4.8.0
143         */
144        @NonNull
145        public static Builder with(@NonNull DataSource dataSource, @NonNull DatabaseType databaseType) {
146                return new Builder(dataSource, databaseType);
147        }
148
149        /**
150         * Gets a reference to the current transaction, if any.
151         *
152         * @return the current transaction
153         */
154        @NonNull
155        public Optional<Transaction> currentTransaction() {
156                return this.transactions.currentTransaction();
157        }
158
159        @NonNull
160        Optional<Transaction> currentTransactionForDatabaseOperation() {
161                return this.transactions.currentTransactionForDatabaseOperation();
162        }
163
164        static boolean hasAmbientTransaction() {
165                return TransactionCoordinator.hasAmbientTransaction();
166        }
167
168        /**
169         * Performs an operation transactionally.
170         * <p>
171         * The transaction will be automatically rolled back if an exception bubbles out of {@code transactionalOperation}.
172         * <p>
173         * On PostgreSQL and DuckDB, pre-commit validation can refuse commit even when the callback returns normally:
174         * the transaction may be aborted, or a required check may be unable to establish transaction usability.
175         * Pyranid attempts the normal rollback path and this method throws {@link DatabaseException}; handling a
176         * statement failure inside the callback does not guarantee successful completion.
177         * <p>
178         * Nested calls to {@code transaction(...)} are independent transactions with independent JDBC connections; they do
179         * not automatically join an outer transaction. Use {@link #participate(Transaction, TransactionalOperation)} to join an
180         * existing transaction explicitly. A transaction is scoped to the {@link DataSource} instance that created it; a
181         * {@link Database} using a different {@link DataSource} fails fast instead of joining it.
182         *
183         * @param transactionalOperation the operation to perform transactionally
184         * @throws DatabaseException if pre-commit validation detects an aborted transaction or cannot establish usability
185         */
186        public void transaction(@NonNull TransactionalOperation transactionalOperation) {
187                requireNonNull(transactionalOperation);
188
189                transaction(() -> {
190                        transactionalOperation.perform();
191                        return Optional.empty();
192                });
193        }
194
195        /**
196         * Performs an operation transactionally with the given options.
197         * <p>
198         * The transaction will be automatically rolled back if an exception bubbles out of {@code transactionalOperation}.
199         * <p>
200         * On PostgreSQL and DuckDB, pre-commit validation can refuse commit even when the callback returns normally:
201         * the transaction may be aborted, or a required check may be unable to establish transaction usability.
202         * Pyranid attempts the normal rollback path and this method throws {@link DatabaseException}; handling a
203         * statement failure inside the callback does not guarantee successful completion.
204         * <p>
205         * Nested calls to {@code transaction(...)} are independent transactions with independent JDBC connections; they do
206         * not automatically join an outer transaction. Use {@link #participate(Transaction, TransactionalOperation)} to join an
207         * existing transaction explicitly. A transaction is scoped to the {@link DataSource} instance that created it; a
208         * {@link Database} using a different {@link DataSource} fails fast instead of joining it.
209         *
210         * @param transactionOptions     options to apply to the transaction
211         * @param transactionalOperation the operation to perform transactionally
212         * @throws DatabaseException if pre-commit validation detects an aborted transaction or cannot establish usability
213         * @since 4.2.0
214         */
215        public void transaction(@NonNull TransactionOptions transactionOptions,
216                                                                                                        @NonNull TransactionalOperation transactionalOperation) {
217                requireNonNull(transactionOptions);
218                requireNonNull(transactionalOperation);
219
220                transaction(transactionOptions, () -> {
221                        transactionalOperation.perform();
222                        return Optional.empty();
223                });
224        }
225
226        /**
227         * Performs an operation transactionally and optionally returns a value.
228         * <p>
229         * The transaction will be automatically rolled back if an exception bubbles out of {@code transactionalOperation}.
230         * <p>
231         * On PostgreSQL and DuckDB, pre-commit validation can refuse commit even when the callback returns normally:
232         * the transaction may be aborted, or a required check may be unable to establish transaction usability.
233         * Pyranid attempts the normal rollback path and this method throws {@link DatabaseException}; handling a
234         * statement failure inside the callback does not guarantee successful completion.
235         * <p>
236         * Nested calls to {@code transaction(...)} are independent transactions with independent JDBC connections; they do
237         * not automatically join an outer transaction. Use {@link #participate(Transaction, ReturningTransactionalOperation)} to
238         * join an existing transaction explicitly. A transaction is scoped to the {@link DataSource} instance that created it; a
239         * {@link Database} using a different {@link DataSource} fails fast instead of joining it.
240         *
241         * @param transactionalOperation the operation to perform transactionally
242         * @param <T>                    the type to be returned
243         * @return the result of the transactional operation
244         * @throws DatabaseException if pre-commit validation detects an aborted transaction or cannot establish usability
245         */
246        @NonNull
247        public <T> Optional<T> transaction(@NonNull ReturningTransactionalOperation<T> transactionalOperation) {
248                requireNonNull(transactionalOperation);
249                return transaction(TransactionOptions.DEFAULT, transactionalOperation);
250        }
251
252        /**
253         * Performs an operation transactionally with the given options, optionally returning a value.
254         * <p>
255         * The transaction will be automatically rolled back if an exception bubbles out of {@code transactionalOperation}.
256         * <p>
257         * On PostgreSQL and DuckDB, pre-commit validation can refuse commit even when the callback returns normally:
258         * the transaction may be aborted, or a required check may be unable to establish transaction usability.
259         * Pyranid attempts the normal rollback path and this method throws {@link DatabaseException}; handling a
260         * statement failure inside the callback does not guarantee successful completion.
261         * <p>
262         * Ordinary failure-derived interruption is restored after cleanup and post-transaction hooks, only when no enclosing
263         * Pyranid transaction remains bound. Handling a nested failure does not defer cancellation to the outer boundary;
264         * callers that intend cancellation must rethrow or restore the flag. A final propagating {@link Error} restores its
265         * reachable interruption evidence even with an enclosing transaction.
266         * <p>
267         * Nested calls to {@code transaction(...)} are independent transactions with independent JDBC connections; they do
268         * not automatically join an outer transaction. Use {@link #participate(Transaction, ReturningTransactionalOperation)} to
269         * join an existing transaction explicitly. A transaction is scoped to the {@link DataSource} instance that created it; a
270         * {@link Database} using a different {@link DataSource} fails fast instead of joining it.
271         *
272         * @param transactionOptions     options to apply to the transaction
273         * @param transactionalOperation the operation to perform transactionally
274         * @param <T>                    the type to be returned
275         * @return the result of the transactional operation
276         * @throws DatabaseException if pre-commit validation detects an aborted transaction or cannot establish usability
277         * @since 4.2.0
278         */
279        @NonNull
280        public <T> Optional<T> transaction(@NonNull TransactionOptions transactionOptions,
281                                                                                                                                                 @NonNull ReturningTransactionalOperation<T> transactionalOperation) {
282                return this.transactions.run(transactionOptions, transactionalOperation);
283        }
284
285        /**
286         * Performs one independent transaction attempt and returns its database outcome and invocation failure.
287         * Uses the default options and performs no automatic retry. A normal rollback-only callback has no failure;
288         * a committed transaction can retain a cleanup or hook failure.
289         * <p>
290         * On PostgreSQL and DuckDB, pre-commit validation can refuse commit after a normal callback return if the
291         * transaction is aborted or a required check cannot establish usability. The refusal is retained in the outcome's
292         * failure. Acknowledged rollback reports {@link TransactionResult#ROLLED_BACK}; failed rollback after application
293         * work could have executed reports {@link TransactionResult#IN_DOUBT}. A final {@link Error} still escapes.
294         *
295         * @param operation the transactional operation
296         * @return the completed transaction outcome, with no attempted value
297         * @since 4.9.0
298         */
299        @NonNull
300        public TransactionOutcome<Void> transactionWithOutcome(@NonNull TransactionalOperation operation) {
301                return transactionWithOutcome(TransactionOptions.DEFAULT, operation);
302        }
303
304        /**
305         * Performs one independent transaction attempt with explicit options, returning its result and ordinary failure.
306         * Argument validation still throws normally; an operational acquisition/begin failure produces an outcome.
307         * Nested calls own independent connections. Use {@code participate(...)} to join a transaction explicitly.
308         * <p>
309         * On PostgreSQL and DuckDB, pre-commit validation can refuse commit after a normal callback return if the
310         * transaction is aborted or a required check cannot establish usability. The refusal is retained in the outcome's
311         * failure. Acknowledged rollback reports {@link TransactionResult#ROLLED_BACK}; failed rollback after application
312         * work could have executed reports {@link TransactionResult#IN_DOUBT}. A final {@link Error} still escapes.
313         *
314         * @param options transaction options
315         * @param operation the transactional operation
316         * @return the completed transaction outcome, with no attempted value
317         * @since 4.9.0
318         */
319        @NonNull
320        public TransactionOutcome<Void> transactionWithOutcome(@NonNull TransactionOptions options,
321                        @NonNull TransactionalOperation operation) {
322                requireNonNull(options);
323                requireNonNull(operation);
324                return transactionWithOutcome(options, () -> {
325                        operation.perform();
326                        return Optional.empty();
327                });
328        }
329
330        /**
331         * Performs one independent transaction attempt and retains the value returned normally by its callback.
332         * The attempted value is available even if completion rolls back, becomes uncertain or fails after commit.
333         * Uses default options; see the options overload for failure and interruption semantics.
334         * <p>
335         * On PostgreSQL and DuckDB, pre-commit validation can refuse commit after a normal callback return if the
336         * transaction is aborted or a required check cannot establish usability. The refusal is retained in the outcome's
337         * failure. Acknowledged rollback reports {@link TransactionResult#ROLLED_BACK}; failed rollback after application
338         * work could have executed reports {@link TransactionResult#IN_DOUBT}. A final {@link Error} still escapes.
339         *
340         * @param operation the transactional operation
341         * @param <T> the callback value type
342         * @return the completed transaction outcome and attempted callback value
343         * @since 4.9.0
344         */
345        @NonNull
346        public <T> TransactionOutcome<T> transactionWithOutcome(@NonNull ReturningTransactionalOperation<T> operation) {
347                return transactionWithOutcome(TransactionOptions.DEFAULT, operation);
348        }
349
350        /**
351         * Performs one independent transaction attempt, returning its final completion and attempted callback value.
352         * <p>
353         * The callback runs once. Ordinary invocation failures, including programming errors, are retained instead of
354         * thrown, with the traditional API's wrapping, causes and suppressed failures. A final {@link Error} escapes
355         * after best-effort completion and observation. Null arguments and failures before a boundary exists still throw.
356         * An empty or accidentally null callback Optional is normalized to empty; a callback that throws has no value.
357         * <p>
358         * Result, value and failure describe separate facts. Rollback-only completion can retain a value without a
359         * failure, and successful commit can retain a cleanup or hook failure. The configured completion observer sees
360         * the same completion after cleanup and hooks. Its own failure remains contained.
361         * <p>
362         * With no enclosing transaction, interruption from a returned failure is restored before return. With an enclosing
363         * transaction, Pyranid preserves an already-pending flag but does not newly publish interruption from a handled
364         * outcome; that evidence remains in its failure. A propagating final Error follows the throwing API's restoration.
365         * <p>
366         * This method never retries and does not join an ambient transaction. Do not combine it with retries by nesting
367         * it inside {@code transactionWithRetry(...)}: that creates an independent transaction. An uncertain result needs
368         * application reconciliation under the original durable operation identity; it does not authorize replay.
369         * <p>
370         * On PostgreSQL and DuckDB, pre-commit validation can refuse commit after a normal callback return if the
371         * transaction is aborted or a required check cannot establish usability. The refusal is retained in the outcome's
372         * failure. Acknowledged rollback reports {@link TransactionResult#ROLLED_BACK}; failed rollback after application
373         * work could have executed reports {@link TransactionResult#IN_DOUBT}. A final {@link Error} still escapes.
374         *
375         * @param options transaction options
376         * @param operation the transactional operation
377         * @param <T> the callback value type
378         * @return the completed transaction outcome and attempted callback value
379         * @since 4.9.0
380         */
381        @NonNull
382        public <T> TransactionOutcome<T> transactionWithOutcome(@NonNull TransactionOptions options,
383                        @NonNull ReturningTransactionalOperation<T> operation) {
384                return this.transactions.runWithOutcome(options, operation);
385        }
386
387        /**
388         * Performs an operation transactionally, retrying according to the given retry policy.
389         * <p>
390         * The entire transaction closure may run more than once. Keep non-idempotent external side effects outside the closure
391         * unless they are safe to repeat.
392         * <p>
393         * For a {@link DatabaseException}, Pyranid consults the retry policy only when replay is known to be safe. Body
394         * failures require acknowledged rollback and no retained committed, in-doubt or cancellation evidence. A failure before
395         * a physical transaction becomes available to application work can also be eligible even if best-effort rollback of that
396         * discarded begin candidate fails. The retry policy still decides whether an eligible failure should be retried.
397         * <p>
398         * A physical commit failure is eligible only when the original driver's exception has a direct, readable SQLState
399         * {@code 40001}, the dialect classifies it as a serialization failure, its cause/next/suppressed evidence is consistent
400         * and readable, and the follow-up rollback succeeds. Transport or causal I/O failures, missing or different subordinate
401         * SQLStates, and vendor-only diagnostics such as Oracle {@code 8177} or SQL Server {@code 3960} do not establish that
402         * proof. The tested DuckDB driver supplies no SQLState for commit conflicts, so those outcomes remain
403         * {@link TransactionResult#IN_DOUBT} and are not retried. Other uncertain commit outcomes, failed rollback after
404         * application work could execute, and failures after successful commit are never replayed.
405         * <p>
406         * On PostgreSQL and DuckDB, pre-commit validation can refuse completion after a normal callback return. The refusal
407         * can inherit classification from an earlier handled failure; after acknowledged rollback, an accepting retry policy
408         * can therefore rerun that normally returned callback. Keep the entire callback safe to replay.
409         * <p>
410         * A savepoint-scope ownership conflict at completion is never replayed, with or without a successful rollback: the
411         * guard raises an {@link IllegalStateException}, not a {@link DatabaseException}, so the conflict leaves this method
412         * without reaching the retry policy. What a successful rollback changes is the attempt's outcome evidence; the conflict
413         * no longer records an indeterminate outcome, so a conflict raised and handled by an independent transaction inside the
414         * closure no longer fences a retry of a later failure.
415         * <p>
416         * Unlike {@link #transaction(TransactionalOperation)} and related transaction methods, retrying methods return
417         * {@link TransactionRetryResult} so callers can inspect failures that were recovered before success.
418         * <p>
419         * This method rejects a call when the innermost ambient transaction on the calling thread uses the same
420         * {@link DataSource} instance, including across different {@code Database} wrappers. Only that innermost transaction
421         * is checked. If a transaction on another source hides an older matching transaction, this method starts an independent
422         * retrying transaction; retries do not restart either surrounding transaction.
423         *
424         * @param retryPolicy           retry policy to apply
425         * @param transactionalOperation the operation to perform transactionally
426         * @return retry result containing any failures retried before success
427         * @since 4.4.0
428         */
429        @NonNull
430        public TransactionRetryResult<Void> transactionWithRetry(@NonNull RetryPolicy retryPolicy,
431                                                                                                                                                                                                                                        @NonNull TransactionalOperation transactionalOperation) {
432                requireNonNull(retryPolicy);
433                requireNonNull(transactionalOperation);
434
435                return transactionWithRetry(retryPolicy, () -> {
436                        transactionalOperation.perform();
437                        return Optional.<Void>empty();
438                });
439        }
440
441        /**
442         * Performs an operation transactionally with the given options, retrying according to the given retry policy.
443         * <p>
444         * The entire transaction closure may run more than once. Keep non-idempotent external side effects outside the closure
445         * unless they are safe to repeat.
446         * <p>
447         * For a {@link DatabaseException}, Pyranid consults the retry policy only when replay is known to be safe. Body
448         * failures require acknowledged rollback and no retained committed, in-doubt or cancellation evidence. A failure before
449         * a physical transaction becomes available to application work can also be eligible even if best-effort rollback of that
450         * discarded begin candidate fails. The retry policy still decides whether an eligible failure should be retried.
451         * <p>
452         * A physical commit failure is eligible only when the original driver's exception has a direct, readable SQLState
453         * {@code 40001}, the dialect classifies it as a serialization failure, its cause/next/suppressed evidence is consistent
454         * and readable, and the follow-up rollback succeeds. Transport or causal I/O failures, missing or different subordinate
455         * SQLStates, and vendor-only diagnostics such as Oracle {@code 8177} or SQL Server {@code 3960} do not establish that
456         * proof. The tested DuckDB driver supplies no SQLState for commit conflicts, so those outcomes remain
457         * {@link TransactionResult#IN_DOUBT} and are not retried. Other uncertain commit outcomes, failed rollback after
458         * application work could execute, and failures after successful commit are never replayed.
459         * <p>
460         * On PostgreSQL and DuckDB, pre-commit validation can refuse completion after a normal callback return. The refusal
461         * can inherit classification from an earlier handled failure; after acknowledged rollback, an accepting retry policy
462         * can therefore rerun that normally returned callback. Keep the entire callback safe to replay.
463         * <p>
464         * A savepoint-scope ownership conflict at completion is never replayed, with or without a successful rollback: the
465         * guard raises an {@link IllegalStateException}, not a {@link DatabaseException}, so the conflict leaves this method
466         * without reaching the retry policy. What a successful rollback changes is the attempt's outcome evidence; the conflict
467         * no longer records an indeterminate outcome, so a conflict raised and handled by an independent transaction inside the
468         * closure no longer fences a retry of a later failure.
469         * <p>
470         * Unlike {@link #transaction(TransactionOptions, TransactionalOperation)} and related transaction methods, retrying
471         * methods return {@link TransactionRetryResult} so callers can inspect failures that were recovered before success.
472         * <p>
473         * This method rejects a call when the innermost ambient transaction on the calling thread uses the same
474         * {@link DataSource} instance, including across different {@code Database} wrappers. Only that innermost transaction
475         * is checked. If a transaction on another source hides an older matching transaction, this method starts an independent
476         * retrying transaction; retries do not restart either surrounding transaction.
477         *
478         * @param retryPolicy           retry policy to apply
479         * @param transactionOptions     options to apply to each transaction attempt
480         * @param transactionalOperation the operation to perform transactionally
481         * @return retry result containing any failures retried before success
482         * @since 4.4.0
483         */
484        @NonNull
485        public TransactionRetryResult<Void> transactionWithRetry(@NonNull RetryPolicy retryPolicy,
486                                                                                                                                                                                                                                        @NonNull TransactionOptions transactionOptions,
487                                                                                                                                                                                                                                        @NonNull TransactionalOperation transactionalOperation) {
488                requireNonNull(retryPolicy);
489                requireNonNull(transactionOptions);
490                requireNonNull(transactionalOperation);
491
492                return transactionWithRetry(retryPolicy, transactionOptions, () -> {
493                        transactionalOperation.perform();
494                        return Optional.<Void>empty();
495                });
496        }
497
498        /**
499         * Performs an operation transactionally and optionally returns a value, retrying according to the given retry policy.
500         * <p>
501         * The entire transaction closure may run more than once. Keep non-idempotent external side effects outside the closure
502         * unless they are safe to repeat.
503         * <p>
504         * For a {@link DatabaseException}, Pyranid consults the retry policy only when replay is known to be safe. Body
505         * failures require acknowledged rollback and no retained committed, in-doubt or cancellation evidence. A failure before
506         * a physical transaction becomes available to application work can also be eligible even if best-effort rollback of that
507         * discarded begin candidate fails. The retry policy still decides whether an eligible failure should be retried.
508         * <p>
509         * A physical commit failure is eligible only when the original driver's exception has a direct, readable SQLState
510         * {@code 40001}, the dialect classifies it as a serialization failure, its cause/next/suppressed evidence is consistent
511         * and readable, and the follow-up rollback succeeds. Transport or causal I/O failures, missing or different subordinate
512         * SQLStates, and vendor-only diagnostics such as Oracle {@code 8177} or SQL Server {@code 3960} do not establish that
513         * proof. The tested DuckDB driver supplies no SQLState for commit conflicts, so those outcomes remain
514         * {@link TransactionResult#IN_DOUBT} and are not retried. Other uncertain commit outcomes, failed rollback after
515         * application work could execute, and failures after successful commit are never replayed.
516         * <p>
517         * On PostgreSQL and DuckDB, pre-commit validation can refuse completion after a normal callback return. The refusal
518         * can inherit classification from an earlier handled failure; after acknowledged rollback, an accepting retry policy
519         * can therefore rerun that normally returned callback. Keep the entire callback safe to replay.
520         * <p>
521         * A savepoint-scope ownership conflict at completion is never replayed, with or without a successful rollback: the
522         * guard raises an {@link IllegalStateException}, not a {@link DatabaseException}, so the conflict leaves this method
523         * without reaching the retry policy. What a successful rollback changes is the attempt's outcome evidence; the conflict
524         * no longer records an indeterminate outcome, so a conflict raised and handled by an independent transaction inside the
525         * closure no longer fences a retry of a later failure.
526         * <p>
527         * Unlike {@link #transaction(ReturningTransactionalOperation)} and related transaction methods, retrying methods return
528         * {@link TransactionRetryResult} so callers can inspect failures that were recovered before success.
529         * <p>
530         * This method rejects a call when the innermost ambient transaction on the calling thread uses the same
531         * {@link DataSource} instance, including across different {@code Database} wrappers. Only that innermost transaction
532         * is checked. If a transaction on another source hides an older matching transaction, this method starts an independent
533         * retrying transaction; retries do not restart either surrounding transaction.
534         *
535         * @param retryPolicy           retry policy to apply
536         * @param transactionalOperation the operation to perform transactionally
537         * @param <T>                    the type to be returned
538         * @return retry result containing the successful transaction value and any failures retried before success
539         * @since 4.4.0
540         */
541        @NonNull
542        public <T> TransactionRetryResult<T> transactionWithRetry(@NonNull RetryPolicy retryPolicy,
543                                                                                                                                                                                                                                         @NonNull ReturningTransactionalOperation<T> transactionalOperation) {
544                requireNonNull(retryPolicy);
545                requireNonNull(transactionalOperation);
546
547                return transactionWithRetry(retryPolicy, TransactionOptions.DEFAULT, transactionalOperation);
548        }
549
550        /**
551         * Performs an operation transactionally with the given options and optionally returns a value, retrying according to the
552         * given retry policy.
553         * <p>
554         * The entire transaction closure may run more than once. Keep non-idempotent external side effects outside the closure
555         * unless they are safe to repeat.
556         * <p>
557         * For a {@link DatabaseException}, Pyranid consults the retry policy only when replay is known to be safe. Body
558         * failures require acknowledged rollback and no retained committed, in-doubt or cancellation evidence. A failure before
559         * a physical transaction becomes available to application work can also be eligible even if best-effort rollback of that
560         * discarded begin candidate fails. The retry policy still decides whether an eligible failure should be retried.
561         * <p>
562         * A physical commit failure is eligible only when the original driver's exception has a direct, readable SQLState
563         * {@code 40001}, the dialect classifies it as a serialization failure, its cause/next/suppressed evidence is consistent
564         * and readable, and the follow-up rollback succeeds. Transport or causal I/O failures, missing or different subordinate
565         * SQLStates, and vendor-only diagnostics such as Oracle {@code 8177} or SQL Server {@code 3960} do not establish that
566         * proof. The tested DuckDB driver supplies no SQLState for commit conflicts, so those outcomes remain
567         * {@link TransactionResult#IN_DOUBT} and are not retried. Other uncertain commit outcomes, failed rollback after
568         * application work could execute, and failures after successful commit are never replayed.
569         * <p>
570         * On PostgreSQL and DuckDB, pre-commit validation can refuse completion after a normal callback return. The refusal
571         * can inherit classification from an earlier handled failure; after acknowledged rollback, an accepting retry policy
572         * can therefore rerun that normally returned callback. Keep the entire callback safe to replay.
573         * <p>
574         * A savepoint-scope ownership conflict at completion is never replayed, with or without a successful rollback: the
575         * guard raises an {@link IllegalStateException}, not a {@link DatabaseException}, so the conflict leaves this method
576         * without reaching the retry policy. What a successful rollback changes is the attempt's outcome evidence; the conflict
577         * no longer records an indeterminate outcome, so a conflict raised and handled by an independent transaction inside the
578         * closure no longer fences a retry of a later failure.
579         * <p>
580         * Unlike {@link #transaction(TransactionOptions, ReturningTransactionalOperation)} and related transaction methods,
581         * retrying methods return {@link TransactionRetryResult} so callers can inspect failures that were recovered before
582         * success.
583         * <p>
584         * This method rejects a call when the innermost ambient transaction on the calling thread uses the same
585         * {@link DataSource} instance, including across different {@code Database} wrappers. Only that innermost transaction
586         * is checked. If a transaction on another source hides an older matching transaction, this method starts an independent
587         * retrying transaction; retries do not restart either surrounding transaction.
588         *
589         * @param retryPolicy           retry policy to apply
590         * @param transactionOptions     options to apply to each transaction attempt
591         * @param transactionalOperation the operation to perform transactionally
592         * @param <T>                    the type to be returned
593         * @return retry result containing the successful transaction value and any failures retried before success
594         * @since 4.4.0
595         */
596        @NonNull
597        public <T> TransactionRetryResult<T> transactionWithRetry(@NonNull RetryPolicy retryPolicy,
598                                                                                                                                                                                                                                         @NonNull TransactionOptions transactionOptions,
599                                                                                                                                                                                                                                         @NonNull ReturningTransactionalOperation<T> transactionalOperation) {
600                requireNonNull(retryPolicy);
601                requireNonNull(transactionOptions);
602                requireNonNull(transactionalOperation);
603
604                if (currentTransaction().isPresent())
605                        throw new IllegalStateException("transactionWithRetry must not be called within an existing transaction");
606
607                return RetryExecutor.DEFAULT.execute(retryPolicy, () -> transaction(transactionOptions, transactionalOperation));
608        }
609
610        static void closeConnection(@NonNull Connection connection, @NonNull DatabaseDialect databaseDialect) {
611                requireNonNull(connection);
612                requireNonNull(databaseDialect);
613
614                try {
615                        connection.close();
616                } catch (SQLException e) {
617                        throw DatabaseException.wrapSafely("Unable to close database connection", e, databaseDialect);
618                }
619        }
620
621        @NonNull
622        static DatabaseException databaseExceptionWithStatementContext(@NonNull StatementContext<?> statementContext,
623                                                                                                                                                                                                                                                        @NonNull Throwable cause) {
624                requireNonNull(statementContext);
625                requireNonNull(cause);
626
627                if (cause instanceof DatabaseException databaseException && databaseException.areStatementDiagnosticsApplied())
628                        return databaseException;
629
630                String message = DatabaseException.messageSafely(cause, "Database operation failed");
631
632                if (cause instanceof DatabaseException databaseException) {
633                        SecureParameterSupport.DiagnosticScrub diagnosticScrub = diagnosticScrubForStatementContext(statementContext);
634
635                        if (diagnosticScrub.redactor() == null && diagnosticScrub.needleRenderingFailureDescriptions().isEmpty())
636                                return databaseException;
637
638                        return databaseExceptionWithStatementContext(statementContext, message, cause, diagnosticScrub);
639                }
640
641                return databaseExceptionWithStatementContext(statementContext, message, cause);
642        }
643
644        @NonNull
645        static DatabaseException databaseExceptionWithStatementContext(@NonNull StatementContext<?> statementContext,
646                                                                                                                                                                                                                                                                                                @NonNull String message,
647                                                                                                                                                                                                                                                                                                @NonNull Throwable cause) {
648                requireNonNull(statementContext);
649                requireNonNull(message);
650                requireNonNull(cause);
651
652                SecureParameterSupport.DiagnosticScrub diagnosticScrub = diagnosticScrubForStatementContext(statementContext);
653                return databaseExceptionWithStatementContext(statementContext, message, cause, diagnosticScrub);
654        }
655
656        @NonNull
657        static DatabaseException databaseExceptionWithStatementContext(@NonNull StatementContext<?> statementContext,
658                                                                                                                                                                                                                                                        @NonNull String message,
659                                                                                                                                                                                                                                                        @NonNull Throwable cause,
660                                                                                                                                                                                                                                                        SecureParameterSupport.@NonNull DiagnosticScrub diagnosticScrub) {
661                requireNonNull(statementContext);
662                requireNonNull(message);
663                requireNonNull(cause);
664                requireNonNull(diagnosticScrub);
665
666                UnaryOperator<String> diagnosticRedactor = diagnosticScrub.redactor();
667
668                // Scrub the RAW message before whitespace-collapsing/truncation: bounding first would break needles
669                // containing consecutive whitespace and can cut a secret mid-way, leaving an unmatchable prefix
670                String scrubbedMessage;
671                try {
672                        scrubbedMessage = diagnosticRedactor == null ? message : diagnosticRedactor.apply(message);
673                } catch (Throwable diagnosticFailure) {
674                        if (cause != diagnosticFailure) cause.addSuppressed(diagnosticFailure);
675                        // A failed redactor must not expose the unredacted driver text as the replacement message.
676                        scrubbedMessage = "Database operation failed";
677                }
678
679                StatementDiagnostic statementDiagnostic = statementDiagnostic(statementContext);
680                String diagnosticMessage = format("%s [%s]",
681                                boundedDiagnosticMessage(scrubbedMessage), statementDiagnostic.diagnostic());
682                DatabaseException databaseException = DatabaseException.wrapSafely(diagnosticMessage, cause,
683                                statementContext.getDatabaseDialect(), diagnosticRedactor);
684                databaseException.markStatementDiagnosticsApplied();
685
686                if (statementDiagnostic.parameterRenderingFailure() != null)
687                        databaseException.addSuppressed(statementDiagnostic.parameterRenderingFailure());
688
689                for (String failureDescription : diagnosticScrub.needleRenderingFailureDescriptions())
690                        databaseException.addSuppressed(new RuntimeException(format(
691                                        "Unable to render a secure parameter for diagnostic scrubbing: %s", failureDescription)));
692
693                return databaseException;
694        }
695
696        private static SecureParameterSupport.@NonNull DiagnosticScrub diagnosticScrubForStatementContext(@NonNull StatementContext<?> statementContext) {
697                requireNonNull(statementContext);
698
699                try {
700                        return SecureParameterSupport.diagnosticScrubForParameters(statementContext.getParameters());
701                } catch (Throwable ignored) {
702                        // Per-needle failures are handled inside diagnosticScrubForParameters; reaching here would be
703                        // catastrophic (a plain getter throwing) - fall back to no scrubbing rather than losing the exception
704                        return SecureParameterSupport.DiagnosticScrub.NONE;
705                }
706        }
707
708        @NonNull
709        private DatabaseException databaseExceptionWithRawConnectionContext(@NonNull Exception cause) {
710                requireNonNull(cause);
711                return DatabaseException.wrapSafely(DatabaseException.messageSafely(cause, "Database operation failed"),
712                                cause, this.databaseDialect);
713        }
714
715        @NonNull
716        private static StatementDiagnostic statementDiagnostic(@NonNull StatementContext<?> statementContext) {
717                requireNonNull(statementContext);
718
719                Statement statement = statementContext.getStatement();
720                String parameters;
721                Throwable parameterRenderingFailure = null;
722
723                try {
724                        parameters = boundedDiagnosticParameters(statementContext.getRedactedParameters());
725                } catch (Throwable t) {
726                        parameters = "<unavailable>";
727                        parameterRenderingFailure = t;
728                }
729
730                String diagnostic = format("statementId=%s, sql=%s, parameters=%s",
731                                statement.getId(), boundedSql(statement.getSql()), parameters);
732
733                if (parameterRenderingFailure != null)
734                        diagnostic = format("%s, parameterRenderingFailure=%s", diagnostic,
735                                        boundedDiagnosticParameter(parameterRenderingFailureDiagnostic(parameterRenderingFailure)));
736
737                return new StatementDiagnostic(diagnostic, parameterRenderingFailure);
738        }
739
740        private record StatementDiagnostic(@NonNull String diagnostic,
741                                                                                                                                                 @Nullable Throwable parameterRenderingFailure) {}
742
743        @NonNull
744        private static String parameterRenderingFailureDiagnostic(@NonNull Throwable parameterRenderingFailure) {
745                requireNonNull(parameterRenderingFailure);
746
747                String message;
748
749                try {
750                        message = parameterRenderingFailure.getMessage();
751                } catch (Throwable ignored) {
752                        message = null;
753                }
754
755                if (message == null || message.trim().length() == 0)
756                        return parameterRenderingFailure.getClass().getName();
757
758                return format("%s: %s", parameterRenderingFailure.getClass().getName(), message);
759        }
760
761        @Nullable
762        static Long sumBatchUpdateCounts(@NonNull List<Long> updateCounts) {
763                requireNonNull(updateCounts);
764
765                long total = 0L;
766
767                for (Long updateCount : updateCounts) {
768                        if (updateCount == null || updateCount < 0L)
769                                return null;
770
771                        try {
772                                total = Math.addExact(total, updateCount);
773                        } catch (ArithmeticException e) {
774                                return null;
775                        }
776                }
777
778                return total;
779        }
780
781        @NonNull
782        private static String boundedDiagnosticMessage(@NonNull String message) {
783                requireNonNull(message);
784
785                String compactMessage = DIAGNOSTIC_WHITESPACE_PATTERN.matcher(message).replaceAll(" ").trim();
786
787                if (compactMessage.length() <= MAX_DIAGNOSTIC_MESSAGE_LENGTH)
788                        return compactMessage;
789
790                int prefixLength = Math.max(0, MAX_DIAGNOSTIC_MESSAGE_LENGTH - TRUNCATED_SUFFIX.length());
791                return compactMessage.substring(0, prefixLength) + TRUNCATED_SUFFIX;
792        }
793
794        @NonNull
795        private static String boundedSql(@NonNull String sql) {
796                requireNonNull(sql);
797
798                String compactSql = DIAGNOSTIC_WHITESPACE_PATTERN.matcher(sql).replaceAll(" ").trim();
799
800                if (compactSql.length() <= MAX_DIAGNOSTIC_SQL_LENGTH)
801                        return compactSql;
802
803                int prefixLength = Math.max(0, MAX_DIAGNOSTIC_SQL_LENGTH - TRUNCATED_SUFFIX.length());
804                return compactSql.substring(0, prefixLength) + TRUNCATED_SUFFIX;
805        }
806
807        @NonNull
808        private static String boundedDiagnosticParameters(@NonNull List<@Nullable Object> parameters) {
809                requireNonNull(parameters);
810
811                StringBuilder parametersBuilder = new StringBuilder("[");
812
813                for (int i = 0; i < parameters.size(); ++i) {
814                        String separator = i == 0 ? "" : ", ";
815                        String renderedParameter = boundedDiagnosticParameter(parameters.get(i));
816                        int requiredLength = parametersBuilder.length() + separator.length() + renderedParameter.length() + 1;
817
818                        if (requiredLength > MAX_DIAGNOSTIC_PARAMETERS_LENGTH) {
819                                int availableLength = MAX_DIAGNOSTIC_PARAMETERS_LENGTH
820                                                - parametersBuilder.length()
821                                                - separator.length()
822                                                - TRUNCATED_SUFFIX.length()
823                                                - 1;
824
825                                parametersBuilder.append(separator);
826
827                                if (availableLength > 0)
828                                        parametersBuilder.append(renderedParameter, 0, Math.min(availableLength, renderedParameter.length()));
829
830                                parametersBuilder.append(TRUNCATED_SUFFIX).append(']');
831                                if (parametersBuilder.length() > MAX_DIAGNOSTIC_PARAMETERS_LENGTH) {
832                                        parametersBuilder.setLength(MAX_DIAGNOSTIC_PARAMETERS_LENGTH - 1);
833                                        parametersBuilder.append(']');
834                                }
835                                return parametersBuilder.toString();
836                        }
837
838                        parametersBuilder.append(separator).append(renderedParameter);
839                }
840
841                parametersBuilder.append(']');
842                return parametersBuilder.toString();
843        }
844
845        @NonNull
846        private static String boundedDiagnosticParameter(@Nullable Object parameter) {
847                String renderedParameter = String.valueOf(parameter);
848                String compactParameter = DIAGNOSTIC_WHITESPACE_PATTERN.matcher(renderedParameter).replaceAll(" ").trim();
849
850                if (compactParameter.length() <= MAX_DIAGNOSTIC_PARAMETER_LENGTH)
851                        return compactParameter;
852
853                int prefixLength = Math.max(0, MAX_DIAGNOSTIC_PARAMETER_LENGTH - TRUNCATED_SUFFIX.length());
854                return compactParameter.substring(0, prefixLength) + TRUNCATED_SUFFIX;
855        }
856
857        /**
858         * Performs an operation in the context of a pre-existing transaction.
859         * <p>
860         * No commit or rollback on the transaction will occur when {@code transactionalOperation} completes.
861         * <p>
862         * However, if an exception bubbles out of {@code transactionalOperation}, the transaction will be marked as rollback-only.
863         * <p>
864         * The transaction must have been created by this {@link Database}, or by another {@link Database} using the same
865         * {@link DataSource} instance.
866         * <p>
867         * If this thread is interrupted while waiting for another participant to release the transaction connection, Pyranid
868         * restores the interrupt flag and throws {@link DatabaseException}.
869         * <p>
870         * Failure-derived interruption from the callback is restored after removing this participation context only
871         * when no Pyranid transaction remains bound on the calling thread. Same-thread participation inside its
872         * owner does not newly publish that flag; already-pending flags are preserved. If a caller handles the
873         * failure inside the owner and intends cancellation, it must rethrow or restore the flag explicitly.
874         * Handled failures do not queue later interruption restoration; the owner is still marked rollback-only.
875         *
876         * @param transaction            the transaction in which to participate
877         * @param transactionalOperation the operation that should participate in the transaction
878         */
879        public void participate(@NonNull Transaction transaction,
880                                                                                                        @NonNull TransactionalOperation transactionalOperation) {
881                requireNonNull(transaction);
882                requireNonNull(transactionalOperation);
883
884                participate(transaction, () -> {
885                        transactionalOperation.perform();
886                        return Optional.empty();
887                });
888        }
889
890        /**
891         * Performs an operation in the context of a pre-existing transaction, optionally returning a value.
892         * <p>
893         * No commit or rollback on the transaction will occur when {@code transactionalOperation} completes.
894         * <p>
895         * However, if an exception bubbles out of {@code transactionalOperation}, the transaction will be marked as rollback-only.
896         * <p>
897         * The transaction must have been created by this {@link Database}, or by another {@link Database} using the same
898         * {@link DataSource} instance.
899         * <p>
900         * If this thread is interrupted while waiting for another participant to release the transaction connection, Pyranid
901         * restores the interrupt flag and throws {@link DatabaseException}.
902         * <p>
903         * Failure-derived interruption from the callback is restored after removing this participation context only
904         * when no Pyranid transaction remains bound on the calling thread. Same-thread participation inside its
905         * owner does not newly publish that flag; already-pending flags are preserved. If a caller handles the
906         * failure inside the owner and intends cancellation, it must rethrow or restore the flag explicitly.
907         * Handled failures do not queue later interruption restoration; the owner is still marked rollback-only.
908         *
909         * @param transaction            the transaction in which to participate
910         * @param transactionalOperation the operation that should participate in the transaction
911         * @param <T>                    the type to be returned
912         * @return the result of the transactional operation
913         */
914        @NonNull
915        public <T> Optional<T> participate(@NonNull Transaction transaction,
916                                                                                                                                                 @NonNull ReturningTransactionalOperation<T> transactionalOperation) {
917                return this.transactions.participate(transaction, transactionalOperation);
918        }
919
920        /**
921         * Creates a fluent builder for executing SQL.
922         * <p>
923         * Named parameters use the {@code :paramName} syntax and are bound via {@link Query#bind(String, Object)}.
924         * Positional parameters via {@code ?} are not supported.
925         * Pyranid ignores parameter-looking text inside SQL string literals, quoted identifiers, comments, PostgreSQL
926         * dollar-quoted strings, and SQL Server-style bracket-quoted identifiers. PostgreSQL JSONB/hstore {@code ?},
927         * {@code ?|}, and {@code ?&} operators are supported; when running against {@link DatabaseType#POSTGRESQL}, Pyranid
928         * emits pgjdbc's escaped {@code ??} form automatically. Unterminated quotes and comments fail fast.
929         * <p>
930         * Example:
931         * <pre>{@code
932         * Optional<Employee> employee = database.query("SELECT * FROM employee WHERE id = :id")
933         *   .bind("id", 42)
934         *   .fetchObject(Employee.class);
935         * }</pre>
936         *
937         * @param sql SQL containing {@code :paramName} placeholders
938         * @return a fluent builder for binding parameters and executing
939         * @since 4.0.0
940         */
941        @NonNull
942        public Query query(@NonNull String sql) {
943                requireNonNull(sql);
944                return new DefaultQuery(this, sql, this.sqlCompiler, this.statementExecutor);
945        }
946
947        /**
948         * Performs a portable connectivity check using JDBC {@link Connection#isValid(int)}.
949         * <p>
950         * This method borrows a fresh connection from this database's {@link DataSource}, calls
951         * {@link Connection#isValid(int)}, and closes the connection before returning. It does <strong>not</strong>
952         * participate in an active Pyranid transaction, if one exists.
953         * <p>
954         * JDBC accepts timeout values in whole seconds. Positive sub-second durations are rounded up to one second;
955         * {@link Duration#ZERO} passes a timeout of {@code 0} to the driver.
956         * <p>
957         * If the failure this method propagates carries evidence of thread interruption, Pyranid restores the interrupt
958         * flag before throwing, as long as no Pyranid transaction is open on the calling thread. Inside a transaction this
959         * method restores nothing, and nothing restores the flag for a failure the caller handles there. A caller that
960         * handles one of these failures inside a transaction and wants to act on the cancellation must call
961         * {@link Thread#interrupt()} itself.
962         *
963         * @param timeout maximum time to wait for driver validation
964         * @throws IllegalArgumentException if {@code timeout} is negative or too large for JDBC's integer-second timeout
965         * @throws DatabaseException if connection acquisition fails, validation throws, or the driver reports the
966         *                           connection is not valid
967         * @since 4.2.0
968         */
969        public void performHealthCheck(@NonNull Duration timeout) {
970                requireNonNull(timeout);
971                int timeoutSeconds = healthCheckTimeoutSeconds(timeout);
972
973                performRawConnectionOperation(connection -> {
974                        boolean valid;
975
976                        try {
977                                valid = connection.isValid(timeoutSeconds);
978                        } catch (SQLException e) {
979                                throw DatabaseException.wrapSafely("Unable to perform database health check", e,
980                                                this.databaseDialect);
981                        }
982
983                        if (!valid)
984                                throw new DatabaseException("Database health check failed: connection is not valid");
985
986                        return Optional.empty();
987                }, false);
988        }
989
990        static void restoreInterruptIfNeeded(@NonNull Throwable throwable) {
991                requireNonNull(throwable);
992                // Failure inspection is best effort; it must never prevent cleanup or replace the primary exception.
993                if (ThrowableGraph.inspect(throwable, current -> current instanceof InterruptedException ? 1 : 0, 0) != 0)
994                        Thread.currentThread().interrupt();
995        }
996
997        static void lockInterruptibly(@NonNull ReentrantLock lock,
998                                                                                                                                                                @NonNull String operation) {
999                requireNonNull(lock);
1000                requireNonNull(operation);
1001
1002                try {
1003                        lock.lockInterruptibly();
1004                } catch (InterruptedException e) {
1005                        Thread.currentThread().interrupt();
1006                        throw new DatabaseException(format("Interrupted while waiting to %s", operation), e);
1007                }
1008        }
1009
1010        @Nullable
1011        static Throwable closeStatementContextResources(@NonNull StatementContext<?> statementContext,
1012                                                                                                                                                                                                                                        @Nullable Throwable cleanupFailure) {
1013                requireNonNull(statementContext);
1014
1015                Queue<AutoCloseable> cleanupOperations = statementContext.getCleanupOperations();
1016                AutoCloseable cleanupOperation;
1017
1018                while ((cleanupOperation = cleanupOperations.poll()) != null) {
1019                        try {
1020                                cleanupOperation.close();
1021                        } catch (Throwable cleanupException) {
1022                                cleanupFailure = appendCleanupFailure(cleanupFailure, cleanupException);
1023                        }
1024                }
1025
1026                return cleanupFailure;
1027        }
1028
1029        /** Keeps the first failure while allowing cleanup to continue when a driver reuses an exception instance. */
1030        @NonNull
1031        static Throwable appendCleanupFailure(@Nullable Throwable existing, @NonNull Throwable additional) {
1032                requireNonNull(additional);
1033                if (existing == null)
1034                        return additional;
1035                if (existing != additional)
1036                        existing.addSuppressed(additional);
1037                return existing;
1038        }
1039
1040        @Nullable
1041        static Duration validateQueryTimeout(@Nullable Duration queryTimeout) {
1042                if (queryTimeout != null) {
1043                        if (queryTimeout.isNegative())
1044                                throw new IllegalArgumentException("queryTimeout must be >= 0");
1045
1046                        queryTimeoutSeconds(queryTimeout);
1047                }
1048
1049                return queryTimeout;
1050        }
1051
1052        @Nullable
1053        static Integer validateNonNegativeStatementSetting(@NonNull String name,
1054                                                                                                                                                                                                                                                 @Nullable Integer value) {
1055                requireNonNull(name);
1056
1057                if (value != null && value < 0)
1058                        throw new IllegalArgumentException(format("%s must be >= 0", name));
1059
1060                return value;
1061        }
1062
1063        @Nullable
1064        static Integer validatePositiveQuerySetting(@NonNull String name,
1065                                                                                                                                                                                                                 @Nullable Integer value) {
1066                requireNonNull(name);
1067
1068                if (value != null && value <= 0)
1069                        throw new IllegalArgumentException(format("%s must be > 0", name));
1070
1071                return value;
1072        }
1073
1074        private static int queryTimeoutSeconds(@NonNull Duration queryTimeout) {
1075                requireNonNull(queryTimeout);
1076
1077                long seconds = queryTimeout.getSeconds();
1078
1079                if (queryTimeout.getNano() > 0) {
1080                        if (seconds == Long.MAX_VALUE)
1081                                throw new IllegalArgumentException(format("queryTimeout must be <= %s seconds", Integer.MAX_VALUE));
1082
1083                        ++seconds;
1084                }
1085
1086                if (seconds > Integer.MAX_VALUE)
1087                        throw new IllegalArgumentException(format("queryTimeout must be <= %s seconds", Integer.MAX_VALUE));
1088
1089                return (int) seconds;
1090        }
1091
1092        private static int healthCheckTimeoutSeconds(@NonNull Duration timeout) {
1093                requireNonNull(timeout);
1094
1095                if (timeout.isNegative())
1096                        throw new IllegalArgumentException("timeout must be >= 0");
1097
1098                long seconds = timeout.getSeconds();
1099
1100                if (timeout.getNano() > 0) {
1101                        if (seconds == Long.MAX_VALUE)
1102                                throw new IllegalArgumentException(format("timeout must be <= %s seconds", Integer.MAX_VALUE));
1103
1104                        ++seconds;
1105                }
1106
1107                if (seconds > Integer.MAX_VALUE)
1108                        throw new IllegalArgumentException(format("timeout must be <= %s seconds", Integer.MAX_VALUE));
1109
1110                return (int) seconds;
1111        }
1112
1113        /**
1114         * Exposes a temporary handle to JDBC {@link DatabaseMetaData}, which provides comprehensive vendor-specific information about this database as a whole.
1115         * <p>
1116         * This method acquires {@link DatabaseMetaData} on its own newly-borrowed connection, which it manages internally.
1117         * <p>
1118         * It does <strong>not</strong> participate in the active transaction, if one exists.
1119         * <p>
1120         * The connection is closed as soon as {@link DatabaseMetaDataReader#read(DatabaseMetaData)} completes.
1121         * <p>
1122         * See <a href="https://docs.oracle.com/en/java/javase/26/docs/api/java.sql/java/sql/DatabaseMetaData.html">{@code DatabaseMetaData} Javadoc</a> for details.
1123         * <p>
1124         * If the failure this method propagates carries evidence of thread interruption, Pyranid restores the interrupt
1125         * flag before throwing, as long as no Pyranid transaction is open on the calling thread. Inside a transaction this
1126         * method restores nothing, and nothing restores the flag for a failure the caller handles there. A caller that
1127         * handles one of these failures inside a transaction and wants to act on the cancellation must call
1128         * {@link Thread#interrupt()} itself.
1129         */
1130        public void readDatabaseMetaData(@NonNull DatabaseMetaDataReader databaseMetaDataReader) {
1131                requireNonNull(databaseMetaDataReader);
1132
1133                performRawConnectionOperation((connection -> {
1134                        databaseMetaDataReader.read(connection.getMetaData());
1135                        return Optional.empty();
1136                }), false);
1137        }
1138
1139        /**
1140         * Performs raw JDBC work with a Pyranid-managed {@link Connection}.
1141         * <p>
1142         * If called inside a Pyranid transaction, this operation uses the transaction's connection and participates in that
1143         * transaction. Otherwise, Pyranid borrows a connection for the duration of the callback and closes it afterwards.
1144         * <p>
1145         * The {@link Connection} passed to {@code rawConnectionOperation} is a guarded handle. Normal JDBC operations are
1146         * delegated to the underlying driver connection, but lifecycle, transaction-management, and connection-wide state
1147         * methods such as
1148         * {@link Connection#close()}, {@link Connection#commit()}, {@link Connection#rollback()},
1149         * {@link Connection#setAutoCommit(boolean)}, {@link Connection#setCatalog(String)}, {@link Connection#setSchema(String)}, and
1150         * {@link Connection#setNetworkTimeout(java.util.concurrent.Executor, int)} throw {@link IllegalStateException}. Use
1151         * Pyranid transaction APIs instead.
1152         * {@link Connection#unwrap(Class)} may return a guarded, callback-scoped proxy for a vendor interface, but never a
1153         * castable physical {@link Connection}; the proxy blocks lifecycle methods and expires with the callback.
1154         * JDBC objects created from this handle are also guarded: {@link java.sql.Statement#getConnection()} and
1155         * {@link java.sql.DatabaseMetaData#getConnection()} return the Pyranid-managed handle, and
1156         * {@link ResultSet#getStatement()} returns a guarded statement. Guarded statements, resultsets, and metadata refuse
1157         * driver-specific {@code unwrap(...)} calls that could expose the driver's underlying connection.
1158         * <p>
1159         * The connection handle is valid only for the duration of the callback. Do not close it, retain it, or use it after this
1160         * method returns.
1161         * <p>
1162         * If the failure this method propagates carries evidence of thread interruption, Pyranid restores the interrupt
1163         * flag before throwing, as long as no Pyranid transaction is open on the calling thread. Inside a transaction this
1164         * method restores nothing, and nothing restores the flag for a failure the caller handles there. A caller that
1165         * handles one of these failures inside a transaction and wants to act on the cancellation must call
1166         * {@link Thread#interrupt()} itself.
1167         *
1168         * @param rawConnectionOperation the raw JDBC operation to perform
1169         * @param <T>                    the type to be returned
1170         * @return the operation result
1171         * @throws DatabaseException if connection acquisition, callback execution, or cleanup fails
1172         * @since 4.2.0
1173         */
1174        @NonNull
1175        public <T> Optional<T> useRawConnection(@NonNull RawConnectionOperation<Connection, T> rawConnectionOperation) {
1176                requireNonNull(rawConnectionOperation);
1177
1178                return performRawConnectionOperation(connection -> {
1179                        PyranidRawConnection rawConnection = new PyranidRawConnection(connection);
1180
1181                        try {
1182                                Optional<T> result = rawConnectionOperation.perform(rawConnection);
1183                                return result == null ? Optional.empty() : result;
1184                        } finally {
1185                                rawConnection.release();
1186                        }
1187                }, true);
1188        }
1189
1190        /**
1191         * Performs driver-specific raw JDBC work with a Pyranid-managed connection of the requested type.
1192         * <p>
1193         * If called inside a Pyranid transaction, this operation uses the transaction's connection. Standard JDBC work
1194         * participates in that transaction; driver-extension APIs may impose additional transaction-start or lifecycle rules.
1195         * Otherwise, Pyranid borrows a connection for the duration of the callback and closes it afterwards.
1196         * <p>
1197         * If the managed connection is already an instance of {@code connectionType}, it is passed directly to
1198         * {@code rawConnectionOperation}. Otherwise, Pyranid obtains the requested driver connection through
1199         * {@link Connection#unwrap(Class)}. Failure to obtain the requested type results in a {@link DatabaseException}.
1200         * <p>
1201         * <strong>Unlike {@link #useRawConnection(RawConnectionOperation)}, the connection supplied by this overload is
1202         * unguarded.</strong> This is necessary for concrete driver APIs, but it also means Pyranid cannot prevent operations
1203         * that interfere with its connection and transaction management. Guarding is selected by the overload, so the
1204         * connection remains unguarded when {@code connectionType} is {@code Connection.class}. Do not close the connection,
1205         * retain it, call
1206         * {@link Connection#commit()}, {@link Connection#rollback()}, or {@link Connection#setAutoCommit(boolean)}, or mutate
1207         * connection-wide state such as schema, catalog, client info, holdability, type map, or network timeout.
1208         * <p>
1209         * The connection and every object obtained from it are valid only for the duration of the callback. Statements, result
1210         * sets, appenders, readers, and other derived resources must be closed before this method returns. Retaining or using any
1211         * of these objects after the callback returns has undefined behavior.
1212         * <p>
1213         * If the failure this method propagates carries evidence of thread interruption, Pyranid restores the interrupt
1214         * flag before throwing, as long as no Pyranid transaction is open on the calling thread. Inside a transaction this
1215         * method restores nothing, and nothing restores the flag for a failure the caller handles there. A caller that
1216         * handles one of these failures inside a transaction and wants to act on the cancellation must call
1217         * {@link Thread#interrupt()} itself.
1218         *
1219         * @param connectionType         driver connection class or interface to expose
1220         * @param rawConnectionOperation the driver-specific raw JDBC operation to perform
1221         * @param <C>                    the requested connection type
1222         * @param <T>                    the type to be returned
1223         * @return the operation result
1224         * @throws DatabaseException if connection acquisition, unwrapping, callback execution, or cleanup fails
1225         * @since 4.7.0
1226         */
1227        @NonNull
1228        public <C extends Connection, T> Optional<T> useRawConnection(@NonNull Class<C> connectionType,
1229                                                                                                                                                                                                                        @NonNull RawConnectionOperation<? super C, T> rawConnectionOperation) {
1230                requireNonNull(connectionType);
1231                requireNonNull(rawConnectionOperation);
1232
1233                return performRawConnectionOperation(connection -> {
1234                        C rawConnection = connectionType.isInstance(connection)
1235                                        ? connectionType.cast(connection)
1236                                        : connection.unwrap(connectionType);
1237
1238                        if (rawConnection == null)
1239                                throw new SQLException(format("Connection.unwrap(%s) returned null", connectionType.getName()));
1240
1241                        Optional<T> result = rawConnectionOperation.perform(rawConnection);
1242                        return result == null ? Optional.empty() : result;
1243                }, true);
1244        }
1245
1246        /**
1247         * Performs an operation with one callback-scoped database-notification listener session.
1248         * <p>
1249         * This method is synchronous and blocking. It acquires at most one listener connection from this
1250         * {@code Database}'s configured {@link DataSource}, registers every requested channel, invokes {@code operation}
1251         * at most once, expires the supplied {@link NotificationSession}, and completes cleanup before returning or
1252         * throwing. It never reconnects.
1253         * <p>
1254         * The configured source must preserve one physical backend session for the entire checkout. For PostgreSQL,
1255         * direct connections and session pooling are suitable. Using PgBouncer transaction or statement pooling as the
1256         * listener source is unsupported: registration can appear to succeed before backend-session affinity is lost and
1257         * notification delivery silently stops. Pyranid does not inspect or validate proxy topology. Applications whose
1258         * ordinary source cannot provide the required affinity should construct a separate {@code Database} over a suitable
1259         * listener source and invoke this method on that instance.
1260         * <p>
1261         * Notifications are lossy hints. Durable applications should normally reconcile authoritative state as the first
1262         * callback action. The operation may use ordinary database methods, but those methods acquire or select their
1263         * connection normally and never reuse the listener connection. Pyranid transaction entry is interrupt-sensitive;
1264         * when a receive returns a batch with a racing interrupt, temporarily clear and remember the flag during bounded
1265         * reconciliation and restore it afterward as described by {@link NotificationSession#awaitNotifications(Duration)}.
1266         * <p>
1267         * A terminal receive failure is retained by the session and rethrown after cleanup even if {@code operation} catches
1268         * it and returns. A retained transport {@link Error} propagates as that exact, unwrapped instance. If the callback
1269         * instead throws a distinct {@code Error}, that callback error remains primary and the retained transport failure is
1270         * suppressed beneath it.
1271         *
1272         * @param channels  fixed, nonempty set of nonblank channels to register
1273         * @param operation operation to invoke after every channel has been registered
1274         * @throws NullPointerException if {@code channels}, a channel, or {@code operation} is null
1275         * @throws IllegalArgumentException if the set is empty or a channel violates common or backend-specific limits
1276         * @throws IllegalStateException if any Pyranid transaction is active on the calling thread
1277         * @throws InterruptedException if cooperative interruption wins after any required cleanup
1278         * @throws UnsupportedOperationException if notification listening is unavailable through the database dialect or
1279         * runtime driver, or is unsupported or disabled for the current server version or configuration
1280         * @throws DatabaseException if connection acquisition, setup, receive, callback execution, or cleanup fails
1281         * @since 4.6.0
1282         */
1283        public void withNotificationSession(@NonNull Set<@NonNull String> channels,
1284                                                                                                                                                        @NonNull NotificationSessionOperation operation)
1285                        throws InterruptedException {
1286                NotificationSessionRunner.run(this, channels, operation);
1287        }
1288
1289        /**
1290         * Performs an operation with one callback-scoped database-notification listener session for a single channel.
1291         * <p>
1292         * This is the single-channel convenience form of
1293         * {@link #withNotificationSession(Set, NotificationSessionOperation)}. The listener connection comes from this
1294         * {@code Database}'s configured {@link DataSource}, which must preserve physical backend-session affinity for the
1295         * entire checkout. For PostgreSQL, using PgBouncer transaction or statement pooling as the listener source is
1296         * unsupported: registration can appear to succeed before affinity is lost and delivery silently stops. Pyranid does
1297         * not inspect or validate proxy topology.
1298         * <p>
1299         * A terminal receive failure is retained and rethrown after cleanup even if {@code operation} catches it and returns.
1300         * A retained transport {@link Error} propagates as the exact, unwrapped instance unless a distinct callback
1301         * {@code Error} takes precedence as described by the set-based overload.
1302         *
1303         * @param channel   nonblank channel to register
1304         * @param operation operation to invoke after the channel has been registered
1305         * @throws NullPointerException if {@code channel} or {@code operation} is null
1306         * @throws IllegalArgumentException if the channel violates common or backend-specific limits
1307         * @throws IllegalStateException if any Pyranid transaction is active on the calling thread
1308         * @throws InterruptedException if cooperative interruption wins after any required cleanup
1309         * @throws UnsupportedOperationException if notification listening is unavailable through the database dialect or
1310         * runtime driver, or is unsupported or disabled for the current server version or configuration
1311         * @throws DatabaseException if connection acquisition, setup, receive, callback execution, or cleanup fails
1312         * @since 4.6.0
1313         */
1314        public void withNotificationSession(@NonNull String channel,
1315                                                                                                                                                        @NonNull NotificationSessionOperation operation)
1316                        throws InterruptedException {
1317                requireNonNull(channel);
1318                requireNonNull(operation);
1319                withNotificationSession(Set.of(channel), operation);
1320        }
1321
1322        /**
1323         * Sends a transient database notification without specifying a payload.
1324         * <p>
1325         * Sending follows ordinary Pyranid statement and transaction selection. On PostgreSQL, a send inside a Pyranid
1326         * transaction becomes visible only if that transaction commits. Payload representation is database-specific;
1327         * PostgreSQL converts the resulting null payload to the empty string.
1328         *
1329         * @param channel nonblank notification channel
1330         * @throws NullPointerException if {@code channel} is null
1331         * @throws IllegalArgumentException if the channel violates common or backend-specific limits
1332         * @throws UnsupportedOperationException if notification sending is unavailable through the database dialect, or is
1333         * unsupported or disabled for the current server version or configuration
1334         * @throws DatabaseException if the send fails
1335         * @since 4.6.0
1336         */
1337        public void sendNotification(@NonNull String channel) {
1338                sendNotification(channel, null);
1339        }
1340
1341        /**
1342         * Sends a transient database notification.
1343         * <p>
1344         * Sending follows ordinary Pyranid statement and transaction selection, including connection ownership,
1345         * parameter binding and redaction, statement logging, timeout configuration, and metrics. Payload nullability
1346         * and null/empty-string handling are database-specific; Pyranid performs no generic normalization.
1347         * <p>
1348         * On PostgreSQL this executes bound {@code pg_catalog.pg_notify(?, ?)} SQL. PostgreSQL converts a null payload to the empty
1349         * string. Delivery occurs only after commit and is discarded by rollback; notification delivery itself remains
1350         * non-durable and may be coalesced.
1351         *
1352         * @param channel nonblank notification channel
1353         * @param payload notification payload, possibly null or empty
1354         * @throws NullPointerException if {@code channel} is null
1355         * @throws IllegalArgumentException if the channel or payload violates common or backend-specific limits
1356         * @throws UnsupportedOperationException if notification sending is unavailable through the database dialect, or is
1357         * unsupported or disabled for the current server version or configuration
1358         * @throws DatabaseException if the send fails
1359         * @since 4.6.0
1360         */
1361        public void sendNotification(@NonNull String channel,
1362                                                                                                 @Nullable String payload) {
1363                Notification.validateChannel(channel);
1364                DatabaseNotificationSupport notificationSupport = getDatabaseDialect().notificationSupport();
1365
1366                notificationSupport.validateChannel(channel);
1367                notificationSupport.validatePayload(payload);
1368
1369                if (!notificationSupport.isSendSupported())
1370                        throw new UnsupportedOperationException(format(
1371                                        "Database type %s does not support notification sends", getDatabaseType()));
1372
1373                Statement statement = Statement.of(generateId(), notificationSupport.sendStatementSql());
1374                StatementContext<Void> statementContext = StatementContext.with(statement, this)
1375                                .parameters(channel, payload)
1376                                .build();
1377
1378                PreparedStatementCustomizer defaultPreparedStatementCustomizer = hasDefaultPreparedStatementSettings()
1379                                ? (context, preparedStatement) -> applyDefaultPreparedStatementSettings(preparedStatement)
1380                                : null;
1381
1382                // Scoped deliberately to PreparedStatement.execute(). Connection acquisition, result draining and
1383                // JDBC cleanup can all raise these same SQLStates for unrelated reasons.
1384                AtomicReference<SQLException> sendStatementFailure = new AtomicReference<>();
1385
1386                try {
1387                        this.statementExecutor.performDatabaseOperation(statementContext, Arrays.asList(channel, payload),
1388                                        defaultPreparedStatementCustomizer, (preparedStatement, timing) -> {
1389                                long startTime = nanoTime();
1390
1391                                boolean resultAvailable;
1392
1393                                try {
1394                                        resultAvailable = preparedStatement.execute();
1395                                } catch (SQLException e) {
1396                                        if (isNotificationStatementUnsupported(e))
1397                                                sendStatementFailure.set(e);
1398
1399                                        throw e;
1400                                }
1401
1402                                drainStatementResults(preparedStatement, resultAvailable);
1403
1404                                return new StatementExecutor.DatabaseOperationResult(
1405                                                Duration.ofNanos(nanoTime() - startTime), null, StatementResult.empty());
1406                        });
1407                } catch (DatabaseException e) {
1408                        // The send statement is Pyranid's own, so the server rejecting it as unsupported syntax or an
1409                        // unavailable function is a server-capability issue rather than malformed caller SQL.
1410                        if (sendStatementFailure.get() != null)
1411                                throw new UnsupportedOperationException(
1412                                                notificationServerCapabilityUnavailableMessage(getDatabaseType()), e);
1413
1414                        throw e;
1415                }
1416        }
1417
1418        /**
1419         * Reports whether the configured database dialect and currently loadable runtime adapter expose the APIs required
1420         * to attempt a notification-listening session.
1421         * <p>
1422         * This method uses the configured database type without acquiring a connection or inspecting JDBC metadata.
1423         * It does not verify whether notifications are enabled or supported by the current server version or configuration,
1424         * acquire a listener session, inspect pool or proxy mode,
1425         * prove backend-session affinity, unwrap a physical listener connection, or emit notification-session lifecycle
1426         * metrics.
1427         *
1428         * @return true if notification listening can be attempted with the current dialect and runtime
1429         * @since 4.6.0
1430         */
1431        @NonNull
1432        public Boolean isNotificationListeningSupported() {
1433                return getDatabaseDialect().notificationSupport().isReceiveRuntimeAvailable();
1434        }
1435
1436        static void drainStatementResults(@NonNull PreparedStatement preparedStatement,
1437                        boolean resultAvailable) throws SQLException {
1438                requireNonNull(preparedStatement);
1439
1440                for (;;) {
1441                        if (resultAvailable) {
1442                                ResultSet resultSet = preparedStatement.getResultSet();
1443                                Throwable resultSetFailure = null;
1444                                try {
1445                                        if (resultSet != null) {
1446                                                while (resultSet.next()) {
1447                                                        // Drain every row before advancing to a possible subsequent result.
1448                                                }
1449                                        }
1450                                } catch (SQLException | RuntimeException | Error failure) {
1451                                        resultSetFailure = failure;
1452                                        throw failure;
1453                                } finally {
1454                                        JdbcResources.close(resultSet, resultSetFailure);
1455                                }
1456                        } else if (preparedStatement.getUpdateCount() == -1) {
1457                                break;
1458                        }
1459
1460                        resultAvailable = preparedStatement.getMoreResults(java.sql.Statement.CLOSE_CURRENT_RESULT);
1461                }
1462        }
1463
1464        static boolean isNotificationStatementUnsupported(@Nullable Throwable throwable) {
1465                return NotificationSessionRunner.isNotificationStatementUnsupported(throwable);
1466        }
1467
1468        @NonNull
1469        private String notificationServerCapabilityUnavailableMessage(@NonNull DatabaseType databaseType) {
1470                return NotificationSessionRunner.notificationServerCapabilityUnavailableMessage(databaseType);
1471        }
1472
1473        boolean hasDefaultPreparedStatementSettings() {
1474                return this.queryTimeout != null || this.fetchSize != null || this.maxRows != null;
1475        }
1476
1477        void applyDefaultPreparedStatementSettings(@NonNull PreparedStatement preparedStatement) throws SQLException {
1478                requireNonNull(preparedStatement);
1479                applyPreparedStatementSettings(preparedStatement, this.queryTimeout, this.fetchSize, this.maxRows);
1480        }
1481
1482        static void applyPreparedStatementSettings(@NonNull PreparedStatement preparedStatement,
1483                                                                                                                                                                                                                 @Nullable Duration queryTimeout,
1484                                                                                                                                                                                                                 @Nullable Integer fetchSize,
1485                                                                                                                                                                                                                 @Nullable Integer maxRows) throws SQLException {
1486                requireNonNull(preparedStatement);
1487
1488                if (queryTimeout != null)
1489                        preparedStatement.setQueryTimeout(queryTimeoutSeconds(queryTimeout));
1490
1491                if (fetchSize != null)
1492                        preparedStatement.setFetchSize(fetchSize);
1493
1494                if (maxRows != null)
1495                        preparedStatement.setMaxRows(maxRows);
1496        }
1497
1498        @FunctionalInterface
1499        interface InternalRawConnectionOperation<R> {
1500                @NonNull
1501                Optional<R> perform(@NonNull Connection connection) throws Exception;
1502        }
1503
1504        /**
1505         * Gets the database type configured when this database was built.
1506         *
1507         * @return the configured database type
1508         * @since 3.0.0
1509         */
1510        @NonNull
1511        public DatabaseType getDatabaseType() {
1512                return this.databaseType;
1513        }
1514
1515        @NonNull
1516        DatabaseDialect getDatabaseDialect() {
1517                return this.databaseDialect;
1518        }
1519
1520        /**
1521         * @since 3.0.0
1522         */
1523        @NonNull
1524        public ZoneId getTimeZone() {
1525                return this.timeZone;
1526        }
1527
1528        /**
1529         * How should Pyranid bind {@link java.time.Instant} and {@link java.time.OffsetDateTime} parameters when JDBC
1530         * parameter metadata cannot identify whether the target is {@code TIMESTAMP} or {@code TIMESTAMP WITH TIME ZONE}?
1531         *
1532         * @return behavior to use when timestamp target metadata is unavailable or non-identifying
1533         * @since 4.2.0
1534         */
1535        @NonNull
1536        public AmbiguousTimestampBindingStrategy getAmbiguousTimestampBindingStrategy() {
1537                return this.ambiguousTimestampBindingStrategy;
1538        }
1539
1540        /**
1541         * Gets the configured redactor used for non-secure parameters in diagnostics.
1542         *
1543         * @return the configured parameter redactor
1544         * @since 4.4.0
1545         */
1546        @NonNull
1547        public ParameterRedactor getParameterRedactor() {
1548                return this.parameterRedactor;
1549        }
1550
1551        /**
1552         * Useful for single-shot "utility" calls that operate outside of normal query operations, e.g. pulling DB metadata.
1553         * <p>
1554         * Example: {@link #readDatabaseMetaData(DatabaseMetaDataReader)}.
1555         */
1556        @NonNull
1557        <R> Optional<R> performRawConnectionOperation(@NonNull InternalRawConnectionOperation<R> rawConnectionOperation,
1558                                                                                                                                                                                                                                        @NonNull Boolean shouldParticipateInExistingTransactionIfPossible) {
1559                requireNonNull(rawConnectionOperation);
1560                requireNonNull(shouldParticipateInExistingTransactionIfPossible);
1561
1562                if (shouldParticipateInExistingTransactionIfPossible) {
1563                        Optional<Transaction> transaction = currentTransactionForDatabaseOperation();
1564                        ReentrantLock connectionLock = transaction.isPresent() ? transaction.get().getConnectionLock() : null;
1565                        // Try to participate in txn if it's available
1566                        Connection connection = null;
1567                        Throwable thrown = null;
1568                        boolean connectionLockAcquired = false;
1569
1570                        try {
1571                                if (connectionLock != null) {
1572                                        lockInterruptibly(connectionLock, "use the transaction connection for a raw connection operation");
1573                                        connectionLockAcquired = true;
1574                                }
1575
1576                                if (transaction.isPresent()) {
1577                                        connection = transaction.get().getConnection();
1578                                } else {
1579                                        try {
1580                                                connection = getDataSource().getConnection();
1581                                        } catch (SQLException e) {
1582                                                throw DatabaseException.wrapSafely("Unable to acquire database connection", e,
1583                                                                this.databaseDialect);
1584                                        }
1585                                }
1586
1587                                if (transaction.isPresent()) transaction.get().requireCompletionValidation();
1588                                return rawConnectionOperation.perform(connection);
1589                        } catch (DatabaseException e) {
1590                                thrown = e;
1591                                if (connection != null && transaction.isPresent()) transaction.get().recordSuspectFailure(e);
1592                                throw e;
1593                        } catch (Error e) {
1594                                thrown = e;
1595                                if (connection != null && transaction.isPresent()) transaction.get().recordSuspectFailure(e);
1596                                throw e;
1597                        } catch (Exception e) {
1598                                DatabaseException wrapped = databaseExceptionWithRawConnectionContext(e);
1599                                thrown = wrapped;
1600                                if (connection != null && transaction.isPresent()) transaction.get().recordSuspectFailure(wrapped);
1601                                throw wrapped;
1602                        } finally {
1603                                Throwable cleanupFailure = null;
1604
1605                                try {
1606                                        // If this was a single-shot operation (not in a transaction), close the connection
1607                                        if (connection != null && !transaction.isPresent()) {
1608                                                try {
1609                                                        closeConnection(connection, this.databaseDialect);
1610                                                } catch (Throwable cleanupException) {
1611                                                        cleanupFailure = cleanupException;
1612                                                }
1613                                        }
1614                                } finally {
1615                                        if (connectionLockAcquired)
1616                                                connectionLock.unlock();
1617
1618                                        Throwable exitThrown = thrown;
1619
1620                                        if (cleanupFailure != null) {
1621                                                if (thrown != null) {
1622                                                        appendCleanupFailure(thrown, cleanupFailure);
1623                                                } else {
1624                                                        exitThrown = cleanupFailure instanceof RuntimeException || cleanupFailure instanceof Error
1625                                                                        ? cleanupFailure : new RuntimeException(cleanupFailure);
1626                                                }
1627                                        }
1628
1629                                        // Closing the borrowed connection can introduce interruption after the operation's catch block, and a
1630                                        // cleanup failure can replace the primary failure outright. Restore from the failure that actually exits,
1631                                        // and only outside a transaction: publishing the interrupt here would abort an ambient transaction's next
1632                                        // statement on this thread, on a failure the caller handles.
1633                                        if (exitThrown != null && transaction.isEmpty())
1634                                                restoreInterruptIfNeeded(exitThrown);
1635
1636                                        if (thrown == null && exitThrown != null) {
1637                                                if (exitThrown instanceof Error error)
1638                                                        throw error;
1639
1640                                                throw (RuntimeException) exitThrown;
1641                                        }
1642                                }
1643                        }
1644                } else {
1645                        boolean acquiredConnection = false;
1646                        Connection connection = null;
1647                        Throwable thrown = null;
1648
1649                        // Always get a fresh connection no matter what and close it afterwards
1650                        try {
1651                                connection = getDataSource().getConnection();
1652                                acquiredConnection = true;
1653                                return rawConnectionOperation.perform(connection);
1654                        } catch (DatabaseException e) {
1655                                thrown = e;
1656                                throw e;
1657                        } catch (Error e) {
1658                                thrown = e;
1659                                throw e;
1660                        } catch (Exception e) {
1661                                DatabaseException wrapped = acquiredConnection
1662                                                ? databaseExceptionWithRawConnectionContext(e)
1663                                                : DatabaseException.wrapSafely("Unable to acquire database connection", e,
1664                                                                this.databaseDialect);
1665                                thrown = wrapped;
1666                                throw wrapped;
1667                        } finally {
1668                                Throwable exitThrown = thrown;
1669
1670                                if (connection != null) {
1671                                        try {
1672                                                closeConnection(connection, this.databaseDialect);
1673                                        } catch (Throwable cleanupException) {
1674                                                if (thrown != null) {
1675                                                        appendCleanupFailure(thrown, cleanupException);
1676                                                } else {
1677                                                        exitThrown = cleanupException instanceof RuntimeException || cleanupException instanceof Error
1678                                                                        ? cleanupException : new RuntimeException(cleanupException);
1679                                                }
1680                                        }
1681                                }
1682
1683                                // Closing the borrowed connection can introduce interruption after the operation's catch block, and a
1684                                // cleanup failure can replace the primary failure outright. Restore from the failure that actually exits,
1685                                // and only outside a transaction: this branch never participates, but an ambient transaction on this thread
1686                                // must not have its next statement aborted here.
1687                                if (exitThrown != null && !hasAmbientTransaction())
1688                                        restoreInterruptIfNeeded(exitThrown);
1689
1690                                if (thrown == null && exitThrown != null) {
1691                                        if (exitThrown instanceof Error error)
1692                                                throw error;
1693
1694                                        throw (RuntimeException) exitThrown;
1695                                }
1696                        }
1697                }
1698        }
1699
1700        @NonNull
1701        DataSource getDataSource() {
1702                return this.dataSource;
1703        }
1704
1705        @NonNull
1706        InstanceProvider getInstanceProvider() {
1707                return this.instanceProvider;
1708        }
1709
1710        @NonNull
1711        ResultSetMapper getResultSetMapper() {
1712                return this.resultSetMapper;
1713        }
1714
1715        @NonNull
1716        public MetricsCollector getMetricsCollector() {
1717                return getMetricsCollectorDispatcher().getMetricsCollector();
1718        }
1719
1720        @NonNull
1721        MetricsCollectorDispatcher getMetricsCollectorDispatcher() {
1722                return this.metricsCollectorDispatcher;
1723        }
1724
1725        @NonNull
1726        Object generateId() {
1727                // "Unique" keys
1728                return this.defaultIdGenerator.incrementAndGet();
1729        }
1730
1731        /**
1732         * Builder used to construct instances of {@link Database}.
1733         * <p>
1734         * This class is intended for use by a single thread.
1735         *
1736         * @author <a href="https://www.revetkn.com">Mark Allen</a>
1737         * @since 1.0.0
1738         */
1739        @NotThreadSafe
1740        public static class Builder {
1741                @NonNull
1742                private final DataSource dataSource;
1743                @NonNull
1744                private final DatabaseType databaseType;
1745                @Nullable
1746                private ZoneId timeZone;
1747                @Nullable
1748                private AmbiguousTimestampBindingStrategy ambiguousTimestampBindingStrategy;
1749                @Nullable
1750                private InstanceProvider instanceProvider;
1751                @Nullable
1752                private PreparedStatementBinder preparedStatementBinder;
1753                @Nullable
1754                private ResultSetMapper resultSetMapper;
1755                @Nullable
1756                private StatementLogger statementLogger;
1757                @Nullable
1758                private ParameterRedactor parameterRedactor;
1759                @Nullable
1760                private MetricsCollector metricsCollector;
1761                @Nullable
1762                private Duration queryTimeout;
1763                @Nullable
1764                private Integer fetchSize;
1765                @Nullable
1766                private Integer maxRows;
1767                @Nullable
1768                private Integer parsedSqlCacheCapacity;
1769
1770                private Builder(@NonNull DataSource dataSource, @NonNull DatabaseType databaseType) {
1771                        this.dataSource = requireNonNull(dataSource);
1772                        this.databaseType = requireNonNull(databaseType);
1773                        this.metricsCollector = null;
1774                        this.queryTimeout = null;
1775                        this.fetchSize = null;
1776                        this.maxRows = null;
1777                        this.parsedSqlCacheCapacity = null;
1778                }
1779
1780                /**
1781                 * Configures the database time zone Pyranid should use when converting zone-less temporal values.
1782                 * <p>
1783                 * This value is used when mapping {@code TIMESTAMP} values to instant-based Java types, and when binding
1784                 * {@link java.time.Instant} or {@link java.time.OffsetDateTime} parameters to known {@code TIMESTAMP}
1785                 * targets. It also applies to ambiguous timestamp bindings if
1786                 * {@link #ambiguousTimestampBindingStrategy(AmbiguousTimestampBindingStrategy)} is configured with
1787                 * {@link AmbiguousTimestampBindingStrategy#TIMESTAMP_WITHOUT_TIME_ZONE}.
1788                 * MySQL/MariaDB ambiguous instant-bearing parameters also use this zone. Local dates and date-times bound to
1789                 * known zoned timestamps are interpreted in this zone, as are zone-less results mapped to {@link java.sql.Timestamp}.
1790                 * <p>
1791                 * If {@code null}, Pyranid uses {@link ZoneId#systemDefault()}.
1792                 *
1793                 * @param timeZone database time zone to use, or {@code null} for the JVM default zone
1794                 * @return this {@code Builder}, for chaining
1795                 * @since 3.0.0
1796                 */
1797                @NonNull
1798                public Builder timeZone(@Nullable ZoneId timeZone) {
1799                        this.timeZone = timeZone;
1800                        return this;
1801                }
1802
1803                /**
1804                 * Configures how Pyranid binds {@link java.time.Instant} and {@link java.time.OffsetDateTime} parameters
1805                 * when JDBC parameter metadata cannot identify whether the target is {@code TIMESTAMP} or
1806                 * {@code TIMESTAMP WITH TIME ZONE}.
1807                 * <p>
1808                 * The default, {@link AmbiguousTimestampBindingStrategy#TIMESTAMP_WITH_TIME_ZONE}, is appropriate for
1809                 * timestamp-with-time-zone targets. Use
1810                 * {@link AmbiguousTimestampBindingStrategy#TIMESTAMP_WITHOUT_TIME_ZONE} for drivers or proxies that
1811                 * cannot provide identifying parameter metadata when your target columns are zone-less {@code TIMESTAMP}
1812                 * values that should be interpreted in {@link #timeZone(ZoneId)}.
1813                 * Non-timestamp metadata such as {@code VARCHAR} or {@code DATE} is also ambiguous for these values.
1814                 * MySQL and MariaDB prefer local timestamps in the configured zone regardless of this preference when the
1815                 * metadata does not positively identify a zoned timestamp. SQLite's zoned/ambiguous path uses canonical UTC text.
1816                 * Oracle's recognized internal metadata-parser failure refuses temporal binding when it removes identifying
1817                 * target metadata; this preference does not bypass that check. Use a target-family SQL cast or custom binder.
1818                 *
1819                 * @param ambiguousTimestampBindingStrategy strategy to use, or {@code null} for the default
1820                 * @return this {@code Builder}, for chaining
1821                 * @since 4.2.0
1822                 */
1823                @NonNull
1824                public Builder ambiguousTimestampBindingStrategy(@Nullable AmbiguousTimestampBindingStrategy ambiguousTimestampBindingStrategy) {
1825                        this.ambiguousTimestampBindingStrategy = ambiguousTimestampBindingStrategy;
1826                        return this;
1827                }
1828
1829                @NonNull
1830                public Builder instanceProvider(@Nullable InstanceProvider instanceProvider) {
1831                        this.instanceProvider = instanceProvider;
1832                        return this;
1833                }
1834
1835                @NonNull
1836                public Builder preparedStatementBinder(@Nullable PreparedStatementBinder preparedStatementBinder) {
1837                        this.preparedStatementBinder = preparedStatementBinder;
1838                        return this;
1839                }
1840
1841                @NonNull
1842                public Builder resultSetMapper(@Nullable ResultSetMapper resultSetMapper) {
1843                        this.resultSetMapper = resultSetMapper;
1844                        return this;
1845                }
1846
1847                /**
1848                 * Configures the statement logger for the {@link Database} being built.
1849                 * <p>
1850                 * {@link StatementLogger} failures are fail-fast: a logger exception can make a successful statement operation throw,
1851                 * and inside a Pyranid transaction it participates in normal rollback handling. If the database statement itself failed,
1852                 * logger failures are suppressed onto the primary statement failure.
1853                 *
1854                 * @param statementLogger statement logger to use, or {@code null} for a no-op logger
1855                 * @return this {@code Builder}, for chaining
1856                 */
1857                @NonNull
1858                public Builder statementLogger(@Nullable StatementLogger statementLogger) {
1859                        this.statementLogger = statementLogger;
1860                        return this;
1861                }
1862
1863                /**
1864                 * Configures the redactor used for non-secure parameters in diagnostics.
1865                 * <p>
1866                 * {@link SecureParameter} values always render via {@link SecureParameter#getMask()} and are never passed to this
1867                 * redactor. Batch executions render a bounded batch summary instead of invoking the redactor for each batch value.
1868                 * Specify {@code null} or omit this setter to render non-secure, non-batch values verbatim.
1869                 *
1870                 * @param parameterRedactor parameter redactor to use, or {@code null} for the default
1871                 * @return this {@code Builder}, for chaining
1872                 * @since 4.4.0
1873                 */
1874                @NonNull
1875                public Builder parameterRedactor(@Nullable ParameterRedactor parameterRedactor) {
1876                        this.parameterRedactor = parameterRedactor;
1877                        return this;
1878                }
1879
1880                /**
1881                 * Configures the metrics collector for the {@link Database} being built.
1882                 * <p>
1883                 * Like all {@code Database} configuration, this value is fixed at {@link #build()} time. Specify {@code null}
1884                 * or omit this setter to disable metrics collection.
1885                 *
1886                 * @param metricsCollector metrics collector to use, or {@code null} to disable
1887                 * @return this {@code Builder}, for chaining
1888                 * @since 4.2.0
1889                 */
1890                @NonNull
1891                public Builder metricsCollector(@Nullable MetricsCollector metricsCollector) {
1892                        this.metricsCollector = metricsCollector;
1893                        return this;
1894                }
1895
1896                /**
1897                 * Configures a database-wide JDBC query timeout default.
1898                 * <p>
1899                 * This maps to {@link java.sql.Statement#setQueryTimeout(int)}. {@code null} leaves the timeout unset.
1900                 * {@link Duration#ZERO} disables the JDBC timeout. Positive sub-second durations are rounded up to one second
1901                 * because JDBC accepts whole seconds. Per-query {@link Query#queryTimeout(Duration)} settings override this value,
1902                 * and {@link Query#customize(PreparedStatementCustomizer)} can override both settings before parameter binding.
1903                 *
1904                 * @param queryTimeout timeout to apply by default, or {@code null} to leave unset
1905                 * @return this {@code Builder}, for chaining
1906                 * @since 4.2.0
1907                 */
1908                @NonNull
1909                public Builder queryTimeout(@Nullable Duration queryTimeout) {
1910                        this.queryTimeout = validateQueryTimeout(queryTimeout);
1911                        return this;
1912                }
1913
1914                /**
1915                 * Configures a database-wide JDBC fetch size default.
1916                 * <p>
1917                 * This maps to {@link java.sql.Statement#setFetchSize(int)}. {@code null} leaves the fetch size unset. A value
1918                 * of {@code 0} uses the driver's default fetch-size behavior. Per-query {@link Query#fetchSize(Integer)}
1919                 * settings override this value, and {@link Query#customize(PreparedStatementCustomizer)} can override both
1920                 * settings before parameter binding.
1921                 * Streaming queries may replace this default with dialect streaming settings, including when it is zero.
1922                 * Use per-query {@code fetchSize(0)} to request driver-default stream behavior, which may buffer results.
1923                 * MySQL streams keep row streaming for positive hints unless Connector/J cursor fetching is positively enabled.
1924                 *
1925                 * @param fetchSize fetch size to apply by default, or {@code null} to leave unset
1926                 * @return this {@code Builder}, for chaining
1927                 * @since 4.2.0
1928                 */
1929                @NonNull
1930                public Builder fetchSize(@Nullable Integer fetchSize) {
1931                        this.fetchSize = validateNonNegativeStatementSetting("fetchSize", fetchSize);
1932                        return this;
1933                }
1934
1935                /**
1936                 * Configures a database-wide JDBC maximum row count default.
1937                 * <p>
1938                 * This maps to {@link java.sql.Statement#setMaxRows(int)}. {@code null} leaves the maximum row count unset. A
1939                 * value of {@code 0} disables the JDBC row limit. Per-query {@link Query#maxRows(Integer)} settings override
1940                 * this value, and {@link Query#customize(PreparedStatementCustomizer)} can override both settings before parameter
1941                 * binding.
1942                 *
1943                 * @param maxRows maximum rows to apply by default, or {@code null} to leave unset
1944                 * @return this {@code Builder}, for chaining
1945                 * @since 4.2.0
1946                 */
1947                @NonNull
1948                public Builder maxRows(@Nullable Integer maxRows) {
1949                        this.maxRows = validateNonNegativeStatementSetting("maxRows", maxRows);
1950                        return this;
1951                }
1952
1953                /**
1954                 * Configures the size of the parsed SQL cache.
1955                 * <p>
1956                 * A value of {@code 0} disables caching. A value of {@code null} uses the default size.
1957                 *
1958                 * @param parsedSqlCacheCapacity cache size (0 disables caching, null uses default)
1959                 * @return this {@code Builder}, for chaining
1960                 */
1961                @NonNull
1962                public Builder parsedSqlCacheCapacity(@Nullable Integer parsedSqlCacheCapacity) {
1963                        if (parsedSqlCacheCapacity != null && parsedSqlCacheCapacity < 0)
1964                                throw new IllegalArgumentException("parsedSqlCacheCapacity must be >= 0");
1965
1966                        this.parsedSqlCacheCapacity = parsedSqlCacheCapacity;
1967                        return this;
1968                }
1969
1970                @NonNull
1971                public Database build() {
1972                        return new Database(this);
1973                }
1974        }
1975
1976}