OCI8Statement.php 8.26 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
<?php
/*
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS 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 COPYRIGHT
 * OWNER OR 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
Benjamin Eberlei's avatar
Benjamin Eberlei committed
16
 * and is licensed under the MIT license. For more information, see
17 18 19 20 21
 * <http://www.doctrine-project.org>.
 */

namespace Doctrine\DBAL\Driver\OCI8;

22 23 24
use PDO;
use IteratorAggregate;
use Doctrine\DBAL\Driver\Statement;
25 26 27 28 29 30 31

/**
 * The OCI8 implementation of the Statement interface.
 *
 * @since 2.0
 * @author Roman Borschel <roman@code-factory.org>
 */
32
class OCI8Statement implements \IteratorAggregate, Statement
33 34
{
    /** Statement handle. */
35
    protected $_dbh;
36
    protected $_sth;
37
    protected $_conn;
38
    protected static $_PARAM = ':param';
39
    protected static $fetchModeMap = array(
40 41
        PDO::FETCH_BOTH => OCI_BOTH,
        PDO::FETCH_ASSOC => OCI_ASSOC,
42 43
        PDO::FETCH_NUM => OCI_NUM,
        PDO::PARAM_LOB => OCI_B_BLOB,
44
        PDO::FETCH_COLUMN => OCI_NUM,
45
    );
46
    protected $_defaultFetchMode = PDO::FETCH_BOTH;
47
    protected $_paramMap = array();
48 49 50 51 52 53 54

    /**
     * Creates a new OCI8Statement that uses the given connection handle and SQL statement.
     *
     * @param resource $dbh The connection handle.
     * @param string $statement The SQL statement.
     */
55
    public function __construct($dbh, $statement, OCI8Connection $conn)
56
    {
57 58
        list($statement, $paramMap) = self::convertPositionalToNamedPlaceholders($statement);
        $this->_sth = oci_parse($dbh, $statement);
59
        $this->_dbh = $dbh;
60
        $this->_paramMap = $paramMap;
61
        $this->_conn = $conn;
62
    }
63 64

    /**
65 66
     * Convert positional (?) into named placeholders (:param<num>)
     *
67 68 69 70 71
     * Oracle does not support positional parameters, hence this method converts all
     * positional parameters into artificially named parameters. Note that this conversion
     * is not perfect. All question marks (?) in the original statement are treated as
     * placeholders and converted to a named parameter.
     *
72 73 74 75 76
     * The algorithm uses a state machine with two possible states: InLiteral and NotInLiteral.
     * Question marks inside literal strings are therefore handled correctly by this method.
     * This comes at a cost, the whole sql statement has to be looped over.
     *
     * @todo extract into utility class in Doctrine\DBAL\Util namespace
77
     * @todo review and test for lost spaces. we experienced missing spaces with oci8 in some sql statements.
78 79
     * @param string $statement The SQL statement to convert.
     * @return string
80
     */
81
    static public function convertPositionalToNamedPlaceholders($statement)
82
    {
83
        $count = 1;
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
        $inLiteral = false; // a valid query never starts with quotes
        $stmtLen = strlen($statement);
        $paramMap = array();
        for ($i = 0; $i < $stmtLen; $i++) {
            if ($statement[$i] == '?' && !$inLiteral) {
                // real positional parameter detected
                $paramMap[$count] = ":param$count";
                $len = strlen($paramMap[$count]);
                $statement = substr_replace($statement, ":param$count", $i, 1);
                $i += $len-1; // jump ahead
                $stmtLen = strlen($statement); // adjust statement length
                ++$count;
            } else if ($statement[$i] == "'" || $statement[$i] == '"') {
                $inLiteral = ! $inLiteral; // switch state!
            }
99
        }
100

101
        return array($statement, $paramMap);
102 103 104 105 106 107 108
    }

    /**
     * {@inheritdoc}
     */
    public function bindValue($param, $value, $type = null)
    {
109
        return $this->bindParam($param, $value, $type, null);
110 111 112 113 114
    }

    /**
     * {@inheritdoc}
     */
115
    public function bindParam($column, &$variable, $type = null,$length = null)
116 117
    {
        $column = isset($this->_paramMap[$column]) ? $this->_paramMap[$column] : $column;
118 119 120 121 122 123 124 125 126

        if ($type == \PDO::PARAM_LOB) {
            $lob = oci_new_descriptor($this->_dbh, OCI_D_LOB);
            $lob->writeTemporary($variable, OCI_TEMP_BLOB);

            return oci_bind_by_name($this->_sth, $column, $lob, -1, OCI_B_BLOB);
        } else {
            return oci_bind_by_name($this->_sth, $column, $variable);
        }
127 128 129 130 131 132 133 134 135 136 137 138
    }

    /**
     * Closes the cursor, enabling the statement to be executed again.
     *
     * @return boolean              Returns TRUE on success or FALSE on failure.
     */
    public function closeCursor()
    {
        return oci_free_statement($this->_sth);
    }

139
    /**
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
     * {@inheritdoc}
     */
    public function columnCount()
    {
        return oci_num_fields($this->_sth);
    }

    /**
     * {@inheritdoc}
     */
    public function errorCode()
    {
        $error = oci_error($this->_sth);
        if ($error !== false) {
            $error = $error['code'];
        }
        return $error;
    }
158

159 160 161 162 163 164 165 166 167 168 169
    /**
     * {@inheritdoc}
     */
    public function errorInfo()
    {
        return oci_error($this->_sth);
    }

    /**
     * {@inheritdoc}
     */
170
    public function execute($params = null)
171
    {
172
        if ($params) {
173
            $hasZeroIndex = array_key_exists(0, $params);
174 175 176 177 178 179
            foreach ($params as $key => $val) {
                if ($hasZeroIndex && is_numeric($key)) {
                    $this->bindValue($key + 1, $val);
                } else {
                    $this->bindValue($key, $val);
                }
180 181
            }
        }
182

183
        $ret = @oci_execute($this->_sth, $this->_conn->getExecuteMode());
184
        if ( ! $ret) {
185 186 187
            throw OCI8Exception::fromErrorInfo($this->errorInfo());
        }
        return $ret;
188 189
    }

190 191 192
    /**
     * {@inheritdoc}
     */
193
    public function setFetchMode($fetchMode, $arg2 = null, $arg3 = null)
194
    {
195
        $this->_defaultFetchMode = $fetchMode;
196 197 198 199 200 201 202
    }

    /**
     * {@inheritdoc}
     */
    public function getIterator()
    {
203
        $data = $this->fetchAll();
204 205 206
        return new \ArrayIterator($data);
    }

207 208 209
    /**
     * {@inheritdoc}
     */
210
    public function fetch($fetchMode = null)
211
    {
212 213 214
        $fetchMode = $fetchMode ?: $this->_defaultFetchMode;
        if ( ! isset(self::$fetchModeMap[$fetchMode])) {
            throw new \InvalidArgumentException("Invalid fetch style: " . $fetchMode);
215
        }
216

217
        return oci_fetch_array($this->_sth, self::$fetchModeMap[$fetchMode] | OCI_RETURN_NULLS | OCI_RETURN_LOBS);
218 219 220 221 222
    }

    /**
     * {@inheritdoc}
     */
223
    public function fetchAll($fetchMode = null)
224
    {
225 226 227
        $fetchMode = $fetchMode ?: $this->_defaultFetchMode;
        if ( ! isset(self::$fetchModeMap[$fetchMode])) {
            throw new \InvalidArgumentException("Invalid fetch style: " . $fetchMode);
228
        }
229

230
        $result = array();
231 232
        if (self::$fetchModeMap[$fetchMode] === OCI_BOTH) {
            while ($row = $this->fetch($fetchMode)) {
233 234 235
                $result[] = $row;
            }
        } else {
236
            $fetchStructure = OCI_FETCHSTATEMENT_BY_ROW;
237
            if ($fetchMode == PDO::FETCH_COLUMN) {
238 239
                $fetchStructure = OCI_FETCHSTATEMENT_BY_COLUMN;
            }
240

241
            oci_fetch_all($this->_sth, $result, 0, -1,
242
                    self::$fetchModeMap[$fetchMode] | OCI_RETURN_NULLS | $fetchStructure | OCI_RETURN_LOBS);
243

244
            if ($fetchMode == PDO::FETCH_COLUMN) {
245 246
                $result = $result[0];
            }
247
        }
248

249 250 251 252 253 254 255 256
        return $result;
    }

    /**
     * {@inheritdoc}
     */
    public function fetchColumn($columnIndex = 0)
    {
257
        $row = oci_fetch_array($this->_sth, OCI_NUM | OCI_RETURN_NULLS | OCI_RETURN_LOBS);
258
        return isset($row[$columnIndex]) ? $row[$columnIndex] : false;
259 260 261 262 263 264 265 266
    }

    /**
     * {@inheritdoc}
     */
    public function rowCount()
    {
        return oci_num_rows($this->_sth);
267
    }
268
}