3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
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. |
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. |
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 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2019
35 * This file contains functions for creating and altering CiviCRM-tables structure.
38 * 'name' => TABLE_NAME,
39 * 'attributes' => ATTRIBUTES,
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, )
56 class CRM_Core_BAO_SchemaHandler
{
59 * Create a CiviCRM-table
61 * @param array $params
64 * TRUE if successfully created, FALSE otherwise
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);
72 $config = CRM_Core_Config
::singleton();
73 if ($config->logging
) {
75 $logging = new CRM_Logging_Schema();
76 $logging->fixSchemaDifferencesFor($params['name'], NULL, FALSE);
79 // always do a trigger rebuild for this table
80 CRM_Core_DAO
::triggerRebuild($params['name']);
86 * @param array $params
90 public static function buildTableSQL(&$params) {
91 $sql = "CREATE TABLE {$params['name']} (";
92 if (isset($params['fields']) &&
93 is_array($params['fields'])
97 foreach ($params['fields'] as $field) {
98 $sql .= self
::buildFieldSQL($field, $separator, $prefix);
101 foreach ($params['fields'] as $field) {
102 $sql .= self
::buildPrimaryKeySQL($field, $separator, $prefix);
104 foreach ($params['fields'] as $field) {
105 $sql .= self
::buildSearchIndexSQL($field, $separator, $prefix);
107 if (isset($params['indexes'])) {
108 foreach ($params['indexes'] as $index) {
109 $sql .= self
::buildIndexSQL($index, $separator, $prefix);
112 foreach ($params['fields'] as $field) {
113 $sql .= self
::buildForeignKeySQL($field, $separator, $prefix, $params['name']);
116 $sql .= "\n) {$params['attributes']};";
121 * @param array $params
127 public static function buildFieldSQL(&$params, $separator, $prefix) {
130 $sql .= str_repeat(' ', 8);
132 $sql .= "`{$params['name']}` {$params['type']}";
134 if (!empty($params['required'])) {
138 if (!empty($params['attributes'])) {
139 $sql .= " {$params['attributes']}";
142 if (!empty($params['default']) &&
143 $params['type'] != 'text'
145 $sql .= " DEFAULT {$params['default']}";
148 if (!empty($params['comment'])) {
149 $sql .= " COMMENT '{$params['comment']}'";
156 * @param array $params
160 * @return NULL|string
162 public static function buildPrimaryKeySQL(&$params, $separator, $prefix) {
164 if (!empty($params['primary'])) {
166 $sql .= str_repeat(' ', 8);
168 $sql .= "PRIMARY KEY ( {$params['name']} )";
174 * @param array $params
177 * @param bool $indexExist
179 * @return NULL|string
181 public static function buildSearchIndexSQL(&$params, $separator, $prefix, $indexExist = FALSE) {
185 if ($params['type'] == 'text') {
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) {
195 $sql .= str_repeat(' ', 8);
197 $sql .= "INDEX_{$params['name']} ( {$params['name']} )";
199 elseif (empty($params['searchable']) && empty($params['fk_table_name']) && $indexExist) {
201 $sql .= str_repeat(' ', 8);
202 $sql .= "DROP INDEX INDEX_{$params['name']}";
208 * @param array $params
214 public static function buildIndexSQL(&$params, $separator, $prefix) {
217 $sql .= str_repeat(' ', 8);
218 if ($params['unique']) {
219 $sql .= 'UNIQUE INDEX';
220 $indexName = 'unique';
224 $indexName = 'index';
228 foreach ($params as $name => $value) {
229 if (substr($name, 0, 11) == 'field_name_') {
230 $indexName .= "_{$value}";
231 $indexFields .= " $value,";
234 $indexFields = substr($indexFields, 0, -1);
236 $sql .= " $indexName ( $indexFields )";
241 * @param string $tableName
242 * @param string $fkTableName
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);
252 ALTER TABLE {$tableName}
253 DROP FOREIGN KEY `FK_{$fkName}`;";
255 CRM_Core_DAO
::executeQuery($dropFKSql);
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);
267 * @param array $params
270 * @param string $tableName
272 * @return NULL|string
274 public static function buildForeignKeySQL(&$params, $separator, $prefix, $tableName) {
276 if (!empty($params['fk_table_name']) && !empty($params['fk_field_name'])) {
278 $sql .= str_repeat(' ', 8);
280 $fkName = "{$tableName}_{$params['name']}";
281 if (strlen($fkName) >= 48) {
282 $fkName = substr($fkName, 0, 32) . "_" . substr(md5($fkName), 0, 16);
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);
292 * @param array $params
293 * @param bool $indexExist
294 * @param bool $triggerRebuild
298 public static function alterFieldSQL(&$params, $indexExist = FALSE, $triggerRebuild = TRUE) {
299 $sql = str_repeat(' ', 8);
300 $sql .= "ALTER TABLE {$params['table_name']}";
302 // lets suppress the required flag, since that can cause sql issue
303 $params['required'] = FALSE;
305 switch ($params['operation']) {
309 $sql .= self
::buildFieldSQL($params, $separator, "ADD COLUMN ");
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']);
319 $sql .= self
::buildFieldSQL($params, $separator, $prefix);
321 $sql .= self
::buildSearchIndexSQL($params, $separator, "ADD INDEX ", $indexExist);
325 $sql .= " DROP COLUMN `{$params['name']}`";
326 if (!empty($params['primary'])) {
327 $sql .= ", DROP PRIMARY KEY";
329 if (!empty($params['fk_table_name'])) {
330 $sql .= ", DROP FOREIGN KEY FK_{$params['fkName']}";
335 // CRM-7007: do not i18n-rewrite this query
336 CRM_Core_DAO
::executeQuery($sql, [], TRUE, NULL, FALSE, FALSE);
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);
349 if ($triggerRebuild) {
350 CRM_Core_DAO
::triggerRebuild($params['table_name']);
357 * Delete a CiviCRM-table.
359 * @param string $tableName
360 * Name of the table to be created.
362 public static function dropTable($tableName) {
363 $sql = "DROP TABLE $tableName";
364 CRM_Core_DAO
::executeQuery($sql);
368 * @param string $tableName
369 * @param string $columnName
371 * @param bool $isUpgradeMode
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";
378 CRM_Core_DAO
::executeQuery($sql);
381 CRM_Core_DAO
::executeQuery($sql, [], TRUE, NULL, FALSE, FALSE);
383 $domain = new CRM_Core_DAO_Domain();
385 if ($domain->locales
) {
386 $locales = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $domain->locales
);
387 CRM_Core_I18n_Schema
::rebuildMultilingualSchema($locales, NULL, $isUpgradeMode);
393 * @param string $tableName
394 * @param bool $dropUnique
396 public static function changeUniqueToIndex($tableName, $dropUnique = TRUE) {
398 $sql = "ALTER TABLE $tableName
399 DROP INDEX `unique_entity_id` ,
400 ADD INDEX `FK_{$tableName}_entity_id` ( `entity_id` )";
403 $sql = " ALTER TABLE $tableName
404 DROP INDEX `FK_{$tableName}_entity_id` ,
405 ADD UNIQUE INDEX `unique_entity_id` ( `entity_id` )";
407 CRM_Core_DAO
::executeQuery($sql);
414 * Tables to create index for in the format:
415 * array('civicrm_entity_table' => 'entity_id')
417 * array('civicrm_entity_table' => array('entity_id', 'entity_table'))
418 * The latter will create a combined index on the 2 keys (in order).
420 * Side note - when creating combined indexes the one with the most variation
421 * goes first - so entity_table always goes after entity_id.
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.
426 * @todo add support for length & multilingual on combined keys.
428 * @param string $createIndexPrefix
429 * @param array $substrLengths
431 public static function createIndexes($tables, $createIndexPrefix = 'index', $substrLengths = []) {
433 $domain = new CRM_Core_DAO_Domain();
435 $locales = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $domain->locales
);
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();
443 foreach ($tables as $table => $fields) {
444 $query = "SHOW INDEX FROM $table";
445 $dao = CRM_Core_DAO
::executeQuery($query);
447 $currentIndexes = [];
448 while ($dao->fetch()) {
449 $currentIndexes[] = $dao->Key_name
;
452 // now check for all fields if the index exists
453 foreach ($fields as $field) {
454 $fieldName = implode('_', (array) $field);
456 if (is_array($field)) {
457 // No support for these for combined indexes as yet - add a test when you
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]})" : '';
470 "index_{$fieldName}{$lengthName}",
471 "FK_{$table}_{$fieldName}{$lengthName}",
472 "UI_{$fieldName}{$lengthName}",
473 "{$createIndexPrefix}_{$fieldName}{$lengthName}",
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)) {
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})";
495 $queries[] = "CREATE INDEX {$createIndexPrefix}_{$fieldName}{$lengthName} ON {$table} (" . implode(',', (array) $field) . "{$lengthSize})";
500 // run the queries without i18n-rewriting
501 $dao = new CRM_Core_DAO();
502 foreach ($queries as $query) {
503 $dao->query($query, FALSE);
508 * Get indexes for tables
509 * @param array $tables
510 * array of table names to find indexes for
512 * @return array('tableName' => array('index1', 'index2'))
514 public static function getIndexes($tables) {
516 foreach ($tables as $table) {
517 $query = "SHOW INDEX FROM $table";
518 $dao = CRM_Core_DAO
::executeQuery($query);
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);
527 $indexes[$table] = $tableIndexes;
533 * Drop an index if one by that name exists.
535 * @param string $tableName
536 * @param string $indexName
538 public static function dropIndexIfExists($tableName, $indexName) {
539 if (self
::checkIfIndexExists($tableName, $indexName)) {
540 CRM_Core_DAO
::executeQuery("DROP INDEX $indexName ON $tableName");
545 * @param int $customFieldID
546 * @param string $tableName
547 * @param string $columnName
552 public static function alterFieldLength($customFieldID, $tableName, $columnName, $length) {
553 // first update the custom field tables
555 UPDATE civicrm_custom_field
560 1 => [$length, 'Integer'],
561 2 => [$customFieldID, 'Integer'],
563 CRM_Core_DAO
::executeQuery($sql, $params);
566 SELECT is_required, default_value
567 FROM civicrm_custom_field
570 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
575 if ($dao->is_required
) {
576 $clause = " NOT NULL";
579 if (!empty($dao->default_value
)) {
580 $clause .= " DEFAULT '{$dao->default_value}'";
582 // now modify the column
584 ALTER TABLE {$tableName}
585 MODIFY {$columnName} varchar( $length )
588 CRM_Core_DAO
::executeQuery($sql);
591 CRM_Core_Error
::fatal(ts('Could Not Find Custom Field Details for %1, %2, %3',
602 * Check if the table has an index matching the name.
604 * @param string $tableName
605 * @param array $indexName
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']]
614 if ($result->fetch()) {
621 * Check if the table has a specified column.
623 * @param string $tableName
624 * @param string $columnName
625 * @param bool $i18nRewrite
626 * Whether to rewrite the query on multilingual setups.
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;
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
643 public static function checkFKExists($table_name, $constraint_name) {
644 $config = CRM_Core_Config
::singleton();
645 $dbUf = DB
::parseDSN($config->dsn
);
647 SELECT CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
648 WHERE TABLE_SCHEMA = %1
650 AND CONSTRAINT_NAME = %3
651 AND CONSTRAINT_TYPE = 'FOREIGN KEY'
654 1 => [$dbUf['database'], 'String'],
655 2 => [$table_name, 'String'],
656 3 => [$constraint_name, 'String'],
658 $dao = CRM_Core_DAO
::executeQuery($query, $params);
667 * Remove a foreign key from a table if it exists.
670 * @param $constraint_name
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}", []);
683 * Add index signature hash to DAO file calculation.
685 * @param string $table table name
686 * @param array $indices index array spec
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']);
697 * Compare the indices specified in the XML files with those in the DB.
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.
704 * index specifications
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();
711 foreach ($requiredIndices as $table => $indices) {
712 $reqSigs[] = CRM_Utils_Array
::collect('sig', $indices);
714 CRM_Utils_Array
::flatten($reqSigs, $requiredSigs);
716 // Get the indices in the database
717 $existingIndices = CRM_Core_BAO_SchemaHandler
::getIndexes(array_keys($requiredIndices));
719 foreach ($existingIndices as $table => $indices) {
720 CRM_Core_BAO_SchemaHandler
::addIndexSignature($table, $indices);
721 $extSigs[] = CRM_Utils_Array
::collect('sig', $indices);
723 CRM_Utils_Array
::flatten($extSigs, $existingSigs);
726 $missingSigs = array_diff($requiredSigs, $existingSigs);
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']);
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;
755 return $missingIndices;
759 * Create missing indices.
761 * @param array $missingIndices as returned by getMissingIndices()
763 public static function createMissingIndices($missingIndices) {
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']) .
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);