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

Query::limitToOne()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 4
c 0
b 0
f 0
nc 4
nop 4
dl 0
loc 7
rs 10
1
<?php
2
3
namespace Lagdo\DbAdmin\Driver\Sqlite\Db;
4
5
use Lagdo\DbAdmin\Driver\Db\ConnectionInterface;
6
7
use Lagdo\DbAdmin\Driver\Db\Query as AbstractQuery;
8
9
class Query extends AbstractQuery
10
{
11
    /**
12
     * @inheritDoc
13
     */
14
    protected function limitToOne(string $table, string $query, string $where, string $separator = "\n")
15
    {
16
        return preg_match('~^INTO~', $query) ||
17
            $this->connection->result("SELECT sqlite_compileoption_used('ENABLE_UPDATE_DELETE_LIMIT')") ?
18
            $this->driver->limit($query, $where, 1, 0, $separator) :
19
            //! use primary key in tables with WITHOUT rowid
20
            " $query WHERE rowid = (SELECT rowid FROM " . $this->driver->table($table) . $where . $separator . "LIMIT 1)";
21
    }
22
23
    /**
24
     * @inheritDoc
25
     */
26
    public function insertOrUpdate(string $table, array $rows, array $primary)
27
    {
28
        $values = [];
29
        foreach ($rows as $set) {
30
            $values[] = "(" . implode(", ", $set) . ")";
31
        }
32
        $result = $this->driver->execute("REPLACE INTO " . $this->driver->table($table) .
33
            " (" . implode(", ", array_keys(reset($rows))) . ") VALUES\n" . implode(",\n", $values));
34
        return $result !== false;
35
    }
36
37
    /**
38
     * @inheritDoc
39
     */
40
    public function user()
41
    {
42
        return get_current_user(); // should return effective user
43
    }
44
45
    /**
46
     * @inheritDoc
47
     */
48
    public function view(string $name)
49
    {
50
        return [
51
            'name' => $name,
52
            'type' => 'VIEW',
53
            'materialized' => false,
54
            'select' => preg_replace('~^(?:[^`"[]+|`[^`]*`|"[^"]*")* AS\s+~iU', '',
55
                $this->connection->result("SELECT sql FROM sqlite_master WHERE name = " .
56
                $this->driver->quote($name)))
57
        ]; //! identifiers may be inside []
58
    }
59
60
    /**
61
     * @inheritDoc
62
     */
63
    public function lastAutoIncrementId()
64
    {
65
        return $this->connection->result("SELECT LAST_INSERT_ROWID()");
66
    }
67
68
    /**
69
     * @inheritDoc
70
     */
71
    public function explain(ConnectionInterface $connection, string $query)
72
    {
73
        return $connection->query("EXPLAIN QUERY PLAN $query");
74
    }
75
}
76