/*
 * $Header: /home/cvs/commons/dbutils-1.0/ja/src/org/apache/commons/dbutils/QueryRunner.java,v 1.1.1.1 2004/02/13 10:02:04 hioki Exp $
 * $Revision: 1.1.1.1 $
 * $Date: 2004/02/13 10:02:04 $
 * 
 * ====================================================================
 *
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 2002-2003 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution, if
 *    any, must include the following acknowledgement:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgement may appear in the software itself,
 *    if and wherever such third-party acknowledgements normally appear.
 *
 * 4. The names "The Jakarta Project", "Commons", and "Apache Software
 *    Foundation" must not be used to endorse or promote products derived
 *    from this software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache"
 *    nor may "Apache" appear in their names without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 *
 */

package org.apache.commons.dbutils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.Arrays;

import javax.sql.DataSource;

/**
 * <code>ResultSet</code> をハンドルするプラグ化可能なストラテジーを持つ SQL の問い合わせを実行します。
 * このクラスはスレッドセーフです。
 * {@primary Executes SQL queries with pluggable strategies for handling 
 * <code>ResultSet</code>s.  This class is thread safe.}
 * 
 * @see ResultSetHandler
 * 
 * @author Henri Yandell
 * @author Juozas Baliuka
 * @author Steven Caswell
 * @author David Graham
 * @translator 小川 環
 * @editor 日置 聡
 * @status underproof
 * @update 2003/12/22
 */
public class QueryRunner {

    /**
     * 接続を取り出すためのデータソース。
     * {@primary The DataSource to retrieve connections from.}
     */
    protected DataSource ds = null;

    /**
     * QueryRunner のコンストラクタ。
     * {@primary Constructor for QueryRunner.}
     */
    public QueryRunner() {
        super();
    }

    /**
     * QueryRunnerのコンストラクタ。
     * <code>Connection</code> パラメータを使用しないメソッドでは、 この
     * <code>DataSource</code> から接続を取り出します。
     * {@primary Constructor for QueryRunner.  Methods that do not take a 
     * <code>Connection</code> parameter will retrieve connections from this
     * <code>DataSource</code>.}
     * 
     * @param ds 接続を取り出すためのデータソース。
     * {@primary The <code>DataSource</code> to retrieve connections from.}
     */
    public QueryRunner(DataSource ds) {
        super();
        this.ds = ds;
    }

    /**
     * <code>PreparedStatement</code> の置換パラメータに、 指定したオブジェクトを埋め込みます。
     * {@primary Fill the <code>PreparedStatement</code> replacement parameters with 
     * the given objects.}
     * @param stmt
     * @param params 問い合わせの置換パラメータ。 <code>null</code> は有効な値として通過されます。
     * {@primary Query replacement parameters; <code>null</code> is a valid
     * value to pass in.}
     * @throws SQLException
     */
    protected void fillStatement(PreparedStatement stmt, Object[] params)
        throws SQLException {

        if (params == null) {
            return;
        }

        for (int i = 0; i < params.length; i++) {
            if (params[i] != null) {
                stmt.setObject(i + 1, params[i]);
            } else {
                stmt.setNull(i + 1, Types.OTHER);
            }
        }
    }

    /**
     * このRunnerが使用している <code>DataSource</code> を返します。
     * {@primary Returns the <code>DataSource</code> this runner is using.}
     */
    public DataSource getDataSource() {
        return this.ds;
    }

    /**
     * 指定したSQLに対応する <code>PreparedStatement</code> オブジェクトを作成および初期化します。
     * <code>QueryRunner</code> のメソッドはステートメントを準備するのにこのメソッドを常に呼び出します。 
     * 必要であれば、PreparedStatement の特別なコンフィグレーションを提供するためにこのメソッドをサブクラスでオーバーライド可能です。 
     * この実装は、ただ単純に <code>conn.prepareStatement(sql)</code> を呼び出します。 
     * {@primary Factory method that creates and initializes a 
     * <code>PreparedStatement</code> object for the given SQL.  
     * <code>QueryRunner</code> methods always call this method to prepare 
     * statements for them.  Subclasses can override this method to provide 
     * special PreparedStatement configuration if needed.  This implementation
     * simply calls <code>conn.prepareStatement(sql)</code>.}
     *  
     * @param conn <code>PreparedStatement</code> を作成するために使用する <code>Connection</code>。
     * {@primary The <code>Connection</code> used to create the 
     * <code>PreparedStatement</code>}
     * @param sql 準備対象の SQL ステートメント。
     * {@primary The SQL statement to prepare.}
     * @return 初期化された <code>PreparedStatement</code>。
     * {@primary An initialized <code>PreparedStatement</code>.}
     * @throws SQLException
     */
    protected PreparedStatement prepareStatement(Connection conn, String sql)
        throws SQLException {
            
        return conn.prepareStatement(sql);
    }

    /**
     * 単一の置換パラメータを埋め込んだ SQL SELECT の問い合わせを実行します。
     * 呼び出し側では、接続の解放処理が課せられます。 
     * {@primary Execute an SQL SELECT query with a single replacement parameter.  The
     * caller is responsible for connection cleanup.}
     * 
     * @param conn 問い合わせを実行する接続。
     * {@primary The connection to execute the query in.}
     * @param sql 実行する問い合わせ。
     * {@primary The query to execute.}
     * @param param 置換パラメータ。
     * {@primary The replacement parameter.}
     * @param rsh 結果をオブジェクトに変換するハンドラ。
     * {@primary The handler that converts the results into an object.}
     * @return ハンドラによって返されるオブジェクト。
     * {@primary The object returned by the handler.}
     * @throws SQLException
     */
    public Object query(
        Connection conn,
        String sql,
        Object param,
        ResultSetHandler rsh)
        throws SQLException {

        return this.query(conn, sql, new Object[] { param }, rsh);
    }

    /**
     * 置換パラメータを埋め込んだ SQL SELECT の問い合わせを実行します。
     * 呼び出し側では、接続の解放処理が課せられます。
     * {@primary Execute an SQL SELECT query with replacement parameters.  The
     * caller is responsible for connection cleanup.}
     * 
     * @param conn 問い合わせを実行する接続。
     * {@primary The connection to execute the query in.}
     * @param sql 実行する問い合わせ。
     * {@primary The query to execute.}
     * @param params 置換パラメータ。
     * {@primary The replacement parameters.}
     * @param rsh 結果をオブジェクトに変換するハンドラ。
     * {@primary The handler that converts the results into an object.}
     * @return ハンドラによって返されるオブジェクト。
     * {@primary The object returned by the handler.}
     * @throws SQLException
     */
    public Object query(
        Connection conn,
        String sql,
        Object[] params,
        ResultSetHandler rsh)
        throws SQLException {

        PreparedStatement stmt = null;
        ResultSet rs = null;
        Object result = null;

        try {
            stmt = this.prepareStatement(conn, sql);
            this.fillStatement(stmt, params);

            rs = this.wrap(stmt.executeQuery());

            result = rsh.handle(rs);

        } catch (SQLException e) {
            this.rethrow(e, sql, params);

        } finally {
            DbUtils.close(rs);
            DbUtils.close(stmt);
        }

        return result;
    }

    /**
     * 置換パラメータが一切含まれない SQL SELECT の問い合わせを実行します。
     * 呼び出し側では、接続の解放処理が課せられます。
     * {@primary Execute an SQL SELECT query without any replacement parameters.  The
     * caller is responsible for connection cleanup.}
     * 
     * @param conn 問い合わせを実行する接続。
     * {@primary The connection to execute the query in.}
     * @param sql 実行する問い合わせ。
     * {@primary The query to execute.}
     * @param rsh 結果をオブジェクトに変換するハンドラ。
     * {@primary The handler that converts the results into an object.}
     * @return ハンドラによって返されるオブジェクト。
     * {@primary The object returned by the handler.}
     * @throws SQLException
     */
    public Object query(Connection conn, String sql, ResultSetHandler rsh)
        throws SQLException {

        return this.query(conn, sql, (Object[]) null, rsh);
    }

    /**
     * 単一の置換パラメータを含む、指定された SQL SELECT を実行します。
     * <code>Connection</code> は、コンストラクタでセットされた <code>DataSource</code> から取り出されます。 
     * {@primary Executes the given SELECT SQL with a single replacement parameter.
     * The <code>Connection</code> is retrieved from the
     * <code>DataSource</code> set in the constructor.}
     * 
     * @param sql 実行するSQLステートメント。
     * {@primary The SQL statement to execute.}
     * @param param 置換パラメータ。
     * {@primary The replacement parameter.}
     * @param rsh <code>ResultSet</code> から結果を格納したオブジェクトを作成するために使用されるハンドラ。 
     * {@primary The handler used to create the result object from the <code>ResultSet</code>.}
     * 
     * @return ハンドラによって生成されるオブジェクト。
     * {@primary An object generated by the handler.}
     * @throws SQLException
     */
    public Object query(String sql, Object param, ResultSetHandler rsh)
        throws SQLException {

        return this.query(sql, new Object[] { param }, rsh);
    }

    /**
     * 指定された SQL SELECT を実行し、結果を格納したオブジェクトを返します。
     * <code>Connection</code> は、コンストラクタでセットされた <code>DataSource</code> から取り出されます。 
     * {@primary Executes the given SELECT SQL query and returns a result object.
     * The <code>Connection</code> is retrieved from the 
     * <code>DataSource</code> set in the constructor.}
     * 
     * @param sql 実行するSQLステートメント。
     * {@primary The SQL statement to execute.}
     * @param params この配列とともにPreparedStatementのINパラメータを初期化します。
     * {@primary Initialize the PreparedStatement's IN parameters with 
     * this array.}
     * 
     * @param rsh <code>ResultSet</code> から結果を格納したオブジェクトを作成するために使用されるハンドラ。 
     * {@primary The handler used to create the result object from the <code>ResultSet</code>.}
     * 
     * @return ハンドラによって生成されるオブジェクト。
     * {@primary An object generated by the handler.}
     * @throws SQLException
     */
    public Object query(String sql, Object[] params, ResultSetHandler rsh)
        throws SQLException {

        Connection conn = this.ds.getConnection();

        try {
            return this.query(conn, sql, params, rsh);

        } finally {
            DbUtils.close(conn);
        }
    }

    /**
     * 指定された SQL SELECT を置換パラメータなしで実行します。
     * <code>Connection</code> は、コンストラクタでセットされた <code>DataSource</code> から取り出されます。 
     * {@primary Executes the given SELECT SQL without any replacement parameters.
     * The <code>Connection</code> is retrieved from the
     * <code>DataSource</code> set in the constructor.}
     * 
     * @param sql 実行するSQLステートメント。
     * {@primary The SQL statement to execute.}
     * @param rsh <code>ResultSet</code> から結果を格納したオブジェクトを作成するために使用されるハンドラ。 
     * {@primary The handler used to create the result object from the <code>ResultSet</code>.}
     * 
     * @return ハンドラによって生成されるオブジェクト。
     * {@primary An object generated by the handler.}
     * @throws SQLException
     */
    public Object query(String sql, ResultSetHandler rsh) throws SQLException {
        return this.query(sql, (Object[]) null, rsh);
    }

    /**
     * さらに有益なエラーメッセージを含む新規の例外をスローします
     * {@primary Throws a new exception with a more informative error message.}
     * 
     * @param cause 再スローされる際に、新規の例外へチェーンされる根本的な例外。
     * {@primary The original exception that will be chained to the new 
     * exception when it's rethrown. }
     * 
     * @param sql 例外発生時に実行した問い合わせ。
     * {@primary The query that was executing when the exception happened.}
     * 
     * @param params 問い合わせの置換パラメータ。 <code>null</code> は有効な値として通過されます。
     * {@primary The query replacement paramaters; <code>null</code> is a 
     * valid value to pass in.}
     * 
     * @throws SQLException
     */
    protected void rethrow(SQLException cause, String sql, Object[] params)
        throws SQLException {

        StringBuffer msg = new StringBuffer(cause.getMessage());

        msg.append(" Query: ");
        msg.append(sql);
        msg.append(" Parameters: ");

        if (params == null) {
            msg.append("[]");
        } else {
            msg.append(Arrays.asList(params));
        }

        SQLException e = new SQLException(msg.toString());
        e.setNextException(cause);

        throw e;
    }

    /**
     * この Runner がデータベース接続を取得するのに使用する <code>DataSource</code> をセットします。 
     * <code>Connection</code> を渡さない状態で、実行メソッドを使用するつもりであれば、 デフォルトコンストラクタを含め
     * Runner が作成した後、これを呼び出すようにすべきです。
     * {@primary Sets the <code>DataSource</code> this runner will use to get
     * database connections from.  This should be called after creating a
     * runner with the default constructor if you intend to use the
     * execute methods without passing in a <code>Connection</code>.}
     * 
     * @param dataSource 使用するデータソース。
     * {@primary The DataSource to use.}
     */
    public void setDataSource(DataSource dataSource) {
        this.ds = dataSource;
    }

    /**
     * 置換パラメータのない SQL INSERT、UPDATE、または、DELETE の問い合わせを実行します。
     * {@primary Execute an SQL INSERT, UPDATE, or DELETE query without replacement
     * parameters.}
     * 
     * @param conn 問い合わせを実行するのに使用する接続。
     * {@primary The connection to use to run the query.}
     * @param sql 実行するSQL。
     * {@primary The SQL to execute.}
     * @return 更新した行数。
     * {@primary The number of rows updated.}
     * @throws SQLException
     */
    public int update(Connection conn, String sql) throws SQLException {
        return this.update(conn, sql, (Object[]) null);
    }

    /**
     * 単一の置換パラメータを埋め込んだ SQL INSERT、UPDATE、または、DELETE の問い合わせを実行します。
     * {@primary Execute an SQL INSERT, UPDATE, or DELETE query with a single replacement
     * parameter.}
     * 
     * @param conn 問い合わせを実行するのに使用する接続。
     * {@primary The connection to use to run the query.}
     * @param sql 実行するSQL。
     * {@primary The SQL to execute.}
     * @param param 置換パラメータ。 
     * {@primary The replacement parameter.}
     * @return 更新した行数。
     * {@primary The number of rows updated.}
     * @throws SQLException
     */
    public int update(Connection conn, String sql, Object param)
        throws SQLException {

        return this.update(conn, sql, new Object[] { param });
    }

    /**
     * SQL INSERT、UPDATE、または、DELETE の問い合わせを実行します。
     * {@primary Execute an SQL INSERT, UPDATE, or DELETE query.}
     * 
     * @param conn 問い合わせを実行するのに使用する接続。
     * {@primary The connection to use to run the query.}
     * @param sql 実行するSQL。
     * {@primary The SQL to execute.}
     * @param params 置換パラメータ。
     * {@primary The query replacement parameters.}
     * @return 更新した行数。
     * {@primary The number of rows updated.}
     * @throws SQLException
     */
    public int update(Connection conn, String sql, Object[] params)
        throws SQLException {

        PreparedStatement stmt = null;
        int rows = 0;

        try {
            stmt = this.prepareStatement(conn, sql);
            this.fillStatement(stmt, params);

            rows = stmt.executeUpdate();

        } catch (SQLException e) {
            this.rethrow(e, sql, params);

        } finally {
            DbUtils.close(stmt);
        }

        return rows;
    }

    /**
     * 置換パラメータを含まない、指定された SQL INSERT、UPDATE、または、DELETE の問い合わせを実行します。
     * <code>Connection</code> は、コンストラクタでセットされた <code>DataSource</code> から取り出されます。
     * {@primary Executes the given INSERT, UPDATE, or DELETE SQL statement without
     * any replacement parameters. The <code>Connection</code> is retrieved 
     * from the <code>DataSource</code> set in the constructor.}
     * 
     * @param sql 実行するSQL文。
     * {@primary The SQL statement to execute.}
     * @throws SQLException
     * @return 更新した行数。
     * {@primary The number of rows updated.}
     */
    public int update(String sql) throws SQLException {
        return this.update(sql, (Object[]) null);
    }

    /**
     * 単一の置換パラメータを含む、指定された SQL INSERT、UPDATE、または、DELETE の問い合わせを実行します。
     * <code>Connection</code> は、コンストラクタでセットされた <code>DataSource</code> から取り出されます。
     * {@primary Executes the given INSERT, UPDATE, or DELETE SQL statement with
     * a single replacement parameter.  The <code>Connection</code> is 
     * retrieved from the <code>DataSource</code> set in the constructor.}
     * 
     * @param sql 実行するSQL文。
     * {@primary The SQL statement to execute.}
     * @param param 置換パラメータ。
     * {@primary The replacement parameter.}
     * @throws SQLException
     * @return 更新した行数。
     * {@primary The number of rows updated.}
     */
    public int update(String sql, Object param) throws SQLException {
        return this.update(sql, new Object[] { param });
    }

    /**
     * 指定された SQL INSERT、UPDATE、または、DELETE の問い合わせを実行します。
     * <code>Connection</code> は、コンストラクタでセットされた <code>DataSource</code> から取り出されます。
     * {@primary Executes the given INSERT, UPDATE, or DELETE SQL statement.  The 
     * <code>Connection</code> is retrieved from the <code>DataSource</code> 
     * set in the constructor.}
     * 
     * @param sql 実行するSQL文。
     * {@primary The SQL statement to execute.}
     * @param params PreparedStatement の IN (例. '?')パラメータを初期化します。
     * {@primary Initializes the PreparedStatement's IN (i.e. '?') parameters.}
     * @throws SQLException
     * @return 更新した行数。
     * {@primary The number of rows updated.}
     */
    public int update(String sql, Object[] params) throws SQLException {

        Connection conn = this.ds.getConnection();

        try {
            return this.update(conn, sql, params);

        } finally {
            DbUtils.close(conn);
        }
    }

    /**
     * <code>ResultSet</code> を処理する前に、デコレータによってラップします。
     * この実装は、デコレーションが施された状態でない限り、与えられた <code>ResultSet</code> を返します。 
     * {@primary Wrap the <code>ResultSet</code> in a decorator before processing it.
     * This implementation returns the <code>ResultSet</code> it is given
     * without any decoration.}
     *
     * <p>
     * 多くの場合、このメソッドの実装はこのように無名インナークラスの中でラップされます。
     * {@primary Often, the implementation of this method can be done in an anonymous 
     * inner class like this:}
     * </p>
     * <pre> 
     * QueryRunner run = new QueryRunner() {
     *     protected ResultSet wrap(ResultSet rs) {
     *         return StringTrimmedResultSet.wrap(rs);
     *     }
     * };
     * </pre>
     * 
     * @param rs デコレーションを施す <code>ResultSet</code>。 <code>null</code> ではいけません。
     * {@primary The <code>ResultSet</code> to decorate; never <code>null</code>.} 
     * @return デコレータによってラップされた <code>ResultSet</code>。
     * {@primary The <code>ResultSet</code> wrapped in some decorator. } 
     */
    protected ResultSet wrap(ResultSet rs) {
        return rs;
    }

}
