package ModSQL;
import java.sql.*;
 
/* $Id: Function_NVL.java,v 1.6 2003/07/09 06:54:49 cvs Exp $
 *
 * Copyright (c) 2003 Chris Studholme <chris.studholme@utoronto.ca>
 *
 * May be copied or modified under the terms of the GNU General Public
 * License.  See COPYING for more information.
 */

/**
 * <p>SQL function for NVL (null value substitution function).
 *
 * @author chris.studholme@utoronto.ca
 */
final class Function_NVL extends AbstractFunction {

  /** Return type of function. */
  private int return_type = Types.NULL;

  /**
   * If name is "nvl", this method returns an instance of this class.
   *
   * @param name name of desired function
   * @return instance of this class, or null if name does not match
   */
  public static Function forName(String name) {
    if (name.equals("nvl"))
      return new Function_NVL();
    return null;
  }

  /**
   * <p>Prepare the function for use.  
   *
   * @throws SQLException if the parameters are invalid
   */
  public void optimize() throws SQLException {
    super.optimize();
    if (parameters.length!=2)
      throw new SQLException("NVL requires exactly two parameters");
    return_type = parameters[0].getSQLType();
    // throw an exception if parameters are not compatable
    getCompatableType(return_type,parameters[1].getSQLType());
  }


  /****************  information methods  ****************/

  /**
   * Returns the SQL type of this function.
   *
   * @return SQL type of data to be returned
   */
  public int getSQLType() {
    return return_type;
  }

  /**
   * Make size of any String that may be returned, or -1 if a maximum size
   * is not known.
   *
   * @return maximum size of String returned or -1 if unknown
   * @throws SQLException if thrown by a parameter
   */
  public int getMaxResultSize() throws SQLException {
    int m1 = parameters[0].getMaxResultSize();
    int m2 = parameters[1].getMaxResultSize();
    if (m1==-1 || m2==-1)
      return -1;
    return m1>m2 ? m1 : m2;
  }

  /**
   * Returns "#NVL".
   *
   * @return name of function
   */
  public String functionName() {
    return "NVL";
  }

  
  /****************  evaluation methods  ****************/

  /**
   * <p>Evaluate parameters and compute the function.
   *
   * @param aggregate passed to parameter
   * @return result object
   * @throws SQLException if a database-access error occurs
   * @throws EndOfTable if thrown by a parameter
   */
  public Object evaluate(boolean aggregate) throws SQLException, EndOfTable {
    Object value = parameters[0].evaluate(aggregate);
    if (value==null)
      value = convertToSQLType(parameters[1].evaluate(aggregate),return_type);
    return value;
  }
};


