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-2012 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.
41 * It acts as the DB abstraction layer for the application. It depends on helper classes
42 * which generate the necessary SQL. This sql is then passed to PEAR DB classes.
43 * The helper class is chosen in DBManagerFactory, which is driven by 'db_type' in 'dbconfig' under config.php.
45 * All the functions in this class will work with any bean which implements the meta interface.
46 * The passed bean is passed to helper class which uses these functions to generate correct sql.
48 * The meta interface has the following functions:
49 * getTableName() Returns table name of the object.
50 * getFieldDefinitions() Returns a collection of field definitions in order.
51 * getFieldDefintion(name) Return field definition for the field.
52 * getFieldValue(name) Returns the value of the field identified by name.
53 * If the field is not set, the function will return boolean FALSE.
54 * getPrimaryFieldDefinition() Returns the field definition for primary key
56 * The field definition is an array with the following keys:
58 * name This represents name of the field. This is a required field.
59 * type This represents type of the field. This is a required field and valid values are:
73 * length This is used only when the type is varchar and denotes the length of the string.
74 * The max value is 255.
75 * enumvals This is a list of valid values for an enum separated by "|".
76 * It is used only if the type is �enum�;
77 * required This field dictates whether it is a required value.
78 * The default value is �FALSE�.
79 * isPrimary This field identifies the primary key of the table.
80 * If none of the fields have this flag set to �TRUE�,
81 * the first field definition is assume to be the primary key.
82 * Default value for this field is �FALSE�.
83 * default This field sets the default value for the field definition.
86 * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
87 * All Rights Reserved.
88 * Contributor(s): ______________________________________..
89 ********************************************************************************/
92 * MySQL manager implementation for mysql extension
94 class MysqlManager extends DBManager
97 * @see DBManager::$dbType
99 public $dbType = 'mysql';
100 public $variant = 'mysql';
101 public $dbName = 'MySQL';
102 public $label = 'LBL_MYSQL';
104 protected $maxNameLengths = array(
111 protected $type_map = array(
113 'double' => 'double',
115 'uint' => 'int unsigned',
116 'ulong' => 'bigint unsigned',
118 'short' => 'smallint',
119 'varchar' => 'varchar',
121 'longtext' => 'longtext',
124 'relate' => 'varchar',
125 'multienum'=> 'text',
127 'longhtml' => 'longtext',
128 'datetime' => 'datetime',
129 'datetimecombo' => 'datetime',
132 'tinyint' => 'tinyint',
135 'longblob' => 'longblob',
136 'currency' => 'decimal(26,6)',
137 'decimal' => 'decimal',
138 'decimal2' => 'decimal',
141 'encrypt' => 'varchar',
143 'decimal_tpl' => 'decimal(%d, %d)',
147 protected $capabilities = array(
148 "affected_rows" => true,
149 "select_rows" => true,
150 "inline_keys" => true,
151 "create_user" => true,
155 "disable_keys" => true,
159 * Parses and runs queries
161 * @param string $sql SQL Statement to execute
162 * @param bool $dieOnError True if we want to call die if the query returns errors
163 * @param string $msg Message to log if error occurs
164 * @param bool $suppress Flag to suppress all error output unless in debug logging mode.
165 * @param bool $keepResult True if we want to push this result into the $lastResult array.
166 * @return resource result set
168 public function query($sql, $dieOnError = false, $msg = '', $suppress = false, $keepResult = false)
171 return $this->queryArray($sql, $dieOnError, $msg, $suppress);
174 parent::countQuery($sql);
175 $GLOBALS['log']->info('Query:' . $sql);
176 $this->checkConnection();
177 $this->query_time = microtime(true);
178 $this->lastsql = $sql;
179 $result = $suppress?@mysql_query($sql, $this->database):mysql_query($sql, $this->database);
181 $this->query_time = microtime(true) - $this->query_time;
182 $GLOBALS['log']->info('Query Execution Time:'.$this->query_time);
186 $this->lastResult = $result;
188 $this->checkError($msg.' Query Failed:' . $sql . '::', $dieOnError);
193 * Returns the number of rows affected by the last query
197 public function getAffectedRowCount($result)
199 return mysql_affected_rows($this->getDatabase());
203 * Returns the number of rows returned by the result
205 * This function can't be reliably implemented on most DB, do not use it.
208 * @param resource $result
211 public function getRowCount($result)
213 return mysql_num_rows($result);
217 * Disconnects from the database
219 * Also handles any cleanup needed
221 public function disconnect()
223 $GLOBALS['log']->debug('Calling MySQL::disconnect()');
224 if(!empty($this->database)){
226 mysql_close($this->database);
227 $this->database = null;
232 * @see DBManager::freeDbResult()
234 protected function freeDbResult($dbResult)
236 if(!empty($dbResult))
237 mysql_free_result($dbResult);
243 * Check if query has LIMIT clause
244 * Relevant for now only for Mysql
248 protected function hasLimit($sql)
250 return stripos($sql, " limit ") !== false;
254 * @see DBManager::limitQuery()
256 public function limitQuery($sql, $start, $count, $dieOnError = false, $msg = '', $execute = true)
258 $start = (int)$start;
259 $count = (int)$count;
262 $GLOBALS['log']->debug('Limit Query:' . $sql. ' Start: ' .$start . ' count: ' . $count);
264 $sql = "$sql LIMIT $start,$count";
265 $this->lastsql = $sql;
267 if(!empty($GLOBALS['sugar_config']['check_query'])){
268 $this->checkQuery($sql);
274 return $this->query($sql, $dieOnError, $msg);
279 * @see DBManager::checkQuery()
281 protected function checkQuery($sql)
283 $result = $this->query('EXPLAIN ' . $sql);
285 while ($row = $this->fetchByAssoc($result)) {
286 if (empty($row['table']))
288 $badQuery[$row['table']] = '';
289 if (strtoupper($row['type']) == 'ALL')
290 $badQuery[$row['table']] .= ' Full Table Scan;';
291 if (empty($row['key']))
292 $badQuery[$row['table']] .= ' No Index Key Used;';
293 if (!empty($row['Extra']) && substr_count($row['Extra'], 'Using filesort') > 0)
294 $badQuery[$row['table']] .= ' Using FileSort;';
295 if (!empty($row['Extra']) && substr_count($row['Extra'], 'Using temporary') > 0)
296 $badQuery[$row['table']] .= ' Using Temporary Table;';
299 if ( empty($badQuery) )
302 foreach($badQuery as $table=>$data ){
304 $warning = ' Table:' . $table . ' Data:' . $data;
305 if(!empty($GLOBALS['sugar_config']['check_query_log'])){
306 $GLOBALS['log']->fatal($sql);
307 $GLOBALS['log']->fatal('CHECK QUERY:' .$warning);
310 $GLOBALS['log']->warn('CHECK QUERY:' .$warning);
319 * @see DBManager::get_columns()
321 public function get_columns($tablename)
323 //find all unique indexes and primary keys.
324 $result = $this->query("DESCRIBE $tablename");
327 while (($row=$this->fetchByAssoc($result)) !=null) {
328 $name = strtolower($row['Field']);
329 $columns[$name]['name']=$name;
331 preg_match_all('/(\w+)(?:\(([0-9]+,?[0-9]*)\)|)( unsigned)?/i', $row['Type'], $matches);
332 $columns[$name]['type']=strtolower($matches[1][0]);
333 if ( isset($matches[2][0]) && in_array(strtolower($matches[1][0]),array('varchar','char','varchar2','int','decimal','float')) )
334 $columns[$name]['len']=strtolower($matches[2][0]);
335 if ( stristr($row['Extra'],'auto_increment') )
336 $columns[$name]['auto_increment'] = '1';
337 if ($row['Null'] == 'NO' && !stristr($row['Key'],'PRI'))
338 $columns[$name]['required'] = 'true';
339 if (!empty($row['Default']) )
340 $columns[$name]['default'] = $row['Default'];
346 * @see DBManager::getFieldsArray()
348 public function getFieldsArray($result, $make_lower_case=false)
350 $field_array = array();
355 $fields = mysql_num_fields($result);
356 for ($i=0; $i < $fields; $i++) {
357 $meta = mysql_fetch_field($result, $i);
361 if($make_lower_case == true)
362 $meta->name = strtolower($meta->name);
364 $field_array[] = $meta->name;
371 * @see DBManager::fetchRow()
373 public function fetchRow($result)
375 if (empty($result)) return false;
377 return mysql_fetch_assoc($result);
381 * @see DBManager::getTablesArray()
383 public function getTablesArray()
385 $this->log->debug('Fetching table list');
387 if ($this->getDatabase()) {
389 $r = $this->query('SHOW TABLES');
391 while ($a = $this->fetchByAssoc($r)) {
392 $row = array_values($a);
399 return false; // no database available
403 * @see DBManager::version()
405 public function version()
407 return $this->getOne("SELECT version() version");
411 * @see DBManager::tableExists()
413 public function tableExists($tableName)
415 $this->log->info("tableExists: $tableName");
417 if ($this->getDatabase()) {
418 $result = $this->query("SHOW TABLES LIKE ".$this->quoted($tableName));
419 if(empty($result)) return false;
420 $row = $this->fetchByAssoc($result);
428 * Get tables like expression
429 * @param $like string
432 public function tablesLike($like)
434 if ($this->getDatabase()) {
436 $r = $this->query('SHOW TABLES LIKE '.$this->quoted($like));
438 while ($a = $this->fetchByAssoc($r)) {
439 $row = array_values($a);
449 * @see DBManager::quote()
451 public function quote($string)
453 if(is_array($string)) {
454 return $this->arrayQuote($string);
456 return mysql_real_escape_string($this->quoteInternal($string), $this->getDatabase());
460 * @see DBManager::connect()
462 public function connect(array $configOptions = null, $dieOnError = false)
464 global $sugar_config;
466 if(is_null($configOptions))
467 $configOptions = $sugar_config['dbconfig'];
469 if ($this->getOption('persistent')) {
470 $this->database = @mysql_pconnect(
471 $configOptions['db_host_name'],
472 $configOptions['db_user_name'],
473 $configOptions['db_password']
477 if (!$this->database) {
478 $this->database = mysql_connect(
479 $configOptions['db_host_name'],
480 $configOptions['db_user_name'],
481 $configOptions['db_password']
483 if(empty($this->database)) {
484 $GLOBALS['log']->fatal("Could not connect to server ".$configOptions['db_host_name']." as ".$configOptions['db_user_name'].":".mysql_error());
486 if(isset($GLOBALS['app_strings']['ERR_NO_DB'])) {
487 sugar_die($GLOBALS['app_strings']['ERR_NO_DB']);
489 sugar_die("Could not connect to the database. Please refer to sugarcrm.log for details.");
495 // Do not pass connection information because we have not connected yet
496 if($this->database && $this->getOption('persistent')){
497 $_SESSION['administrator_error'] = "<b>Severe Performance Degradation: Persistent Database Connections "
498 . "not working. Please set \$sugar_config['dbconfigoption']['persistent'] to false "
499 . "in your config.php file</b>";
502 if(!empty($configOptions['db_name']) && !@mysql_select_db($configOptions['db_name'])) {
503 $GLOBALS['log']->fatal( "Unable to select database {$configOptions['db_name']}: " . mysql_error($this->database));
505 sugar_die($GLOBALS['app_strings']['ERR_NO_DB']);
511 // cn: using direct calls to prevent this from spamming the Logs
512 mysql_query("SET CHARACTER SET utf8", $this->database);
513 $names = "SET NAMES 'utf8'";
514 $collation = $this->getOption('collation');
515 if(!empty($collation)) {
516 $names .= " COLLATE '$collation'";
518 mysql_query($names, $this->database);
520 if(!$this->checkError('Could Not Connect:', $dieOnError))
521 $GLOBALS['log']->info("connected to db");
522 $this->connectOptions = $configOptions;
524 $GLOBALS['log']->info("Connect:".$this->database);
529 * @see DBManager::repairTableParams()
531 * For MySQL, we can write the ALTER TABLE statement all in one line, which speeds things
532 * up quite a bit. So here, we'll parse the returned SQL into a single ALTER TABLE command.
534 public function repairTableParams($tablename, $fielddefs, $indices, $execute = true, $engine = null)
536 $sql = parent::repairTableParams($tablename,$fielddefs,$indices,false,$engine);
541 if ( stristr($sql,'create table') )
544 $msg = "Error creating table: ".$tablename. ":";
545 $this->query($sql,true,$msg);
550 // first, parse out all the comments
552 preg_match_all('!/\*.*?\*/!is', $sql, $match);
553 $commentBlocks = $match[0];
554 $sql = preg_replace('!/\*.*?\*/!is','', $sql);
556 // now, we should only have alter table statements
557 // let's replace the 'alter table name' part with a comma
558 $sql = preg_replace("!alter table $tablename!is",', ', $sql);
560 // re-add it at the beginning
561 $sql = substr_replace($sql,'',strpos($sql,','),1);
562 $sql = str_replace(";","",$sql);
563 $sql = str_replace("\n","",$sql);
564 $sql = "ALTER TABLE $tablename $sql";
567 $this->query($sql,'Error with MySQL repair table');
569 // and re-add the comments at the beginning
570 $sql = implode("\n",$commentBlocks) . "\n". $sql . "\n";
576 * @see DBManager::convert()
578 public function convert($string, $type, array $additional_parameters = array())
580 $all_parameters = $additional_parameters;
581 if(is_array($string)) {
582 $all_parameters = array_merge($string, $all_parameters);
583 } elseif (!is_null($string)) {
584 array_unshift($all_parameters, $string);
586 $all_strings = implode(',', $all_parameters);
588 switch (strtolower($type)) {
592 return "LEFT($all_strings)";
594 if(empty($additional_parameters)) {
595 return "DATE_FORMAT($string,'%Y-%m-%d')";
597 $format = $additional_parameters[0];
598 if($format[0] != "'") {
599 $format = $this->quoted($format);
601 return "DATE_FORMAT($string,$format)";
604 if(empty($additional_parameters) && !strstr($all_strings, ",")) {
605 $all_strings .= ",''";
607 return "IFNULL($all_strings)";
609 return "CONCAT($all_strings)";
611 return "QUARTER($string)";
613 return "LENGTH($string)";
615 return "MONTH($string)";
617 return "DATE_ADD($string, INTERVAL {$additional_parameters[0]} {$additional_parameters[1]})";
619 return "DATE_ADD($string, INTERVAL + CONCAT({$additional_parameters[0]}, ':', {$additional_parameters[1]}) HOUR_MINUTE)";
627 * @see DBManager::fromConvert()
629 public function fromConvert($string, $type)
635 * Returns the name of the engine to use or null if we are to use the default
637 * @param object $bean SugarBean instance
640 protected function getEngine($bean)
644 if (isset($dictionary[$bean->getObjectName()]['engine'])) {
645 $engine = $dictionary[$bean->getObjectName()]['engine'];
651 * Returns true if the engine given is enabled in the backend
653 * @param string $engine
656 protected function isEngineEnabled($engine)
658 if(!is_string($engine)) return false;
660 $engine = strtoupper($engine);
662 $r = $this->query("SHOW ENGINES");
664 while ( $row = $this->fetchByAssoc($r) )
665 if ( strtoupper($row['Engine']) == $engine )
666 return ($row['Support']=='YES' || $row['Support']=='DEFAULT');
672 * @see DBManager::createTableSQL()
674 public function createTableSQL(SugarBean $bean)
676 $tablename = $bean->getTableName();
677 $fieldDefs = $bean->getFieldDefinitions();
678 $indices = $bean->getIndices();
679 $engine = $this->getEngine($bean);
680 return $this->createTableSQLParams($tablename, $fieldDefs, $indices, $engine);
684 * Generates sql for create table statement for a bean.
686 * @param string $tablename
687 * @param array $fieldDefs
688 * @param array $indices
689 * @param string $engine optional, MySQL engine to use
690 * @return string SQL Create Table statement
692 public function createTableSQLParams($tablename, $fieldDefs, $indices, $engine = null)
694 if ( empty($engine) && isset($fieldDefs['engine']))
695 $engine = $fieldDefs['engine'];
696 if ( !$this->isEngineEnabled($engine) )
699 $columns = $this->columnSQLRep($fieldDefs, false, $tablename);
703 $keys = $this->keysSQL($indices);
707 // cn: bug 9873 - module tables do not get created in utf8 with assoc collation
708 $collation = $this->getOption('collation');
709 if(empty($collation)) {
710 $collation = 'utf8_general_ci';
712 $sql = "CREATE TABLE $tablename ($columns $keys) CHARACTER SET utf8 COLLATE $collation";
715 $sql.= " ENGINE=$engine";
721 * Does this type represent text (i.e., non-varchar) value?
722 * @param string $type
724 public function isTextType($type)
726 $type = $this->getColumnType(strtolower($type));
727 return in_array($type, array('blob','text','longblob', 'longtext'));
731 * @see DBManager::oneColumnSQLRep()
733 protected function oneColumnSQLRep($fieldDef, $ignoreRequired = false, $table = '', $return_as_array = false)
735 // always return as array for post-processing
736 $ref = parent::oneColumnSQLRep($fieldDef, $ignoreRequired, $table, true);
738 if ( $ref['colType'] == 'int' && !empty($fieldDef['len']) ) {
739 $ref['colType'] .= "(".$fieldDef['len'].")";
742 // bug 22338 - don't set a default value on text or blob fields
743 if ( isset($ref['default']) &&
744 in_array($ref['colBaseType'], array('text', 'blob', 'longtext', 'longblob')))
745 $ref['default'] = '';
747 if ( $return_as_array )
750 return "{$ref['name']} {$ref['colType']} {$ref['default']} {$ref['required']} {$ref['auto_increment']}";
754 * @see DBManager::changeColumnSQL()
756 protected function changeColumnSQL($tablename, $fieldDefs, $action, $ignoreRequired = false)
759 if ($this->isFieldArray($fieldDefs)){
760 foreach ($fieldDefs as $def){
761 if ($action == 'drop')
762 $columns[] = $def['name'];
764 $columns[] = $this->oneColumnSQLRep($def, $ignoreRequired);
767 if ($action == 'drop')
768 $columns[] = $fieldDefs['name'];
770 $columns[] = $this->oneColumnSQLRep($fieldDefs);
773 return "ALTER TABLE $tablename $action COLUMN ".implode(",$action column ", $columns);
777 * Generates SQL for key specification inside CREATE TABLE statement
779 * The passes array is an array of field definitions or a field definition
780 * itself. The keys generated will be either primary, foreign, unique, index
781 * or none at all depending on the setting of the "key" parameter of a field definition
783 * @param array $indices
784 * @param bool $alter_table
785 * @param string $alter_action
786 * @return string SQL Statement
788 protected function keysSQL($indices, $alter_table = false, $alter_action = '')
790 // check if the passed value is an array of fields.
791 // if not, convert it into an array
792 if (!$this->isFieldArray($indices))
793 $indices[] = $indices;
796 foreach ($indices as $index) {
797 if(!empty($index['db']) && $index['db'] != $this->dbType)
799 if (isset($index['source']) && $index['source'] != 'db')
802 $type = $index['type'];
803 $name = $index['name'];
805 if (is_array($index['fields']))
806 $fields = implode(", ", $index['fields']);
808 $fields = $index['fields'];
812 $columns[] = " UNIQUE $name ($fields)";
815 $columns[] = " PRIMARY KEY ($fields)";
820 case 'alternate_key':
822 * @todo here it is assumed that the primary key of the foreign
823 * table will always be named 'id'. It must be noted though
824 * that this can easily be fixed by referring to db dictionary
825 * to find the correct primary field name
828 $columns[] = " INDEX $name ($fields)";
830 $columns[] = " KEY $name ($fields)";
833 if ($this->full_text_indexing_installed())
834 $columns[] = " FULLTEXT ($fields)";
836 $GLOBALS['log']->debug('MYISAM engine is not available/enabled, full-text indexes will be skipped. Skipping:',$name);
840 $columns = implode(", $alter_action ", $columns);
841 if(!empty($alter_action)){
842 $columns = $alter_action . ' '. $columns;
848 * @see DBManager::setAutoIncrement()
850 protected function setAutoIncrement($table, $field_name)
852 return "auto_increment";
856 * Sets the next auto-increment value of a column to a specific value.
858 * @param string $table tablename
859 * @param string $field_name
861 public function setAutoIncrementStart($table, $field_name, $start_value)
863 $start_value = (int)$start_value;
864 return $this->query( "ALTER TABLE $table AUTO_INCREMENT = $start_value;");
868 * Returns the next value for an auto increment
870 * @param string $table tablename
871 * @param string $field_name
874 public function getAutoIncrement($table, $field_name)
876 $result = $this->query("SHOW TABLE STATUS LIKE '$table'");
877 $row = $this->fetchByAssoc($result);
878 if (!empty($row['Auto_increment']))
879 return $row['Auto_increment'];
885 * @see DBManager::get_indices()
887 public function get_indices($tablename)
889 //find all unique indexes and primary keys.
890 $result = $this->query("SHOW INDEX FROM $tablename");
893 while (($row=$this->fetchByAssoc($result)) !=null) {
895 if ($row['Key_name'] =='PRIMARY') {
896 $index_type='primary';
898 elseif ( $row['Non_unique'] == '0' ) {
899 $index_type='unique';
901 $name = strtolower($row['Key_name']);
902 $indices[$name]['name']=$name;
903 $indices[$name]['type']=$index_type;
904 $indices[$name]['fields'][]=strtolower($row['Column_name']);
910 * @see DBManager::add_drop_constraint()
912 public function add_drop_constraint($table, $definition, $drop = false)
914 $type = $definition['type'];
915 $fields = implode(',',$definition['fields']);
916 $name = $definition['name'];
922 case 'alternate_key':
925 $sql = "ALTER TABLE {$table} DROP INDEX {$name} ";
927 $sql = "ALTER TABLE {$table} ADD INDEX {$name} ({$fields})";
929 // constraints as indices
932 $sql = "ALTER TABLE {$table} DROP INDEX $name";
934 $sql = "ALTER TABLE {$table} ADD CONSTRAINT UNIQUE {$name} ({$fields})";
938 $sql = "ALTER TABLE {$table} DROP PRIMARY KEY";
940 $sql = "ALTER TABLE {$table} ADD CONSTRAINT PRIMARY KEY ({$fields})";
944 $sql = "ALTER TABLE {$table} DROP FOREIGN KEY ({$fields})";
946 $sql = "ALTER TABLE {$table} ADD CONSTRAINT FOREIGN KEY {$name} ({$fields}) REFERENCES {$definition['foreignTable']}({$definition['foreignField']})";
953 * Runs a query and returns a single row
955 * @param string $sql SQL Statement to execute
956 * @param bool $dieOnError True if we want to call die if the query returns errors
957 * @param string $msg Message to log if error occurs
958 * @param bool $suppress Message to log if error occurs
959 * @return array single row from the query
961 public function fetchOne($sql, $dieOnError = false, $msg = '', $suppress = false)
963 if(stripos($sql, ' LIMIT ') === false) {
964 // little optimization to just fetch one row
965 $sql .= " LIMIT 0,1";
967 return parent::fetchOne($sql, $dieOnError, $msg, $suppress);
971 * @see DBManager::full_text_indexing_installed()
973 public function full_text_indexing_installed($dbname = null)
975 return $this->isEngineEnabled('MyISAM');
979 * @see DBManager::massageFieldDef()
981 public function massageFieldDef(&$fieldDef, $tablename)
983 parent::massageFieldDef($fieldDef,$tablename);
985 if ( isset($fieldDef['default']) &&
986 ($fieldDef['dbType'] == 'text'
987 || $fieldDef['dbType'] == 'blob'
988 || $fieldDef['dbType'] == 'longtext'
989 || $fieldDef['dbType'] == 'longblob' ))
990 unset($fieldDef['default']);
991 if ($fieldDef['dbType'] == 'uint')
992 $fieldDef['len'] = '10';
993 if ($fieldDef['dbType'] == 'ulong')
994 $fieldDef['len'] = '20';
995 if ($fieldDef['dbType'] == 'bool')
996 $fieldDef['type'] = 'tinyint';
997 if ($fieldDef['dbType'] == 'bool' && empty($fieldDef['default']) )
998 $fieldDef['default'] = '0';
999 if (($fieldDef['dbType'] == 'varchar' || $fieldDef['dbType'] == 'enum') && empty($fieldDef['len']) )
1000 $fieldDef['len'] = '255';
1001 if ($fieldDef['dbType'] == 'uint')
1002 $fieldDef['len'] = '10';
1003 if ($fieldDef['dbType'] == 'int' && empty($fieldDef['len']) )
1004 $fieldDef['len'] = '11';
1006 if($fieldDef['dbType'] == 'decimal') {
1007 if(isset($fieldDef['len'])) {
1008 if(strstr($fieldDef['len'], ",") === false) {
1009 $fieldDef['len'] .= ",0";
1012 $fieldDef['len'] = '10,0';
1018 * Generates SQL for dropping a table.
1020 * @param string $name table name
1021 * @return string SQL statement
1023 public function dropTableNameSQL($name)
1025 return "DROP TABLE IF EXISTS ".$name;
1028 public function dropIndexes($tablename, $indexes, $execute = true)
1031 foreach ($indexes as $index) {
1032 $name =$index['name'];
1034 unset(self::$index_descriptions[$tablename][$name]);
1036 if ($index['type'] == 'primary') {
1037 $sql[] = 'DROP PRIMARY KEY';
1039 $sql[] = "DROP INDEX $name";
1043 $sql = "ALTER TABLE $tablename ".join(",", $sql);
1053 * List of available collation settings
1056 public function getDefaultCollation()
1058 return "utf8_general_ci";
1062 * List of available collation settings
1065 public function getCollationList()
1067 $q = "SHOW COLLATION LIKE 'utf8%'";
1068 $r = $this->query($q);
1070 while($a = $this->fetchByAssoc($r)) {
1071 $res[] = $a['Collation'];
1078 * @see DBManager::renameColumnSQL()
1080 public function renameColumnSQL($tablename, $column, $newname)
1082 $field = $this->describeField($column, $tablename);
1083 $field['name'] = $newname;
1084 return "ALTER TABLE $tablename CHANGE COLUMN $column ".$this->oneColumnSQLRep($field);
1087 public function emptyValue($type)
1089 $ctype = $this->getColumnType($type);
1090 if($ctype == "datetime") {
1091 return $this->convert($this->quoted("0000-00-00 00:00:00"), "datetime");
1093 if($ctype == "date") {
1094 return $this->convert($this->quoted("0000-00-00"), "date");
1096 if($ctype == "time") {
1097 return $this->convert($this->quoted("00:00:00"), "time");
1099 return parent::emptyValue($type);
1104 * @see DBManager::lastDbError()
1106 public function lastDbError()
1108 if($this->database) {
1109 if(mysql_errno($this->database)) {
1110 return "MySQL error ".mysql_errno($this->database).": ".mysql_error($this->database);
1113 $err = mysql_error();
1122 * Quote MySQL search term
1123 * @param unknown_type $term
1125 protected function quoteTerm($term)
1127 if(strpos($term, ' ') !== false) {
1128 return '"'.$term.'"';
1134 * Generate fulltext query from set of terms
1135 * @param string $fields Field to search against
1136 * @param array $terms Search terms that may be or not be in the result
1137 * @param array $must_terms Search terms that have to be in the result
1138 * @param array $exclude_terms Search terms that have to be not in the result
1140 public function getFulltextQuery($field, $terms, $must_terms = array(), $exclude_terms = array())
1142 $condition = array();
1143 foreach($terms as $term) {
1144 $condition[] = $this->quoteTerm($term);
1146 foreach($must_terms as $term) {
1147 $condition[] = "+".$this->quoteTerm($term);
1149 foreach($exclude_terms as $term) {
1150 $condition[] = "-".$this->quoteTerm($term);
1152 $condition = $this->quoted(join(" ",$condition));
1153 return "MATCH($field) AGAINST($condition IN BOOLEAN MODE)";
1157 * Get list of all defined charsets
1160 protected function getCharsetInfo()
1162 $charsets = array();
1163 $res = $this->query("show variables like 'character\\_set\\_%'");
1164 while($row = $this->fetchByAssoc($res)) {
1165 $charsets[$row['Variable_name']] = $row['Value'];
1170 public function getDbInfo()
1172 $charsets = $this->getCharsetInfo();
1173 $charset_str = array();
1174 foreach($charsets as $name => $value) {
1175 $charset_str[] = "$name = $value";
1178 "MySQL Version" => @mysql_get_client_info(),
1179 "MySQL Host Info" => @mysql_get_host_info($this->database),
1180 "MySQL Server Info" => @mysql_get_server_info($this->database),
1181 "MySQL Client Encoding" => @mysql_client_encoding($this->database),
1182 "MySQL Character Set Settings" => join(", ", $charset_str),
1186 public function validateQuery($query)
1188 $res = $this->query("EXPLAIN $query");
1189 return !empty($res);
1192 protected function makeTempTableCopy($table)
1194 $this->log->debug("creating temp table for [$table]...");
1195 $result = $this->query("SHOW CREATE TABLE {$table}");
1196 if(empty($result)) {
1199 $row = $this->fetchByAssoc($result);
1200 if(empty($row) || empty($row['Create Table'])) {
1203 $create = $row['Create Table'];
1204 // rewrite DDL with _temp name
1205 $tempTableQuery = str_replace("CREATE TABLE `{$table}`", "CREATE TABLE `{$table}__uw_temp`", $create);
1206 $r2 = $this->query($tempTableQuery);
1211 // get sample data into the temp table to test for data/constraint conflicts
1212 $this->log->debug('inserting temp dataset...');
1213 $q3 = "INSERT INTO `{$table}__uw_temp` SELECT * FROM `{$table}` LIMIT 10";
1214 $this->query($q3, false, "Preflight Failed for: {$q3}");
1219 * Tests an ALTER TABLE query
1220 * @param string table The table name to get DDL
1221 * @param string query The query to test.
1222 * @return string Non-empty if error found
1224 protected function verifyAlterTable($table, $query)
1226 $this->log->debug("verifying ALTER TABLE");
1227 // Skipping ALTER TABLE [table] DROP PRIMARY KEY because primary keys are not being copied
1228 // over to the temp tables
1229 if(strpos(strtoupper($query), 'DROP PRIMARY KEY') !== false) {
1230 $this->log->debug("Skipping DROP PRIMARY KEY");
1233 if(!$this->makeTempTableCopy($table)) {
1234 return 'Could not create temp table copy';
1237 // test the query on the test table
1238 $this->log->debug('testing query: ['.$query.']');
1239 $tempTableTestQuery = str_replace("ALTER TABLE `{$table}`", "ALTER TABLE `{$table}__uw_temp`", $query);
1240 if (strpos($tempTableTestQuery, 'idx') === false) {
1241 if(strpos($tempTableTestQuery, '__uw_temp') === false) {
1242 return 'Could not use a temp table to test query!';
1245 $this->log->debug('testing query on temp table: ['.$tempTableTestQuery.']');
1246 $this->query($tempTableTestQuery, false, "Preflight Failed for: {$query}");
1248 // test insertion of an index on a table
1249 $tempTableTestQuery_idx = str_replace("ADD INDEX `idx_", "ADD INDEX `temp_idx_", $tempTableTestQuery);
1250 $this->log->debug('testing query on temp table: ['.$tempTableTestQuery_idx.']');
1251 $this->query($tempTableTestQuery_idx, false, "Preflight Failed for: {$query}");
1253 $mysqlError = $this->getL();
1254 if(!empty($mysqlError)) {
1257 $this->dropTableName("{$table}__uw_temp");
1262 protected function verifyGenericReplaceQuery($querytype, $table, $query)
1264 $this->log->debug("verifying $querytype statement");
1266 if(!$this->makeTempTableCopy($table)) {
1267 return 'Could not create temp table copy';
1269 // test the query on the test table
1270 $this->log->debug('testing query: ['.$query.']');
1271 $tempTableTestQuery = str_replace("$querytype `{$table}`", "$querytype `{$table}__uw_temp`", $query);
1272 if(strpos($tempTableTestQuery, '__uw_temp') === false) {
1273 return 'Could not use a temp table to test query!';
1276 $this->query($tempTableTestQuery, false, "Preflight Failed for: {$query}");
1277 $error = $this->lastError(); // empty on no-errors
1278 $this->dropTableName("{$table}__uw_temp"); // just in case
1283 * Tests a DROP TABLE query
1284 * @param string table The table name to get DDL
1285 * @param string query The query to test.
1286 * @return string Non-empty if error found
1288 public function verifyDropTable($table, $query)
1290 return $this->verifyGenericReplaceQuery("DROP TABLE", $table, $query);
1294 * Tests an INSERT INTO query
1295 * @param string table The table name to get DDL
1296 * @param string query The query to test.
1297 * @return string Non-empty if error found
1299 public function verifyInsertInto($table, $query)
1301 return $this->verifyGenericReplaceQuery("INSERT INTO", $table, $query);
1305 * Tests an UPDATE query
1306 * @param string table The table name to get DDL
1307 * @param string query The query to test.
1308 * @return string Non-empty if error found
1310 public function verifyUpdate($table, $query)
1312 return $this->verifyGenericReplaceQuery("UPDATE", $table, $query);
1316 * Tests an DELETE FROM query
1317 * @param string table The table name to get DDL
1318 * @param string query The query to test.
1319 * @return string Non-empty if error found
1321 public function verifyDeleteFrom($table, $query)
1323 return $this->verifyGenericReplaceQuery("DELETE FROM", $table, $query);
1327 * Check if certain database exists
1328 * @param string $dbname
1330 public function dbExists($dbname)
1332 $db = $this->getOne("SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = ".$this->quoted($dbname));
1338 * @param string $dbname
1340 protected function selectDb($dbname)
1342 return mysql_select_db($dbname);
1346 * Check if certain DB user exists
1347 * @param string $username
1349 public function userExists($username)
1351 $db = $this->getOne("SELECT DATABASE()");
1352 if(!$this->selectDb("mysql")) {
1355 $user = $this->getOne("select count(*) from user where user = ".$this->quoted($username));
1356 if(!$this->selectDb($db)) {
1357 $this->checkError("Cannot select database $db", true);
1359 return !empty($user);
1364 * @param string $database_name
1365 * @param string $host_name
1366 * @param string $user
1367 * @param string $password
1369 public function createDbUser($database_name, $host_name, $user, $password)
1371 $qpassword = $this->quote($password);
1372 $this->query("GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, ALTER, DROP, INDEX
1373 ON `$database_name`.*
1374 TO \"$user\"@\"$host_name\"
1375 IDENTIFIED BY '{$qpassword}';", true);
1377 $this->query("SET PASSWORD FOR \"{$user}\"@\"{$host_name}\" = password('{$qpassword}');", true);
1378 if($host_name != 'localhost') {
1379 $this->createDbUser($database_name, "localhost", $user, $password);
1385 * @param string $dbname
1387 public function createDatabase($dbname)
1389 $this->query("CREATE DATABASE `$dbname` CHARACTER SET utf8 COLLATE utf8_general_ci", true);
1392 public function preInstall()
1394 $db->query("ALTER DATABASE `{$setup_db_database_name}` DEFAULT CHARACTER SET utf8", true);
1395 $db->query("ALTER DATABASE `{$setup_db_database_name}` DEFAULT COLLATE utf8_general_ci", true);
1401 * @param string $dbname
1403 public function dropDatabase($dbname)
1405 return $this->query("DROP DATABASE IF EXISTS `$dbname`", true);
1409 * Check if this driver can be used
1412 public function valid()
1414 return function_exists("mysql_connect");
1419 * @see DBManager::canInstall()
1421 public function canInstall()
1423 $db_version = $this->version();
1424 if(empty($db_version)) {
1425 return array('ERR_DB_VERSION_FAILURE');
1427 if(version_compare($db_version, '4.1.2') < 0) {
1428 return array('ERR_DB_MYSQL_VERSION', $db_version);
1433 public function installConfig()
1436 'LBL_DBCONFIG_MSG3' => array(
1437 "setup_db_database_name" => array("label" => 'LBL_DBCONF_DB_NAME', "required" => true),
1439 'LBL_DBCONFIG_MSG2' => array(
1440 "setup_db_host_name" => array("label" => 'LBL_DBCONF_HOST_NAME', "required" => true),
1442 'LBL_DBCONF_TITLE_USER_INFO' => array(),
1443 'LBL_DBCONFIG_B_MSG1' => array(
1444 "setup_db_admin_user_name" => array("label" => 'LBL_DBCONF_DB_ADMIN_USER', "required" => true),
1445 "setup_db_admin_password" => array("label" => 'LBL_DBCONF_DB_ADMIN_PASSWORD', "type" => "password"),
1451 * Disable keys on the table
1453 * @param string $tableName
1455 public function disableKeys($tableName)
1457 return $this->query('ALTER TABLE '.$tableName.' DISABLE KEYS');
1461 * Re-enable keys on the table
1463 * @param string $tableName
1465 public function enableKeys($tableName)
1467 return $this->query('ALTER TABLE '.$tableName.' ENABLE KEYS');
1471 * Returns a DB specific FROM clause which can be used to select against functions.
1472 * Note that depending on the database that this may also be an empty string.
1475 public function getFromDummyTable()
1481 * Returns a DB specific piece of SQL which will generate GUID (UUID)
1482 * This string can be used in dynamic SQL to do multiple inserts with a single query.
1483 * I.e. generate a unique Sugar id in a sub select of an insert statement.
1487 public function getGuidSQL()