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 java.util.Objects;
025import java.util.Optional;
026import java.util.function.Consumer;
027
028import static java.util.Objects.requireNonNull;
029
030/**
031 * Options for a Pyranid-managed transaction.
032 * <p>
033 * Use this when transaction behavior differs from the defaults. For example:
034 * <pre>{@code
035 * database.transaction(
036 *   TransactionOptions.withIsolation(TransactionIsolation.REPEATABLE_READ)
037 *     .readOnly(true)
038 *     .build(),
039 *   () -> {
040 *     // transactional work
041 *   });
042 * }</pre>
043 *
044 * @author <a href="https://www.revetkn.com">Mark Allen</a>
045 * @since 4.2.0
046 */
047@ThreadSafe
048public final class TransactionOptions {
049        @NonNull
050        static final TransactionOptions DEFAULT;
051
052        static {
053                DEFAULT = new TransactionOptions(TransactionIsolation.DEFAULT, null, null);
054        }
055
056        @NonNull
057        private final TransactionIsolation isolation;
058        @Nullable
059        private final Boolean readOnly;
060        @Nullable
061        private final Consumer<@NonNull TransactionCompletion> completionObserver;
062
063        private TransactionOptions(@NonNull TransactionIsolation isolation,
064                                                                                                                 @Nullable Boolean readOnly,
065                        @Nullable Consumer<@NonNull TransactionCompletion> completionObserver) {
066                requireNonNull(isolation);
067
068                this.isolation = isolation;
069                this.readOnly = readOnly;
070                this.completionObserver = completionObserver;
071        }
072
073        /**
074         * Starts building transaction options with a transaction isolation level.
075         *
076         * @param isolation the desired database transaction isolation level
077         * @return a transaction options builder
078         */
079        @NonNull
080        public static Builder withIsolation(@NonNull TransactionIsolation isolation) {
081                return new Builder().isolation(isolation);
082        }
083
084        /**
085         * Starts building transaction options with a read-only setting.
086         * <p>
087         * {@code true} requests a read-only transaction, {@code false} requests a read-write transaction, and {@code null}
088         * leaves the connection's read-only state unchanged.
089         * Drivers may reject changes on an open connection. In particular, SQLite's default JDBC configuration and
090         * DuckDB require read-only mode to be configured when opening the database connection. Use a separately
091         * configured read-only data source and leave this option {@code null} to inherit its state.
092         *
093         * @param readOnly read-only setting to apply
094         * @return a transaction options builder
095         */
096        @NonNull
097        public static Builder withReadOnly(@Nullable Boolean readOnly) {
098                return new Builder().readOnly(readOnly);
099        }
100
101        /**
102         * Gets the transaction isolation level.
103         *
104         * @return transaction isolation level
105         */
106        @NonNull
107        public TransactionIsolation getIsolation() {
108                return this.isolation;
109        }
110
111        /**
112         * Gets the read-only setting to apply, if any.
113         * <p>
114         * {@code true} requests a read-only transaction, {@code false} requests a read-write transaction, and empty leaves the
115         * connection's read-only state unchanged.
116         *
117         * @return read-only setting to apply
118         */
119        @NonNull
120        public Optional<Boolean> getReadOnly() {
121                return Optional.ofNullable(this.readOnly);
122        }
123
124        /**
125         * Gets the diagnostic observer invoked after connection cleanup and all post-transaction hooks.
126         *
127         * @return completion observer, if configured
128         * @since 4.8.0
129         */
130        @NonNull
131        public Optional<Consumer<@NonNull TransactionCompletion>> getCompletionObserver() {
132                return Optional.ofNullable(this.completionObserver);
133        }
134
135        @Override
136        public boolean equals(Object object) {
137                if (this == object)
138                        return true;
139
140                if (!(object instanceof TransactionOptions))
141                        return false;
142
143                TransactionOptions transactionOptions = (TransactionOptions) object;
144                return getIsolation() == transactionOptions.getIsolation()
145                                && Objects.equals(getReadOnly(), transactionOptions.getReadOnly())
146                                && Objects.equals(this.completionObserver, transactionOptions.completionObserver);
147        }
148
149        @Override
150        public int hashCode() {
151                return Objects.hash(getIsolation(), getReadOnly(), this.completionObserver);
152        }
153
154        @Override
155        @NonNull
156        public String toString() {
157                return String.format("%s{isolation=%s, readOnly=%s}",
158                                getClass().getSimpleName(), getIsolation().name(), getReadOnly().map(String::valueOf).orElse("unchanged"));
159        }
160
161        /**
162         * Builder used to construct {@link TransactionOptions}.
163         * <p>
164         * This class is intended for use by a single thread.
165         *
166         * @author <a href="https://www.revetkn.com">Mark Allen</a>
167         * @since 4.2.0
168         */
169        @NotThreadSafe
170        public static final class Builder {
171                @NonNull
172                private TransactionIsolation isolation;
173                @Nullable
174                private Boolean readOnly;
175                @Nullable
176                private Consumer<@NonNull TransactionCompletion> completionObserver;
177
178                private Builder() {
179                        this.isolation = TransactionIsolation.DEFAULT;
180                        this.readOnly = null;
181                }
182
183                /**
184                 * Configures the transaction isolation level.
185                 *
186                 * @param isolation the desired database transaction isolation level
187                 * @return this builder, for chaining
188                 */
189                @NonNull
190                public Builder isolation(@NonNull TransactionIsolation isolation) {
191                        requireNonNull(isolation);
192                        this.isolation = isolation;
193                        return this;
194                }
195
196                /**
197                 * Configures the transaction read-only setting.
198                 * <p>
199                 * {@code true} requests a read-only transaction, {@code false} requests a read-write transaction, and {@code null}
200                 * leaves the connection's read-only state unchanged.
201                 *
202                 * @param readOnly read-only setting to apply
203                 * @return this builder, for chaining
204                 */
205                @NonNull
206                public Builder readOnly(@Nullable Boolean readOnly) {
207                        this.readOnly = readOnly;
208                        return this;
209                }
210
211                /**
212                 * Configures diagnostic observation of each transaction boundary, including every retry attempt.
213                 * <p>
214                 * The observer runs synchronously after JDBC cleanup and all post-transaction hooks, before the transaction
215                 * method returns or throws. Its failure is contained and does not change the transaction result or retry
216                 * decisions. Use {@link Transaction#addPostTransactionOperation(Consumer)} for application hooks whose failures
217                 * should propagate. Observers must be fast and thread-safe when these options are shared across threads.
218                 * Argument validation failures before a transaction scope exists are not observed.
219                 *
220                 * @param completionObserver observer, or {@code null} to remove it
221                 * @return this builder, for chaining
222                 * @since 4.8.0
223                 */
224                @NonNull
225                public Builder completionObserver(@Nullable Consumer<@NonNull TransactionCompletion> completionObserver) {
226                        this.completionObserver = completionObserver;
227                        return this;
228                }
229
230                /**
231                 * Builds transaction options.
232                 *
233                 * @return transaction options
234                 */
235                @NonNull
236                public TransactionOptions build() {
237                        return new TransactionOptions(this.isolation, this.readOnly, this.completionObserver);
238                }
239        }
240}