xref: /plugin/sqlite/SQLiteDB.php (revision 74c4ec254943736f39f1acd6435b4a9dfb4f5b40)
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
11e49844fbSAndreas Gohruse dokuwiki\ErrorHandler;
12b35b734aSSzymon Olewniczakuse dokuwiki\Extension\Event;
130290deaeSAndreas Gohruse dokuwiki\Logger;
148da7d805SAndreas Gohr
158da7d805SAndreas Gohr/**
168da7d805SAndreas Gohr * Helpers to access a SQLite Database with automatic schema migration
178da7d805SAndreas Gohr */
188da7d805SAndreas Gohrclass SQLiteDB
198da7d805SAndreas Gohr{
208da7d805SAndreas Gohr    const FILE_EXTENSION = '.sqlite3';
218da7d805SAndreas Gohr
228da7d805SAndreas Gohr    /** @var \PDO */
238da7d805SAndreas Gohr    protected $pdo;
248da7d805SAndreas Gohr
258da7d805SAndreas Gohr    /** @var string */
268da7d805SAndreas Gohr    protected $schemadir;
278da7d805SAndreas Gohr
288da7d805SAndreas Gohr    /** @var string */
298da7d805SAndreas Gohr    protected $dbname;
308da7d805SAndreas Gohr
313a56750bSAndreas Gohr    /** @var \helper_plugin_sqlite */
328da7d805SAndreas Gohr    protected $helper;
338da7d805SAndreas Gohr
34fe64ba38SAndreas Gohr
358da7d805SAndreas Gohr    /**
368da7d805SAndreas Gohr     * Constructor
378da7d805SAndreas Gohr     *
388da7d805SAndreas Gohr     * @param string $dbname Database name
398da7d805SAndreas Gohr     * @param string $schemadir directory with schema migration files
408da7d805SAndreas Gohr     * @param \helper_plugin_sqlite $sqlitehelper for backwards compatibility
418da7d805SAndreas Gohr     * @throws \Exception
428da7d805SAndreas Gohr     */
438da7d805SAndreas Gohr    public function __construct($dbname, $schemadir, $sqlitehelper = null)
448da7d805SAndreas Gohr    {
458da7d805SAndreas Gohr        if (!class_exists('pdo') || !in_array('sqlite', \PDO::getAvailableDrivers())) {
468da7d805SAndreas Gohr            throw new \Exception('SQLite PDO driver not available');
478da7d805SAndreas Gohr        }
488da7d805SAndreas Gohr
498da7d805SAndreas Gohr        // backwards compatibility, circular dependency
508da7d805SAndreas Gohr        $this->helper = $sqlitehelper;
513a56750bSAndreas Gohr        if (!$this->helper) {
523a56750bSAndreas Gohr            $this->helper = new \helper_plugin_sqlite();
533a56750bSAndreas Gohr        }
543a56750bSAndreas Gohr        $this->helper->setAdapter($this);
558da7d805SAndreas Gohr
568da7d805SAndreas Gohr        $this->schemadir = $schemadir;
578da7d805SAndreas Gohr        $this->dbname = $dbname;
588da7d805SAndreas Gohr        $file = $this->getDbFile();
598da7d805SAndreas Gohr
608da7d805SAndreas Gohr        $this->pdo = new \PDO(
618da7d805SAndreas Gohr            'sqlite:' . $file,
628da7d805SAndreas Gohr            null,
638da7d805SAndreas Gohr            null,
648da7d805SAndreas Gohr            [
65*74c4ec25SAndreas Gohr                \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
66*74c4ec25SAndreas Gohr                \PDO::ATTR_TIMEOUT => 10, // wait for locks up to 10 seconds
678da7d805SAndreas Gohr            ]
688da7d805SAndreas Gohr        );
698da7d805SAndreas Gohr
70*74c4ec25SAndreas Gohr        try {
71*74c4ec25SAndreas Gohr            // See https://www.sqlite.org/wal.html
72*74c4ec25SAndreas Gohr            $this->exec('PRAGMA journal_mode=WAL');
73*74c4ec25SAndreas Gohr        } catch (\Exception $e) {
74*74c4ec25SAndreas Gohr            // this is not critical, but we log it as error. FIXME might be degraded to debug later
75*74c4ec25SAndreas Gohr            Logger::error('SQLite: Could not set WAL mode.', $e, $e->getFile(), $e->getLine());
76*74c4ec25SAndreas Gohr        }
77*74c4ec25SAndreas Gohr
788da7d805SAndreas Gohr        if ($schemadir !== '') {
798da7d805SAndreas Gohr            // schema dir is empty, when accessing the DB from Admin interface instead of plugin context
808da7d805SAndreas Gohr            $this->applyMigrations();
818da7d805SAndreas Gohr        }
828da7d805SAndreas Gohr        Functions::register($this->pdo);
838da7d805SAndreas Gohr    }
848da7d805SAndreas Gohr
85aae177f9SAndreas Gohr    /**
86aae177f9SAndreas Gohr     * Do not serialize the DB connection
87aae177f9SAndreas Gohr     *
88aae177f9SAndreas Gohr     * @return array
89aae177f9SAndreas Gohr     */
90c9d29defSAndreas Gohr    public function __sleep()
91c9d29defSAndreas Gohr    {
92aae177f9SAndreas Gohr        $this->pdo = null;
93aae177f9SAndreas Gohr        return array_keys(get_object_vars($this));
94aae177f9SAndreas Gohr    }
95aae177f9SAndreas Gohr
96aae177f9SAndreas Gohr    /**
97aae177f9SAndreas Gohr     * On deserialization, reinit database connection
98aae177f9SAndreas Gohr     */
99c9d29defSAndreas Gohr    public function __wakeup()
100c9d29defSAndreas Gohr    {
101aae177f9SAndreas Gohr        $this->__construct($this->dbname, $this->schemadir, $this->helper);
102aae177f9SAndreas Gohr    }
1038da7d805SAndreas Gohr
1048da7d805SAndreas Gohr    // region public API
1058da7d805SAndreas Gohr
1068da7d805SAndreas Gohr    /**
1078da7d805SAndreas Gohr     * Direct access to the PDO object
1088da7d805SAndreas Gohr     * @return \PDO
1098da7d805SAndreas Gohr     */
11033e488b3SAndreas Gohr    public function getPdo()
11133e488b3SAndreas Gohr    {
112e22957e9SSzymon Olewniczak        return $this->pdo;
113801b921eSSzymon Olewniczak    }
114801b921eSSzymon Olewniczak
115801b921eSSzymon Olewniczak    /**
1168da7d805SAndreas Gohr     * Execute a statement and return it
1178da7d805SAndreas Gohr     *
1188da7d805SAndreas Gohr     * @param string $sql
11927eb38daSAndreas Gohr     * @param ...mixed|array $parameters
1208da7d805SAndreas Gohr     * @return \PDOStatement Be sure to close the cursor yourself
1218da7d805SAndreas Gohr     * @throws \PDOException
1228da7d805SAndreas Gohr     */
12327eb38daSAndreas Gohr    public function query($sql, ...$parameters)
1248da7d805SAndreas Gohr    {
1250290deaeSAndreas Gohr        $start = microtime(true);
1260290deaeSAndreas Gohr
12727eb38daSAndreas Gohr        if ($parameters && is_array($parameters[0])) $parameters = $parameters[0];
12827eb38daSAndreas Gohr
12903f14a77SAndreas Gohr        // Statement preparation sometime throws ValueErrors instead of PDOExceptions, we streamline here
13003f14a77SAndreas Gohr        try {
1318da7d805SAndreas Gohr            $stmt = $this->pdo->prepare($sql);
13203f14a77SAndreas Gohr        } catch (\Throwable $e) {
13303f14a77SAndreas Gohr            throw new \PDOException($e->getMessage(), (int)$e->getCode(), $e);
13403f14a77SAndreas Gohr        }
135b35b734aSSzymon Olewniczak        $eventData = [
136b8ae4891SSzymon Olewniczak            'sqlitedb' => $this,
137b35b734aSSzymon Olewniczak            'sql' => &$sql,
138b35b734aSSzymon Olewniczak            'parameters' => &$parameters,
139b35b734aSSzymon Olewniczak            'stmt' => $stmt
140b35b734aSSzymon Olewniczak        ];
141b35b734aSSzymon Olewniczak        $event = new Event('PLUGIN_SQLITE_QUERY_EXECUTE', $eventData);
142b35b734aSSzymon Olewniczak        if ($event->advise_before()) {
1438da7d805SAndreas Gohr            $stmt->execute($parameters);
144b35b734aSSzymon Olewniczak        }
145b35b734aSSzymon Olewniczak        $event->advise_after();
1460290deaeSAndreas Gohr
1470290deaeSAndreas Gohr        $time = microtime(true) - $start;
1480290deaeSAndreas Gohr        if ($time > 0.2) {
1490290deaeSAndreas Gohr            Logger::debug('[sqlite] slow query:  (' . $time . 's)', [
1500290deaeSAndreas Gohr                'sql' => $sql,
1510290deaeSAndreas Gohr                'parameters' => $parameters,
1520290deaeSAndreas Gohr                'backtrace' => explode("\n", dbg_backtrace())
1530290deaeSAndreas Gohr            ]);
1540290deaeSAndreas Gohr        }
1550290deaeSAndreas Gohr
1568da7d805SAndreas Gohr        return $stmt;
1578da7d805SAndreas Gohr    }
1588da7d805SAndreas Gohr
1598da7d805SAndreas Gohr    /**
1608da7d805SAndreas Gohr     * Execute a statement and return metadata
1618da7d805SAndreas Gohr     *
1628da7d805SAndreas Gohr     * Returns the last insert ID on INSERTs or the number of affected rows
1638da7d805SAndreas Gohr     *
1648da7d805SAndreas Gohr     * @param string $sql
16527eb38daSAndreas Gohr     * @param ...mixed|array $parameters
1668da7d805SAndreas Gohr     * @return int
1678da7d805SAndreas Gohr     * @throws \PDOException
1688da7d805SAndreas Gohr     */
16927eb38daSAndreas Gohr    public function exec($sql, ...$parameters)
1708da7d805SAndreas Gohr    {
17127eb38daSAndreas Gohr        $stmt = $this->query($sql, ...$parameters);
1728da7d805SAndreas Gohr
1738da7d805SAndreas Gohr        $count = $stmt->rowCount();
1748da7d805SAndreas Gohr        $stmt->closeCursor();
1758da7d805SAndreas Gohr        if ($count && preg_match('/^INSERT /i', $sql)) {
1768da7d805SAndreas Gohr            return $this->queryValue('SELECT last_insert_rowid()');
1778da7d805SAndreas Gohr        }
1788da7d805SAndreas Gohr
1798da7d805SAndreas Gohr        return $count;
1808da7d805SAndreas Gohr    }
1818da7d805SAndreas Gohr
1828da7d805SAndreas Gohr    /**
1838da7d805SAndreas Gohr     * Simple query abstraction
1848da7d805SAndreas Gohr     *
1858da7d805SAndreas Gohr     * Returns all data
1868da7d805SAndreas Gohr     *
1878da7d805SAndreas Gohr     * @param string $sql
18827eb38daSAndreas Gohr     * @param ...mixed|array $params
1898da7d805SAndreas Gohr     * @return array
1908da7d805SAndreas Gohr     * @throws \PDOException
1918da7d805SAndreas Gohr     */
19227eb38daSAndreas Gohr    public function queryAll($sql, ...$params)
1938da7d805SAndreas Gohr    {
19427eb38daSAndreas Gohr        $stmt = $this->query($sql, ...$params);
1958da7d805SAndreas Gohr        $data = $stmt->fetchAll(\PDO::FETCH_ASSOC);
1968da7d805SAndreas Gohr        $stmt->closeCursor();
1978da7d805SAndreas Gohr        return $data;
1988da7d805SAndreas Gohr    }
1998da7d805SAndreas Gohr
2008da7d805SAndreas Gohr    /**
2018da7d805SAndreas Gohr     * Query one single row
2028da7d805SAndreas Gohr     *
2038da7d805SAndreas Gohr     * @param string $sql
20427eb38daSAndreas Gohr     * @param ...mixed|array $params
2058da7d805SAndreas Gohr     * @return array|null
2068da7d805SAndreas Gohr     * @throws \PDOException
2078da7d805SAndreas Gohr     */
20827eb38daSAndreas Gohr    public function queryRecord($sql, ...$params)
2098da7d805SAndreas Gohr    {
21027eb38daSAndreas Gohr        $stmt = $this->query($sql, ...$params);
211a7a36cdbSAndreas Gohr        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
2128da7d805SAndreas Gohr        $stmt->closeCursor();
213a7a36cdbSAndreas Gohr        if (is_array($row) && count($row)) {
214a7a36cdbSAndreas Gohr            return $row;
215a7a36cdbSAndreas Gohr        }
2168da7d805SAndreas Gohr        return null;
2178da7d805SAndreas Gohr    }
2188da7d805SAndreas Gohr
2198da7d805SAndreas Gohr    /**
2208da7d805SAndreas Gohr     * Insert or replace the given data into the table
2218da7d805SAndreas Gohr     *
2228da7d805SAndreas Gohr     * @param string $table
2238da7d805SAndreas Gohr     * @param array $data
2248da7d805SAndreas Gohr     * @param bool $replace Conflict resolution, replace or ignore
225a7a36cdbSAndreas Gohr     * @return array|null Either the inserted row or null if nothing was inserted
2268da7d805SAndreas Gohr     * @throws \PDOException
2278da7d805SAndreas Gohr     */
2288da7d805SAndreas Gohr    public function saveRecord($table, $data, $replace = true)
2298da7d805SAndreas Gohr    {
2308da7d805SAndreas Gohr        $columns = array_map(function ($column) {
2318da7d805SAndreas Gohr            return '"' . $column . '"';
2328da7d805SAndreas Gohr        }, array_keys($data));
2338da7d805SAndreas Gohr        $values = array_values($data);
2348da7d805SAndreas Gohr        $placeholders = array_pad([], count($columns), '?');
2358da7d805SAndreas Gohr
2368da7d805SAndreas Gohr        if ($replace) {
2378da7d805SAndreas Gohr            $command = 'REPLACE';
2388da7d805SAndreas Gohr        } else {
2398da7d805SAndreas Gohr            $command = 'INSERT OR IGNORE';
2408da7d805SAndreas Gohr        }
2418da7d805SAndreas Gohr
2428da7d805SAndreas Gohr        /** @noinspection SqlResolve */
243a7a36cdbSAndreas Gohr        $sql = $command . ' INTO "' . $table . '" (' . join(',', $columns) . ') VALUES (' . join(',',
244a7a36cdbSAndreas Gohr                $placeholders) . ')';
245b35b734aSSzymon Olewniczak        $stm = $this->query($sql, $values);
246a7a36cdbSAndreas Gohr        $success = $stm->rowCount();
2478da7d805SAndreas Gohr        $stm->closeCursor();
248a7a36cdbSAndreas Gohr
249a7a36cdbSAndreas Gohr        if ($success) {
250a7a36cdbSAndreas Gohr            $sql = 'SELECT * FROM "' . $table . '" WHERE rowid = last_insert_rowid()';
251a7a36cdbSAndreas Gohr            return $this->queryRecord($sql);
252a7a36cdbSAndreas Gohr        }
253a7a36cdbSAndreas Gohr        return null;
2548da7d805SAndreas Gohr    }
2558da7d805SAndreas Gohr
2568da7d805SAndreas Gohr    /**
2578da7d805SAndreas Gohr     * Execute a query that returns a single value
2588da7d805SAndreas Gohr     *
2598da7d805SAndreas Gohr     * @param string $sql
26027eb38daSAndreas Gohr     * @param ...mixed|array $params
2618da7d805SAndreas Gohr     * @return mixed|null
2628da7d805SAndreas Gohr     * @throws \PDOException
2638da7d805SAndreas Gohr     */
26427eb38daSAndreas Gohr    public function queryValue($sql, ...$params)
2658da7d805SAndreas Gohr    {
26627eb38daSAndreas Gohr        $result = $this->queryAll($sql, ...$params);
267c9d29defSAndreas Gohr        if (is_array($result) && count($result)) {
268c9d29defSAndreas Gohr            return array_values($result[0])[0];
269c9d29defSAndreas Gohr        }
2708da7d805SAndreas Gohr        return null;
2718da7d805SAndreas Gohr    }
2728da7d805SAndreas Gohr
27333e488b3SAndreas Gohr    /**
27433e488b3SAndreas Gohr     * Execute a query that returns a list of key-value pairs
27533e488b3SAndreas Gohr     *
27633e488b3SAndreas Gohr     * The first column is used as key, the second as value. Any additional colums are ignored.
27733e488b3SAndreas Gohr     *
27833e488b3SAndreas Gohr     * @param string $sql
27927eb38daSAndreas Gohr     * @param ...mixed|array $params
28033e488b3SAndreas Gohr     * @return array
28133e488b3SAndreas Gohr     */
28227eb38daSAndreas Gohr    public function queryKeyValueList($sql, ...$params)
28333e488b3SAndreas Gohr    {
28427eb38daSAndreas Gohr        $result = $this->queryAll($sql, ...$params);
28533e488b3SAndreas Gohr        if (!$result) return [];
28633e488b3SAndreas Gohr        if (count(array_keys($result[0])) != 2) {
28733e488b3SAndreas Gohr            throw new \RuntimeException('queryKeyValueList expects a query that returns exactly two columns');
28833e488b3SAndreas Gohr        }
28933e488b3SAndreas Gohr        [$key, $val] = array_keys($result[0]);
29033e488b3SAndreas Gohr
29133e488b3SAndreas Gohr        return array_combine(
29233e488b3SAndreas Gohr            array_column($result, $key),
29333e488b3SAndreas Gohr            array_column($result, $val)
29433e488b3SAndreas Gohr        );
29533e488b3SAndreas Gohr    }
29633e488b3SAndreas Gohr
2978da7d805SAndreas Gohr    // endregion
2988da7d805SAndreas Gohr
2998da7d805SAndreas Gohr    // region meta handling
3008da7d805SAndreas Gohr
3018da7d805SAndreas Gohr    /**
3028da7d805SAndreas Gohr     * Get a config value from the opt table
3038da7d805SAndreas Gohr     *
3048da7d805SAndreas Gohr     * @param string $opt Config name
3058da7d805SAndreas Gohr     * @param mixed $default What to return if the value isn't set
3068da7d805SAndreas Gohr     * @return mixed
3078da7d805SAndreas Gohr     * @throws \PDOException
3088da7d805SAndreas Gohr     */
3098da7d805SAndreas Gohr    public function getOpt($opt, $default = null)
3108da7d805SAndreas Gohr    {
3118da7d805SAndreas Gohr        $value = $this->queryValue("SELECT val FROM opts WHERE opt = ?", [$opt]);
312c9d29defSAndreas Gohr        if ($value === null) {
313c9d29defSAndreas Gohr            return $default;
314c9d29defSAndreas Gohr        }
3158da7d805SAndreas Gohr        return $value;
3168da7d805SAndreas Gohr    }
3178da7d805SAndreas Gohr
3188da7d805SAndreas Gohr    /**
3198da7d805SAndreas Gohr     * Set a config value in the opt table
3208da7d805SAndreas Gohr     *
3218da7d805SAndreas Gohr     * @param $opt
3228da7d805SAndreas Gohr     * @param $value
3238da7d805SAndreas Gohr     * @throws \PDOException
3248da7d805SAndreas Gohr     */
3258da7d805SAndreas Gohr    public function setOpt($opt, $value)
3268da7d805SAndreas Gohr    {
3278da7d805SAndreas Gohr        $this->exec('REPLACE INTO opts (opt,val) VALUES (?,?)', [$opt, $value]);
3288da7d805SAndreas Gohr    }
3298da7d805SAndreas Gohr
3308da7d805SAndreas Gohr    /**
3318da7d805SAndreas Gohr     * @return string
3328da7d805SAndreas Gohr     */
3338da7d805SAndreas Gohr    public function getDbName()
3348da7d805SAndreas Gohr    {
3358da7d805SAndreas Gohr        return $this->dbname;
3368da7d805SAndreas Gohr    }
3378da7d805SAndreas Gohr
3388da7d805SAndreas Gohr    /**
3398da7d805SAndreas Gohr     * @return string
3408da7d805SAndreas Gohr     */
3418da7d805SAndreas Gohr    public function getDbFile()
3428da7d805SAndreas Gohr    {
3438da7d805SAndreas Gohr        global $conf;
3448da7d805SAndreas Gohr        return $conf['metadir'] . '/' . $this->dbname . self::FILE_EXTENSION;
3458da7d805SAndreas Gohr    }
3468da7d805SAndreas Gohr
3478da7d805SAndreas Gohr    /**
3488da7d805SAndreas Gohr     * Create a dump of the database and its contents
3498da7d805SAndreas Gohr     *
3508da7d805SAndreas Gohr     * @return string
3518da7d805SAndreas Gohr     * @throws \Exception
3528da7d805SAndreas Gohr     */
3538da7d805SAndreas Gohr    public function dumpToFile($filename)
3548da7d805SAndreas Gohr    {
3558da7d805SAndreas Gohr        $fp = fopen($filename, 'w');
3568da7d805SAndreas Gohr        if (!$fp) {
3578da7d805SAndreas Gohr            throw new \Exception('Could not open file ' . $filename . ' for writing');
3588da7d805SAndreas Gohr        }
3598da7d805SAndreas Gohr
3607ddaad11SAndreas Gohr        $tables = $this->queryAll("SELECT name,sql FROM sqlite_master WHERE type='table'");
3617ddaad11SAndreas Gohr        $indexes = $this->queryAll("SELECT name,sql FROM sqlite_master WHERE type='index'");
3628da7d805SAndreas Gohr
3638da7d805SAndreas Gohr        foreach ($tables as $table) {
3647ddaad11SAndreas Gohr            fwrite($fp, "DROP TABLE IF EXISTS '{$table['name']}';\n");
3657ddaad11SAndreas Gohr        }
3668da7d805SAndreas Gohr
3677ddaad11SAndreas Gohr        foreach ($tables as $table) {
3687ddaad11SAndreas Gohr            fwrite($fp, $table['sql'] . ";\n");
3697ddaad11SAndreas Gohr        }
3707ddaad11SAndreas Gohr
3717ddaad11SAndreas Gohr        foreach ($tables as $table) {
3728da7d805SAndreas Gohr            $sql = "SELECT * FROM " . $table['name'];
3738da7d805SAndreas Gohr            $res = $this->query($sql);
3748da7d805SAndreas Gohr            while ($row = $res->fetch(\PDO::FETCH_ASSOC)) {
3757ddaad11SAndreas Gohr                $values = join(',', array_map(function ($value) {
3767ddaad11SAndreas Gohr                    if ($value === null) return 'NULL';
3777ddaad11SAndreas Gohr                    return $this->pdo->quote($value);
3787ddaad11SAndreas Gohr                }, $row));
3797ddaad11SAndreas Gohr                fwrite($fp, "INSERT INTO '{$table['name']}' VALUES ({$values});\n");
3808da7d805SAndreas Gohr            }
3818da7d805SAndreas Gohr            $res->closeCursor();
3828da7d805SAndreas Gohr        }
3838da7d805SAndreas Gohr
3848da7d805SAndreas Gohr        foreach ($indexes as $index) {
3858da7d805SAndreas Gohr            fwrite($fp, $index['sql'] . ";\n");
3868da7d805SAndreas Gohr        }
3878da7d805SAndreas Gohr        fclose($fp);
3888da7d805SAndreas Gohr        return $filename;
3898da7d805SAndreas Gohr    }
3908da7d805SAndreas Gohr
3918da7d805SAndreas Gohr    // endregion
3928da7d805SAndreas Gohr
3938da7d805SAndreas Gohr    // region migration handling
3948da7d805SAndreas Gohr
3958da7d805SAndreas Gohr    /**
3968da7d805SAndreas Gohr     * Apply all pending migrations
3978da7d805SAndreas Gohr     *
3988da7d805SAndreas Gohr     * Each migration is executed in a transaction which is rolled back on failure
3998da7d805SAndreas Gohr     * Migrations can be files in the schema directory or event handlers
4008da7d805SAndreas Gohr     *
4018da7d805SAndreas Gohr     * @throws \Exception
4028da7d805SAndreas Gohr     */
4038da7d805SAndreas Gohr    protected function applyMigrations()
4048da7d805SAndreas Gohr    {
4058da7d805SAndreas Gohr        $currentVersion = $this->currentDbVersion();
4068da7d805SAndreas Gohr        $latestVersion = $this->latestDbVersion();
4078da7d805SAndreas Gohr
408c70cffc9SAndreas Gohr        if ($currentVersion === $latestVersion) return;
409c70cffc9SAndreas Gohr
4108da7d805SAndreas Gohr        for ($newVersion = $currentVersion + 1; $newVersion <= $latestVersion; $newVersion++) {
4118da7d805SAndreas Gohr            $data = [
4128da7d805SAndreas Gohr                'dbname' => $this->dbname,
4138da7d805SAndreas Gohr                'from' => $currentVersion,
4148da7d805SAndreas Gohr                'to' => $newVersion,
4158da7d805SAndreas Gohr                'file' => $this->getMigrationFile($newVersion),
4168da7d805SAndreas Gohr                'sqlite' => $this->helper,
4178da7d805SAndreas Gohr                'adapter' => $this,
4188da7d805SAndreas Gohr            ];
4198da7d805SAndreas Gohr            $event = new \Doku_Event('PLUGIN_SQLITE_DATABASE_UPGRADE', $data);
4208da7d805SAndreas Gohr
4218da7d805SAndreas Gohr            $this->pdo->beginTransaction();
4228da7d805SAndreas Gohr            try {
4238da7d805SAndreas Gohr                if ($event->advise_before()) {
4248da7d805SAndreas Gohr                    // standard migration file
4257ddaad11SAndreas Gohr                    $sql = Tools::SQLstring2array(file_get_contents($data['file']));
4267ddaad11SAndreas Gohr                    foreach ($sql as $query) {
4277ddaad11SAndreas Gohr                        $this->pdo->exec($query);
4287ddaad11SAndreas Gohr                    }
429c9d29defSAndreas Gohr                } else {
430c9d29defSAndreas Gohr                    if (!$event->result) {
4318da7d805SAndreas Gohr                        // advise before returned false, but the result was false
4328da7d805SAndreas Gohr                        throw new \PDOException('Plugin event did not signal success');
4338da7d805SAndreas Gohr                    }
434c9d29defSAndreas Gohr                }
4358da7d805SAndreas Gohr                $this->setOpt('dbversion', $newVersion);
4368da7d805SAndreas Gohr                $this->pdo->commit();
4378da7d805SAndreas Gohr                $event->advise_after();
4388da7d805SAndreas Gohr            } catch (\Exception $e) {
4398da7d805SAndreas Gohr                // something went wrong, rollback
4408da7d805SAndreas Gohr                $this->pdo->rollBack();
4418da7d805SAndreas Gohr                throw $e;
4428da7d805SAndreas Gohr            }
4438da7d805SAndreas Gohr        }
4448da7d805SAndreas Gohr
4458da7d805SAndreas Gohr        // vacuum the database to free up unused space
4468da7d805SAndreas Gohr        $this->pdo->exec('VACUUM');
4478da7d805SAndreas Gohr    }
4488da7d805SAndreas Gohr
4498da7d805SAndreas Gohr    /**
4508da7d805SAndreas Gohr     * Read the current version from the opt table
4518da7d805SAndreas Gohr     *
4528da7d805SAndreas Gohr     * The opt table is created here if not found
4538da7d805SAndreas Gohr     *
4548da7d805SAndreas Gohr     * @return int
4558da7d805SAndreas Gohr     * @throws \PDOException
4568da7d805SAndreas Gohr     */
4578da7d805SAndreas Gohr    protected function currentDbVersion()
4588da7d805SAndreas Gohr    {
4598da7d805SAndreas Gohr        try {
4608da7d805SAndreas Gohr            $version = $this->getOpt('dbversion', 0);
4618da7d805SAndreas Gohr            return (int)$version;
462e49844fbSAndreas Gohr        } catch (\PDOException $e) {
463e49844fbSAndreas Gohr            // temporary logging for #80
464e49844fbSAndreas Gohr            Logger::error(
465e49844fbSAndreas Gohr                'SQLite: Could not read dbversion from opt table. Should only happen on new plugin install',
466e49844fbSAndreas Gohr                [
467e49844fbSAndreas Gohr                    'dbname' => $this->dbname,
468e49844fbSAndreas Gohr                    'exception' => get_class($e),
469e49844fbSAndreas Gohr                    'message' => $e->getMessage(),
470e49844fbSAndreas Gohr                    'code' => $e->getCode(),
471e49844fbSAndreas Gohr                ],
472e49844fbSAndreas Gohr                __FILE__,
473e49844fbSAndreas Gohr                __LINE__
474e49844fbSAndreas Gohr            );
475e49844fbSAndreas Gohr
4768da7d805SAndreas Gohr            // add the opt table - if this fails too, let the exception bubble up
4778da7d805SAndreas Gohr            $sql = "CREATE TABLE IF NOT EXISTS opts (opt TEXT NOT NULL PRIMARY KEY, val NOT NULL DEFAULT '')";
4788da7d805SAndreas Gohr            $this->exec($sql);
4798da7d805SAndreas Gohr            return 0;
4808da7d805SAndreas Gohr        }
4818da7d805SAndreas Gohr    }
4828da7d805SAndreas Gohr
4838da7d805SAndreas Gohr    /**
4848da7d805SAndreas Gohr     * Get the version this db should have
4858da7d805SAndreas Gohr     *
4868da7d805SAndreas Gohr     * @return int
4878da7d805SAndreas Gohr     * @throws \PDOException
4888da7d805SAndreas Gohr     */
4898da7d805SAndreas Gohr    protected function latestDbVersion()
4908da7d805SAndreas Gohr    {
4918da7d805SAndreas Gohr        if (!file_exists($this->schemadir . '/latest.version')) {
4928da7d805SAndreas Gohr            throw new \PDOException('No latest.version in schema dir');
4938da7d805SAndreas Gohr        }
4948da7d805SAndreas Gohr        return (int)trim(file_get_contents($this->schemadir . '/latest.version'));
4958da7d805SAndreas Gohr    }
4968da7d805SAndreas Gohr
4978da7d805SAndreas Gohr    /**
4988da7d805SAndreas Gohr     * Get the migrartion file for the given version
4998da7d805SAndreas Gohr     *
5008da7d805SAndreas Gohr     * @param int $version
5018da7d805SAndreas Gohr     * @return string
5028da7d805SAndreas Gohr     */
5038da7d805SAndreas Gohr    protected function getMigrationFile($version)
5048da7d805SAndreas Gohr    {
5058da7d805SAndreas Gohr        return sprintf($this->schemadir . '/update%04d.sql', $version);
5068da7d805SAndreas Gohr    }
5078da7d805SAndreas Gohr    // endregion
5088da7d805SAndreas Gohr}
509