Passed
Pull Request — dev (#91)
by Def
31:57 queued 19:36
created

CommandPDOSqlite::extractUsedParams()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 16
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 4

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 9
dl 0
loc 16
ccs 10
cts 10
cp 1
rs 9.9666
c 1
b 0
f 0
cc 4
nc 4
nop 2
crap 4
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Db\Sqlite\PDO;
6
7
use PDOException;
8
use Throwable;
9
use Yiisoft\Db\Cache\QueryCache;
10
use Yiisoft\Db\Command\CommandPDO;
11
use Yiisoft\Db\Connection\ConnectionPDOInterface;
12
use Yiisoft\Db\Exception\ConvertException;
13
use Yiisoft\Db\Exception\Exception;
14
use Yiisoft\Db\Exception\InvalidArgumentException;
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
use Yiisoft\Db\Sqlite\SqlToken;
17
use Yiisoft\Db\Sqlite\SqlTokenizer;
18
use Yiisoft\Strings\StringHelper;
19
20
use function array_pop;
21
use function count;
22
use function ltrim;
23
use function preg_match_all;
24
use function strpos;
25
26
final class CommandPDOSqlite extends CommandPDO
27
{
28
    /**
29
     * @inheritDoc
30
     */
31 1
    public function insertEx(string $table, array $columns): bool|array
32
    {
33 1
        $params = [];
34 1
        $sql = $this->db->getQueryBuilder()->insertEx($table, $columns, $params);
35 1
        $this->setSql($sql)->bindValues($params);
36
37 1
        if (!$this->execute()) {
38
            return false;
39
        }
40
41 1
        $tableSchema = $this->queryBuilder()->schema()->getTableSchema($table);
42 1
        $tablePrimaryKeys = $tableSchema?->getPrimaryKey() ?? [];
43
44 1
        $result = [];
45 1
        foreach ($tablePrimaryKeys as $name) {
46 1
            if ($tableSchema?->getColumn($name)?->isAutoIncrement()) {
47 1
                $result[$name] = $this->queryBuilder()->schema()->getLastInsertID((string) $tableSchema?->getSequenceName());
48 1
                continue;
49
            }
50
51
            /** @var mixed */
52
            $result[$name] = $columns[$name] ?? $tableSchema?->getColumn($name)?->getDefaultValue();
53
        }
54
55 1
        return $result;
56
    }
57
58 177
    public function queryBuilder(): QueryBuilderInterface
59
    {
60 177
        return $this->db->getQueryBuilder();
61
    }
62
63
    /**
64
     * Executes the SQL statement.
65
     *
66
     * This method should only be used for executing non-query SQL statement, such as `INSERT`, `DELETE`, `UPDATE` SQLs.
67
     * No result set will be returned.
68
     *
69
     * @throws Exception|Throwable execution failed.
70
     *
71
     * @return int number of rows affected by the execution.
72
     */
73 46
    public function execute(): int
74
    {
75 46
        $sql = $this->getSql();
76
77
        /** @var array<string, string> */
78 46
        $params = $this->params;
79
80 46
        $statements = $this->splitStatements($sql, $params);
81
82 46
        if ($statements === false) {
0 ignored issues
show
introduced by
The condition $statements === false is always true.
Loading history...
83 41
            return parent::execute();
84
        }
85
86 5
        $result = 0;
87
88
        /** @psalm-var array<array-key, array<array-key, string|array>> $statements */
89 5
        foreach ($statements as $statement) {
90 5
            [$statementSql, $statementParams] = $statement;
91 5
            $statementSql = is_string($statementSql) ? $statementSql : '';
92 5
            $statementParams = is_array($statementParams) ? $statementParams : [];
93 5
            $this->setSql($statementSql)->bindValues($statementParams);
94 5
            $result = parent::execute();
95
        }
96
97 5
        $this->setSql($sql)->bindValues($params);
98
99 5
        return $result;
100
    }
101
102 152
    protected function getCacheKey(int $queryMode, string $rawSql): array
103
    {
104
        return [
105 152
            __CLASS__,
106
            $queryMode,
107 152
            $this->db->getDriver()->getDsn(),
108 152
            $this->db->getDriver()->getUsername(),
109
            $rawSql,
110
        ];
111
    }
112
113 161
    protected function internalExecute(?string $rawSql): void
114
    {
115 161
        $attempt = 0;
116
117 161
        while (true) {
118
            try {
119
                if (
120 161
                    ++$attempt === 1
121 161
                    && $this->isolationLevel !== null
122 161
                    && $this->db->getTransaction() === null
123
                ) {
124
                    $this->db->transaction(fn (?string $rawSql) => $this->internalExecute($rawSql), $this->isolationLevel);
125
                } else {
126 161
                    $this->pdoStatement?->execute();
127
                }
128 161
                break;
129 2
            } catch (PDOException $e) {
130 2
                $rawSql = $rawSql ?: $this->getRawSql();
131 2
                $e = (new ConvertException($e, $rawSql))->run();
132
133 2
                if ($this->retryHandler === null || !($this->retryHandler)($e, $attempt)) {
134 2
                    throw $e;
135
                }
136
            }
137
        }
138
    }
139
140
    /**
141
     * Performs the actual DB query of a SQL statement.
142
     *
143
     * @param int $queryMode - return results as DataReader
144
     *
145
     * @throws Exception|Throwable if the query causes any problem.
146
     *
147
     * @return mixed the method execution result.
148
     */
149 161
    protected function queryInternal(int $queryMode): mixed
150
    {
151 161
        $sql = $this->getSql();
152
153
        /** @var array<string, string> */
154 161
        $params = $this->params;
155
156 161
        $statements = $this->splitStatements($sql, $params);
157
158 161
        if ($statements === false || $statements === []) {
0 ignored issues
show
introduced by
The condition $statements === false is always true.
Loading history...
159 161
            return parent::queryInternal($queryMode);
160
        }
161
162 1
        [$lastStatementSql, $lastStatementParams] = array_pop($statements);
163
164
        /**
165
         * @psalm-var array<array-key, array> $statements
166
         */
167 1
        foreach ($statements as $statement) {
168
            /**
169
             * @var string $statementSql
170
             * @var array $statementParams
171
             */
172 1
            [$statementSql, $statementParams] = $statement;
173 1
            $this->setSql($statementSql)->bindValues($statementParams);
174 1
            parent::execute();
175
        }
176
177 1
        $this->setSql($lastStatementSql)->bindValues($lastStatementParams);
178
179
        /** @var string */
180 1
        $result = parent::queryInternal($queryMode);
181
182 1
        $this->setSql($sql)->bindValues($params);
183
184 1
        return $result;
185
    }
186
187
    /**
188
     * Splits the specified SQL codes into individual SQL statements and returns them or `false` if there's a single
189
     * statement.
190
     *
191
     * @param string $sql
192
     * @param array $params
193
     *
194
     * @throws InvalidArgumentException
195
     *
196
     * @return array|bool (array|string)[][]|bool
197
     *
198
     * @psalm-param array<string, string> $params
199
     * @psalm-return false|list<array{0: string, 1: array}>
200
     */
201 161
    private function splitStatements(string $sql, array $params): bool|array
202
    {
203 161
        $semicolonIndex = strpos($sql, ';');
204
205 161
        if ($semicolonIndex === false || $semicolonIndex === StringHelper::byteLength($sql) - 1) {
206 161
            return false;
207
        }
208
209 5
        $tokenizer = new SqlTokenizer($sql);
210
211 5
        $codeToken = $tokenizer->tokenize();
212
213 5
        if (count($codeToken->getChildren()) === 1) {
214
            return false;
215
        }
216
217 5
        $statements = [];
218
219 5
        foreach ($codeToken->getChildren() as $statement) {
220 5
            $statements[] = [$statement->getSql(), $this->extractUsedParams($statement, $params)];
221
        }
222
223 5
        return $statements;
224
    }
225
226
    /**
227
     * Returns named bindings used in the specified statement token.
228
     *
229
     * @param SqlToken $statement
230
     * @param array $params
231
     *
232
     * @return array
233
     *
234
     * @psalm-param array<string, string> $params
235
     */
236 5
    private function extractUsedParams(SqlToken $statement, array $params): array
237
    {
238 5
        preg_match_all('/(?P<placeholder>[:][a-zA-Z0-9_]+)/', $statement->getSql(), $matches, PREG_SET_ORDER);
239
240 5
        $result = [];
241
242 5
        foreach ($matches as $match) {
243 5
            $phName = ltrim($match['placeholder'], ':');
244 5
            if (isset($params[$phName])) {
245 1
                $result[$phName] = $params[$phName];
246 4
            } elseif (isset($params[':' . $phName])) {
247 4
                $result[':' . $phName] = $params[':' . $phName];
248
            }
249
        }
250
251 5
        return $result;
252
    }
253
}
254