Test Failed
Pull Request — dev (#119)
by Wilmer
02:37
created

CommandPDOMysql::schema()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 1
c 0
b 0
f 0
dl 0
loc 3
ccs 1
cts 1
cp 1
rs 10
cc 1
nc 1
nop 0
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Db\Mysql\PDO;
6
7
use PDOException;
8
use Yiisoft\Db\Driver\PDO\CommandPDO;
9
use Yiisoft\Db\Exception\ConvertException;
10
use Yiisoft\Db\Query\QueryBuilderInterface;
11
use Yiisoft\Db\Schema\SchemaInterface;
12
13
final class CommandPDOMysql extends CommandPDO
14
{
15
    /**
16
     * @inheritDoc
17 1
     */
18
    public function insertEx(string $table, array $columns): bool|array
19 1
    {
20 1
        $params = [];
21 1
        $sql = $this->db->getQueryBuilder()->insertEx($table, $columns, $params);
22
        $this->setSql($sql)->bindValues($params);
23 1
24
        if (!$this->execute()) {
25
            return false;
26
        }
27 1
28 1
        $tableSchema = $this->db->getSchema()->getTableSchema($table);
29
        $tablePrimaryKeys = $tableSchema?->getPrimaryKey() ?? [];
30 1
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
                continue;
36
            }
37
38
            /** @var mixed */
39
            $result[$name] = $columns[$name] ?? $tableSchema?->getColumn($name)?->getDefaultValue();
40
        }
41 1
42
        return $result;
43
    }
44 184
45
    public function queryBuilder(): QueryBuilderInterface
46 184
    {
47
        return $this->db->getQueryBuilder();
48
    }
49 173
50
    public function schema(): SchemaInterface
51 173
    {
52
        return $this->db->getSchema();
53 173
    }
54
55
    protected function internalExecute(?string $rawSql): void
56 173
    {
57 173
        $attempt = 0;
58 173
59
        while (true) {
60
            try {
61
                if (
62 173
                    ++$attempt === 1
63
                    && $this->isolationLevel !== null
64 170
                    && $this->db->getTransaction() === null
65 23
                ) {
66 23
                    $this->db->transaction(fn (?string $rawSql) => $this->internalExecute($rawSql), $this->isolationLevel);
67 23
                } else {
68
                    $this->pdoStatement?->execute();
69 23
                }
70 23
                break;
71
            } catch (PDOException $e) {
72
                $rawSql = $rawSql ?: $this->getRawSql();
73
                $e = (new ConvertException($e, $rawSql))->run();
74
75
                if ($this->retryHandler === null || !($this->retryHandler)($e, $attempt)) {
76
                    throw $e;
77
                }
78
            }
79
        }
80
    }
81
}
82