xref: /plugin/sqlite/SQLiteDB.php (revision 27eb38dad6ac16ba55cb051804719e1c950a9e0a)
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
338da7d805SAndreas Gohr    /**
348da7d805SAndreas Gohr     * Constructor
358da7d805SAndreas Gohr     *
368da7d805SAndreas Gohr     * @param string $dbname Database name
378da7d805SAndreas Gohr     * @param string $schemadir directory with schema migration files
388da7d805SAndreas Gohr     * @param \helper_plugin_sqlite $sqlitehelper for backwards compatibility
398da7d805SAndreas Gohr     * @throws \Exception
408da7d805SAndreas Gohr     */
418da7d805SAndreas Gohr    public function __construct($dbname, $schemadir, $sqlitehelper = null)
428da7d805SAndreas Gohr    {
438da7d805SAndreas Gohr        if (!class_exists('pdo') || !in_array('sqlite', \PDO::getAvailableDrivers())) {
448da7d805SAndreas Gohr            throw new \Exception('SQLite PDO driver not available');
458da7d805SAndreas Gohr        }
468da7d805SAndreas Gohr
478da7d805SAndreas Gohr        // backwards compatibility, circular dependency
488da7d805SAndreas Gohr        $this->helper = $sqlitehelper;
493a56750bSAndreas Gohr        if (!$this->helper) {
503a56750bSAndreas Gohr            $this->helper = new \helper_plugin_sqlite();
513a56750bSAndreas Gohr        }
523a56750bSAndreas Gohr        $this->helper->setAdapter($this);
538da7d805SAndreas Gohr
548da7d805SAndreas Gohr        $this->schemadir = $schemadir;
558da7d805SAndreas Gohr        $this->dbname = $dbname;
568da7d805SAndreas Gohr        $file = $this->getDbFile();
578da7d805SAndreas Gohr
588da7d805SAndreas Gohr        $this->pdo = new \PDO(
598da7d805SAndreas Gohr            'sqlite:' . $file,
608da7d805SAndreas Gohr            null,
618da7d805SAndreas Gohr            null,
628da7d805SAndreas Gohr            [
638da7d805SAndreas Gohr                \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION
648da7d805SAndreas Gohr            ]
658da7d805SAndreas Gohr        );
668da7d805SAndreas Gohr
678da7d805SAndreas Gohr        if ($schemadir !== '') {
688da7d805SAndreas Gohr            // schema dir is empty, when accessing the DB from Admin interface instead of plugin context
698da7d805SAndreas Gohr            $this->applyMigrations();
708da7d805SAndreas Gohr        }
718da7d805SAndreas Gohr        Functions::register($this->pdo);
728da7d805SAndreas Gohr    }
738da7d805SAndreas Gohr
74aae177f9SAndreas Gohr    /**
75aae177f9SAndreas Gohr     * Do not serialize the DB connection
76aae177f9SAndreas Gohr     *
77aae177f9SAndreas Gohr     * @return array
78aae177f9SAndreas Gohr     */
79c9d29defSAndreas Gohr    public function __sleep()
80c9d29defSAndreas Gohr    {
81aae177f9SAndreas Gohr        $this->pdo = null;
82aae177f9SAndreas Gohr        return array_keys(get_object_vars($this));
83aae177f9SAndreas Gohr    }
84aae177f9SAndreas Gohr
85aae177f9SAndreas Gohr    /**
86aae177f9SAndreas Gohr     * On deserialization, reinit database connection
87aae177f9SAndreas Gohr     */
88c9d29defSAndreas Gohr    public function __wakeup()
89c9d29defSAndreas Gohr    {
90aae177f9SAndreas Gohr        $this->__construct($this->dbname, $this->schemadir, $this->helper);
91aae177f9SAndreas Gohr    }
928da7d805SAndreas Gohr
938da7d805SAndreas Gohr    // region public API
948da7d805SAndreas Gohr
958da7d805SAndreas Gohr    /**
968da7d805SAndreas Gohr     * Direct access to the PDO object
978da7d805SAndreas Gohr     * @return \PDO
988da7d805SAndreas Gohr     */
9933e488b3SAndreas Gohr    public function getPdo()
10033e488b3SAndreas Gohr    {
101e22957e9SSzymon Olewniczak        return $this->pdo;
102801b921eSSzymon Olewniczak    }
103801b921eSSzymon Olewniczak
104801b921eSSzymon Olewniczak    /**
1058da7d805SAndreas Gohr     * Execute a statement and return it
1068da7d805SAndreas Gohr     *
1078da7d805SAndreas Gohr     * @param string $sql
108*27eb38daSAndreas Gohr     * @param ...mixed|array $parameters
1098da7d805SAndreas Gohr     * @return \PDOStatement Be sure to close the cursor yourself
1108da7d805SAndreas Gohr     * @throws \PDOException
1118da7d805SAndreas Gohr     */
112*27eb38daSAndreas Gohr    public function query($sql, ...$parameters)
1138da7d805SAndreas Gohr    {
1140290deaeSAndreas Gohr        $start = microtime(true);
1150290deaeSAndreas Gohr
116*27eb38daSAndreas Gohr        if($parameters && is_array($parameters[0])) $parameters = $parameters[0];
117*27eb38daSAndreas Gohr
11803f14a77SAndreas Gohr        // Statement preparation sometime throws ValueErrors instead of PDOExceptions, we streamline here
11903f14a77SAndreas Gohr        try {
1208da7d805SAndreas Gohr            $stmt = $this->pdo->prepare($sql);
12103f14a77SAndreas Gohr        } catch (\Throwable $e) {
12203f14a77SAndreas Gohr            throw new \PDOException($e->getMessage(), (int)$e->getCode(), $e);
12303f14a77SAndreas Gohr        }
124b35b734aSSzymon Olewniczak        $eventData = [
125b8ae4891SSzymon Olewniczak            'sqlitedb' => $this,
126b35b734aSSzymon Olewniczak            'sql' => &$sql,
127b35b734aSSzymon Olewniczak            'parameters' => &$parameters,
128b35b734aSSzymon Olewniczak            'stmt' => $stmt
129b35b734aSSzymon Olewniczak        ];
130b35b734aSSzymon Olewniczak        $event = new Event('PLUGIN_SQLITE_QUERY_EXECUTE', $eventData);
131b35b734aSSzymon Olewniczak        if ($event->advise_before()) {
1328da7d805SAndreas Gohr            $stmt->execute($parameters);
133b35b734aSSzymon Olewniczak        }
134b35b734aSSzymon Olewniczak        $event->advise_after();
1350290deaeSAndreas Gohr
1360290deaeSAndreas Gohr        $time = microtime(true) - $start;
1370290deaeSAndreas Gohr        if ($time > 0.2) {
1380290deaeSAndreas Gohr            Logger::debug('[sqlite] slow query:  (' . $time . 's)', [
1390290deaeSAndreas Gohr                'sql' => $sql,
1400290deaeSAndreas Gohr                'parameters' => $parameters,
1410290deaeSAndreas Gohr                'backtrace' => explode("\n", dbg_backtrace())
1420290deaeSAndreas Gohr            ]);
1430290deaeSAndreas Gohr        }
1440290deaeSAndreas Gohr
1458da7d805SAndreas Gohr        return $stmt;
1468da7d805SAndreas Gohr    }
1478da7d805SAndreas Gohr
1488da7d805SAndreas Gohr    /**
1498da7d805SAndreas Gohr     * Execute a statement and return metadata
1508da7d805SAndreas Gohr     *
1518da7d805SAndreas Gohr     * Returns the last insert ID on INSERTs or the number of affected rows
1528da7d805SAndreas Gohr     *
1538da7d805SAndreas Gohr     * @param string $sql
154*27eb38daSAndreas Gohr     * @param ...mixed|array $parameters
1558da7d805SAndreas Gohr     * @return int
1568da7d805SAndreas Gohr     * @throws \PDOException
1578da7d805SAndreas Gohr     */
158*27eb38daSAndreas Gohr    public function exec($sql, ...$parameters)
1598da7d805SAndreas Gohr    {
160*27eb38daSAndreas Gohr        $stmt = $this->query($sql, ...$parameters);
1618da7d805SAndreas Gohr
1628da7d805SAndreas Gohr        $count = $stmt->rowCount();
1638da7d805SAndreas Gohr        $stmt->closeCursor();
1648da7d805SAndreas Gohr        if ($count && preg_match('/^INSERT /i', $sql)) {
1658da7d805SAndreas Gohr            return $this->queryValue('SELECT last_insert_rowid()');
1668da7d805SAndreas Gohr        }
1678da7d805SAndreas Gohr
1688da7d805SAndreas Gohr        return $count;
1698da7d805SAndreas Gohr    }
1708da7d805SAndreas Gohr
1718da7d805SAndreas Gohr    /**
1728da7d805SAndreas Gohr     * Simple query abstraction
1738da7d805SAndreas Gohr     *
1748da7d805SAndreas Gohr     * Returns all data
1758da7d805SAndreas Gohr     *
1768da7d805SAndreas Gohr     * @param string $sql
177*27eb38daSAndreas Gohr     * @param ...mixed|array $params
1788da7d805SAndreas Gohr     * @return array
1798da7d805SAndreas Gohr     * @throws \PDOException
1808da7d805SAndreas Gohr     */
181*27eb38daSAndreas Gohr    public function queryAll($sql, ...$params)
1828da7d805SAndreas Gohr    {
183*27eb38daSAndreas Gohr        $stmt = $this->query($sql, ...$params);
1848da7d805SAndreas Gohr        $data = $stmt->fetchAll(\PDO::FETCH_ASSOC);
1858da7d805SAndreas Gohr        $stmt->closeCursor();
1868da7d805SAndreas Gohr        return $data;
1878da7d805SAndreas Gohr    }
1888da7d805SAndreas Gohr
1898da7d805SAndreas Gohr    /**
1908da7d805SAndreas Gohr     * Query one single row
1918da7d805SAndreas Gohr     *
1928da7d805SAndreas Gohr     * @param string $sql
193*27eb38daSAndreas Gohr     * @param ...mixed|array $params
1948da7d805SAndreas Gohr     * @return array|null
1958da7d805SAndreas Gohr     * @throws \PDOException
1968da7d805SAndreas Gohr     */
197*27eb38daSAndreas Gohr    public function queryRecord($sql, ...$params)
1988da7d805SAndreas Gohr    {
199*27eb38daSAndreas Gohr        $stmt = $this->query($sql, ...$params);
200a7a36cdbSAndreas Gohr        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
2018da7d805SAndreas Gohr        $stmt->closeCursor();
202a7a36cdbSAndreas Gohr        if (is_array($row) && count($row)) {
203a7a36cdbSAndreas Gohr            return $row;
204a7a36cdbSAndreas Gohr        }
2058da7d805SAndreas Gohr        return null;
2068da7d805SAndreas Gohr    }
2078da7d805SAndreas Gohr
2088da7d805SAndreas Gohr    /**
2098da7d805SAndreas Gohr     * Insert or replace the given data into the table
2108da7d805SAndreas Gohr     *
2118da7d805SAndreas Gohr     * @param string $table
2128da7d805SAndreas Gohr     * @param array $data
2138da7d805SAndreas Gohr     * @param bool $replace Conflict resolution, replace or ignore
214a7a36cdbSAndreas Gohr     * @return array|null Either the inserted row or null if nothing was inserted
2158da7d805SAndreas Gohr     * @throws \PDOException
2168da7d805SAndreas Gohr     */
2178da7d805SAndreas Gohr    public function saveRecord($table, $data, $replace = true)
2188da7d805SAndreas Gohr    {
2198da7d805SAndreas Gohr        $columns = array_map(function ($column) {
2208da7d805SAndreas Gohr            return '"' . $column . '"';
2218da7d805SAndreas Gohr        }, array_keys($data));
2228da7d805SAndreas Gohr        $values = array_values($data);
2238da7d805SAndreas Gohr        $placeholders = array_pad([], count($columns), '?');
2248da7d805SAndreas Gohr
2258da7d805SAndreas Gohr        if ($replace) {
2268da7d805SAndreas Gohr            $command = 'REPLACE';
2278da7d805SAndreas Gohr        } else {
2288da7d805SAndreas Gohr            $command = 'INSERT OR IGNORE';
2298da7d805SAndreas Gohr        }
2308da7d805SAndreas Gohr
2318da7d805SAndreas Gohr        /** @noinspection SqlResolve */
232a7a36cdbSAndreas Gohr        $sql = $command . ' INTO "' . $table . '" (' . join(',', $columns) . ') VALUES (' . join(',',
233a7a36cdbSAndreas Gohr                $placeholders) . ')';
234b35b734aSSzymon Olewniczak        $stm = $this->query($sql, $values);
235a7a36cdbSAndreas Gohr        $success = $stm->rowCount();
2368da7d805SAndreas Gohr        $stm->closeCursor();
237a7a36cdbSAndreas Gohr
238a7a36cdbSAndreas Gohr        if ($success) {
239a7a36cdbSAndreas Gohr            $sql = 'SELECT * FROM "' . $table . '" WHERE rowid = last_insert_rowid()';
240a7a36cdbSAndreas Gohr            return $this->queryRecord($sql);
241a7a36cdbSAndreas Gohr        }
242a7a36cdbSAndreas Gohr        return null;
2438da7d805SAndreas Gohr    }
2448da7d805SAndreas Gohr
2458da7d805SAndreas Gohr    /**
2468da7d805SAndreas Gohr     * Execute a query that returns a single value
2478da7d805SAndreas Gohr     *
2488da7d805SAndreas Gohr     * @param string $sql
249*27eb38daSAndreas Gohr     * @param ...mixed|array $params
2508da7d805SAndreas Gohr     * @return mixed|null
2518da7d805SAndreas Gohr     * @throws \PDOException
2528da7d805SAndreas Gohr     */
253*27eb38daSAndreas Gohr    public function queryValue($sql, ...$params)
2548da7d805SAndreas Gohr    {
255*27eb38daSAndreas Gohr        $result = $this->queryAll($sql, ...$params);
256c9d29defSAndreas Gohr        if (is_array($result) && count($result)) {
257c9d29defSAndreas Gohr            return array_values($result[0])[0];
258c9d29defSAndreas Gohr        }
2598da7d805SAndreas Gohr        return null;
2608da7d805SAndreas Gohr    }
2618da7d805SAndreas Gohr
26233e488b3SAndreas Gohr    /**
26333e488b3SAndreas Gohr     * Execute a query that returns a list of key-value pairs
26433e488b3SAndreas Gohr     *
26533e488b3SAndreas Gohr     * The first column is used as key, the second as value. Any additional colums are ignored.
26633e488b3SAndreas Gohr     *
26733e488b3SAndreas Gohr     * @param string $sql
268*27eb38daSAndreas Gohr     * @param ...mixed|array $params
26933e488b3SAndreas Gohr     * @return array
27033e488b3SAndreas Gohr     */
271*27eb38daSAndreas Gohr    public function queryKeyValueList($sql, ...$params)
27233e488b3SAndreas Gohr    {
273*27eb38daSAndreas Gohr        $result = $this->queryAll($sql, ...$params);
27433e488b3SAndreas Gohr        if (!$result) return [];
27533e488b3SAndreas Gohr        if (count(array_keys($result[0])) != 2) {
27633e488b3SAndreas Gohr            throw new \RuntimeException('queryKeyValueList expects a query that returns exactly two columns');
27733e488b3SAndreas Gohr        }
27833e488b3SAndreas Gohr        [$key, $val] = array_keys($result[0]);
27933e488b3SAndreas Gohr
28033e488b3SAndreas Gohr        return array_combine(
28133e488b3SAndreas Gohr            array_column($result, $key),
28233e488b3SAndreas Gohr            array_column($result, $val)
28333e488b3SAndreas Gohr        );
28433e488b3SAndreas Gohr    }
28533e488b3SAndreas Gohr
2868da7d805SAndreas Gohr    // endregion
2878da7d805SAndreas Gohr
2888da7d805SAndreas Gohr    // region meta handling
2898da7d805SAndreas Gohr
2908da7d805SAndreas Gohr    /**
2918da7d805SAndreas Gohr     * Get a config value from the opt table
2928da7d805SAndreas Gohr     *
2938da7d805SAndreas Gohr     * @param string $opt Config name
2948da7d805SAndreas Gohr     * @param mixed $default What to return if the value isn't set
2958da7d805SAndreas Gohr     * @return mixed
2968da7d805SAndreas Gohr     * @throws \PDOException
2978da7d805SAndreas Gohr     */
2988da7d805SAndreas Gohr    public function getOpt($opt, $default = null)
2998da7d805SAndreas Gohr    {
3008da7d805SAndreas Gohr        $value = $this->queryValue("SELECT val FROM opts WHERE opt = ?", [$opt]);
301c9d29defSAndreas Gohr        if ($value === null) {
302c9d29defSAndreas Gohr            return $default;
303c9d29defSAndreas Gohr        }
3048da7d805SAndreas Gohr        return $value;
3058da7d805SAndreas Gohr    }
3068da7d805SAndreas Gohr
3078da7d805SAndreas Gohr    /**
3088da7d805SAndreas Gohr     * Set a config value in the opt table
3098da7d805SAndreas Gohr     *
3108da7d805SAndreas Gohr     * @param $opt
3118da7d805SAndreas Gohr     * @param $value
3128da7d805SAndreas Gohr     * @throws \PDOException
3138da7d805SAndreas Gohr     */
3148da7d805SAndreas Gohr    public function setOpt($opt, $value)
3158da7d805SAndreas Gohr    {
3168da7d805SAndreas Gohr        $this->exec('REPLACE INTO opts (opt,val) VALUES (?,?)', [$opt, $value]);
3178da7d805SAndreas Gohr    }
3188da7d805SAndreas Gohr
3198da7d805SAndreas Gohr    /**
3208da7d805SAndreas Gohr     * @return string
3218da7d805SAndreas Gohr     */
3228da7d805SAndreas Gohr    public function getDbName()
3238da7d805SAndreas Gohr    {
3248da7d805SAndreas Gohr        return $this->dbname;
3258da7d805SAndreas Gohr    }
3268da7d805SAndreas Gohr
3278da7d805SAndreas Gohr    /**
3288da7d805SAndreas Gohr     * @return string
3298da7d805SAndreas Gohr     */
3308da7d805SAndreas Gohr    public function getDbFile()
3318da7d805SAndreas Gohr    {
3328da7d805SAndreas Gohr        global $conf;
3338da7d805SAndreas Gohr        return $conf['metadir'] . '/' . $this->dbname . self::FILE_EXTENSION;
3348da7d805SAndreas Gohr    }
3358da7d805SAndreas Gohr
3368da7d805SAndreas Gohr    /**
3378da7d805SAndreas Gohr     * Create a dump of the database and its contents
3388da7d805SAndreas Gohr     *
3398da7d805SAndreas Gohr     * @return string
3408da7d805SAndreas Gohr     * @throws \Exception
3418da7d805SAndreas Gohr     */
3428da7d805SAndreas Gohr    public function dumpToFile($filename)
3438da7d805SAndreas Gohr    {
3448da7d805SAndreas Gohr        $fp = fopen($filename, 'w');
3458da7d805SAndreas Gohr        if (!$fp) {
3468da7d805SAndreas Gohr            throw new \Exception('Could not open file ' . $filename . ' for writing');
3478da7d805SAndreas Gohr        }
3488da7d805SAndreas Gohr
3497ddaad11SAndreas Gohr        $tables = $this->queryAll("SELECT name,sql FROM sqlite_master WHERE type='table'");
3507ddaad11SAndreas Gohr        $indexes = $this->queryAll("SELECT name,sql FROM sqlite_master WHERE type='index'");
3518da7d805SAndreas Gohr
3528da7d805SAndreas Gohr        foreach ($tables as $table) {
3537ddaad11SAndreas Gohr            fwrite($fp, "DROP TABLE IF EXISTS '{$table['name']}';\n");
3547ddaad11SAndreas Gohr        }
3558da7d805SAndreas Gohr
3567ddaad11SAndreas Gohr        foreach ($tables as $table) {
3577ddaad11SAndreas Gohr            fwrite($fp, $table['sql'] . ";\n");
3587ddaad11SAndreas Gohr        }
3597ddaad11SAndreas Gohr
3607ddaad11SAndreas Gohr        foreach ($tables as $table) {
3618da7d805SAndreas Gohr            $sql = "SELECT * FROM " . $table['name'];
3628da7d805SAndreas Gohr            $res = $this->query($sql);
3638da7d805SAndreas Gohr            while ($row = $res->fetch(\PDO::FETCH_ASSOC)) {
3647ddaad11SAndreas Gohr                $values = join(',', array_map(function ($value) {
3657ddaad11SAndreas Gohr                    if ($value === null) return 'NULL';
3667ddaad11SAndreas Gohr                    return $this->pdo->quote($value);
3677ddaad11SAndreas Gohr                }, $row));
3687ddaad11SAndreas Gohr                fwrite($fp, "INSERT INTO '{$table['name']}' VALUES ({$values});\n");
3698da7d805SAndreas Gohr            }
3708da7d805SAndreas Gohr            $res->closeCursor();
3718da7d805SAndreas Gohr        }
3728da7d805SAndreas Gohr
3738da7d805SAndreas Gohr        foreach ($indexes as $index) {
3748da7d805SAndreas Gohr            fwrite($fp, $index['sql'] . ";\n");
3758da7d805SAndreas Gohr        }
3768da7d805SAndreas Gohr        fclose($fp);
3778da7d805SAndreas Gohr        return $filename;
3788da7d805SAndreas Gohr    }
3798da7d805SAndreas Gohr
3808da7d805SAndreas Gohr    // endregion
3818da7d805SAndreas Gohr
3828da7d805SAndreas Gohr    // region migration handling
3838da7d805SAndreas Gohr
3848da7d805SAndreas Gohr    /**
3858da7d805SAndreas Gohr     * Apply all pending migrations
3868da7d805SAndreas Gohr     *
3878da7d805SAndreas Gohr     * Each migration is executed in a transaction which is rolled back on failure
3888da7d805SAndreas Gohr     * Migrations can be files in the schema directory or event handlers
3898da7d805SAndreas Gohr     *
3908da7d805SAndreas Gohr     * @throws \Exception
3918da7d805SAndreas Gohr     */
3928da7d805SAndreas Gohr    protected function applyMigrations()
3938da7d805SAndreas Gohr    {
3948da7d805SAndreas Gohr        $currentVersion = $this->currentDbVersion();
3958da7d805SAndreas Gohr        $latestVersion = $this->latestDbVersion();
3968da7d805SAndreas Gohr
3978da7d805SAndreas Gohr        for ($newVersion = $currentVersion + 1; $newVersion <= $latestVersion; $newVersion++) {
3988da7d805SAndreas Gohr            $data = [
3998da7d805SAndreas Gohr                'dbname' => $this->dbname,
4008da7d805SAndreas Gohr                'from' => $currentVersion,
4018da7d805SAndreas Gohr                'to' => $newVersion,
4028da7d805SAndreas Gohr                'file' => $this->getMigrationFile($newVersion),
4038da7d805SAndreas Gohr                'sqlite' => $this->helper,
4048da7d805SAndreas Gohr                'adapter' => $this,
4058da7d805SAndreas Gohr            ];
4068da7d805SAndreas Gohr            $event = new \Doku_Event('PLUGIN_SQLITE_DATABASE_UPGRADE', $data);
4078da7d805SAndreas Gohr
4088da7d805SAndreas Gohr            $this->pdo->beginTransaction();
4098da7d805SAndreas Gohr            try {
4108da7d805SAndreas Gohr                if ($event->advise_before()) {
4118da7d805SAndreas Gohr                    // standard migration file
4127ddaad11SAndreas Gohr                    $sql = Tools::SQLstring2array(file_get_contents($data['file']));
4137ddaad11SAndreas Gohr                    foreach ($sql as $query) {
4147ddaad11SAndreas Gohr                        $this->pdo->exec($query);
4157ddaad11SAndreas Gohr                    }
416c9d29defSAndreas Gohr                } else {
417c9d29defSAndreas Gohr                    if (!$event->result) {
4188da7d805SAndreas Gohr                        // advise before returned false, but the result was false
4198da7d805SAndreas Gohr                        throw new \PDOException('Plugin event did not signal success');
4208da7d805SAndreas Gohr                    }
421c9d29defSAndreas Gohr                }
4228da7d805SAndreas Gohr                $this->setOpt('dbversion', $newVersion);
4238da7d805SAndreas Gohr                $this->pdo->commit();
4248da7d805SAndreas Gohr                $event->advise_after();
4258da7d805SAndreas Gohr            } catch (\Exception $e) {
4268da7d805SAndreas Gohr                // something went wrong, rollback
4278da7d805SAndreas Gohr                $this->pdo->rollBack();
4288da7d805SAndreas Gohr                throw $e;
4298da7d805SAndreas Gohr            }
4308da7d805SAndreas Gohr        }
4318da7d805SAndreas Gohr
4328da7d805SAndreas Gohr        // vacuum the database to free up unused space
4338da7d805SAndreas Gohr        $this->pdo->exec('VACUUM');
4348da7d805SAndreas Gohr    }
4358da7d805SAndreas Gohr
4368da7d805SAndreas Gohr    /**
4378da7d805SAndreas Gohr     * Read the current version from the opt table
4388da7d805SAndreas Gohr     *
4398da7d805SAndreas Gohr     * The opt table is created here if not found
4408da7d805SAndreas Gohr     *
4418da7d805SAndreas Gohr     * @return int
4428da7d805SAndreas Gohr     * @throws \PDOException
4438da7d805SAndreas Gohr     */
4448da7d805SAndreas Gohr    protected function currentDbVersion()
4458da7d805SAndreas Gohr    {
4468da7d805SAndreas Gohr        try {
4478da7d805SAndreas Gohr            $version = $this->getOpt('dbversion', 0);
4488da7d805SAndreas Gohr            return (int)$version;
4498da7d805SAndreas Gohr        } catch (\PDOException $ignored) {
4508da7d805SAndreas Gohr            // add the opt table - if this fails too, let the exception bubble up
4518da7d805SAndreas Gohr            $sql = "CREATE TABLE IF NOT EXISTS opts (opt TEXT NOT NULL PRIMARY KEY, val NOT NULL DEFAULT '')";
4528da7d805SAndreas Gohr            $this->exec($sql);
4538da7d805SAndreas Gohr            $this->setOpt('dbversion', 0);
4548da7d805SAndreas Gohr            return 0;
4558da7d805SAndreas Gohr        }
4568da7d805SAndreas Gohr    }
4578da7d805SAndreas Gohr
4588da7d805SAndreas Gohr    /**
4598da7d805SAndreas Gohr     * Get the version this db should have
4608da7d805SAndreas Gohr     *
4618da7d805SAndreas Gohr     * @return int
4628da7d805SAndreas Gohr     * @throws \PDOException
4638da7d805SAndreas Gohr     */
4648da7d805SAndreas Gohr    protected function latestDbVersion()
4658da7d805SAndreas Gohr    {
4668da7d805SAndreas Gohr        if (!file_exists($this->schemadir . '/latest.version')) {
4678da7d805SAndreas Gohr            throw new \PDOException('No latest.version in schema dir');
4688da7d805SAndreas Gohr        }
4698da7d805SAndreas Gohr        return (int)trim(file_get_contents($this->schemadir . '/latest.version'));
4708da7d805SAndreas Gohr    }
4718da7d805SAndreas Gohr
4728da7d805SAndreas Gohr    /**
4738da7d805SAndreas Gohr     * Get the migrartion file for the given version
4748da7d805SAndreas Gohr     *
4758da7d805SAndreas Gohr     * @param int $version
4768da7d805SAndreas Gohr     * @return string
4778da7d805SAndreas Gohr     */
4788da7d805SAndreas Gohr    protected function getMigrationFile($version)
4798da7d805SAndreas Gohr    {
4808da7d805SAndreas Gohr        return sprintf($this->schemadir . '/update%04d.sql', $version);
4818da7d805SAndreas Gohr    }
4828da7d805SAndreas Gohr    // endregion
4838da7d805SAndreas Gohr}
484