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.time.Duration;
025import java.util.ArrayList;
026import java.util.List;
027import java.util.Objects;
028import java.util.Optional;
029import java.util.stream.Collectors;
030
031import static java.lang.String.format;
032import static java.util.Objects.requireNonNull;
033
034/**
035 * A collection of SQL statement execution diagnostics.
036 *
037 * @author <a href="https://www.revetkn.com">Mark Allen</a>
038 * @since 1.0.0
039 */
040@ThreadSafe
041public final class StatementLog<T> {
042        @NonNull
043        private final StatementContext<T> statementContext;
044        @NonNull
045        private final Duration totalDuration;
046        @Nullable
047        private final Duration elapsedDuration;
048        @Nullable
049        private final Duration connectionAcquisitionDuration;
050        @Nullable
051        private final Duration preparationDuration;
052        @Nullable
053        private final Duration executionDuration;
054        @Nullable
055        private final Duration resultSetMappingDuration;
056        @Nullable
057        private final Integer batchSize;
058        @Nullable
059        private final Exception exception;
060
061        /**
062         * Creates a {@code StatementLog} for the given {@code builder}.
063         *
064         * @param builder the builder used to construct this {@code StatementLog}
065         */
066        private StatementLog(@NonNull Builder builder) {
067                requireNonNull(builder);
068
069                this.statementContext = requireNonNull(builder.statementContext);
070                this.connectionAcquisitionDuration = builder.connectionAcquisitionDuration;
071                this.preparationDuration = builder.preparationDuration;
072                this.executionDuration = builder.executionDuration;
073                this.resultSetMappingDuration = builder.resultSetMappingDuration;
074                this.batchSize = builder.batchSize;
075                this.exception = builder.exception;
076                this.elapsedDuration = builder.elapsedDuration;
077
078                Duration totalDuration = Duration.ZERO;
079
080                if (this.connectionAcquisitionDuration != null)
081                        totalDuration = totalDuration.plus(this.connectionAcquisitionDuration);
082
083                if (this.preparationDuration != null)
084                        totalDuration = totalDuration.plus(this.preparationDuration);
085
086                if (this.executionDuration != null)
087                        totalDuration = totalDuration.plus(this.executionDuration);
088
089                if (this.resultSetMappingDuration != null)
090                        totalDuration = totalDuration.plus(this.resultSetMappingDuration);
091
092                this.totalDuration = totalDuration;
093        }
094
095        /**
096         * Creates a {@link StatementLog} builder for the given {@code statementContext}.
097         *
098         * @param statementContext current SQL context
099         * @return a {@link StatementLog} builder
100         */
101        @NonNull
102        public static <T> Builder withStatementContext(@NonNull StatementContext<T> statementContext) {
103                requireNonNull(statementContext);
104                return new Builder(statementContext);
105        }
106
107        @Override
108        @NonNull
109        public String toString() {
110                List<String> components = new ArrayList<>(8);
111
112                components.add(format("statementContext=%s", getStatementContext()));
113                components.add(format("totalDuration=%s", getTotalDuration()));
114                getElapsedDuration().ifPresent(elapsed -> components.add(format("elapsedDuration=%s", elapsed)));
115
116                Duration connectionAcquisitionDuration = getConnectionAcquisitionDuration().orElse(null);
117
118                if (connectionAcquisitionDuration != null)
119                        components.add(format("connectionAcquisitionDuration=%s", connectionAcquisitionDuration));
120
121                Duration preparationDuration = getPreparationDuration().orElse(null);
122
123                if (preparationDuration != null)
124                        components.add(format("preparationDuration=%s", preparationDuration));
125
126                Duration executionDuration = getExecutionDuration().orElse(null);
127
128                if (executionDuration != null)
129                        components.add(format("executionDuration=%s", executionDuration));
130
131                Duration resultSetMappingDuration = getResultSetMappingDuration().orElse(null);
132
133                if (resultSetMappingDuration != null)
134                        components.add(format("resultSetMappingDuration=%s", resultSetMappingDuration));
135
136                Integer batchSize = getBatchSize().orElse(null);
137
138                if (batchSize != null)
139                        components.add(format("batchSize=%s", batchSize));
140
141                Exception exception = getException().orElse(null);
142
143                if (exception != null)
144                        components.add(format("exception=%s", exception));
145
146                return format("%s{%s}", getClass().getSimpleName(), components.stream().collect(Collectors.joining(", ")));
147        }
148
149        @Override
150        public boolean equals(@Nullable Object object) {
151                if (this == object)
152                        return true;
153
154                if (!(object instanceof StatementLog))
155                        return false;
156
157                StatementLog statementLog = (StatementLog) object;
158
159                return Objects.equals(getStatementContext(), statementLog.getStatementContext())
160                                && Objects.equals(getConnectionAcquisitionDuration(), statementLog.getConnectionAcquisitionDuration())
161                                && Objects.equals(getPreparationDuration(), statementLog.getPreparationDuration())
162                                && Objects.equals(getExecutionDuration(), statementLog.getExecutionDuration())
163                                && Objects.equals(getResultSetMappingDuration(), statementLog.getResultSetMappingDuration())
164                                && Objects.equals(getElapsedDuration(), statementLog.getElapsedDuration())
165                                && Objects.equals(getBatchSize(), statementLog.getBatchSize())
166                                && Objects.equals(getException(), statementLog.getException());
167        }
168
169        @Override
170        public int hashCode() {
171                return Objects.hash(getStatementContext(), getConnectionAcquisitionDuration(), getPreparationDuration(),
172                                getExecutionDuration(), getResultSetMappingDuration(), getElapsedDuration(), getBatchSize(), getException());
173        }
174
175        /**
176         * How long did it take to acquire a {@link java.sql.Connection} from the {@link javax.sql.DataSource}?
177         *
178         * @return how long it took to acquire a {@link java.sql.Connection}, if available
179         */
180        @NonNull
181        public Optional<Duration> getConnectionAcquisitionDuration() {
182                return Optional.ofNullable(this.connectionAcquisitionDuration);
183        }
184
185        /**
186         * How long did it take to bind data to the {@link java.sql.PreparedStatement}?
187         *
188         * @return how long it took to bind data to the {@link java.sql.PreparedStatement}, if available
189         */
190        @NonNull
191        public Optional<Duration> getPreparationDuration() {
192                return Optional.ofNullable(this.preparationDuration);
193        }
194
195        /**
196         * How long did it take to execute the SQL statement?
197         *
198         * @return how long it took to execute the SQL statement, if available
199         */
200        @NonNull
201        public Optional<Duration> getExecutionDuration() {
202                return Optional.ofNullable(this.executionDuration);
203        }
204
205        /**
206         * How long did it take to extract data from the {@link java.sql.ResultSet}?
207         *
208         * @return how long it took to extract data from the {@link java.sql.ResultSet}, if available
209         */
210        @NonNull
211        public Optional<Duration> getResultSetMappingDuration() {
212                return Optional.ofNullable(this.resultSetMappingDuration);
213        }
214
215        /**
216         * How long did it take to perform the database operation in total?
217         * <p>
218         * This is the sum of {@link #getConnectionAcquisitionDuration()} + {@link #getPreparationDuration()} +
219         * {@link #getExecutionDuration()} + {@link #getResultSetMappingDuration()}.
220         *
221         * @return how long the database operation took in total
222         */
223        @NonNull
224        public Duration getTotalDuration() {
225                return this.totalDuration;
226        }
227
228        /**
229         * Elapsed time from executor entry, before connection/lock acquisition, through resource cleanup.
230         * Includes consumer time while a stream remains open, and ends at stream exhaustion or explicit early closure.
231         * Later application callback work, SQL compilation, and terminal statement metrics/logger callbacks are excluded.
232         * This is measured independently of the active phase sum returned by {@link #getTotalDuration()}.
233         *
234         * @return elapsed duration, absent for manually constructed logs unless explicitly supplied
235         * @since 4.8.0
236         */
237        @NonNull
238        public Optional<Duration> getElapsedDuration() { return Optional.ofNullable(this.elapsedDuration); }
239
240        /**
241         * The SQL statement that was executed.
242         *
243         * @return the SQL statement that was executed.
244         */
245        @NonNull
246        public StatementContext<T> getStatementContext() {
247                return this.statementContext;
248        }
249
250        /**
251         * The size of the batch operation.
252         *
253         * @return how many records were processed as part of the batch operation, if available
254         */
255        @NonNull
256        public Optional<Integer> getBatchSize() {
257                return Optional.ofNullable(this.batchSize);
258        }
259
260        /**
261         * The exception that occurred during SQL statement execution.
262         *
263         * @return the exception that occurred during SQL statement execution, if available
264         */
265        @NonNull
266        public Optional<Exception> getException() {
267                return Optional.ofNullable(this.exception);
268        }
269
270        /**
271         * Builder used to construct instances of {@link StatementLog}.
272         * <p>
273         * This class is intended for use by a single thread.
274         *
275         * @author <a href="https://www.revetkn.com">Mark Allen</a>
276         * @since 1.0.0
277         */
278        @NotThreadSafe
279        public static class Builder<T> {
280                @NonNull
281                private final StatementContext<T> statementContext;
282                @Nullable
283                private Duration connectionAcquisitionDuration;
284                @Nullable
285                private Duration elapsedDuration;
286                @Nullable
287                private Duration preparationDuration;
288                @Nullable
289                private Duration executionDuration;
290                @Nullable
291                private Duration resultSetMappingDuration;
292                @Nullable
293                private Integer batchSize;
294                @Nullable
295                private Exception exception;
296
297                /**
298                 * Creates a {@code Builder} for the given {@code statementContext}.
299                 *
300                 * @param statementContext current SQL context
301                 */
302                private Builder(@NonNull StatementContext<T> statementContext) {
303                        requireNonNull(statementContext);
304                        this.statementContext = statementContext;
305                }
306
307                /**
308                 * Specifies how long it took to acquire a {@link java.sql.Connection} from the {@link javax.sql.DataSource}.
309                 *
310                 * @param connectionAcquisitionDuration how long it took to acquire a {@link java.sql.Connection}, if available
311                 * @return this {@code Builder}, for chaining
312                 */
313                @NonNull
314                public Builder connectionAcquisitionDuration(@Nullable Duration connectionAcquisitionDuration) {
315                        this.connectionAcquisitionDuration = connectionAcquisitionDuration;
316                        return this;
317                }
318
319                /**
320                 * Specifies how long it took to bind data to a {@link java.sql.PreparedStatement}.
321                 *
322                 * @param preparationDuration how long it took to bind data to a {@link java.sql.PreparedStatement}, if available
323                 * @return this {@code Builder}, for chaining
324                 */
325                @NonNull
326                public Builder preparationDuration(@Nullable Duration preparationDuration) {
327                        this.preparationDuration = preparationDuration;
328                        return this;
329                }
330
331                /**
332                 * Specifies how long it took to execute a SQL statement.
333                 *
334                 * @param executionDuration how long it took to execute a SQL statement, if available
335                 * @return this {@code Builder}, for chaining
336                 */
337                @NonNull
338                public Builder executionDuration(@Nullable Duration executionDuration) {
339                        this.executionDuration = executionDuration;
340                        return this;
341                }
342
343                /**
344                 * Specifies how long it took to extract data from a {@link java.sql.ResultSet}.
345                 *
346                 * @param resultSetMappingDuration how long it took to extract data from a {@link java.sql.ResultSet}, if available
347                 * @return this {@code Builder}, for chaining
348                 */
349                @NonNull
350                public Builder resultSetMappingDuration(@Nullable Duration resultSetMappingDuration) {
351                        this.resultSetMappingDuration = resultSetMappingDuration;
352                        return this;
353                }
354
355                /**
356                 * Supplies independently measured elapsed time; null leaves it absent.
357                 * @param elapsedDuration nonnegative elapsed duration, or null
358                 * @return this builder
359                 * @since 4.8.0
360                 */
361                @NonNull
362                public Builder elapsedDuration(@Nullable Duration elapsedDuration) {
363                        if (elapsedDuration != null && elapsedDuration.isNegative())
364                                throw new IllegalArgumentException("elapsedDuration must be >= 0");
365                        this.elapsedDuration = elapsedDuration;
366                        return this;
367                }
368
369                /**
370                 * Specifies the size of the batch operation.
371                 *
372                 * @param batchSize how many records were processed as part of the batch operation, if available
373                 * @return this {@code Builder}, for chaining
374                 */
375                @NonNull
376                public Builder batchSize(@Nullable Integer batchSize) {
377                        this.batchSize = batchSize;
378                        return this;
379                }
380
381                /**
382                 * Specifies the exception that occurred during SQL statement execution.
383                 *
384                 * @param exception the exception that occurred during SQL statement execution, if available
385                 * @return this {@code Builder}, for chaining
386                 */
387                @NonNull
388                public Builder exception(@Nullable Exception exception) {
389                        this.exception = exception;
390                        return this;
391                }
392
393                /**
394                 * Constructs a {@code StatementLog} instance.
395                 *
396                 * @return a {@code StatementLog} instance
397                 */
398                @NonNull
399                public StatementLog build() {
400                        return new StatementLog(this);
401                }
402        }
403}