OCI8Statement.php 10.1 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
{
Benjamin Morel's avatar
Benjamin Morel committed
34 35 36
    /**
     * @var resource
     */
37
    protected $_dbh;
Benjamin Morel's avatar
Benjamin Morel committed
38 39 40 41

    /**
     * @var resource
     */
42
    protected $_sth;
Benjamin Morel's avatar
Benjamin Morel committed
43 44 45 46

    /**
     * @var \Doctrine\DBAL\Driver\OCI8\OCI8Connection
     */
47
    protected $_conn;
Benjamin Morel's avatar
Benjamin Morel committed
48 49 50 51

    /**
     * @var string
     */
52
    protected static $_PARAM = ':param';
Benjamin Morel's avatar
Benjamin Morel committed
53 54 55 56

    /**
     * @var array
     */
57
    protected static $fetchModeMap = array(
58 59
        PDO::FETCH_BOTH => OCI_BOTH,
        PDO::FETCH_ASSOC => OCI_ASSOC,
60
        PDO::FETCH_NUM => OCI_NUM,
61
        PDO::FETCH_COLUMN => OCI_NUM,
62
    );
Benjamin Morel's avatar
Benjamin Morel committed
63 64 65 66

    /**
     * @var integer
     */
67
    protected $_defaultFetchMode = PDO::FETCH_BOTH;
Benjamin Morel's avatar
Benjamin Morel committed
68 69 70 71

    /**
     * @var array
     */
72
    protected $_paramMap = array();
73

74 75 76 77 78 79 80 81 82
    /**
     * Holds references to bound parameter values.
     *
     * This is a new requirement for PHP7's oci8 extension that prevents bound values from being garbage collected.
     *
     * @var array
     */
    private $boundValues = array();

83 84 85 86 87 88 89
    /**
     * Indicates whether the statement is in the state when fetching results is possible
     *
     * @var bool
     */
    private $result = false;

90 91 92
    /**
     * Creates a new OCI8Statement that uses the given connection handle and SQL statement.
     *
Benjamin Morel's avatar
Benjamin Morel committed
93 94 95
     * @param resource                                  $dbh       The connection handle.
     * @param string                                    $statement The SQL statement.
     * @param \Doctrine\DBAL\Driver\OCI8\OCI8Connection $conn
96
     */
97
    public function __construct($dbh, $statement, OCI8Connection $conn)
98
    {
99 100
        list($statement, $paramMap) = self::convertPositionalToNamedPlaceholders($statement);
        $this->_sth = oci_parse($dbh, $statement);
101
        $this->_dbh = $dbh;
102
        $this->_paramMap = $paramMap;
103
        $this->_conn = $conn;
104
    }
105 106

    /**
Benjamin Morel's avatar
Benjamin Morel committed
107
     * Converts positional (?) into named placeholders (:param<num>).
108
     *
109 110 111 112 113
     * 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.
     *
114 115 116 117 118
     * 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
119
     * @todo review and test for lost spaces. we experienced missing spaces with oci8 in some sql statements.
Benjamin Morel's avatar
Benjamin Morel committed
120
     *
121
     * @param string $statement The SQL statement to convert.
Benjamin Morel's avatar
Benjamin Morel committed
122
     *
123
     * @return string
124
     */
125
    static public function convertPositionalToNamedPlaceholders($statement)
126
    {
127
        $count = 1;
128 129 130 131 132 133 134 135 136 137 138 139
        $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;
Steve Müller's avatar
Steve Müller committed
140
            } elseif ($statement[$i] == "'" || $statement[$i] == '"') {
141 142
                $inLiteral = ! $inLiteral; // switch state!
            }
143
        }
144

145
        return array($statement, $paramMap);
146 147 148 149 150 151 152
    }

    /**
     * {@inheritdoc}
     */
    public function bindValue($param, $value, $type = null)
    {
153
        return $this->bindParam($param, $value, $type, null);
154 155 156 157 158
    }

    /**
     * {@inheritdoc}
     */
Benjamin Eberlei's avatar
Benjamin Eberlei committed
159
    public function bindParam($column, &$variable, $type = null, $length = null)
160 161
    {
        $column = isset($this->_paramMap[$column]) ? $this->_paramMap[$column] : $column;
162 163 164 165 166

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

167 168
            $this->boundValues[$column] =& $lob;

169
            return oci_bind_by_name($this->_sth, $column, $lob, -1, OCI_B_BLOB);
Steve Müller's avatar
Steve Müller committed
170
        } elseif ($length !== null) {
171 172
            $this->boundValues[$column] =& $variable;

Benjamin Eberlei's avatar
Benjamin Eberlei committed
173
            return oci_bind_by_name($this->_sth, $column, $variable, $length);
174
        }
Benjamin Eberlei's avatar
Benjamin Eberlei committed
175

176 177
        $this->boundValues[$column] =& $variable;

Benjamin Eberlei's avatar
Benjamin Eberlei committed
178
        return oci_bind_by_name($this->_sth, $column, $variable);
179 180 181
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
182
     * {@inheritdoc}
183 184 185
     */
    public function closeCursor()
    {
186 187 188 189 190
        // not having the result means there's nothing to close
        if (!$this->result) {
            return true;
        }

191
        oci_cancel($this->_sth);
192

193 194
        $this->result = false;

195
        return true;
196 197
    }

198
    /**
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214
     * {@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'];
        }
Benjamin Morel's avatar
Benjamin Morel committed
215

216 217
        return $error;
    }
218

219 220 221 222 223 224 225 226 227 228 229
    /**
     * {@inheritdoc}
     */
    public function errorInfo()
    {
        return oci_error($this->_sth);
    }

    /**
     * {@inheritdoc}
     */
230
    public function execute($params = null)
231
    {
232
        if ($params) {
233
            $hasZeroIndex = array_key_exists(0, $params);
234 235 236 237 238 239
            foreach ($params as $key => $val) {
                if ($hasZeroIndex && is_numeric($key)) {
                    $this->bindValue($key + 1, $val);
                } else {
                    $this->bindValue($key, $val);
                }
240 241
            }
        }
242

243
        $ret = @oci_execute($this->_sth, $this->_conn->getExecuteMode());
244
        if ( ! $ret) {
245 246
            throw OCI8Exception::fromErrorInfo($this->errorInfo());
        }
Benjamin Morel's avatar
Benjamin Morel committed
247

248 249
        $this->result = true;

250
        return $ret;
251 252
    }

253 254 255
    /**
     * {@inheritdoc}
     */
256
    public function setFetchMode($fetchMode, $arg2 = null, $arg3 = null)
257
    {
258
        $this->_defaultFetchMode = $fetchMode;
Benjamin Morel's avatar
Benjamin Morel committed
259 260

        return true;
261 262 263 264 265 266 267
    }

    /**
     * {@inheritdoc}
     */
    public function getIterator()
    {
268
        $data = $this->fetchAll();
Benjamin Morel's avatar
Benjamin Morel committed
269

270 271 272
        return new \ArrayIterator($data);
    }

273 274 275
    /**
     * {@inheritdoc}
     */
276
    public function fetch($fetchMode = null)
277
    {
278 279 280 281 282 283
        // do not try fetching from the statement if it's not expected to contain result
        // in order to prevent exceptional situation
        if (!$this->result) {
            return false;
        }

284 285 286
        $fetchMode = $fetchMode ?: $this->_defaultFetchMode;
        if ( ! isset(self::$fetchModeMap[$fetchMode])) {
            throw new \InvalidArgumentException("Invalid fetch style: " . $fetchMode);
287
        }
288

289
        return oci_fetch_array($this->_sth, self::$fetchModeMap[$fetchMode] | OCI_RETURN_NULLS | OCI_RETURN_LOBS);
290 291 292 293 294
    }

    /**
     * {@inheritdoc}
     */
295
    public function fetchAll($fetchMode = null)
296
    {
297 298 299
        $fetchMode = $fetchMode ?: $this->_defaultFetchMode;
        if ( ! isset(self::$fetchModeMap[$fetchMode])) {
            throw new \InvalidArgumentException("Invalid fetch style: " . $fetchMode);
300
        }
301

302
        $result = array();
303 304
        if (self::$fetchModeMap[$fetchMode] === OCI_BOTH) {
            while ($row = $this->fetch($fetchMode)) {
305 306 307
                $result[] = $row;
            }
        } else {
308
            $fetchStructure = OCI_FETCHSTATEMENT_BY_ROW;
309
            if ($fetchMode == PDO::FETCH_COLUMN) {
310 311
                $fetchStructure = OCI_FETCHSTATEMENT_BY_COLUMN;
            }
312

313 314 315 316 317 318
            // do not try fetching from the statement if it's not expected to contain result
            // in order to prevent exceptional situation
            if (!$this->result) {
                return array();
            }

319
            oci_fetch_all($this->_sth, $result, 0, -1,
320
                self::$fetchModeMap[$fetchMode] | OCI_RETURN_NULLS | $fetchStructure | OCI_RETURN_LOBS);
321

322
            if ($fetchMode == PDO::FETCH_COLUMN) {
323 324
                $result = $result[0];
            }
325
        }
326

327 328 329 330 331 332 333 334
        return $result;
    }

    /**
     * {@inheritdoc}
     */
    public function fetchColumn($columnIndex = 0)
    {
335 336 337 338 339 340
        // do not try fetching from the statement if it's not expected to contain result
        // in order to prevent exceptional situation
        if (!$this->result) {
            return false;
        }

341
        $row = oci_fetch_array($this->_sth, OCI_NUM | OCI_RETURN_NULLS | OCI_RETURN_LOBS);
Benjamin Morel's avatar
Benjamin Morel committed
342

343 344 345 346 347
        if (false === $row) {
            return false;
        }

        return isset($row[$columnIndex]) ? $row[$columnIndex] : null;
348 349 350 351 352 353 354 355
    }

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