xref: /plugin/bez/action/migration.php (revision fe5d6d1ebd253c129098b67fff8cf438a54d8650)
1<?php
2/**
3 * DokuWiki Plugin bez (Action Component)
4 *
5 */
6
7// must be run within Dokuwiki
8
9if(!defined('DOKU_INC')) die();
10
11/**
12 * Class action_plugin_bez_migration
13 *
14 * Handle migrations that need more than just SQL
15 */
16class action_plugin_bez_migration extends DokuWiki_Action_Plugin {
17    /**
18     * @inheritDoc
19     */
20    public function register(Doku_Event_Handler $controller) {
21        $controller->register_hook('PLUGIN_SQLITE_DATABASE_UPGRADE', 'BEFORE', $this, 'handle_migrations');
22    }
23
24    /**
25     * Call our custom migrations when defined
26     *
27     * @param Doku_Event $event
28     * @param $param
29     */
30    public function handle_migrations(Doku_Event $event, $param) {
31        if ($event->data['sqlite']->getAdapter()->getDbname() !== 'b3p') {
32            return;
33        }
34        $to = $event->data['to'];
35
36        if(is_callable(array($this, "migration$to"))) {
37            $event->preventDefault();
38            $event->result = call_user_func(array($this, "migration$to"), $event->data);
39        }
40    }
41
42    /**
43     * Executes Migration 1
44     *
45     * Add a latest column to all existing multi tables
46     *
47     * @param helper_plugin_sqlite $sqlite
48     * @return bool
49     */
50    protected function migration1($data) {
51        $file = $data['file'];
52        /** @var helper_plugin_sqlite $sqlite */
53        $sqlite = $data['sqlite'];
54
55        $sql = file_get_contents($file);
56        if ($sql === false) {
57            throw new Exception('cannot open file '.$file);
58        }
59
60        $matches = array();
61        preg_match_all('/.*?(?(?=BEGIN)BEGIN.*?END)\s*;/is', $sql, $matches);
62        $queries = $matches[0];
63
64        $db = $sqlite->getAdapter()->getDb();
65
66        $db->beginTransaction();
67        foreach ($queries as $query) {
68            $res = $db->query($query);
69            if($res === false) {
70                $err = $db->errorInfo();
71                msg($err[0].' '.$err[1].' '.$err[2].':<br /><pre>'.hsc($sql).'</pre>', -1);
72                $db->rollBack();
73                return false;
74            }
75        }
76        $db->commit();
77
78        return true;
79    }
80
81}
82