Failed Conditions
Push — develop ( c067f0...c4478a )
by Sergei
10:16
created

OCI8Statement::execute()   A

Complexity

Conditions 6
Paths 4

Size

Total Lines 21
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 6

Importance

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

144
                $result = self::findClosingQuote($statement, $tokenOffset, /** @scrutinizer ignore-type */ $currentLiteralDelimiter);
Loading history...
145
            }
146 712
        } while ($result);
147
148 712
        if ($currentLiteralDelimiter) {
149 6
            throw new OCI8Exception(sprintf(
150 6
                'The statement contains non-terminated string literal starting at offset %d',
151 6
                $tokenOffset - 1
152
            ));
153
        }
154
155 706
        $fragments[] = substr($statement, $fragmentOffset);
156 706
        $statement   = implode('', $fragments);
157
158 706
        return [$statement, $paramMap];
159
    }
160
161
    /**
162
     * Finds next placeholder or opening quote.
163
     *
164
     * @param string             $statement               The SQL statement to parse
165
     * @param string             $tokenOffset             The offset to start searching from
166
     * @param int                $fragmentOffset          The offset to build the next fragment from
167
     * @param string[]           $fragments               Fragments of the original statement not containing placeholders
168
     * @param string|null        $currentLiteralDelimiter The delimiter of the current string literal
169
     *                                                    or NULL if not currently in a literal
170
     * @param array<int, string> $paramMap                Mapping of the original parameter positions to their named replacements
171
     *
172
     * @return bool Whether the token was found
173
     */
174 712
    private static function findPlaceholderOrOpeningQuote(
175
        $statement,
176
        &$tokenOffset,
177
        &$fragmentOffset,
178
        &$fragments,
179
        &$currentLiteralDelimiter,
180
        &$paramMap
181
    ) {
182 712
        $token = self::findToken($statement, $tokenOffset, '/[?\'"]/');
183
184 712
        if (! $token) {
185 706
            return false;
186
        }
187
188 642
        if ($token === '?') {
189 436
            $position            = count($paramMap) + 1;
190 436
            $param               = ':param' . $position;
191 436
            $fragments[]         = substr($statement, $fragmentOffset, $tokenOffset - $fragmentOffset);
192 436
            $fragments[]         = $param;
193 436
            $paramMap[$position] = $param;
194 436
            $tokenOffset        += 1;
195 436
            $fragmentOffset      = $tokenOffset;
196
197 436
            return true;
198
        }
199
200 386
        $currentLiteralDelimiter = $token;
201 386
        ++$tokenOffset;
202
203 386
        return true;
204
    }
205
206
    /**
207
     * Finds closing quote
208
     *
209
     * @param string      $statement               The SQL statement to parse
210
     * @param string      $tokenOffset             The offset to start searching from
211
     * @param string|null $currentLiteralDelimiter The delimiter of the current string literal
212
     *                                             or NULL if not currently in a literal
213
     *
214
     * @return bool Whether the token was found
215
     */
216 386
    private static function findClosingQuote(
217
        $statement,
218
        &$tokenOffset,
219
        &$currentLiteralDelimiter
220
    ) {
221 386
        $token = self::findToken(
222 386
            $statement,
223 386
            $tokenOffset,
224 386
            '/' . preg_quote($currentLiteralDelimiter, '/') . '/'
225
        );
226
227 386
        if (! $token) {
228 6
            return false;
229
        }
230
231 382
        $currentLiteralDelimiter = false;
232 382
        ++$tokenOffset;
233
234 382
        return true;
235
    }
236
237
    /**
238
     * Finds the token described by regex starting from the given offset. Updates the offset with the position
239
     * where the token was found.
240
     *
241
     * @param string $statement The SQL statement to parse
242
     * @param string $offset    The offset to start searching from
243
     * @param string $regex     The regex containing token pattern
244
     *
245
     * @return string|null Token or NULL if not found
246
     */
247 712
    private static function findToken($statement, &$offset, $regex)
248
    {
249 712
        if (preg_match($regex, $statement, $matches, PREG_OFFSET_CAPTURE, $offset)) {
0 ignored issues
show
Bug introduced by
$offset of type string is incompatible with the type integer expected by parameter $offset of preg_match(). ( Ignorable by Annotation )

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

249
        if (preg_match($regex, $statement, $matches, PREG_OFFSET_CAPTURE, /** @scrutinizer ignore-type */ $offset)) {
Loading history...
250 642
            $offset = $matches[0][1];
251 642
            return $matches[0][0];
252
        }
253
254 712
        return null;
255
    }
256
257
    /**
258
     * {@inheritdoc}
259
     */
260 236
    public function bindValue($param, $value, $type = ParameterType::STRING)
261
    {
262 236
        return $this->bindParam($param, $value, $type, null);
263
    }
264
265
    /**
266
     * {@inheritdoc}
267
     */
268 246
    public function bindParam($column, &$variable, $type = ParameterType::STRING, $length = null)
269
    {
270 246
        $column = $this->_paramMap[$column] ?? $column;
271
272 246
        if ($type === ParameterType::LARGE_OBJECT) {
273 8
            $lob = oci_new_descriptor($this->_dbh, OCI_D_LOB);
274 8
            $lob->writeTemporary($variable, OCI_TEMP_BLOB);
275
276 8
            $variable =& $lob;
277
        }
278
279 246
        $this->boundValues[$column] =& $variable;
280
281 246
        return oci_bind_by_name(
282 246
            $this->_sth,
283 246
            $column,
284 246
            $variable,
285 246
            $length ?? -1,
286 246
            $this->convertParameterType($type)
287
        );
288
    }
289
290
    /**
291
     * Converts DBAL parameter type to oci8 parameter type
292
     */
293 246
    private function convertParameterType(int $type) : int
294
    {
295 246
        switch ($type) {
296
            case ParameterType::BINARY:
297 2
                return OCI_B_BIN;
298
299
            case ParameterType::LARGE_OBJECT:
300 8
                return OCI_B_BLOB;
301
302
            default:
303 242
                return SQLT_CHR;
304
        }
305
    }
306
307
    /**
308
     * {@inheritdoc}
309
     */
310 38
    public function closeCursor()
311
    {
312
        // not having the result means there's nothing to close
313 38
        if (! $this->result) {
314 8
            return true;
315
        }
316
317 30
        oci_cancel($this->_sth);
318
319 30
        $this->result = false;
320
321 30
        return true;
322
    }
323
324
    /**
325
     * {@inheritdoc}
326
     */
327 8
    public function columnCount()
328
    {
329 8
        return oci_num_fields($this->_sth);
330
    }
331
332
    /**
333
     * {@inheritdoc}
334
     */
335
    public function errorCode()
336
    {
337
        $error = oci_error($this->_sth);
338
        if ($error !== false) {
339
            $error = $error['code'];
340
        }
341
342
        return $error;
343
    }
344
345
    /**
346
     * {@inheritdoc}
347
     */
348 278
    public function errorInfo()
349
    {
350 278
        return oci_error($this->_sth);
351
    }
352
353
    /**
354
     * {@inheritdoc}
355
     */
356 518
    public function execute($params = null)
357
    {
358 518
        if ($params) {
359 182
            $hasZeroIndex = array_key_exists(0, $params);
360 182
            foreach ($params as $key => $val) {
361 182
                if ($hasZeroIndex && is_numeric($key)) {
362 182
                    $this->bindValue($key + 1, $val);
363
                } else {
364 182
                    $this->bindValue($key, $val);
365
                }
366
            }
367
        }
368
369 510
        $ret = @oci_execute($this->_sth, $this->_conn->getExecuteMode());
370 510
        if (! $ret) {
371 282
            throw OCI8Exception::fromErrorInfo($this->errorInfo());
372
        }
373
374 504
        $this->result = true;
375
376 504
        return $ret;
377
    }
378
379
    /**
380
     * {@inheritdoc}
381
     */
382 450
    public function setFetchMode($fetchMode, ...$args)
383
    {
384 450
        $this->_defaultFetchMode = $fetchMode;
385
386 450
        return true;
387
    }
388
389
    /**
390
     * {@inheritdoc}
391
     */
392 6
    public function getIterator()
393
    {
394 6
        return new StatementIterator($this);
395
    }
396
397
    /**
398
     * {@inheritdoc}
399
     */
400 156
    public function fetch($fetchMode = null, ...$args)
401
    {
402
        // do not try fetching from the statement if it's not expected to contain result
403
        // in order to prevent exceptional situation
404 156
        if (! $this->result) {
405 6
            return false;
406
        }
407
408 150
        $fetchMode = $fetchMode ?: $this->_defaultFetchMode;
409
410 150
        if ($fetchMode === FetchMode::COLUMN) {
411 2
            return $this->fetchColumn();
412
        }
413
414 148
        if ($fetchMode === FetchMode::STANDARD_OBJECT) {
415 2
            return oci_fetch_object($this->_sth);
416
        }
417
418 146
        if (! isset(self::$fetchModeMap[$fetchMode])) {
419
            throw new InvalidArgumentException('Invalid fetch style: ' . $fetchMode);
420
        }
421
422 146
        return oci_fetch_array(
423 146
            $this->_sth,
424 146
            self::$fetchModeMap[$fetchMode] | OCI_RETURN_NULLS | OCI_RETURN_LOBS
425
        );
426
    }
427
428
    /**
429
     * {@inheritdoc}
430
     */
431 192
    public function fetchAll($fetchMode = null, ...$args)
432
    {
433 192
        $fetchMode = $fetchMode ?: $this->_defaultFetchMode;
434
435 192
        $result = [];
436
437 192
        if ($fetchMode === FetchMode::STANDARD_OBJECT) {
438 2
            while ($row = $this->fetch($fetchMode)) {
439 2
                $result[] = $row;
440
            }
441
442 2
            return $result;
443
        }
444
445 190
        if (! isset(self::$fetchModeMap[$fetchMode])) {
446
            throw new InvalidArgumentException('Invalid fetch style: ' . $fetchMode);
447
        }
448
449 190
        if (self::$fetchModeMap[$fetchMode] === OCI_BOTH) {
450 2
            while ($row = $this->fetch($fetchMode)) {
451 2
                $result[] = $row;
452
            }
453
        } else {
454 188
            $fetchStructure = OCI_FETCHSTATEMENT_BY_ROW;
455
456 188
            if ($fetchMode === FetchMode::COLUMN) {
457 12
                $fetchStructure = OCI_FETCHSTATEMENT_BY_COLUMN;
458
            }
459
460
            // do not try fetching from the statement if it's not expected to contain result
461
            // in order to prevent exceptional situation
462 188
            if (! $this->result) {
463 6
                return [];
464
            }
465
466 182
            oci_fetch_all(
467 182
                $this->_sth,
468 182
                $result,
469 182
                0,
470 182
                -1,
471 182
                self::$fetchModeMap[$fetchMode] | OCI_RETURN_NULLS | $fetchStructure | OCI_RETURN_LOBS
472
            );
473
474 182
            if ($fetchMode === FetchMode::COLUMN) {
475 12
                $result = $result[0];
476
            }
477
        }
478
479 184
        return $result;
480
    }
481
482
    /**
483
     * {@inheritdoc}
484
     */
485 102
    public function fetchColumn($columnIndex = 0)
486
    {
487
        // do not try fetching from the statement if it's not expected to contain result
488
        // in order to prevent exceptional situation
489 102
        if (! $this->result) {
490 6
            return false;
491
        }
492
493 96
        $row = oci_fetch_array($this->_sth, OCI_NUM | OCI_RETURN_NULLS | OCI_RETURN_LOBS);
494
495 96
        if ($row === false) {
496 6
            return false;
497
        }
498
499 90
        return $row[$columnIndex] ?? null;
500
    }
501
502
    /**
503
     * {@inheritdoc}
504
     */
505 348
    public function rowCount() : int
506
    {
507 348
        return oci_num_rows($this->_sth);
508
    }
509
}
510