-
-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy pathAbstractPdoCommand.php
More file actions
307 lines (262 loc) · 9.49 KB
/
AbstractPdoCommand.php
File metadata and controls
307 lines (262 loc) · 9.49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
<?php
declare(strict_types=1);
namespace Yiisoft\Db\Driver\Pdo;
use PDO;
use PDOException;
use PDOStatement;
use Psr\Log\LoggerAwareInterface;
use Psr\Log\LoggerAwareTrait;
use Psr\Log\LogLevel;
use Throwable;
use Yiisoft\Db\Command\AbstractCommand;
use Yiisoft\Db\Command\Param;
use Yiisoft\Db\Command\ParamInterface;
use Yiisoft\Db\Connection\ConnectionInterface;
use Yiisoft\Db\Exception\ConvertException;
use Yiisoft\Db\Exception\Exception;
use Yiisoft\Db\Exception\InvalidParamException;
use Yiisoft\Db\Profiler\Context\CommandContext;
use Yiisoft\Db\Profiler\ProfilerAwareInterface;
use Yiisoft\Db\Profiler\ProfilerAwareTrait;
use Yiisoft\Db\QueryBuilder\QueryBuilderInterface;
use function restore_error_handler;
use function set_error_handler;
use function str_starts_with;
/**
* Represents a database command that can be executed using a PDO (PHP Data Object) database connection.
*
* It's an abstract class that provides a common interface for building and executing various types of statements
* such as {@see cancel()}, {@see execute()}, {@see insert()}, {@see update()}, {@see delete()}, etc., using a PDO
* connection.
*
* It also provides methods for binding parameter values and retrieving query results.
*/
abstract class AbstractPdoCommand extends AbstractCommand implements PdoCommandInterface, LoggerAwareInterface, ProfilerAwareInterface
{
use LoggerAwareTrait;
use ProfilerAwareTrait;
/**
* @var PDOStatement|null Represents a prepared statement and, after the statement is executed, an associated
* result set.
*
* @link https://www.php.net/manual/en/class.pdostatement.php
*/
protected PDOStatement|null $pdoStatement = null;
public function __construct(protected PdoConnectionInterface $db)
{
}
/**
* This method mainly sets {@see pdoStatement} to be `null`.
*/
public function cancel(): void
{
$this->pdoStatement = null;
}
public function getPdoStatement(): PDOStatement|null
{
return $this->pdoStatement;
}
public function bindParam(
int|string $name,
mixed &$value,
int|null $dataType = null,
int|null $length = null,
mixed $driverOptions = null
): static {
$this->prepare();
if ($dataType === null) {
$dataType = $this->db->getSchema()->getDataType($value);
}
if ($length === null) {
$this->pdoStatement?->bindParam($name, $value, $dataType);
} elseif ($driverOptions === null) {
$this->pdoStatement?->bindParam($name, $value, $dataType, $length);
} else {
$this->pdoStatement?->bindParam($name, $value, $dataType, $length, $driverOptions);
}
return $this;
}
public function bindValue(int|string $name, mixed $value, int|null $dataType = null): static
{
if ($dataType === null) {
$dataType = $this->db->getSchema()->getDataType($value);
}
$this->params[$name] = new Param($value, $dataType);
return $this;
}
public function bindValues(array $values): static
{
if (empty($values)) {
return $this;
}
/**
* @psalm-var array<string, int>|ParamInterface|int $value
*/
foreach ($values as $name => $value) {
if ($value instanceof ParamInterface) {
$this->params[$name] = $value;
} else {
$type = $this->db->getSchema()->getDataType($value);
$this->params[$name] = new Param($value, $type);
}
}
return $this;
}
public function prepare(bool|null $forRead = null): void
{
if (isset($this->pdoStatement)) {
$this->bindPendingParams();
return;
}
$sql = $this->getSql();
/**
* If SQL is empty, there will be {@see \ValueError} on prepare pdoStatement.
*
* @link https://php.watch/versions/8.0/ValueError
*/
if ($sql === '') {
return;
}
$pdo = $this->db->getActivePdo($sql, $forRead);
try {
$this->pdoStatement = $pdo->prepare($sql);
$this->bindPendingParams();
} catch (PDOException $e) {
$message = $e->getMessage() . "\nFailed to prepare SQL: $sql";
$errorInfo = $e->errorInfo ?? null;
throw new Exception($message, $errorInfo, $e);
}
}
/**
* Binds pending parameters registered via {@see bindValue()} and {@see bindValues()}.
*
* Note that this method requires an active {@see pdoStatement}.
*/
protected function bindPendingParams(): void
{
foreach ($this->params as $name => $value) {
$this->pdoStatement?->bindValue($name, $value->getValue(), $value->getType());
}
}
protected function getConnection(): ConnectionInterface
{
return $this->db;
}
protected function getQueryBuilder(): QueryBuilderInterface
{
return $this->db->getQueryBuilder();
}
protected function getQueryMode(int $queryMode): string
{
return match ($queryMode) {
self::QUERY_MODE_EXECUTE => 'execute',
self::QUERY_MODE_ROW => 'queryOne',
self::QUERY_MODE_ALL => 'queryAll',
self::QUERY_MODE_COLUMN => 'queryColumn',
self::QUERY_MODE_CURSOR => 'query',
self::QUERY_MODE_SCALAR => 'queryScalar',
self::QUERY_MODE_ROW | self::QUERY_MODE_EXECUTE => 'insertWithReturningPks'
};
}
/**
* Executes a prepared statement.
*
* It's a wrapper around {@see PDOStatement::execute()} to support transactions and retry handlers.
*
* @throws Exception
* @throws Throwable
*/
protected function internalExecute(): void
{
$attempt = 0;
while (true) {
try {
if (
++$attempt === 1
&& $this->isolationLevel !== null
&& $this->db->getTransaction() === null
) {
$this->db->transaction(
fn () => $this->internalExecute(),
$this->isolationLevel
);
} else {
set_error_handler(
static fn(int $errorNumber, string $errorString): bool =>
str_starts_with($errorString, 'Packets out of order. Expected '),
E_WARNING,
);
try {
$this->pdoStatement?->execute();
} finally {
restore_error_handler();
}
}
break;
} catch (PDOException $e) {
$rawSql ??= $this->getRawSql();
$e = (new ConvertException($e, $rawSql))->run();
if ($this->retryHandler === null || !($this->retryHandler)($e, $attempt)) {
throw $e;
}
}
}
}
/**
* @throws InvalidParamException
*/
protected function internalGetQueryResult(int $queryMode): mixed
{
if ($queryMode === self::QUERY_MODE_CURSOR) {
/** @psalm-suppress PossiblyNullArgument */
return new PdoDataReader($this->pdoStatement);
}
if ($queryMode === self::QUERY_MODE_EXECUTE) {
return $this->pdoStatement?->rowCount() ?? 0;
}
if ($this->is($queryMode, self::QUERY_MODE_ROW)) {
/** @psalm-var array|false $result */
$result = $this->pdoStatement?->fetch(PDO::FETCH_ASSOC);
} elseif ($this->is($queryMode, self::QUERY_MODE_SCALAR)) {
/** @psalm-var mixed $result */
$result = $this->pdoStatement?->fetchColumn();
} elseif ($this->is($queryMode, self::QUERY_MODE_COLUMN)) {
/** @psalm-var mixed $result */
$result = $this->pdoStatement?->fetchAll(PDO::FETCH_COLUMN);
} elseif ($this->is($queryMode, self::QUERY_MODE_ALL)) {
/** @psalm-var mixed $result */
$result = $this->pdoStatement?->fetchAll(PDO::FETCH_ASSOC);
} else {
throw new InvalidParamException("Unknown query mode '$queryMode'");
}
$this->pdoStatement?->closeCursor();
return $result;
}
protected function queryInternal(int $queryMode): mixed
{
$logCategory = self::class . '::' . $this->getQueryMode($queryMode);
$this->logger?->log(LogLevel::INFO, $rawSql = $this->getRawSql(), [$logCategory, 'type' => LogType::QUERY]);
$queryContext = new CommandContext(__METHOD__, $logCategory, $this->getSql(), $this->getParams());
/** @psalm-var string|null $rawSql */
$this->profiler?->begin($rawSql ??= $this->getRawSql(), $queryContext);
/** @psalm-var string $rawSql */
try {
/** @psalm-var mixed $result */
$result = parent::queryInternal($queryMode);
} catch (Throwable $e) {
$this->profiler?->end($rawSql, $queryContext->setException($e));
throw $e;
}
$this->profiler?->end($rawSql, $queryContext);
return $result;
}
/**
* Refreshes table schema, which was marked by {@see requireTableSchemaRefresh()}.
*/
protected function refreshTableSchema(): void
{
if ($this->refreshTableName !== null) {
$this->db->getSchema()->refreshTableSchema($this->refreshTableName);
}
}
}