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 java.sql.SQLException;
024import java.util.ArrayList;
025import java.util.List;
026import java.util.Optional;
027import java.util.function.UnaryOperator;
028import java.util.stream.Collectors;
029
030import static java.lang.String.format;
031
032/**
033 * Thrown when an error occurs when interacting with a {@link Database}.
034 * <p>
035 * If the {@code cause} of this exception is a {@link SQLException}, the {@link #getErrorCode()} and {@link #getSqlState()}
036 * accessors are shorthand for retrieving the corresponding {@link SQLException} values.
037 *
038 * @author <a href="https://www.revetkn.com">Mark Allen</a>
039 * @since 1.0.0
040 */
041@NotThreadSafe
042public class DatabaseException extends RuntimeException {
043        private static final long serialVersionUID = 3913934772829113027L;
044
045        @Nullable
046        private final Integer errorCode;
047        @Nullable
048        private final String sqlState;
049        @Nullable
050        private final String column;
051        @Nullable
052        private final String constraint;
053        @Nullable
054        private final String datatype;
055        @Nullable
056        private final String detail;
057        @Nullable
058        private final String file;
059        @Nullable
060        private final String hint;
061        @Nullable
062        private final Integer internalPosition;
063        @Nullable
064        private final String internalQuery;
065        @Nullable
066        private final Integer line;
067        @Nullable
068        private final String dbmsMessage;
069        @Nullable
070        private final Integer position;
071        @Nullable
072        private final String routine;
073        @Nullable
074        private final String schema;
075        @Nullable
076        private final String severity;
077        @Nullable
078        private final String table;
079        @Nullable
080        private final String where;
081        @NonNull
082        private final Boolean uniqueConstraintViolation;
083        @NonNull
084        private final Boolean foreignKeyViolation;
085        @NonNull
086        private final Boolean deadlock;
087        @NonNull
088        private final Boolean transientException;
089        @NonNull
090        private final Boolean serializationFailure;
091        @NonNull
092        private final Boolean timeout;
093        private boolean transactionOutcomeCommitted;
094        private boolean transactionOutcomeIndeterminate;
095        private boolean statementDiagnosticsApplied;
096
097        /** Keeps diagnostic accessors from replacing the operation failure or bypassing cleanup. */
098        static DatabaseException wrapSafely(String message, Throwable cause, DatabaseDialect dialect) {
099                if (cause instanceof DatabaseException original) return original;
100                return wrapSafely(message, cause, dialect, null);
101        }
102
103        static DatabaseException wrapSafely(String message, Throwable cause, DatabaseDialect dialect,
104                        @Nullable UnaryOperator<String> diagnosticRedactor) {
105                try {
106                        return cause instanceof DatabaseException original
107                                        ? new DatabaseException(message, original, diagnosticRedactor)
108                                        : new DatabaseException(message, cause, dialect, diagnosticRedactor);
109                } catch (Throwable diagnosticFailure) {
110                        if (cause != diagnosticFailure) cause.addSuppressed(diagnosticFailure);
111                        // The original cause remains available, including retry-outcome and interruption evidence.
112                        // No driver metadata is inspected again, and no raw metadata bypasses diagnostic redaction.
113                        return new DatabaseException(message, cause, GenericDialect.INSTANCE, null, false);
114                }
115        }
116
117        static String messageSafely(Throwable cause, String fallback) {
118                try {
119                        String message = cause.getMessage();
120                        return message == null || message.trim().isEmpty() ? fallback : message;
121                } catch (Throwable diagnosticFailure) {
122                        if (cause != diagnosticFailure) cause.addSuppressed(diagnosticFailure);
123                        return fallback;
124                }
125        }
126
127        /**
128         * Creates a {@code DatabaseException} with the given {@code message}.
129         *
130         * @param message a message describing this exception
131         */
132        public DatabaseException(@Nullable String message) {
133                this(message, null);
134        }
135
136        /**
137         * Creates a {@code DatabaseException} which wraps the given {@code cause}.
138         *
139         * @param cause the cause of this exception
140         */
141        public DatabaseException(@Nullable Throwable cause) {
142                this(cause == null ? null : cause.getMessage(), cause);
143        }
144
145        /**
146         * Creates a {@code DatabaseException} which wraps the given {@code cause}.
147         *
148         * @param message a message describing this exception
149         * @param cause   the cause of this exception
150         */
151        public DatabaseException(@Nullable String message,
152                                                                                                         @Nullable Throwable cause) {
153                this(message, cause, DatabaseDialect.forExceptionCause(cause));
154        }
155
156        DatabaseException(@Nullable String message,
157                                                                                @Nullable Throwable cause,
158                                                                                @NonNull DatabaseDialect databaseDialect) {
159                this(message, cause, databaseDialect, null);
160        }
161
162        /**
163         * Package-private constructor which applies a best-effort diagnostic redactor to driver-text metadata fields
164         * extracted from the cause - used by {@link Database} to scrub verbatim occurrences of {@link SecureParameter}
165         * values that the database driver may have echoed into its error text. The operational SQLState code is preserved
166         * verbatim so classification and application error policies can inspect it independently of parameter text.
167         * <p>
168         * The {@code message} is deliberately NOT re-scrubbed here: the caller is expected to have scrubbed the raw
169         * driver text before composing the message (scrubbing must run before whitespace-collapsing/truncation), and
170         * the composed remainder is Pyranid-rendered and already redaction-aware. Re-applying the redactor would
171         * re-scan mask text from the first pass, violating the documented one-pass "masks are never re-masked"
172         * semantics. Each metadata field, by contrast, is raw dialect-extracted text seen exactly once.
173         * <p>
174         * The {@code cause} chain is deliberately left untouched: sinks that render the stack trace or walk
175         * {@link #getCause()} can still observe the raw driver text.
176         */
177        DatabaseException(@Nullable String message,
178                                                                                @Nullable Throwable cause,
179                                                                                @NonNull DatabaseDialect databaseDialect,
180                                                                                @Nullable UnaryOperator<String> diagnosticRedactor) {
181                this(message, cause, databaseDialect, diagnosticRedactor, true);
182        }
183
184        /** Preserves a failure after driver diagnostic accessors have themselves failed. */
185        DatabaseException(@Nullable String message, @Nullable Throwable cause,
186                        @NonNull DatabaseDialect databaseDialect, @Nullable UnaryOperator<String> diagnosticRedactor,
187                        boolean inspectCause) {
188                super(message, cause);
189
190                Throwable diagnosticCause = inspectCause ? cause : null;
191                DatabaseExceptionMetadata metadata = databaseDialect.databaseExceptionMetadata(diagnosticCause);
192
193                this.errorCode = metadata.errorCode;
194                this.sqlState = metadata.sqlState;
195                this.column = applyDiagnosticRedactor(diagnosticRedactor, metadata.column);
196                this.constraint = applyDiagnosticRedactor(diagnosticRedactor, metadata.constraint);
197                this.datatype = applyDiagnosticRedactor(diagnosticRedactor, metadata.datatype);
198                this.detail = applyDiagnosticRedactor(diagnosticRedactor, metadata.detail);
199                this.file = applyDiagnosticRedactor(diagnosticRedactor, metadata.file);
200                this.hint = applyDiagnosticRedactor(diagnosticRedactor, metadata.hint);
201                this.internalPosition = metadata.internalPosition;
202                this.internalQuery = applyDiagnosticRedactor(diagnosticRedactor, metadata.internalQuery);
203                this.line = metadata.line;
204                this.dbmsMessage = applyDiagnosticRedactor(diagnosticRedactor, metadata.dbmsMessage);
205                this.position = metadata.position;
206                this.routine = applyDiagnosticRedactor(diagnosticRedactor, metadata.routine);
207                this.schema = applyDiagnosticRedactor(diagnosticRedactor, metadata.schema);
208                this.severity = applyDiagnosticRedactor(diagnosticRedactor, metadata.severity);
209                this.table = applyDiagnosticRedactor(diagnosticRedactor, metadata.table);
210                this.where = applyDiagnosticRedactor(diagnosticRedactor, metadata.where);
211                this.uniqueConstraintViolation = databaseDialect.isUniqueConstraintViolation(metadata, diagnosticCause);
212                this.foreignKeyViolation = databaseDialect.isForeignKeyViolation(metadata, diagnosticCause);
213                this.deadlock = databaseDialect.isDeadlock(metadata, diagnosticCause);
214                this.transientException = databaseDialect.isTransient(metadata, diagnosticCause);
215                this.serializationFailure = databaseDialect.isSerializationFailure(metadata, diagnosticCause);
216                this.timeout = databaseDialect.isTimeout(metadata, diagnosticCause);
217                int inheritedOutcomes = TransactionRetrySafety.outcomesOf(cause);
218                this.transactionOutcomeCommitted = (inheritedOutcomes & TransactionRetrySafety.COMMITTED) != 0;
219                this.transactionOutcomeIndeterminate = (inheritedOutcomes & TransactionRetrySafety.IN_DOUBT) != 0;
220                this.statementDiagnosticsApplied = false;
221        }
222
223        DatabaseException(@Nullable String message,
224                                                                                @NonNull DatabaseException cause,
225                                                                                @Nullable UnaryOperator<String> diagnosticRedactor) {
226                super(message, cause);
227
228                this.errorCode = cause.errorCode;
229                this.sqlState = cause.sqlState;
230                this.column = applyDiagnosticRedactor(diagnosticRedactor, cause.column);
231                this.constraint = applyDiagnosticRedactor(diagnosticRedactor, cause.constraint);
232                this.datatype = applyDiagnosticRedactor(diagnosticRedactor, cause.datatype);
233                this.detail = applyDiagnosticRedactor(diagnosticRedactor, cause.detail);
234                this.file = applyDiagnosticRedactor(diagnosticRedactor, cause.file);
235                this.hint = applyDiagnosticRedactor(diagnosticRedactor, cause.hint);
236                this.internalPosition = cause.internalPosition;
237                this.internalQuery = applyDiagnosticRedactor(diagnosticRedactor, cause.internalQuery);
238                this.line = cause.line;
239                this.dbmsMessage = applyDiagnosticRedactor(diagnosticRedactor, cause.dbmsMessage);
240                this.position = cause.position;
241                this.routine = applyDiagnosticRedactor(diagnosticRedactor, cause.routine);
242                this.schema = applyDiagnosticRedactor(diagnosticRedactor, cause.schema);
243                this.severity = applyDiagnosticRedactor(diagnosticRedactor, cause.severity);
244                this.table = applyDiagnosticRedactor(diagnosticRedactor, cause.table);
245                this.where = applyDiagnosticRedactor(diagnosticRedactor, cause.where);
246                this.uniqueConstraintViolation = cause.uniqueConstraintViolation;
247                this.foreignKeyViolation = cause.foreignKeyViolation;
248                this.deadlock = cause.deadlock;
249                this.transientException = cause.transientException;
250                this.serializationFailure = cause.serializationFailure;
251                this.timeout = cause.timeout;
252                this.transactionOutcomeCommitted = cause.transactionOutcomeCommitted;
253                this.transactionOutcomeIndeterminate = cause.transactionOutcomeIndeterminate;
254                this.statementDiagnosticsApplied = cause.statementDiagnosticsApplied;
255        }
256
257        void markTransactionOutcomeCommitted() {
258                this.transactionOutcomeCommitted = true;
259        }
260
261        boolean isTransactionOutcomeCommitted() {
262                return this.transactionOutcomeCommitted;
263        }
264
265        void markTransactionOutcomeIndeterminate() {
266                this.transactionOutcomeIndeterminate = true;
267        }
268
269        boolean isTransactionOutcomeIndeterminate() {
270                return this.transactionOutcomeIndeterminate;
271        }
272
273        boolean isTransactionOutcomeRetryUnsafe() {
274                return TransactionRetrySafety.outcomesOf(this) != 0;
275        }
276
277        void markStatementDiagnosticsApplied() {
278                this.statementDiagnosticsApplied = true;
279        }
280
281        boolean areStatementDiagnosticsApplied() {
282                return this.statementDiagnosticsApplied;
283        }
284
285        @Nullable
286        private static String applyDiagnosticRedactor(@Nullable UnaryOperator<String> diagnosticRedactor,
287                                                                                                                                                                                                @Nullable String value) {
288                return diagnosticRedactor == null || value == null ? value : diagnosticRedactor.apply(value);
289        }
290
291        /**
292         * Renders general diagnostics without automatically appending server detail, hint, internal query or context.
293         * Explicit diagnostic accessors retain those fields; messages and original causes can still contain data.
294         *
295         * @return a diagnostic description
296         */
297        @Override
298        public String toString() {
299                List<String> components = new ArrayList<>(20);
300
301                if (getMessage() != null && getMessage().trim().length() > 0)
302                        components.add(format("message=%s", getMessage().trim()));
303
304                if (getErrorCode().isPresent())
305                        components.add(format("errorCode=%s", getErrorCode().get()));
306                if (getSqlState().isPresent())
307                        components.add(format("sqlState=%s", getSqlState().get()));
308                if (getColumn().isPresent())
309                        components.add(format("column=%s", getColumn().get()));
310                if (getConstraint().isPresent())
311                        components.add(format("constraint=%s", getConstraint().get()));
312                if (getDatatype().isPresent())
313                        components.add(format("datatype=%s", getDatatype().get()));
314                if (getFile().isPresent())
315                        components.add(format("file=%s", getFile().get()));
316                if (getInternalPosition().isPresent())
317                        components.add(format("internalPosition=%s", getInternalPosition().get()));
318                if (getLine().isPresent())
319                        components.add(format("line=%s", getLine().get()));
320                if (getDbmsMessage().isPresent())
321                        components.add(format("dbmsMessage=%s", getDbmsMessage().get()));
322                if (getPosition().isPresent())
323                        components.add(format("position=%s", getPosition().get()));
324                if (getRoutine().isPresent())
325                        components.add(format("routine=%s", getRoutine().get()));
326                if (getSchema().isPresent())
327                        components.add(format("schema=%s", getSchema().get()));
328                if (getSeverity().isPresent())
329                        components.add(format("severity=%s", getSeverity().get()));
330                if (getTable().isPresent())
331                        components.add(format("table=%s", getTable().get()));
332
333                return format("%s: %s", getClass().getName(), components.stream().collect(Collectors.joining(", ")));
334        }
335
336        /**
337         * Shorthand for {@link SQLException#getErrorCode()} if this exception was caused by a {@link SQLException}.
338         *
339         * @return the value of {@link SQLException#getErrorCode()}, or empty if not available
340         */
341        @NonNull
342        public Optional<Integer> getErrorCode() {
343                return Optional.ofNullable(this.errorCode);
344        }
345
346        /**
347         * Shorthand for {@link SQLException#getSQLState()} if this exception was caused by a {@link SQLException}.
348         * The available operational code is preserved verbatim; secure-parameter literal scrubbing does not modify it.
349         *
350         * @return the value of {@link SQLException#getSQLState()}, or empty if not available
351         */
352        @NonNull
353        public Optional<String> getSqlState() {
354                return Optional.ofNullable(this.sqlState);
355        }
356
357        /**
358         * Determines if this exception is recognized as a unique constraint violation.
359         * <p>
360         * This method is intentionally conservative: it returns {@code true} only when Pyranid recognizes a database-specific
361         * error code or SQLState as a unique or primary-key uniqueness violation.
362         *
363         * @return {@code true} if this exception is recognized as a unique constraint violation
364         * @since 4.3.0
365         */
366        @NonNull
367        public Boolean isUniqueConstraintViolation() {
368                return this.uniqueConstraintViolation;
369        }
370
371        /**
372         * Determines if this exception is recognized as a foreign-key violation.
373         * <p>
374         * This method is intentionally conservative: it returns {@code true} only when Pyranid recognizes a database-specific
375         * error code or SQLState as a foreign-key violation.
376         * For example, SQL Server error {@code 547} is not classified as a foreign-key violation by code alone because the
377         * same error code also covers other constraint failures, such as {@code CHECK} constraints.
378         *
379         * @return {@code true} if this exception is recognized as a foreign-key violation
380         * @since 4.3.0
381         */
382        @NonNull
383        public Boolean isForeignKeyViolation() {
384                return this.foreignKeyViolation;
385        }
386
387        /**
388         * Determines if this exception is recognized as a deadlock.
389         * <p>
390         * This method is intentionally conservative: it returns {@code true} only when Pyranid recognizes a database-specific
391         * error code or SQLState as a deadlock.
392         *
393         * @return {@code true} if this exception is recognized as a deadlock
394         * @since 4.3.0
395         */
396        @NonNull
397        public Boolean isDeadlock() {
398                return this.deadlock;
399        }
400
401        /**
402         * Determines if this exception is recognized as transient.
403         * <p>
404         * This method is intentionally conservative: it returns {@code true} for JDBC transient/recoverable exception classes,
405         * SQLState classes for connection exceptions and transaction rollbacks, or database-specific deadlock/lock-timeout
406         * signals recognized by Pyranid. A {@code true} result does not guarantee that retrying the operation will succeed.
407         *
408         * @return {@code true} if this exception is recognized as transient
409         * @since 4.3.0
410         */
411        @NonNull
412        public Boolean isTransient() {
413                return this.transientException;
414        }
415
416        /**
417         * Determines if this exception is recognized as a serialization failure.
418         * <p>
419         * This method is intentionally conservative: it returns {@code true} only when Pyranid recognizes a database-specific
420         * error code or SQLState as a serialization failure.
421         *
422         * @return {@code true} if this exception is recognized as a serialization failure
423         * @since 4.4.0
424         */
425        @NonNull
426        public Boolean isSerializationFailure() {
427                return this.serializationFailure;
428        }
429
430        /**
431         * Determines if this exception is recognized as a timeout or cancellation.
432         * <p>
433         * This method is intentionally conservative: it returns {@code true} only when Pyranid recognizes a JDBC timeout,
434         * database-specific timeout, or database-specific cancellation signal. A {@code true} result does not mean the operation
435         * is automatically safe to retry.
436         *
437         * @return {@code true} if this exception is recognized as a timeout or cancellation
438         * @since 4.4.0
439         */
440        @NonNull
441        public Boolean isTimeout() {
442                return this.timeout;
443        }
444
445        /**
446         * @return the value of the offending {@code column}, or empty if not available
447         * @since 1.0.12
448         */
449        @NonNull
450        public Optional<String> getColumn() {
451                return Optional.ofNullable(this.column);
452        }
453
454        /**
455         * @return the value of the offending {@code constraint}, or empty if not available
456         * @since 1.0.12
457         */
458        @NonNull
459        public Optional<String> getConstraint() {
460                return Optional.ofNullable(this.constraint);
461        }
462
463        /**
464         * @return the value of the offending {@code datatype}, or empty if not available
465         * @since 1.0.12
466         */
467        @NonNull
468        public Optional<String> getDatatype() {
469                return Optional.ofNullable(this.datatype);
470        }
471
472        /**
473         * @return the value of the offending {@code detail}, or empty if not available
474         * @since 1.0.12
475         */
476        @NonNull
477        public Optional<String> getDetail() {
478                return Optional.ofNullable(this.detail);
479        }
480
481        /**
482         * @return the value of the offending {@code file}, or empty if not available
483         * @since 1.0.12
484         */
485        @NonNull
486        public Optional<String> getFile() {
487                return Optional.ofNullable(this.file);
488        }
489
490        /**
491         * @return the value of the error {@code hint}, or empty if not available
492         * @since 1.0.12
493         */
494        @NonNull
495        public Optional<String> getHint() {
496                return Optional.ofNullable(this.hint);
497        }
498
499        /**
500         * @return the positive, one-based character position within the internal query, or empty if the server supplied none
501         * @since 1.0.12
502         */
503        @NonNull
504        public Optional<Integer> getInternalPosition() {
505                return Optional.ofNullable(this.internalPosition);
506        }
507
508        /**
509         * @return the value of the offending {@code internalQuery}, or empty if not available
510         * @since 1.0.12
511         */
512        @NonNull
513        public Optional<String> getInternalQuery() {
514                return Optional.ofNullable(this.internalQuery);
515        }
516
517        /**
518         * @return the value of the offending {@code line}, or empty if not available
519         * @since 1.0.12
520         */
521        @NonNull
522        public Optional<Integer> getLine() {
523                return Optional.ofNullable(this.line);
524        }
525
526        /**
527         * @return the value of the error {@code dbmsMessage}, or empty if not available
528         * @since 1.0.12
529         */
530        @NonNull
531        public Optional<String> getDbmsMessage() {
532                return Optional.ofNullable(this.dbmsMessage);
533        }
534
535        /**
536         * @return the positive, one-based character position within the submitted query, or empty if the server supplied none
537         * @since 1.0.12
538         */
539        @NonNull
540        public Optional<Integer> getPosition() {
541                return Optional.ofNullable(this.position);
542        }
543
544        /**
545         * @return the value of the offending {@code routine}, or empty if not available
546         * @since 1.0.12
547         */
548        @NonNull
549        public Optional<String> getRoutine() {
550                return Optional.ofNullable(this.routine);
551        }
552
553        /**
554         * @return the value of the offending {@code schema}, or empty if not available
555         * @since 1.0.12
556         */
557        @NonNull
558        public Optional<String> getSchema() {
559                return Optional.ofNullable(this.schema);
560        }
561
562        /**
563         * @return the error {@code severity}, or empty if not available
564         * @since 1.0.12
565         */
566        @NonNull
567        public Optional<String> getSeverity() {
568                return Optional.ofNullable(this.severity);
569        }
570
571        /**
572         * @return the value of the offending {@code table}, or empty if not available
573         * @since 1.0.12
574         */
575        @NonNull
576        public Optional<String> getTable() {
577                return Optional.ofNullable(this.table);
578        }
579
580        /**
581         * @return the value of the offending {@code where}, or empty if not available
582         * @since 1.0.12
583         */
584        @NonNull
585        public Optional<String> getWhere() {
586                return Optional.ofNullable(this.where);
587        }
588}