Merge branch 'MDL-76500' of https://github.com/paulholden/moodle
[moodle.git] / lib / xmldb / xmldb_index.php
blob1cc90fa771b8f575c23ff6dc8c45484fa878299e
1 <?php
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.
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/>.
17 /**
18 * This class represent one XMLDB Index
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
26 defined('MOODLE_INTERNAL') || die();
29 class xmldb_index extends xmldb_object {
31 /** @var bool is unique? */
32 protected $unique;
34 /** @var array index fields */
35 protected $fields;
37 /** @var array index hints */
38 protected $hints;
40 /**
41 * Note:
42 * - MySQL: MyISAM has a limit of 1000 bytes for any key including composed, InnoDB has limit 3500 bytes.
44 * @const max length of composed indexes, one utf-8 char is 3 bytes in the worst case
46 const INDEX_COMPOSED_MAX_BYTES = 999;
48 /**
49 * Note:
50 * - MySQL: InnoDB limits size of index on single column to 767bytes (256 chars)
52 * @const single column index length limit, one utf-8 char is 3 bytes in the worst case
54 const INDEX_MAX_BYTES = 765;
56 /**
57 * Creates one new xmldb_index
59 * @param string $name
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
64 public function __construct($name, $type=null, $fields=array(), $hints=array()) {
65 $this->unique = false;
66 $this->fields = array();
67 $this->hints = array();
68 parent::__construct($name);
69 $this->set_attributes($type, $fields, $hints);
72 /**
73 * Set all the attributes of one xmldb_index
75 * @param string type XMLDB_INDEX_UNIQUE, XMLDB_INDEX_NOTUNIQUE
76 * @param array fields an array of fieldnames to build the index over
77 * @param array $hints array of optional hints
79 public function set_attributes($type, $fields, $hints = array()) {
80 $this->unique = !empty($type) ? true : false;
81 $this->fields = $fields;
82 $this->hints = $hints;
85 /**
86 * Get the index unique
87 * @return bool
89 public function getUnique() {
90 return $this->unique;
93 /**
94 * Set the index unique
95 * @param bool $unique
97 public function setUnique($unique = true) {
98 $this->unique = $unique;
102 * Set the index fields
103 * @param array $fields
105 public function setFields($fields) {
106 $this->fields = $fields;
110 * Get the index fields
111 * @return array
113 public function getFields() {
114 return $this->fields;
118 * Set optional index hints.
119 * @param array $hints
121 public function setHints($hints) {
122 $this->hints = $hints;
126 * Returns optional index hints.
127 * @return array
129 public function getHints() {
130 return $this->hints;
134 * Load data from XML to the index
135 * @param $xmlarr array
136 * @return bool
138 public function arr2xmldb_index($xmlarr) {
140 $result = true;
142 // Debug the table
143 // traverse_xmlize($xmlarr); //Debug
144 // print_object ($GLOBALS['traverse_array']); //Debug
145 // $GLOBALS['traverse_array']=""; //Debug
147 // Process key attributes (name, unique, fields, comment, previous, next)
148 if (isset($xmlarr['@']['NAME'])) {
149 $this->name = trim($xmlarr['@']['NAME']);
150 } else {
151 $this->errormsg = 'Missing NAME attribute';
152 $this->debug($this->errormsg);
153 $result = false;
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)';
164 $this->debug($this->errormsg);
165 $result = false;
167 } else {
168 $this->errormsg = 'Undefined UNIQUE attribute';
169 $this->debug($this->errormsg);
170 $result = false;
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);
181 } else {
182 $this->errormsg = 'Incorrect FIELDS attribute (comma separated of fields)';
183 $this->debug($this->errormsg);
184 $result = false;
186 } else {
187 $this->errormsg = 'Empty FIELDS attribute';
188 $this->debug($this->errormsg);
189 $result = false;
191 } else {
192 $this->errormsg = 'Missing FIELDS attribute';
193 $this->debug($this->errormsg);
194 $result = false;
196 // Finally, set the array of fields
197 $this->fields = $fieldsarr;
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);
208 if (isset($xmlarr['@']['COMMENT'])) {
209 $this->comment = trim($xmlarr['@']['COMMENT']);
212 // Set some attributes
213 if ($result) {
214 $this->loaded = true;
216 $this->calculateHash();
217 return $result;
221 * This function calculate and set the hash of one xmldb_index
222 * @retur nvoid, changes $this->hash
224 public function calculateHash($recursive = false) {
225 if (!$this->loaded) {
226 $this->hash = null;
227 } else {
228 $key = $this->unique . implode (', ', $this->fields) . implode (', ', $this->hints);
229 $this->hash = md5($key);
234 *This function will output the XML text for one index
235 * @return string
237 public function xmlOutput() {
238 $o = '';
239 $o.= ' <INDEX NAME="' . $this->name . '"';
240 if ($this->unique) {
241 $unique = 'true';
242 } else {
243 $unique = 'false';
245 $o.= ' UNIQUE="' . $unique . '"';
246 $o.= ' FIELDS="' . implode(', ', $this->fields) . '"';
247 if ($this->hints) {
248 $o.= ' HINTS="' . implode(', ', $this->hints) . '"';
250 if ($this->comment) {
251 $o.= ' COMMENT="' . htmlspecialchars($this->comment, ENT_COMPAT) . '"';
253 $o.= '/>' . "\n";
255 return $o;
259 * This function will set all the attributes of the xmldb_index object
260 * based on information passed in one ADOindex
261 * @param array
262 * @return void
264 public function setFromADOIndex($adoindex) {
266 // Set the unique field
267 $this->unique = false;
268 // Set the fields, converting all them to lowercase
269 $fields = array_flip(array_change_key_case(array_flip($adoindex['columns'])));
270 $this->fields = $fields;
271 // Some more fields
272 $this->loaded = true;
273 $this->changed = true;
277 * Returns the PHP code needed to define one xmldb_index
278 * @return string
280 public function getPHP() {
282 $result = '';
284 // The type
285 $unique = $this->getUnique();
286 if (!empty($unique)) {
287 $result .= 'XMLDB_INDEX_UNIQUE, ';
288 } else {
289 $result .= 'XMLDB_INDEX_NOTUNIQUE, ';
291 // The fields
292 $indexfields = $this->getFields();
293 if (!empty($indexfields)) {
294 $result .= "['". implode("', '", $indexfields) . "']";
295 } else {
296 $result .= 'null';
298 // Hints
299 $hints = $this->getHints();
300 if (!empty($hints)) {
301 $result .= ", ['". implode("', '", $hints) . "']";
304 // Return result
305 return $result;
309 * Shows info in a readable format
310 * @return string
312 public function readableInfo() {
313 $o = '';
314 // unique
315 if ($this->unique) {
316 $o .= 'unique';
317 } else {
318 $o .= 'not unique';
320 // fields
321 $o .= ' (' . implode(', ', $this->fields) . ')';
323 if ($this->hints) {
324 $o .= ' [' . implode(', ', $this->hints) . ']';
327 return $o;
331 * Validates the index restrictions.
333 * The error message should not be localised because it is intended for developers,
334 * end users and admins should never see these problems!
336 * @param xmldb_table $xmldb_table optional when object is table
337 * @return string null if ok, error message if problem found
339 public function validateDefinition(xmldb_table $xmldb_table=null) {
340 if (!$xmldb_table) {
341 return 'Invalid xmldb_index->validateDefinition() call, $xmldb_table is required.';
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;
351 switch ($field->getType()) {
352 case XMLDB_TYPE_INTEGER:
353 $total += 8; // big int
354 break;
356 case XMLDB_TYPE_NUMBER:
357 $total += 12; // this is just a guess
358 break;
360 case XMLDB_TYPE_FLOAT:
361 $total += 8; // double precision
362 break;
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.';
369 $total += ($field->getLength() * 3); // the most complex utf-8 chars have 3 bytes
370 break;
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';
374 break;
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';
378 break;
380 case XMLDB_TYPE_DATETIME:
381 $total += 8; // this is just a guess
382 break;
384 case XMLDB_TYPE_TIMESTAMP:
385 $total += 8; // this is just a guess
386 break;
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.';
395 return null;