Failed Conditions
Push — master ( 4d0d2a...06d1d8 )
by Marco
22s queued 16s
created

convertPositionalToNamedPlaceholders()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 32
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 21
CRAP Score 4

Importance

Changes 0
Metric Value
eloc 22
dl 0
loc 32
ccs 21
cts 21
cp 1
rs 9.568
c 0
b 0
f 0
cc 4
nc 4
nop 1
crap 4
1
<?php
2
3
namespace Doctrine\DBAL\Driver\OCI8;
4
5
use Doctrine\DBAL\Driver\Statement;
6
use Doctrine\DBAL\Driver\StatementIterator;
7
use Doctrine\DBAL\FetchMode;
8
use Doctrine\DBAL\ParameterType;
9
use InvalidArgumentException;
10
use IteratorAggregate;
11
use PDO;
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
     * @param resource $dbh   The connection handle.
98
     * @param string   $query The SQL query.
99
     */
100 296
    public function __construct($dbh, $query, OCI8Connection $conn)
101
    {
102 296
        [$query, $paramMap] = self::convertPositionalToNamedPlaceholders($query);
103
104 296
        $stmt = oci_parse($dbh, $query);
105 296
        assert(is_resource($stmt));
106
107 296
        $this->_sth      = $stmt;
108 296
        $this->_dbh      = $dbh;
109 296
        $this->_paramMap = $paramMap;
110 296
        $this->_conn     = $conn;
111 296
    }
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
     * @return mixed[] [0] => the statement value (string), [1] => the paramMap value (array).
128
     *
129
     * @throws OCI8Exception
130
     *
131
     * @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 497
    public static function convertPositionalToNamedPlaceholders($statement)
135
    {
136 497
        $fragmentOffset          = $tokenOffset = 0;
137 497
        $fragments               = $paramMap = [];
138 497
        $currentLiteralDelimiter = null;
139
140
        do {
141 497
            if (! $currentLiteralDelimiter) {
142 497
                $result = self::findPlaceholderOrOpeningQuote(
143 497
                    $statement,
144 322
                    $tokenOffset,
145 322
                    $fragmentOffset,
146 322
                    $fragments,
147 322
                    $currentLiteralDelimiter,
148 322
                    $paramMap
149
                );
150
            } else {
151 296
                $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 497
        } while ($result);
154
155 497
        if ($currentLiteralDelimiter) {
156 6
            throw new OCI8Exception(sprintf(
157 6
                'The statement contains non-terminated string literal starting at offset %d',
158 6
                $tokenOffset - 1
159
            ));
160
        }
161
162 491
        $fragments[] = substr($statement, $fragmentOffset);
163 491
        $statement   = implode('', $fragments);
164
165 491
        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
     * @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 497
    private static function findPlaceholderOrOpeningQuote(
182
        $statement,
183
        &$tokenOffset,
184
        &$fragmentOffset,
185
        &$fragments,
186
        &$currentLiteralDelimiter,
187
        &$paramMap
188
    ) {
189 497
        $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
191 497
        if (! $token) {
192 491
            return false;
193
        }
194
195 445
        if ($token === '?') {
196 319
            $position            = count($paramMap) + 1;
197 319
            $param               = ':param' . $position;
198 319
            $fragments[]         = substr($statement, $fragmentOffset, $tokenOffset - $fragmentOffset);
199 319
            $fragments[]         = $param;
200 319
            $paramMap[$position] = $param;
201 319
            $tokenOffset        += 1;
202 319
            $fragmentOffset      = $tokenOffset;
203
204 319
            return true;
205
        }
206
207 296
        $currentLiteralDelimiter = $token;
208 296
        ++$tokenOffset;
209
210 296
        return true;
211
    }
212
213
    /**
214
     * Finds closing quote
215
     *
216
     * @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
     */
222 296
    private static function findClosingQuote(
223
        $statement,
224
        &$tokenOffset,
225
        &$currentLiteralDelimiter
226
    ) {
227 296
        $token = self::findToken(
228 171
            $statement,
229 171
            $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 296
            '/' . preg_quote($currentLiteralDelimiter, '/') . '/'
231
        );
232
233 296
        if (! $token) {
234 6
            return false;
235
        }
236
237 292
        $currentLiteralDelimiter = false;
238 292
        ++$tokenOffset;
239
240 292
        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
     * @param string $statement The SQL statement to parse
248
     * @param int    $offset    The offset to start searching from
249
     * @param string $regex     The regex containing token pattern
250
     *
251
     * @return string|null Token or NULL if not found
252
     */
253 497
    private static function findToken($statement, &$offset, $regex)
254
    {
255 497
        if (preg_match($regex, $statement, $matches, PREG_OFFSET_CAPTURE, $offset)) {
256 445
            $offset = $matches[0][1];
257
258 445
            return $matches[0][0];
259
        }
260
261 497
        return null;
262
    }
263
264
    /**
265
     * {@inheritdoc}
266
     */
267 119
    public function bindValue($param, $value, $type = ParameterType::STRING)
268
    {
269 119
        return $this->bindParam($param, $value, $type, null);
270
    }
271
272
    /**
273
     * {@inheritdoc}
274
     */
275 124
    public function bindParam($column, &$variable, $type = ParameterType::STRING, $length = null)
276
    {
277 124
        $column = $this->_paramMap[$column];
278
279 124
        if ($type === ParameterType::LARGE_OBJECT) {
280 4
            $lob = oci_new_descriptor($this->_dbh, OCI_D_LOB);
281
282 4
            $class = 'OCI-Lob';
283 4
            assert($lob instanceof $class);
284
285 4
            $lob->writeTemporary($variable, OCI_TEMP_BLOB);
286
287 4
            $variable =& $lob;
288
        }
289
290 124
        $this->boundValues[$column] =& $variable;
291
292 124
        return oci_bind_by_name(
293 124
            $this->_sth,
294 124
            $column,
295 124
            $variable,
296 124
            $length ?? -1,
297 124
            $this->convertParameterType($type)
298
        );
299
    }
300
301
    /**
302
     * Converts DBAL parameter type to oci8 parameter type
303
     */
304 124
    private function convertParameterType(int $type) : int
305
    {
306 124
        switch ($type) {
307
            case ParameterType::BINARY:
308 1
                return OCI_B_BIN;
309
310
            case ParameterType::LARGE_OBJECT:
311 4
                return OCI_B_BLOB;
312
313
            default:
314 122
                return SQLT_CHR;
315
        }
316
    }
317
318
    /**
319
     * {@inheritdoc}
320
     */
321 20
    public function closeCursor()
322
    {
323
        // not having the result means there's nothing to close
324 20
        if (! $this->result) {
325 4
            return true;
326
        }
327
328 16
        oci_cancel($this->_sth);
329
330 16
        $this->result = false;
331
332 16
        return true;
333
    }
334
335
    /**
336
     * {@inheritdoc}
337
     */
338 4
    public function columnCount()
339
    {
340 4
        return oci_num_fields($this->_sth) ?: 0;
341
    }
342
343
    /**
344
     * {@inheritdoc}
345
     */
346
    public function errorCode()
347
    {
348
        $error = oci_error($this->_sth);
349
        if ($error !== false) {
350
            $error = $error['code'];
351
        }
352
353
        return $error;
354
    }
355
356
    /**
357
     * {@inheritdoc}
358
     */
359 144
    public function errorInfo()
360
    {
361 144
        $error = oci_error($this->_sth);
362
363 144
        if ($error === false) {
364
            return [];
365
        }
366
367 144
        return $error;
368
    }
369
370
    /**
371
     * {@inheritdoc}
372
     */
373 299
    public function execute($params = null)
374
    {
375 299
        if ($params) {
376 94
            $hasZeroIndex = array_key_exists(0, $params);
377
378 94
            foreach ($params as $key => $val) {
379 94
                if ($hasZeroIndex && is_int($key)) {
380 94
                    $this->bindValue($key + 1, $val);
381
                } else {
382 94
                    $this->bindValue($key, $val);
383
                }
384
            }
385
        }
386
387 295
        $ret = @oci_execute($this->_sth, $this->_conn->getExecuteMode());
388 295
        if (! $ret) {
389 148
            throw OCI8Exception::fromErrorInfo($this->errorInfo());
390
        }
391
392 290
        $this->result = true;
393
394 290
        return $ret;
395
    }
396
397
    /**
398
     * {@inheritdoc}
399
     */
400 263
    public function setFetchMode($fetchMode, $arg2 = null, $arg3 = null)
401
    {
402 263
        $this->_defaultFetchMode = $fetchMode;
403
404 263
        return true;
405
    }
406
407
    /**
408
     * {@inheritdoc}
409
     */
410 5
    public function getIterator()
411
    {
412 5
        return new StatementIterator($this);
413
    }
414
415
    /**
416
     * {@inheritdoc}
417
     */
418 78
    public function fetch($fetchMode = null, $cursorOrientation = PDO::FETCH_ORI_NEXT, $cursorOffset = 0)
419
    {
420
        // do not try fetching from the statement if it's not expected to contain result
421
        // in order to prevent exceptional situation
422 78
        if (! $this->result) {
423 3
            return false;
424
        }
425
426 75
        $fetchMode = $fetchMode ?: $this->_defaultFetchMode;
427
428 75
        if ($fetchMode === FetchMode::COLUMN) {
429 1
            return $this->fetchColumn();
430
        }
431
432 74
        if ($fetchMode === FetchMode::STANDARD_OBJECT) {
433 1
            return oci_fetch_object($this->_sth);
434
        }
435
436 73
        if (! isset(self::$fetchModeMap[$fetchMode])) {
437
            throw new InvalidArgumentException('Invalid fetch style: ' . $fetchMode);
438
        }
439
440 73
        return oci_fetch_array(
441 73
            $this->_sth,
442 73
            self::$fetchModeMap[$fetchMode] | OCI_RETURN_NULLS | OCI_RETURN_LOBS
443
        );
444
    }
445
446
    /**
447
     * {@inheritdoc}
448
     */
449 116
    public function fetchAll($fetchMode = null, $fetchArgument = null, $ctorArgs = null)
450
    {
451 116
        $fetchMode = $fetchMode ?: $this->_defaultFetchMode;
452
453 116
        $result = [];
454
455 116
        if ($fetchMode === FetchMode::STANDARD_OBJECT) {
456 1
            while ($row = $this->fetch($fetchMode)) {
457 1
                $result[] = $row;
458
            }
459
460 1
            return $result;
461
        }
462
463 115
        if (! isset(self::$fetchModeMap[$fetchMode])) {
464
            throw new InvalidArgumentException('Invalid fetch style: ' . $fetchMode);
465
        }
466
467 115
        if (self::$fetchModeMap[$fetchMode] === OCI_BOTH) {
468 1
            while ($row = $this->fetch($fetchMode)) {
469 1
                $result[] = $row;
470
            }
471
        } else {
472 114
            $fetchStructure = OCI_FETCHSTATEMENT_BY_ROW;
473
474 114
            if ($fetchMode === FetchMode::COLUMN) {
475 6
                $fetchStructure = OCI_FETCHSTATEMENT_BY_COLUMN;
476
            }
477
478
            // do not try fetching from the statement if it's not expected to contain result
479
            // in order to prevent exceptional situation
480 114
            if (! $this->result) {
481 3
                return [];
482
            }
483
484 111
            oci_fetch_all(
485 111
                $this->_sth,
486 111
                $result,
487 111
                0,
488 111
                -1,
489 111
                self::$fetchModeMap[$fetchMode] | OCI_RETURN_NULLS | $fetchStructure | OCI_RETURN_LOBS
490
            );
491
492 111
            if ($fetchMode === FetchMode::COLUMN) {
493 6
                $result = $result[0];
494
            }
495
        }
496
497 112
        return $result;
498
    }
499
500
    /**
501
     * {@inheritdoc}
502
     */
503 69
    public function fetchColumn($columnIndex = 0)
504
    {
505
        // do not try fetching from the statement if it's not expected to contain result
506
        // in order to prevent exceptional situation
507 69
        if (! $this->result) {
508 3
            return false;
509
        }
510
511 66
        $row = oci_fetch_array($this->_sth, OCI_NUM | OCI_RETURN_NULLS | OCI_RETURN_LOBS);
512
513 66
        if ($row === false) {
514 3
            return false;
515
        }
516
517 63
        return $row[$columnIndex] ?? null;
518
    }
519
520
    /**
521
     * {@inheritdoc}
522
     */
523 172
    public function rowCount()
524
    {
525 172
        return oci_num_rows($this->_sth) ?: 0;
526
    }
527
}
528