Failed Conditions
Pull Request — master (#3359)
by Sergei
25:01 queued 22:04
created

OCI8Statement::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 5
dl 0
loc 7
ccs 0
cts 6
cp 0
rs 10
c 0
b 0
f 0
cc 1
nc 1
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 PDO;
13
use const OCI_ASSOC;
14
use const OCI_B_BIN;
15
use const OCI_B_BLOB;
16
use const OCI_BOTH;
17
use const OCI_D_LOB;
18
use const OCI_FETCHSTATEMENT_BY_COLUMN;
19
use const OCI_FETCHSTATEMENT_BY_ROW;
20
use const OCI_NUM;
21
use const OCI_RETURN_LOBS;
22
use const OCI_RETURN_NULLS;
23
use const OCI_TEMP_BLOB;
24
use const PREG_OFFSET_CAPTURE;
25
use const SQLT_CHR;
26
use function array_key_exists;
27
use function count;
28
use function implode;
29
use function is_numeric;
30
use function oci_bind_by_name;
31
use function oci_cancel;
32
use function oci_error;
33
use function oci_execute;
34
use function oci_fetch_all;
35
use function oci_fetch_array;
36
use function oci_fetch_object;
37
use function oci_new_descriptor;
38
use function oci_num_fields;
39
use function oci_num_rows;
40
use function oci_parse;
41
use function preg_match;
42
use function preg_quote;
43
use function sprintf;
44
use function substr;
45
46
/**
47
 * The OCI8 implementation of the Statement interface.
48
 */
49
class OCI8Statement implements IteratorAggregate, Statement
50
{
51
    /** @var resource */
52
    protected $_dbh;
53
54
    /** @var resource */
55
    protected $_sth;
56
57
    /** @var OCI8Connection */
58
    protected $_conn;
59
60
    /** @var string */
61
    protected static $_PARAM = ':param';
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   $statement The SQL statement.
98
     */
99
    public function __construct($dbh, $statement, OCI8Connection $conn)
100
    {
101
        [$statement, $paramMap] = self::convertPositionalToNamedPlaceholders($statement);
102
        $this->_sth             = oci_parse($dbh, $statement);
103
        $this->_dbh             = $dbh;
104
        $this->_paramMap        = $paramMap;
105
        $this->_conn            = $conn;
106
    }
107
108
    /**
109
     * Converts positional (?) into named placeholders (:param<num>).
110
     *
111
     * Oracle does not support positional parameters, hence this method converts all
112
     * positional parameters into artificially named parameters. Note that this conversion
113
     * is not perfect. All question marks (?) in the original statement are treated as
114
     * placeholders and converted to a named parameter.
115
     *
116
     * The algorithm uses a state machine with two possible states: InLiteral and NotInLiteral.
117
     * Question marks inside literal strings are therefore handled correctly by this method.
118
     * This comes at a cost, the whole sql statement has to be looped over.
119
     *
120
     * @param string $statement The SQL statement to convert.
121
     *
122
     * @return mixed[] [0] => the statement value (string), [1] => the paramMap value (array).
123
     *
124
     * @throws OCI8Exception
125
     *
126
     * @todo extract into utility class in Doctrine\DBAL\Util namespace
127
     * @todo review and test for lost spaces. we experienced missing spaces with oci8 in some sql statements.
128
     */
129 230
    public static function convertPositionalToNamedPlaceholders($statement)
130
    {
131 230
        $fragmentOffset          = $tokenOffset = 0;
132 230
        $fragments               = $paramMap = [];
133 230
        $currentLiteralDelimiter = null;
134
135
        do {
136 230
            if (! $currentLiteralDelimiter) {
137 230
                $result = self::findPlaceholderOrOpeningQuote(
138 230
                    $statement,
139 230
                    $tokenOffset,
140 230
                    $fragmentOffset,
141 230
                    $fragments,
142 230
                    $currentLiteralDelimiter,
143 230
                    $paramMap
144
                );
145
            } else {
146 184
                $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

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

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