1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Yiisoft\Db\Mysql; |
6
|
|
|
|
7
|
|
|
use PDOException; |
8
|
|
|
use Yiisoft\Db\Driver\PDO\CommandPDO as AbstractCommandPDO; |
9
|
|
|
use Yiisoft\Db\Driver\PDO\ConnectionPDOInterface; |
10
|
|
|
use Yiisoft\Db\Exception\ConvertException; |
11
|
|
|
use Yiisoft\Db\QueryBuilder\QueryBuilderInterface; |
12
|
|
|
|
13
|
|
|
final class CommandPDO extends AbstractCommandPDO |
14
|
|
|
{ |
15
|
|
|
/** |
16
|
|
|
* @inheritDoc |
17
|
|
|
*/ |
18
|
1 |
|
public function insertEx(string $table, array $columns): bool|array |
19
|
|
|
{ |
20
|
1 |
|
$params = []; |
21
|
1 |
|
$sql = $this->db->getQueryBuilder()->insertEx($table, $columns, $params); |
22
|
1 |
|
$this->setSql($sql)->bindValues($params); |
23
|
|
|
|
24
|
1 |
|
if (!$this->execute()) { |
25
|
|
|
return false; |
26
|
|
|
} |
27
|
|
|
|
28
|
1 |
|
$tableSchema = $this->db->getSchema()->getTableSchema($table); |
29
|
1 |
|
$tablePrimaryKeys = $tableSchema?->getPrimaryKey() ?? []; |
30
|
|
|
|
31
|
1 |
|
$result = []; |
32
|
1 |
|
foreach ($tablePrimaryKeys as $name) { |
33
|
1 |
|
if ($tableSchema?->getColumn($name)?->isAutoIncrement()) { |
34
|
1 |
|
$result[$name] = $this->db->getLastInsertID((string) $tableSchema?->getSequenceName()); |
35
|
1 |
|
continue; |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
/** @var mixed */ |
39
|
|
|
$result[$name] = $columns[$name] ?? $tableSchema?->getColumn($name)?->getDefaultValue(); |
40
|
|
|
} |
41
|
|
|
|
42
|
1 |
|
return $result; |
43
|
|
|
} |
44
|
|
|
|
45
|
188 |
|
public function queryBuilder(): QueryBuilderInterface |
46
|
|
|
{ |
47
|
188 |
|
return $this->db->getQueryBuilder(); |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
/** |
51
|
|
|
* @psalm-suppress UnusedClosureParam |
52
|
|
|
*/ |
53
|
|
|
protected function internalExecute(string|null $rawSql): void |
54
|
|
|
{ |
55
|
177 |
|
$attempt = 0; |
56
|
|
|
|
57
|
177 |
|
while (true) { |
58
|
|
|
try { |
59
|
177 |
|
if ( |
60
|
|
|
++$attempt === 1 |
61
|
|
|
&& $this->isolationLevel !== null |
62
|
|
|
&& $this->db->getTransaction() === null |
63
|
177 |
|
) { |
64
|
177 |
|
$this->db->transaction( |
65
|
|
|
fn (ConnectionPDOInterface $db) => $this->internalExecute($rawSql), |
|
|
|
|
66
|
|
|
$this->isolationLevel, |
67
|
|
|
); |
68
|
|
|
} else { |
69
|
|
|
$this->pdoStatement?->execute(); |
70
|
|
|
} |
71
|
177 |
|
break; |
72
|
|
|
} catch (PDOException $e) { |
73
|
175 |
|
$rawSql = $rawSql ?: $this->getRawSql(); |
74
|
22 |
|
$e = (new ConvertException($e, $rawSql))->run(); |
75
|
22 |
|
|
76
|
22 |
|
if ($this->retryHandler === null || !($this->retryHandler)($e, $attempt)) { |
77
|
|
|
throw $e; |
78
|
22 |
|
} |
79
|
22 |
|
} |
80
|
|
|
} |
81
|
|
|
} |
82
|
|
|
} |
83
|
|
|
|
This check looks for parameters that have been defined for a function or method, but which are not used in the method body.