xref: /plugin/struct/meta/SchemaBuilder.php (revision 6684d78dd5413bd0494cdf5cc1379d727d5c1cc5)
1<?php
2
3namespace plugin\struct\meta;
4
5/**
6 * Class SchemaBuilder
7 *
8 * This class builds and updates the schema definitions for our tables. This includes CREATEing and ALTERing
9 * the actual data tables as well as updating the meta information in our meta data tables.
10 *
11 * To use, simply instantiate a new object of the Builder and run the build() method on it.
12 *
13 * Note: even though data tables use a data_ prefix in the database, this prefix is internal only and should
14 *       never be passed as $table anywhere!
15 *
16 * @package plugin\struct\meta
17 */
18class SchemaBuilder {
19
20    /**
21     * @var array The posted new data for the schema
22     * @see Schema::AdminEditor()
23     */
24    protected $data = array();
25
26    /**
27     * @var string The table name associated with the schema
28     */
29    protected $table = '';
30
31    /**
32     * @var Schema the previously valid schema for this table
33     */
34    protected $oldschema;
35
36    /** @var int the ID of the newly created schema */
37    protected $newschemaid = 0;
38
39    /** @var \helper_plugin_sqlite|null  */
40    protected $sqlite;
41
42    /**
43     * SchemaBuilder constructor.
44     *
45     * @param string $table The table's name
46     * @param array $data The defining of the table (basically what get's posted in the schema editor form)
47     * @see Schema::AdminEditor()
48     */
49    public function __construct($table, $data) {
50        $this->table = $table;
51        $this->data = $data;
52        $this->oldschema = new Schema($table);
53
54        /** @var \helper_plugin_struct_db $helper */
55        $helper = plugin_load('helper', 'struct_db');
56        $this->sqlite = $helper->getDB();
57    }
58
59    /**
60     * Create the new schema
61     *
62     * @return bool|int the new schema id on success
63     */
64    public function build() {
65        $this->sqlite->query('BEGIN TRANSACTION');
66
67        // create the data table if new schema
68        if(!$this->oldschema->getId()) {
69            $ok = $this->newDataTable();
70            if(!$ok) return false;
71        }
72
73        // create a new schema
74        if(!$this->newSchema()) return false;
75
76        // update column info
77        if(!$this->updateColumns()) return false;
78        if(!$this->addColumns()) return false;
79
80        $this->sqlite->query('COMMIT TRANSACTION');
81
82        return $this->newschemaid;
83    }
84
85    /**
86     * Creates a new schema
87     *
88     * @todo use checksum or other heuristic to see if we really need a new schema OTOH we probably need one nearly always!?
89     */
90    protected function newSchema() {
91        $sql = "INSERT INTO schemas (tbl, ts) VALUES (?, ?)";
92        $this->sqlite->query($sql, $this->table, time());
93        $res = $this->sqlite->query('SELECT last_insert_rowid()');
94        $this->newschemaid = $this->sqlite->res2single($res);
95        $this->sqlite->res_close($res);
96        if(!$this->newschemaid) return false;
97        return true;
98    }
99
100    /**
101     * Updates all the existing column infos and adds them to the new schema
102     */
103    protected function updateColumns() {
104        foreach($this->oldschema->getColumns() as $column) {
105            $oldEntry = $column->getType()->getAsEntry();
106            $oldTid   = $column->getTid();
107            $newEntry = $oldEntry;
108            $newTid   = $oldTid;
109            $enabled  = true;
110            $sort = $column->getSort();
111            if(isset($this->data['cols'][$column->getColref()])){
112                // todo I'm not too happy with this hardcoded here - we should probably have a list of fields at one place
113                $newEntry['config'] = $this->data['cols'][$column->getColref()]['config'];
114                $newEntry['label'] = $this->data['cols'][$column->getColref()]['label'];
115                $newEntry['ismulti'] = $this->data['cols'][$column->getColref()]['multi'];
116                $newEntry['class'] = $this->data['cols'][$column->getColref()]['class'];
117                $sort = $this->data['cols'][$column->getColref()]['sort'];
118
119                // when the type definition has changed, we create a new one
120                if(array_diff_assoc($oldEntry, $newEntry)) {
121                    $ok = $this->sqlite->storeEntry('types', $newEntry);
122                    if(!$ok) return false;
123                    $res = $this->sqlite->query('SELECT last_insert_rowid()');
124                    if(!$res) return false;
125                    $newTid = $this->sqlite->res2single($res);
126                    $this->sqlite->res_close($res);
127                }
128            } else {
129                $enabled = false; // no longer there FIXME this assumes we remove the entry from the form completely. We might not want to do that
130            }
131
132            // add this type to the schema columns
133            $schemaEntry = array(
134                'sid' => $this->newschemaid,
135                'colref' => $column->getColref(),
136                'enabled' => $enabled,
137                'tid' => $newTid,
138                'sort' => $sort
139            );
140            $ok = $this->sqlite->storeEntry('schema_cols', $schemaEntry);
141            if(!$ok) return false;
142        }
143        return true;
144    }
145
146    /**
147     * Adds new columns to the new schema
148     *
149     * @return bool
150     */
151    protected function addColumns() {
152        if(!isset($this->data['new'])) return true;
153
154        $colref = count($this->oldschema->getColumns())+1;
155
156        foreach($this->data['new'] as $column) {
157            // todo this duplicates the hardcoding as in  the function above
158            $newEntry = array();
159            $newEntry['config'] = $column['config'];
160            $newEntry['label'] = $column['label'];
161            $newEntry['ismulti'] = $column['multi'];
162            $newEntry['class'] = $column['class'];
163            $sort = $column['sort'];
164            $enabled = true;
165
166            // only save if the column got a name
167            if(!$newEntry['label']) continue;
168
169            // add new column to the data table
170            if(!$this->addDataTableColumn($colref)) {
171                return false;
172            }
173
174            // save the type
175            $ok = $this->sqlite->storeEntry('types', $newEntry);
176            if(!$ok) return false;
177            $res = $this->sqlite->query('SELECT last_insert_rowid()');
178            if(!$res) return false;
179            $newTid = $this->sqlite->res2single($res);
180            $this->sqlite->res_close($res);
181
182
183            // add this type to the schema columns
184            $schemaEntry = array(
185                'sid' => $this->newschemaid,
186                'colref' => $colref,
187                'enabled' => $enabled,
188                'tid' => $newTid,
189                'sort' => $sort
190            );
191            $ok = $this->sqlite->storeEntry('schema_cols', $schemaEntry);
192            if(!$ok) return false;
193            $colref++;
194        }
195
196        return true;
197    }
198
199    /**
200     * Create a completely new data table with columns yet
201     *
202     * @todo how do we want to handle indexes?
203     * @return bool
204     */
205    protected function newDataTable() {
206        $tbl = 'data_' . $this->table;
207
208        $sql = "CREATE TABLE $tbl (
209                    pid NOT NULL,
210                    rev INTEGER NOT NULL,
211                    PRIMARY KEY(pid, rev)
212                )";
213
214        return (bool) $this->sqlite->query($sql);
215    }
216
217    /**
218     * Add an additional column to the existing data table
219     *
220     * @param int $index the new column index to add
221     * @return bool
222     */
223    protected function addDataTableColumn($index) {
224        $tbl = 'data_' . $this->table;
225        $sql = " ALTER TABLE $tbl ADD COLUMN col$index DEFAULT ''";
226        if(! $this->sqlite->query($sql)) {
227            return false;
228        }
229        return true;
230    }
231
232}
233