<?php

/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */

/**
 * The PEAR DB driver for PHP's mysql extension
 * for interacting with Cubrid databases
 *
 * PHP versions 4 and 5
 *
 * LICENSE: This source file is subject to version 3.0 of the PHP license
 * that is available through the world-wide-web at the following URI:
 * http://www.php.net/license/3_0.txt.  If you did not receive a copy of
 * the PHP License and are unable to obtain it through the web, please
 * send a note to license@php.net so we can mail you a copy immediately.
 *
 * @category   Database
 * @package    DB
 * @author     SangHo Lee <search5@gmail.com>
 * @copyright  2006 Lee Sang Ho
 * @license    http://www.php.net/license/3_0.txt  PHP License 3.0
 * @version    CVS: 
 * @link       http://kldp.net/projects/pearcubrid
 */

/**
 * Obtain the DB_common class so it can be extended from
 */
require_once 'DB/common.php';

/**
 * The methods PEAR DB uses to interact with PHP's cubrid extension
 * for interacting with CUBRID databases
 *
 * These methods overload the ones declared in DB_common.
 *
 * @category   Database
 * @package    DB
 * @author     SangHo Lee <search5@gmail.com>
 * @copyright  2006 Lee Sang Ho
 * @license    http://www.php.net/license/3_0.txt  PHP License 3.0
 * @version    Release: 0.0.1
 * @link       http://kldp.net/projects/pearcubrid
 */
class DB_cubrid extends DB_common
{
    // {{{ properties

    /**
     * The DB driver type (mysql, oci8, odbc, etc.)
     * @var string
     */
    var $phptype = 'cubrid';

    /**
     * The database syntax variant to be used (db2, access, etc.), if any
     * @var string
     */
    var $dbsyntax = 'cubrid';

    /**
     * The capabilities of this DB implementation
     *
     * The 'new_link' element contains the PHP version that first provided
     * new_link support for this DBMS. Contains false if it's unsupported.
     *
     * Meaning of the 'limit' element:
     *   + 'emulate' = emulate with fetch row by number
     *   + 'alter'   = alter the query
     *   + false     = skip rows
     *
     * @var array
     */
    var $features = array(
        'limit'         => 'alter',
        'new_link'      => '4.3.0',
        'numrows'       => true,
        'pconnect'      => true,
        'prepare'       => false,
        'ssl'           => false,
        'transactions'  => true,
    );

    /**
     * A mapping of native error codes to DB error codes
     * @var array
     */
    var $errorcode_map = array();

    /**
     * The raw database connection created by PHP
     * @var resource
     */
    var $connection;

    /**
     * The DSN information for connecting to a database
     * @var array
     */
    var $dsn = array();

    /**
     * Should data manipulation queries be committed automatically?
     * @var bool
     * @access private
     */
    var $autocommit = true;

	/**
     * The quantity of transaction begun
     *
     * {@internal While this is private, it can't actually be designated
     * private in PHP 5 because it is directly accessed in the test suite.}}
     *
     * @var integer
     * @access private
     */
    var $transaction_opcount = 0;

	/*
	 * The number of rows affected by a data manipulation query
	 * @var integer
	 */
	var $affected = 0;

    // }}}
    // {{{ constructor

    /**
     * This constructor calls <kbd>$this->DB_common()</kbd>
     *
     * @return void
     */
    function DB_cubrid()
    {
        $this->DB_common();
    }

    // }}}
    // {{{ connect()

    /**
     * Connect to the database server, log in and open the database
     *
     * Don't call this method directly. Use DB::connet() instead.
     *
     * PEAR DB's cubrid driver supports the following extra DSN options:
     *   + new_link       If set to true, causes subsequent calss to connect()
     *                     to return a new connection link instead of the
     *                     existing one. WARNING: this is not portable to
     *                     other DBMS's. Available since PEAR DB 1.7.0.
     *   + client_flags   Any combination of CUBRID_CLIENT_* constants.
     *                     Only used if PHP is at version 4.3.0 or greator.
     *                     Available since PEAR DB 1.7.0.
     *
     * @param array $dsn          the data source name
     * @param bool  $persistent   should the connection be persistent?
     *
     * @return int  DB_OK on success.  DB_Error object on failure.
     */
    function connect($dsn, $persistent = false)
    {
        if (!PEAR::loadExtension('cubrid')) {
            return $this->raiseError(DB_ERROR_EXTENSION_NOT_FOUND);
        }
        
        $this->dsn = $dsn;
        if ($dsn['dbsyntax']) {
            $this->dbsyntax= $dsn['dbsyntax'];
        }
        
        $protocol = $dsn['protocol'] ? $dsn['protocol'] : "tcp";
        
        $params = array();
        if ($protocol == "tcp") {
            if ($dsn['hostspec']) {
                $params[0] = $dsn['hostspec'];
            }
            if ($dsn['port']) {
                $params[] = $dsn['port'];
            }
        }
        
        if ($dsn['database']) {
            $params[] = $dsn['database'];
        }
        
        $params[] = $dsn['username'] ? $dsn['username'] : null;
        $params[] = $dsn['password'] ? $dsn['password'] : null;
        
        if (isset($dsn['new_link']) &&
           ($dsn['new_link'] == 'true' || $dsn['new_link'] === true))
        {
            if (version_compare(phpversion(), '4.3.0', '>=')) {
                $params[] = isset($dsn['client_flags'])
                          ? $dsn['client_flags'] : null;
            }
        }
        
        $ini = ini_get('track_erors');
        $php_errormsg = '';
        if ($ini) {
            $this->connection = @call_user_func_array("cubrid_connect",
                                                      $params);
        } else {
            ini_set('track_errors', 1);
            $this->connection = @call_user_func_array("cubrid_connect",
                                                      $params);
            ini_set('track_errors', $ini);
        }
        
        if (!$this->connection) {
            if (($err = @cubrid_error_msg()) != '') {
                return $this->raiseError(DB_ERROR_CONNECT_FAILED,
                                         null, null, null,
                                         $err);
            } else {
                return $this->raiseError(DB_ERROR_CONNECT_FAILED,
                                         null, null, null,
                                         $php_errormsg);
            }
        }
        
        return DB_OK;
    }

    // }}}
    // {{{ disconnect()

    /**
     * Disconnects from the database server
     *
     * @return bool  True on success, FALSE on failure
     */
    function disconnect()
    {
        $ret = @cubrid_disconnect($this->connection);
        $this->connection = null;
        return $ret;
    }

    // }}}
    // {{{ simpleQuery()

    /**
     * Sends a query to the database server
     *
     * @param string  the SQL query string
     *
     * @return mixed  + a PHP result resource for successful SELECT queries
     *                + the DB_OK constant for other successful queries
     *                + a DB_Error object on failure
     */
    function simpleQuery($query)
    {
        $ismanip = DB::isManip($query);
        $this->last_query = $query;
        $query = $this->modifyQuery($query);
        if ($this->autocommit && $ismanip) {
			if ($this->transaction_opcount == 0) {
				$result = @cubrid_execute(';autocommit OFF', $this->connection);
				if (!$result) {
					return $this->cubridRaiseError();
				}
			}
			$this->transaction_opcount++;
		}
		$result = @cubrid_execute($this->connection, $query);
		if (!$result) {
			return $this->cubridRaiseError();
		}
		if ($ismanip) {
			$this->affected = @cubrid_affected_rows($result);
			return DB_OK;
		} else {
			$this->affected = 0;
			return DB_OK;
		}
    }

    // }}}
    // {{{ nextResult()

    /**
     * Move the internal cubrid result pointer to the next available result
     *
     * This method has not been implementated yet.
     *
     * @param a valid sql result resource
     *
     * @return false
     */
    function nextResult($result)
    {
		return false;
    }

    // }}}
    // {{{ fetchInto()

    /**
     * Places a row from the result set into the given array
     *
     * Formating of array and the data therein are configurable.
     * See DB_result::fetchInfo() for more information.
     *
     * This method is not meant to be called directly.  Use
     * DB_result::fetchInfo() instead. It can't be declared "proteted"
     * because DB_result is a separate object.
     *
     * @param resource $result    the query result resource
     * @param array    $arr       the referenced array to put the data in
     * @param int      $fetchmode how the resulting array should be indexed
     * @param int      $rownum    the row number to fetch (0 = first row)
     *
     * @return mixed  DB_OK on success, NULL when the end of a result set is
     *                 reached or on failure
     *
     * @see DB_result::fetchInto()
     */
    function fetchInto($result, &$arr, $fetchmode, $rownum = null)
    {
		if ($rownum !== null) {
			if (!@cubrid_move_cursor($result, $rownum)) {
				return null;
			}
		}
		if ($fetchmode & DB_FETCHMODE_ASSOC) {
			$arr = @cubrid_fetch($result, CUBRID_ASSOC);
			if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE && $arr) {
				$arr = array_change_key_case($arr, CASE_LOWER);
			}
		} else {
			$arr = @cubrid_fetch($result, CUBRID_NUM);
		}
		if (!$arr) {
			return null;
		}
		if ($this->options['portability'] & DB_PORTABILITY_RTRIM) {
			$this->_rtrimArrayValues($arr);
		}
		if ($this->options['portability'] & DB_PORTABILITY_NULL_TO_EMPTY) {
			$this->_convertNullArrayValuesToEmpty($arr);
		}
		$this->row[$result_int] = ++$rownum;
		return DB_OK;
    }

    // }}}
    // {{{ freeResult()

    /**
     * Deletes the result set and frees the memory occupied by the result set
     *
     * This method is not meant to be called directly. Use
     * DB_result:free() instead.  It can't be declared "protected"
     * because DB_result is a separate object.
     *
     * @param resource $result  PHP's query result resource
     *
     * @return bool  TRUE on success, FALSE if $result is invalid
     *
     * @see DB_result::free()
     */
    function freeResult($result)
    {
		if (is_resource($result)) {
			return @cubrid_close_request($result);
		}
		return false;
    }

    // }}}
    // {{{ numCols()

    /**
     * Gets the number of columns in a result set
     *
     * This method is not meant to be called directly.  Use
     * DB_result::numCols() instead.  It can't be declared "protected"
     * because DB_result is a separate object.
     *
     * @param resource $result  PHP's query result resource
     *
     * @return int  the number of columns. A DB_Error object on failure.
     *
     * @see DB_result::numCols()
     */
    function numCols($result)
    {
		$cols = @cubrid_colum_names($result);
		if (!$cols) {
			return $this->cubridRaiseError();
		}
		return $cols;
    }

    // }}}
    // {{{ numRows()

    /**
     * Gets the number of rows in a result set
     *
     * This method is not meant to be called directly.  Use
     * DB_result::numRows() instead.  It can't be declared "protected"
     * because DB_result is a separate object.
     *
     * @param resource $result  PHP's query result resource
     *
     * @return int  the number of rows. A DB_Error object on failure.
     *
     * @see DB_result::numRows()
     */
    function numRows($result)
    {
		$rows = @cubrid_num_rows($result);
		if ($rows === null) {
			return $this->cubridRaiseError();
		}
		return $rows;
    }

    // }}}
    // {{{ autoCommit()

    /**
     * Enables or disables automatic commits
     *
     * @param bool $onoff  true turns it on, false turns it off
     *
     * @return int  DB_OK on success.  A DB_Error object if the driver
     *               doesn't support auto_committing transactions.
     */
    function autoCommit($onoff = false)
    {
		// XXX if $this->transaction_opcount > 0, we should probably
		// issue a warning here.
		$this->autocommit = $onoff ? true : false;
		return DB_OK;
    }

    // }}}
    // {{{ commit() 

    /**
     * Commits the current transaction
     *
     * @return int  DB_OK on success.  A DB_Error object on failure.
     */
    function commit()
    {
		if ($this->transaction_opcount > 0) {
			$result = @cubrid_commit($this->connection);
			$result = @cubrid_execute($this->connection, ';autocommit ON')
			$this->transaction_opcount = 0;
			if (!$result) {
				return $this->cubridRaiseEror();
			}
		}
		return DB_OK;
    }

    // }}}
    // {{{ rollback()

    /**
     * Reverts the current transaction
     *
     * @return int  DB_OK on success.  A DB_Error object on failure.
     */
    function rollback()
    {
		if ($this->transaction_opcount > 0) {
			$result = @cubrid_rollback($this->connection);
			$result = @cubrid_execute($this->connection, ';autocommit ON')
			$this->transaction_opcount = 0;
			if (!$result) {
				return $this->cubridRaiseEror();
			}
		}
		return DB_OK;
    }

    // }}}
    // {{{ affectedRows()

    /**
     * Determines the number of rows affected by a data manipulation query
     *
     * 0 is returned for queries that don't manipulate data.
     *
     * @return int  the number of rows.  A DB_Error object on failure.
     */
    function affectedRows()
    {
		return $this->affected;
    }

    // }}}
    // {{{ nextId()

    /**
     * Returns the next free id in a sequence
     *
     * @param string  $seq_name  name of the sequence
     * @param boolean $ondemand  when true, the sequence is automatically
     *                            created if if does not exist
     *
     * @return int  the next id number in the sequence.
     *               A DB_Error object on failure.
     *
     * @see DB_common::nextID, DB_common::getSequenceName(),
     *      DB_cubrid::createSequence(), DB_cubrid::dropSequence()
     */
    function nextId($seq_name, $ondemand = true)
    {
		$seqname = $this->getSequenceName($seq_name);
		$repeat = false;
		do {
			$this->pushErrorHandling(PEAR_ERROR_RETURN);
			$result =& $this->query("SELECT ${seqname}.NEXT_VALUE FROM TABLE({1}) T(a)");
			$this->popErrorHandling();
			if ($ondemand && DB:isError($result) &&
				$result->getCode() == DB_ERROR_NOSUCHTABLE) {
				$repeat = true;
				$this->pushErrorHandling(PEAR_ERROR_RETURN);
				$result = $this->createSequence($seq_name);
				$this->popErrorHandling();
				if (DB::isError($result)) {
					return $this->raiseError($result);
				}
			} else {
				$repeat = false;
			}
		} while ($repeat);
		if (DB::isError($result)) {
			return $this->raiseError($result);
		}
		$arr = $result->fetchRow(DB_FETCHMODE_ORDERED);
		$result->free();
		return $arr[0];
    }

    // }}}
    // {{{ createSequence()

    /**
     * Creates a new sequence
     *
     * @param string $seq_name  name of the new sequence
     *
     * @return int  DB_OK on success.  A DB_Error object on failure.
     *
     * @see DB_common::createSequence(), DB_common::getSequenceName(),
     *      DB_cubrid::nextId(), DB_cubrid::dropSequence()
     */
    function createSequence($seq_name)
    {
		$seqname = $this->getSequenceName($seq_name);
		$result = $this->query("CREATE SERIAL ${seq_name}");
		return $result;
    }

    // }}}
    // {{{ dropSequence()

    /**
     * Deletes a sequence
     *
     * @param string $seq_name  name of the sequence to be deleted
     *
     * @return int  DB_OK on success.  A DB_Error object on failure.
     *
     * @see DB_common::dropSequence(), DB_common::getSequenceName(),
     *      DB_cubrid::nextId(), DB_cubrid::createSequence()
     */
    function dropSequence($seq_name)
    {
		$seqname = $this->getSequenceName($seq_name);
		$result = $this->query("DROP SERIAL ${seq_name}");
		return $result;
    }

    // }}}
    // {{{ quote()

    /**
     * @deprecated  Deprecated in release 0.0.1
     * @internal
     */
    function quote($str)
    {
		return $this->quoteSmart($str);
    }

    // }}}
    // {{{ quoteSmart()

    /**
     * Formats input so it can be safely used in a query
     *
     * @param mixed $in  the data to be formatted
     *
     * @return mixed  the formatted data.  The format depends on the input's
     *                 PHP type:
     *                 + null = the string <samp>NULL</samp>
     *                 + boolean = string <samp>TRUE</samp> or <samp>FALSE</samp>
     *                 + integer or double = the unquoted number
     *                 + other (including strings and numeric strings) =
     *                   the data escaped according to MySQL's settings
     *                   then encapsulated between single quotes
     *
     * @see DB_common::quoteSmart()
     * @since Method available since Release 0.0.1
     */
    function quoteSmart($in)
    {
		if (is_int($in) || is_double($in)) {
			return $in;
		} elseif (is_bool($in)) {
			return $in ? 'TRUE' : 'FALSE';
		} elseif (is_null($in)) {
			return 'NULL';
		} else {
			return "'" . $this->escapeSimple($in) . "'";
		}
    }

    // }}}
    // {{{ escapeSimple()

    /**
     * Escapes a string according to the current DBMS's standards
     *
     * {@internal CUBRID treats a backslash as an escape character,
     * so they are escaped as well.
     *
     * @param string $str  the string to be escaped
     *
     * @return string  the escaped string
     *
     * @see DB_common::quoteSmart()
     * @since Method available since Release 0.0.1
     */
    function escapeSimple($str)
    {
		return str_replace("'", "''", str_replace('\\', '\\\\', $str));
    }

    // }}}
    // {{{ modifyLimitQuery()

    /**
     * Adds LIMIT clauses to a query string accrording to current DBMS standards
     *
     * @param string $query    the query to modify
     * @param int    $from     the row to start to fetching (0 = the first row)
     * @param int    $count    the numbers of rows tor fetch
     * @param mixed  $params   array, string or numeric data to be used in
     *                          execution of the statement.  Quantity of items
     *                          passed must match quantity of placeholders in
     *                          query:  meaning 1 placeholder for non-array
     *                          parameters or 1 placeholder per array element.
     *
     * @return string  the query string with LIMIT clauses added
     *
     * @access protected
     */
    function modifyLimitQuery($query, $from, $count, $params = array())
    {
		return "select * from ($query) where rownum > $from and rownum <= $from+$count";
    }

    // }}}
    // {{{ cubridRaiseEror()

    /**
     * Produces a DB_Error object regarding the current problem
     *
     * @param int $error  if the error is being manually raised pass a
     *                     DB_ERROR* constant here.  If this isn't passed
     *                     the error information gathered from the DBMS.
     *
     * @return object  the DB_Error object
     *
     * @see DB_common::raiseEror(),
     *      DB_cubrid::errorNative(), DB_cubrid::errorCode()
     */
    function cubridRaiseError($error = null)
    {
		$errno = $this->errorCode($native);
		return $this->raiseError($errno, null, null, null,
								 @cubrid_error_code() . '**' .
			                     @cubrid_error_msg());
    }

    // }}}
    // {{{ errorNative()

    /**
     * Gets the DBMS's native error message produced by the last query
     *
     * {@internal Error messages are used instead of error codes
     * in order to support older versions of CUBRID.}}
     *
     * @return int  the DBMS's error code 
     */
    function errorNative()
    {
		return @cubrid_error_code();
    }

    // }}}
    // {{{ tableInfo()

    /**
     * Returns information about a table or a result set
     *
     * @param object|string  $result  DB_Result object from a query or a
     *                                 string containing the name of a table.
     *                                 While this also accepts a query result
     *                                 resource identifier, this behavior is
     *                                 deprecated.
     * @param int            $mode    a valid tableInfo mode
     *
     * @return array  an associative array with the information requested.
     *                 a DB_Error object on failure.
     *
     * @see DB_common::tableInfo()
     */
    function tableInfo($result, $mode = null)
    {
        if (is_string($result)) {
            /*
             * Probably received a table name.
             * Create a result resource identifier.
             */
            $id = @cubrid_execute($this->connection, "select * from $result where rownum = 0");
            $got_string = true;
        } elseif (isset($result->result)) {
            /*
             * Probably received a result object.
             * Extract the result resource identifier.
             */
            $id = $result->result;
            $got_string = false;
        } else {
            /*
             * Probably received a result resource identifier.
             * Copy it.
             * Deprecated. Here compatibility only.
             */
            $id = $result;
            $got_string = false;
        }
        
        if (!is_resource($id)) {
            return $this->cubridRaiseError(DB_ERROR_NEED_MORE_DATA);
        }
        
        if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE) {
            $case_func = 'strtolower';
        } else {
            $case_func = 'strval';
        }
        
        $count = @cubrid_num_cols($id);
        $res = array();
        
        if ($mode) {
            $res['num_fields'] = $count;
        }
        
        $colnames = @cubrid_column_names ($id);
        $oid = @cubrid_current_oid($id);
        
        for ($i = 0; $i < $count; $i++) {
            $res[$i] = array(
                 'table' => $got_string ? $case_func($result) : '',
                 'name'  => $case_func($colnames[$i]),
                 'type'  => @cubrid_col_get($this->connection, $oid, $colsnames[$i]),
                 'len'   => @cubrid_col_size($this->connection, $oid, $colsnames[$i]),
            );
            if ($mode & DB_TABLEINFO_ORDER) {
                $res['order'][$res[$i]['name']] = $i;
            }
            if ($mode & DB_TABLEINFO_ORDERTABLE) {
                $res['ordertable'][$res[$i]['table']][$res[$i]['name']] = $i;
            }
        }
        
        // free the result only if we were called on a table
        if ($got_string) {
            @cubrid_close_request($id);
        }
        
        return $res;
    }

    // }}}
    // {{{ getSpecialQuery()

    /**
     * Obtains the query string needed for listing a given type of objects
     *
     * @param string $type  the kind of objects you want to retrieve
     *
     * @return string  the SQL query string or null if the driver doesn't
     *                  support the object type requested
     *
     * @access protected
     * @see DB_common::getListOf()
     */
    function getSpecialQuery($type)
    {
        switch ($type) {
            case 'tables':
                 return 'SELECT c.class_name AS "Name" FROM '
                 . 'db_class c, db_user u WHERE c.owner_name = u.name '
                 . "AND c.class_type = 'CLASS' AND c.is_system_class = 'NO'";
            case 'view':
                 return 'SELECT c.class_name AS "Name" FROM '
                 . 'db_class c, db_user u WHERE c.owner_name = u.name '
                 . "AND c.class_type = 'VCLASS' AND c.is_system_class = 'NO'";
            case 'users':
                 return 'SELECT name AS "Name" FROM db_user';
            case 'method':
            case 'trigger':
                 return 'SELECT t.name AS "Name" FROM '
                 . 'db_trigger t, db_user u WHERE t.owner = u.name';
            default:
                return null;
        }
    }

    // }}}

}

/*
 * Local variables:
 * tab-width: 4
 * c-basic-offset: 4
 * End:
 */

?>
