Passed
Pull Request — master (#49)
by Thomas
02:17
created

Sqlite::describe()   A

Complexity

Conditions 4
Paths 8

Size

Total Lines 23
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 4

Importance

Changes 0
Metric Value
eloc 14
dl 0
loc 23
ccs 10
cts 10
cp 1
rs 9.7998
c 0
b 0
f 0
cc 4
nc 8
nop 1
crap 4
1
<?php
2
3
namespace ORM\Dbal;
4
5
use ORM\Entity;
6
use ORM\Exception;
7
8
/**
9
 * Database abstraction for SQLite databases
10
 *
11
 * @package ORM\Dbal
12
 * @author  Thomas Flori <[email protected]>
13
 */
14
class Sqlite extends Dbal
15
{
16
    protected static $typeMapping = [
17
        'integer' => Type\Number::class,
18
        'int'     => Type\Number::class,
19
        'double'  => Type\Number::class,
20
        'real'    => Type\Number::class,
21
        'float'   => Type\Number::class,
22
        'numeric' => Type\Number::class,
23
        'decimal' => Type\Number::class,
24
25
        'varchar'   => Type\VarChar::class,
26
        'character' => Type\VarChar::class,
27
28
        'text' => Type\Text::class,
29
30
        'boolean' => Type\Boolean::class,
31
        'json'    => Type\Json::class,
32
33
        'datetime' => Type\DateTime::class,
34
        'date'     => Type\DateTime::class,
35
        'time'     => Type\Time::class,
36
    ];
37
38 2
    public function insertAndSyncWithAutoInc(Entity ...$entities)
39
    {
40 2
        if (count($entities) === 0) {
41 2
            return false;
42
        }
43 2
        static::assertSameType($entities);
44 1
45 1
        $entity = reset($entities);
46
        $pdo = $this->entityManager->getConnection();
47 1
        $table = $this->escapeIdentifier($entity::getTableName());
48
        $pKey = $this->escapeIdentifier($entity::getColumnName($entity::getPrimaryKeyVars()[0]));
49
        $pdo->beginTransaction();
50 2
        $pdo->query($this->buildInsertStatement(...$entities));
51
        $rows = $pdo->query('SELECT * FROM ' . $table . ' WHERE ' . $pKey . ' <= ' . $pdo->lastInsertId() .
52
                            ' ORDER BY ' . $pKey . ' DESC LIMIT ' . count($entities))
53 32
            ->fetchAll(\PDO::FETCH_ASSOC);
54
        $pdo->commit();
55 32
56 32
        /** @var Entity $entity */
57 32
        foreach (array_reverse($entities) as $key => $entity) {
58
            $entity->setOriginalData($rows[$key]);
59 32
            $entity->reset();
60 32
            $this->entityManager->map($entity, true);
61
        }
62 32
63
        return true;
64 32
    }
65 2
66
    public function describe($schemaTable)
67
    {
68 30
        $table = explode($this->identifierDivider, $schemaTable);
69
        list($schema, $table) = count($table) === 2 ? $table : [ null, $table[ 0 ] ];
70 30
        $schema = $schema !== null ? $this->escapeIdentifier($schema) . '.' : '';
71 30
72 30
        $result     = $this->entityManager->getConnection()->query(
73 30
            'PRAGMA ' . $schema . 'table_info(' . $this->escapeIdentifier($table) . ')'
74
        );
75 30
        $rawColumns = $result->fetchAll(\PDO::FETCH_ASSOC);
76
77
        if (count($rawColumns) === 0) {
78
            throw new Exception('Unknown table ' . $table);
79
        }
80
81
        $compositeKey = $this->hasCompositeKey($rawColumns);
82
83
        $cols = array_map(function ($rawColumn) use ($compositeKey) {
84 30
            $columnDefinition = $this->normalizeColumnDefinition($rawColumn, $compositeKey);
85
            return new Column($this, $columnDefinition);
86 30
        }, $rawColumns);
87 30
88 30
        return new Table($cols);
89 30
    }
90
91 30
    /**
92
     * Checks $rawColumns for a multiple primary key
93
     *
94
     * @param array $rawColumns
95
     * @return bool
96
     */
97
    protected function hasCompositeKey($rawColumns)
98
    {
99
        return count(array_filter(array_map(
100
            function ($rawColumn) {
101
                return $rawColumn[ 'pk' ];
102
            },
103
            $rawColumns
104 30
        ))) > 1;
105
    }
106 30
107
    /**
108 30
     * Normalize a column definition
109 30
     *
110 29
     * The column definition from "PRAGMA table_info(<table>)" is to special as useful. Here we normalize it to a more
111
     * ANSI-SQL style.
112
     *
113 30
     * @param array $rawColumn
114 30
     * @param bool  $compositeKey
115 30
     * @return array
116 30
     */
117 30
    protected function normalizeColumnDefinition($rawColumn, $compositeKey = false)
118
    {
119 30
        $definition = [];
120 30
121 28
        $definition['data_type'] = $this->normalizeType($rawColumn['type']);
122 2
        $definition['type'] = isset(static::$typeMapping[$definition['data_type']]) ?
123 2
            static::$typeMapping[$definition['data_type']] : null;
124 28
125 27
        $definition['column_name']              = $rawColumn['name'];
126 27
        $definition['is_nullable']              = $rawColumn['notnull'] === '0';
127 2
        $definition['column_default']           = $rawColumn['dflt_value'];
128 2
        $definition['character_maximum_length'] = null;
129 26
        $definition['datetime_precision']       = null;
130 9
131 1
        if (in_array($definition['data_type'], ['varchar', 'char'])) {
132
            $definition['character_maximum_length'] = $this->extractParenthesis($rawColumn['type']);
133 9
        } elseif (in_array($definition['data_type'], ['datetime', 'timestamp', 'time'])) {
134
            $definition['datetime_precision'] = $this->extractParenthesis($rawColumn['type']);
135
        } elseif ($definition['data_type'] === 'integer' && !$definition['column_default'] &&
136 30
                  $rawColumn['pk'] === '1' && !$compositeKey
137
        ) {
138
            $definition['column_default'] = 'sequence(rowid)';
139
        }
140
141
        return $definition;
142
    }
143
}
144