Completed
Push — master ( a79949...86c63e )
by Joao
12s queued 10s
created

SqliteDatabase::isDatabaseVersioned()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
1
<?php
2
3
namespace ByJG\DbMigration\Database;
4
5
use Psr\Http\Message\UriInterface;
6
7
class SqliteDatabase extends AbstractDatabase
8
{
9
10
    public static function prepareEnvironment(UriInterface $uri)
11
    {
12
    }
13
14
    public function createDatabase()
15
    {
16
    }
17
18
    public function dropDatabase()
19
    {
20
        $iterator = $this->getDbDriver()->getIterator("
21
            select 
22
                'drop table ' || name || ';' as command 
23
            from sqlite_master 
24
            where type = 'table' 
25
              and name <> 'sqlite_sequence';
26
        ");
27
28
        foreach ($iterator as $row) {
29
            $this->getDbDriver()->execute($row->get('command'));
30
        }
31
    }
32
33
    /**
34
     * @throws \ByJG\DbMigration\Exception\DatabaseNotVersionedException
35
     * @throws \ByJG\DbMigration\Exception\OldVersionSchemaException
36
     */
37
    public function createVersion()
38
    {
39
        $this->getDbDriver()->execute('CREATE TABLE IF NOT EXISTS ' . $this->getMigrationTable() . ' (version int, status varchar(20))');
40
        $this->checkExistsVersion();
41
    }
42
43
    public function executeSql($sql)
44
    {
45
        $statements = preg_split("/;(\r\n|\r|\n)/", $sql);
46
47
        foreach ($statements as $sql) {
48
            $this->executeSqlInternal($sql);
49
        }
50
    }
51
52
    protected function executeSqlInternal($sql)
53
    {
54
        $this->getDbDriver()->execute($sql);
55
    }
56
57
    protected function isTableExists($schema, $table)
58
    {
59
        $count = $this->getDbDriver()->getScalar(
60
            "SELECT count(*) FROM sqlite_master WHERE type='table' AND name=[[table]]",
61
            [
62
                "table" => $table
63
            ]
64
        );
65
66
        return (intval($count) !== 0);
67
    }
68
69
    public function isDatabaseVersioned()
70
    {
71
        return $this->isTableExists(null, $this->getMigrationTable());
72
    }
73
}
74