<?php
/**
 * @copyright NetMonsters <team@netmonsters.ru>
 * @link http://netmonsters.ru
 * @package Majestic
 * @subpackage db
 * @since 2010-02-19
 * @version SVN: $Id$
 * @filesource $URL$
 */

/**
 * @property MySQLiDriver $driver
 * @property MySQLi_Result $result
 */
class MySQLiStatement extends DbStatement
{
    
    /**
     * Fetches single row
     * 
     * @param mixed $style
     * @return mixed
     */
    public function fetch($style = Db::FETCH_OBJ)
    {
        if (!$this->result) {
            return false;
        }
        
        $row = false;
        switch ($style) {
            case Db::FETCH_OBJ:
                $row = $this->result->fetch_object();
            break;
            case Db::FETCH_NUM:
                $row = $this->result->fetch_array(MYSQLI_NUM);
            break;
            case Db::FETCH_ASSOC:
                $row = $this->result->fetch_assoc();
            break;
            case Db::FETCH_BOTH:
                $row = $this->result->fetch_array(MYSQLI_BOTH);
            break;
            default:
                throw new Exception('Invalid fetch mode "' . $style . '" specified');
        }
        return $row;
    }
    
    /**
     * @param string $class
     */
    public function fetchObject($class = 'stdClass')
    {
        return $this->result->fetch_object($class);
    }
    
    public function close()
    {
        if ($this->result !== null) {
            $this->result->close();
            $this->result = null;
        }
    }
    
    public function affectedRows()
    {
        return $this->driver->getConnection()->affected_rows;
    }
    
    public function numRows()
    {
        if ($this->result) {
            return $this->result->num_rows;
        }
        return false;
    }
    
    protected function driverExecute($sql)
    {
        /**
         * @var MySQLi
         */
        $mysqli = $this->driver->getConnection();
        if (DEBUG) {
            $profiler = Profiler::getInstance()->profilerCommand('MySQL', $sql);
            $result = $mysqli->query($sql);
            $profiler->end();
        } else {
            $result = $mysqli->query($sql);
        }
        if ($result === false) {
            $message = $mysqli->error . "\nQuery: \"" . $sql . '"';
            throw new Exception($message, $mysqli->errno);
        }
        if ($result instanceof MySQLi_Result) {
            $this->result = $result;
        }
        return true;
    }
}