Completed
Pull Request — master (#49)
by Thomas
02:04
created

Mysql   A

Complexity

Total Complexity 13

Size/Duplication

Total Lines 106
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 13
eloc 65
dl 0
loc 106
ccs 42
cts 42
cp 1
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A describe() 0 14 3
A insertAndSyncWithAutoInc() 0 25 3
B normalizeColumnDefinition() 0 24 7
1
<?php
2
3
namespace ORM\Dbal;
4
5
use ORM\Entity;
6
use ORM\Exception;
7
8
/**
9
 * Database abstraction for MySQL databases
10
 *
11
 * @package ORM\Dbal
12
 * @author  Thomas Flori <[email protected]>
13
 */
14
class Mysql extends Dbal
15
{
16
    protected static $typeMapping = [
17
        'tinyint'   => Type\Number::class,
18
        'smallint'  => Type\Number::class,
19
        'mediumint' => Type\Number::class,
20
        'int'       => Type\Number::class,
21
        'bigint'    => Type\Number::class,
22
        'decimal'   => Type\Number::class,
23
        'float'     => Type\Number::class,
24
        'double'    => Type\Number::class,
25
26
        'varchar' => Type\VarChar::class,
27
        'char'    => Type\VarChar::class,
28
29
        'text'       => Type\Text::class,
30
        'tinytext'   => Type\Text::class,
31
        'mediumtext' => Type\Text::class,
32
        'longtext'   => Type\Text::class,
33
34
        'datetime'  => Type\DateTime::class,
35
        'date'      => Type\DateTime::class,
36
        'timestamp' => Type\DateTime::class,
37
38
        'time' => Type\Time::class,
39
        'enum' => Type\Enum::class,
40
        'set'  => Type\Set::class,
41
        'json' => Type\Json::class,
42
    ];
43
44 6
    public function insertAndSyncWithAutoInc(Entity ...$entities)
45
    {
46 6
        if (count($entities) === 0) {
47 6
            return false;
48
        }
49 6
        static::assertSameType($entities);
50 4
51 1
        $entity = reset($entities);
52
        $table = $this->escapeIdentifier($entity::getTableName());
53 2
        $pKey = $this->escapeIdentifier($entity::getColumnName($entity::getPrimaryKeyVars()[0]));
54
        $pdo = $this->entityManager->getConnection();
55
        $pdo->beginTransaction();
56 3
        $pdo->query($this->buildInsertStatement(...$entities));
57
        $rows = $pdo->query('SELECT * FROM ' . $table . ' WHERE ' . $pKey . ' >= LAST_INSERT_ID()')
58
            ->fetchAll(\PDO::FETCH_ASSOC);
59 50
        $pdo->commit();
60
61
        /** @var Entity $entity */
62 50
        foreach (array_values($entities) as $key => $entity) {
63 1
            $entity->setOriginalData($rows[$key]);
64 1
            $entity->reset();
65
            $this->entityManager->map($entity, true);
66
        }
67 49
68 49
        return true;
69 49
    }
70
71
    public function describe($table)
72 49
    {
73
        try {
74
            $result = $this->entityManager->getConnection()->query('DESCRIBE ' . $this->escapeIdentifier($table));
75
        } catch (\PDOException $exception) {
76
            throw new Exception('Unknown table ' . $table, 0, $exception);
77
        }
78
79
        $cols = [];
80
        while ($rawColumn = $result->fetch(\PDO::FETCH_ASSOC)) {
81
            $cols[] = new Column($this, $this->normalizeColumnDefinition($rawColumn));
82
        }
83
84 49
        return new Table($cols);
85
    }
86 49
87
    /**
88 49
     * Normalize a column definition
89 49
     *
90 44
     * The column definition from "DESCRIBE <table>" is to special as useful. Here we normalize it to a more
91
     * ANSI-SQL style.
92
     *
93 49
     * @param array $rawColumn
94 49
     * @return array
95 49
     */
96 46
    protected function normalizeColumnDefinition($rawColumn)
97 49
    {
98 49
        $definition = [];
99
100 49
        $definition['data_type'] = $this->normalizeType($rawColumn['Type']);
101 49
        $definition['type'] = isset(static::$typeMapping[$definition['data_type']]) ?
102 47
            static::$typeMapping[$definition['data_type']] : null;
103 4
104 4
        $definition['column_name'] = $rawColumn['Field'];
105 45
        $definition['is_nullable'] = $rawColumn['Null'] === 'YES';
106 41
        $definition['character_maximum_length'] = null;
107 37
        $definition['datetime_precision'] = null;
108 12
        $definition['column_default'] = $rawColumn['Default'] === null && $rawColumn['Extra'] === 'auto_increment' ?
109 12
            'sequence(AUTO_INCREMENT)' : $rawColumn['Default'];
110 33
111 31
        if (in_array($definition['data_type'], ['varchar', 'char'])) {
112 4
            $definition['character_maximum_length'] = $this->extractParenthesis($rawColumn['Type']);
113 4
        } elseif (in_array($definition['data_type'], ['datetime', 'timestamp', 'time'])) {
114
            $definition['datetime_precision'] = $this->extractParenthesis($rawColumn['Type']);
115
        } elseif (in_array($definition['data_type'], ['set', 'enum'])) {
116 49
            $definition['enumeration_values'] = $this->extractParenthesis($rawColumn['Type']);
117
        }
118
119
        return $definition;
120
    }
121
}
122