xref: /plugin/sqlite/SQLiteDB.php (revision 549d6b89b978a64afd5c9843bf382a945e384b56)
18da7d805SAndreas Gohr<?php
28da7d805SAndreas Gohr
38da7d805SAndreas Gohr/**
48da7d805SAndreas Gohr * @noinspection SqlNoDataSourceInspection
58da7d805SAndreas Gohr * @noinspection SqlDialectInspection
68da7d805SAndreas Gohr * @noinspection PhpComposerExtensionStubsInspection
78da7d805SAndreas Gohr */
88da7d805SAndreas Gohr
98da7d805SAndreas Gohrnamespace dokuwiki\plugin\sqlite;
108da7d805SAndreas Gohr
11b35b734aSSzymon Olewniczakuse dokuwiki\Extension\Event;
120290deaeSAndreas Gohruse dokuwiki\Logger;
138da7d805SAndreas Gohr
148da7d805SAndreas Gohr/**
158da7d805SAndreas Gohr * Helpers to access a SQLite Database with automatic schema migration
168da7d805SAndreas Gohr */
178da7d805SAndreas Gohrclass SQLiteDB
188da7d805SAndreas Gohr{
198da7d805SAndreas Gohr    const FILE_EXTENSION = '.sqlite3';
208da7d805SAndreas Gohr
218da7d805SAndreas Gohr    /** @var \PDO */
228da7d805SAndreas Gohr    protected $pdo;
238da7d805SAndreas Gohr
248da7d805SAndreas Gohr    /** @var string */
258da7d805SAndreas Gohr    protected $schemadir;
268da7d805SAndreas Gohr
278da7d805SAndreas Gohr    /** @var string */
288da7d805SAndreas Gohr    protected $dbname;
298da7d805SAndreas Gohr
303a56750bSAndreas Gohr    /** @var \helper_plugin_sqlite */
318da7d805SAndreas Gohr    protected $helper;
328da7d805SAndreas Gohr
33fe64ba38SAndreas Gohr
348da7d805SAndreas Gohr    /**
358da7d805SAndreas Gohr     * Constructor
368da7d805SAndreas Gohr     *
378da7d805SAndreas Gohr     * @param string $dbname Database name
388da7d805SAndreas Gohr     * @param string $schemadir directory with schema migration files
398da7d805SAndreas Gohr     * @param \helper_plugin_sqlite $sqlitehelper for backwards compatibility
408da7d805SAndreas Gohr     * @throws \Exception
418da7d805SAndreas Gohr     */
428da7d805SAndreas Gohr    public function __construct($dbname, $schemadir, $sqlitehelper = null)
438da7d805SAndreas Gohr    {
448da7d805SAndreas Gohr        if (!class_exists('pdo') || !in_array('sqlite', \PDO::getAvailableDrivers())) {
458da7d805SAndreas Gohr            throw new \Exception('SQLite PDO driver not available');
468da7d805SAndreas Gohr        }
478da7d805SAndreas Gohr
488da7d805SAndreas Gohr        // backwards compatibility, circular dependency
498da7d805SAndreas Gohr        $this->helper = $sqlitehelper;
503a56750bSAndreas Gohr        if (!$this->helper) {
513a56750bSAndreas Gohr            $this->helper = new \helper_plugin_sqlite();
523a56750bSAndreas Gohr        }
533a56750bSAndreas Gohr        $this->helper->setAdapter($this);
548da7d805SAndreas Gohr
558da7d805SAndreas Gohr        $this->schemadir = $schemadir;
568da7d805SAndreas Gohr        $this->dbname = $dbname;
578da7d805SAndreas Gohr        $file = $this->getDbFile();
588da7d805SAndreas Gohr
598da7d805SAndreas Gohr        $this->pdo = new \PDO(
608da7d805SAndreas Gohr            'sqlite:' . $file,
618da7d805SAndreas Gohr            null,
628da7d805SAndreas Gohr            null,
638da7d805SAndreas Gohr            [
6474c4ec25SAndreas Gohr                \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
6574c4ec25SAndreas Gohr                \PDO::ATTR_TIMEOUT => 10, // wait for locks up to 10 seconds
668da7d805SAndreas Gohr            ]
678da7d805SAndreas Gohr        );
688da7d805SAndreas Gohr
6974c4ec25SAndreas Gohr        try {
7074c4ec25SAndreas Gohr            // See https://www.sqlite.org/wal.html
7174c4ec25SAndreas Gohr            $this->exec('PRAGMA journal_mode=WAL');
7274c4ec25SAndreas Gohr        } catch (\Exception $e) {
7374c4ec25SAndreas Gohr            // this is not critical, but we log it as error. FIXME might be degraded to debug later
7474c4ec25SAndreas Gohr            Logger::error('SQLite: Could not set WAL mode.', $e, $e->getFile(), $e->getLine());
7574c4ec25SAndreas Gohr        }
7674c4ec25SAndreas Gohr
778da7d805SAndreas Gohr        if ($schemadir !== '') {
788da7d805SAndreas Gohr            // schema dir is empty, when accessing the DB from Admin interface instead of plugin context
798da7d805SAndreas Gohr            $this->applyMigrations();
808da7d805SAndreas Gohr        }
818da7d805SAndreas Gohr        Functions::register($this->pdo);
828da7d805SAndreas Gohr    }
838da7d805SAndreas Gohr
84aae177f9SAndreas Gohr    /**
85*549d6b89SAnna Dabrowska     * Try optimizing the database before closing the connection.
86*549d6b89SAnna Dabrowska     *
87*549d6b89SAnna Dabrowska     * @see https://www.sqlite.org/pragma.html#pragma_optimize
88*549d6b89SAnna Dabrowska     */
89*549d6b89SAnna Dabrowska    public function __destruct()
90*549d6b89SAnna Dabrowska    {
91*549d6b89SAnna Dabrowska        try {
92*549d6b89SAnna Dabrowska            $this->exec("PRAGMA analysis_limit=400");
93*549d6b89SAnna Dabrowska            $this->exec('PRAGMA optimize;');
94*549d6b89SAnna Dabrowska        } catch (\Exception $e) {
95*549d6b89SAnna Dabrowska            // ignore failures, this is not essential and not available until 3.18.0.
96*549d6b89SAnna Dabrowska        }
97*549d6b89SAnna Dabrowska    }
98*549d6b89SAnna Dabrowska
99*549d6b89SAnna Dabrowska    /**
100aae177f9SAndreas Gohr     * Do not serialize the DB connection
101aae177f9SAndreas Gohr     *
102aae177f9SAndreas Gohr     * @return array
103aae177f9SAndreas Gohr     */
104c9d29defSAndreas Gohr    public function __sleep()
105c9d29defSAndreas Gohr    {
106aae177f9SAndreas Gohr        $this->pdo = null;
107aae177f9SAndreas Gohr        return array_keys(get_object_vars($this));
108aae177f9SAndreas Gohr    }
109aae177f9SAndreas Gohr
110aae177f9SAndreas Gohr    /**
111aae177f9SAndreas Gohr     * On deserialization, reinit database connection
112aae177f9SAndreas Gohr     */
113c9d29defSAndreas Gohr    public function __wakeup()
114c9d29defSAndreas Gohr    {
115aae177f9SAndreas Gohr        $this->__construct($this->dbname, $this->schemadir, $this->helper);
116aae177f9SAndreas Gohr    }
1178da7d805SAndreas Gohr
1188da7d805SAndreas Gohr    // region public API
1198da7d805SAndreas Gohr
1208da7d805SAndreas Gohr    /**
1218da7d805SAndreas Gohr     * Direct access to the PDO object
1228da7d805SAndreas Gohr     * @return \PDO
1238da7d805SAndreas Gohr     */
12433e488b3SAndreas Gohr    public function getPdo()
12533e488b3SAndreas Gohr    {
126e22957e9SSzymon Olewniczak        return $this->pdo;
127801b921eSSzymon Olewniczak    }
128801b921eSSzymon Olewniczak
129801b921eSSzymon Olewniczak    /**
1308da7d805SAndreas Gohr     * Execute a statement and return it
1318da7d805SAndreas Gohr     *
1328da7d805SAndreas Gohr     * @param string $sql
13327eb38daSAndreas Gohr     * @param ...mixed|array $parameters
1348da7d805SAndreas Gohr     * @return \PDOStatement Be sure to close the cursor yourself
1358da7d805SAndreas Gohr     * @throws \PDOException
1368da7d805SAndreas Gohr     */
13727eb38daSAndreas Gohr    public function query($sql, ...$parameters)
1388da7d805SAndreas Gohr    {
1390290deaeSAndreas Gohr        $start = microtime(true);
1400290deaeSAndreas Gohr
14127eb38daSAndreas Gohr        if ($parameters && is_array($parameters[0])) $parameters = $parameters[0];
14227eb38daSAndreas Gohr
14303f14a77SAndreas Gohr        // Statement preparation sometime throws ValueErrors instead of PDOExceptions, we streamline here
14403f14a77SAndreas Gohr        try {
1458da7d805SAndreas Gohr            $stmt = $this->pdo->prepare($sql);
14603f14a77SAndreas Gohr        } catch (\Throwable $e) {
14703f14a77SAndreas Gohr            throw new \PDOException($e->getMessage(), (int)$e->getCode(), $e);
14803f14a77SAndreas Gohr        }
149b35b734aSSzymon Olewniczak        $eventData = [
150b8ae4891SSzymon Olewniczak            'sqlitedb' => $this,
151b35b734aSSzymon Olewniczak            'sql' => &$sql,
152b35b734aSSzymon Olewniczak            'parameters' => &$parameters,
153b35b734aSSzymon Olewniczak            'stmt' => $stmt
154b35b734aSSzymon Olewniczak        ];
155b35b734aSSzymon Olewniczak        $event = new Event('PLUGIN_SQLITE_QUERY_EXECUTE', $eventData);
156b35b734aSSzymon Olewniczak        if ($event->advise_before()) {
1578da7d805SAndreas Gohr            $stmt->execute($parameters);
158b35b734aSSzymon Olewniczak        }
159b35b734aSSzymon Olewniczak        $event->advise_after();
1600290deaeSAndreas Gohr
1610290deaeSAndreas Gohr        $time = microtime(true) - $start;
1620290deaeSAndreas Gohr        if ($time > 0.2) {
1630290deaeSAndreas Gohr            Logger::debug('[sqlite] slow query:  (' . $time . 's)', [
1640290deaeSAndreas Gohr                'sql' => $sql,
1650290deaeSAndreas Gohr                'parameters' => $parameters,
1660290deaeSAndreas Gohr                'backtrace' => explode("\n", dbg_backtrace())
1670290deaeSAndreas Gohr            ]);
1680290deaeSAndreas Gohr        }
1690290deaeSAndreas Gohr
1708da7d805SAndreas Gohr        return $stmt;
1718da7d805SAndreas Gohr    }
1728da7d805SAndreas Gohr
1738da7d805SAndreas Gohr    /**
1748da7d805SAndreas Gohr     * Execute a statement and return metadata
1758da7d805SAndreas Gohr     *
1768da7d805SAndreas Gohr     * Returns the last insert ID on INSERTs or the number of affected rows
1778da7d805SAndreas Gohr     *
1788da7d805SAndreas Gohr     * @param string $sql
17927eb38daSAndreas Gohr     * @param ...mixed|array $parameters
1808da7d805SAndreas Gohr     * @return int
1818da7d805SAndreas Gohr     * @throws \PDOException
1828da7d805SAndreas Gohr     */
18327eb38daSAndreas Gohr    public function exec($sql, ...$parameters)
1848da7d805SAndreas Gohr    {
18527eb38daSAndreas Gohr        $stmt = $this->query($sql, ...$parameters);
1868da7d805SAndreas Gohr
1878da7d805SAndreas Gohr        $count = $stmt->rowCount();
1888da7d805SAndreas Gohr        $stmt->closeCursor();
1898da7d805SAndreas Gohr        if ($count && preg_match('/^INSERT /i', $sql)) {
1908da7d805SAndreas Gohr            return $this->queryValue('SELECT last_insert_rowid()');
1918da7d805SAndreas Gohr        }
1928da7d805SAndreas Gohr
1938da7d805SAndreas Gohr        return $count;
1948da7d805SAndreas Gohr    }
1958da7d805SAndreas Gohr
1968da7d805SAndreas Gohr    /**
1978da7d805SAndreas Gohr     * Simple query abstraction
1988da7d805SAndreas Gohr     *
1998da7d805SAndreas Gohr     * Returns all data
2008da7d805SAndreas Gohr     *
2018da7d805SAndreas Gohr     * @param string $sql
20227eb38daSAndreas Gohr     * @param ...mixed|array $params
2038da7d805SAndreas Gohr     * @return array
2048da7d805SAndreas Gohr     * @throws \PDOException
2058da7d805SAndreas Gohr     */
20627eb38daSAndreas Gohr    public function queryAll($sql, ...$params)
2078da7d805SAndreas Gohr    {
20827eb38daSAndreas Gohr        $stmt = $this->query($sql, ...$params);
2098da7d805SAndreas Gohr        $data = $stmt->fetchAll(\PDO::FETCH_ASSOC);
2108da7d805SAndreas Gohr        $stmt->closeCursor();
2118da7d805SAndreas Gohr        return $data;
2128da7d805SAndreas Gohr    }
2138da7d805SAndreas Gohr
2148da7d805SAndreas Gohr    /**
2158da7d805SAndreas Gohr     * Query one single row
2168da7d805SAndreas Gohr     *
2178da7d805SAndreas Gohr     * @param string $sql
21827eb38daSAndreas Gohr     * @param ...mixed|array $params
2198da7d805SAndreas Gohr     * @return array|null
2208da7d805SAndreas Gohr     * @throws \PDOException
2218da7d805SAndreas Gohr     */
22227eb38daSAndreas Gohr    public function queryRecord($sql, ...$params)
2238da7d805SAndreas Gohr    {
22427eb38daSAndreas Gohr        $stmt = $this->query($sql, ...$params);
225a7a36cdbSAndreas Gohr        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
2268da7d805SAndreas Gohr        $stmt->closeCursor();
227a7a36cdbSAndreas Gohr        if (is_array($row) && count($row)) {
228a7a36cdbSAndreas Gohr            return $row;
229a7a36cdbSAndreas Gohr        }
2308da7d805SAndreas Gohr        return null;
2318da7d805SAndreas Gohr    }
2328da7d805SAndreas Gohr
2338da7d805SAndreas Gohr    /**
2348da7d805SAndreas Gohr     * Insert or replace the given data into the table
2358da7d805SAndreas Gohr     *
2368da7d805SAndreas Gohr     * @param string $table
2378da7d805SAndreas Gohr     * @param array $data
2388da7d805SAndreas Gohr     * @param bool $replace Conflict resolution, replace or ignore
239a7a36cdbSAndreas Gohr     * @return array|null Either the inserted row or null if nothing was inserted
2408da7d805SAndreas Gohr     * @throws \PDOException
2418da7d805SAndreas Gohr     */
2428da7d805SAndreas Gohr    public function saveRecord($table, $data, $replace = true)
2438da7d805SAndreas Gohr    {
2448da7d805SAndreas Gohr        $columns = array_map(function ($column) {
2458da7d805SAndreas Gohr            return '"' . $column . '"';
2468da7d805SAndreas Gohr        }, array_keys($data));
2478da7d805SAndreas Gohr        $values = array_values($data);
2488da7d805SAndreas Gohr        $placeholders = array_pad([], count($columns), '?');
2498da7d805SAndreas Gohr
2508da7d805SAndreas Gohr        if ($replace) {
2518da7d805SAndreas Gohr            $command = 'REPLACE';
2528da7d805SAndreas Gohr        } else {
2538da7d805SAndreas Gohr            $command = 'INSERT OR IGNORE';
2548da7d805SAndreas Gohr        }
2558da7d805SAndreas Gohr
2568da7d805SAndreas Gohr        /** @noinspection SqlResolve */
257a7a36cdbSAndreas Gohr        $sql = $command . ' INTO "' . $table . '" (' . join(',', $columns) . ') VALUES (' . join(',',
258a7a36cdbSAndreas Gohr                $placeholders) . ')';
259b35b734aSSzymon Olewniczak        $stm = $this->query($sql, $values);
260a7a36cdbSAndreas Gohr        $success = $stm->rowCount();
2618da7d805SAndreas Gohr        $stm->closeCursor();
262a7a36cdbSAndreas Gohr
263a7a36cdbSAndreas Gohr        if ($success) {
264a7a36cdbSAndreas Gohr            $sql = 'SELECT * FROM "' . $table . '" WHERE rowid = last_insert_rowid()';
265a7a36cdbSAndreas Gohr            return $this->queryRecord($sql);
266a7a36cdbSAndreas Gohr        }
267a7a36cdbSAndreas Gohr        return null;
2688da7d805SAndreas Gohr    }
2698da7d805SAndreas Gohr
2708da7d805SAndreas Gohr    /**
2718da7d805SAndreas Gohr     * Execute a query that returns a single value
2728da7d805SAndreas Gohr     *
2738da7d805SAndreas Gohr     * @param string $sql
27427eb38daSAndreas Gohr     * @param ...mixed|array $params
2758da7d805SAndreas Gohr     * @return mixed|null
2768da7d805SAndreas Gohr     * @throws \PDOException
2778da7d805SAndreas Gohr     */
27827eb38daSAndreas Gohr    public function queryValue($sql, ...$params)
2798da7d805SAndreas Gohr    {
28027eb38daSAndreas Gohr        $result = $this->queryAll($sql, ...$params);
281c9d29defSAndreas Gohr        if (is_array($result) && count($result)) {
282c9d29defSAndreas Gohr            return array_values($result[0])[0];
283c9d29defSAndreas Gohr        }
2848da7d805SAndreas Gohr        return null;
2858da7d805SAndreas Gohr    }
2868da7d805SAndreas Gohr
28733e488b3SAndreas Gohr    /**
28833e488b3SAndreas Gohr     * Execute a query that returns a list of key-value pairs
28933e488b3SAndreas Gohr     *
29033e488b3SAndreas Gohr     * The first column is used as key, the second as value. Any additional colums are ignored.
29133e488b3SAndreas Gohr     *
29233e488b3SAndreas Gohr     * @param string $sql
29327eb38daSAndreas Gohr     * @param ...mixed|array $params
29433e488b3SAndreas Gohr     * @return array
29533e488b3SAndreas Gohr     */
29627eb38daSAndreas Gohr    public function queryKeyValueList($sql, ...$params)
29733e488b3SAndreas Gohr    {
29827eb38daSAndreas Gohr        $result = $this->queryAll($sql, ...$params);
29933e488b3SAndreas Gohr        if (!$result) return [];
30033e488b3SAndreas Gohr        if (count(array_keys($result[0])) != 2) {
30133e488b3SAndreas Gohr            throw new \RuntimeException('queryKeyValueList expects a query that returns exactly two columns');
30233e488b3SAndreas Gohr        }
30333e488b3SAndreas Gohr        [$key, $val] = array_keys($result[0]);
30433e488b3SAndreas Gohr
30533e488b3SAndreas Gohr        return array_combine(
30633e488b3SAndreas Gohr            array_column($result, $key),
30733e488b3SAndreas Gohr            array_column($result, $val)
30833e488b3SAndreas Gohr        );
30933e488b3SAndreas Gohr    }
31033e488b3SAndreas Gohr
3118da7d805SAndreas Gohr    // endregion
3128da7d805SAndreas Gohr
3138da7d805SAndreas Gohr    // region meta handling
3148da7d805SAndreas Gohr
3158da7d805SAndreas Gohr    /**
3168da7d805SAndreas Gohr     * Get a config value from the opt table
3178da7d805SAndreas Gohr     *
3188da7d805SAndreas Gohr     * @param string $opt Config name
3198da7d805SAndreas Gohr     * @param mixed $default What to return if the value isn't set
3208da7d805SAndreas Gohr     * @return mixed
3218da7d805SAndreas Gohr     * @throws \PDOException
3228da7d805SAndreas Gohr     */
3238da7d805SAndreas Gohr    public function getOpt($opt, $default = null)
3248da7d805SAndreas Gohr    {
3258da7d805SAndreas Gohr        $value = $this->queryValue("SELECT val FROM opts WHERE opt = ?", [$opt]);
326c9d29defSAndreas Gohr        if ($value === null) {
327c9d29defSAndreas Gohr            return $default;
328c9d29defSAndreas Gohr        }
3298da7d805SAndreas Gohr        return $value;
3308da7d805SAndreas Gohr    }
3318da7d805SAndreas Gohr
3328da7d805SAndreas Gohr    /**
3338da7d805SAndreas Gohr     * Set a config value in the opt table
3348da7d805SAndreas Gohr     *
3358da7d805SAndreas Gohr     * @param $opt
3368da7d805SAndreas Gohr     * @param $value
3378da7d805SAndreas Gohr     * @throws \PDOException
3388da7d805SAndreas Gohr     */
3398da7d805SAndreas Gohr    public function setOpt($opt, $value)
3408da7d805SAndreas Gohr    {
3418da7d805SAndreas Gohr        $this->exec('REPLACE INTO opts (opt,val) VALUES (?,?)', [$opt, $value]);
3428da7d805SAndreas Gohr    }
3438da7d805SAndreas Gohr
3448da7d805SAndreas Gohr    /**
3458da7d805SAndreas Gohr     * @return string
3468da7d805SAndreas Gohr     */
3478da7d805SAndreas Gohr    public function getDbName()
3488da7d805SAndreas Gohr    {
3498da7d805SAndreas Gohr        return $this->dbname;
3508da7d805SAndreas Gohr    }
3518da7d805SAndreas Gohr
3528da7d805SAndreas Gohr    /**
3538da7d805SAndreas Gohr     * @return string
3548da7d805SAndreas Gohr     */
3558da7d805SAndreas Gohr    public function getDbFile()
3568da7d805SAndreas Gohr    {
3578da7d805SAndreas Gohr        global $conf;
3588da7d805SAndreas Gohr        return $conf['metadir'] . '/' . $this->dbname . self::FILE_EXTENSION;
3598da7d805SAndreas Gohr    }
3608da7d805SAndreas Gohr
3618da7d805SAndreas Gohr    /**
3628da7d805SAndreas Gohr     * Create a dump of the database and its contents
3638da7d805SAndreas Gohr     *
3648da7d805SAndreas Gohr     * @return string
3658da7d805SAndreas Gohr     * @throws \Exception
3668da7d805SAndreas Gohr     */
3678da7d805SAndreas Gohr    public function dumpToFile($filename)
3688da7d805SAndreas Gohr    {
3698da7d805SAndreas Gohr        $fp = fopen($filename, 'w');
3708da7d805SAndreas Gohr        if (!$fp) {
3718da7d805SAndreas Gohr            throw new \Exception('Could not open file ' . $filename . ' for writing');
3728da7d805SAndreas Gohr        }
3738da7d805SAndreas Gohr
3747ddaad11SAndreas Gohr        $tables = $this->queryAll("SELECT name,sql FROM sqlite_master WHERE type='table'");
3757ddaad11SAndreas Gohr        $indexes = $this->queryAll("SELECT name,sql FROM sqlite_master WHERE type='index'");
3768da7d805SAndreas Gohr
3778da7d805SAndreas Gohr        foreach ($tables as $table) {
3787ddaad11SAndreas Gohr            fwrite($fp, "DROP TABLE IF EXISTS '{$table['name']}';\n");
3797ddaad11SAndreas Gohr        }
3808da7d805SAndreas Gohr
3817ddaad11SAndreas Gohr        foreach ($tables as $table) {
3827ddaad11SAndreas Gohr            fwrite($fp, $table['sql'] . ";\n");
3837ddaad11SAndreas Gohr        }
3847ddaad11SAndreas Gohr
3857ddaad11SAndreas Gohr        foreach ($tables as $table) {
3868da7d805SAndreas Gohr            $sql = "SELECT * FROM " . $table['name'];
3878da7d805SAndreas Gohr            $res = $this->query($sql);
3888da7d805SAndreas Gohr            while ($row = $res->fetch(\PDO::FETCH_ASSOC)) {
3897ddaad11SAndreas Gohr                $values = join(',', array_map(function ($value) {
3907ddaad11SAndreas Gohr                    if ($value === null) return 'NULL';
3917ddaad11SAndreas Gohr                    return $this->pdo->quote($value);
3927ddaad11SAndreas Gohr                }, $row));
3937ddaad11SAndreas Gohr                fwrite($fp, "INSERT INTO '{$table['name']}' VALUES ({$values});\n");
3948da7d805SAndreas Gohr            }
3958da7d805SAndreas Gohr            $res->closeCursor();
3968da7d805SAndreas Gohr        }
3978da7d805SAndreas Gohr
3988da7d805SAndreas Gohr        foreach ($indexes as $index) {
3998da7d805SAndreas Gohr            fwrite($fp, $index['sql'] . ";\n");
4008da7d805SAndreas Gohr        }
4018da7d805SAndreas Gohr        fclose($fp);
4028da7d805SAndreas Gohr        return $filename;
4038da7d805SAndreas Gohr    }
4048da7d805SAndreas Gohr
4058da7d805SAndreas Gohr    // endregion
4068da7d805SAndreas Gohr
4078da7d805SAndreas Gohr    // region migration handling
4088da7d805SAndreas Gohr
4098da7d805SAndreas Gohr    /**
4108da7d805SAndreas Gohr     * Apply all pending migrations
4118da7d805SAndreas Gohr     *
4128da7d805SAndreas Gohr     * Each migration is executed in a transaction which is rolled back on failure
4138da7d805SAndreas Gohr     * Migrations can be files in the schema directory or event handlers
4148da7d805SAndreas Gohr     *
4158da7d805SAndreas Gohr     * @throws \Exception
4168da7d805SAndreas Gohr     */
4178da7d805SAndreas Gohr    protected function applyMigrations()
4188da7d805SAndreas Gohr    {
4198da7d805SAndreas Gohr        $currentVersion = $this->currentDbVersion();
4208da7d805SAndreas Gohr        $latestVersion = $this->latestDbVersion();
4218da7d805SAndreas Gohr
422c70cffc9SAndreas Gohr        if ($currentVersion === $latestVersion) return;
423c70cffc9SAndreas Gohr
4248da7d805SAndreas Gohr        for ($newVersion = $currentVersion + 1; $newVersion <= $latestVersion; $newVersion++) {
4258da7d805SAndreas Gohr            $data = [
4268da7d805SAndreas Gohr                'dbname' => $this->dbname,
4278da7d805SAndreas Gohr                'from' => $currentVersion,
4288da7d805SAndreas Gohr                'to' => $newVersion,
4298da7d805SAndreas Gohr                'file' => $this->getMigrationFile($newVersion),
4308da7d805SAndreas Gohr                'sqlite' => $this->helper,
4318da7d805SAndreas Gohr                'adapter' => $this,
4328da7d805SAndreas Gohr            ];
4338da7d805SAndreas Gohr            $event = new \Doku_Event('PLUGIN_SQLITE_DATABASE_UPGRADE', $data);
4348da7d805SAndreas Gohr
4358da7d805SAndreas Gohr            $this->pdo->beginTransaction();
4368da7d805SAndreas Gohr            try {
4378da7d805SAndreas Gohr                if ($event->advise_before()) {
4388da7d805SAndreas Gohr                    // standard migration file
4397ddaad11SAndreas Gohr                    $sql = Tools::SQLstring2array(file_get_contents($data['file']));
4407ddaad11SAndreas Gohr                    foreach ($sql as $query) {
4417ddaad11SAndreas Gohr                        $this->pdo->exec($query);
4427ddaad11SAndreas Gohr                    }
443c9d29defSAndreas Gohr                } else {
444c9d29defSAndreas Gohr                    if (!$event->result) {
4458da7d805SAndreas Gohr                        // advise before returned false, but the result was false
4468da7d805SAndreas Gohr                        throw new \PDOException('Plugin event did not signal success');
4478da7d805SAndreas Gohr                    }
448c9d29defSAndreas Gohr                }
4498da7d805SAndreas Gohr                $this->setOpt('dbversion', $newVersion);
4508da7d805SAndreas Gohr                $this->pdo->commit();
4518da7d805SAndreas Gohr                $event->advise_after();
4528da7d805SAndreas Gohr            } catch (\Exception $e) {
4538da7d805SAndreas Gohr                // something went wrong, rollback
4548da7d805SAndreas Gohr                $this->pdo->rollBack();
4558da7d805SAndreas Gohr                throw $e;
4568da7d805SAndreas Gohr            }
4578da7d805SAndreas Gohr        }
4588da7d805SAndreas Gohr
4598da7d805SAndreas Gohr        // vacuum the database to free up unused space
4608da7d805SAndreas Gohr        $this->pdo->exec('VACUUM');
4618da7d805SAndreas Gohr    }
4628da7d805SAndreas Gohr
4638da7d805SAndreas Gohr    /**
4648da7d805SAndreas Gohr     * Read the current version from the opt table
4658da7d805SAndreas Gohr     *
4668da7d805SAndreas Gohr     * The opt table is created here if not found
4678da7d805SAndreas Gohr     *
4688da7d805SAndreas Gohr     * @return int
4698da7d805SAndreas Gohr     * @throws \PDOException
4708da7d805SAndreas Gohr     */
4718da7d805SAndreas Gohr    protected function currentDbVersion()
4728da7d805SAndreas Gohr    {
4738da7d805SAndreas Gohr        try {
4748da7d805SAndreas Gohr            $version = $this->getOpt('dbversion', 0);
4758da7d805SAndreas Gohr            return (int)$version;
476e49844fbSAndreas Gohr        } catch (\PDOException $e) {
477f71fd150SAndreas Gohr            if (!preg_match('/no such table/', $e->getMessage())) {
478f71fd150SAndreas Gohr                // if this is not a "no such table" error, there is something wrong see #80
479e49844fbSAndreas Gohr                Logger::error(
480f71fd150SAndreas Gohr                    'SQLite: Could not read dbversion from opt table due to unexpected error',
481e49844fbSAndreas Gohr                    [
482e49844fbSAndreas Gohr                        'dbname' => $this->dbname,
483e49844fbSAndreas Gohr                        'exception' => get_class($e),
484e49844fbSAndreas Gohr                        'message' => $e->getMessage(),
485e49844fbSAndreas Gohr                        'code' => $e->getCode(),
486e49844fbSAndreas Gohr                    ],
487e49844fbSAndreas Gohr                    __FILE__,
488e49844fbSAndreas Gohr                    __LINE__
489e49844fbSAndreas Gohr                );
490f71fd150SAndreas Gohr            }
491e49844fbSAndreas Gohr
4928da7d805SAndreas Gohr            // add the opt table - if this fails too, let the exception bubble up
4938da7d805SAndreas Gohr            $sql = "CREATE TABLE IF NOT EXISTS opts (opt TEXT NOT NULL PRIMARY KEY, val NOT NULL DEFAULT '')";
4948da7d805SAndreas Gohr            $this->exec($sql);
4958da7d805SAndreas Gohr            return 0;
4968da7d805SAndreas Gohr        }
4978da7d805SAndreas Gohr    }
4988da7d805SAndreas Gohr
4998da7d805SAndreas Gohr    /**
5008da7d805SAndreas Gohr     * Get the version this db should have
5018da7d805SAndreas Gohr     *
5028da7d805SAndreas Gohr     * @return int
5038da7d805SAndreas Gohr     * @throws \PDOException
5048da7d805SAndreas Gohr     */
5058da7d805SAndreas Gohr    protected function latestDbVersion()
5068da7d805SAndreas Gohr    {
5078da7d805SAndreas Gohr        if (!file_exists($this->schemadir . '/latest.version')) {
5088da7d805SAndreas Gohr            throw new \PDOException('No latest.version in schema dir');
5098da7d805SAndreas Gohr        }
5108da7d805SAndreas Gohr        return (int)trim(file_get_contents($this->schemadir . '/latest.version'));
5118da7d805SAndreas Gohr    }
5128da7d805SAndreas Gohr
5138da7d805SAndreas Gohr    /**
5148da7d805SAndreas Gohr     * Get the migrartion file for the given version
5158da7d805SAndreas Gohr     *
5168da7d805SAndreas Gohr     * @param int $version
5178da7d805SAndreas Gohr     * @return string
5188da7d805SAndreas Gohr     */
5198da7d805SAndreas Gohr    protected function getMigrationFile($version)
5208da7d805SAndreas Gohr    {
5218da7d805SAndreas Gohr        return sprintf($this->schemadir . '/update%04d.sql', $version);
5228da7d805SAndreas Gohr    }
5238da7d805SAndreas Gohr    // endregion
5248da7d805SAndreas Gohr}
525