1<?php
2
3namespace dokuwiki\plugin\sqlite;
4
5use dokuwiki\Extension\Event;
6
7class QuerySaver
8{
9    protected $db;
10    protected $upstream;
11
12    /**
13     * @param string $dbname The database the queries are saved for
14     */
15    public function __construct($dbname)
16    {
17        $this->db = new SQLiteDB('sqlite', DOKU_PLUGIN . 'sqlite/db/');
18        $this->upstream = $dbname;
19    }
20
21    /**
22     * Save a query
23     *
24     * @param string $name
25     * @param string $query
26     */
27    public function saveQuery($name, $query)
28    {
29        $eventData = [
30            'sqlitedb' => $this->db,
31            'upstream'  => $this->upstream,
32            'name' => &$name,
33            'query' => &$query
34        ];
35        $event = new Event('PLUGIN_SQLITE_QUERY_SAVE', $eventData);
36        if ($event->advise_before()) {
37            $sql = 'INSERT INTO queries (db, name, sql) VALUES (?, ?, ?)';
38            $this->db->exec($sql, [$this->upstream, $name, $query]);
39        }
40        $event->advise_after();
41    }
42
43    /**
44     * Get a saved query
45     *
46     * @param string $name
47     * @return string The SQL query
48     */
49    public function getQuery($name)
50    {
51        $sql = 'SELECT sql FROM queries WHERE db = ? AND name = ?';
52        return $this->db->queryValue($sql, [$this->upstream, $name]);
53    }
54
55    /**
56     * Delete a saved query
57     *
58     * @param string $name
59     */
60    public function deleteQuery($name)
61    {
62        $eventData = [
63            'sqlitedb' => $this->db,
64            'upstream'  => $this->upstream,
65            'name' => &$name
66        ];
67        $event = new Event('PLUGIN_SQLITE_QUERY_DELETE', $eventData);
68        if ($event->advise_before()) {
69            $sql = 'DELETE FROM queries WHERE db = ? AND name = ?';
70            $this->db->exec($sql, [$this->upstream, $name]);
71        }
72        $event->advise_after();
73    }
74
75    /**
76     * Get all saved queries
77     *
78     * @return array
79     */
80    public function getQueries()
81    {
82        $sql = 'SELECT name, sql FROM queries WHERE db = ?';
83        return $this->db->queryAll($sql, [$this->upstream]);
84    }
85}
86