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 every String metadata field
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.
166         * <p>
167         * The {@code message} is deliberately NOT re-scrubbed here: the caller is expected to have scrubbed the raw
168         * driver text before composing the message (scrubbing must run before whitespace-collapsing/truncation), and
169         * the composed remainder is Pyranid-rendered and already redaction-aware. Re-applying the redactor would
170         * re-scan mask text from the first pass, violating the documented one-pass "masks are never re-masked"
171         * semantics. Each metadata field, by contrast, is raw dialect-extracted text seen exactly once.
172         * <p>
173         * The {@code cause} chain is deliberately left untouched: sinks that render the stack trace or walk
174         * {@link #getCause()} can still observe the raw driver text.
175         */
176        DatabaseException(@Nullable String message,
177                                                                                @Nullable Throwable cause,
178                                                                                @NonNull DatabaseDialect databaseDialect,
179                                                                                @Nullable UnaryOperator<String> diagnosticRedactor) {
180                this(message, cause, databaseDialect, diagnosticRedactor, true);
181        }
182
183        /** Preserves a failure after driver diagnostic accessors have themselves failed. */
184        DatabaseException(@Nullable String message, @Nullable Throwable cause,
185                        @NonNull DatabaseDialect databaseDialect, @Nullable UnaryOperator<String> diagnosticRedactor,
186                        boolean inspectCause) {
187                super(message, cause);
188
189                Throwable diagnosticCause = inspectCause ? cause : null;
190                DatabaseExceptionMetadata metadata = databaseDialect.databaseExceptionMetadata(diagnosticCause);
191
192                this.errorCode = metadata.errorCode;
193                this.sqlState = applyDiagnosticRedactor(diagnosticRedactor, metadata.sqlState);
194                this.column = applyDiagnosticRedactor(diagnosticRedactor, metadata.column);
195                this.constraint = applyDiagnosticRedactor(diagnosticRedactor, metadata.constraint);
196                this.datatype = applyDiagnosticRedactor(diagnosticRedactor, metadata.datatype);
197                this.detail = applyDiagnosticRedactor(diagnosticRedactor, metadata.detail);
198                this.file = applyDiagnosticRedactor(diagnosticRedactor, metadata.file);
199                this.hint = applyDiagnosticRedactor(diagnosticRedactor, metadata.hint);
200                this.internalPosition = metadata.internalPosition;
201                this.internalQuery = applyDiagnosticRedactor(diagnosticRedactor, metadata.internalQuery);
202                this.line = metadata.line;
203                this.dbmsMessage = applyDiagnosticRedactor(diagnosticRedactor, metadata.dbmsMessage);
204                this.position = metadata.position;
205                this.routine = applyDiagnosticRedactor(diagnosticRedactor, metadata.routine);
206                this.schema = applyDiagnosticRedactor(diagnosticRedactor, metadata.schema);
207                this.severity = applyDiagnosticRedactor(diagnosticRedactor, metadata.severity);
208                this.table = applyDiagnosticRedactor(diagnosticRedactor, metadata.table);
209                this.where = applyDiagnosticRedactor(diagnosticRedactor, metadata.where);
210                this.uniqueConstraintViolation = databaseDialect.isUniqueConstraintViolation(metadata, diagnosticCause);
211                this.foreignKeyViolation = databaseDialect.isForeignKeyViolation(metadata, diagnosticCause);
212                this.deadlock = databaseDialect.isDeadlock(metadata, diagnosticCause);
213                this.transientException = databaseDialect.isTransient(metadata, diagnosticCause);
214                this.serializationFailure = databaseDialect.isSerializationFailure(metadata, diagnosticCause);
215                this.timeout = databaseDialect.isTimeout(metadata, diagnosticCause);
216                int inheritedOutcomes = TransactionRetrySafety.outcomesOf(cause);
217                this.transactionOutcomeCommitted = (inheritedOutcomes & TransactionRetrySafety.COMMITTED) != 0;
218                this.transactionOutcomeIndeterminate = (inheritedOutcomes & TransactionRetrySafety.IN_DOUBT) != 0;
219                this.statementDiagnosticsApplied = false;
220        }
221
222        DatabaseException(@Nullable String message,
223                                                                                @NonNull DatabaseException cause,
224                                                                                @Nullable UnaryOperator<String> diagnosticRedactor) {
225                super(message, cause);
226
227                this.errorCode = cause.errorCode;
228                this.sqlState = applyDiagnosticRedactor(diagnosticRedactor, cause.sqlState);
229                this.column = applyDiagnosticRedactor(diagnosticRedactor, cause.column);
230                this.constraint = applyDiagnosticRedactor(diagnosticRedactor, cause.constraint);
231                this.datatype = applyDiagnosticRedactor(diagnosticRedactor, cause.datatype);
232                this.detail = applyDiagnosticRedactor(diagnosticRedactor, cause.detail);
233                this.file = applyDiagnosticRedactor(diagnosticRedactor, cause.file);
234                this.hint = applyDiagnosticRedactor(diagnosticRedactor, cause.hint);
235                this.internalPosition = cause.internalPosition;
236                this.internalQuery = applyDiagnosticRedactor(diagnosticRedactor, cause.internalQuery);
237                this.line = cause.line;
238                this.dbmsMessage = applyDiagnosticRedactor(diagnosticRedactor, cause.dbmsMessage);
239                this.position = cause.position;
240                this.routine = applyDiagnosticRedactor(diagnosticRedactor, cause.routine);
241                this.schema = applyDiagnosticRedactor(diagnosticRedactor, cause.schema);
242                this.severity = applyDiagnosticRedactor(diagnosticRedactor, cause.severity);
243                this.table = applyDiagnosticRedactor(diagnosticRedactor, cause.table);
244                this.where = applyDiagnosticRedactor(diagnosticRedactor, cause.where);
245                this.uniqueConstraintViolation = cause.uniqueConstraintViolation;
246                this.foreignKeyViolation = cause.foreignKeyViolation;
247                this.deadlock = cause.deadlock;
248                this.transientException = cause.transientException;
249                this.serializationFailure = cause.serializationFailure;
250                this.timeout = cause.timeout;
251                this.transactionOutcomeCommitted = cause.transactionOutcomeCommitted;
252                this.transactionOutcomeIndeterminate = cause.transactionOutcomeIndeterminate;
253                this.statementDiagnosticsApplied = cause.statementDiagnosticsApplied;
254        }
255
256        void markTransactionOutcomeCommitted() {
257                this.transactionOutcomeCommitted = true;
258        }
259
260        boolean isTransactionOutcomeCommitted() {
261                return this.transactionOutcomeCommitted;
262        }
263
264        void markTransactionOutcomeIndeterminate() {
265                this.transactionOutcomeIndeterminate = true;
266        }
267
268        boolean isTransactionOutcomeIndeterminate() {
269                return this.transactionOutcomeIndeterminate;
270        }
271
272        boolean isTransactionOutcomeRetryUnsafe() {
273                return TransactionRetrySafety.outcomesOf(this) != 0;
274        }
275
276        void markStatementDiagnosticsApplied() {
277                this.statementDiagnosticsApplied = true;
278        }
279
280        boolean areStatementDiagnosticsApplied() {
281                return this.statementDiagnosticsApplied;
282        }
283
284        @Nullable
285        private static String applyDiagnosticRedactor(@Nullable UnaryOperator<String> diagnosticRedactor,
286                                                                                                                                                                                                @Nullable String value) {
287                return diagnosticRedactor == null || value == null ? value : diagnosticRedactor.apply(value);
288        }
289
290        @Override
291        public String toString() {
292                List<String> components = new ArrayList<>(20);
293
294                if (getMessage() != null && getMessage().trim().length() > 0)
295                        components.add(format("message=%s", getMessage().trim()));
296
297                if (getErrorCode().isPresent())
298                        components.add(format("errorCode=%s", getErrorCode().get()));
299                if (getSqlState().isPresent())
300                        components.add(format("sqlState=%s", getSqlState().get()));
301                if (getColumn().isPresent())
302                        components.add(format("column=%s", getColumn().get()));
303                if (getConstraint().isPresent())
304                        components.add(format("constraint=%s", getConstraint().get()));
305                if (getDatatype().isPresent())
306                        components.add(format("datatype=%s", getDatatype().get()));
307                if (getDetail().isPresent())
308                        components.add(format("detail=%s", getDetail().get()));
309                if (getFile().isPresent())
310                        components.add(format("file=%s", getFile().get()));
311                if (getHint().isPresent())
312                        components.add(format("hint=%s", getHint().get()));
313                if (getInternalPosition().isPresent())
314                        components.add(format("internalPosition=%s", getInternalPosition().get()));
315                if (getInternalQuery().isPresent())
316                        components.add(format("internalQuery=%s", getInternalQuery().get()));
317                if (getLine().isPresent())
318                        components.add(format("line=%s", getLine().get()));
319                if (getDbmsMessage().isPresent())
320                        components.add(format("dbmsMessage=%s", getDbmsMessage().get()));
321                if (getPosition().isPresent())
322                        components.add(format("position=%s", getPosition().get()));
323                if (getRoutine().isPresent())
324                        components.add(format("routine=%s", getRoutine().get()));
325                if (getSchema().isPresent())
326                        components.add(format("schema=%s", getSchema().get()));
327                if (getSeverity().isPresent())
328                        components.add(format("severity=%s", getSeverity().get()));
329                if (getTable().isPresent())
330                        components.add(format("table=%s", getTable().get()));
331                if (getWhere().isPresent())
332                        components.add(format("where=%s", getWhere().get()));
333
334                return format("%s: %s", getClass().getName(), components.stream().collect(Collectors.joining(", ")));
335        }
336
337        /**
338         * Shorthand for {@link SQLException#getErrorCode()} if this exception was caused by a {@link SQLException}.
339         *
340         * @return the value of {@link SQLException#getErrorCode()}, or empty if not available
341         */
342        @NonNull
343        public Optional<Integer> getErrorCode() {
344                return Optional.ofNullable(this.errorCode);
345        }
346
347        /**
348         * Shorthand for {@link SQLException#getSQLState()} if this exception was caused by a {@link SQLException}.
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 value of the offending {@code internalPosition}, or empty if not available
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 value of the offending {@code position}, or empty if not available
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}