3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
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-2015
37 * This file contains functions for creating and altering CiviCRM-tables.
41 * structure, similar to what is used in GenCode.php
44 * 'name' => TABLE_NAME,
45 * 'attributes' => ATTRIBUTES,
48 * 'name' => FIELD_NAME,
49 * 'type' => FIELD_SQL_TYPE,
50 * // can be field, index, constraint
51 * 'class' => FIELD_CLASS_TYPE,
52 * 'primary' => BOOLEAN,
53 * 'required' => BOOLEAN,
54 * 'searchable' => TRUE,
55 * 'fk_table_name' => FOREIGN_KEY_TABLE_NAME,
56 * 'fk_field_name' => FOREIGN_KEY_FIELD_NAME,
57 * 'comment' => COMMENT,
58 * 'default' => DEFAULT, )
62 class CRM_Core_BAO_SchemaHandler
{
65 * Create a CiviCRM-table
67 * @param array $params
70 * TRUE if successfully created, FALSE otherwise
73 public static function createTable(&$params) {
74 $sql = self
::buildTableSQL($params);
75 // do not i18n-rewrite
76 $dao = CRM_Core_DAO
::executeQuery($sql, array(), TRUE, NULL, FALSE, FALSE);
79 $config = CRM_Core_Config
::singleton();
80 if ($config->logging
) {
82 $logging = new CRM_Logging_Schema();
83 $logging->fixSchemaDifferencesFor($params['name'], NULL, FALSE);
86 // always do a trigger rebuild for this table
87 CRM_Core_DAO
::triggerRebuild($params['name']);
93 * @param array $params
97 public static function buildTableSQL(&$params) {
98 $sql = "CREATE TABLE {$params['name']} (";
99 if (isset($params['fields']) &&
100 is_array($params['fields'])
104 foreach ($params['fields'] as $field) {
105 $sql .= self
::buildFieldSQL($field, $separator, $prefix);
108 foreach ($params['fields'] as $field) {
109 $sql .= self
::buildPrimaryKeySQL($field, $separator, $prefix);
111 foreach ($params['fields'] as $field) {
112 $sql .= self
::buildSearchIndexSQL($field, $separator, $prefix);
114 if (isset($params['indexes'])) {
115 foreach ($params['indexes'] as $index) {
116 $sql .= self
::buildIndexSQL($index, $separator, $prefix);
119 foreach ($params['fields'] as $field) {
120 $sql .= self
::buildForeignKeySQL($field, $separator, $prefix, $params['name']);
123 $sql .= "\n) {$params['attributes']};";
128 * @param array $params
134 public static function buildFieldSQL(&$params, $separator, $prefix) {
137 $sql .= str_repeat(' ', 8);
139 $sql .= "`{$params['name']}` {$params['type']}";
141 if (!empty($params['required'])) {
145 if (!empty($params['attributes'])) {
146 $sql .= " {$params['attributes']}";
149 if (!empty($params['default']) &&
150 $params['type'] != 'text'
152 $sql .= " DEFAULT {$params['default']}";
155 if (!empty($params['comment'])) {
156 $sql .= " COMMENT '{$params['comment']}'";
163 * @param array $params
167 * @return NULL|string
169 public static function buildPrimaryKeySQL(&$params, $separator, $prefix) {
171 if (!empty($params['primary'])) {
173 $sql .= str_repeat(' ', 8);
175 $sql .= "PRIMARY KEY ( {$params['name']} )";
181 * @param array $params
184 * @param bool $indexExist
186 * @return NULL|string
188 public static function buildSearchIndexSQL(&$params, $separator, $prefix, $indexExist = FALSE) {
192 if ($params['type'] == 'text') {
196 //create index only for searchable fields during ADD,
197 //create index only if field is become searchable during MODIFY,
198 //drop index only if field is no more searchable and index was exist.
199 if (!empty($params['searchable']) && !$indexExist) {
201 $sql .= str_repeat(' ', 8);
203 $sql .= "INDEX_{$params['name']} ( {$params['name']} )";
205 elseif (empty($params['searchable']) && $indexExist) {
207 $sql .= str_repeat(' ', 8);
208 $sql .= "DROP INDEX INDEX_{$params['name']}";
214 * @param array $params
220 public static function buildIndexSQL(&$params, $separator, $prefix) {
223 $sql .= str_repeat(' ', 8);
224 if ($params['unique']) {
225 $sql .= 'UNIQUE INDEX';
226 $indexName = 'unique';
230 $indexName = 'index';
234 foreach ($params as $name => $value) {
235 if (substr($name, 0, 11) == 'field_name_') {
236 $indexName .= "_{$value}";
237 $indexFields .= " $value,";
240 $indexFields = substr($indexFields, 0, -1);
242 $sql .= " $indexName ( $indexFields )";
247 * @param string $tableName
248 * @param string $fkTableName
252 public static function changeFKConstraint($tableName, $fkTableName) {
253 $fkName = "{$tableName}_entity_id";
254 if (strlen($fkName) >= 48) {
255 $fkName = substr($fkName, 0, 32) . "_" . substr(md5($fkName), 0, 16);
258 ALTER TABLE {$tableName}
259 DROP FOREIGN KEY `FK_{$fkName}`;";
261 $dao = CRM_Core_DAO
::executeQuery($dropFKSql);
265 ALTER TABLE {$tableName}
266 ADD CONSTRAINT `FK_{$fkName}` FOREIGN KEY (`entity_id`) REFERENCES {$fkTableName} (`id`) ON DELETE CASCADE;";
267 // CRM-7007: do not i18n-rewrite this query
268 $dao = CRM_Core_DAO
::executeQuery($addFKSql, array(), TRUE, NULL, FALSE, FALSE);
275 * @param array $params
278 * @param string $tableName
280 * @return NULL|string
282 public static function buildForeignKeySQL(&$params, $separator, $prefix, $tableName) {
284 if (!empty($params['fk_table_name']) && !empty($params['fk_field_name'])) {
286 $sql .= str_repeat(' ', 8);
288 $fkName = "{$tableName}_{$params['name']}";
289 if (strlen($fkName) >= 48) {
290 $fkName = substr($fkName, 0, 32) . "_" . substr(md5($fkName), 0, 16);
293 $sql .= "CONSTRAINT FK_$fkName FOREIGN KEY ( `{$params['name']}` ) REFERENCES {$params['fk_table_name']} ( {$params['fk_field_name']} ) ";
294 $sql .= CRM_Utils_Array
::value('fk_attributes', $params);
300 * @param array $params
301 * @param bool $indexExist
302 * @param bool $triggerRebuild
306 public static function alterFieldSQL(&$params, $indexExist = FALSE, $triggerRebuild = TRUE) {
307 $sql = str_repeat(' ', 8);
308 $sql .= "ALTER TABLE {$params['table_name']}";
310 // lets suppress the required flag, since that can cause sql issue
311 $params['required'] = FALSE;
313 switch ($params['operation']) {
317 $sql .= self
::buildFieldSQL($params, $separator, "ADD COLUMN ");
319 $sql .= self
::buildPrimaryKeySQL($params, $separator, "ADD PRIMARY KEY ");
320 $sql .= self
::buildSearchIndexSQL($params, $separator, "ADD INDEX ");
321 $sql .= self
::buildForeignKeySQL($params, $separator, "ADD ", $params['table_name']);
327 $sql .= self
::buildFieldSQL($params, $separator, $prefix);
329 $sql .= self
::buildSearchIndexSQL($params, $separator, "ADD INDEX ", $indexExist);
333 $sql .= " DROP COLUMN `{$params['name']}`";
334 if (!empty($params['primary'])) {
335 $sql .= ", DROP PRIMARY KEY";
337 if (!empty($params['fk_table_name'])) {
338 $sql .= ", DROP FOREIGN KEY FK_{$params['fkName']}";
343 // CRM-7007: do not i18n-rewrite this query
344 $dao = CRM_Core_DAO
::executeQuery($sql, array(), TRUE, NULL, FALSE, FALSE);
347 $config = CRM_Core_Config
::singleton();
348 if ($config->logging
) {
349 // CRM-16717 not sure why this was originally limited to add.
350 // For example custom tables can have field length changes - which need to flow through to logging.
351 // Are there any modifies we DON'T was to call this function for (& shouldn't it be clever enough to cope?)
352 if ($params['operation'] == 'add' ||
$params['operation'] == 'modify') {
353 $logging = new CRM_Logging_Schema();
354 $logging->fixSchemaDifferencesFor($params['table_name'], array(trim($prefix) => array($params['name'])), FALSE);
358 if ($triggerRebuild) {
359 CRM_Core_DAO
::triggerRebuild($params['table_name']);
366 * Delete a CiviCRM-table
368 * @param string $tableName
369 * Name of the table to be created.
371 public static function dropTable($tableName) {
372 $sql = "DROP TABLE $tableName";
373 $dao = CRM_Core_DAO
::executeQuery($sql);
377 * @param string $tableName
378 * @param string $columnName
380 public static function dropColumn($tableName, $columnName) {
381 $sql = "ALTER TABLE $tableName DROP COLUMN $columnName";
382 $dao = CRM_Core_DAO
::executeQuery($sql);
386 * @param string $tableName
387 * @param bool $dropUnique
389 public static function changeUniqueToIndex($tableName, $dropUnique = TRUE) {
391 $sql = "ALTER TABLE $tableName
392 DROP INDEX `unique_entity_id` ,
393 ADD INDEX `FK_{$tableName}_entity_id` ( `entity_id` )";
396 $sql = " ALTER TABLE $tableName
397 DROP INDEX `FK_{$tableName}_entity_id` ,
398 ADD UNIQUE INDEX `unique_entity_id` ( `entity_id` )";
400 $dao = CRM_Core_DAO
::executeQuery($sql);
405 * @param string $createIndexPrefix
406 * @param array $substrLenghts
408 public static function createIndexes(&$tables, $createIndexPrefix = 'index', $substrLenghts = array()) {
410 require_once 'CRM/Core/DAO/Domain.php';
411 $domain = new CRM_Core_DAO_Domain();
413 $locales = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $domain->locales
);
415 // if we're multilingual, cache the information on internationalised fields
416 static $columns = NULL;
417 if (!CRM_Utils_System
::isNull($locales) and $columns === NULL) {
418 $columns = CRM_Core_I18n_SchemaStructure
::columns();
421 foreach ($tables as $table => $fields) {
422 $query = "SHOW INDEX FROM $table";
423 $dao = CRM_Core_DAO
::executeQuery($query);
425 $currentIndexes = array();
426 while ($dao->fetch()) {
427 $currentIndexes[] = $dao->Key_name
;
430 // now check for all fields if the index exists
431 foreach ($fields as $field) {
432 // handle indices over substrings, CRM-6245
433 // $lengthName is appended to index name, $lengthSize is the field size modifier
434 $lengthName = isset($substrLenghts[$table][$field]) ?
"_{$substrLenghts[$table][$field]}" : '';
435 $lengthSize = isset($substrLenghts[$table][$field]) ?
"({$substrLenghts[$table][$field]})" : '';
438 "index_{$field}{$lengthName}",
439 "FK_{$table}_{$field}{$lengthName}",
440 "UI_{$field}{$lengthName}",
441 "{$createIndexPrefix}_{$field}{$lengthName}",
444 // skip to the next $field if one of the above $names exists; handle multilingual for CRM-4126
445 foreach ($names as $name) {
446 $regex = '/^' . preg_quote($name) . '(_[a-z][a-z]_[A-Z][A-Z])?$/';
447 if (preg_grep($regex, $currentIndexes)) {
452 // the index doesn't exist, so create it
453 // if we're multilingual and the field is internationalised, do it for every locale
454 if (!CRM_Utils_System
::isNull($locales) and isset($columns[$table][$field])) {
455 foreach ($locales as $locale) {
456 $queries[] = "CREATE INDEX {$createIndexPrefix}_{$field}{$lengthName}_{$locale} ON {$table} ({$field}_{$locale}{$lengthSize})";
460 $queries[] = "CREATE INDEX {$createIndexPrefix}_{$field}{$lengthName} ON {$table} ({$field}{$lengthSize})";
465 // run the queries without i18n-rewriting
466 $dao = new CRM_Core_DAO();
467 foreach ($queries as $query) {
468 $dao->query($query, FALSE);
473 * @param int $customFieldID
474 * @param string $tableName
475 * @param string $columnName
480 public static function alterFieldLength($customFieldID, $tableName, $columnName, $length) {
481 // first update the custom field tables
483 UPDATE civicrm_custom_field
488 1 => array($length, 'Integer'),
489 2 => array($customFieldID, 'Integer'),
491 CRM_Core_DAO
::executeQuery($sql, $params);
494 SELECT is_required, default_value
495 FROM civicrm_custom_field
498 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
503 if ($dao->is_required
) {
504 $clause = " NOT NULL";
507 if (!empty($dao->default_value
)) {
508 $clause .= " DEFAULT '{$dao->default_value}'";
510 // now modify the column
512 ALTER TABLE {$tableName}
513 MODIFY {$columnName} varchar( $length )
516 CRM_Core_DAO
::executeQuery($sql);
519 CRM_Core_Error
::fatal(ts('Could Not Find Custom Field Details for %1, %2, %3',