Passed
Pull Request — master (#140)
by Alexander
07:36 queued 03:38
created

CommandPDO::splitStatements()   A

Complexity

Conditions 5
Paths 4

Size

Total Lines 23
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 5

Importance

Changes 0
Metric Value
eloc 11
dl 0
loc 23
ccs 12
cts 12
cp 1
rs 9.6111
c 0
b 0
f 0
cc 5
nc 4
nop 2
crap 5
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\Exception\ConvertException;
11
use Yiisoft\Db\Exception\Exception;
12
use Yiisoft\Db\Exception\InvalidArgumentException;
13
use Yiisoft\Db\QueryBuilder\QueryBuilderInterface;
14
use Yiisoft\Db\Schema\SchemaInterface;
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
    public function insertEx(string $table, array $columns): bool|array
29
    {
30
        $params = [];
31
        $sql = $this->db->getQueryBuilder()->insertEx($table, $columns, $params);
32
        $this->setSql($sql)->bindValues($params);
33
34
        if (!$this->execute()) {
35
            return false;
36
        }
37
38
        $tableSchema = $this->db->getSchema()->getTableSchema($table);
39
        $tablePrimaryKeys = $tableSchema?->getPrimaryKey() ?? [];
40
41
        $result = [];
42
        foreach ($tablePrimaryKeys as $name) {
43
            if ($tableSchema?->getColumn($name)?->isAutoIncrement()) {
44
                $result[$name] = $this->db->getLastInsertID((string) $tableSchema?->getSequenceName());
45
                continue;
46
            }
47
48
            /** @var mixed */
49
            $result[$name] = $columns[$name] ?? $tableSchema?->getColumn($name)?->getDefaultValue();
50
        }
51
52
        return $result;
53
    }
54
55 222
    public function queryBuilder(): QueryBuilderInterface
56
    {
57 222
        return $this->db->getQueryBuilder();
58
    }
59
60
    public function schema(): SchemaInterface
61
    {
62
        return $this->db->getSchema();
63
    }
64
65
    /**
66
     * Executes the SQL statement.
67
     *
68
     * This method should only be used for executing non-query SQL statement, such as `INSERT`, `DELETE`, `UPDATE` SQLs.
69
     * No result set will be returned.
70
     *
71
     * @throws Exception|Throwable execution failed.
72
     *
73
     * @return int number of rows affected by the execution.
74
     */
75 76
    public function execute(): int
76
    {
77 76
        $sql = $this->getSql();
78
79
        /** @var array<string, string> */
80 76
        $params = $this->params;
81
82 76
        $statements = $this->splitStatements($sql, $params);
83
84 76
        if ($statements === false) {
0 ignored issues
show
introduced by
The condition $statements === false is always true.
Loading history...
85 71
            return parent::execute();
86
        }
87
88 5
        $result = 0;
89
90
        /** @psalm-var array<array-key, array<array-key, string|array>> $statements */
91 5
        foreach ($statements as $statement) {
92 5
            [$statementSql, $statementParams] = $statement;
93 5
            $statementSql = is_string($statementSql) ? $statementSql : '';
94 5
            $statementParams = is_array($statementParams) ? $statementParams : [];
95 5
            $this->setSql($statementSql)->bindValues($statementParams);
96 5
            $result = parent::execute();
97
        }
98
99 5
        $this->setSql($sql)->bindValues($params);
100
101 5
        return $result;
102
    }
103
104 199
    protected function internalExecute(string|null $rawSql): void
105
    {
106 199
        $attempt = 0;
107
108 199
        while (true) {
109
            try {
110
                if (
111
                    ++$attempt === 1
112 199
                    && $this->isolationLevel !== null
113 199
                    && $this->db->getTransaction() === null
114
                ) {
115
                    $this->db->transaction(
116
                        fn (string|null $rawSql) => $this->internalExecute($rawSql),
117
                        $this->isolationLevel,
118
                    );
119
                } else {
120 199
                    $this->pdoStatement?->execute();
121
                }
122 199
                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 199
    protected function queryInternal(int $queryMode): mixed
144
    {
145 199
        $sql = $this->getSql();
146
147
        /** @var array<string, string> */
148 199
        $params = $this->params;
149
150 199
        $statements = $this->splitStatements($sql, $params);
151
152 199
        if ($statements === false || $statements === []) {
0 ignored issues
show
introduced by
The condition $statements === false is always true.
Loading history...
153 199
            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
        /** @var string */
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 200
    private function splitStatements(string $sql, array $params): bool|array
193
    {
194 200
        $semicolonIndex = strpos($sql, ';');
195
196 200
        if ($semicolonIndex === false || $semicolonIndex === StringHelper::byteLength($sql) - 1) {
197 200
            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