2 if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
3 /*********************************************************************************
4 * SugarCRM Community Edition is a customer relationship management program developed by
5 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
7 * This program is free software; you can redistribute it and/or modify it under
8 * the terms of the GNU Affero General Public License version 3 as published by the
9 * Free Software Foundation with the addition of the following permission added
10 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
11 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
12 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
14 * This program is distributed in the hope that it will be useful, but WITHOUT
15 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
16 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
19 * You should have received a copy of the GNU Affero General Public License along with
20 * this program; if not, see http://www.gnu.org/licenses or write to the Free
21 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
24 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
25 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
27 * The interactive user interfaces in modified source and object code versions
28 * of this program must display Appropriate Legal Notices, as required under
29 * Section 5 of the GNU Affero General Public License version 3.
31 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
32 * these Appropriate Legal Notices must retain the display of the "Powered by
33 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
34 * technical reasons, the Appropriate Legal Notices must display the words
35 * "Powered by SugarCRM".
36 ********************************************************************************/
38 /*********************************************************************************
40 * Description: This file handles the Data base functionality for the application specific
41 * to oracle database. It is called by the DBManager class to generate various sql statements.
43 * All the functions in this class will work with any bean which implements the meta interface.
44 * Please refer the DBManager documentation for the details.
46 * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
47 * All Rights Reserved.
48 * Contributor(s): ______________________________________..
49 ********************************************************************************/
50 require_once('include/database/DBHelper.php');
52 class MysqlHelper extends DBHelper
55 * @see DBHelper::createTableSQL()
57 public function createTableSQL(
61 $tablename = $bean->getTableName();
62 $fieldDefs = $bean->getFieldDefinitions();
63 $indices = $bean->getIndices();
64 $engine = $this->getEngine($bean);
65 return $this->createTableSQLParams($tablename, $fieldDefs, $indices, $engine);
69 * Generates sql for create table statement for a bean.
71 * @param string $tablename
72 * @param array $fieldDefs
73 * @param array $indices
74 * @param string $engine optional, MySQL engine to use
75 * @return string SQL Create Table statement
77 public function createTableSQLParams(
84 if ( empty($engine) && isset($fieldDefs['engine']))
85 $engine = $fieldDefs['engine'];
86 if ( !$this->isEngineEnabled($engine) )
89 $sql = parent::createTableSQLParams($tablename,$fieldDefs,$indices);
91 $sql.= " ENGINE=$engine";
97 * Returns the name of the engine to use or null if we are to use the default
99 * @param object $bean SugarBean instance
102 private function getEngine($bean)
106 if (isset($dictionary[$bean->getObjectName()]['engine'])) {
107 $engine = $dictionary[$bean->getObjectName()]['engine'];
113 * Returns true if the engine given is enabled in the backend
115 * @param string $engine
118 private function isEngineEnabled(
122 $engine = strtoupper($engine);
124 $r = $this->db->query("SHOW ENGINES");
126 while ( $row = $this->db->fetchByAssoc($r) )
127 if ( strtoupper($row['Engine']) == $engine )
128 return ($row['Support']=='YES' || $row['Support']=='DEFAULT');
134 * @see DBHelper::getColumnType()
136 public function getColumnType(
144 'double' => 'double',
146 'uint' => 'int unsigned',
147 'ulong' => 'bigint unsigned',
149 'short' => 'smallint',
150 'varchar' => 'varchar',
152 'longtext' => 'longtext',
155 'relate' => 'varchar',
156 'multienum'=> 'text',
158 'datetime' => 'datetime',
159 'datetimecombo' => 'datetime',
162 'tinyint' => 'tinyint',
165 'longblob' => 'longblob',
166 'currency' => 'decimal(26,6)',
167 'decimal' => 'decimal',
168 'decimal2' => 'decimal',
171 'encrypt'=>'varchar',
179 * @see DBHelper::oneColumnSQLRep()
181 protected function oneColumnSQLRep(
183 $ignoreRequired = false,
185 $return_as_array = false
188 $ref = parent::oneColumnSQLRep($fieldDef, $ignoreRequired, $table, true);
190 if ( $ref['colType'] == 'int'
191 && !empty($fieldDef['len']) )
192 $ref['colType'] .= "(".$fieldDef['len'].")";
194 // bug 22338 - don't set a default value on text or blob fields
195 if ( isset($ref['default']) &&
196 ($ref['colType'] == 'text' || $ref['colType'] == 'blob'
197 || $ref['colType'] == 'longtext' || $ref['colType'] == 'longblob' ))
198 $ref['default'] = '';
200 if ( $return_as_array )
203 return "{$ref['name']} {$ref['colType']} {$ref['default']} {$ref['required']} {$ref['auto_increment']}";
207 * @see DBHelper::changeColumnSQL()
209 protected function changeColumnSQL(
213 $ignoreRequired = false
216 if ($this->isFieldArray($fieldDefs)){
217 foreach ($fieldDefs as $def){
218 if ($action == 'drop')
219 $columns[] = $def['name'];
221 $columns[] = $this->oneColumnSQLRep($def, $ignoreRequired);
224 if ($action == 'drop')
225 $columns[] = $fieldDefs['name'];
227 $columns[] = $this->oneColumnSQLRep($fieldDefs);
230 return "alter table $tablename $action column ".implode(",$action column ", $columns);
234 * @see DBHelper::deleteColumnSQL()
236 public function deleteColumnSQL(
241 if ($this->isFieldArray($fieldDefs))
242 foreach ($fieldDefs as $fieldDef)
243 $columns[] = $fieldDef['name'];
245 $columns[] = $fieldDefs['name'];
247 return "alter table ".$bean->getTableName()." drop column ".implode(", drop column ", $columns);
251 * @see DBHelper::keysSQL
253 public function keysSQL(
255 $alter_table = false,
259 // check if the passed value is an array of fields.
260 // if not, convert it into an array
261 if (!$this->isFieldArray($indices))
262 $indices[] = $indices;
265 foreach ($indices as $index) {
266 if(!empty($index['db']) && $index['db'] != 'mysql')
268 if (isset($index['source']) && $index['source'] != 'db')
271 $type = $index['type'];
272 $name = $index['name'];
274 if (is_array($index['fields']))
275 $fields = implode(", ", $index['fields']);
277 $fields = $index['fields'];
281 $columns[] = " UNIQUE $name ($fields)";
284 $columns[] = " PRIMARY KEY ($fields)";
289 case 'alternate_key':
291 * @todo here it is assumed that the primary key of the foreign
292 * table will always be named 'id'. It must be noted though
293 * that this can easily be fixed by referring to db dictionary
294 * to find the correct primary field name
297 $columns[] = " INDEX $name ($fields)";
299 $columns[] = " KEY $name ($fields)";
302 if ($this->full_text_indexing_enabled())
303 $columns[] = " FULLTEXT ($fields)";
305 $GLOBALS['log']->debug('MYISAM engine is not available/enabled, full-text indexes will be skipped. Skipping:',$name);
309 $columns = implode(", $alter_action ", $columns);
310 if(!empty($alter_action)){
311 $columns = $alter_action . ' '. $columns;
317 * @see DBHelper::setAutoIncrement()
319 protected function setAutoIncrement(
324 return "auto_increment";
328 * Sets the next auto-increment value of a column to a specific value.
330 * @param string $table tablename
331 * @param string $field_name
333 public function setAutoIncrementStart(
339 $this->db->query( "ALTER TABLE $table AUTO_INCREMENT = $start_value;");
345 * Returns the next value for an auto increment
347 * @param string $table tablename
348 * @param string $field_name
351 public function getAutoIncrement(
357 $result = $this->db->query("SHOW TABLE STATUS LIKE '$table'");
358 $row = $this->db->fetchByAssoc($result);
359 if (!empty($row['Auto_increment']))
360 return $row['Auto_increment'];
366 * @see DBHelper::get_indices()
368 public function get_indices(
372 //find all unique indexes and primary keys.
373 $result = $this->db->query("SHOW INDEX FROM $tablename");
376 while (($row=$this->db->fetchByAssoc($result)) !=null) {
378 if ($row['Key_name'] =='PRIMARY') {
379 $index_type='primary';
381 elseif ( $row['Non_unique'] == '0' ) {
382 $index_type='unique';
384 $name = strtolower($row['Key_name']);
385 $indices[$name]['name']=$name;
386 $indices[$name]['type']=$index_type;
387 $indices[$name]['fields'][]=strtolower($row['Column_name']);
393 * @see DBHelper::get_columns()
395 public function get_columns(
399 //find all unique indexes and primary keys.
400 $result = $this->db->query("DESCRIBE $tablename");
403 while (($row=$this->db->fetchByAssoc($result)) !=null) {
404 $name = strtolower($row['Field']);
405 $columns[$name]['name']=$name;
407 preg_match_all("/(\w+)(?:\(([0-9]+,?[0-9]*)\)|)( unsigned)?/i", $row['Type'], $matches);
408 $columns[$name]['type']=strtolower($matches[1][0]);
409 if ( isset($matches[2][0]) && in_array(strtolower($matches[1][0]),array('varchar','char','varchar2','int','decimal','float')) )
410 $columns[$name]['len']=strtolower($matches[2][0]);
411 if ( stristr($row['Extra'],'auto_increment') )
412 $columns[$name]['auto_increment'] = '1';
413 if ($row['Null'] == 'NO' && !stristr($row['Key'],'PRI'))
414 $columns[$name]['required'] = 'true';
415 if (!empty($row['Default']) )
416 $columns[$name]['default'] = $row['Default'];
422 * @see DBHelper::add_drop_constraint()
424 public function add_drop_constraint(
430 $type = $definition['type'];
431 $fields = implode(',',$definition['fields']);
432 $name = $definition['name'];
433 $foreignTable = isset($definition['foreignTable']) ? $definition['foreignTable'] : array();
439 case 'alternate_key':
441 $sql = "DROP INDEX {$name} ";
443 $sql = "CREATE INDEX {$name} ON {$table} ({$fields})";
445 // constraints as indices
448 $sql = "ALTER TABLE {$table} DROP INDEX $name";
450 $sql = "ALTER TABLE {$table} ADD CONSTRAINT UNIQUE {$name} ({$fields})";
454 $sql = "ALTER TABLE {$table} DROP PRIMARY KEY";
456 $sql = "ALTER TABLE {$table} ADD CONSTRAINT PRIMARY KEY ({$fields})";
460 $sql = "ALTER TABLE {$table} DROP FOREIGN KEY ({$fields})";
462 $sql = "ALTER TABLE {$table} ADD CONSTRAINT FOREIGN KEY {$name} ({$fields}) REFERENCES {$foreignTable}({$foreignfields})";
469 * @see DBHelper::number_of_columns()
471 public function number_of_columns(
475 $result = $this->db->query("DESCRIBE $table_name");
477 return ($this->db->getRowCount($result));
481 * @see DBHelper::full_text_indexing_enabled()
483 protected function full_text_indexing_enabled(
487 return $this->isEngineEnabled('MyISAM');
491 * @see DBHelper::massageFieldDef()
493 public function massageFieldDef(
498 DBHelper::massageFieldDef($fieldDef,$tablename);
500 if ( isset($fieldDef['default']) &&
501 ($fieldDef['dbType'] == 'text'
502 || $fieldDef['dbType'] == 'blob'
503 || $fieldDef['dbType'] == 'longtext'
504 || $fieldDef['dbType'] == 'longblob' ))
505 unset($fieldDef['default']);
506 if ($fieldDef['dbType'] == 'uint')
507 $fieldDef['len'] = '10';
508 if ($fieldDef['dbType'] == 'ulong')
509 $fieldDef['len'] = '20';
510 if ($fieldDef['dbType'] == 'bool')
511 $fieldDef['type'] = 'tinyint';
512 if ($fieldDef['dbType'] == 'bool' && empty($fieldDef['default']) )
513 $fieldDef['default'] = '0';
514 if (($fieldDef['dbType'] == 'varchar' || $fieldDef['dbType'] == 'enum') && empty($fieldDef['len']) )
515 $fieldDef['len'] = '255';
516 if ($fieldDef['dbType'] == 'uint')
517 $fieldDef['len'] = '10';
518 if ($fieldDef['dbType'] == 'int' && empty($fieldDef['len']) )
519 $fieldDef['len'] = '11';