Passed
Branch main (2a1ad3)
by Thierry
06:07 queued 03:57
created

Grammar   A

Complexity

Total Complexity 13

Size/Duplication

Total Lines 72
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 22
c 0
b 0
f 0
dl 0
loc 72
rs 10
wmc 13

7 Methods

Rating   Name   Duplication   Size   Complexity  
A limit() 0 4 3
A escapeId() 0 3 1
A sqlForCreateTrigger() 0 5 1
A autoIncrement() 0 3 1
A sqlForCreateTable() 0 14 3
A sqlForTruncateTable() 0 3 1
A sqlForCreateIndex() 0 5 3
1
<?php
2
3
namespace Lagdo\DbAdmin\Driver\Sqlite\Db;
4
5
use Lagdo\DbAdmin\Driver\Db\Grammar as AbstractGrammar;
6
7
class Grammar extends AbstractGrammar
8
{
9
    /**
10
     * @inheritDoc
11
     */
12
    public function escapeId(string $idf)
13
    {
14
        return '"' . str_replace('"', '""', $idf) . '"';
15
    }
16
17
    /**
18
     * @inheritDoc
19
     */
20
    public function limit(string $query, string $where, int $limit, int $offset = 0, string $separator = " ")
21
    {
22
        return " $query$where" . ($limit !== 0 ? $separator .
23
            "LIMIT $limit" . ($offset ? " OFFSET $offset" : "") : "");
24
    }
25
26
    /**
27
     * @inheritDoc
28
     */
29
    public function autoIncrement()
30
    {
31
        return " PRIMARY KEY AUTOINCREMENT";
32
    }
33
34
    /**
35
     * @inheritDoc
36
     */
37
    public function sqlForCreateTable(string $table, bool $autoIncrement, string $style)
38
    {
39
        $query = $this->connection->result("SELECT sql FROM sqlite_master " .
40
            "WHERE type IN ('table', 'view') AND name = " . $this->driver->quote($table));
41
        foreach ($this->driver->indexes($table) as $name => $index) {
42
            if ($name == '') {
43
                continue;
44
            }
45
            $columns = implode(", ", array_map(function ($key) {
46
                return $this->escapeId($key);
47
            }, $index->columns));
48
            $query .= ";\n\n" . $this->sqlForCreateIndex($table, $index->type, $name, "($columns)");
49
        }
50
        return $query;
51
    }
52
53
    /**
54
     * @inheritDoc
55
     */
56
    public function sqlForCreateIndex(string $table, string $type, string $name, string $columns)
57
    {
58
        return "CREATE $type " . ($type != "INDEX" ? "INDEX " : "") .
59
            $this->escapeId($name != "" ? $name : uniqid($table . "_")) .
60
            " ON " . $this->table($table) . " $columns";
61
    }
62
63
    /**
64
     * @inheritDoc
65
     */
66
    public function sqlForTruncateTable(string $table)
67
    {
68
        return "DELETE FROM " . $this->table($table);
69
    }
70
71
    /**
72
     * @inheritDoc
73
     */
74
    public function sqlForCreateTrigger(string $table)
75
    {
76
        $query = "SELECT sql || ';;\n' FROM sqlite_master WHERE type = 'trigger' AND tbl_name = " .
77
            $this->driver->quote($table);
78
        return implode($this->driver->values($query));
79
    }
80
}
81