/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You 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.
 */

package org.apache.tomcat.dbcp.dbcp;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import java.util.NoSuchElementException;

import org.apache.tomcat.dbcp.pool.KeyedObjectPool;
import org.apache.tomcat.dbcp.pool.KeyedPoolableObjectFactory;

/**
 * A {@link DelegatingConnection} that pools {@link PreparedStatement}s.
 * <p>
 * The {@link #prepareStatement} and {@link #prepareCall} methods, rather than creating a new PreparedStatement
 * each time, may actually pull the statement from a pool of unused statements.
 * The {@link PreparedStatement#close} method of the returned statement doesn't
 * actually close the statement, but rather returns it to the pool.
 * (See {@link PoolablePreparedStatement}, {@link PoolableCallableStatement}.)
 *
 *
 * @see PoolablePreparedStatement
 * @author Rodney Waldhoff
 * @author Dirk Verbeeck
 */
public class PoolingConnection extends DelegatingConnection
        implements KeyedPoolableObjectFactory<PStmtKey, DelegatingPreparedStatement> {

    /** Pool of {@link PreparedStatement}s. and {@link CallableStatement}s */
    protected KeyedObjectPool<PStmtKey, DelegatingPreparedStatement> _pstmtPool = null;

    /**
     * Constructor.
     * @param c the underlying {@link Connection}.
     */
    public PoolingConnection(Connection c) {
        super(c);
    }

    /**
     * Constructor.
     * @param c the underlying {@link Connection}.
     * @param pool {@link KeyedObjectPool} of {@link PreparedStatement}s and {@link CallableStatement}s.
     */
    public PoolingConnection(Connection c, KeyedObjectPool<PStmtKey, DelegatingPreparedStatement> pool) {
        super(c);
        _pstmtPool = pool;
    }


    /**
     * Close and free all {@link PreparedStatement}s or {@link CallableStatement} from the pool, and
     * close the underlying connection.
     */
    @Override
    public synchronized void close() throws SQLException {
        if(null != _pstmtPool) {
            KeyedObjectPool<PStmtKey, DelegatingPreparedStatement> oldpool = _pstmtPool;
            _pstmtPool = null;
            try {
                oldpool.close();
            } catch(RuntimeException e) {
                throw e;
            } catch(SQLException e) {
                throw e;
            } catch(Exception e) {
                throw (SQLException) new SQLException("Cannot close connection").initCause(e);
            }
        }
        getInnermostDelegate().close();
    }

    /**
     * Create or obtain a {@link PreparedStatement} from the pool.
     * @param sql the sql string used to define the PreparedStatement
     * @return a {@link PoolablePreparedStatement}
     */
    @Override
    public PreparedStatement prepareStatement(String sql) throws SQLException {
        if (null == _pstmtPool) {
            throw new SQLException(
                    "Statement pool is null - closed or invalid PoolingConnection.");
        }
        try {
            return _pstmtPool.borrowObject(createKey(sql));
        } catch(NoSuchElementException e) {
            throw (SQLException) new SQLException("MaxOpenPreparedStatements limit reached").initCause(e);
        } catch(RuntimeException e) {
            throw e;
        } catch(Exception e) {
            throw new SQLException("Borrow prepareStatement from pool failed", e);
        }
    }

    @Override
    public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException {
        if (null == _pstmtPool) {
            throw new SQLException(
                    "Statement pool is null - closed or invalid PoolingConnection.");
        }
        try {
            return _pstmtPool.borrowObject(createKey(sql, autoGeneratedKeys));
        }
        catch (NoSuchElementException e) {
            throw (SQLException)new SQLException("MaxOpenPreparedStatements limit reached", e).initCause(e);
        }
        catch (RuntimeException e) {
            throw e;
        }
        catch (Exception e) {
            throw (SQLException)new SQLException("Borrow prepareStatement from pool failed").initCause(e);
        }
    }

    /**
     * Create or obtain a {@link PreparedStatement} from the pool.
     * @param sql the sql string used to define the PreparedStatement
     * @param resultSetType result set type
     * @param resultSetConcurrency result set concurrency
     * @return a {@link PoolablePreparedStatement}
     */
    @Override
    public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException {
        if (null == _pstmtPool) {
            throw new SQLException(
                    "Statement pool is null - closed or invalid PoolingConnection.");
        }
        try {
            return _pstmtPool.borrowObject(createKey(sql,resultSetType,resultSetConcurrency));
        } catch(NoSuchElementException e) {
            throw (SQLException) new SQLException("MaxOpenPreparedStatements limit reached").initCause(e);
        } catch(RuntimeException e) {
            throw e;
        } catch(Exception e) {
            throw (SQLException) new SQLException("Borrow prepareStatement from pool failed").initCause(e);
        }
    }

    /**
     * Create or obtain a {@link CallableStatement} from the pool.
     * @param sql the sql string used to define the CallableStatement
     * @return a {@link PoolableCallableStatement}
     * @throws SQLException
     * @since 1.3
     */
    @Override
    public CallableStatement prepareCall(String sql) throws SQLException {
        try {
            return (CallableStatement) (_pstmtPool.borrowObject(createKey(sql, StatementType.CALLABLE_STATEMENT)));
        } catch (NoSuchElementException e) {
            throw new SQLException("MaxOpenCallableStatements limit reached", e);
        } catch (RuntimeException e) {
            throw e;
        } catch (Exception e) {
            throw new SQLException("Borrow callableStatement from pool failed", e);
        }
    }

    /**
     * Create or obtain a {@link CallableStatement} from the pool.
     * @param sql the sql string used to define the CallableStatement
     * @param resultSetType result set type
     * @param resultSetConcurrency result set concurrency
     * @return a {@link PoolableCallableStatement}
     * @throws SQLException
     * @since 1.3
     */
    @Override
    public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException {
        try {
            return (CallableStatement) (_pstmtPool.borrowObject(createKey(sql, resultSetType,
                            resultSetConcurrency, StatementType.CALLABLE_STATEMENT)));
        } catch (NoSuchElementException e) {
            throw new SQLException("MaxOpenCallableStatements limit reached", e);
        } catch (RuntimeException e) {
            throw e;
        } catch (Exception e) {
            throw new SQLException("Borrow callableStatement from pool failed", e);
        }
    }

    /**
     * Create or obtain a {@link PreparedStatement} from the pool.
     * @param sql the sql string used to define the PreparedStatement
     * @param resultSetType result set type
     * @param resultSetConcurrency result set concurrency
     * @param resultSetHoldability result set holdability
     * @return a {@link PoolablePreparedStatement}
     */
    @Override
    public PreparedStatement prepareStatement(final String sql, final int resultSetType,
            final int resultSetConcurrency, final int resultSetHoldability) throws SQLException {
        if (null == _pstmtPool) {
            throw new SQLException(
                    "Statement pool is null - closed or invalid PoolingConnection.");
        }
        try {
            return _pstmtPool.borrowObject(createKey(sql, resultSetType, resultSetConcurrency, resultSetHoldability));
        } catch(final NoSuchElementException e) {
            throw new SQLException("MaxOpenPreparedStatements limit reached", e);
        } catch(final RuntimeException e) {
            throw e;
        } catch(final Exception e) {
            throw new SQLException("Borrow prepareStatement from pool failed", e);
        }
    }

    /**
     * Create or obtain a {@link PreparedStatement} from the pool.
     * @param sql the sql string used to define the PreparedStatement
     * @param columnIndexes column indexes
     * @return a {@link PoolablePreparedStatement}
     */
    @Override
    public PreparedStatement prepareStatement(final String sql, final int columnIndexes[])
            throws SQLException {
        if (null == _pstmtPool) {
            throw new SQLException(
                    "Statement pool is null - closed or invalid PoolingConnection.");
        }
        try {
            return _pstmtPool.borrowObject(createKey(sql, columnIndexes));
        } catch(final NoSuchElementException e) {
            throw new SQLException("MaxOpenPreparedStatements limit reached", e);
        } catch(final RuntimeException e) {
            throw e;
        } catch(final Exception e) {
            throw new SQLException("Borrow prepareStatement from pool failed", e);
        }
    }

    /**
     * Create or obtain a {@link PreparedStatement} from the pool.
     * @param sql the sql string used to define the PreparedStatement
     * @param columnNames column names
     * @return a {@link PoolablePreparedStatement}
     */
    @Override
    public PreparedStatement prepareStatement(final String sql, final String columnNames[])
            throws SQLException {
        if (null == _pstmtPool) {
            throw new SQLException(
                    "Statement pool is null - closed or invalid PoolingConnection.");
        }
        try {
            return _pstmtPool.borrowObject(createKey(sql, columnNames));
        } catch(final NoSuchElementException e) {
            throw new SQLException("MaxOpenPreparedStatements limit reached", e);
        } catch(final RuntimeException e) {
            throw e;
        } catch(final Exception e) {
            throw new SQLException("Borrow prepareStatement from pool failed", e);
        }
    }

    /**
     * Create or obtain a {@link CallableStatement} from the pool.
     * @param sql the sql string used to define the CallableStatement
     * @param resultSetType result set type
     * @param resultSetConcurrency result set concurrency
     * @param resultSetHoldability result set holdability
     * @return a {@link PoolableCallableStatement}
     * @throws SQLException
     */
    @Override
    public CallableStatement prepareCall(final String sql, final int resultSetType,
            final int resultSetConcurrency, final int resultSetHoldability) throws SQLException {
        try {
            return (CallableStatement) _pstmtPool.borrowObject(createKey(sql, resultSetType,
                            resultSetConcurrency, resultSetHoldability, StatementType.CALLABLE_STATEMENT));
        } catch (final NoSuchElementException e) {
            throw new SQLException("MaxOpenCallableStatements limit reached", e);
        } catch (final RuntimeException e) {
            throw e;
        } catch (final Exception e) {
            throw new SQLException("Borrow callableStatement from pool failed", e);
        }
    }

    /**
     * Create a PStmtKey for the given arguments.
     * @param sql the sql string used to define the statement
     */
    protected PStmtKey createKey(String sql) {
        return new PStmtKey(normalizeSQL(sql), getCatalogOrNull(), getSchemaOrNull());
    }


    protected PStmtKey createKey(final String sql, final int columnIndexes[]) {
        return new PStmtKey(normalizeSQL(sql), getCatalogOrNull(), getSchemaOrNull(), columnIndexes);
    }


    protected PStmtKey createKey(final String sql, final int autoGeneratedKeys) {
        return new PStmtKey(normalizeSQL(sql), getCatalogOrNull(), getSchemaOrNull(), autoGeneratedKeys);
    }


    /**
     * Create a PStmtKey for the given arguments.
     * @param sql the sql string used to define the statement
     * @param resultSetType result set type
     * @param resultSetConcurrency result set concurrency
     */
    protected PStmtKey createKey(String sql, int resultSetType, int resultSetConcurrency) {
        return new PStmtKey(normalizeSQL(sql), getCatalogOrNull(), getSchemaOrNull(), resultSetType, resultSetConcurrency);
    }


    protected PStmtKey createKey(final String sql, final int resultSetType, final int resultSetConcurrency,
            final int resultSetHoldability) {
        return new PStmtKey(normalizeSQL(sql), getCatalogOrNull(), getSchemaOrNull(), resultSetType, resultSetConcurrency,
                resultSetHoldability);
    }


    protected PStmtKey createKey(final String sql, final int resultSetType, final int resultSetConcurrency,
            final int resultSetHoldability, final StatementType statementType) {
        return new PStmtKey(normalizeSQL(sql), getCatalogOrNull(), getSchemaOrNull(), resultSetType, resultSetConcurrency,
                resultSetHoldability, statementType);
    }


    /**
     * Create a PStmtKey for the given arguments.
     * @param sql the sql string used to define the statement
     * @param resultSetType result set type
     * @param resultSetConcurrency result set concurrency
     * @param stmtType statement type
     */
    protected PStmtKey createKey(String sql, int resultSetType, int resultSetConcurrency, StatementType stmtType) {
        return new PStmtKey(normalizeSQL(sql), getCatalogOrNull(), getSchemaOrNull(), resultSetType, resultSetConcurrency, stmtType);
    }


    /**
     * Create a PStmtKey for the given arguments.
     * @param sql the sql string used to define the statement
     * @param stmtType statement type
     */
    protected PStmtKey createKey(String sql, StatementType stmtType) {
        return new PStmtKey(normalizeSQL(sql), getCatalogOrNull(), getSchemaOrNull(), stmtType, null);
    }

    /**
     * Create a PStmtKey for the given arguments.
     * @param sql the sql string used to define the statement
     * @param columnNames column names
     */
    protected PStmtKey createKey(final String sql, final String columnNames[]) {
        return new PStmtKey(normalizeSQL(sql), getCatalogOrNull(), getSchemaOrNull(), columnNames);
    }


    /**
     * Normalize the given SQL statement, producing a
     * cannonical form that is semantically equivalent to the original.
     */
    protected String normalizeSQL(String sql) {
        return sql.trim();
    }

    private String getCatalogOrNull() {
        String catalog = null;
        try {
            catalog = getCatalog();
        } catch (final SQLException e) {
            // Ignored
        }
        return catalog;
    }

    private String getSchemaOrNull() {
        String schema = null;
        try {
            schema = getSchema();
        } catch (final SQLException e) {
            // Ignored
        }
        return schema;
    }

    /**
     * {@link KeyedPoolableObjectFactory} method for creating
     * {@link PoolablePreparedStatement}s or {@link PoolableCallableStatement}s.
     * The <code>stmtType</code> field in the key determines whether
     * a PoolablePreparedStatement or PoolableCallableStatement is created.
     *
     * @param key the key for the {@link PreparedStatement} to be created
     * @see #createKey(String, int, int, StatementType)
     */
    @Override
    public DelegatingPreparedStatement makeObject(PStmtKey key) throws Exception {
        if (key == null) {
            throw new IllegalArgumentException("Prepared statement key is null.");
        }
        if (key.getStmtType() == StatementType.PREPARED_STATEMENT ) {
            PreparedStatement statement = (PreparedStatement) key.createStatement(getDelegate());
            @SuppressWarnings({"rawtypes", "unchecked"}) // Unable to find way to avoid this
            PoolablePreparedStatement pps = new PoolablePreparedStatement(statement, key, _pstmtPool, this);
            return pps;
        } else {
            CallableStatement statement = (CallableStatement) key.createStatement(getDelegate());
            return new PoolableCallableStatement(statement, key, _pstmtPool, this);
        }
    }

    /**
     * {@link KeyedPoolableObjectFactory} method for destroying
     * PoolablePreparedStatements and PoolableCallableStatements.
     * Closes the underlying statement.
     *
     * @param key ignored
     * @param obj the pooled statement to be destroyed.
     */
    @Override
    public void destroyObject(PStmtKey key, DelegatingPreparedStatement obj) throws Exception {
        obj.getInnermostDelegate().close();
    }

    /**
     * {@link KeyedPoolableObjectFactory} method for validating
     * pooled statements. Currently always returns true.
     *
     * @param key ignored
     * @param obj ignored
     * @return <code>true</code>
     */
    @Override
    public boolean validateObject(PStmtKey key, DelegatingPreparedStatement obj) {
        return true;
    }

    /**
     * {@link KeyedPoolableObjectFactory} method for activating
     * pooled statements.
     *
     * @param key ignored
     * @param obj pooled statement to be activated
     */
    @Override
    public void activateObject(PStmtKey key, DelegatingPreparedStatement obj) throws Exception {
        obj.activate();
    }

    /**
     * {@link KeyedPoolableObjectFactory} method for passivating
     * {@link PreparedStatement}s or {@link CallableStatement}s.
     * Invokes {@link PreparedStatement#clearParameters}.
     *
     * @param key ignored
     * @param obj a {@link PreparedStatement}
     */
    @Override
    public void passivateObject(PStmtKey key, DelegatingPreparedStatement obj) throws Exception {
        ((PreparedStatement)obj).clearParameters();
        obj.passivate();
    }

    @Override
    public String toString() {
        if (_pstmtPool != null ) {
            return "PoolingConnection: " + _pstmtPool.toString();
        } else {
            return "PoolingConnection: null";
        }
    }

    public enum StatementType {
        CALLABLE_STATEMENT,
        PREPARED_STATEMENT
    }
}
