Passed
Push — master ( aa56fb...89b72d )
by Joao
10:12 queued 12s
created

SqliteDatabase::schema()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 1
c 0
b 0
f 0
dl 0
loc 3
rs 10
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
    public static function schema()
10
    {
11
        return 'sqlite';
12
    }
13
14
    public static function prepareEnvironment(UriInterface $uri)
15
    {
16
    }
17
18
    public function createDatabase()
19
    {
20
    }
21
22
    public function dropDatabase()
23
    {
24
        $iterator = $this->getDbDriver()->getIterator("
25
            select
26
                'drop ' || type || ' ' || name || ';' as command
27
            from sqlite_master
28
            where name <> 'sqlite_sequence' and name not like 'sqlite_autoindex_%'
29
            order by CASE type
30
                         WHEN 'index' THEN 0
31
                         WHEN 'trigger' THEN 1
32
                         WHEN 'view' THEN 2
33
                         ELSE 99
34
                    END;
35
        ");
36
37
        foreach ($iterator as $row) {
38
            $this->getDbDriver()->execute($row->get('command'));
39
        }
40
    }
41
42
    /**
43
     * @throws \ByJG\DbMigration\Exception\DatabaseNotVersionedException
44
     * @throws \ByJG\DbMigration\Exception\OldVersionSchemaException
45
     */
46
    public function createVersion()
47
    {
48
        $this->getDbDriver()->execute('CREATE TABLE IF NOT EXISTS ' . $this->getMigrationTable() . ' (version int, status varchar(20), PRIMARY KEY (version))');
49
        $this->checkExistsVersion();
50
    }
51
52
    public function executeSql($sql)
53
    {
54
        $statements = preg_split("/;(\r\n|\r|\n)/", $sql);
55
56
        foreach ($statements as $sql) {
0 ignored issues
show
introduced by
$sql is overwriting one of the parameters of this function.
Loading history...
57
            $this->executeSqlInternal($sql);
58
        }
59
    }
60
61
    protected function executeSqlInternal($sql)
62
    {
63
        if (empty(trim($sql))) {
64
            return;
65
        }
66
        $this->getDbDriver()->execute($sql);
67
    }
68
69
    protected function isTableExists($schema, $table)
70
    {
71
        $count = $this->getDbDriver()->getScalar(
72
            "SELECT count(*) FROM sqlite_master WHERE type='table' AND name=[[table]]",
73
            [
74
                "table" => $table
75
            ]
76
        );
77
78
        return (intval($count) !== 0);
79
    }
80
81
    public function isDatabaseVersioned()
82
    {
83
        return $this->isTableExists(null, $this->getMigrationTable());
84
    }
85
}
86