001package com.identityworksllc.iiq.common.query;
002
003import sailpoint.object.SailPointObject;
004
005import java.sql.PreparedStatement;
006import java.sql.SQLException;
007import java.sql.Timestamp;
008import java.sql.Types;
009import java.util.Date;
010
011/**
012 * Utility class for setting the parameters on a {@link java.sql.Statement} based on the input,
013 * invoking the typed setXYZ methods (e.g., setString for a string).
014 *
015 * Unrecognized input types will be set via `setString`.
016 */
017public class Parameters {
018    /**
019     * Sets up the parameter in the given PreparedStatement per the type
020     * of the input.
021     *
022     * @param stmt The PreparedStatement to wire up
023     * @param param The parameter number to wire up
024     * @param value The value of the parameter
025     * @throws SQLException on any database failures
026     */
027    private static void setupParameter(PreparedStatement stmt, int param, Object value) throws SQLException {
028        if (value == null) {
029            stmt.setNull(param, Types.VARCHAR);
030        } else if (value instanceof TimestampWithTimezone) {
031            stmt.setTimestamp(param, (Timestamp) value, ((TimestampWithTimezone) value).getZonedCalendar());
032        } else if (value instanceof Timestamp) {
033            stmt.setTimestamp(param, (Timestamp) value);
034        } else if (value instanceof Date) {
035            stmt.setDate(param, new java.sql.Date(((Date) value).getTime()));
036        } else if (value instanceof Long) {
037            stmt.setLong(param, (Long) value);
038        } else if (value instanceof Integer) {
039            stmt.setInt(param, (Integer) value);
040        } else if (value instanceof SailPointObject) {
041            stmt.setString(param, ((SailPointObject) value).getId());
042        } else {
043            stmt.setString(param, String.valueOf(value));
044        }
045    }
046
047    /**
048     * Set up the given parameters in the prepared statmeent
049     * @param stmt The statement
050     * @param parameters The parameters
051     * @throws SQLException if any failures occur setting parameters
052     */
053    public static void setupParameters(PreparedStatement stmt, Object[] parameters) throws SQLException {
054        if (parameters == null || parameters.length == 0) {
055            return;
056        }
057        int param = 1;
058        for (Object parameter : parameters) {
059            setupParameter(stmt, param, parameter);
060            param++;
061        }
062    }
063
064    /**
065     * Private utility constructor
066     */
067    private Parameters() {
068
069    }
070}