2 if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
3 /*********************************************************************************
4 * SugarCRM 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(
108 if (isset($dictionary[$bean->getObjectName()]['engine'])) {
109 $engine = $dictionary[$bean->getObjectName()]['engine'];
115 * Returns true if the engine given is enabled in the backend
117 * @param string $engine
120 private function isEngineEnabled(
124 $engine = strtoupper($engine);
126 $r = $this->db->query("SHOW ENGINES");
128 while ( $row = $this->db->fetchByAssoc($r) )
129 if ( strtoupper($row['Engine']) == $engine )
130 return ($row['Support']=='YES' || $row['Support']=='DEFAULT');
136 * @see DBHelper::getColumnType()
138 public function getColumnType(
146 'double' => 'double',
148 'uint' => 'int unsigned',
149 'ulong' => 'bigint unsigned',
151 'short' => 'smallint',
152 'varchar' => 'varchar',
154 'longtext' => 'longtext',
157 'relate' => 'varchar',
158 'multienum'=> 'text',
160 'datetime' => 'datetime',
161 'datetimecombo' => 'datetime',
164 'tinyint' => 'tinyint',
167 'longblob' => 'longblob',
168 'currency' => 'decimal(26,6)',
169 'decimal' => 'decimal',
170 'decimal2' => 'decimal',
173 'encrypt'=>'varchar',
180 * @see DBHelper::oneColumnSQLRep()
182 protected function oneColumnSQLRep(
184 $ignoreRequired = false,
186 $return_as_array = false
189 $ref = parent::oneColumnSQLRep($fieldDef, $ignoreRequired, $table, true);
191 if ( $ref['colType'] == 'int'
192 && !empty($fieldDef['len']) )
193 $ref['colType'] .= "(".$fieldDef['len'].")";
195 // bug 22338 - don't set a default value on text or blob fields
196 if ( isset($ref['default']) &&
197 ($ref['colType'] == 'text' || $ref['colType'] == 'blob'
198 || $ref['colType'] == 'longtext' || $ref['colType'] == 'longblob' ))
199 $ref['default'] = '';
201 if ( $return_as_array )
204 return "{$ref['name']} {$ref['colType']} {$ref['default']} {$ref['required']} {$ref['auto_increment']}";
208 * @see DBHelper::changeColumnSQL()
210 protected function changeColumnSQL(
214 $ignoreRequired = false
217 if ($this->isFieldArray($fieldDefs)){
218 foreach ($fieldDefs as $def){
219 if ($action == 'drop')
220 $columns[] = $def['name'];
222 $columns[] = $this->oneColumnSQLRep($def, $ignoreRequired);
225 if ($action == 'drop')
226 $columns[] = $fieldDefs['name'];
228 $columns[] = $this->oneColumnSQLRep($fieldDefs);
231 return "alter table $tablename $action column ".implode(",$action column ", $columns);
235 * @see DBHelper::deleteColumnSQL()
237 public function deleteColumnSQL(
242 if ($this->isFieldArray($fieldDefs))
243 foreach ($fieldDefs as $fieldDef)
244 $columns[] = $fieldDef['name'];
246 $columns[] = $fieldDefs['name'];
248 return "alter table ".$bean->getTableName()." drop column ".implode(", drop column ", $columns);
252 * @see DBHelper::keysSQL
254 public function keysSQL(
256 $alter_table = false,
260 // check if the passed value is an array of fields.
261 // if not, convert it into an array
262 if (!$this->isFieldArray($indices))
263 $indices[] = $indices;
266 foreach ($indices as $index) {
267 if(!empty($index['db']) && $index['db'] != 'mysql')
270 $type = $index['type'];
271 $name = $index['name'];
273 if (is_array($index['fields']))
274 $fields = implode(", ", $index['fields']);
276 $fields = $index['fields'];
280 $columns[] = " UNIQUE $name ($fields)";
283 $columns[] = " PRIMARY KEY ($fields)";
288 case 'alternate_key':
290 * @todo here it is assumed that the primary key of the foreign
291 * table will always be named 'id'. It must be noted though
292 * that this can easily be fixed by referring to db dictionary
293 * to find the correct primary field name
296 $columns[] = " INDEX $name ($fields)";
298 $columns[] = " KEY $name ($fields)";
301 if ($this->full_text_indexing_enabled())
302 $columns[] = " FULLTEXT ($fields)";
304 $GLOBALS['log']->debug('MYISAM engine is not available/enabled, full-text indexes will be skipped. Skipping:',$name);
308 $columns = implode(", $alter_action ", $columns);
309 if(!empty($alter_action)){
310 $columns = $alter_action . ' '. $columns;
316 * @see DBHelper::setAutoIncrement()
318 protected function setAutoIncrement(
323 return "auto_increment";
327 * Sets the next auto-increment value of a column to a specific value.
329 * @param string $table tablename
330 * @param string $field_name
332 public function setAutoIncrementStart(
338 $this->db->query( "ALTER TABLE $table AUTO_INCREMENT = $start_value;");
344 * Returns the next value for an auto increment
346 * @param string $table tablename
347 * @param string $field_name
350 public function getAutoIncrement(
356 $result = $this->db->query("SHOW TABLE STATUS LIKE '$table'");
357 $row = $this->db->fetchByAssoc($result);
358 if (!empty($row['Auto_increment']))
359 return $row['Auto_increment'];
365 * @see DBHelper::get_indices()
367 public function get_indices(
371 //find all unique indexes and primary keys.
372 $result = $this->db->query("SHOW INDEX FROM $tablename");
375 while (($row=$this->db->fetchByAssoc($result)) !=null) {
377 if ($row['Key_name'] =='PRIMARY') {
378 $index_type='primary';
380 elseif ( $row['Non_unique'] == '0' ) {
381 $index_type='unique';
383 $name = strtolower($row['Key_name']);
384 $indices[$name]['name']=$name;
385 $indices[$name]['type']=$index_type;
386 $indices[$name]['fields'][]=strtolower($row['Column_name']);
392 * @see DBHelper::get_columns()
394 public function get_columns(
398 //find all unique indexes and primary keys.
399 $result = $this->db->query("DESCRIBE $tablename");
402 while (($row=$this->db->fetchByAssoc($result)) !=null) {
403 $name = strtolower($row['Field']);
404 $columns[$name]['name']=$name;
406 preg_match_all("/(\w+)(?:\(([0-9]+,?[0-9]*)\)|)( unsigned)?/i", $row['Type'], $matches);
407 $columns[$name]['type']=strtolower($matches[1][0]);
408 if ( isset($matches[2][0]) && in_array(strtolower($matches[1][0]),array('varchar','char','varchar2','int','decimal','float')) )
409 $columns[$name]['len']=strtolower($matches[2][0]);
410 if ( stristr($row['Extra'],'auto_increment') )
411 $columns[$name]['auto_increment'] = '1';
412 if ($row['Null'] == 'NO' && !stristr($row['Key'],'PRI'))
413 $columns[$name]['required'] = 'true';
414 if ( !empty($row['Default']) )
415 $columns[$name]['default'] = $row['Default'];
421 * @see DBHelper::add_drop_constraint()
423 public function add_drop_constraint(
429 $type = $definition['type'];
430 $fields = implode(',',$definition['fields']);
431 $name = $definition['name'];
432 $foreignTable = isset($definition['foreignTable']) ? $definition['foreignTable'] : array();
438 case 'alternate_key':
440 $sql = "DROP INDEX {$name} ";
442 $sql = "CREATE INDEX {$name} ON {$table} ({$fields})";
444 // constraints as indices
447 $sql = "ALTER TABLE {$table} DROP INDEX $name";
449 $sql = "ALTER TABLE {$table} ADD CONSTRAINT UNIQUE {$name} ({$fields})";
453 $sql = "ALTER TABLE {$table} DROP PRIMARY KEY";
455 $sql = "ALTER TABLE {$table} ADD CONSTRAINT PRIMARY KEY ({$fields})";
459 $sql = "ALTER TABLE {$table} DROP FOREIGN KEY ({$fields})";
461 $sql = "ALTER TABLE {$table} ADD CONSTRAINT FOREIGN KEY {$name} ({$fields}) REFERENCES {$foreignTable}({$foreignfields})";
468 * @see DBHelper::number_of_columns()
470 public function number_of_columns(
474 $result = $this->db->query("DESCRIBE $table_name");
476 return ($this->db->getRowCount($result));
480 * @see DBHelper::full_text_indexing_enabled()
482 protected function full_text_indexing_enabled(
486 return $this->isEngineEnabled('MyISAM');
490 * @see DBHelper::massageFieldDef()
492 public function massageFieldDef(
497 DBHelper::massageFieldDef($fieldDef,$tablename);
499 if ( isset($fieldDef['default']) &&
500 ($fieldDef['dbType'] == 'text'
501 || $fieldDef['dbType'] == 'blob'
502 || $fieldDef['dbType'] == 'longtext'
503 || $fieldDef['dbType'] == 'longblob' ))
504 unset($fieldDef['default']);
505 if ($fieldDef['dbType'] == 'uint')
506 $fieldDef['len'] = '10';
507 if ($fieldDef['dbType'] == 'ulong')
508 $fieldDef['len'] = '20';
509 if ($fieldDef['dbType'] == 'bool')
510 $fieldDef['type'] = 'tinyint';
511 if ($fieldDef['dbType'] == 'bool' && empty($fieldDef['default']) )
512 $fieldDef['default'] = '0';
513 if (($fieldDef['dbType'] == 'varchar' || $fieldDef['dbType'] == 'enum') && empty($fieldDef['len']) )
514 $fieldDef['len'] = '255';
515 if ($fieldDef['dbType'] == 'uint')
516 $fieldDef['len'] = '10';
517 if ($fieldDef['dbType'] == 'int' && empty($fieldDef['len']) )
518 $fieldDef['len'] = '11';