Failed Conditions
Pull Request — develop (#3486)
by Sergei
194:17 queued 129:15
created

OCI8Statement::findClosingQuote()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 19
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 2

Importance

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

151
                $result = self::findClosingQuote($statement, $tokenOffset, /** @scrutinizer ignore-type */ $currentLiteralDelimiter);
Loading history...
152
            }
153
        } while ($result);
154
155 492
        if ($currentLiteralDelimiter) {
156 492
            throw new OCI8Exception(sprintf(
157
                'The statement contains non-terminated string literal starting at offset %d',
158 492
                $tokenOffset - 1
159
            ));
160
        }
161
162
        $fragments[] = substr($statement, $fragmentOffset);
163
        $statement   = implode('', $fragments);
164
165
        return [$statement, $paramMap];
166
    }
167
168
    /**
169
     * Finds next placeholder or opening quote.
170
     *
171
     * @param string             $statement               The SQL statement to parse
172
     * @param string             $tokenOffset             The offset to start searching from
173
     * @param int                $fragmentOffset          The offset to build the next fragment from
174 495
     * @param string[]           $fragments               Fragments of the original statement not containing placeholders
175
     * @param string|null        $currentLiteralDelimiter The delimiter of the current string literal
176
     *                                                    or NULL if not currently in a literal
177
     * @param array<int, string> $paramMap                Mapping of the original parameter positions to their named replacements
178
     *
179
     * @return bool Whether the token was found
180
     */
181
    private static function findPlaceholderOrOpeningQuote(
182 495
        $statement,
183
        &$tokenOffset,
184 495
        &$fragmentOffset,
185 492
        &$fragments,
186
        &$currentLiteralDelimiter,
187
        &$paramMap
188 459
    ) {
189 353
        $token = self::findToken($statement, $tokenOffset, '/[?\'"]/');
0 ignored issues
show
Bug introduced by
$tokenOffset of type string is incompatible with the type integer expected by parameter $offset of Doctrine\DBAL\Driver\OCI...8Statement::findToken(). ( Ignorable by Annotation )

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

189
        $token = self::findToken($statement, /** @scrutinizer ignore-type */ $tokenOffset, '/[?\'"]/');
Loading history...
190 353
191 353
        if (! $token) {
192 353
            return false;
193 353
        }
194 353
195 353
        if ($token === '?') {
196
            $position            = count($paramMap) + 1;
197 353
            $param               = ':param' . $position;
198
            $fragments[]         = substr($statement, $fragmentOffset, $tokenOffset - $fragmentOffset);
199
            $fragments[]         = $param;
200 304
            $paramMap[$position] = $param;
201 304
            $tokenOffset        += 1;
202
            $fragmentOffset      = $tokenOffset;
203 304
204
            return true;
205
        }
206
207
        $currentLiteralDelimiter = $token;
208
        ++$tokenOffset;
209
210
        return true;
211
    }
212
213
    /**
214
     * Finds closing quote
215
     *
216 304
     * @param string $statement               The SQL statement to parse
217
     * @param string $tokenOffset             The offset to start searching from
218
     * @param string $currentLiteralDelimiter The delimiter of the current string literal
219
     *
220
     * @return bool Whether the token was found
221 304
     */
222 304
    private static function findClosingQuote(
223 304
        $statement,
224 304
        &$tokenOffset,
225
        &$currentLiteralDelimiter
226
    ) {
227 304
        $token = self::findToken(
228 3
            $statement,
229
            $tokenOffset,
0 ignored issues
show
Bug introduced by
$tokenOffset of type string is incompatible with the type integer expected by parameter $offset of Doctrine\DBAL\Driver\OCI...8Statement::findToken(). ( Ignorable by Annotation )

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

229
            /** @scrutinizer ignore-type */ $tokenOffset,
Loading history...
230
            '/' . preg_quote($currentLiteralDelimiter, '/') . '/'
231 302
        );
232 302
233
        if (! $token) {
234 302
            return false;
235
        }
236
237
        $currentLiteralDelimiter = false;
238
        ++$tokenOffset;
239
240
        return true;
241
    }
242
243
    /**
244
     * Finds the token described by regex starting from the given offset. Updates the offset with the position
245
     * where the token was found.
246
     *
247 495
     * @param string $statement The SQL statement to parse
248
     * @param int    $offset    The offset to start searching from
249 495
     * @param string $regex     The regex containing token pattern
250 459
     *
251 459
     * @return string|null Token or NULL if not found
252
     */
253
    private static function findToken($statement, &$offset, $regex)
254 495
    {
255
        if (preg_match($regex, $statement, $matches, PREG_OFFSET_CAPTURE, $offset)) {
256
            $offset = $matches[0][1];
257
            return $matches[0][0];
258
        }
259
260 119
        return null;
261
    }
262 119
263
    /**
264
     * {@inheritdoc}
265
     */
266
    public function bindValue($param, $value, $type = ParameterType::STRING) : void
267
    {
268 124
        $this->bindParam($param, $value, $type, null);
269
    }
270 124
271
    /**
272 124
     * {@inheritdoc}
273 4
     */
274 4
    public function bindParam($column, &$variable, $type = ParameterType::STRING, $length = null) : void
275
    {
276 4
        $column = $this->_paramMap[$column];
277
278
        if ($type === ParameterType::LARGE_OBJECT) {
279 124
            $lob = oci_new_descriptor($this->_dbh, OCI_D_LOB);
280
281 124
            $class = 'OCI-Lob';
282 124
            assert($lob instanceof $class);
283 124
284 124
            $lob->writeTemporary($variable, OCI_TEMP_BLOB);
285 124
286 124
            $variable =& $lob;
287
        }
288
289
        $this->boundValues[$column] =& $variable;
290
291
        if (! oci_bind_by_name(
292
            $this->_sth,
293 124
            $column,
294
            $variable,
295 124
            $length ?? -1,
296
            $this->convertParameterType($type)
297 1
        )) {
298
            throw OCI8Exception::fromErrorInfo($this->errorInfo());
299
        }
300 4
    }
301
302
    /**
303 122
     * Converts DBAL parameter type to oci8 parameter type
304
     */
305
    private function convertParameterType(int $type) : int
306
    {
307
        switch ($type) {
308
            case ParameterType::BINARY:
309
                return OCI_B_BIN;
310 19
311
            case ParameterType::LARGE_OBJECT:
312
                return OCI_B_BLOB;
313 19
314 4
            default:
315
                return SQLT_CHR;
316
        }
317 15
    }
318
319 15
    /**
320
     * {@inheritdoc}
321 15
     */
322
    public function closeCursor() : void
323
    {
324
        // not having the result means there's nothing to close
325
        if (! $this->result) {
326
            return;
327 4
        }
328
329 4
        oci_cancel($this->_sth);
330
331
        $this->result = false;
332
    }
333
334
    /**
335
     * {@inheritdoc}
336
     */
337
    public function columnCount()
338
    {
339
        return oci_num_fields($this->_sth) ?: 0;
340
    }
341
342
    /**
343
     * {@inheritdoc}
344
     */
345
    public function errorCode()
346
    {
347
        $error = oci_error($this->_sth);
348 140
        if ($error !== false) {
349
            $error = $error['code'];
350 140
        }
351
352
        return $error;
353
    }
354
355
    /**
356 263
     * {@inheritdoc}
357
     */
358 263
    public function errorInfo()
359 92
    {
360 92
        $error = oci_error($this->_sth);
361 92
362 92
        if ($error === false) {
363
            return [];
364
        }
365
366
        return $error;
367 92
    }
368 92
369
    /**
370
     * {@inheritdoc}
371
     */
372
    public function execute($params = null) : void
373 259
    {
374 259
        if ($params) {
375 142
            $hasZeroIndex = array_key_exists(0, $params);
376
377
            foreach ($params as $key => $val) {
378 256
                if ($hasZeroIndex && is_int($key)) {
379
                    $param = $key + 1;
380 256
                } else {
381
                    $param = $key;
382
                }
383
384
                $this->bindValue($param, $val);
385
            }
386 229
        }
387
388 229
        $ret = @oci_execute($this->_sth, $this->_conn->getExecuteMode());
389
        if (! $ret) {
390 229
            throw OCI8Exception::fromErrorInfo($this->errorInfo());
391
        }
392
393
        $this->result = true;
394
    }
395
396 3
    /**
397
     * {@inheritdoc}
398 3
     */
399
    public function setFetchMode($fetchMode, ...$args) : void
400
    {
401
        $this->_defaultFetchMode = $fetchMode;
402
    }
403
404 78
    /**
405
     * {@inheritdoc}
406
     */
407
    public function getIterator()
408 78
    {
409 3
        return new StatementIterator($this);
410
    }
411
412 75
    /**
413
     * {@inheritdoc}
414 75
     */
415 1
    public function fetch($fetchMode = null, ...$args)
416
    {
417
        // do not try fetching from the statement if it's not expected to contain result
418 74
        // in order to prevent exceptional situation
419 1
        if (! $this->result) {
420
            return false;
421
        }
422 73
423
        $fetchMode = $fetchMode ?: $this->_defaultFetchMode;
424
425
        if ($fetchMode === FetchMode::COLUMN) {
426 73
            return $this->fetchColumn();
427 73
        }
428 73
429
        if ($fetchMode === FetchMode::STANDARD_OBJECT) {
430
            return oci_fetch_object($this->_sth);
431
        }
432
433
        if (! isset(self::$fetchModeMap[$fetchMode])) {
434
            throw new InvalidArgumentException('Invalid fetch style: ' . $fetchMode);
435 97
        }
436
437 97
        return oci_fetch_array(
438
            $this->_sth,
439 97
            self::$fetchModeMap[$fetchMode] | OCI_RETURN_NULLS | OCI_RETURN_LOBS
440
        );
441 97
    }
442 1
443 1
    /**
444
     * {@inheritdoc}
445
     */
446 1
    public function fetchAll($fetchMode = null, ...$args)
447
    {
448
        $fetchMode = $fetchMode ?: $this->_defaultFetchMode;
449 96
450
        $result = [];
451
452
        if ($fetchMode === FetchMode::STANDARD_OBJECT) {
453 96
            while ($row = $this->fetch($fetchMode)) {
454 1
                $result[] = $row;
455 1
            }
456
457
            return $result;
458 95
        }
459
460 95
        if (! isset(self::$fetchModeMap[$fetchMode])) {
461 6
            throw new InvalidArgumentException('Invalid fetch style: ' . $fetchMode);
462
        }
463
464
        if (self::$fetchModeMap[$fetchMode] === OCI_BOTH) {
465
            while ($row = $this->fetch($fetchMode)) {
466 95
                $result[] = $row;
467 3
            }
468
        } else {
469
            $fetchStructure = OCI_FETCHSTATEMENT_BY_ROW;
470 92
471 92
            if ($fetchMode === FetchMode::COLUMN) {
472 92
                $fetchStructure = OCI_FETCHSTATEMENT_BY_COLUMN;
473 92
            }
474 92
475 92
            // do not try fetching from the statement if it's not expected to contain result
476
            // in order to prevent exceptional situation
477
            if (! $this->result) {
478 92
                return [];
479 6
            }
480
481
            oci_fetch_all(
482
                $this->_sth,
483 93
                $result,
484
                0,
485
                -1,
486
                self::$fetchModeMap[$fetchMode] | OCI_RETURN_NULLS | $fetchStructure | OCI_RETURN_LOBS
487
            );
488
489 53
            if ($fetchMode === FetchMode::COLUMN) {
490
                $result = $result[0];
491
            }
492
        }
493 53
494 3
        return $result;
495
    }
496
497 50
    /**
498
     * {@inheritdoc}
499 50
     */
500 3
    public function fetchColumn($columnIndex = 0)
501
    {
502
        // do not try fetching from the statement if it's not expected to contain result
503 47
        // in order to prevent exceptional situation
504
        if (! $this->result) {
505
            return false;
506
        }
507
508
        $row = oci_fetch_array($this->_sth, OCI_NUM | OCI_RETURN_NULLS | OCI_RETURN_LOBS);
509 176
510
        if ($row === false) {
511 176
            return false;
512
        }
513
514
        if (! array_key_exists($columnIndex, $row)) {
515
            throw DBALException::invalidColumnIndex($columnIndex, count($row));
516
        }
517
518
        return $row[$columnIndex];
519
    }
520
521
    /**
522
     * {@inheritdoc}
523
     */
524
    public function rowCount() : int
525
    {
526
        return oci_num_rows($this->_sth) ?: 0;
527
    }
528
}
529