Passed
Branch dev (e46bdf)
by Wilmer
09:54
created

CommandPDOOracle   A

Complexity

Total Complexity 29

Size/Duplication

Total Lines 149
Duplicated Lines 0 %

Test Coverage

Coverage 90.67%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 29
eloc 83
c 1
b 0
f 0
dl 0
loc 149
ccs 68
cts 75
cp 0.9067
rs 10

7 Methods

Rating   Name   Duplication   Size   Complexity  
A queryBuilder() 0 3 1
B insertEx() 0 50 7
A __construct() 0 3 1
B prepare() 0 29 7
B internalExecute() 0 22 9
A bindPendingParams() 0 15 3
A getCacheKey() 0 9 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Db\Oracle\PDO;
6
7
use PDO;
8
use PDOException;
9
use Yiisoft\Db\Cache\QueryCache;
10
use Yiisoft\Db\Command\Command;
11
use Yiisoft\Db\Connection\ConnectionPDOInterface;
12
use Yiisoft\Db\Exception\ConvertException;
13
use Yiisoft\Db\Exception\Exception;
14
use Yiisoft\Db\Query\QueryBuilder;
0 ignored issues
show
Bug introduced by
The type Yiisoft\Db\Query\QueryBuilder was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
15
use Yiisoft\Db\Query\QueryBuilderInterface;
0 ignored issues
show
Bug introduced by
The type Yiisoft\Db\Query\QueryBuilderInterface was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
16
17
/**
18
 * Command represents an Oracle SQL statement to be executed against a database.
19
 */
20
final class CommandPDOOracle extends Command
21
{
22 331
    public function __construct(private ConnectionPDOInterface $db, QueryCache $queryCache)
23
    {
24 331
        parent::__construct($queryCache);
25
    }
26
27 169
    public function queryBuilder(): QueryBuilderInterface
28
    {
29 169
        return $this->db->getQueryBuilder();
30
    }
31
32 1
    public function insertEx(string $table, array $columns): bool|array
33
    {
34 1
        $params = [];
35 1
        $sql = $this->queryBuilder()->insertEx($table, $columns, $params);
36
37 1
        $tableSchema = $this->queryBuilder()->schema()->getTableSchema($table);
38
39 1
        $returnColumns = $tableSchema?->getPrimaryKey() ?? [];
40 1
        $columnSchemas = $tableSchema?->getColumns() ?? [];
41
42 1
        $returnParams = [];
43 1
        $returning = [];
44 1
        foreach ($returnColumns as $name) {
45 1
            $phName = QueryBuilder::PARAM_PREFIX . (count($params) + count($returnParams));
46
47 1
            $returnParams[$phName] = [
48
                'column' => $name,
49
                'value' => '',
50
            ];
51
52 1
            if (!isset($columnSchemas[$name]) || $columnSchemas[$name]->getPhpType() !== 'integer') {
53
                $returnParams[$phName]['dataType'] = PDO::PARAM_STR;
54
            } else {
55 1
                $returnParams[$phName]['dataType'] = PDO::PARAM_INT;
56
            }
57
58 1
            $returnParams[$phName]['size'] = $columnSchemas[$name]->getSize() ?? -1;
59
60 1
            $returning[] = $this->db->getQuoter()->quoteColumnName($name);
61
        }
62
63 1
        $sql .= ' RETURNING ' . implode(', ', $returning) . ' INTO ' . implode(', ', array_keys($returnParams));
64
65 1
        $this->setSql($sql)->bindValues($params);
66 1
        $this->prepare(false);
67
68 1
        foreach ($returnParams as $name => &$value) {
69 1
            $this->bindParam($name, $value['value'], $value['dataType'], $value['size']);
70
        }
71
72 1
        if (!$this->execute()) {
73
            return false;
74
        }
75
76 1
        $result = [];
77 1
        foreach ($returnParams as $value) {
78 1
            $result[$value['column']] = $value['value'];
79
        }
80
81 1
        return $result;
82
    }
83
84 160
    public function prepare(?bool $forRead = null): void
85
    {
86 160
        if (isset($this->pdoStatement)) {
87 6
            $this->bindPendingParams();
88
89 6
            return;
90
        }
91
92 160
        $sql = $this->getSql();
93
94 160
        if ($this->db->getTransaction()) {
95
            /** master is in a transaction. use the same connection. */
96 5
            $forRead = false;
97
        }
98
99 160
        if ($forRead || ($forRead === null && $this->db->getSchema()->isReadQuery($sql))) {
100 156
            $pdo = $this->db->getSlavePdo();
101
        } else {
102 58
            $pdo = $this->db->getMasterPdo();
103
        }
104
105
        try {
106 160
            $this->pdoStatement = $pdo->prepare($sql);
107 160
            $this->bindPendingParams();
108
        } catch (PDOException $e) {
109
            $message = $e->getMessage() . "\nFailed to prepare SQL: $sql";
110
            $errorInfo = $e->errorInfo ?? null;
111
112
            throw new Exception($message, $errorInfo, $e);
113
        }
114
    }
115
116 160
    protected function bindPendingParams(): void
117
    {
118 160
        $paramsPassedByReference = [];
119
120 160
        foreach ($this->params as $name => $value) {
121 140
            if (PDO::PARAM_STR === $value->getType()) {
122 135
                $paramsPassedByReference[$name] = $value->getValue();
123 135
                $this->pdoStatement?->bindParam(
124
                    $name,
125 135
                    $paramsPassedByReference[$name],
126 135
                    $value->getType(),
127 135
                    strlen($value->getValue())
128
                );
129
            } else {
130 22
                $this->pdoStatement?->bindValue($name, $value->getValue(), $value->getType());
131
            }
132
        }
133
    }
134
135 2
    protected function getCacheKey(string $method, array|int|null $fetchMode, string $rawSql): array
136
    {
137
        return [
138 2
            __CLASS__,
139
            $method,
140
            $fetchMode,
141 2
            $this->db->getDriver()->getDsn(),
142 2
            $this->db->getDriver()->getUsername(),
143
            $rawSql,
144
        ];
145
    }
146
147 159
    protected function internalExecute(?string $rawSql): void
148
    {
149 159
        $attempt = 0;
150
151 159
        while (true) {
152
            try {
153
                if (
154 159
                    ++$attempt === 1
155 159
                    && $this->isolationLevel !== null
156 159
                    && $this->db->getTransaction() === null
157
                ) {
158
                    $this->db->transaction(fn ($rawSql) => $this->internalExecute($rawSql), $this->isolationLevel);
159
                } else {
160 159
                    $this->pdoStatement->execute();
0 ignored issues
show
Bug introduced by
The method execute() does not exist on null. ( Ignorable by Annotation )

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

160
                    $this->pdoStatement->/** @scrutinizer ignore-call */ 
161
                                         execute();

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
161
                }
162 159
                break;
163 6
            } catch (PDOException $e) {
164 6
                $rawSql = $rawSql ?: $this->getRawSql();
165 6
                $e = (new ConvertException($e, $rawSql))->run();
166
167 6
                if ($this->retryHandler === null || !($this->retryHandler)($e, $attempt)) {
168 6
                    throw $e;
169
                }
170
            }
171
        }
172
    }
173
}
174