Passed
Pull Request — master (#141)
by Wilmer
05:33
created

CommandPDO::insertEx()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 25
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 4.0378

Importance

Changes 0
Metric Value
eloc 14
dl 0
loc 25
ccs 13
cts 15
cp 0.8667
rs 9.7998
c 0
b 0
f 0
cc 4
nc 4
nop 2
crap 4.0378
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\CommandPDO as 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
use Yiisoft\Strings\StringHelper;
16
17
use function array_pop;
18
use function count;
19
use function ltrim;
20
use function preg_match_all;
21
use function strpos;
22
23
final class CommandPDO extends AbstractCommandPDO
24
{
25
    /**
26
     * @inheritDoc
27
     */
28 1
    public function insertEx(string $table, array $columns): bool|array
29
    {
30 1
        $params = [];
31 1
        $sql = $this->db->getQueryBuilder()->insertEx($table, $columns, $params);
32 1
        $this->setSql($sql)->bindValues($params);
33
34 1
        if (!$this->execute()) {
35
            return false;
36
        }
37
38 1
        $tableSchema = $this->db->getSchema()->getTableSchema($table);
39 1
        $tablePrimaryKeys = $tableSchema?->getPrimaryKey() ?? [];
40
41 1
        $result = [];
42 1
        foreach ($tablePrimaryKeys as $name) {
43 1
            if ($tableSchema?->getColumn($name)?->isAutoIncrement()) {
44 1
                $result[$name] = $this->db->getLastInsertID((string) $tableSchema?->getSequenceName());
45 1
                continue;
46
            }
47
48
            /** @psalm-var mixed */
49
            $result[$name] = $columns[$name] ?? $tableSchema?->getColumn($name)?->getDefaultValue();
50
        }
51
52 1
        return $result;
53
    }
54
55 224
    public function queryBuilder(): QueryBuilderInterface
56
    {
57 224
        return $this->db->getQueryBuilder();
58
    }
59
60
    /**
61
     * Executes the SQL statement.
62
     *
63
     * This method should only be used for executing non-query SQL statement, such as `INSERT`, `DELETE`, `UPDATE` SQLs.
64
     * No result set will be returned.
65
     *
66
     * @throws Exception|Throwable execution failed.
67
     *
68
     * @return int number of rows affected by the execution.
69
     */
70 78
    public function execute(): int
71
    {
72 78
        $sql = $this->getSql();
73
74
        /** @psalm-var array<string, string> $params */
75 78
        $params = $this->params;
76
77 78
        $statements = $this->splitStatements($sql, $params);
78
79 78
        if ($statements === false) {
0 ignored issues
show
introduced by
The condition $statements === false is always true.
Loading history...
80 73
            return parent::execute();
81
        }
82
83 5
        $result = 0;
84
85
        /** @psalm-var array<array-key, array<array-key, string|array>> $statements */
86 5
        foreach ($statements as $statement) {
87 5
            [$statementSql, $statementParams] = $statement;
88 5
            $statementSql = is_string($statementSql) ? $statementSql : '';
89 5
            $statementParams = is_array($statementParams) ? $statementParams : [];
90 5
            $this->setSql($statementSql)->bindValues($statementParams);
91 5
            $result = parent::execute();
92
        }
93
94 5
        $this->setSql($sql)->bindValues($params);
95
96 5
        return $result;
97
    }
98
99
    /**
100
     * @psalm-suppress UnusedClosureParam
101
     *
102
     * @throws Throwable
103
     */
104 201
    protected function internalExecute(string|null $rawSql): void
105
    {
106 201
        $attempt = 0;
107
108 201
        while (true) {
109
            try {
110
                if (
111
                    ++$attempt === 1
112 201
                    && $this->isolationLevel !== null
113 201
                    && $this->db->getTransaction() === null
114
                ) {
115 1
                    $this->db->transaction(
116 1
                        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

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