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.ThreadSafe;
023import java.lang.reflect.Constructor;
024import java.lang.reflect.InvocationTargetException;
025import java.util.Arrays;
026import java.util.List;
027
028import static java.lang.String.format;
029import static java.util.Objects.requireNonNull;
030
031/**
032 * Contract for a factory that creates instances given a type.
033 * <p>
034 * Useful for resultset mapping, where each row in the resultset might require a new instance.
035 * <p>
036 * Implementors are suggested to employ application-specific strategies, such as having a DI container handle instance
037 * creation.
038 * <p>
039 * Implementations should be threadsafe.
040 *
041 * @author <a href="https://www.revetkn.com">Mark Allen</a>
042 * @since 1.0.0
043 */
044@ThreadSafe
045public interface InstanceProvider {
046        /**
047         * Provides an instance of the given {@code instanceType}.
048         * <p>
049         * Whether the instance is new every time or shared/reused is implementation-dependent.
050         *
051         * @param <T>          instance type token
052         * @param instanceType the type of instance to create
053         * @return an instance of the given {@code instanceType}
054         */
055        @NonNull
056        default <T> T provide(@NonNull StatementContext<T> statementContext,
057                                                                                                @NonNull Class<T> instanceType) {
058                requireNonNull(statementContext);
059                requireNonNull(instanceType);
060
061                try {
062                        return instanceType.getDeclaredConstructor().newInstance();
063                } catch (Exception e) {
064                        throw DatabaseException.wrapSafely(format(
065                                        "Unable to create an instance of %s. Please verify that %s has a public no-argument constructor",
066                                        instanceType, instanceType.getSimpleName()), e, DatabaseDialect.forExceptionCause(e));
067                }
068        }
069
070        /**
071         * Provides an instance of the given {@code recordType}.
072         * <p>
073         * Whether the instance is new every time or shared/reused is implementation-dependent.
074         *
075         * @param <T>        instance type token
076         * @param recordType the type of instance to create (must be a record)
077         * @param initargs   values used to construct the record instance
078         * @return an instance of the given {@code recordType}
079         * @since 2.0.0
080         */
081        @NonNull
082        default <T extends Record> T provideRecord(@NonNull StatementContext<T> statementContext,
083                                                                                                                                                                                 @NonNull Class<T> recordType,
084                                                                                                                                                                                 Object @Nullable ... initargs) {
085                requireNonNull(statementContext);
086                requireNonNull(recordType);
087
088                try {
089                        // Find the canonical constructor for the record.
090                        // Hat tip to https://stackoverflow.com/a/67127067
091                        Class<?>[] componentTypes = Arrays.stream(recordType.getRecordComponents())
092                                        .map(rc -> rc.getType())
093                                        .toArray(Class<?>[]::new);
094
095                        Constructor<T> constructor = recordType.getDeclaredConstructor(componentTypes);
096                        return constructor.newInstance(initargs);
097                } catch (NoSuchMethodException | InstantiationException | IllegalAccessException |
098                                                 IllegalArgumentException | InvocationTargetException e) {
099                        List<String> components = Arrays.stream(recordType.getRecordComponents())
100                                        .map(component -> component.getName() + ":" + component.getType().getTypeName())
101                                        .toList();
102                        throw DatabaseException.wrapSafely(String.format("Unable to instantiate Record type %s with components %s",
103                                        recordType.getName(), components), e, DatabaseDialect.forExceptionCause(e));
104                }
105        }
106}