-
-
Notifications
You must be signed in to change notification settings - Fork 15
/
Command.php
73 lines (57 loc) · 2.03 KB
/
Command.php
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
<?php
declare(strict_types=1);
namespace Yiisoft\Db\Mysql;
use Yiisoft\Db\Driver\Pdo\AbstractPdoCommand;
use Yiisoft\Db\Exception\IntegrityException;
use function str_starts_with;
/**
* Implements a database command that can be executed with a PDO (PHP Data Object) database connection for MySQL,
* MariaDB.
*/
final class Command extends AbstractPdoCommand
{
public function insertWithReturningPks(string $table, array $columns): bool|array
{
$params = [];
$sql = $this->db->getQueryBuilder()->insert($table, $columns, $params);
$this->setSql($sql)->bindValues($params);
$tableSchema = $this->db->getSchema()->getTableSchema($table);
if (!$this->execute()) {
return false;
}
$tablePrimaryKeys = $tableSchema?->getPrimaryKey() ?? [];
$result = [];
foreach ($tablePrimaryKeys as $name) {
if ($tableSchema?->getColumn($name)?->isAutoIncrement()) {
$result[$name] = $this->db->getLastInsertID((string) $tableSchema?->getSequenceName());
continue;
}
/** @psalm-var mixed */
$result[$name] = $columns[$name] ?? $tableSchema?->getColumn($name)?->getDefaultValue();
}
return $result;
}
protected function queryInternal(int $queryMode): mixed
{
try {
return parent::queryInternal($queryMode);
} catch (IntegrityException $e) {
if (
str_starts_with($e->getMessage(), 'SQLSTATE[HY000]: General error: 2006 ')
&& $this->db->getTransaction() === null
) {
$this->cancel();
$this->db->close();
return parent::queryInternal($queryMode);
}
throw $e;
}
}
public function showDatabases(): array
{
$sql = <<<SQL
SHOW DATABASES WHERE `Database` NOT IN ('information_schema', 'mysql', 'performance_schema', 'sys')
SQL;
return $this->setSql($sql)->queryColumn();
}
}