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.ResultSet;
024import java.sql.SQLException;
025import java.util.List;
026import java.util.Locale;
027import java.util.Optional;
028
029import static java.util.Objects.requireNonNull;
030
031/**
032 * Contract for mapping a {@link ResultSet} row to the specified type.
033 * <p>
034 * A production-ready concrete implementation is available via the following static methods:
035 * <ul>
036 *   <li>{@link #withDefaultConfiguration()}</li>
037 *   <li>{@link #withPlanCachingEnabled(Boolean)} (builder)</li>
038 *   <li>{@link #withCustomColumnMappers(List)} (builder)</li>
039 *   <li>{@link #withNormalizationLocale(Locale)} (builder)</li>
040 * </ul>
041 * <p>
042 * How to acquire an instance:
043 * <pre>{@code  // With out-of-the-box defaults
044 * ResultSetMapper default = ResultSetMapper.withDefaultConfiguration();
045 *
046 * // Customized
047 * ResultSetMapper custom = ResultSetMapper.withPlanCachingEnabled(false)
048 *  .customColumnMappers(List.of(...))
049 *  .normalizationLocale(Locale.forLanguageTag("pt-BR"))
050 *  .build();}</pre> Or, implement your own: <pre>{@code  ResultSetMapper myImpl = new ResultSetMapper() {
051 *   @NonNull
052 *   @Override
053 *   public <T> Optional<T> map(
054 *     @NonNull StatementContext<T> statementContext,
055 *     @NonNull ResultSet resultSet,
056 *     @NonNull Class<T> resultSetRowType,
057 *     @NonNull InstanceProvider instanceProvider
058 *   ) throws SQLException {
059 *     // Pull data from resultSet and apply to a new instance of T
060 *     return Optional.empty();
061 *   }
062 * };}</pre>
063 *
064 * @author <a href="https://www.revetkn.com">Mark Allen</a>
065 * @since 1.0.0
066 */
067@FunctionalInterface
068public interface ResultSetMapper {
069        /**
070         * Maps the current row of {@code resultSet} to the result class indicated by {@code statementContext}.
071         *
072         * @param <T>              result instance type token
073         * @param statementContext current SQL context
074         * @param resultSet        provides raw row data to pull from
075         * @param resultSetRowType the type to which the {@link ResultSet} row should be marshaled
076         * @param instanceProvider instance-creation factory, used to instantiate {@code resultSetRowType} row objects
077         * @return an {@link Optional} containing an instance of the given {@code resultClass}, or {@link Optional#empty()} to indicate a {@code null} value
078         * @throws SQLException if an error occurs during mapping
079         */
080        @NonNull
081        <T> Optional<T> map(@NonNull StatementContext<T> statementContext,
082                                                                                        @NonNull ResultSet resultSet,
083                                                                                        @NonNull Class<T> resultSetRowType,
084                                                                                        @NonNull InstanceProvider instanceProvider) throws SQLException;
085
086        /**
087         * Default maximum number of cached row-mapping plans per result class.
088         */
089        @NonNull
090        Integer DEFAULT_PLAN_CACHE_CAPACITY = 1024;
091
092        /**
093         * Retained for source and binary compatibility. Preferred custom column mappers are not cached.
094         *
095         * @deprecated this value has no effect and will be removed in 5.0.0
096         */
097        @Deprecated(since = "4.5.0", forRemoval = true)
098        int DEFAULT_PREFERRED_COLUMN_MAPPER_CACHE_CAPACITY = 256;
099
100        /**
101         * Acquires a builder with the locale used for non-ASCII case normalization of JDBC column names.
102         * ASCII letters are folded independently of locale before locale-sensitive lowercasing.
103         *
104         * @param normalizationLocale the locale used after locale-independent ASCII folding
105         * @return a {@code Builder} for a concrete implementation
106         */
107        @NonNull
108        static Builder withNormalizationLocale(@NonNull Locale normalizationLocale) {
109                requireNonNull(normalizationLocale);
110                return new Builder().normalizationLocale(normalizationLocale);
111        }
112
113        /**
114         * Acquires a builder for a concrete implementation of this interface, specifying a {@link List} of custom column-specific mapping logic to apply, in priority order.
115         *
116         * @param customColumnMappers a {@link List} of custom column-specific mapping logic to apply, in priority order
117         * @return a {@code Builder} for a concrete implementation
118         */
119        @NonNull
120        static Builder withCustomColumnMappers(@NonNull List<@NonNull CustomColumnMapper> customColumnMappers) {
121                requireNonNull(customColumnMappers);
122                return new Builder().customColumnMappers(customColumnMappers);
123        }
124
125        /**
126         * Acquires a builder for a concrete implementation of this interface, specifying whether an internal "mapping plan" cache should be used to speed up {@link ResultSet} mapping.
127         * <p>
128         * Disabling plan caching is primarily useful for highly dynamic schemas; plans use the same mapping rules but are compiled without retention.
129         *
130         * @param planCachingEnabled whether an internal "mapping plan" cache should be used to speed up {@link ResultSet} mapping
131         * @return a {@code Builder} for a concrete implementation
132         */
133        @NonNull
134        static Builder withPlanCachingEnabled(@NonNull Boolean planCachingEnabled) {
135                requireNonNull(planCachingEnabled);
136                return new Builder().planCachingEnabled(planCachingEnabled);
137        }
138
139        /**
140         * Acquires a concrete implementation of this interface with out-of-the-box defaults.
141         * <p>
142         * The returned instance is thread-safe.
143         *
144         * @return a concrete implementation of this interface with out-of-the-box defaults
145         */
146        @NonNull
147        static ResultSetMapper withDefaultConfiguration() {
148                return new Builder().build();
149        }
150
151        /**
152         * Builder used to construct a standard implementation of {@link ResultSetMapper}.
153         * <p>
154         * This class is intended for use by a single thread.
155         *
156         * @author <a href="https://www.revetkn.com">Mark Allen</a>
157         * @since 3.0.0
158         */
159        @NotThreadSafe
160        class Builder {
161                @NonNull
162                Locale normalizationLocale;
163                @NonNull
164                List<@NonNull CustomColumnMapper> customColumnMappers;
165                @NonNull
166                Boolean planCachingEnabled;
167                @NonNull
168                Integer planCacheCapacity;
169                boolean failOnUnmappedColumns;
170                boolean detachLobValues;
171                @Nullable
172                Long maxLobBytes = 16L * 1024 * 1024;
173                @Nullable
174                Long maxLobCharacters = 8L * 1024 * 1024;
175
176                private Builder() {
177                        this.normalizationLocale = Locale.ROOT;
178                        this.customColumnMappers = List.of();
179                        this.planCachingEnabled = true;
180                        this.planCacheCapacity = DEFAULT_PLAN_CACHE_CAPACITY;
181                }
182
183                /**
184                 * Specifies the locale used for non-ASCII case normalization when matching JDBC column names to Java properties.
185                 * ASCII uppercase letters always fold to their ASCII lowercase equivalents before locale-sensitive lowercasing,
186                 * keeping identifiers such as {@code ID} stable under Turkish and Azerbaijani locales. This locale still affects
187                 * non-ASCII letters; the default is {@link Locale#ROOT}.
188                 *
189                 * @param normalizationLocale the locale used after locale-independent ASCII folding
190                 * @return this {@code Builder}, for chaining
191                 */
192                @NonNull
193                public Builder normalizationLocale(@NonNull Locale normalizationLocale) {
194                        requireNonNull(normalizationLocale);
195                        this.normalizationLocale = normalizationLocale;
196                        return this;
197                }
198
199                /**
200                 * Specifies a {@link List} of custom column-specific mapping logic to apply, in priority order.
201                 *
202                 * @param customColumnMappers a {@link List} of custom column-specific mapping logic to apply, in priority order
203                 * @return this {@code Builder}, for chaining
204                 */
205                @NonNull
206                public Builder customColumnMappers(@NonNull List<@NonNull CustomColumnMapper> customColumnMappers) {
207                        requireNonNull(customColumnMappers);
208                        this.customColumnMappers = customColumnMappers;
209                        return this;
210                }
211
212                /**
213                 * Specifies whether an internal "mapping plan" cache should be used to speed up {@link ResultSet} mapping.
214                 * <p>
215                 * Disabling plan caching is primarily useful for highly dynamic schemas; plans use the same mapping rules but are compiled without retention.
216                 *
217                 * @param planCachingEnabled whether an internal "mapping plan" cache should be used to speed up {@link ResultSet} mapping
218                 * @return this {@code Builder}, for chaining
219                 */
220                @NonNull
221                public Builder planCachingEnabled(@NonNull Boolean planCachingEnabled) {
222                        requireNonNull(planCachingEnabled);
223                        this.planCachingEnabled = planCachingEnabled;
224                        return this;
225                }
226
227                /**
228                 * Specifies the maximum number of row-mapping plans to cache per result class when plan caching is enabled.
229                 * <p>
230                 * Use {@code 0} for an unbounded cache.
231                 *
232                 * @param planCacheCapacity maximum number of cached plans per result class, or {@code 0} for unbounded.
233                 *                          Defaults to {@link #DEFAULT_PLAN_CACHE_CAPACITY}.
234                 * @return this {@code Builder}, for chaining
235                 */
236                @NonNull
237                public Builder planCacheCapacity(@NonNull Integer planCacheCapacity) {
238                        requireNonNull(planCacheCapacity);
239                        if (planCacheCapacity < 0)
240                                throw new IllegalArgumentException("Plan cache capacity must be >= 0");
241                        this.planCacheCapacity = planCacheCapacity;
242                        return this;
243                }
244
245                /**
246                 * Rejects source columns that do not match a writable bean property or record component by throwing
247                 * {@link DatabaseException} when the row is mapped.
248                 * Disabled by default. This checks by-name row mappings before built-in column bindings read values; it does not
249                 * require every target member to be selected. Map rows, scalar values, custom whole-row mappings,
250                 * and the direct single-STRUCT record fallback keep their existing mapping rules.
251                 * Validation runs when a row is mapped; empty result sets do not invoke the row mapper.
252                 *
253                 * @param failOnUnmappedColumns whether to reject unmatched source columns
254                 * @return this builder
255                 * @since 4.9.0
256                 */
257                @NonNull
258                public Builder failOnUnmappedColumns(@NonNull Boolean failOnUnmappedColumns) {
259                        this.failOnUnmappedColumns = requireNonNull(failOnUnmappedColumns);
260                        return this;
261                }
262
263                /**
264                 * Detaches LOBs exposed by native Map/Object mapping, including {@code Object}-typed bean properties
265                 * and record components, as byte arrays or Strings.
266                 * Disabled by default. BLOBs become {@code byte[]}; CLOBs, NCLOBs and SQLXML become
267                 * {@link String}. Existing byte/character materialization limits apply, including nested
268                 * Java arrays, collections and maps. Containers are copied without mutating driver values.
269                 * Explicit JDBC-handle targets and handled custom mapper results retain their ownership contract.
270                 *
271                 * @param detachLobValues whether native result values should detach LOBs
272                 * @return this builder
273                 * @since 4.9.0
274                 */
275                @NonNull
276                public Builder detachLobValues(@NonNull Boolean detachLobValues) {
277                        this.detachLobValues = requireNonNull(detachLobValues);
278                        return this;
279                }
280
281                /**
282                 * Limits each BLOB value materialized by the default mapper as {@code byte[]}.
283                 * Defaults to 16 MiB. The limit does not cover driver buffering, custom mappers,
284                 * ordinary binary columns, or the aggregate size of a result list.
285                 * This setter enables the binary limit even after {@link #unboundedLobMaterialization()}.
286                 *
287                 * @param maxLobBytes strictly positive maximum byte count
288                 * @return this builder
289                 * @since 4.8.0
290                 */
291                @NonNull
292                public Builder maxLobBytes(@NonNull Long maxLobBytes) {
293                        requireNonNull(maxLobBytes);
294                        if (maxLobBytes <= 0)
295                                throw new IllegalArgumentException("Maximum LOB bytes must be > 0");
296                        this.maxLobBytes = maxLobBytes;
297                        return this;
298                }
299
300                /**
301                 * Limits each CLOB/NCLOB value materialized by the default mapper as {@link String}, and SQLXML values
302                 * detached through {@link #detachLobValues(Boolean)}.
303                 * Defaults to 8,388,608 UTF-16 code units. The limit does not cover driver buffering,
304                 * custom mappers, ordinary character columns, or the aggregate size of a result list.
305                 * This setter enables the character limit even after {@link #unboundedLobMaterialization()}.
306                 *
307                 * @param maxLobCharacters strictly positive maximum UTF-16 code-unit count
308                 * @return this builder
309                 * @since 4.8.0
310                 */
311                @NonNull
312                public Builder maxLobCharacters(@NonNull Long maxLobCharacters) {
313                        requireNonNull(maxLobCharacters);
314                        if (maxLobCharacters <= 0)
315                                throw new IllegalArgumentException("Maximum LOB characters must be > 0");
316                        this.maxLobCharacters = maxLobCharacters;
317                        return this;
318                }
319
320                /**
321                 * Disables both configurable LOB limits. Java array and string size limits still apply.
322                 * Later calls to either finite-limit setter re-enable that limit independently.
323                 *
324                 * @return this builder
325                 * @since 4.8.0
326                 */
327                @NonNull
328                public Builder unboundedLobMaterialization() {
329                        this.maxLobBytes = null;
330                        this.maxLobCharacters = null;
331                        return this;
332                }
333
334                /**
335                 * Retained for source and binary compatibility. This setting has no effect.
336                 * <p>
337                 * Pyranid always evaluates applicable custom column mappers in their configured priority order. This method is
338                 * deprecated and will be removed in 5.0.0.
339                 *
340                 * @param preferredColumnMapperCacheCapacity ignored compatibility value; must be greater than or equal to {@code 0}
341                 * @return this {@code Builder}, for chaining
342                 */
343                @Deprecated(since = "4.5.0", forRemoval = true)
344                @NonNull
345                public Builder preferredColumnMapperCacheCapacity(@NonNull Integer preferredColumnMapperCacheCapacity) {
346                        requireNonNull(preferredColumnMapperCacheCapacity);
347                        if (preferredColumnMapperCacheCapacity < 0)
348                                throw new IllegalArgumentException("Preferred column mapper cache capacity must be >= 0");
349                        return this;
350                }
351
352                /**
353                 * Constructs a default {@code ResultSetMapper} instance.
354                 * <p>
355                 * The constructed instance is thread-safe.
356                 *
357                 * @return a {@code ResultSetMapper} instance
358                 */
359                @NonNull
360                public ResultSetMapper build() {
361                        return new DefaultResultSetMapper(this);
362                }
363        }
364}