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