Passed
Push — main ( 2f6ba2...07a540 )
by Thierry
14:56 queued 07:25
created

Database::alterTable()   B

Complexity

Conditions 8
Paths 48

Size

Total Lines 24
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 4
Bugs 0 Features 0
Metric Value
cc 8
eloc 15
c 4
b 0
f 0
nc 48
nop 2
dl 0
loc 24
rs 8.4444
1
<?php
2
3
namespace Lagdo\DbAdmin\Driver\Sqlite\Db;
4
5
use Lagdo\DbAdmin\Driver\Entity\TableEntity;
6
use Lagdo\DbAdmin\Driver\Db\Database as AbstractDatabase;
7
8
use function is_object;
9
use function intval;
10
use function implode;
11
use function array_reverse;
12
13
class Database extends AbstractDatabase
14
{
15
    /**
16
     * @param string $table
17
     * @param int $autoIncrement
18
     *
19
     * @return void
20
     */
21
    private function setAutoIncrement(string $table, int $autoIncrement)
22
    {
23
        if ($autoIncrement) {
24
            $this->driver->execute('BEGIN');
25
            $this->driver->execute("UPDATE sqlite_sequence SET seq = $autoIncrement WHERE name = " .
26
                $this->driver->quote($table)); // ignores error
27
            if (!$this->driver->affectedRows()) {
28
                $this->driver->execute('INSERT INTO sqlite_sequence (name, seq) VALUES (' .
29
                    $this->driver->quote($table) . ", $autoIncrement)");
30
            }
31
            $this->driver->execute('COMMIT');
32
        }
33
    }
34
35
    /**
36
     * @inheritDoc
37
     */
38
    public function tables()
39
    {
40
        return $this->driver->keyValues('SELECT name, type FROM sqlite_master ' .
41
            "WHERE type IN ('table', 'view') ORDER BY (name = 'sqlite_sequence'), name");
42
    }
43
44
    /**
45
     * @inheritDoc
46
     */
47
    public function countTables(array $databases)
48
    {
49
        $connection = $this->driver->createConnection(); // New connection
50
        $counts = [];
51
        $query = "SELECT count(*) FROM sqlite_master WHERE type IN ('table', 'view')";
52
        foreach ($databases as $database) {
53
            $counts[$database] = 0;
54
            $connection->open($database);
55
            $statement = $connection->query($query);
56
            if (is_object($statement) && ($row = $statement->fetchRow())) {
57
                $counts[$database] = intval($row[0]);
58
            }
59
        }
60
        return $counts;
61
    }
62
63
    /**
64
     * @inheritDoc
65
     */
66
    public function dropViews(array $views)
67
    {
68
        return $this->driver->applyQueries('DROP VIEW', $views);
69
    }
70
71
    /**
72
     * @inheritDoc
73
     */
74
    public function dropTables(array $tables)
75
    {
76
        return $this->driver->applyQueries('DROP TABLE', $tables);
77
    }
78
79
    /**
80
     * @inheritDoc
81
     */
82
    public function moveTables(array $tables, array $views, string $target)
83
    {
84
        return false;
85
    }
86
87
    /**
88
     * @inheritDoc
89
     */
90
    public function truncateTables(array $tables)
91
    {
92
        return $this->driver->applyQueries('DELETE FROM', $tables);
93
    }
94
95
    /**
96
     * @inheritDoc
97
     */
98
    public function createTable(TableEntity $tableAttrs)
99
    {
100
        foreach ($tableAttrs->fields as $key => $field) {
101
            $tableAttrs->fields[$key] = '  ' . implode($field);
102
        }
103
        $tableAttrs->fields = array_merge($tableAttrs->fields, array_filter($tableAttrs->foreign));
104
        if (!$this->driver->execute('CREATE TABLE ' . $this->driver->table($tableAttrs->name) .
105
            " (\n" . implode(",\n", $tableAttrs->fields) . "\n)")) {
106
            // implicit ROLLBACK to not overwrite $this->driver->error()
107
            return false;
108
        }
109
        $this->setAutoIncrement($tableAttrs->name, $tableAttrs->autoIncrement);
110
        return true;
111
    }
112
113
    /**
114
     * @inheritDoc
115
     */
116
    public function alterTable(string $table, TableEntity $tableAttrs)
117
    {
118
        $clauses = [];
119
        foreach ($tableAttrs->fields as $field) {
120
            if ($field[1]) {
121
                $clauses[] = ($field[0] != ''  ? $field[1] : 'ADD ' . implode($field[1]));
122
            }
123
        }
124
        $queries = [];
125
        foreach ($clauses as $clause) {
126
            $queries[] = 'ALTER TABLE ' . $this->driver->table($table) . ' ' . $clause;
127
        }
128
        if ($table != $tableAttrs->name) {
129
            $queries[] = 'ALTER TABLE ' . $this->driver->table($table) . ' RENAME TO ' .
130
                $this->driver->table($tableAttrs->name);
131
        }
132
        // TODO: Wrap queries into a transaction
133
        foreach ($queries as $query) {
134
            if (!$this->driver->execute($query)) {
135
                return false;
136
            }
137
        }
138
        $this->setAutoIncrement($tableAttrs->name, $tableAttrs->autoIncrement);
139
        return true;
140
    }
141
142
    /**
143
     * @inheritDoc
144
     */
145
    public function alterIndexes(string $table, array $alter, array $drop)
146
    {
147
        $queries = [];
148
        foreach (array_reverse($drop) as $index) {
149
            $queries[] = 'DROP INDEX ' . $this->driver->escapeId($index->name);
150
        }
151
        foreach (array_reverse($alter) as $index) {
152
            // Can't alter primary keys
153
            if ($index->type !== 'PRIMARY') {
154
                $queries[] =  $this->driver->sqlForCreateIndex($table, $index->type,
155
                    $index->name, '(' . implode(', ', $index->columns) . ')');
156
            }
157
        }
158
        // TODO: Wrap queries into a transaction
159
        foreach ($queries as $query) {
160
            $this->driver->execute($query);
161
        }
162
        return true;
163
    }
164
}
165