xref: /plugin/sqlite/helper/db.php (revision 74f97ccf1023a6cf39ecc6971c0f0ebb3978597b)
1<?php
2
3/**
4 * DokuWiki Plugin struct (Helper Component)
5 *
6 * @license GPL 2 http://www.gnu.org/licenses/gpl-2.0.html
7 * @author  Andreas Gohr, Michael Große <dokuwiki@cosmocode.de>
8 */
9
10use dokuwiki\plugin\struct\meta\StructException;
11
12class helper_plugin_sqlite_db extends DokuWiki_Plugin
13{
14    /** @var helper_plugin_sqlite */
15    protected $sqlite;
16
17    /**
18     * helper_plugin_struct_db constructor.
19     */
20    public function __construct()
21    {
22        $this->init();
23    }
24
25    /**
26     * Initialize the database
27     *
28     * @throws Exception
29     */
30    protected function init()
31    {
32        /** @var helper_plugin_sqlite $sqlite */
33        $this->sqlite = plugin_load('helper', 'sqlite');
34        if (!$this->sqlite) {
35            if (defined('DOKU_UNITTEST')) throw new \Exception('Couldn\'t load sqlite.');
36            return;
37        }
38
39        if ($this->sqlite->getAdapter() === null) {
40            if (defined('DOKU_UNITTEST')) throw new \Exception('Couldn\'t load PDO sqlite.');
41            $this->sqlite = null;
42            return;
43        }
44
45        if ($this->sqlite->getAdapter()->getName() != DOKU_EXT_PDO) {
46            if (defined('DOKU_UNITTEST')) throw new \Exception('Couldn\'t load PDO sqlite.');
47            $this->sqlite = null;
48            return;
49        }
50        $this->sqlite->getAdapter()->setUseNativeAlter(true);
51
52        // initialize the database connection
53        if (!$this->sqlite->init('sqlite', DOKU_PLUGIN . 'sqlite/db/')) {
54            if (defined('DOKU_UNITTEST')) throw new \Exception('Couldn\'t init sqlite.');
55            $this->sqlite = null;
56            return;
57        }
58    }
59
60    /**
61     * @param bool $throw throw an Exception when sqlite not available?
62     * @return helper_plugin_sqlite|null
63     */
64    public function getDB($throw = true)
65    {
66        global $conf;
67        $len = strlen($conf['metadir']);
68        if ($this->sqlite && $conf['metadir'] != substr($this->sqlite->getAdapter()->getDbFile(), 0, $len)) {
69            $this->init();
70        }
71        if (!$this->sqlite && $throw) {
72            throw new StructException('no sqlite');
73        }
74        return $this->sqlite;
75    }
76
77    /**
78     * Completely remove the database and reinitialize it
79     *
80     * You do not want to call this except for testing!
81     */
82    public function resetDB()
83    {
84        if (!$this->sqlite) return;
85        $file = $this->sqlite->getAdapter()->getDbFile();
86        if (!$file) return;
87        unlink($file);
88        clearstatcache(true, $file);
89        $this->init();
90    }
91}
92
93// vim:ts=4:sw=4:et:
94