Merge pull request #14170 from mlutfy/cart-emails
[civicrm-core.git] / CRM / Core / BAO / SchemaHandler.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2019
32 */
33
34 /**
35 * This file contains functions for creating and altering CiviCRM-tables structure.
36 *
37 * $table = array(
38 * 'name' => TABLE_NAME,
39 * 'attributes' => ATTRIBUTES,
40 * 'fields' => array(
41 * array(
42 * 'name' => FIELD_NAME,
43 * // can be field, index, constraint
44 * 'type' => FIELD_SQL_TYPE,
45 * 'class' => FIELD_CLASS_TYPE,
46 * 'primary' => BOOLEAN,
47 * 'required' => BOOLEAN,
48 * 'searchable' => TRUE,
49 * 'fk_table_name' => FOREIGN_KEY_TABLE_NAME,
50 * 'fk_field_name' => FOREIGN_KEY_FIELD_NAME,
51 * 'comment' => COMMENT,
52 * 'default' => DEFAULT, )
53 * ...
54 * ));
55 */
56 class CRM_Core_BAO_SchemaHandler {
57
58 /**
59 * Create a CiviCRM-table
60 *
61 * @param array $params
62 *
63 * @return bool
64 * TRUE if successfully created, FALSE otherwise
65 *
66 */
67 public static function createTable(&$params) {
68 $sql = self::buildTableSQL($params);
69 // do not i18n-rewrite
70 CRM_Core_DAO::executeQuery($sql, [], TRUE, NULL, FALSE, FALSE);
71
72 $config = CRM_Core_Config::singleton();
73 if ($config->logging) {
74 // logging support
75 $logging = new CRM_Logging_Schema();
76 $logging->fixSchemaDifferencesFor($params['name'], NULL, FALSE);
77 }
78
79 // always do a trigger rebuild for this table
80 CRM_Core_DAO::triggerRebuild($params['name']);
81
82 return TRUE;
83 }
84
85 /**
86 * @param array $params
87 *
88 * @return string
89 */
90 public static function buildTableSQL(&$params) {
91 $sql = "CREATE TABLE {$params['name']} (";
92 if (isset($params['fields']) &&
93 is_array($params['fields'])
94 ) {
95 $separator = "\n";
96 $prefix = NULL;
97 foreach ($params['fields'] as $field) {
98 $sql .= self::buildFieldSQL($field, $separator, $prefix);
99 $separator = ",\n";
100 }
101 foreach ($params['fields'] as $field) {
102 $sql .= self::buildPrimaryKeySQL($field, $separator, $prefix);
103 }
104 foreach ($params['fields'] as $field) {
105 $sql .= self::buildSearchIndexSQL($field, $separator, $prefix);
106 }
107 if (isset($params['indexes'])) {
108 foreach ($params['indexes'] as $index) {
109 $sql .= self::buildIndexSQL($index, $separator, $prefix);
110 }
111 }
112 foreach ($params['fields'] as $field) {
113 $sql .= self::buildForeignKeySQL($field, $separator, $prefix, $params['name']);
114 }
115 }
116 $sql .= "\n) {$params['attributes']};";
117 return $sql;
118 }
119
120 /**
121 * @param array $params
122 * @param $separator
123 * @param $prefix
124 *
125 * @return string
126 */
127 public static function buildFieldSQL(&$params, $separator, $prefix) {
128 $sql = '';
129 $sql .= $separator;
130 $sql .= str_repeat(' ', 8);
131 $sql .= $prefix;
132 $sql .= "`{$params['name']}` {$params['type']}";
133
134 if (!empty($params['required'])) {
135 $sql .= " NOT NULL";
136 }
137
138 if (!empty($params['attributes'])) {
139 $sql .= " {$params['attributes']}";
140 }
141
142 if (!empty($params['default']) &&
143 $params['type'] != 'text'
144 ) {
145 $sql .= " DEFAULT {$params['default']}";
146 }
147
148 if (!empty($params['comment'])) {
149 $sql .= " COMMENT '{$params['comment']}'";
150 }
151
152 return $sql;
153 }
154
155 /**
156 * @param array $params
157 * @param $separator
158 * @param $prefix
159 *
160 * @return NULL|string
161 */
162 public static function buildPrimaryKeySQL(&$params, $separator, $prefix) {
163 $sql = NULL;
164 if (!empty($params['primary'])) {
165 $sql .= $separator;
166 $sql .= str_repeat(' ', 8);
167 $sql .= $prefix;
168 $sql .= "PRIMARY KEY ( {$params['name']} )";
169 }
170 return $sql;
171 }
172
173 /**
174 * @param array $params
175 * @param $separator
176 * @param $prefix
177 * @param bool $indexExist
178 *
179 * @return NULL|string
180 */
181 public static function buildSearchIndexSQL(&$params, $separator, $prefix, $indexExist = FALSE) {
182 $sql = NULL;
183
184 // dont index blob
185 if ($params['type'] == 'text') {
186 return $sql;
187 }
188
189 //create index only for searchable fields during ADD,
190 //create index only if field is become searchable during MODIFY,
191 //drop index only if field is no longer searchable and it does not reference
192 //a forgein key (and indexExist is true)
193 if (!empty($params['searchable']) && !$indexExist) {
194 $sql .= $separator;
195 $sql .= str_repeat(' ', 8);
196 $sql .= $prefix;
197 $sql .= "INDEX_{$params['name']} ( {$params['name']} )";
198 }
199 elseif (empty($params['searchable']) && empty($params['fk_table_name']) && $indexExist) {
200 $sql .= $separator;
201 $sql .= str_repeat(' ', 8);
202 $sql .= "DROP INDEX INDEX_{$params['name']}";
203 }
204 return $sql;
205 }
206
207 /**
208 * @param array $params
209 * @param $separator
210 * @param $prefix
211 *
212 * @return string
213 */
214 public static function buildIndexSQL(&$params, $separator, $prefix) {
215 $sql = '';
216 $sql .= $separator;
217 $sql .= str_repeat(' ', 8);
218 if ($params['unique']) {
219 $sql .= 'UNIQUE INDEX';
220 $indexName = 'unique';
221 }
222 else {
223 $sql .= 'INDEX';
224 $indexName = 'index';
225 }
226 $indexFields = NULL;
227
228 foreach ($params as $name => $value) {
229 if (substr($name, 0, 11) == 'field_name_') {
230 $indexName .= "_{$value}";
231 $indexFields .= " $value,";
232 }
233 }
234 $indexFields = substr($indexFields, 0, -1);
235
236 $sql .= " $indexName ( $indexFields )";
237 return $sql;
238 }
239
240 /**
241 * @param string $tableName
242 * @param string $fkTableName
243 *
244 * @return bool
245 */
246 public static function changeFKConstraint($tableName, $fkTableName) {
247 $fkName = "{$tableName}_entity_id";
248 if (strlen($fkName) >= 48) {
249 $fkName = substr($fkName, 0, 32) . "_" . substr(md5($fkName), 0, 16);
250 }
251 $dropFKSql = "
252 ALTER TABLE {$tableName}
253 DROP FOREIGN KEY `FK_{$fkName}`;";
254
255 CRM_Core_DAO::executeQuery($dropFKSql);
256
257 $addFKSql = "
258 ALTER TABLE {$tableName}
259 ADD CONSTRAINT `FK_{$fkName}` FOREIGN KEY (`entity_id`) REFERENCES {$fkTableName} (`id`) ON DELETE CASCADE;";
260 // CRM-7007: do not i18n-rewrite this query
261 CRM_Core_DAO::executeQuery($addFKSql, [], TRUE, NULL, FALSE, FALSE);
262
263 return TRUE;
264 }
265
266 /**
267 * @param array $params
268 * @param $separator
269 * @param $prefix
270 * @param string $tableName
271 *
272 * @return NULL|string
273 */
274 public static function buildForeignKeySQL(&$params, $separator, $prefix, $tableName) {
275 $sql = NULL;
276 if (!empty($params['fk_table_name']) && !empty($params['fk_field_name'])) {
277 $sql .= $separator;
278 $sql .= str_repeat(' ', 8);
279 $sql .= $prefix;
280 $fkName = "{$tableName}_{$params['name']}";
281 if (strlen($fkName) >= 48) {
282 $fkName = substr($fkName, 0, 32) . "_" . substr(md5($fkName), 0, 16);
283 }
284
285 $sql .= "CONSTRAINT FK_$fkName FOREIGN KEY ( `{$params['name']}` ) REFERENCES {$params['fk_table_name']} ( {$params['fk_field_name']} ) ";
286 $sql .= CRM_Utils_Array::value('fk_attributes', $params);
287 }
288 return $sql;
289 }
290
291 /**
292 * @param array $params
293 * @param bool $indexExist
294 * @param bool $triggerRebuild
295 *
296 * @return bool
297 */
298 public static function alterFieldSQL(&$params, $indexExist = FALSE, $triggerRebuild = TRUE) {
299 $sql = str_repeat(' ', 8);
300 $sql .= "ALTER TABLE {$params['table_name']}";
301
302 // lets suppress the required flag, since that can cause sql issue
303 $params['required'] = FALSE;
304
305 switch ($params['operation']) {
306 case 'add':
307 $separator = "\n";
308 $prefix = "ADD ";
309 $sql .= self::buildFieldSQL($params, $separator, "ADD COLUMN ");
310 $separator = ",\n";
311 $sql .= self::buildPrimaryKeySQL($params, $separator, "ADD PRIMARY KEY ");
312 $sql .= self::buildSearchIndexSQL($params, $separator, "ADD INDEX ");
313 $sql .= self::buildForeignKeySQL($params, $separator, "ADD ", $params['table_name']);
314 break;
315
316 case 'modify':
317 $separator = "\n";
318 $prefix = "MODIFY ";
319 $sql .= self::buildFieldSQL($params, $separator, $prefix);
320 $separator = ",\n";
321 $sql .= self::buildSearchIndexSQL($params, $separator, "ADD INDEX ", $indexExist);
322 break;
323
324 case 'delete':
325 $sql .= " DROP COLUMN `{$params['name']}`";
326 if (!empty($params['primary'])) {
327 $sql .= ", DROP PRIMARY KEY";
328 }
329 if (!empty($params['fk_table_name'])) {
330 $sql .= ", DROP FOREIGN KEY FK_{$params['fkName']}";
331 }
332 break;
333 }
334
335 // CRM-7007: do not i18n-rewrite this query
336 CRM_Core_DAO::executeQuery($sql, [], TRUE, NULL, FALSE, FALSE);
337
338 $config = CRM_Core_Config::singleton();
339 if ($config->logging) {
340 // CRM-16717 not sure why this was originally limited to add.
341 // For example custom tables can have field length changes - which need to flow through to logging.
342 // Are there any modifies we DON'T was to call this function for (& shouldn't it be clever enough to cope?)
343 if ($params['operation'] == 'add' || $params['operation'] == 'modify') {
344 $logging = new CRM_Logging_Schema();
345 $logging->fixSchemaDifferencesFor($params['table_name'], [trim($prefix) => [$params['name']]], FALSE);
346 }
347 }
348
349 if ($triggerRebuild) {
350 CRM_Core_DAO::triggerRebuild($params['table_name']);
351 }
352
353 return TRUE;
354 }
355
356 /**
357 * Delete a CiviCRM-table.
358 *
359 * @param string $tableName
360 * Name of the table to be created.
361 */
362 public static function dropTable($tableName) {
363 $sql = "DROP TABLE $tableName";
364 CRM_Core_DAO::executeQuery($sql);
365 }
366
367 /**
368 * @param string $tableName
369 * @param string $columnName
370 * @param bool $l18n
371 * @param bool $isUpgradeMode
372 *
373 */
374 public static function dropColumn($tableName, $columnName, $l18n = FALSE, $isUpgradeMode = FALSE) {
375 if (self::checkIfFieldExists($tableName, $columnName)) {
376 $sql = "ALTER TABLE $tableName DROP COLUMN $columnName";
377 if ($l18n) {
378 CRM_Core_DAO::executeQuery($sql);
379 }
380 else {
381 CRM_Core_DAO::executeQuery($sql, [], TRUE, NULL, FALSE, FALSE);
382 }
383 $domain = new CRM_Core_DAO_Domain();
384 $domain->find(TRUE);
385 if ($domain->locales) {
386 $locales = explode(CRM_Core_DAO::VALUE_SEPARATOR, $domain->locales);
387 CRM_Core_I18n_Schema::rebuildMultilingualSchema($locales, NULL, $isUpgradeMode);
388 }
389 }
390 }
391
392 /**
393 * @param string $tableName
394 * @param bool $dropUnique
395 */
396 public static function changeUniqueToIndex($tableName, $dropUnique = TRUE) {
397 if ($dropUnique) {
398 $sql = "ALTER TABLE $tableName
399 DROP INDEX `unique_entity_id` ,
400 ADD INDEX `FK_{$tableName}_entity_id` ( `entity_id` )";
401 }
402 else {
403 $sql = " ALTER TABLE $tableName
404 DROP INDEX `FK_{$tableName}_entity_id` ,
405 ADD UNIQUE INDEX `unique_entity_id` ( `entity_id` )";
406 }
407 CRM_Core_DAO::executeQuery($sql);
408 }
409
410 /**
411 * Create indexes.
412 *
413 * @param $tables
414 * Tables to create index for in the format:
415 * array('civicrm_entity_table' => 'entity_id')
416 * OR
417 * array('civicrm_entity_table' => array('entity_id', 'entity_table'))
418 * The latter will create a combined index on the 2 keys (in order).
419 *
420 * Side note - when creating combined indexes the one with the most variation
421 * goes first - so entity_table always goes after entity_id.
422 *
423 * It probably makes sense to consider more sophisticated options at some point
424 * but at the moment this is only being as enhanced as fast as the test is.
425 *
426 * @todo add support for length & multilingual on combined keys.
427 *
428 * @param string $createIndexPrefix
429 * @param array $substrLengths
430 */
431 public static function createIndexes($tables, $createIndexPrefix = 'index', $substrLengths = []) {
432 $queries = [];
433 $domain = new CRM_Core_DAO_Domain();
434 $domain->find(TRUE);
435 $locales = explode(CRM_Core_DAO::VALUE_SEPARATOR, $domain->locales);
436
437 // if we're multilingual, cache the information on internationalised fields
438 static $columns = NULL;
439 if (!CRM_Utils_System::isNull($locales) and $columns === NULL) {
440 $columns = CRM_Core_I18n_SchemaStructure::columns();
441 }
442
443 foreach ($tables as $table => $fields) {
444 $query = "SHOW INDEX FROM $table";
445 $dao = CRM_Core_DAO::executeQuery($query);
446
447 $currentIndexes = [];
448 while ($dao->fetch()) {
449 $currentIndexes[] = $dao->Key_name;
450 }
451
452 // now check for all fields if the index exists
453 foreach ($fields as $field) {
454 $fieldName = implode('_', (array) $field);
455
456 if (is_array($field)) {
457 // No support for these for combined indexes as yet - add a test when you
458 // want to add that.
459 $lengthName = '';
460 $lengthSize = '';
461 }
462 else {
463 // handle indices over substrings, CRM-6245
464 // $lengthName is appended to index name, $lengthSize is the field size modifier
465 $lengthName = isset($substrLengths[$table][$fieldName]) ? "_{$substrLengths[$table][$fieldName]}" : '';
466 $lengthSize = isset($substrLengths[$table][$fieldName]) ? "({$substrLengths[$table][$fieldName]})" : '';
467 }
468
469 $names = [
470 "index_{$fieldName}{$lengthName}",
471 "FK_{$table}_{$fieldName}{$lengthName}",
472 "UI_{$fieldName}{$lengthName}",
473 "{$createIndexPrefix}_{$fieldName}{$lengthName}",
474 ];
475
476 // skip to the next $field if one of the above $names exists; handle multilingual for CRM-4126
477 foreach ($names as $name) {
478 $regex = '/^' . preg_quote($name) . '(_[a-z][a-z]_[A-Z][A-Z])?$/';
479 if (preg_grep($regex, $currentIndexes)) {
480 continue 2;
481 }
482 }
483
484 // the index doesn't exist, so create it
485 // if we're multilingual and the field is internationalised, do it for every locale
486 // @todo remove is_array check & add multilingual support for combined indexes and add a test.
487 // Note combined indexes currently using this function are on fields like
488 // entity_id + entity_table which are not multilingual.
489 if (!is_array($field) && !CRM_Utils_System::isNull($locales) and isset($columns[$table][$fieldName])) {
490 foreach ($locales as $locale) {
491 $queries[] = "CREATE INDEX {$createIndexPrefix}_{$fieldName}{$lengthName}_{$locale} ON {$table} ({$fieldName}_{$locale}{$lengthSize})";
492 }
493 }
494 else {
495 $queries[] = "CREATE INDEX {$createIndexPrefix}_{$fieldName}{$lengthName} ON {$table} (" . implode(',', (array) $field) . "{$lengthSize})";
496 }
497 }
498 }
499
500 // run the queries without i18n-rewriting
501 $dao = new CRM_Core_DAO();
502 foreach ($queries as $query) {
503 $dao->query($query, FALSE);
504 }
505 }
506
507 /**
508 * Get indexes for tables
509 * @param array $tables
510 * array of table names to find indexes for
511 *
512 * @return array('tableName' => array('index1', 'index2'))
513 */
514 public static function getIndexes($tables) {
515 $indexes = [];
516 foreach ($tables as $table) {
517 $query = "SHOW INDEX FROM $table";
518 $dao = CRM_Core_DAO::executeQuery($query);
519
520 $tableIndexes = [];
521 while ($dao->fetch()) {
522 $tableIndexes[$dao->Key_name]['name'] = $dao->Key_name;
523 $tableIndexes[$dao->Key_name]['field'][] = $dao->Column_name .
524 ($dao->Sub_part ? '(' . $dao->Sub_part . ')' : '');
525 $tableIndexes[$dao->Key_name]['unique'] = ($dao->Non_unique == 0 ? 1 : 0);
526 }
527 $indexes[$table] = $tableIndexes;
528 }
529 return $indexes;
530 }
531
532 /**
533 * Drop an index if one by that name exists.
534 *
535 * @param string $tableName
536 * @param string $indexName
537 */
538 public static function dropIndexIfExists($tableName, $indexName) {
539 if (self::checkIfIndexExists($tableName, $indexName)) {
540 CRM_Core_DAO::executeQuery("DROP INDEX $indexName ON $tableName");
541 }
542 }
543
544 /**
545 * @param int $customFieldID
546 * @param string $tableName
547 * @param string $columnName
548 * @param $length
549 *
550 * @throws Exception
551 */
552 public static function alterFieldLength($customFieldID, $tableName, $columnName, $length) {
553 // first update the custom field tables
554 $sql = "
555 UPDATE civicrm_custom_field
556 SET text_length = %1
557 WHERE id = %2
558 ";
559 $params = [
560 1 => [$length, 'Integer'],
561 2 => [$customFieldID, 'Integer'],
562 ];
563 CRM_Core_DAO::executeQuery($sql, $params);
564
565 $sql = "
566 SELECT is_required, default_value
567 FROM civicrm_custom_field
568 WHERE id = %2
569 ";
570 $dao = CRM_Core_DAO::executeQuery($sql, $params);
571
572 if ($dao->fetch()) {
573 $clause = '';
574
575 if ($dao->is_required) {
576 $clause = " NOT NULL";
577 }
578
579 if (!empty($dao->default_value)) {
580 $clause .= " DEFAULT '{$dao->default_value}'";
581 }
582 // now modify the column
583 $sql = "
584 ALTER TABLE {$tableName}
585 MODIFY {$columnName} varchar( $length )
586 $clause
587 ";
588 CRM_Core_DAO::executeQuery($sql);
589 }
590 else {
591 CRM_Core_Error::fatal(ts('Could Not Find Custom Field Details for %1, %2, %3',
592 [
593 1 => $tableName,
594 2 => $columnName,
595 3 => $customFieldID,
596 ]
597 ));
598 }
599 }
600
601 /**
602 * Check if the table has an index matching the name.
603 *
604 * @param string $tableName
605 * @param array $indexName
606 *
607 * @return bool
608 */
609 public static function checkIfIndexExists($tableName, $indexName) {
610 $result = CRM_Core_DAO::executeQuery(
611 "SHOW INDEX FROM $tableName WHERE key_name = %1 AND seq_in_index = 1",
612 [1 => [$indexName, 'String']]
613 );
614 if ($result->fetch()) {
615 return TRUE;
616 }
617 return FALSE;
618 }
619
620 /**
621 * Check if the table has a specified column.
622 *
623 * @param string $tableName
624 * @param string $columnName
625 * @param bool $i18nRewrite
626 * Whether to rewrite the query on multilingual setups.
627 *
628 * @return bool
629 */
630 public static function checkIfFieldExists($tableName, $columnName, $i18nRewrite = TRUE) {
631 $query = "SHOW COLUMNS FROM $tableName LIKE '%1'";
632 $dao = CRM_Core_DAO::executeQuery($query, [1 => [$columnName, 'Alphanumeric']], TRUE, NULL, FALSE, $i18nRewrite);
633 $result = $dao->fetch() ? TRUE : FALSE;
634 return $result;
635 }
636
637 /**
638 * Check if a foreign key Exists
639 * @param string $table_name
640 * @param string $constraint_name
641 * @return bool TRUE if FK is found
642 */
643 public static function checkFKExists($table_name, $constraint_name) {
644 $config = CRM_Core_Config::singleton();
645 $dbUf = DB::parseDSN($config->dsn);
646 $query = "
647 SELECT CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
648 WHERE TABLE_SCHEMA = %1
649 AND TABLE_NAME = %2
650 AND CONSTRAINT_NAME = %3
651 AND CONSTRAINT_TYPE = 'FOREIGN KEY'
652 ";
653 $params = [
654 1 => [$dbUf['database'], 'String'],
655 2 => [$table_name, 'String'],
656 3 => [$constraint_name, 'String'],
657 ];
658 $dao = CRM_Core_DAO::executeQuery($query, $params);
659
660 if ($dao->fetch()) {
661 return TRUE;
662 }
663 return FALSE;
664 }
665
666 /**
667 * Remove a foreign key from a table if it exists.
668 *
669 * @param $table_name
670 * @param $constraint_name
671 *
672 * @return bool
673 */
674 public static function safeRemoveFK($table_name, $constraint_name) {
675 if (self::checkFKExists($table_name, $constraint_name)) {
676 CRM_Core_DAO::executeQuery("ALTER TABLE {$table_name} DROP FOREIGN KEY {$constraint_name}", []);
677 return TRUE;
678 }
679 return FALSE;
680 }
681
682 /**
683 * Add index signature hash to DAO file calculation.
684 *
685 * @param string $table table name
686 * @param array $indices index array spec
687 */
688 public static function addIndexSignature($table, &$indices) {
689 foreach ($indices as $indexName => $index) {
690 $indices[$indexName]['sig'] = $table . "::" .
691 (array_key_exists('unique', $index) ? $index['unique'] : 0) . "::" .
692 implode("::", $index['field']);
693 }
694 }
695
696 /**
697 * Compare the indices specified in the XML files with those in the DB.
698 *
699 * @param bool $dropFalseIndices
700 * If set - this function deletes false indices present in the DB which mismatches the expected
701 * values of xml file so that civi re-creates them with correct values using createMissingIndices() function.
702 *
703 * @return array
704 * index specifications
705 */
706 public static function getMissingIndices($dropFalseIndices = FALSE) {
707 $requiredSigs = $existingSigs = [];
708 // Get the indices defined (originally) in the xml files
709 $requiredIndices = CRM_Core_DAO_AllCoreTables::indices();
710 $reqSigs = [];
711 foreach ($requiredIndices as $table => $indices) {
712 $reqSigs[] = CRM_Utils_Array::collect('sig', $indices);
713 }
714 CRM_Utils_Array::flatten($reqSigs, $requiredSigs);
715
716 // Get the indices in the database
717 $existingIndices = CRM_Core_BAO_SchemaHandler::getIndexes(array_keys($requiredIndices));
718 $extSigs = [];
719 foreach ($existingIndices as $table => $indices) {
720 CRM_Core_BAO_SchemaHandler::addIndexSignature($table, $indices);
721 $extSigs[] = CRM_Utils_Array::collect('sig', $indices);
722 }
723 CRM_Utils_Array::flatten($extSigs, $existingSigs);
724
725 // Compare
726 $missingSigs = array_diff($requiredSigs, $existingSigs);
727
728 //CRM-20774 - Drop index key which exist in db but the value varies.
729 $existingKeySigs = array_intersect_key($missingSigs, $existingSigs);
730 if ($dropFalseIndices && !empty($existingKeySigs)) {
731 foreach ($existingKeySigs as $sig) {
732 $sigParts = explode('::', $sig);
733 foreach ($requiredIndices[$sigParts[0]] as $index) {
734 if ($index['sig'] == $sig && !empty($index['name'])) {
735 self::dropIndexIfExists($sigParts[0], $index['name']);
736 continue;
737 }
738 }
739 }
740 }
741
742 // Get missing indices
743 $missingIndices = [];
744 foreach ($missingSigs as $sig) {
745 $sigParts = explode('::', $sig);
746 if (array_key_exists($sigParts[0], $requiredIndices)) {
747 foreach ($requiredIndices[$sigParts[0]] as $index) {
748 if ($index['sig'] == $sig) {
749 $missingIndices[$sigParts[0]][] = $index;
750 continue;
751 }
752 }
753 }
754 }
755 return $missingIndices;
756 }
757
758 /**
759 * Create missing indices.
760 *
761 * @param array $missingIndices as returned by getMissingIndices()
762 */
763 public static function createMissingIndices($missingIndices) {
764 $queries = [];
765 foreach ($missingIndices as $table => $indexList) {
766 foreach ($indexList as $index) {
767 $queries[] = "CREATE " .
768 (array_key_exists('unique', $index) && $index['unique'] ? 'UNIQUE ' : '') .
769 "INDEX {$index['name']} ON {$table} (" .
770 implode(", ", $index['field']) .
771 ")";
772 }
773 }
774
775 /* FIXME potential problem if index name already exists, so check before creating */
776 $dao = new CRM_Core_DAO();
777 foreach ($queries as $query) {
778 $dao->query($query, FALSE);
779 }
780 }
781
782 }