1<?php 2 3namespace dokuwiki\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 dokuwiki\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 protected $user; 27 28 /** 29 * @var string The table name associated with the schema 30 */ 31 protected $table = ''; 32 33 /** 34 * @var Schema the previously valid schema for this table 35 */ 36 protected $oldschema; 37 38 /** @var int the ID of the newly created schema */ 39 protected $newschemaid = 0; 40 41 /** @var \helper_plugin_struct_db */ 42 protected $helper; 43 44 /** @var \helper_plugin_sqlite|null */ 45 protected $sqlite; 46 47 /** @var int the time for which this schema should be created - default to time() can be overriden for tests */ 48 protected $time = 0; 49 50 /** 51 * SchemaBuilder constructor. 52 * 53 * @param string $table The table's name 54 * @param array $data The defining of the table (basically what get's posted in the schema editor form) 55 * @see Schema::AdminEditor() 56 */ 57 public function __construct($table, $data) { 58 $this->table = $table; 59 $this->data = $data; 60 $this->oldschema = new Schema($table, 0, $data['islookup']); 61 62 $this->helper = plugin_load('helper', 'struct_db'); 63 $this->sqlite = $this->helper->getDB(); 64 $this->user = $_SERVER['REMOTE_USER']; 65 } 66 67 /** 68 * Create the new schema 69 * 70 * @param int $time when to create this schema 0 for now 71 * @return bool|int the new schema id on success 72 */ 73 public function build($time=0) { 74 $this->time = $time; 75 $this->fixLabelUniqueness(); 76 77 $this->sqlite->query('BEGIN TRANSACTION'); 78 $ok = true; 79 // create the data table if new schema 80 if(!$this->oldschema->getId()) { 81 if($this->oldschema->isLookup()) { 82 $ok = $this->newLookupTable(); 83 } else { 84 $ok = $this->newDataTable(); 85 } 86 } 87 88 // create a new schema 89 $ok = $ok && $this->newSchema(); 90 91 // update column info 92 $ok = $ok && $this->updateColumns(); 93 $ok = $ok && $this->addColumns(); 94 95 if (!$ok) { 96 $this->sqlite->query('ROLLBACK TRANSACTION'); 97 return false; 98 } 99 $this->sqlite->query('COMMIT TRANSACTION'); 100 101 return $this->newschemaid; 102 } 103 104 /** 105 * Makes sure all labels in the schema to save are unique 106 */ 107 protected function fixLabelUniqueness() { 108 $labels = array(); 109 110 if(isset($this->data['cols'])) foreach($this->data['cols'] as $idx => $column) { 111 $this->data['cols'][$idx]['label'] = $this->fixLabel($column['label'], $labels); 112 } 113 114 if(isset($this->data['new'])) foreach($this->data['new'] as $idx => $column) { 115 $this->data['new'][$idx]['label'] = $this->fixLabel($column['label'], $labels); 116 } 117 } 118 119 /** 120 * Creates a unique label from the given one 121 * 122 * @param string $wantedlabel 123 * @param array $labels list of already assigned labels (will be filled) 124 * @return string 125 */ 126 protected function fixLabel($wantedlabel, &$labels) { 127 $wantedlabel = trim($wantedlabel); 128 $fixedlabel = $wantedlabel; 129 $idx = 1; 130 while(isset($labels[utf8_strtolower($fixedlabel)])) { 131 $fixedlabel = $wantedlabel.$idx++; 132 } 133 // did we actually do a rename? apply it. 134 if($fixedlabel != $wantedlabel) { 135 msg(sprintf($this->helper->getLang('duplicate_label'), $wantedlabel, $fixedlabel), -1); 136 $this->data['cols']['label'] = $fixedlabel; 137 } 138 $labels[utf8_strtolower($fixedlabel)] = 1; 139 return $fixedlabel; 140 } 141 142 /** 143 * Creates a new schema 144 * 145 * @todo use checksum or other heuristic to see if we really need a new schema OTOH we probably need one nearly always!? 146 */ 147 protected function newSchema() { 148 if(!$this->time) $this->time = time(); 149 150 $sql = "INSERT INTO schemas (tbl, ts, islookup, user) VALUES (?, ?, ?, ?)"; 151 $this->sqlite->query($sql, $this->table, $this->time, (int) $this->oldschema->isLookup(), $this->user); 152 $res = $this->sqlite->query('SELECT last_insert_rowid()'); 153 $this->newschemaid = $this->sqlite->res2single($res); 154 $this->sqlite->res_close($res); 155 if(!$this->newschemaid) return false; 156 return true; 157 } 158 159 /** 160 * Updates all the existing column infos and adds them to the new schema 161 */ 162 protected function updateColumns() { 163 foreach($this->oldschema->getColumns() as $column) { 164 $oldEntry = $column->getType()->getAsEntry(); 165 $oldTid = $column->getTid(); 166 $newEntry = $oldEntry; 167 $newTid = $oldTid; 168 $sort = $column->getSort(); 169 if(isset($this->data['cols'][$column->getColref()])){ 170 // todo I'm not too happy with this hardcoded here - we should probably have a list of fields at one place 171 $newEntry['config'] = $this->data['cols'][$column->getColref()]['config']; 172 $newEntry['label'] = $this->data['cols'][$column->getColref()]['label']; 173 $newEntry['ismulti'] = $this->data['cols'][$column->getColref()]['ismulti']; 174 $newEntry['class'] = $this->data['cols'][$column->getColref()]['class']; 175 $sort = $this->data['cols'][$column->getColref()]['sort']; 176 $enabled = (bool) $this->data['cols'][$column->getColref()]['isenabled']; 177 178 // when the type definition has changed, we create a new one 179 if(array_diff_assoc($oldEntry, $newEntry)) { 180 $ok = $this->sqlite->storeEntry('types', $newEntry); 181 if(!$ok) return false; 182 $res = $this->sqlite->query('SELECT last_insert_rowid()'); 183 if(!$res) return false; 184 $newTid = $this->sqlite->res2single($res); 185 $this->sqlite->res_close($res); 186 if ($oldEntry['ismulti'] == false && $newEntry['ismulti'] == '1') { 187 $this->migrateSingleToMulti($this->oldschema->getTable(), $column->getColref()); 188 } 189 } 190 } else { 191 $enabled = false; // no longer there for some reason 192 } 193 194 // add this type to the schema columns 195 $schemaEntry = array( 196 'sid' => $this->newschemaid, 197 'colref' => $column->getColref(), 198 'enabled' => $enabled, 199 'tid' => $newTid, 200 'sort' => $sort 201 ); 202 $ok = $this->sqlite->storeEntry('schema_cols', $schemaEntry); 203 if(!$ok) return false; 204 } 205 return true; 206 } 207 208 /** 209 * Write the latest value from an entry in a data_ table to the corresponding multi_table 210 * 211 * @param string $table 212 * @param int $colref 213 */ 214 protected function migrateSingleToMulti($table, $colref) { 215 $sqlSelect = "SELECT pid, rev, col$colref AS value FROM data_$table WHERE latest = 1"; 216 $res = $this->sqlite->query($sqlSelect); 217 $valueSet = $this->sqlite->res2arr($res); 218 $this->sqlite->res_close($res); 219 $valueString = array(); 220 $arguments = array(); 221 foreach ($valueSet as $values) { 222 if (blank($values['value']) || trim($values['value']) == '') { 223 continue; 224 } 225 $valueString[] = "(?, ?, ?, ?, ?)"; 226 $arguments = array_merge($arguments, array($colref, $values['pid'], $values['rev'], 1, $values['value'])); 227 } 228 if (empty($valueString)) { 229 return; 230 } 231 $valueString = join(',', $valueString); 232 $sqlInsert = "INSERT OR REPLACE INTO multi_$table (colref, pid, rev, row, value) VALUES $valueString"; 233 $this->sqlite->query($sqlInsert, $arguments); 234 } 235 236 /** 237 * Adds new columns to the new schema 238 * 239 * @return bool 240 */ 241 protected function addColumns() { 242 if(!isset($this->data['new'])) return true; 243 244 $colref = count($this->oldschema->getColumns())+1; 245 246 foreach($this->data['new'] as $column) { 247 if(!$column['isenabled']) continue; // we do not add a disabled column 248 249 // todo this duplicates the hardcoding as in the function above 250 $newEntry = array(); 251 $newEntry['config'] = $column['config']; 252 $newEntry['label'] = $column['label']; 253 $newEntry['ismulti'] = $column['ismulti']; 254 $newEntry['class'] = $column['class']; 255 $sort = $column['sort']; 256 257 258 // only save if the column got a name 259 if(!$newEntry['label']) continue; 260 261 // add new column to the data table 262 if(!$this->addDataTableColumn($colref)) { 263 return false; 264 } 265 266 // save the type 267 $ok = $this->sqlite->storeEntry('types', $newEntry); 268 if(!$ok) return false; 269 $res = $this->sqlite->query('SELECT last_insert_rowid()'); 270 if(!$res) return false; 271 $newTid = $this->sqlite->res2single($res); 272 $this->sqlite->res_close($res); 273 274 275 // add this type to the schema columns 276 $schemaEntry = array( 277 'sid' => $this->newschemaid, 278 'colref' => $colref, 279 'enabled' => true, 280 'tid' => $newTid, 281 'sort' => $sort 282 ); 283 $ok = $this->sqlite->storeEntry('schema_cols', $schemaEntry); 284 if(!$ok) return false; 285 $colref++; 286 } 287 288 return true; 289 } 290 291 /** 292 * Create a completely new data table with no columns yet also create the appropriate 293 * multi value table for the schema 294 * 295 * @todo how do we want to handle indexes? 296 * @return bool 297 */ 298 protected function newDataTable() { 299 $ok = true; 300 301 $tbl = 'data_' . $this->table; 302 $sql = "CREATE TABLE $tbl ( 303 pid NOT NULL, 304 rev INTEGER NOT NULL, 305 latest BOOLEAN NOT NULL DEFAULT 0, 306 PRIMARY KEY(pid, rev) 307 )"; 308 $ok = $ok && (bool) $this->sqlite->query($sql); 309 310 $tbl = 'multi_' . $this->table; 311 $sql = "CREATE TABLE $tbl ( 312 colref INTEGER NOT NULL, 313 pid NOT NULL, 314 rev INTEGER NOT NULL, 315 row INTEGER NOT NULL, 316 value, 317 PRIMARY KEY(colref, pid, rev, row) 318 );"; 319 $ok = $ok && (bool) $this->sqlite->query($sql); 320 321 return $ok; 322 } 323 324 /** 325 * Creates a new lookup table with no columns 326 * 327 * This is basically the same as @see newDataTable() but sets 328 * different primary keys and types 329 * 330 * @return bool 331 */ 332 protected function newLookupTable() { 333 $ok = true; 334 335 $tbl = 'data_' . $this->table; 336 $sql = "CREATE TABLE $tbl ( 337 pid INTEGER PRIMARY KEY, 338 rev INTEGER NOT NULL DEFAULT 0, 339 latest BOOLEAN NOT NULL DEFAULT 1 340 )"; 341 $ok = $ok && (bool) $this->sqlite->query($sql); 342 343 $tbl = 'multi_' . $this->table; 344 $sql = "CREATE TABLE $tbl ( 345 colref INTEGER NOT NULL, 346 pid INTEGER NOT NULL, 347 rev INTEGER NOT NULL DEFAULT 0, 348 row INTEGER NOT NULL, 349 value, 350 PRIMARY KEY(colref, pid, row) 351 );"; 352 $ok = $ok && (bool) $this->sqlite->query($sql); 353 354 return $ok; 355 } 356 357 /** 358 * Add an additional column to the existing data table 359 * 360 * @param int $index the new column index to add 361 * @return bool 362 */ 363 protected function addDataTableColumn($index) { 364 $tbl = 'data_' . $this->table; 365 $sql = " ALTER TABLE $tbl ADD COLUMN col$index DEFAULT ''"; 366 if(! $this->sqlite->query($sql)) { 367 return false; 368 } 369 return true; 370 } 371 372 /** 373 * @param string $user 374 * @return SchemaBuilder 375 */ 376 public function setUser($user) { 377 $this->user = $user; 378 return $this; 379 } 380 381 382} 383