xref: /plugin/struct/action/migration.php (revision 4cd5cc28e2bf004aed676e9b1f46cc188a4b2240)
1<?php
2
3/**
4 * DokuWiki Plugin struct (Action 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
10/**
11 * Class action_plugin_struct_migration
12 *
13 * Handle migrations that need more than just SQL
14 */
15class action_plugin_struct_migration extends DokuWiki_Action_Plugin
16{
17    /**
18     * @inheritDoc
19     */
20    public function register(Doku_Event_Handler $controller)
21    {
22        $controller->register_hook('PLUGIN_SQLITE_DATABASE_UPGRADE', 'BEFORE', $this, 'handleMigrations');
23    }
24
25    /**
26     * Call our custom migrations when defined
27     *
28     * @param Doku_Event $event
29     * @param $param
30     */
31    public function handleMigrations(Doku_Event $event, $param)
32    {
33        if ($event->data['sqlite']->getAdapter()->getDbname() !== 'struct') {
34            return;
35        }
36        $to = $event->data['to'];
37
38        if (is_callable(array($this, "migration$to"))) {
39            $event->preventDefault();
40            $event->result = call_user_func(array($this, "migration$to"), $event->data['sqlite']);
41        }
42    }
43
44    /**
45     * Executes Migration 12
46     *
47     * Add a latest column to all existing multi tables
48     *
49     * @param helper_plugin_sqlite $sqlite
50     * @return bool
51     */
52    protected function migration12(helper_plugin_sqlite $sqlite)
53    {
54        /** @noinspection SqlResolve */
55        $sql = "SELECT name FROM sqlite_master WHERE type = 'table' AND name LIKE 'multi_%'";
56        $res = $sqlite->query($sql);
57        $tables = $sqlite->res2arr($res);
58        $sqlite->res_close($res);
59
60        foreach ($tables as $row) {
61            $sql = 'ALTER TABLE ? ADD COLUMN latest INT DEFAULT 1';
62            $sqlite->query($sql, $row['name']);
63        }
64
65        return true;
66    }
67
68    /**
69     * Executes Migration 16
70     *
71     * Unifies previous page and lookup schema types
72     *
73     * @param helper_plugin_sqlite $sqlite
74     * @return bool
75     */
76    protected function migration16(helper_plugin_sqlite $sqlite)
77    {
78        // get tables and their SQL definitions
79        $sql = "SELECT sql, name FROM sqlite_master
80                WHERE type = 'table'
81                AND (name LIKE 'data_%' OR name LIKE 'multi_%')";
82        $res = $sqlite->query($sql);
83        $tables = $sqlite->res2arr($res);
84        $sqlite->res_close($res);
85
86        // get latest versions of schemas with islookup property
87        $sql = "SELECT MAX(id) AS id, tbl, islookup FROM schemas
88                    GROUP BY tbl
89            ";
90        $res = $sqlite->query($sql);
91        $schemas = $sqlite->res2arr($res);
92
93        $sqlite->query('BEGIN TRANSACTION');
94        $ok = true;
95
96        // Step 1: move original data to temporary tables and create new ones with modified schemas
97        foreach ($tables as $table) {
98            $name = $table['name'];
99            $sql = $table['sql'];
100
101            // move original data to temp_*
102            $ok = $ok && $sqlite->query("ALTER TABLE $name RENAME TO temp_$name");
103
104            // update pid definitions
105            $sql = preg_replace('/pid (\w* ?NOT NULL|\w* ?PRIMARY KEY)/', 'pid TEXT DEFAULT ""', $sql);
106
107            // add rid and new primary key to regular tables
108            $cnt = 0;
109            $sql = preg_replace('/(PRIMARY KEY ?\([^\)]+?)(\))/', ' rid INTEGER, $1, rid $2', $sql, -1, $cnt);
110            // add rid and new primary key to lookup tables
111            if (!$cnt) {
112                $sql = str_replace(')', ', rid INTEGER, PRIMARY KEY(pid,rid) )', $sql);
113            }
114
115            // create the new table
116            $ok = $ok && $sqlite->query($sql);
117            if (!$ok) return false;
118        }
119
120        // Step 2: transfer data back from original tables (temp_*)
121        foreach ($schemas as $schema) {
122            $name = $schema['tbl'];
123            $sid = $schema['id'];
124            $isLookup = $schema['islookup'];
125
126            if (!$isLookup) {
127                $s = sprintf('INSERT INTO data_%s SELECT *, 0 FROM temp_data_%s', $name, $name);
128                $ok = $ok && $sqlite->query($s);
129                if (!$ok) return false;
130
131                $s = sprintf('INSERT INTO multi_%s SELECT *, 0 FROM temp_multi_%s', $name, $name);
132                $ok = $ok && $sqlite->query($s);
133                if (!$ok) return false;
134            } else {
135                // transfer pid to rid
136                $s = sprintf('INSERT INTO data_%s SELECT *, pid FROM temp_data_%s', $name, $name);
137                $ok = $ok && $sqlite->query($s);
138                if (!$ok) return false;
139
140                $s = sprintf('INSERT INTO multi_%s SELECT *, pid FROM temp_multi_%s', $name, $name);
141                $ok = $ok && $sqlite->query($s);
142                if (!$ok) return false;
143
144                // all lookup data has empty pids at this point
145                $s = "UPDATE data_$name SET pid = ''";
146                $ok = $ok && $sqlite->query($s);
147                if (!$ok) return false;
148
149                $s = "UPDATE multi_$name SET pid = ''";
150                $ok = $ok && $sqlite->query($s);
151                if (!$ok) return false;
152            }
153
154            // introduce composite ids in lookup columns
155            $s = "SELECT C.colref AS COL, T.class AS TYPE
156                FROM schema_cols AS C
157                LEFT OUTER JOIN types AS T
158                    ON C.tid = T.id
159                WHERE C.sid = $sid
160                AND TYPE = 'Lookup'
161            ";
162            $res = $sqlite->query($s);
163            $cols = $sqlite->res2arr($res);
164
165            if ($cols) {
166                foreach ($cols as $col) {
167                    $colno = $col['COL'];
168                    $s = "UPDATE data_$name SET col$colno = '[" . '""' . ",'||col$colno||']' WHERE col$colno != ''";
169                    $ok = $ok && $sqlite->query($s);
170                    if (!$ok) return false;
171
172                    // multi_
173                    $s = "UPDATE multi_$name SET value = '[" . '""' . ",'||value||']' WHERE colref=$colno";
174                    $ok = $ok && $sqlite->query($s);
175                    if (!$ok) return false;
176                }
177            }
178        }
179
180        // Step 3: delete temp_* tables
181        foreach ($tables as $table) {
182            $name = $table['name'];
183            $s = "DROP TABLE temp_$name";
184            $ok = $ok && $sqlite->query($s);
185            if (!$ok) return false;
186        }
187
188        // Step 4: remove islookup in schemas table
189        $sql = "SELECT sql FROM sqlite_master
190                WHERE type = 'table'
191                AND name = 'schemas'";
192        $res = $sqlite->query($sql);
193        $t = $sqlite->res2arr($res);
194        $sql = $t[0]['sql'];
195        $sql = str_replace('islookup INTEGER,', '', $sql);
196
197        $s = 'ALTER TABLE schemas RENAME TO temp_schemas';
198        $ok = $ok && $sqlite->query($s);
199        if (!$ok) return false;
200
201        // create a new table without islookup
202        $ok = $ok && $sqlite->query($sql);
203        if (!$ok) return false;
204
205        $s = 'INSERT INTO schemas SELECT id, tbl, ts, user, comment, config FROM temp_schemas';
206        $ok = $ok && $sqlite->query($s);
207
208        if (!$ok) {
209            $sqlite->query('ROLLBACK TRANSACTION');
210            return false;
211        }
212        $sqlite->query('COMMIT TRANSACTION');
213        return true;
214    }
215}
216