CachedPreparedStatement.java 6.69 KB
Newer Older
Matt Tucker's avatar
Matt Tucker committed
1 2 3 4 5
/**
 * $RCSfile$
 * $Revision: 3055 $
 * $Date: 2005-11-10 21:57:51 -0300 (Thu, 10 Nov 2005) $
 *
6
 * Copyright (C) 2004-2008 Jive Software. All rights reserved.
Matt Tucker's avatar
Matt Tucker committed
7
 *
8 9 10 11 12 13 14 15 16 17 18
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
Matt Tucker's avatar
Matt Tucker committed
19 20 21 22 23 24
 */

package org.jivesoftware.database;

import java.sql.PreparedStatement;
import java.sql.SQLException;
25 26 27 28 29 30
import java.sql.Types;
import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
Matt Tucker's avatar
Matt Tucker committed
31 32 33 34

/**
 * Allows PreparedStatement information to be cached. A prepared statement consists of
 * a SQL statement containing bind variables as well as variable values. For example,
35
 * the SQL statement <tt>"SELECT * FROM person WHERE age &gt; ?"</tt> would have the integer
Matt Tucker's avatar
Matt Tucker committed
36 37 38 39 40 41 42 43
 * variable <tt>18</tt> (which replaces the "?" chracter) to find all adults. This class
 * encapsulates both the SQL string and bind variable values so that actual
 * PreparedStatement can be created from that information later.
 *
 * @author Matt Tucker
 */
public class CachedPreparedStatement  {

44 45
	private static final Logger Log = LoggerFactory.getLogger(CachedPreparedStatement.class);

Matt Tucker's avatar
Matt Tucker committed
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
    private String sql;
    private List<Object> params;
    private List<Integer> types;

    /**
     * Constructs a new CachedPreparedStatement.
     */
    public CachedPreparedStatement() {
        params = new ArrayList<Object>();
        types = new ArrayList<Integer>();
    }

    /**
     * Constructs a new CachedPreparedStatement.
     *
     * @param sql the SQL.
     */
    public CachedPreparedStatement(String sql) {
        this();
        setSQL(sql);
    }

    /**
     * Returns the SQL.
     *
     * @return the SQL.
     */
    public String getSQL() {
        return sql;
    }

    /**
     * Sets the SQL.
     *
     * @param sql the SQL.
     */
    public void setSQL(String sql) {
        this.sql = sql;
    }

    /**
     * Adds a boolean parameter to the prepared statement.
     *
     * @param value the boolean value.
     */
    public void addBoolean(boolean value) {
        params.add(value);
        types.add(Types.BOOLEAN);
    }

    /**
     * Adds an integer parameter to the prepared statement.
     *
     * @param value the int value.
     */
    public void addInt(int value) {
        params.add(value);
        types.add(Types.INTEGER);
    }

    /**
     * Adds a long parameter to the prepared statement.
     *
     * @param value the long value.
     */
    public void addLong(long value) {
        params.add(value);
        types.add(Types.BIGINT);
    }

    /**
     * Adds a String parameter to the prepared statement.
     *
     * @param value the String value.
     */
    public void addString(String value) {
        params.add(value);
        types.add(Types.VARCHAR);
    }

    /**
     * Sets all parameters on the given PreparedStatement. The standard code block
     * for turning a CachedPreparedStatement into a PreparedStatement is as follows:
     *
     * <pre>
     * PreparedStatement pstmt = con.prepareStatement(cachedPstmt.getSQL());
     * cachedPstmt.setParams(pstmt);
     * </pre>
     *
     * @param pstmt the prepared statement.
     * @throws java.sql.SQLException if an SQL Exception occurs.
     */
    public void setParams(PreparedStatement pstmt) throws SQLException {
        for (int i=0; i<params.size(); i++) {
            Object param = params.get(i);
            int type = types.get(i);
            // Set param, noting fact that params start at 1 and not 0.
            switch(type) {
                case Types.INTEGER:
                    pstmt.setInt(i+1, (Integer)param);
                    break;
                case Types.BIGINT:
                    pstmt.setLong(i+1, (Long)param);
                    break;
                case Types.VARCHAR:
                    pstmt.setString(i+1, (String)param);
                    break;
                case Types.BOOLEAN:
                    pstmt.setBoolean(i+1, (Boolean)param);
            }
        }
    }

159 160
    @Override
	public boolean equals(Object object) {
Matt Tucker's avatar
Matt Tucker committed
161 162 163 164 165 166 167 168 169 170 171 172 173 174
        if (object == null) {
            return false;
        }
        if (!(object instanceof CachedPreparedStatement)) {
            return false;
        }
        if (this == object) {
            return true;
        }
        CachedPreparedStatement otherStmt = (CachedPreparedStatement)object;
        return (sql == null && otherStmt.sql == null) || sql != null && sql.equals(otherStmt.sql)
                && types.equals(otherStmt.types) && params.equals(otherStmt.params);
    }

175 176
    @Override
	public int hashCode() {
Matt Tucker's avatar
Matt Tucker committed
177 178 179 180 181 182 183 184 185
        int hashCode = 1;
        if (sql != null) {
            hashCode += sql.hashCode();
        }
        hashCode = hashCode * 31 + types.hashCode();
        hashCode = hashCode * 31 + params.hashCode();
        return hashCode;
    }

186 187
    @Override
	public String toString() {
Matt Tucker's avatar
Matt Tucker committed
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
        String toStringSql = sql;
        try {
            int index = toStringSql.indexOf('?');
            int count = 0;

            while (index > -1) {
                Object param = params.get(count);
                int type = types.get(count);
                String val = null;

                // Get param
                switch(type) {
                    case Types.INTEGER:
                        val = "" + param;
                        break;
                    case Types.BIGINT:
                        val = "" + param;
                        break;
                    case Types.VARCHAR:
                        val =  '\'' + (String) param + '\'';
                        break;
                    case Types.BOOLEAN:
                        val = "" + param;
                }

                toStringSql = toStringSql.substring(0, index) + val +
                        ((index == toStringSql.length() -1) ? "" : toStringSql.substring(index + 1));
                index = toStringSql.indexOf('?', index + val.length());
                count++;
            }
        }
        catch (Exception e) {
220
            Log.error(e.getMessage(), e);
Matt Tucker's avatar
Matt Tucker committed
221 222 223 224 225
        }

        return "CachedPreparedStatement{ sql=" + toStringSql + '}';
    }
}