Completed
Pull Request — master (#3772)
by Christoph
51:54
created

OCI8Statement::bindParam()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 25
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 3.0021

Importance

Changes 0
Metric Value
eloc 15
dl 0
loc 25
ccs 15
cts 16
cp 0.9375
rs 9.7666
c 0
b 0
f 0
cc 3
nc 4
nop 4
crap 3.0021
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Doctrine\DBAL\Driver\OCI8;
6
7
use Doctrine\DBAL\Driver\Statement;
8
use Doctrine\DBAL\Driver\StatementIterator;
9
use Doctrine\DBAL\Exception\InvalidColumnIndex;
10
use Doctrine\DBAL\FetchMode;
11
use Doctrine\DBAL\ParameterType;
12
use InvalidArgumentException;
13
use IteratorAggregate;
14
use const OCI_ASSOC;
15
use const OCI_B_BIN;
16
use const OCI_B_BLOB;
17
use const OCI_BOTH;
18
use const OCI_D_LOB;
19
use const OCI_FETCHSTATEMENT_BY_COLUMN;
20
use const OCI_FETCHSTATEMENT_BY_ROW;
21
use const OCI_NUM;
22
use const OCI_RETURN_LOBS;
23
use const OCI_RETURN_NULLS;
24
use const OCI_TEMP_BLOB;
25
use const PREG_OFFSET_CAPTURE;
26
use const SQLT_CHR;
27
use function array_key_exists;
28
use function assert;
29
use function count;
30
use function implode;
31
use function is_int;
32
use function is_resource;
33
use function oci_bind_by_name;
34
use function oci_cancel;
35
use function oci_error;
36
use function oci_execute;
37
use function oci_fetch_all;
38
use function oci_fetch_array;
39
use function oci_fetch_object;
40
use function oci_new_descriptor;
41
use function oci_num_fields;
42
use function oci_num_rows;
43
use function oci_parse;
44
use function preg_match;
45
use function preg_quote;
46
use function sprintf;
47
use function substr;
48
49
/**
50
 * The OCI8 implementation of the Statement interface.
51
 */
52
class OCI8Statement implements IteratorAggregate, Statement
53
{
54
    /** @var resource */
55
    protected $_dbh;
56
57
    /** @var resource */
58
    protected $_sth;
59
60
    /** @var OCI8Connection */
61
    protected $_conn;
62
63
    /** @var int[] */
64
    protected static $fetchModeMap = [
65
        FetchMode::MIXED       => OCI_BOTH,
66
        FetchMode::ASSOCIATIVE => OCI_ASSOC,
67
        FetchMode::NUMERIC     => OCI_NUM,
68
        FetchMode::COLUMN      => OCI_NUM,
69
    ];
70
71
    /** @var int */
72
    protected $_defaultFetchMode = FetchMode::MIXED;
73
74
    /** @var string[] */
75
    protected $_paramMap = [];
76
77
    /**
78
     * Holds references to bound parameter values.
79
     *
80
     * This is a new requirement for PHP7's oci8 extension that prevents bound values from being garbage collected.
81
     *
82
     * @var mixed[]
83
     */
84
    private $boundValues = [];
85
86
    /**
87
     * Indicates whether the statement is in the state when fetching results is possible
88
     *
89
     * @var bool
90
     */
91
    private $result = false;
92
93
    /**
94
     * Creates a new OCI8Statement that uses the given connection handle and SQL statement.
95
     *
96
     * @param resource $dbh   The connection handle.
97
     * @param string   $query The SQL query.
98
     */
99 696
    public function __construct($dbh, string $query, OCI8Connection $conn)
100
    {
101 696
        [$query, $paramMap] = self::convertPositionalToNamedPlaceholders($query);
102
103 696
        $stmt = oci_parse($dbh, $query);
104 696
        assert(is_resource($stmt));
105
106 696
        $this->_sth      = $stmt;
107 696
        $this->_dbh      = $dbh;
108 696
        $this->_paramMap = $paramMap;
109 696
        $this->_conn     = $conn;
110 696
    }
111
112
    /**
113
     * Converts positional (?) into named placeholders (:param<num>).
114
     *
115
     * Oracle does not support positional parameters, hence this method converts all
116
     * positional parameters into artificially named parameters. Note that this conversion
117
     * is not perfect. All question marks (?) in the original statement are treated as
118
     * placeholders and converted to a named parameter.
119
     *
120
     * The algorithm uses a state machine with two possible states: InLiteral and NotInLiteral.
121
     * Question marks inside literal strings are therefore handled correctly by this method.
122
     * This comes at a cost, the whole sql statement has to be looped over.
123
     *
124
     * @param string $statement The SQL statement to convert.
125
     *
126
     * @return mixed[] [0] => the statement value (string), [1] => the paramMap value (array).
127
     *
128
     * @throws OCI8Exception
129
     *
130
     * @todo extract into utility class in Doctrine\DBAL\Util namespace
131
     * @todo review and test for lost spaces. we experienced missing spaces with oci8 in some sql statements.
132
     */
133 873
    public static function convertPositionalToNamedPlaceholders(string $statement) : array
134
    {
135 873
        $fragmentOffset          = $tokenOffset = 0;
136 873
        $fragments               = $paramMap = [];
137 873
        $currentLiteralDelimiter = null;
138
139
        do {
140 873
            if ($currentLiteralDelimiter === null) {
141 873
                $result = self::findPlaceholderOrOpeningQuote(
142 873
                    $statement,
143
                    $tokenOffset,
144
                    $fragmentOffset,
145
                    $fragments,
146
                    $currentLiteralDelimiter,
147
                    $paramMap
148
                );
149
            } else {
150 457
                $result = self::findClosingQuote($statement, $tokenOffset, $currentLiteralDelimiter);
0 ignored issues
show
Bug introduced by
$currentLiteralDelimiter of type null is incompatible with the type string expected by parameter $currentLiteralDelimiter of Doctrine\DBAL\Driver\OCI...ent::findClosingQuote(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

150
                $result = self::findClosingQuote($statement, $tokenOffset, /** @scrutinizer ignore-type */ $currentLiteralDelimiter);
Loading history...
151
            }
152 873
        } while ($result);
153
154 873
        if ($currentLiteralDelimiter) {
155 9
            throw new OCI8Exception(sprintf(
156 9
                'The statement contains non-terminated string literal starting at offset %d.',
157 9
                $tokenOffset - 1
158
            ));
159
        }
160
161 864
        $fragments[] = substr($statement, $fragmentOffset);
162 864
        $statement   = implode('', $fragments);
163
164 864
        return [$statement, $paramMap];
165
    }
166
167
    /**
168
     * Finds next placeholder or opening quote.
169
     *
170
     * @param string      $statement               The SQL statement to parse
171
     * @param int         $tokenOffset             The offset to start searching from
172
     * @param int         $fragmentOffset          The offset to build the next fragment from
173
     * @param string[]    $fragments               Fragments of the original statement not containing placeholders
174
     * @param string|null $currentLiteralDelimiter The delimiter of the current string literal
175
     *                                             or NULL if not currently in a literal
176
     * @param string[]    $paramMap                Mapping of the original parameter positions to their named replacements
177
     *
178
     * @return bool Whether the token was found
179
     */
180 873
    private static function findPlaceholderOrOpeningQuote(
181
        string $statement,
182
        int &$tokenOffset,
183
        int &$fragmentOffset,
184
        array &$fragments,
185
        ?string &$currentLiteralDelimiter,
186
        array &$paramMap
187
    ) : bool {
188 873
        $token = self::findToken($statement, $tokenOffset, '/[?\'"]/');
189
190 873
        if (! $token) {
191 864
            return false;
192
        }
193
194 707
        if ($token === '?') {
195 456
            $position            = count($paramMap) + 1;
196 456
            $param               = ':param' . $position;
197 456
            $fragments[]         = substr($statement, $fragmentOffset, $tokenOffset - $fragmentOffset);
198 456
            $fragments[]         = $param;
199 456
            $paramMap[$position] = $param;
200 456
            $tokenOffset        += 1;
201 456
            $fragmentOffset      = $tokenOffset;
202
203 456
            return true;
204
        }
205
206 457
        $currentLiteralDelimiter = $token;
207 457
        ++$tokenOffset;
208
209 457
        return true;
210
    }
211
212
    /**
213
     * Finds closing quote
214
     *
215
     * @param string $statement               The SQL statement to parse
216
     * @param int    $tokenOffset             The offset to start searching from
217
     * @param string $currentLiteralDelimiter The delimiter of the current string literal
218
     *
219
     * @return bool Whether the token was found
220
     */
221 457
    private static function findClosingQuote(
222
        string $statement,
223
        int &$tokenOffset,
224
        string &$currentLiteralDelimiter
225
    ) : bool {
226 457
        $token = self::findToken(
227 365
            $statement,
228
            $tokenOffset,
229 457
            '/' . preg_quote($currentLiteralDelimiter, '/') . '/'
230
        );
231
232 457
        if (! $token) {
233 9
            return false;
234
        }
235
236 451
        $currentLiteralDelimiter = null;
237 451
        ++$tokenOffset;
238
239 451
        return true;
240
    }
241
242
    /**
243
     * Finds the token described by regex starting from the given offset. Updates the offset with the position
244
     * where the token was found.
245
     *
246
     * @param string $statement The SQL statement to parse
247
     * @param int    $offset    The offset to start searching from
248
     * @param string $regex     The regex containing token pattern
249
     *
250
     * @return string|null Token or NULL if not found
251
     */
252 873
    private static function findToken(string $statement, int &$offset, string $regex) : ?string
253
    {
254 873
        if (preg_match($regex, $statement, $matches, PREG_OFFSET_CAPTURE, $offset)) {
255 707
            $offset = $matches[0][1];
256
257 707
            return $matches[0][0];
258
        }
259
260 873
        return null;
261
    }
262
263
    /**
264
     * {@inheritdoc}
265
     */
266 248
    public function bindValue($param, $value, int $type = ParameterType::STRING) : void
267
    {
268 248
        $this->bindParam($param, $value, $type, null);
269 246
    }
270
271
    /**
272
     * {@inheritdoc}
273
     */
274 290
    public function bindParam($param, &$variable, int $type = ParameterType::STRING, ?int $length = null) : void
275
    {
276 290
        $param = $this->_paramMap[$param];
277
278 290
        if ($type === ParameterType::LARGE_OBJECT) {
279 8
            $lob = oci_new_descriptor($this->_dbh, OCI_D_LOB);
280
281 8
            $class = 'OCI-Lob';
282 8
            assert($lob instanceof $class);
283
284 8
            $lob->writeTemporary($variable, OCI_TEMP_BLOB);
285
286 8
            $variable =& $lob;
287
        }
288
289 290
        $this->boundValues[$param] =& $variable;
290
291 290
        if (! oci_bind_by_name(
292 290
            $this->_sth,
293 290
            $param,
294 290
            $variable,
295 290
            $length ?? -1,
296 290
            $this->convertParameterType($type)
297
        )) {
298
            throw OCI8Exception::fromErrorInfo(oci_error($this->_sth));
299
        }
300 288
    }
301
302
    /**
303
     * Converts DBAL parameter type to oci8 parameter type
304
     */
305 290
    private function convertParameterType(int $type) : int
306
    {
307 290
        switch ($type) {
308
            case ParameterType::BINARY:
309 2
                return OCI_B_BIN;
310
311
            case ParameterType::LARGE_OBJECT:
312 8
                return OCI_B_BLOB;
313
314
            default:
315 286
                return SQLT_CHR;
316
        }
317
    }
318
319
    /**
320
     * {@inheritdoc}
321
     */
322 38
    public function closeCursor() : void
323
    {
324
        // not having the result means there's nothing to close
325 38
        if (! $this->result) {
326 6
            return;
327
        }
328
329 32
        oci_cancel($this->_sth);
330
331 32
        $this->result = false;
332 32
    }
333
334
    /**
335
     * {@inheritdoc}
336
     */
337 8
    public function columnCount() : int
338
    {
339 8
        return oci_num_fields($this->_sth) ?: 0;
340
    }
341
342
    /**
343
     * {@inheritdoc}
344
     */
345 700
    public function execute(?array $params = null) : void
346
    {
347 700
        if ($params) {
348 196
            $hasZeroIndex = array_key_exists(0, $params);
349
350 196
            foreach ($params as $key => $val) {
351 196
                if ($hasZeroIndex && is_int($key)) {
352 196
                    $param = $key + 1;
353
                } else {
354
                    $param = $key;
355
                }
356
357 196
                $this->bindValue($param, $val);
358
            }
359
        }
360
361 692
        $ret = @oci_execute($this->_sth, $this->_conn->getExecuteMode());
362 692
        if (! $ret) {
363 302
            throw OCI8Exception::fromErrorInfo(oci_error($this->_sth));
364
        }
365
366 672
        $this->result = true;
367 672
    }
368
369
    /**
370
     * {@inheritdoc}
371
     */
372 622
    public function setFetchMode(int $fetchMode, ...$args) : void
373
    {
374 622
        $this->_defaultFetchMode = $fetchMode;
375 622
    }
376
377
    /**
378
     * {@inheritdoc}
379
     */
380 8
    public function getIterator()
381
    {
382 8
        return new StatementIterator($this);
383
    }
384
385
    /**
386
     * {@inheritdoc}
387
     */
388 234
    public function fetch(?int $fetchMode = null, ...$args)
389
    {
390
        // do not try fetching from the statement if it's not expected to contain result
391
        // in order to prevent exceptional situation
392 234
        if (! $this->result) {
393 6
            return false;
394
        }
395
396 228
        $fetchMode = $fetchMode ?: $this->_defaultFetchMode;
397
398 228
        if ($fetchMode === FetchMode::COLUMN) {
399 2
            return $this->fetchColumn();
400
        }
401
402 226
        if ($fetchMode === FetchMode::STANDARD_OBJECT) {
403 2
            return oci_fetch_object($this->_sth);
404
        }
405
406 224
        if (! isset(self::$fetchModeMap[$fetchMode])) {
407
            throw new InvalidArgumentException(sprintf('Invalid fetch mode %d.', $fetchMode));
408
        }
409
410 224
        return oci_fetch_array(
411 224
            $this->_sth,
412 224
            self::$fetchModeMap[$fetchMode] | OCI_RETURN_NULLS | OCI_RETURN_LOBS
413
        );
414
    }
415
416
    /**
417
     * {@inheritdoc}
418
     */
419 218
    public function fetchAll(?int $fetchMode = null, ...$args) : array
420
    {
421 218
        $fetchMode = $fetchMode ?: $this->_defaultFetchMode;
422
423 218
        $result = [];
424
425 218
        if ($fetchMode === FetchMode::STANDARD_OBJECT) {
426 2
            while ($row = $this->fetch($fetchMode)) {
427 2
                $result[] = $row;
428
            }
429
430 2
            return $result;
431
        }
432
433 216
        if (! isset(self::$fetchModeMap[$fetchMode])) {
434
            throw new InvalidArgumentException(sprintf('Invalid fetch mode %d.', $fetchMode));
435
        }
436
437 216
        if (self::$fetchModeMap[$fetchMode] === OCI_BOTH) {
438 2
            while ($row = $this->fetch($fetchMode)) {
439 2
                $result[] = $row;
440
            }
441
        } else {
442 214
            $fetchStructure = OCI_FETCHSTATEMENT_BY_ROW;
443
444 214
            if ($fetchMode === FetchMode::COLUMN) {
445 14
                $fetchStructure = OCI_FETCHSTATEMENT_BY_COLUMN;
446
            }
447
448
            // do not try fetching from the statement if it's not expected to contain result
449
            // in order to prevent exceptional situation
450 214
            if (! $this->result) {
451 6
                return [];
452
            }
453
454 208
            oci_fetch_all(
455 208
                $this->_sth,
456 208
                $result,
457 208
                0,
458 208
                -1,
459 208
                self::$fetchModeMap[$fetchMode] | OCI_RETURN_NULLS | $fetchStructure | OCI_RETURN_LOBS
460
            );
461
462 208
            if ($fetchMode === FetchMode::COLUMN) {
463 14
                $result = $result[0];
464
            }
465
        }
466
467 210
        return $result;
468
    }
469
470
    /**
471
     * {@inheritdoc}
472
     */
473 368
    public function fetchColumn(int $columnIndex = 0)
474
    {
475
        // do not try fetching from the statement if it's not expected to contain result
476
        // in order to prevent exceptional situation
477 368
        if (! $this->result) {
478 6
            return false;
479
        }
480
481 362
        $row = oci_fetch_array($this->_sth, OCI_NUM | OCI_RETURN_NULLS | OCI_RETURN_LOBS);
482
483 362
        if ($row === false) {
484 6
            return false;
485
        }
486
487 356
        if (! array_key_exists($columnIndex, $row)) {
488 4
            throw InvalidColumnIndex::new($columnIndex, count($row));
489
        }
490
491 352
        return $row[$columnIndex];
492
    }
493
494
    /**
495
     * {@inheritdoc}
496
     */
497 348
    public function rowCount() : int
498
    {
499 348
        return oci_num_rows($this->_sth) ?: 0;
500
    }
501
}
502