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 if (CRM_Core_Config
::singleton()->logging
) {
74 $logging = new CRM_Logging_Schema();
75 $logging->fixSchemaDifferencesFor($params['name']);
78 // always do a trigger rebuild for this table
79 Civi
::service('sql_triggers')->rebuild($params['name'], TRUE);
85 * @param array $params
89 public static function buildTableSQL($params) {
90 $sql = "CREATE TABLE {$params['name']} (";
91 if (isset($params['fields']) &&
92 is_array($params['fields'])
96 foreach ($params['fields'] as $field) {
97 $sql .= self
::buildFieldSQL($field, $separator, $prefix);
100 foreach ($params['fields'] as $field) {
101 $sql .= self
::buildPrimaryKeySQL($field, $separator, $prefix);
103 foreach ($params['fields'] as $field) {
104 $sql .= self
::buildSearchIndexSQL($field, $separator, $prefix);
106 if (isset($params['indexes'])) {
107 foreach ($params['indexes'] as $index) {
108 $sql .= self
::buildIndexSQL($index, $separator, $prefix);
111 foreach ($params['fields'] as $field) {
112 $sql .= self
::buildForeignKeySQL($field, $separator, $prefix, $params['name']);
115 $sql .= "\n) {$params['attributes']};";
120 * @param array $params
126 public static function buildFieldSQL($params, $separator, $prefix) {
129 $sql .= str_repeat(' ', 8);
131 $sql .= "`{$params['name']}` {$params['type']}";
133 if (!empty($params['required'])) {
137 if (!empty($params['attributes'])) {
138 $sql .= " {$params['attributes']}";
141 if (!empty($params['default']) &&
142 $params['type'] != 'text'
144 $sql .= " DEFAULT {$params['default']}";
147 if (!empty($params['comment'])) {
148 $sql .= " COMMENT '{$params['comment']}'";
155 * @param array $params
159 * @return NULL|string
161 public static function buildPrimaryKeySQL($params, $separator, $prefix) {
163 if (!empty($params['primary'])) {
165 $sql .= str_repeat(' ', 8);
167 $sql .= "PRIMARY KEY ( {$params['name']} )";
173 * @param array $params
176 * @param bool $indexExist
178 * @return NULL|string
180 public static function buildSearchIndexSQL($params, $separator, $prefix, $indexExist = FALSE) {
184 if ($params['type'] == 'text') {
188 //create index only for searchable fields during ADD,
189 //create index only if field is become searchable during MODIFY,
190 //drop index only if field is no longer searchable and it does not reference
191 //a forgein key (and indexExist is true)
192 if (!empty($params['searchable']) && !$indexExist) {
194 $sql .= str_repeat(' ', 8);
196 $sql .= "INDEX_{$params['name']} ( {$params['name']} )";
198 elseif (empty($params['searchable']) && empty($params['fk_table_name']) && $indexExist) {
200 $sql .= str_repeat(' ', 8);
201 $sql .= "DROP INDEX INDEX_{$params['name']}";
207 * @param array $params
213 public static function buildIndexSQL(&$params, $separator, $prefix) {
216 $sql .= str_repeat(' ', 8);
217 if ($params['unique']) {
218 $sql .= 'UNIQUE INDEX';
219 $indexName = 'unique';
223 $indexName = 'index';
227 foreach ($params as $name => $value) {
228 if (substr($name, 0, 11) == 'field_name_') {
229 $indexName .= "_{$value}";
230 $indexFields .= " $value,";
233 $indexFields = substr($indexFields, 0, -1);
235 $sql .= " $indexName ( $indexFields )";
240 * @param string $tableName
241 * @param string $fkTableName
245 public static function changeFKConstraint($tableName, $fkTableName) {
246 $fkName = "{$tableName}_entity_id";
247 if (strlen($fkName) >= 48) {
248 $fkName = substr($fkName, 0, 32) . "_" . substr(md5($fkName), 0, 16);
251 ALTER TABLE {$tableName}
252 DROP FOREIGN KEY `FK_{$fkName}`;";
254 CRM_Core_DAO
::executeQuery($dropFKSql);
257 ALTER TABLE {$tableName}
258 ADD CONSTRAINT `FK_{$fkName}` FOREIGN KEY (`entity_id`) REFERENCES {$fkTableName} (`id`) ON DELETE CASCADE;";
259 // CRM-7007: do not i18n-rewrite this query
260 CRM_Core_DAO
::executeQuery($addFKSql, [], TRUE, NULL, FALSE, FALSE);
266 * @param array $params
269 * @param string $tableName
271 * @return NULL|string
273 public static function buildForeignKeySQL($params, $separator, $prefix, $tableName) {
275 if (!empty($params['fk_table_name']) && !empty($params['fk_field_name'])) {
277 $sql .= str_repeat(' ', 8);
279 $fkName = "{$tableName}_{$params['name']}";
280 if (strlen($fkName) >= 48) {
281 $fkName = substr($fkName, 0, 32) . "_" . substr(md5($fkName), 0, 16);
284 $sql .= "CONSTRAINT FK_$fkName FOREIGN KEY ( `{$params['name']}` ) REFERENCES {$params['fk_table_name']} ( {$params['fk_field_name']} ) ";
285 $sql .= CRM_Utils_Array
::value('fk_attributes', $params);
291 * @param array $params
292 * @param bool $indexExist
293 * @param bool $triggerRebuild
297 public static function alterFieldSQL($params, $indexExist = FALSE, $triggerRebuild = TRUE) {
298 CRM_Core_Error
::deprecatedFunctionWarning('function no longer in use / supported');
299 // lets suppress the required flag, since that can cause sql issue
300 $params['required'] = FALSE;
302 $sql = self
::buildFieldChangeSql($params, $indexExist);
304 // CRM-7007: do not i18n-rewrite this query
305 CRM_Core_DAO
::executeQuery($sql, [], TRUE, NULL, FALSE, FALSE);
307 $config = CRM_Core_Config
::singleton();
308 if ($config->logging
) {
309 // CRM-16717 not sure why this was originally limited to add.
310 // For example custom tables can have field length changes - which need to flow through to logging.
311 // Are there any modifies we DON'T was to call this function for (& shouldn't it be clever enough to cope?)
312 if ($params['operation'] == 'add' ||
$params['operation'] == 'modify') {
313 $logging = new CRM_Logging_Schema();
314 $logging->fixSchemaDifferencesFor($params['table_name'], [trim(strtoupper($params['operation'])) => [$params['name']]]);
318 if ($triggerRebuild) {
319 Civi
::service('sql_triggers')->rebuild($params['table_name'], TRUE);
326 * Delete a CiviCRM-table.
328 * @param string $tableName
329 * Name of the table to be created.
331 public static function dropTable($tableName) {
332 $sql = "DROP TABLE $tableName";
333 CRM_Core_DAO
::executeQuery($sql);
337 * @param string $tableName
338 * @param string $columnName
340 * @param bool $isUpgradeMode
343 public static function dropColumn($tableName, $columnName, $l18n = FALSE, $isUpgradeMode = FALSE) {
344 if (self
::checkIfFieldExists($tableName, $columnName)) {
345 $sql = "ALTER TABLE $tableName DROP COLUMN $columnName";
347 CRM_Core_DAO
::executeQuery($sql);
350 CRM_Core_DAO
::executeQuery($sql, [], TRUE, NULL, FALSE, FALSE);
352 $domain = new CRM_Core_DAO_Domain();
354 if ($domain->locales
) {
355 $locales = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $domain->locales
);
356 CRM_Core_I18n_Schema
::rebuildMultilingualSchema($locales, NULL, $isUpgradeMode);
362 * @param string $tableName
363 * @param bool $dropUnique
365 public static function changeUniqueToIndex($tableName, $dropUnique = TRUE) {
367 $sql = "ALTER TABLE $tableName
368 DROP INDEX `unique_entity_id` ,
369 ADD INDEX `FK_{$tableName}_entity_id` ( `entity_id` )";
372 $sql = " ALTER TABLE $tableName
373 DROP INDEX `FK_{$tableName}_entity_id` ,
374 ADD UNIQUE INDEX `unique_entity_id` ( `entity_id` )";
376 CRM_Core_DAO
::executeQuery($sql);
383 * Tables to create index for in the format:
384 * array('civicrm_entity_table' => 'entity_id')
386 * array('civicrm_entity_table' => array('entity_id', 'entity_table'))
387 * The latter will create a combined index on the 2 keys (in order).
389 * Side note - when creating combined indexes the one with the most variation
390 * goes first - so entity_table always goes after entity_id.
392 * It probably makes sense to consider more sophisticated options at some point
393 * but at the moment this is only being as enhanced as fast as the test is.
395 * @todo add support for length & multilingual on combined keys.
397 * @param string $createIndexPrefix
398 * @param array $substrLengths
400 public static function createIndexes($tables, $createIndexPrefix = 'index', $substrLengths = []) {
402 $domain = new CRM_Core_DAO_Domain();
404 $locales = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $domain->locales
);
406 // if we're multilingual, cache the information on internationalised fields
407 static $columns = NULL;
408 if (!CRM_Utils_System
::isNull($locales) and $columns === NULL) {
409 $columns = CRM_Core_I18n_SchemaStructure
::columns();
412 foreach ($tables as $table => $fields) {
413 $query = "SHOW INDEX FROM $table";
414 $dao = CRM_Core_DAO
::executeQuery($query);
416 $currentIndexes = [];
417 while ($dao->fetch()) {
418 $currentIndexes[] = $dao->Key_name
;
421 // now check for all fields if the index exists
422 foreach ($fields as $field) {
423 $fieldName = implode('_', (array) $field);
425 if (is_array($field)) {
426 // No support for these for combined indexes as yet - add a test when you
432 // handle indices over substrings, CRM-6245
433 // $lengthName is appended to index name, $lengthSize is the field size modifier
434 $lengthName = isset($substrLengths[$table][$fieldName]) ?
"_{$substrLengths[$table][$fieldName]}" : '';
435 $lengthSize = isset($substrLengths[$table][$fieldName]) ?
"({$substrLengths[$table][$fieldName]})" : '';
439 "index_{$fieldName}{$lengthName}",
440 "FK_{$table}_{$fieldName}{$lengthName}",
441 "UI_{$fieldName}{$lengthName}",
442 "{$createIndexPrefix}_{$fieldName}{$lengthName}",
445 // skip to the next $field if one of the above $names exists; handle multilingual for CRM-4126
446 foreach ($names as $name) {
447 $regex = '/^' . preg_quote($name) . '(_[a-z][a-z]_[A-Z][A-Z])?$/';
448 if (preg_grep($regex, $currentIndexes)) {
453 // the index doesn't exist, so create it
454 // if we're multilingual and the field is internationalised, do it for every locale
455 // @todo remove is_array check & add multilingual support for combined indexes and add a test.
456 // Note combined indexes currently using this function are on fields like
457 // entity_id + entity_table which are not multilingual.
458 if (!is_array($field) && !CRM_Utils_System
::isNull($locales) and isset($columns[$table][$fieldName])) {
459 foreach ($locales as $locale) {
460 $queries[] = "CREATE INDEX {$createIndexPrefix}_{$fieldName}{$lengthName}_{$locale} ON {$table} ({$fieldName}_{$locale}{$lengthSize})";
464 $queries[] = "CREATE INDEX {$createIndexPrefix}_{$fieldName}{$lengthName} ON {$table} (" . implode(',', (array) $field) . "{$lengthSize})";
469 // run the queries without i18n-rewriting
470 $dao = new CRM_Core_DAO();
471 foreach ($queries as $query) {
472 $dao->query($query, FALSE);
477 * Get indexes for tables
478 * @param array $tables
479 * array of table names to find indexes for
481 * @return array('tableName' => array('index1', 'index2'))
483 public static function getIndexes($tables) {
485 foreach ($tables as $table) {
486 $query = "SHOW INDEX FROM $table";
487 $dao = CRM_Core_DAO
::executeQuery($query);
490 while ($dao->fetch()) {
491 $tableIndexes[$dao->Key_name
]['name'] = $dao->Key_name
;
492 $tableIndexes[$dao->Key_name
]['field'][] = $dao->Column_name
.
493 ($dao->Sub_part ?
'(' . $dao->Sub_part
. ')' : '');
494 $tableIndexes[$dao->Key_name
]['unique'] = ($dao->Non_unique
== 0 ?
1 : 0);
496 $indexes[$table] = $tableIndexes;
502 * Drop an index if one by that name exists.
504 * @param string $tableName
505 * @param string $indexName
507 public static function dropIndexIfExists($tableName, $indexName) {
508 if (self
::checkIfIndexExists($tableName, $indexName)) {
509 CRM_Core_DAO
::executeQuery("DROP INDEX $indexName ON $tableName");
514 * @param int $customFieldID
515 * @param string $tableName
516 * @param string $columnName
521 public static function alterFieldLength($customFieldID, $tableName, $columnName, $length) {
522 // first update the custom field tables
524 UPDATE civicrm_custom_field
529 1 => [$length, 'Integer'],
530 2 => [$customFieldID, 'Integer'],
532 CRM_Core_DAO
::executeQuery($sql, $params);
535 SELECT is_required, default_value
536 FROM civicrm_custom_field
539 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
544 if ($dao->is_required
) {
545 $clause = " NOT NULL";
548 if (!empty($dao->default_value
)) {
549 $clause .= " DEFAULT '{$dao->default_value}'";
551 // now modify the column
553 ALTER TABLE {$tableName}
554 MODIFY {$columnName} varchar( $length )
557 CRM_Core_DAO
::executeQuery($sql);
560 CRM_Core_Error
::fatal(ts('Could Not Find Custom Field Details for %1, %2, %3',
571 * Check if the table has an index matching the name.
573 * @param string $tableName
574 * @param array $indexName
578 public static function checkIfIndexExists($tableName, $indexName) {
579 $result = CRM_Core_DAO
::executeQuery(
580 "SHOW INDEX FROM $tableName WHERE key_name = %1 AND seq_in_index = 1",
581 [1 => [$indexName, 'String']]
583 if ($result->fetch()) {
590 * Check if the table has a specified column.
592 * @param string $tableName
593 * @param string $columnName
594 * @param bool $i18nRewrite
595 * Whether to rewrite the query on multilingual setups.
599 public static function checkIfFieldExists($tableName, $columnName, $i18nRewrite = TRUE) {
600 $query = "SHOW COLUMNS FROM $tableName LIKE '%1'";
601 $dao = CRM_Core_DAO
::executeQuery($query, [1 => [$columnName, 'Alphanumeric']], TRUE, NULL, FALSE, $i18nRewrite);
602 $result = $dao->fetch() ?
TRUE : FALSE;
607 * Check if a foreign key Exists
608 * @param string $table_name
609 * @param string $constraint_name
610 * @return bool TRUE if FK is found
612 public static function checkFKExists($table_name, $constraint_name) {
613 $config = CRM_Core_Config
::singleton();
614 $dbUf = DB
::parseDSN($config->dsn
);
616 SELECT CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
617 WHERE TABLE_SCHEMA = %1
619 AND CONSTRAINT_NAME = %3
620 AND CONSTRAINT_TYPE = 'FOREIGN KEY'
623 1 => [$dbUf['database'], 'String'],
624 2 => [$table_name, 'String'],
625 3 => [$constraint_name, 'String'],
627 $dao = CRM_Core_DAO
::executeQuery($query, $params);
636 * Remove a foreign key from a table if it exists.
639 * @param $constraint_name
643 public static function safeRemoveFK($table_name, $constraint_name) {
644 if (self
::checkFKExists($table_name, $constraint_name)) {
645 CRM_Core_DAO
::executeQuery("ALTER TABLE {$table_name} DROP FOREIGN KEY {$constraint_name}", []);
652 * Add index signature hash to DAO file calculation.
654 * @param string $table table name
655 * @param array $indices index array spec
657 public static function addIndexSignature($table, &$indices) {
658 foreach ($indices as $indexName => $index) {
659 $indices[$indexName]['sig'] = $table . "::" .
660 (array_key_exists('unique', $index) ?
$index['unique'] : 0) . "::" .
661 implode("::", $index['field']);
666 * Compare the indices specified in the XML files with those in the DB.
668 * @param bool $dropFalseIndices
669 * If set - this function deletes false indices present in the DB which mismatches the expected
670 * values of xml file so that civi re-creates them with correct values using createMissingIndices() function.
673 * index specifications
675 public static function getMissingIndices($dropFalseIndices = FALSE) {
676 $requiredSigs = $existingSigs = [];
677 // Get the indices defined (originally) in the xml files
678 $requiredIndices = CRM_Core_DAO_AllCoreTables
::indices();
680 foreach ($requiredIndices as $table => $indices) {
681 $reqSigs[] = CRM_Utils_Array
::collect('sig', $indices);
683 CRM_Utils_Array
::flatten($reqSigs, $requiredSigs);
685 // Get the indices in the database
686 $existingIndices = CRM_Core_BAO_SchemaHandler
::getIndexes(array_keys($requiredIndices));
688 foreach ($existingIndices as $table => $indices) {
689 CRM_Core_BAO_SchemaHandler
::addIndexSignature($table, $indices);
690 $extSigs[] = CRM_Utils_Array
::collect('sig', $indices);
692 CRM_Utils_Array
::flatten($extSigs, $existingSigs);
695 $missingSigs = array_diff($requiredSigs, $existingSigs);
697 //CRM-20774 - Drop index key which exist in db but the value varies.
698 $existingKeySigs = array_intersect_key($missingSigs, $existingSigs);
699 if ($dropFalseIndices && !empty($existingKeySigs)) {
700 foreach ($existingKeySigs as $sig) {
701 $sigParts = explode('::', $sig);
702 foreach ($requiredIndices[$sigParts[0]] as $index) {
703 if ($index['sig'] == $sig && !empty($index['name'])) {
704 self
::dropIndexIfExists($sigParts[0], $index['name']);
711 // Get missing indices
712 $missingIndices = [];
713 foreach ($missingSigs as $sig) {
714 $sigParts = explode('::', $sig);
715 if (array_key_exists($sigParts[0], $requiredIndices)) {
716 foreach ($requiredIndices[$sigParts[0]] as $index) {
717 if ($index['sig'] == $sig) {
718 $missingIndices[$sigParts[0]][] = $index;
724 return $missingIndices;
728 * Create missing indices.
730 * @param array $missingIndices as returned by getMissingIndices()
732 public static function createMissingIndices($missingIndices) {
734 foreach ($missingIndices as $table => $indexList) {
735 foreach ($indexList as $index) {
736 $queries[] = "CREATE " .
737 (array_key_exists('unique', $index) && $index['unique'] ?
'UNIQUE ' : '') .
738 "INDEX {$index['name']} ON {$table} (" .
739 implode(", ", $index['field']) .
744 /* FIXME potential problem if index name already exists, so check before creating */
745 $dao = new CRM_Core_DAO();
746 foreach ($queries as $query) {
747 $dao->query($query, FALSE);
752 * Build the sql to alter the field.
754 * @param array $params
755 * @param bool $indexExist
759 public static function buildFieldChangeSql($params, $indexExist) {
760 $sql = str_repeat(' ', 8);
761 $sql .= "ALTER TABLE {$params['table_name']}";
762 return $sql . self
::getFieldAlterSQL($params, $indexExist);
766 * Get the sql to alter an individual field.
768 * This will need to have an ALTER TABLE statement appended but by getting
769 * by individual field we can do one or many.
771 * @param array $params
772 * @param bool $indexExist
776 public static function getFieldAlterSQL($params, $indexExist) {
778 switch ($params['operation']) {
781 $sql .= self
::buildFieldSQL($params, $separator, "ADD COLUMN ");
783 $sql .= self
::buildPrimaryKeySQL($params, $separator, "ADD PRIMARY KEY ");
784 $sql .= self
::buildSearchIndexSQL($params, $separator, "ADD INDEX ");
785 $sql .= self
::buildForeignKeySQL($params, $separator, "ADD ", $params['table_name']);
790 $sql .= self
::buildFieldSQL($params, $separator, "MODIFY ");
792 $sql .= self
::buildSearchIndexSQL($params, $separator, "ADD INDEX ", $indexExist);
796 $sql .= " DROP COLUMN `{$params['name']}`";
797 if (!empty($params['primary'])) {
798 $sql .= ", DROP PRIMARY KEY";
800 if (!empty($params['fk_table_name'])) {
801 $sql .= ", DROP FOREIGN KEY FK_{$params['fkName']}";