xref: /plugin/struct/meta/SchemaBuilder.php (revision b8d3247dc56feb4b81d8c7df61a4214dd02a662f)
11c502704SAndreas Gohr<?php
21c502704SAndreas Gohr
3ba766201SAndreas Gohrnamespace dokuwiki\plugin\struct\meta;
41c502704SAndreas Gohr
57234bfb1Ssplitbrainuse dokuwiki\plugin\sqlite\SQLiteDB;
6a91bbca2SAndreas Gohruse dokuwiki\Utf8\PhpString;
7a91bbca2SAndreas Gohr
87182938bSAndreas Gohr/**
97182938bSAndreas Gohr * Class SchemaBuilder
107182938bSAndreas Gohr *
117182938bSAndreas Gohr * This class builds and updates the schema definitions for our tables. This includes CREATEing and ALTERing
127182938bSAndreas Gohr * the actual data tables as well as updating the meta information in our meta data tables.
137182938bSAndreas Gohr *
147182938bSAndreas Gohr * To use, simply instantiate a new object of the Builder and run the build() method on it.
157182938bSAndreas Gohr *
167182938bSAndreas Gohr * Note: even though data tables use a data_ prefix in the database, this prefix is internal only and should
177182938bSAndreas Gohr *       never be passed as $table anywhere!
187182938bSAndreas Gohr *
19ba766201SAndreas Gohr * @package dokuwiki\plugin\struct\meta
207182938bSAndreas Gohr */
21d6d97f60SAnna Dabrowskaclass SchemaBuilder
22d6d97f60SAnna Dabrowska{
231c502704SAndreas Gohr    /**
241c502704SAndreas Gohr     * @var array The posted new data for the schema
257182938bSAndreas Gohr     * @see Schema::AdminEditor()
261c502704SAndreas Gohr     */
277234bfb1Ssplitbrain    protected $data = [];
281c502704SAndreas Gohr
29fa7b96aaSMichael Grosse    protected $user;
30fa7b96aaSMichael Grosse
311c502704SAndreas Gohr    /**
321c502704SAndreas Gohr     * @var string The table name associated with the schema
331c502704SAndreas Gohr     */
341c502704SAndreas Gohr    protected $table = '';
351c502704SAndreas Gohr
361c502704SAndreas Gohr    /**
371c502704SAndreas Gohr     * @var Schema the previously valid schema for this table
381c502704SAndreas Gohr     */
391c502704SAndreas Gohr    protected $oldschema;
401c502704SAndreas Gohr
411c502704SAndreas Gohr    /** @var int the ID of the newly created schema */
421c502704SAndreas Gohr    protected $newschemaid = 0;
431c502704SAndreas Gohr
44a1603abdSAndreas Gohr    /** @var \helper_plugin_struct_db */
45a1603abdSAndreas Gohr    protected $helper;
46a1603abdSAndreas Gohr
477234bfb1Ssplitbrain    /** @var SQLiteDB|null */
481c502704SAndreas Gohr    protected $sqlite;
491c502704SAndreas Gohr
509d580426SAndreas Gohr    /** @var int the time for which this schema should be created - default to time() can be overriden for tests */
519d580426SAndreas Gohr    protected $time = 0;
529d580426SAndreas Gohr
531c502704SAndreas Gohr    /**
541c502704SAndreas Gohr     * SchemaBuilder constructor.
557182938bSAndreas Gohr     *
567182938bSAndreas Gohr     * @param string $table The table's name
577182938bSAndreas Gohr     * @param array $data The defining of the table (basically what get's posted in the schema editor form)
587182938bSAndreas Gohr     * @see Schema::AdminEditor()
591c502704SAndreas Gohr     */
60d6d97f60SAnna Dabrowska    public function __construct($table, $data)
61d6d97f60SAnna Dabrowska    {
62ecf2cba2SAndreas Gohr        global $INPUT;
63ecf2cba2SAndreas Gohr
641c502704SAndreas Gohr        $this->table = $table;
651c502704SAndreas Gohr        $this->data = $data;
660ceefd5cSAnna Dabrowska        $this->oldschema = new Schema($table, 0);
671c502704SAndreas Gohr
68a1603abdSAndreas Gohr        $this->helper = plugin_load('helper', 'struct_db');
69a1603abdSAndreas Gohr        $this->sqlite = $this->helper->getDB();
701ca21e17SAnna Dabrowska        $this->user = $_SERVER['REMOTE_USER'] ?? '';
711c502704SAndreas Gohr    }
721c502704SAndreas Gohr
731c502704SAndreas Gohr    /**
741c502704SAndreas Gohr     * Create the new schema
751c502704SAndreas Gohr     *
769d580426SAndreas Gohr     * @param int $time when to create this schema 0 for now
771ca21e17SAnna Dabrowska     * @return int the new schema id on success
781c502704SAndreas Gohr     */
79d6d97f60SAnna Dabrowska    public function build($time = 0)
80d6d97f60SAnna Dabrowska    {
819d580426SAndreas Gohr        $this->time = $time;
82a1603abdSAndreas Gohr        $this->fixLabelUniqueness();
83a1603abdSAndreas Gohr
841c502704SAndreas Gohr        $this->sqlite->query('BEGIN TRANSACTION');
856390a534SMichael Große        $ok = true;
866684d78dSAndreas Gohr        // create the data table if new schema
876684d78dSAndreas Gohr        if (!$this->oldschema->getId()) {
881c502704SAndreas Gohr            $ok = $this->newDataTable();
896684d78dSAndreas Gohr        }
901c502704SAndreas Gohr
911c502704SAndreas Gohr        // create a new schema
926390a534SMichael Große        $ok = $ok && $this->newSchema();
931c502704SAndreas Gohr
941c502704SAndreas Gohr        // update column info
956390a534SMichael Große        $ok = $ok && $this->updateColumns();
966390a534SMichael Große        $ok = $ok && $this->addColumns();
971c502704SAndreas Gohr
986390a534SMichael Große        if (!$ok) {
996390a534SMichael Große            $this->sqlite->query('ROLLBACK TRANSACTION');
1006390a534SMichael Große            return false;
1016390a534SMichael Große        }
1021c502704SAndreas Gohr        $this->sqlite->query('COMMIT TRANSACTION');
1031c502704SAndreas Gohr
1045cc23c44SAndreas Gohr        return (int)$this->newschemaid;
1051c502704SAndreas Gohr    }
1061c502704SAndreas Gohr
1071c502704SAndreas Gohr    /**
108a1603abdSAndreas Gohr     * Makes sure all labels in the schema to save are unique
109a1603abdSAndreas Gohr     */
110d6d97f60SAnna Dabrowska    protected function fixLabelUniqueness()
111d6d97f60SAnna Dabrowska    {
1127234bfb1Ssplitbrain        $labels = [];
113a1603abdSAndreas Gohr
114cf25d54bSAndreas Gohr        if (isset($this->data['cols'])) foreach ($this->data['cols'] as $idx => $column) {
115a1603abdSAndreas Gohr            $this->data['cols'][$idx]['label'] = $this->fixLabel($column['label'], $labels);
116a1603abdSAndreas Gohr        }
117a1603abdSAndreas Gohr
118cf25d54bSAndreas Gohr        if (isset($this->data['new'])) foreach ($this->data['new'] as $idx => $column) {
119a1603abdSAndreas Gohr            $this->data['new'][$idx]['label'] = $this->fixLabel($column['label'], $labels);
120a1603abdSAndreas Gohr        }
121a1603abdSAndreas Gohr    }
122a1603abdSAndreas Gohr
123a1603abdSAndreas Gohr    /**
124a1603abdSAndreas Gohr     * Creates a unique label from the given one
125a1603abdSAndreas Gohr     *
126a1603abdSAndreas Gohr     * @param string $wantedlabel
127a1603abdSAndreas Gohr     * @param array $labels list of already assigned labels (will be filled)
128a1603abdSAndreas Gohr     * @return string
129a1603abdSAndreas Gohr     */
130d6d97f60SAnna Dabrowska    protected function fixLabel($wantedlabel, &$labels)
131d6d97f60SAnna Dabrowska    {
132a1603abdSAndreas Gohr        $wantedlabel = trim($wantedlabel);
133a1603abdSAndreas Gohr        $fixedlabel = $wantedlabel;
134a1603abdSAndreas Gohr        $idx = 1;
135a91bbca2SAndreas Gohr        while (isset($labels[PhpString::strtolower($fixedlabel)])) {
136a1603abdSAndreas Gohr            $fixedlabel = $wantedlabel . $idx++;
137a1603abdSAndreas Gohr        }
138a1603abdSAndreas Gohr        // did we actually do a rename? apply it.
1397234bfb1Ssplitbrain        if ($fixedlabel !== $wantedlabel) {
140a1603abdSAndreas Gohr            msg(sprintf($this->helper->getLang('duplicate_label'), $wantedlabel, $fixedlabel), -1);
141a1603abdSAndreas Gohr            $this->data['cols']['label'] = $fixedlabel;
142a1603abdSAndreas Gohr        }
143a91bbca2SAndreas Gohr        $labels[PhpString::strtolower($fixedlabel)] = 1;
144a1603abdSAndreas Gohr        return $fixedlabel;
145a1603abdSAndreas Gohr    }
146a1603abdSAndreas Gohr
147a1603abdSAndreas Gohr    /**
1481c502704SAndreas Gohr     * Creates a new schema
1491c502704SAndreas Gohr     */
150d6d97f60SAnna Dabrowska    protected function newSchema()
151d6d97f60SAnna Dabrowska    {
1529d580426SAndreas Gohr        if (!$this->time) $this->time = time();
1539d580426SAndreas Gohr
1548f171097SAndreas Gohr        $config = $this->data['config'] ?? '{}';
155127d6bacSMichael Große
15676f0676dSAndreas Gohr        /** @noinspection SqlResolve */
1575b808f9fSAnna Dabrowska        $sql = "INSERT INTO schemas (tbl, ts, user, config) VALUES (?, ?, ?, ?)";
15879b29326SAnna Dabrowska        $this->sqlite->query($sql, [$this->table, $this->time, $this->user, $config]);
15979b29326SAnna Dabrowska        $this->newschemaid = $this->sqlite->queryValue('SELECT last_insert_rowid()');
16079b29326SAnna Dabrowska
1611c502704SAndreas Gohr        if (!$this->newschemaid) return false;
1621c502704SAndreas Gohr        return true;
1631c502704SAndreas Gohr    }
1641c502704SAndreas Gohr
1651c502704SAndreas Gohr    /**
1661c502704SAndreas Gohr     * Updates all the existing column infos and adds them to the new schema
1671c502704SAndreas Gohr     */
168d6d97f60SAnna Dabrowska    protected function updateColumns()
169d6d97f60SAnna Dabrowska    {
1701c502704SAndreas Gohr        foreach ($this->oldschema->getColumns() as $column) {
1711c502704SAndreas Gohr            $oldEntry = $column->getType()->getAsEntry();
1721c502704SAndreas Gohr            $oldTid = $column->getTid();
1731c502704SAndreas Gohr            $newEntry = $oldEntry;
1741c502704SAndreas Gohr            $newTid = $oldTid;
1751c502704SAndreas Gohr            $sort = $column->getSort();
1761c502704SAndreas Gohr            if (isset($this->data['cols'][$column->getColref()])) {
17717a3a578SAndreas Gohr                // todo I'm not too happy with this hardcoded here -
17817a3a578SAndreas Gohr                // we should probably have a list of fields at one place
1791c502704SAndreas Gohr                $newEntry['config'] = $this->data['cols'][$column->getColref()]['config'];
1801c502704SAndreas Gohr                $newEntry['label'] = $this->data['cols'][$column->getColref()]['label'];
1813a41f427SAnna Dabrowska                $newEntry['ismulti'] = $this->data['cols'][$column->getColref()]['ismulti'] ?? 0;
1821c502704SAndreas Gohr                $newEntry['class'] = $this->data['cols'][$column->getColref()]['class'];
1831c502704SAndreas Gohr                $sort = $this->data['cols'][$column->getColref()]['sort'];
1843a41f427SAnna Dabrowska                $enabled = (bool)($this->data['cols'][$column->getColref()]['isenabled'] ?? 0);
1851c502704SAndreas Gohr
1861c502704SAndreas Gohr                // when the type definition has changed, we create a new one
1871c502704SAndreas Gohr                if (array_diff_assoc($oldEntry, $newEntry)) {
18879b29326SAnna Dabrowska                    $ok = $this->sqlite->saveRecord('types', $newEntry);
1891c502704SAndreas Gohr                    if (!$ok) return false;
19079b29326SAnna Dabrowska                    $newTid = $this->sqlite->queryValue('SELECT last_insert_rowid()');
19179b29326SAnna Dabrowska                    if (!$newTid) return false;
192b3e0ad6dSMichael Grosse                    if ($oldEntry['ismulti'] == false && $newEntry['ismulti'] == '1') {
193b3e0ad6dSMichael Grosse                        $this->migrateSingleToMulti($this->oldschema->getTable(), $column->getColref());
194b3e0ad6dSMichael Grosse                    }
1951c502704SAndreas Gohr                }
1961c502704SAndreas Gohr            } else {
19726147f8cSAndreas Gohr                $enabled = false; // no longer there for some reason
1981c502704SAndreas Gohr            }
1991c502704SAndreas Gohr
2001c502704SAndreas Gohr            // add this type to the schema columns
2017fe2cdf2SAndreas Gohr            $schemaEntry = [
2027fe2cdf2SAndreas Gohr                'sid' => $this->newschemaid,
2037fe2cdf2SAndreas Gohr                'colref' => $column->getColref(),
2047fe2cdf2SAndreas Gohr                'enabled' => $enabled,
2057fe2cdf2SAndreas Gohr                'tid' => $newTid,
2067fe2cdf2SAndreas Gohr                'sort' => $sort
2077fe2cdf2SAndreas Gohr            ];
20879b29326SAnna Dabrowska            $ok = $this->sqlite->saveRecord('schema_cols', $schemaEntry);
2091c502704SAndreas Gohr            if (!$ok) return false;
2101c502704SAndreas Gohr        }
2111c502704SAndreas Gohr        return true;
2121c502704SAndreas Gohr    }
2131c502704SAndreas Gohr
2144050be94SMichael Grosse    /**
2154050be94SMichael Grosse     * Write the latest value from an entry in a data_ table to the corresponding multi_table
2164050be94SMichael Grosse     *
2174050be94SMichael Grosse     * @param string $table
2184050be94SMichael Grosse     * @param int $colref
2194050be94SMichael Grosse     */
220d6d97f60SAnna Dabrowska    protected function migrateSingleToMulti($table, $colref)
221d6d97f60SAnna Dabrowska    {
22276f0676dSAndreas Gohr        /** @noinspection SqlResolve */
223fc6ac2e5SAnna Dabrowska        $sqlSelect = "SELECT pid, rev, published, col$colref AS value FROM data_$table WHERE latest = 1";
22479b29326SAnna Dabrowska        $valueSet = $this->sqlite->queryAll($sqlSelect);
2257234bfb1Ssplitbrain        $valueString = [];
2267234bfb1Ssplitbrain        $arguments = [];
227b3e0ad6dSMichael Grosse        foreach ($valueSet as $values) {
228b3e0ad6dSMichael Grosse            if (blank($values['value']) || trim($values['value']) == '') {
229b3e0ad6dSMichael Grosse                continue;
230b3e0ad6dSMichael Grosse            }
231fc6ac2e5SAnna Dabrowska            $valueString[] = "(?, ?, ?, ?, ?, ?)";
232*b8d3247dSAnna Dabrowska            $arguments = [
233*b8d3247dSAnna Dabrowska                ...$arguments,
234*b8d3247dSAnna Dabrowska                $colref,
235*b8d3247dSAnna Dabrowska                $values['pid'],
236*b8d3247dSAnna Dabrowska                $values['rev'],
237*b8d3247dSAnna Dabrowska                $values['published'],
238*b8d3247dSAnna Dabrowska                1,
239*b8d3247dSAnna Dabrowska                $values['value']
240*b8d3247dSAnna Dabrowska            ];
241b3e0ad6dSMichael Grosse        }
2427234bfb1Ssplitbrain        if ($valueString === []) {
243b3e0ad6dSMichael Grosse            return;
244b3e0ad6dSMichael Grosse        }
2457234bfb1Ssplitbrain        $valueString = implode(',', $valueString);
24676f0676dSAndreas Gohr        /** @noinspection SqlResolve */
24712d2f24fSAnna Dabrowska        $sqlInsert = "INSERT OR REPLACE INTO multi_$table (colref, pid, rev, published, row, value) VALUES $valueString"; // phpcs:ignore
2484050be94SMichael Grosse        $this->sqlite->query($sqlInsert, $arguments);
249b3e0ad6dSMichael Grosse    }
250b3e0ad6dSMichael Grosse
2511c502704SAndreas Gohr    /**
2521c502704SAndreas Gohr     * Adds new columns to the new schema
2531c502704SAndreas Gohr     *
2541c502704SAndreas Gohr     * @return bool
2551c502704SAndreas Gohr     */
256d6d97f60SAnna Dabrowska    protected function addColumns()
257d6d97f60SAnna Dabrowska    {
2581c502704SAndreas Gohr        if (!isset($this->data['new'])) return true;
2591c502704SAndreas Gohr
2601c502704SAndreas Gohr        $colref = count($this->oldschema->getColumns()) + 1;
2611c502704SAndreas Gohr
2621c502704SAndreas Gohr        foreach ($this->data['new'] as $column) {
26326147f8cSAndreas Gohr            if (!$column['isenabled']) continue; // we do not add a disabled column
26426147f8cSAndreas Gohr
2651c502704SAndreas Gohr            // todo this duplicates the hardcoding as in  the function above
2667234bfb1Ssplitbrain            $newEntry = [];
2671ca21e17SAnna Dabrowska            $newEntry['config'] = $column['config'] ?? '{}';
2681c502704SAndreas Gohr            $newEntry['label'] = $column['label'];
2693a41f427SAnna Dabrowska            $newEntry['ismulti'] = $column['ismulti'] ?? 0;
2701c502704SAndreas Gohr            $newEntry['class'] = $column['class'];
2711c502704SAndreas Gohr            $sort = $column['sort'];
27226147f8cSAndreas Gohr
2731c502704SAndreas Gohr
2746684d78dSAndreas Gohr            // only save if the column got a name
2756684d78dSAndreas Gohr            if (!$newEntry['label']) continue;
2766684d78dSAndreas Gohr
2776684d78dSAndreas Gohr            // add new column to the data table
2786684d78dSAndreas Gohr            if (!$this->addDataTableColumn($colref)) {
2796684d78dSAndreas Gohr                return false;
2806684d78dSAndreas Gohr            }
2816684d78dSAndreas Gohr
2821c502704SAndreas Gohr            // save the type
28379b29326SAnna Dabrowska            $ok = $this->sqlite->saveRecord('types', $newEntry);
2841c502704SAndreas Gohr            if (!$ok) return false;
28579b29326SAnna Dabrowska            $newTid = $this->sqlite->queryValue('SELECT last_insert_rowid()');
28679b29326SAnna Dabrowska
28779b29326SAnna Dabrowska            if (!$newTid) return false;
2881c502704SAndreas Gohr
2891c502704SAndreas Gohr
2901c502704SAndreas Gohr            // add this type to the schema columns
2917fe2cdf2SAndreas Gohr            $schemaEntry = [
2927fe2cdf2SAndreas Gohr                'sid' => $this->newschemaid,
2937fe2cdf2SAndreas Gohr                'colref' => $colref,
2947fe2cdf2SAndreas Gohr                'enabled' => true,
2957fe2cdf2SAndreas Gohr                'tid' => $newTid,
2967fe2cdf2SAndreas Gohr                'sort' => $sort
2977fe2cdf2SAndreas Gohr            ];
29879b29326SAnna Dabrowska            $ok = $this->sqlite->saveRecord('schema_cols', $schemaEntry);
2991c502704SAndreas Gohr            if (!$ok) return false;
3001c502704SAndreas Gohr            $colref++;
3011c502704SAndreas Gohr        }
3021c502704SAndreas Gohr
3031c502704SAndreas Gohr        return true;
3041c502704SAndreas Gohr    }
3051c502704SAndreas Gohr
3061c502704SAndreas Gohr    /**
3070fe33e72SAndreas Gohr     * Create a completely new data table with no columns yet also create the appropriate
3080fe33e72SAndreas Gohr     * multi value table for the schema
3091c502704SAndreas Gohr     *
3101c502704SAndreas Gohr     * @return bool
3110549dcc5SAndreas Gohr     * @todo how do we want to handle indexes?
3121c502704SAndreas Gohr     */
313d6d97f60SAnna Dabrowska    protected function newDataTable()
314d6d97f60SAnna Dabrowska    {
3150fe33e72SAndreas Gohr        $ok = true;
3161c502704SAndreas Gohr
3170fe33e72SAndreas Gohr        $tbl = 'data_' . $this->table;
3181c502704SAndreas Gohr        $sql = "CREATE TABLE $tbl (
31986a40c1eSAnna Dabrowska                    pid TEXT DEFAULT '',
3200ceefd5cSAnna Dabrowska                    rid INTEGER,
3210ceefd5cSAnna Dabrowska                    rev INTEGER,
3227059e7e1SAndreas Gohr                    latest BOOLEAN NOT NULL DEFAULT 0,
323fc6ac2e5SAnna Dabrowska                    published BOOLEAN DEFAULT NULL,
3240ceefd5cSAnna Dabrowska                    PRIMARY KEY(pid, rid, rev)
3256684d78dSAndreas Gohr                )";
3260fe33e72SAndreas Gohr        $ok = $ok && (bool)$this->sqlite->query($sql);
3271c502704SAndreas Gohr
3280fe33e72SAndreas Gohr        $tbl = 'multi_' . $this->table;
3290fe33e72SAndreas Gohr        $sql = "CREATE TABLE $tbl (
3300fe33e72SAndreas Gohr                    colref INTEGER NOT NULL,
33186a40c1eSAnna Dabrowska                    pid TEXT DEFAULT '',
3320ceefd5cSAnna Dabrowska                    rid INTEGER,
3330ceefd5cSAnna Dabrowska                    rev INTEGER,
3348f259467SAndreas Gohr                    latest INTEGER NOT NULL DEFAULT 0,
335fc6ac2e5SAnna Dabrowska                    published BOOLEAN DEFAULT NULL,
3360fe33e72SAndreas Gohr                    row INTEGER NOT NULL,
3370fe33e72SAndreas Gohr                    value,
3380ceefd5cSAnna Dabrowska                    PRIMARY KEY(colref, pid, rid, rev, row)
3397c080d69SAndreas Gohr                );";
3407c080d69SAndreas Gohr        $ok = $ok && (bool)$this->sqlite->query($sql);
3417c080d69SAndreas Gohr
3427c080d69SAndreas Gohr        return $ok;
3437c080d69SAndreas Gohr    }
3447c080d69SAndreas Gohr
3457c080d69SAndreas Gohr    /**
3466684d78dSAndreas Gohr     * Add an additional column to the existing data table
3471c502704SAndreas Gohr     *
3486684d78dSAndreas Gohr     * @param int $index the new column index to add
3491c502704SAndreas Gohr     * @return bool
3501c502704SAndreas Gohr     */
351d6d97f60SAnna Dabrowska    protected function addDataTableColumn($index)
352d6d97f60SAnna Dabrowska    {
3531c502704SAndreas Gohr        $tbl = 'data_' . $this->table;
3546684d78dSAndreas Gohr        $sql = " ALTER TABLE $tbl ADD COLUMN col$index DEFAULT ''";
3551c502704SAndreas Gohr        if (!$this->sqlite->query($sql)) {
3561c502704SAndreas Gohr            return false;
3571c502704SAndreas Gohr        }
3581c502704SAndreas Gohr        return true;
3591c502704SAndreas Gohr    }
3601c502704SAndreas Gohr
36178bff02fSMichael Grosse    /**
36278bff02fSMichael Grosse     * @param string $user
36378bff02fSMichael Grosse     * @return SchemaBuilder
36478bff02fSMichael Grosse     */
365d6d97f60SAnna Dabrowska    public function setUser($user)
366d6d97f60SAnna Dabrowska    {
36778bff02fSMichael Grosse        $this->user = $user;
36878bff02fSMichael Grosse        return $this;
36978bff02fSMichael Grosse    }
3701c502704SAndreas Gohr}
371