Merge pull request #3209 from eileenmcnaughton/comments
[civicrm-core.git] / CRM / Core / BAO / SchemaHandler.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
06b69b18 4 | CiviCRM version 4.5 |
6a488035 5 +--------------------------------------------------------------------+
06b69b18 6 | Copyright CiviCRM LLC (c) 2004-2014 |
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 +--------------------------------------------------------------------+
26*/
27
28/**
29 *
30 * @package CRM
06b69b18 31 * @copyright CiviCRM LLC (c) 2004-2014
6a488035
TO
32 * $Id$
33 *
34 */
35
36/**
37 * This file contains functions for creating and altering CiviCRM-tables.
38 */
39
40/**
41 * structure, similar to what is used in GenCode.php
42 *
43 * $table = array(
44 'name' => TABLE_NAME,
45 * 'attributes' => ATTRIBUTES,
46 * 'fields' => array(
47 * array(
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, )
59 * ...
60 * ) );
61 */
62class CRM_Core_BAO_SchemaHandler {
63
64 /**
65 * Function for creating a civiCRM-table
66 *
77b97be7
EM
67 * @param $params
68 *
69 * @internal param String $tableName name of the table to be created.
70 * @internal param Array $tableAttributes array containing atrributes for the table that needs to be created
6a488035
TO
71 *
72 * @return true if successfully created, false otherwise
73 *
74 * @static
75 * @access public
76 */
77 static function createTable(&$params) {
78 $sql = self::buildTableSQL($params);
79 // do not i18n-rewrite
80 $dao = CRM_Core_DAO::executeQuery($sql, array(), TRUE, NULL, FALSE, FALSE);
81 $dao->free();
82
83 $config = CRM_Core_Config::singleton();
84 if ($config->logging) {
85 // logging support
86 $logging = new CRM_Logging_Schema;
87 $logging->fixSchemaDifferencesFor($params['name'], null, FALSE);
88 }
89
90 // always do a trigger rebuild for this table
91 CRM_Core_DAO::triggerRebuild($params['name']);
92
93 return TRUE;
94 }
95
96 static function buildTableSQL(&$params) {
97 $sql = "CREATE TABLE {$params['name']} (";
98 if (isset($params['fields']) &&
99 is_array($params['fields'])
100 ) {
101 $separator = "\n";
102 $prefix = NULL;
103 foreach ($params['fields'] as $field) {
104 $sql .= self::buildFieldSQL($field, $separator, $prefix);
105 $separator = ",\n";
106 }
107 foreach ($params['fields'] as $field) {
108 $sql .= self::buildPrimaryKeySQL($field, $separator, $prefix);
109 }
110 foreach ($params['fields'] as $field) {
111 $sql .= self::buildSearchIndexSQL($field, $separator, $prefix);
112 }
113 if (isset($params['indexes'])) {
114 foreach ($params['indexes'] as $index) {
115 $sql .= self::buildIndexSQL($index, $separator, $prefix);
116 }
117 }
118 foreach ($params['fields'] as $field) {
119 $sql .= self::buildForeignKeySQL($field, $separator, $prefix, $params['name']);
120 }
121 }
122 $sql .= "\n) {$params['attributes']};";
123 return $sql;
124 }
125
126 static function buildFieldSQL(&$params, $separator, $prefix) {
127 $sql = '';
128 $sql .= $separator;
129 $sql .= str_repeat(' ', 8);
130 $sql .= $prefix;
131 $sql .= "`{$params['name']}` {$params['type']}";
132
a7488080 133 if (!empty($params['required'])) {
6a488035
TO
134 $sql .= " NOT NULL";
135 }
136
a7488080 137 if (!empty($params['attributes'])) {
6a488035
TO
138 $sql .= " {$params['attributes']}";
139 }
140
a7488080 141 if (!empty($params['default']) &&
6a488035
TO
142 $params['type'] != 'text'
143 ) {
144 $sql .= " DEFAULT {$params['default']}";
145 }
146
a7488080 147 if (!empty($params['comment'])) {
6a488035
TO
148 $sql .= " COMMENT '{$params['comment']}'";
149 }
150
151 return $sql;
152 }
153
154 static function buildPrimaryKeySQL(&$params, $separator, $prefix) {
155 $sql = NULL;
a7488080 156 if (!empty($params['primary'])) {
6a488035
TO
157 $sql .= $separator;
158 $sql .= str_repeat(' ', 8);
159 $sql .= $prefix;
160 $sql .= "PRIMARY KEY ( {$params['name']} )";
161 }
162 return $sql;
163 }
164
165 static function buildSearchIndexSQL(&$params, $separator, $prefix, $indexExist = FALSE) {
166 $sql = NULL;
167
168 // dont index blob
169 if ($params['type'] == 'text') {
170 return $sql;
171 }
172
173 //create index only for searchable fields during ADD,
174 //create index only if field is become searchable during MODIFY,
175 //drop index only if field is no more searchable and index was exist.
a7488080 176 if (!empty($params['searchable']) && !$indexExist) {
6a488035
TO
177 $sql .= $separator;
178 $sql .= str_repeat(' ', 8);
179 $sql .= $prefix;
180 $sql .= "INDEX_{$params['name']} ( {$params['name']} )";
181 }
a7488080 182 elseif (empty($params['searchable']) && $indexExist) {
6a488035
TO
183 $sql .= $separator;
184 $sql .= str_repeat(' ', 8);
185 $sql .= "DROP INDEX INDEX_{$params['name']}";
186 }
187 return $sql;
188 }
189
190 static function buildIndexSQL(&$params, $separator, $prefix) {
191 $sql = '';
192 $sql .= $separator;
193 $sql .= str_repeat(' ', 8);
194 if ($params['unique']) {
195 $sql .= 'UNIQUE INDEX';
196 $indexName = 'unique';
197 }
198 else {
199 $sql .= 'INDEX';
200 $indexName = 'index';
201 }
202 $indexFields = NULL;
203
204 foreach ($params as $name => $value) {
205 if (substr($name, 0, 11) == 'field_name_') {
206 $indexName .= "_{$value}";
207 $indexFields .= " $value,";
208 }
209 }
210 $indexFields = substr($indexFields, 0, -1);
211
212 $sql .= " $indexName ( $indexFields )";
213 return $sql;
214 }
215
216 static function changeFKConstraint($tableName, $fkTableName) {
217 $fkName = "{$tableName}_entity_id";
218 if (strlen($fkName) >= 48) {
219 $fkName = substr($fkName, 0, 32) . "_" . substr(md5($fkName), 0, 16);
220 }
221 $dropFKSql = "
222ALTER TABLE {$tableName}
223 DROP FOREIGN KEY `FK_{$fkName}`;";
224
225 $dao = CRM_Core_DAO::executeQuery($dropFKSql);
226 $dao->free();
227
228 $addFKSql = "
229ALTER TABLE {$tableName}
230 ADD CONSTRAINT `FK_{$fkName}` FOREIGN KEY (`entity_id`) REFERENCES {$fkTableName} (`id`) ON DELETE CASCADE;";
231 // CRM-7007: do not i18n-rewrite this query
232 $dao = CRM_Core_DAO::executeQuery($addFKSql, array(), TRUE, NULL, FALSE, FALSE);
233 $dao->free();
234
235 return TRUE;
236 }
237
238 static function buildForeignKeySQL(&$params, $separator, $prefix, $tableName) {
239 $sql = NULL;
8cc574cf 240 if (!empty($params['fk_table_name']) && !empty($params['fk_field_name'])) {
6a488035
TO
241 $sql .= $separator;
242 $sql .= str_repeat(' ', 8);
243 $sql .= $prefix;
244 $fkName = "{$tableName}_{$params['name']}";
245 if (strlen($fkName) >= 48) {
246 $fkName = substr($fkName, 0, 32) . "_" . substr(md5($fkName), 0, 16);
247 }
248
249 $sql .= "CONSTRAINT FK_$fkName FOREIGN KEY ( `{$params['name']}` ) REFERENCES {$params['fk_table_name']} ( {$params['fk_field_name']} ) ";
250 $sql .= CRM_Utils_Array::value('fk_attributes', $params);
251 }
252 return $sql;
253 }
254
255 static function alterFieldSQL(&$params, $indexExist = FALSE, $triggerRebuild = TRUE) {
256 $sql = str_repeat(' ', 8);
257 $sql .= "ALTER TABLE {$params['table_name']}";
258
259 // lets suppress the required flag, since that can cause sql issue
260 $params['required'] = FALSE;
261
262 switch ($params['operation']) {
263 case 'add':
264 $separator = "\n";
265 $prefix = "ADD ";
266 $sql .= self::buildFieldSQL($params, $separator, "ADD COLUMN ");
267 $separator = ",\n";
268 $sql .= self::buildPrimaryKeySQL($params, $separator, "ADD PRIMARY KEY ");
269 $sql .= self::buildSearchIndexSQL($params, $separator, "ADD INDEX ");
270 $sql .= self::buildForeignKeySQL($params, $separator, "ADD ", $params['table_name']);
271 break;
272
273 case 'modify':
274 $separator = "\n";
275 $prefix = "MODIFY ";
276 $sql .= self::buildFieldSQL($params, $separator, $prefix);
277 $separator = ",\n";
278 $sql .= self::buildSearchIndexSQL($params, $separator, "ADD INDEX ", $indexExist);
279 break;
280
281 case 'delete':
282 $sql .= " DROP COLUMN `{$params['name']}`";
a7488080 283 if (!empty($params['primary'])) {
6a488035
TO
284 $sql .= ", DROP PRIMARY KEY";
285 }
a7488080 286 if (!empty($params['fk_table_name'])) {
6a488035
TO
287 $sql .= ", DROP FOREIGN KEY FK_{$params['fkName']}";
288 }
289 break;
290 }
291
292 // CRM-7007: do not i18n-rewrite this query
293 $dao = CRM_Core_DAO::executeQuery($sql, array(), TRUE, NULL, FALSE, FALSE);
294 $dao->free();
295
296 $config = CRM_Core_Config::singleton();
297 if ($config->logging) {
298 // logging support: if we’re adding a column (but only then!) make sure the potential relevant log table gets a column as well
299 if ($params['operation'] == 'add') {
300 $logging = new CRM_Logging_Schema;
12de149a 301 $logging->fixSchemaDifferencesFor($params['table_name'], array('ADD' => array($params['name'])), FALSE);
6a488035
TO
302 }
303 }
304
305 if($triggerRebuild) {
306 CRM_Core_DAO::triggerRebuild($params['table_name']);
307 }
308
309 return TRUE;
310 }
311
312 /**
313 * Function to delete a civiCRM-table
314 *
315 * @param String $tableName name of the table to be created.
316 *
317 * @return true if successfully deleted, false otherwise
318 *
319 * @static
320 * @access public
321 */
322 static function dropTable($tableName) {
323 $sql = "DROP TABLE $tableName";
324 $dao = CRM_Core_DAO::executeQuery($sql);
325 }
326
327 static function dropColumn($tableName, $columnName) {
328 $sql = "ALTER TABLE $tableName DROP COLUMN $columnName";
329 $dao = CRM_Core_DAO::executeQuery($sql);
330 }
331
332 static function changeUniqueToIndex($tableName, $dropUnique = TRUE) {
333 if ($dropUnique) {
334 $sql = "ALTER TABLE $tableName
335DROP INDEX `unique_entity_id` ,
336ADD INDEX `FK_{$tableName}_entity_id` ( `entity_id` )";
337 }
338 else {
339 $sql = " ALTER TABLE $tableName
340DROP INDEX `FK_{$tableName}_entity_id` ,
341ADD UNIQUE INDEX `unique_entity_id` ( `entity_id` )";
342 }
343 $dao = CRM_Core_DAO::executeQuery($sql);
344 }
345
346 static function createIndexes(&$tables, $createIndexPrefix = 'index', $substrLenghts = array(
347 )) {
348 $queries = array();
349
350 require_once 'CRM/Core/DAO/Domain.php';
351 $domain = new CRM_Core_DAO_Domain;
352 $domain->find(TRUE);
353 $locales = explode(CRM_Core_DAO::VALUE_SEPARATOR, $domain->locales);
354
355 // if we're multilingual, cache the information on internationalised fields
356 static $columns = NULL;
357 if (!CRM_Utils_System::isNull($locales) and $columns === NULL) {
358 $columns = CRM_Core_I18n_SchemaStructure::columns();
359 }
360
361 foreach ($tables as $table => $fields) {
362 $query = "SHOW INDEX FROM $table";
363 $dao = CRM_Core_DAO::executeQuery($query);
364
365 $currentIndexes = array();
366 while ($dao->fetch()) {
367 $currentIndexes[] = $dao->Key_name;
368 }
369
370 // now check for all fields if the index exists
371 foreach ($fields as $field) {
372 // handle indices over substrings, CRM-6245
373 // $lengthName is appended to index name, $lengthSize is the field size modifier
374 $lengthName = isset($substrLenghts[$table][$field]) ? "_{$substrLenghts[$table][$field]}" : '';
375 $lengthSize = isset($substrLenghts[$table][$field]) ? "({$substrLenghts[$table][$field]})" : '';
376
377 $names = array("index_{$field}{$lengthName}", "FK_{$table}_{$field}{$lengthName}", "UI_{$field}{$lengthName}", "{$createIndexPrefix}_{$field}{$lengthName}");
378
379 // skip to the next $field if one of the above $names exists; handle multilingual for CRM-4126
380 foreach ($names as $name) {
381 $regex = '/^' . preg_quote($name) . '(_[a-z][a-z]_[A-Z][A-Z])?$/';
382 if (preg_grep($regex, $currentIndexes)) {
383 continue 2;
384 }
385 }
386
387 // the index doesn't exist, so create it
388 // if we're multilingual and the field is internationalised, do it for every locale
389 if (!CRM_Utils_System::isNull($locales) and isset($columns[$table][$field])) {
390 foreach ($locales as $locale) {
391 $queries[] = "CREATE INDEX {$createIndexPrefix}_{$field}{$lengthName}_{$locale} ON {$table} ({$field}_{$locale}{$lengthSize})";
392 }
393 }
394 else {
395 $queries[] = "CREATE INDEX {$createIndexPrefix}_{$field}{$lengthName} ON {$table} ({$field}{$lengthSize})";
396 }
397 }
398 }
399
400 // run the queries without i18n-rewriting
401 $dao = new CRM_Core_DAO;
402 foreach ($queries as $query) {
403 $dao->query($query, FALSE);
404 }
405 }
406
407 static function alterFieldLength($customFieldID, $tableName, $columnName, $length) {
408 // first update the custom field tables
409 $sql = "
410UPDATE civicrm_custom_field
411SET text_length = %1
412WHERE id = %2
413";
414 $params = array(1 => array($length, 'Integer'),
415 2 => array($customFieldID, 'Integer'),
416 );
417 CRM_Core_DAO::executeQuery($sql, $params);
418
419 $sql = "
420SELECT is_required, default_value
421FROM civicrm_custom_field
422WHERE id = %2
423";
424 $dao = CRM_Core_DAO::executeQuery($sql, $params);
425
426 if ($dao->fetch()) {
427 $clause = '';
428
429 if ($dao->is_required) {
430 $clause = " NOT NULL";
431 }
432
433 if (!empty($dao->default_value)) {
434 $clause .= " DEFAULT '{$dao->default_value}'";
435 }
436 // now modify the column
437 $sql = "
438ALTER TABLE {$tableName}
439MODIFY {$columnName} varchar( $length )
440 $clause
441";
442 CRM_Core_DAO::executeQuery($sql);
443 }
444 else {
445 CRM_Core_Error::fatal(ts('Could Not Find Custom Field Details for %1, %2, %3',
446 array(
447 1 => $tableName,
448 2 => $columnName,
449 3 => $customFieldID
450 )
451 ));
452 }
453 }
454}
455