MDL-62783 XMLDB: Generate PHP with [] arrays
[moodle.git] / lib / xmldb / xmldb_index.php
CommitLineData
4a0e2e63 1<?php
94417438
PS
2// This file is part of Moodle - http://moodle.org/
3//
4// Moodle is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8//
9// Moodle is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12// GNU General Public License for more details.
13//
14// You should have received a copy of the GNU General Public License
15// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
16
17/**
18 * This class represent one XMLDB Index
19 *
20 * @package core_xmldb
21 * @copyright 1999 onwards Martin Dougiamas http://dougiamas.com
22 * 2001-3001 Eloy Lafuente (stronk7) http://contiento.com
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24 */
25
26defined('MOODLE_INTERNAL') || die();
8165877a 27
8165877a 28
a8cb94f6 29class xmldb_index extends xmldb_object {
eef868d1 30
94417438 31 /** @var bool is unique? */
ef7c3f10 32 protected $unique;
94417438
PS
33
34 /** @var array index fields */
ef7c3f10 35 protected $fields;
8165877a 36
bd991d03
PS
37 /** @var array index hints */
38 protected $hints;
39
b2cfdcf6
PS
40 /**
41 * Note:
42 * - MySQL: MyISAM has a limit of 1000 bytes for any key including composed, InnoDB has limit 3500 bytes.
43 *
44 * @const max length of composed indexes, one utf-8 char is 3 bytes in the worst case
45 */
46 const INDEX_COMPOSED_MAX_BYTES = 999;
47
48 /**
49 * Note:
50 * - MySQL: InnoDB limits size of index on single column to 767bytes (256 chars)
51 *
52 * @const single column index length limit, one utf-8 char is 3 bytes in the worst case
53 */
54 const INDEX_MAX_BYTES = 765;
55
8165877a 56 /**
a8cb94f6 57 * Creates one new xmldb_index
94417438
PS
58 *
59 * @param string $name
bd991d03
PS
60 * @param string $type XMLDB_INDEX_UNIQUE, XMLDB_INDEX_NOTUNIQUE
61 * @param array $fields an array of fieldnames to build the index over
62 * @param array $hints an array of optional hints
8165877a 63 */
bd991d03 64 public function __construct($name, $type=null, $fields=array(), $hints=array()) {
8165877a 65 $this->unique = false;
66 $this->fields = array();
bd991d03 67 $this->hints = array();
69b80cc2 68 parent::__construct($name);
661dd35d 69 $this->set_attributes($type, $fields, $hints);
8165877a 70 }
71
76fd4736 72 /**
a8cb94f6 73 * Set all the attributes of one xmldb_index
76fd4736 74 *
75 * @param string type XMLDB_INDEX_UNIQUE, XMLDB_INDEX_NOTUNIQUE
76 * @param array fields an array of fieldnames to build the index over
bd991d03 77 * @param array $hints array of optional hints
76fd4736 78 */
bd991d03 79 public function set_attributes($type, $fields, $hints = array()) {
b0d84443 80 $this->unique = !empty($type) ? true : false;
76fd4736 81 $this->fields = $fields;
bd991d03 82 $this->hints = $hints;
76fd4736 83 }
8165877a 84
76fd4736 85 /**
86 * Get the index unique
94417438 87 * @return bool
76fd4736 88 */
aaddfac5 89 public function getUnique() {
76fd4736 90 return $this->unique;
91 }
92
93 /**
94 * Set the index unique
94417438 95 * @param bool $unique
76fd4736 96 */
aaddfac5 97 public function setUnique($unique = true) {
76fd4736 98 $this->unique = $unique;
99 }
8165877a 100
101 /**
102 * Set the index fields
94417438 103 * @param array $fields
8165877a 104 */
aaddfac5 105 public function setFields($fields) {
8165877a 106 $this->fields = $fields;
107 }
108
eef868d1 109 /**
8165877a 110 * Get the index fields
a6d9d4ef 111 * @return array
8165877a 112 */
aaddfac5 113 public function getFields() {
8165877a 114 return $this->fields;
115 }
116
bd991d03
PS
117 /**
118 * Set optional index hints.
119 * @param array $hints
120 */
121 public function setHints($hints) {
122 $this->hints = $hints;
123 }
124
125 /**
126 * Returns optional index hints.
127 * @return array
128 */
129 public function getHints() {
130 return $this->hints;
131 }
132
8165877a 133 /**
134 * Load data from XML to the index
94417438
PS
135 * @param $xmlarr array
136 * @return bool
8165877a 137 */
aaddfac5 138 public function arr2xmldb_index($xmlarr) {
8165877a 139
140 $result = true;
141
94417438
PS
142 // Debug the table
143 // traverse_xmlize($xmlarr); //Debug
144 // print_object ($GLOBALS['traverse_array']); //Debug
145 // $GLOBALS['traverse_array']=""; //Debug
8165877a 146
94417438 147 // Process key attributes (name, unique, fields, comment, previous, next)
8165877a 148 if (isset($xmlarr['@']['NAME'])) {
149 $this->name = trim($xmlarr['@']['NAME']);
150 } else {
151 $this->errormsg = 'Missing NAME attribute';
5bbe4831 152 $this->debug($this->errormsg);
8165877a 153 $result = false;
154 }
155
156 if (isset($xmlarr['@']['UNIQUE'])) {
157 $unique = strtolower(trim($xmlarr['@']['UNIQUE']));
158 if ($unique == 'true') {
159 $this->unique = true;
160 } else if ($unique == 'false') {
161 $this->unique = false;
162 } else {
163 $this->errormsg = 'Incorrect UNIQUE attribute (true/false allowed)';
5bbe4831 164 $this->debug($this->errormsg);
8165877a 165 $result = false;
166 }
167 } else {
168 $this->errormsg = 'Undefined UNIQUE attribute';
5bbe4831 169 $this->debug($this->errormsg);
8165877a 170 $result = false;
171 }
eef868d1 172
8165877a 173 if (isset($xmlarr['@']['FIELDS'])) {
174 $fields = strtolower(trim($xmlarr['@']['FIELDS']));
175 if ($fields) {
176 $fieldsarr = explode(',',$fields);
177 if ($fieldsarr) {
178 foreach ($fieldsarr as $key => $element) {
179 $fieldsarr [$key] = trim($element);
180 }
181 } else {
182 $this->errormsg = 'Incorrect FIELDS attribute (comma separated of fields)';
5bbe4831 183 $this->debug($this->errormsg);
8165877a 184 $result = false;
185 }
186 } else {
187 $this->errormsg = 'Empty FIELDS attribute';
5bbe4831 188 $this->debug($this->errormsg);
8165877a 189 $result = false;
190 }
191 } else {
192 $this->errormsg = 'Missing FIELDS attribute';
5bbe4831 193 $this->debug($this->errormsg);
8165877a 194 $result = false;
195 }
94417438 196 // Finally, set the array of fields
8165877a 197 $this->fields = $fieldsarr;
198
bd991d03
PS
199 if (isset($xmlarr['@']['HINTS'])) {
200 $this->hints = array();
201 $hints = strtolower(trim($xmlarr['@']['HINTS']));
202 if ($hints !== '') {
203 $hints = explode(',', $hints);
204 $this->hints = array_map('trim', $hints);
205 }
206 }
207
8165877a 208 if (isset($xmlarr['@']['COMMENT'])) {
209 $this->comment = trim($xmlarr['@']['COMMENT']);
210 }
211
94417438 212 // Set some attributes
8165877a 213 if ($result) {
214 $this->loaded = true;
215 }
216 $this->calculateHash();
217 return $result;
218 }
219
220 /**
a8cb94f6 221 * This function calculate and set the hash of one xmldb_index
94417438 222 * @retur nvoid, changes $this->hash
8165877a 223 */
aaddfac5 224 public function calculateHash($recursive = false) {
8165877a 225 if (!$this->loaded) {
002252f7 226 $this->hash = null;
8165877a 227 } else {
bd991d03 228 $key = $this->unique . implode (', ', $this->fields) . implode (', ', $this->hints);
8165877a 229 $this->hash = md5($key);
230 }
231 }
232
eef868d1 233 /**
8165877a 234 *This function will output the XML text for one index
94417438 235 * @return string
8165877a 236 */
aaddfac5 237 public function xmlOutput() {
8165877a 238 $o = '';
239 $o.= ' <INDEX NAME="' . $this->name . '"';
240 if ($this->unique) {
241 $unique = 'true';
242 } else {
243 $unique = 'false';
244 }
245 $o.= ' UNIQUE="' . $unique . '"';
246 $o.= ' FIELDS="' . implode(', ', $this->fields) . '"';
bd991d03
PS
247 if ($this->hints) {
248 $o.= ' HINTS="' . implode(', ', $this->hints) . '"';
249 }
8165877a 250 if ($this->comment) {
251 $o.= ' COMMENT="' . htmlspecialchars($this->comment) . '"';
252 }
8165877a 253 $o.= '/>' . "\n";
254
255 return $o;
256 }
257
258 /**
a8cb94f6 259 * This function will set all the attributes of the xmldb_index object
8165877a 260 * based on information passed in one ADOindex
94417438
PS
261 * @param array
262 * @return void
8165877a 263 */
aaddfac5 264 public function setFromADOIndex($adoindex) {
8165877a 265
94417438 266 // Set the unique field
8165877a 267 $this->unique = false;
94417438 268 // Set the fields, converting all them to lowercase
470617ba 269 $fields = array_flip(array_change_key_case(array_flip($adoindex['columns'])));
270 $this->fields = $fields;
94417438 271 // Some more fields
8165877a 272 $this->loaded = true;
273 $this->changed = true;
274 }
275
aed4e527 276 /**
a8cb94f6 277 * Returns the PHP code needed to define one xmldb_index
94417438 278 * @return string
aed4e527 279 */
aaddfac5 280 public function getPHP() {
aed4e527 281
282 $result = '';
283
94417438 284 // The type
aed4e527 285 $unique = $this->getUnique();
286 if (!empty($unique)) {
287 $result .= 'XMLDB_INDEX_UNIQUE, ';
288 } else {
289 $result .= 'XMLDB_INDEX_NOTUNIQUE, ';
290 }
94417438 291 // The fields
aed4e527 292 $indexfields = $this->getFields();
293 if (!empty($indexfields)) {
f4e18a0a 294 $result .= "['". implode("', '", $indexfields) . "']";
aed4e527 295 } else {
296 $result .= 'null';
297 }
bd991d03
PS
298 // Hints
299 $hints = $this->getHints();
300 if (!empty($hints)) {
f4e18a0a 301 $result .= ", ['". implode("', '", $hints) . "']";
bd991d03
PS
302 }
303
94417438 304 // Return result
aed4e527 305 return $result;
306 }
307
eef868d1 308 /**
8165877a 309 * Shows info in a readable format
94417438 310 * @return string
8165877a 311 */
aaddfac5 312 public function readableInfo() {
8165877a 313 $o = '';
94417438 314 // unique
8165877a 315 if ($this->unique) {
316 $o .= 'unique';
317 } else {
318 $o .= 'not unique';
319 }
94417438 320 // fields
8165877a 321 $o .= ' (' . implode(', ', $this->fields) . ')';
322
bd991d03
PS
323 if ($this->hints) {
324 $o .= ' [' . implode(', ', $this->hints) . ']';
325 }
326
8165877a 327 return $o;
328 }
b2cfdcf6
PS
329
330 /**
331 * Validates the index restrictions.
332 *
333 * The error message should not be localised because it is intended for developers,
334 * end users and admins should never see these problems!
335 *
336 * @param xmldb_table $xmldb_table optional when object is table
337 * @return string null if ok, error message if problem found
338 */
aaddfac5 339 public function validateDefinition(xmldb_table $xmldb_table=null) {
b2cfdcf6
PS
340 if (!$xmldb_table) {
341 return 'Invalid xmldb_index->validateDefinition() call, $xmldb_table si required.';
342 }
343
344 $total = 0;
345 foreach ($this->getFields() as $fieldname) {
346 if (!$field = $xmldb_table->getField($fieldname)) {
347 // argh, we do not have the fields loaded yet, this should not happen during install
348 continue;
349 }
350
351 switch ($field->getType()) {
352 case XMLDB_TYPE_INTEGER:
353 $total += 8; // big int
b1c1eeae 354 break;
b2cfdcf6
PS
355
356 case XMLDB_TYPE_NUMBER:
357 $total += 12; // this is just a guess
b1c1eeae 358 break;
b2cfdcf6
PS
359
360 case XMLDB_TYPE_FLOAT:
361 $total += 8; // double precision
b1c1eeae 362 break;
b2cfdcf6
PS
363
364 case XMLDB_TYPE_CHAR:
365 if ($field->getLength() > self::INDEX_MAX_BYTES / 3) {
366 return 'Invalid index definition in table {'.$xmldb_table->getName(). '}: XMLDB_TYPE_CHAR field "'.$field->getName().'" can not be indexed because it is too long.'
367 .' Limit is '.(self::INDEX_MAX_BYTES/3).' chars.';
368 }
369 $total += ($field->getLength() * 3); // the most complex utf-8 chars have 3 bytes
b1c1eeae 370 break;
b2cfdcf6
PS
371
372 case XMLDB_TYPE_TEXT:
373 return 'Invalid index definition in table {'.$xmldb_table->getName(). '}: XMLDB_TYPE_TEXT field "'.$field->getName().'" can not be indexed';
b1c1eeae 374 break;
b2cfdcf6
PS
375
376 case XMLDB_TYPE_BINARY:
377 return 'Invalid index definition in table {'.$xmldb_table->getName(). '}: XMLDB_TYPE_BINARY field "'.$field->getName().'" can not be indexed';
b1c1eeae 378 break;
b2cfdcf6
PS
379
380 case XMLDB_TYPE_DATETIME:
381 $total += 8; // this is just a guess
b1c1eeae 382 break;
b2cfdcf6
PS
383
384 case XMLDB_TYPE_TIMESTAMP:
385 $total += 8; // this is just a guess
b1c1eeae 386 break;
b2cfdcf6
PS
387 }
388 }
389
390 if ($total > self::INDEX_COMPOSED_MAX_BYTES) {
391 return 'Invalid index definition in table {'.$xmldb_table->getName(). '}: the composed index on fields "'.implode(',', $this->getFields()).'" is too long.'
392 .' Limit is '.self::INDEX_COMPOSED_MAX_BYTES.' bytes / '.(self::INDEX_COMPOSED_MAX_BYTES/3).' chars.';
393 }
394
395 return null;
396 }
8165877a 397}