Test Failed
Pull Request — master (#242)
by Wilmer
05:44 queued 01:49
created

CommandPDO::showDatabases()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 4
c 0
b 0
f 0
dl 0
loc 7
ccs 2
cts 2
cp 1
rs 10
cc 1
nc 1
nop 0
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Db\Sqlite;
6
7
use PDOException;
8
use Throwable;
9
use Yiisoft\Db\Driver\PDO\AbstractCommandPDO;
10
use Yiisoft\Db\Driver\PDO\ConnectionPDOInterface;
11
use Yiisoft\Db\Exception\ConvertException;
12
use Yiisoft\Db\Exception\Exception;
13
use Yiisoft\Db\Exception\InvalidArgumentException;
14
use Yiisoft\Db\QueryBuilder\QueryBuilderInterface;
15
16
use function array_pop;
17
use function count;
18
use function ltrim;
19
use function preg_match_all;
20
use function strpos;
21
22
/**
23
 * Implements a database command that can be executed with a PDO (PHP Data Object) database connection for SQLite
24
 * Server.
25
 */
26
final class CommandPDO extends AbstractCommandPDO
27
{
28 4
    public function insertWithReturningPks(string $table, array $columns): bool|array
29
    {
30 4
        $params = [];
31 4
        $sql = $this->db->getQueryBuilder()->insert($table, $columns, $params);
32 4
        $this->setSql($sql)->bindValues($params);
33
34 4
        if (!$this->execute()) {
35
            return false;
36
        }
37
38 4
        $tableSchema = $this->db->getSchema()->getTableSchema($table);
39 4
        $tablePrimaryKeys = $tableSchema?->getPrimaryKey() ?? [];
40
41 4
        $result = [];
42 4
        foreach ($tablePrimaryKeys as $name) {
43 4
            if ($tableSchema?->getColumn($name)?->isAutoIncrement()) {
44 3
                $result[$name] = $this->db->getLastInsertID((string) $tableSchema?->getSequenceName());
45 3
                continue;
46
            }
47
48
            /** @psalm-var mixed */
49 1
            $result[$name] = $columns[$name] ?? $tableSchema?->getColumn($name)?->getDefaultValue();
50
        }
51
52 4
        return $result;
53
    }
54
55 280
    public function showDatabases(): array
56
    {
57 280
        $sql = <<<SQL
58
        SELECT name FROM pragma_database_list;
59
        SQL;
60
61
        return $this->setSql($sql)->queryColumn();
62
    }
63
64
    protected function getQueryBuilder(): QueryBuilderInterface
65
    {
66
        return $this->db->getQueryBuilder();
67
    }
68
69
    /**
70
     * Executes the SQL statement.
71 109
     *
72
     * This method should only be used for executing a non-query SQL statement, such as `INSERT`, `DELETE`, `UPDATE` SQLs.
73 109
     * No result set will be returned.
74
     *
75
     * @throws Exception
76 109
     * @throws Throwable The execution failed.
77
     *
78 109
     * @return int Number of rows affected by the execution.
79
     */
80 109
    public function execute(): int
81 97
    {
82
        $sql = $this->getSql();
83
84 12
        /** @psalm-var array<string, string> $params */
85
        $params = $this->params;
86
87 12
        $statements = $this->splitStatements($sql, $params);
88 12
89 12
        if ($statements === false) {
0 ignored issues
show
introduced by
The condition $statements === false is always true.
Loading history...
90 12
            return parent::execute();
91 12
        }
92 12
93
        $result = 0;
94
95 12
        /** @psalm-var array<array-key, array<array-key, string|array>> $statements */
96
        foreach ($statements as $statement) {
97 12
            [$statementSql, $statementParams] = $statement;
98
            $statementSql = is_string($statementSql) ? $statementSql : '';
99
            $statementParams = is_array($statementParams) ? $statementParams : [];
100
            $this->setSql($statementSql)->bindValues($statementParams);
101
            $result = parent::execute();
102
        }
103
104
        $this->setSql($sql)->bindValues($params);
105 247
106
        return $result;
107 247
    }
108
109 247
    /**
110
     * @psalm-suppress UnusedClosureParam
111
     *
112 247
     * @throws Throwable
113 247
     */
114 247
    protected function internalExecute(string|null $rawSql): void
115
    {
116 1
        $attempt = 0;
117 1
118 1
        while (true) {
119 1
            try {
120
                if (
121 247
                    ++$attempt === 1
122
                    && $this->isolationLevel !== null
123 247
                    && $this->db->getTransaction() === null
124 2
                ) {
125 2
                    $this->db->transaction(
126 2
                        fn (ConnectionPDOInterface $db) => $this->internalExecute($rawSql),
0 ignored issues
show
Unused Code introduced by
The parameter $db is not used and could be removed. ( Ignorable by Annotation )

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

126
                        fn (/** @scrutinizer ignore-unused */ ConnectionPDOInterface $db) => $this->internalExecute($rawSql),

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
127
                        $this->isolationLevel,
128 2
                    );
129 2
                } else {
130
                    $this->pdoStatement?->execute();
131
                }
132
                break;
133
            } catch (PDOException $e) {
134
                $rawSql = $rawSql ?: $this->getRawSql();
135
                $e = (new ConvertException($e, $rawSql))->run();
136
137
                if ($this->retryHandler === null || !($this->retryHandler)($e, $attempt)) {
138
                    throw $e;
139
                }
140
            }
141
        }
142
    }
143
144
    /**
145 247
     * Performs the actual DB query of an SQL statement.
146
     *
147 247
     * @param int $queryMode Return results as DataReader
148
     *
149
     * @throws Exception
150 247
     * @throws Throwable If the query causes any problem.
151
     *
152 247
     * @return mixed The method execution result.
153
     */
154 247
    protected function queryInternal(int $queryMode): mixed
155 247
    {
156
        $sql = $this->getSql();
157
158 1
        /** @psalm-var array<string, string> $params */
159
        $params = $this->params;
160
161
        $statements = $this->splitStatements($sql, $params);
162
163 1
        if ($statements === false || $statements === []) {
0 ignored issues
show
introduced by
The condition $statements === false is always true.
Loading history...
164
            return parent::queryInternal($queryMode);
165
        }
166
167
        [$lastStatementSql, $lastStatementParams] = array_pop($statements);
168 1
169 1
        /**
170 1
         * @psalm-var array<array-key, array> $statements
171
         */
172
        foreach ($statements as $statement) {
173 1
            /**
174
             * @psalm-var string $statementSql
175
             * @psalm-var array $statementParams
176 1
             */
177
            [$statementSql, $statementParams] = $statement;
178 1
            $this->setSql($statementSql)->bindValues($statementParams);
179
            parent::execute();
180 1
        }
181
182
        $this->setSql($lastStatementSql)->bindValues($lastStatementParams);
183
184
        /** @psalm-var string $result */
185
        $result = parent::queryInternal($queryMode);
186
187
        $this->setSql($sql)->bindValues($params);
188
189
        return $result;
190
    }
191
192
    /**
193
     * Splits the specified SQL into individual SQL statements and returns them or `false` if there's a single
194
     * statement.
195
     *
196
     * @param string $sql SQL to split.
197 248
     *
198
     * @throws InvalidArgumentException
199 248
     *
200
     * @return array|bool List of SQL statements or `false` if there's a single statement.
201 248
     *
202 248
     * @psalm-param array<string, string> $params
203
     *
204
     * @psalm-return false|list<array{0: string, 1: array}>
205 13
     */
206
    private function splitStatements(string $sql, array $params): bool|array
207 13
    {
208
        $semicolonIndex = strpos($sql, ';');
209 13
210 1
        if ($semicolonIndex === false || $semicolonIndex === mb_strlen($sql, '8bit') - 1) {
211
            return false;
212
        }
213 12
214
        $tokenizer = new SqlTokenizer($sql);
215 12
216 12
        $codeToken = $tokenizer->tokenize();
217
218
        if (count($codeToken->getChildren()) === 1) {
219 12
            return false;
220
        }
221
222
        $statements = [];
223
224
        foreach ($codeToken->getChildren() as $statement) {
225
            $statements[] = [$statement->getSql(), $this->extractUsedParams($statement, $params)];
226
        }
227 12
228
        return $statements;
229 12
    }
230
231 12
    /**
232
     * Returns named bindings used in the specified statement token.
233 12
     *
234 12
     * @psalm-param array<string, string> $params
235 12
     */
236 1
    private function extractUsedParams(SqlToken $statement, array $params): array
237 11
    {
238 11
        preg_match_all('/(?P<placeholder>:\w+)/', $statement->getSql(), $matches, PREG_SET_ORDER);
239
240
        $result = [];
241
242 12
        foreach ($matches as $match) {
243
            $phName = ltrim($match['placeholder'], ':');
244
            if (isset($params[$phName])) {
245
                $result[$phName] = $params[$phName];
246
            } elseif (isset($params[':' . $phName])) {
247
                $result[':' . $phName] = $params[':' . $phName];
248
            }
249
        }
250
251
        return $result;
252
    }
253
}
254