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 'datetime' => 'datetime',
128 'datetimecombo' => 'datetime',
131 'tinyint' => 'tinyint',
134 'longblob' => 'longblob',
135 'currency' => 'decimal(26,6)',
136 'decimal' => 'decimal',
137 'decimal2' => 'decimal',
140 'encrypt' => 'varchar',
142 'decimal_tpl' => 'decimal(%d, %d)',
146 protected $capabilities = array(
147 "affected_rows" => true,
148 "select_rows" => true,
149 "inline_keys" => true,
150 "create_user" => true,
154 "disable_keys" => true,
158 * Parses and runs queries
160 * @param string $sql SQL Statement to execute
161 * @param bool $dieOnError True if we want to call die if the query returns errors
162 * @param string $msg Message to log if error occurs
163 * @param bool $suppress Flag to suppress all error output unless in debug logging mode.
164 * @param bool $keepResult True if we want to push this result into the $lastResult array.
165 * @return resource result set
167 public function query($sql, $dieOnError = false, $msg = '', $suppress = false, $keepResult = false)
170 return $this->queryArray($sql, $dieOnError, $msg, $suppress);
173 parent::countQuery($sql);
174 $GLOBALS['log']->info('Query:' . $sql);
175 $this->checkConnection();
176 $this->query_time = microtime(true);
177 $this->lastsql = $sql;
178 $result = $suppress?@mysql_query($sql, $this->database):mysql_query($sql, $this->database);
180 $this->query_time = microtime(true) - $this->query_time;
181 $GLOBALS['log']->info('Query Execution Time:'.$this->query_time);
185 $this->lastResult = $result;
187 $this->checkError($msg.' Query Failed:' . $sql . '::', $dieOnError);
192 * Returns the number of rows affected by the last query
196 public function getAffectedRowCount($result)
198 return mysql_affected_rows($this->getDatabase());
202 * Returns the number of rows returned by the result
204 * This function can't be reliably implemented on most DB, do not use it.
207 * @param resource $result
210 public function getRowCount($result)
212 return mysql_num_rows($result);
216 * Disconnects from the database
218 * Also handles any cleanup needed
220 public function disconnect()
222 $GLOBALS['log']->debug('Calling MySQL::disconnect()');
223 if(!empty($this->database)){
225 mysql_close($this->database);
226 $this->database = null;
231 * @see DBManager::freeDbResult()
233 protected function freeDbResult($dbResult)
235 if(!empty($dbResult))
236 mysql_free_result($dbResult);
242 * Check if query has LIMIT clause
243 * Relevant for now only for Mysql
247 protected function hasLimit($sql)
249 return stripos($sql, " limit ") !== false;
253 * @see DBManager::limitQuery()
255 public function limitQuery($sql, $start, $count, $dieOnError = false, $msg = '', $execute = true)
257 $start = (int)$start;
258 $count = (int)$count;
261 $GLOBALS['log']->debug('Limit Query:' . $sql. ' Start: ' .$start . ' count: ' . $count);
263 $sql = "$sql LIMIT $start,$count";
264 $this->lastsql = $sql;
266 if(!empty($GLOBALS['sugar_config']['check_query'])){
267 $this->checkQuery($sql);
273 return $this->query($sql, $dieOnError, $msg);
278 * @see DBManager::checkQuery()
280 protected function checkQuery($sql)
282 $result = $this->query('EXPLAIN ' . $sql);
284 while ($row = $this->fetchByAssoc($result)) {
285 if (empty($row['table']))
287 $badQuery[$row['table']] = '';
288 if (strtoupper($row['type']) == 'ALL')
289 $badQuery[$row['table']] .= ' Full Table Scan;';
290 if (empty($row['key']))
291 $badQuery[$row['table']] .= ' No Index Key Used;';
292 if (!empty($row['Extra']) && substr_count($row['Extra'], 'Using filesort') > 0)
293 $badQuery[$row['table']] .= ' Using FileSort;';
294 if (!empty($row['Extra']) && substr_count($row['Extra'], 'Using temporary') > 0)
295 $badQuery[$row['table']] .= ' Using Temporary Table;';
298 if ( empty($badQuery) )
301 foreach($badQuery as $table=>$data ){
303 $warning = ' Table:' . $table . ' Data:' . $data;
304 if(!empty($GLOBALS['sugar_config']['check_query_log'])){
305 $GLOBALS['log']->fatal($sql);
306 $GLOBALS['log']->fatal('CHECK QUERY:' .$warning);
309 $GLOBALS['log']->warn('CHECK QUERY:' .$warning);
318 * @see DBManager::get_columns()
320 public function get_columns($tablename)
322 //find all unique indexes and primary keys.
323 $result = $this->query("DESCRIBE $tablename");
326 while (($row=$this->fetchByAssoc($result)) !=null) {
327 $name = strtolower($row['Field']);
328 $columns[$name]['name']=$name;
330 preg_match_all('/(\w+)(?:\(([0-9]+,?[0-9]*)\)|)( unsigned)?/i', $row['Type'], $matches);
331 $columns[$name]['type']=strtolower($matches[1][0]);
332 if ( isset($matches[2][0]) && in_array(strtolower($matches[1][0]),array('varchar','char','varchar2','int','decimal','float')) )
333 $columns[$name]['len']=strtolower($matches[2][0]);
334 if ( stristr($row['Extra'],'auto_increment') )
335 $columns[$name]['auto_increment'] = '1';
336 if ($row['Null'] == 'NO' && !stristr($row['Key'],'PRI'))
337 $columns[$name]['required'] = 'true';
338 if (!empty($row['Default']) )
339 $columns[$name]['default'] = $row['Default'];
345 * @see DBManager::getFieldsArray()
347 public function getFieldsArray($result, $make_lower_case=false)
349 $field_array = array();
354 $fields = mysql_num_fields($result);
355 for ($i=0; $i < $fields; $i++) {
356 $meta = mysql_fetch_field($result, $i);
360 if($make_lower_case == true)
361 $meta->name = strtolower($meta->name);
363 $field_array[] = $meta->name;
370 * @see DBManager::fetchRow()
372 public function fetchRow($result)
374 if (empty($result)) return false;
376 return mysql_fetch_assoc($result);
380 * @see DBManager::getTablesArray()
382 public function getTablesArray()
384 $this->log->debug('Fetching table list');
386 if ($this->getDatabase()) {
388 $r = $this->query('SHOW TABLES');
390 while ($a = $this->fetchByAssoc($r)) {
391 $row = array_values($a);
398 return false; // no database available
402 * @see DBManager::version()
404 public function version()
406 return $this->getOne("SELECT version() version");
410 * @see DBManager::tableExists()
412 public function tableExists($tableName)
414 $this->log->info("tableExists: $tableName");
416 if ($this->getDatabase()) {
417 $result = $this->query("SHOW TABLES LIKE ".$this->quoted($tableName));
418 if(empty($result)) return false;
419 $row = $this->fetchByAssoc($result);
427 * Get tables like expression
428 * @param $like string
431 public function tablesLike($like)
433 if ($this->getDatabase()) {
435 $r = $this->query('SHOW TABLES LIKE '.$this->quoted($like));
437 while ($a = $this->fetchByAssoc($r)) {
438 $row = array_values($a);
448 * @see DBManager::quote()
450 public function quote($string)
452 if(is_array($string)) {
453 return $this->arrayQuote($string);
455 return mysql_real_escape_string($this->quoteInternal($string), $this->getDatabase());
459 * @see DBManager::connect()
461 public function connect(array $configOptions = null, $dieOnError = false)
463 global $sugar_config;
465 if(is_null($configOptions))
466 $configOptions = $sugar_config['dbconfig'];
468 if ($this->getOption('persistent')) {
469 $this->database = @mysql_pconnect(
470 $configOptions['db_host_name'],
471 $configOptions['db_user_name'],
472 $configOptions['db_password']
476 if (!$this->database) {
477 $this->database = mysql_connect(
478 $configOptions['db_host_name'],
479 $configOptions['db_user_name'],
480 $configOptions['db_password']
482 if(empty($this->database)) {
483 $GLOBALS['log']->fatal("Could not connect to server ".$configOptions['db_host_name']." as ".$configOptions['db_user_name'].":".mysql_error());
485 if(isset($GLOBALS['app_strings']['ERR_NO_DB'])) {
486 sugar_die($GLOBALS['app_strings']['ERR_NO_DB']);
488 sugar_die("Could not connect to the database. Please refer to sugarcrm.log for details.");
494 // Do not pass connection information because we have not connected yet
495 if($this->database && $this->getOption('persistent')){
496 $_SESSION['administrator_error'] = "<b>Severe Performance Degradation: Persistent Database Connections "
497 . "not working. Please set \$sugar_config['dbconfigoption']['persistent'] to false "
498 . "in your config.php file</b>";
501 if(!empty($configOptions['db_name']) && !@mysql_select_db($configOptions['db_name'])) {
502 $GLOBALS['log']->fatal( "Unable to select database {$configOptions['db_name']}: " . mysql_error($this->database));
504 sugar_die($GLOBALS['app_strings']['ERR_NO_DB']);
510 // cn: using direct calls to prevent this from spamming the Logs
511 mysql_query("SET CHARACTER SET utf8", $this->database);
512 $names = "SET NAMES 'utf8'";
513 $collation = $this->getOption('collation');
514 if(!empty($collation)) {
515 $names .= " COLLATE '$collation'";
517 mysql_query($names, $this->database);
519 if(!$this->checkError('Could Not Connect:', $dieOnError))
520 $GLOBALS['log']->info("connected to db");
521 $this->connectOptions = $configOptions;
523 $GLOBALS['log']->info("Connect:".$this->database);
528 * @see DBManager::repairTableParams()
530 * For MySQL, we can write the ALTER TABLE statement all in one line, which speeds things
531 * up quite a bit. So here, we'll parse the returned SQL into a single ALTER TABLE command.
533 public function repairTableParams($tablename, $fielddefs, $indices, $execute = true, $engine = null)
535 $sql = parent::repairTableParams($tablename,$fielddefs,$indices,false,$engine);
540 if ( stristr($sql,'create table') )
543 $msg = "Error creating table: ".$tablename. ":";
544 $this->query($sql,true,$msg);
549 // first, parse out all the comments
551 preg_match_all('!/\*.*?\*/!is', $sql, $match);
552 $commentBlocks = $match[0];
553 $sql = preg_replace('!/\*.*?\*/!is','', $sql);
555 // now, we should only have alter table statements
556 // let's replace the 'alter table name' part with a comma
557 $sql = preg_replace("!alter table $tablename!is",', ', $sql);
559 // re-add it at the beginning
560 $sql = substr_replace($sql,'',strpos($sql,','),1);
561 $sql = str_replace(";","",$sql);
562 $sql = str_replace("\n","",$sql);
563 $sql = "ALTER TABLE $tablename $sql";
566 $this->query($sql,'Error with MySQL repair table');
568 // and re-add the comments at the beginning
569 $sql = implode("\n",$commentBlocks) . "\n". $sql . "\n";
575 * @see DBManager::convert()
577 public function convert($string, $type, array $additional_parameters = array())
579 $all_parameters = $additional_parameters;
580 if(is_array($string)) {
581 $all_parameters = array_merge($string, $all_parameters);
582 } elseif (!is_null($string)) {
583 array_unshift($all_parameters, $string);
585 $all_strings = implode(',', $all_parameters);
587 switch (strtolower($type)) {
591 return "LEFT($all_strings)";
593 if(empty($additional_parameters)) {
594 return "DATE_FORMAT($string,'%Y-%m-%d')";
596 $format = $additional_parameters[0];
597 if($format[0] != "'") {
598 $format = $this->quoted($format);
600 return "DATE_FORMAT($string,$format)";
603 if(empty($additional_parameters) && !strstr($all_strings, ",")) {
604 $all_strings .= ",''";
606 return "IFNULL($all_strings)";
608 return "CONCAT($all_strings)";
610 return "QUARTER($string)";
612 return "LENGTH($string)";
614 return "MONTH($string)";
616 return "DATE_ADD($string, INTERVAL {$additional_parameters[0]} {$additional_parameters[1]})";
618 return "DATE_ADD($string, INTERVAL + CONCAT({$additional_parameters[0]}, ':', {$additional_parameters[1]}) HOUR_MINUTE)";
626 * @see DBManager::fromConvert()
628 public function fromConvert($string, $type)
634 * Returns the name of the engine to use or null if we are to use the default
636 * @param object $bean SugarBean instance
639 protected function getEngine($bean)
643 if (isset($dictionary[$bean->getObjectName()]['engine'])) {
644 $engine = $dictionary[$bean->getObjectName()]['engine'];
650 * Returns true if the engine given is enabled in the backend
652 * @param string $engine
655 protected function isEngineEnabled($engine)
657 if(!is_string($engine)) return false;
659 $engine = strtoupper($engine);
661 $r = $this->query("SHOW ENGINES");
663 while ( $row = $this->fetchByAssoc($r) )
664 if ( strtoupper($row['Engine']) == $engine )
665 return ($row['Support']=='YES' || $row['Support']=='DEFAULT');
671 * @see DBManager::createTableSQL()
673 public function createTableSQL(SugarBean $bean)
675 $tablename = $bean->getTableName();
676 $fieldDefs = $bean->getFieldDefinitions();
677 $indices = $bean->getIndices();
678 $engine = $this->getEngine($bean);
679 return $this->createTableSQLParams($tablename, $fieldDefs, $indices, $engine);
683 * Generates sql for create table statement for a bean.
685 * @param string $tablename
686 * @param array $fieldDefs
687 * @param array $indices
688 * @param string $engine optional, MySQL engine to use
689 * @return string SQL Create Table statement
691 public function createTableSQLParams($tablename, $fieldDefs, $indices, $engine = null)
693 if ( empty($engine) && isset($fieldDefs['engine']))
694 $engine = $fieldDefs['engine'];
695 if ( !$this->isEngineEnabled($engine) )
698 $columns = $this->columnSQLRep($fieldDefs, false, $tablename);
702 $keys = $this->keysSQL($indices);
706 // cn: bug 9873 - module tables do not get created in utf8 with assoc collation
707 $collation = $this->getOption('collation');
708 if(empty($collation)) {
709 $collation = 'utf8_general_ci';
711 $sql = "CREATE TABLE $tablename ($columns $keys) CHARACTER SET utf8 COLLATE $collation";
714 $sql.= " ENGINE=$engine";
720 * @see DBManager::oneColumnSQLRep()
722 protected function oneColumnSQLRep($fieldDef, $ignoreRequired = false, $table = '', $return_as_array = false)
724 // always return as array for post-processing
725 $ref = parent::oneColumnSQLRep($fieldDef, $ignoreRequired, $table, true);
727 if ( $ref['colType'] == 'int' && !empty($fieldDef['len']) ) {
728 $ref['colType'] .= "(".$fieldDef['len'].")";
731 // bug 22338 - don't set a default value on text or blob fields
732 if ( isset($ref['default']) &&
733 in_array($ref['colBaseType'], array('text', 'blob', 'longtext', 'longblob')))
734 $ref['default'] = '';
736 if ( $return_as_array )
739 return "{$ref['name']} {$ref['colType']} {$ref['default']} {$ref['required']} {$ref['auto_increment']}";
743 * @see DBManager::changeColumnSQL()
745 protected function changeColumnSQL($tablename, $fieldDefs, $action, $ignoreRequired = false)
748 if ($this->isFieldArray($fieldDefs)){
749 foreach ($fieldDefs as $def){
750 if ($action == 'drop')
751 $columns[] = $def['name'];
753 $columns[] = $this->oneColumnSQLRep($def, $ignoreRequired);
756 if ($action == 'drop')
757 $columns[] = $fieldDefs['name'];
759 $columns[] = $this->oneColumnSQLRep($fieldDefs);
762 return "ALTER TABLE $tablename $action COLUMN ".implode(",$action column ", $columns);
766 * Generates SQL for key specification inside CREATE TABLE statement
768 * The passes array is an array of field definitions or a field definition
769 * itself. The keys generated will be either primary, foreign, unique, index
770 * or none at all depending on the setting of the "key" parameter of a field definition
772 * @param array $indices
773 * @param bool $alter_table
774 * @param string $alter_action
775 * @return string SQL Statement
777 protected function keysSQL($indices, $alter_table = false, $alter_action = '')
779 // check if the passed value is an array of fields.
780 // if not, convert it into an array
781 if (!$this->isFieldArray($indices))
782 $indices[] = $indices;
785 foreach ($indices as $index) {
786 if(!empty($index['db']) && $index['db'] != $this->dbType)
788 if (isset($index['source']) && $index['source'] != 'db')
791 $type = $index['type'];
792 $name = $index['name'];
794 if (is_array($index['fields']))
795 $fields = implode(", ", $index['fields']);
797 $fields = $index['fields'];
801 $columns[] = " UNIQUE $name ($fields)";
804 $columns[] = " PRIMARY KEY ($fields)";
809 case 'alternate_key':
811 * @todo here it is assumed that the primary key of the foreign
812 * table will always be named 'id'. It must be noted though
813 * that this can easily be fixed by referring to db dictionary
814 * to find the correct primary field name
817 $columns[] = " INDEX $name ($fields)";
819 $columns[] = " KEY $name ($fields)";
822 if ($this->full_text_indexing_installed())
823 $columns[] = " FULLTEXT ($fields)";
825 $GLOBALS['log']->debug('MYISAM engine is not available/enabled, full-text indexes will be skipped. Skipping:',$name);
829 $columns = implode(", $alter_action ", $columns);
830 if(!empty($alter_action)){
831 $columns = $alter_action . ' '. $columns;
837 * @see DBManager::setAutoIncrement()
839 protected function setAutoIncrement($table, $field_name)
841 return "auto_increment";
845 * Sets the next auto-increment value of a column to a specific value.
847 * @param string $table tablename
848 * @param string $field_name
850 public function setAutoIncrementStart($table, $field_name, $start_value)
852 $start_value = (int)$start_value;
853 return $this->query( "ALTER TABLE $table AUTO_INCREMENT = $start_value;");
857 * Returns the next value for an auto increment
859 * @param string $table tablename
860 * @param string $field_name
863 public function getAutoIncrement($table, $field_name)
865 $result = $this->query("SHOW TABLE STATUS LIKE '$table'");
866 $row = $this->fetchByAssoc($result);
867 if (!empty($row['Auto_increment']))
868 return $row['Auto_increment'];
874 * @see DBManager::get_indices()
876 public function get_indices($tablename)
878 //find all unique indexes and primary keys.
879 $result = $this->query("SHOW INDEX FROM $tablename");
882 while (($row=$this->fetchByAssoc($result)) !=null) {
884 if ($row['Key_name'] =='PRIMARY') {
885 $index_type='primary';
887 elseif ( $row['Non_unique'] == '0' ) {
888 $index_type='unique';
890 $name = strtolower($row['Key_name']);
891 $indices[$name]['name']=$name;
892 $indices[$name]['type']=$index_type;
893 $indices[$name]['fields'][]=strtolower($row['Column_name']);
899 * @see DBManager::add_drop_constraint()
901 public function add_drop_constraint($table, $definition, $drop = false)
903 $type = $definition['type'];
904 $fields = implode(',',$definition['fields']);
905 $name = $definition['name'];
911 case 'alternate_key':
914 $sql = "ALTER TABLE {$table} DROP INDEX {$name} ";
916 $sql = "ALTER TABLE {$table} ADD INDEX {$name} ({$fields})";
918 // constraints as indices
921 $sql = "ALTER TABLE {$table} DROP INDEX $name";
923 $sql = "ALTER TABLE {$table} ADD CONSTRAINT UNIQUE {$name} ({$fields})";
927 $sql = "ALTER TABLE {$table} DROP PRIMARY KEY";
929 $sql = "ALTER TABLE {$table} ADD CONSTRAINT PRIMARY KEY ({$fields})";
933 $sql = "ALTER TABLE {$table} DROP FOREIGN KEY ({$fields})";
935 $sql = "ALTER TABLE {$table} ADD CONSTRAINT FOREIGN KEY {$name} ({$fields}) REFERENCES {$definition['foreignTable']}({$definition['foreignField']})";
942 * Runs a query and returns a single row
944 * @param string $sql SQL Statement to execute
945 * @param bool $dieOnError True if we want to call die if the query returns errors
946 * @param string $msg Message to log if error occurs
947 * @param bool $suppress Message to log if error occurs
948 * @return array single row from the query
950 public function fetchOne($sql, $dieOnError = false, $msg = '', $suppress = false)
952 if(stripos($sql, ' LIMIT ') === false) {
953 // little optimization to just fetch one row
954 $sql .= " LIMIT 0,1";
956 return parent::fetchOne($sql, $dieOnError, $msg, $suppress);
960 * @see DBManager::full_text_indexing_installed()
962 public function full_text_indexing_installed($dbname = null)
964 return $this->isEngineEnabled('MyISAM');
968 * @see DBManager::massageFieldDef()
970 public function massageFieldDef(&$fieldDef, $tablename)
972 parent::massageFieldDef($fieldDef,$tablename);
974 if ( isset($fieldDef['default']) &&
975 ($fieldDef['dbType'] == 'text'
976 || $fieldDef['dbType'] == 'blob'
977 || $fieldDef['dbType'] == 'longtext'
978 || $fieldDef['dbType'] == 'longblob' ))
979 unset($fieldDef['default']);
980 if ($fieldDef['dbType'] == 'uint')
981 $fieldDef['len'] = '10';
982 if ($fieldDef['dbType'] == 'ulong')
983 $fieldDef['len'] = '20';
984 if ($fieldDef['dbType'] == 'bool')
985 $fieldDef['type'] = 'tinyint';
986 if ($fieldDef['dbType'] == 'bool' && empty($fieldDef['default']) )
987 $fieldDef['default'] = '0';
988 if (($fieldDef['dbType'] == 'varchar' || $fieldDef['dbType'] == 'enum') && empty($fieldDef['len']) )
989 $fieldDef['len'] = '255';
990 if ($fieldDef['dbType'] == 'uint')
991 $fieldDef['len'] = '10';
992 if ($fieldDef['dbType'] == 'int' && empty($fieldDef['len']) )
993 $fieldDef['len'] = '11';
995 if($fieldDef['dbType'] == 'decimal') {
996 if(isset($fieldDef['len'])) {
997 if(strstr($fieldDef['len'], ",") === false) {
998 $fieldDef['len'] .= ",0";
1001 $fieldDef['len'] = '10,0';
1007 * Generates SQL for dropping a table.
1009 * @param string $name table name
1010 * @return string SQL statement
1012 public function dropTableNameSQL($name)
1014 return "DROP TABLE IF EXISTS ".$name;
1017 public function dropIndexes($tablename, $indexes, $execute = true)
1020 foreach ($indexes as $index) {
1021 $name =$index['name'];
1023 unset(self::$index_descriptions[$tablename][$name]);
1025 if ($index['type'] == 'primary') {
1026 $sql[] = 'DROP PRIMARY KEY';
1028 $sql[] = "DROP INDEX $name";
1032 $sql = "ALTER TABLE $tablename ".join(",", $sql);
1042 * List of available collation settings
1045 public function getDefaultCollation()
1047 return "utf8_general_ci";
1051 * List of available collation settings
1054 public function getCollationList()
1056 $q = "SHOW COLLATION LIKE 'utf8%'";
1057 $r = $this->query($q);
1059 while($a = $this->fetchByAssoc($r)) {
1060 $res[] = $a['Collation'];
1067 * @see DBManager::renameColumnSQL()
1069 public function renameColumnSQL($tablename, $column, $newname)
1071 $field = $this->describeField($column, $tablename);
1072 $field['name'] = $newname;
1073 return "ALTER TABLE $tablename CHANGE COLUMN $column ".$this->oneColumnSQLRep($field);
1076 public function emptyValue($type)
1078 $ctype = $this->getColumnType($type);
1079 if($ctype == "datetime") {
1080 return $this->convert($this->quoted("0000-00-00 00:00:00"), "datetime");
1082 if($ctype == "date") {
1083 return $this->convert($this->quoted("0000-00-00"), "date");
1085 if($ctype == "time") {
1086 return $this->convert($this->quoted("00:00:00"), "time");
1088 return parent::emptyValue($type);
1093 * @see DBManager::lastDbError()
1095 public function lastDbError()
1097 if($this->database) {
1098 if(mysql_errno($this->database)) {
1099 return "MySQL error ".mysql_errno($this->database).": ".mysql_error($this->database);
1102 $err = mysql_error();
1111 * Quote MySQL search term
1112 * @param unknown_type $term
1114 protected function quoteTerm($term)
1116 if(strpos($term, ' ') !== false) {
1117 return '"'.$term.'"';
1123 * Generate fulltext query from set of terms
1124 * @param string $fields Field to search against
1125 * @param array $terms Search terms that may be or not be in the result
1126 * @param array $must_terms Search terms that have to be in the result
1127 * @param array $exclude_terms Search terms that have to be not in the result
1129 public function getFulltextQuery($field, $terms, $must_terms = array(), $exclude_terms = array())
1131 $condition = array();
1132 foreach($terms as $term) {
1133 $condition[] = $this->quoteTerm($term);
1135 foreach($must_terms as $term) {
1136 $condition[] = "+".$this->quoteTerm($term);
1138 foreach($exclude_terms as $term) {
1139 $condition[] = "-".$this->quoteTerm($term);
1141 $condition = $this->quoted(join(" ",$condition));
1142 return "MATCH($field) AGAINST($condition IN BOOLEAN MODE)";
1146 * Get list of all defined charsets
1149 protected function getCharsetInfo()
1151 $charsets = array();
1152 $res = $this->query("show variables like 'character\\_set\\_%'");
1153 while($row = $this->fetchByAssoc($res)) {
1154 $charsets[$row['Variable_name']] = $row['Value'];
1159 public function getDbInfo()
1161 $charsets = $this->getCharsetInfo();
1162 $charset_str = array();
1163 foreach($charsets as $name => $value) {
1164 $charset_str[] = "$name = $value";
1167 "MySQL Version" => @mysql_get_client_info(),
1168 "MySQL Host Info" => @mysql_get_host_info($this->database),
1169 "MySQL Server Info" => @mysql_get_server_info($this->database),
1170 "MySQL Client Encoding" => @mysql_client_encoding($this->database),
1171 "MySQL Character Set Settings" => join(", ", $charset_str),
1175 public function validateQuery($query)
1177 $res = $this->query("EXPLAIN $query");
1178 return !empty($res);
1181 protected function makeTempTableCopy($table)
1183 $this->log->debug("creating temp table for [$table]...");
1184 $result = $this->query("SHOW CREATE TABLE {$table}");
1185 if(empty($result)) {
1188 $row = $this->fetchByAssoc($result);
1189 if(empty($row) || empty($row['Create Table'])) {
1192 $create = $row['Create Table'];
1193 // rewrite DDL with _temp name
1194 $tempTableQuery = str_replace("CREATE TABLE `{$table}`", "CREATE TABLE `{$table}__uw_temp`", $create);
1195 $r2 = $this->query($tempTableQuery);
1200 // get sample data into the temp table to test for data/constraint conflicts
1201 $this->log->debug('inserting temp dataset...');
1202 $q3 = "INSERT INTO `{$table}__uw_temp` SELECT * FROM `{$table}` LIMIT 10";
1203 $this->query($q3, false, "Preflight Failed for: {$q3}");
1208 * Tests an ALTER TABLE query
1209 * @param string table The table name to get DDL
1210 * @param string query The query to test.
1211 * @return string Non-empty if error found
1213 protected function verifyAlterTable($table, $query)
1215 $this->log->debug("verifying ALTER TABLE");
1216 // Skipping ALTER TABLE [table] DROP PRIMARY KEY because primary keys are not being copied
1217 // over to the temp tables
1218 if(strpos(strtoupper($query), 'DROP PRIMARY KEY') !== false) {
1219 $this->log->debug("Skipping DROP PRIMARY KEY");
1222 if(!$this->makeTempTableCopy($table)) {
1223 return 'Could not create temp table copy';
1226 // test the query on the test table
1227 $this->log->debug('testing query: ['.$query.']');
1228 $tempTableTestQuery = str_replace("ALTER TABLE `{$table}`", "ALTER TABLE `{$table}__uw_temp`", $query);
1229 if (strpos($tempTableTestQuery, 'idx') === false) {
1230 if(strpos($tempTableTestQuery, '__uw_temp') === false) {
1231 return 'Could not use a temp table to test query!';
1234 $this->log->debug('testing query on temp table: ['.$tempTableTestQuery.']');
1235 $this->query($tempTableTestQuery, false, "Preflight Failed for: {$query}");
1237 // test insertion of an index on a table
1238 $tempTableTestQuery_idx = str_replace("ADD INDEX `idx_", "ADD INDEX `temp_idx_", $tempTableTestQuery);
1239 $this->log->debug('testing query on temp table: ['.$tempTableTestQuery_idx.']');
1240 $this->query($tempTableTestQuery_idx, false, "Preflight Failed for: {$query}");
1242 $mysqlError = $this->getL();
1243 if(!empty($mysqlError)) {
1246 $this->dropTableName("{$table}__uw_temp");
1251 protected function verifyGenericReplaceQuery($querytype, $table, $query)
1253 $this->log->debug("verifying $querytype statement");
1255 if(!$this->makeTempTableCopy($table)) {
1256 return 'Could not create temp table copy';
1258 // test the query on the test table
1259 $this->log->debug('testing query: ['.$query.']');
1260 $tempTableTestQuery = str_replace("$querytype `{$table}`", "$querytype `{$table}__uw_temp`", $query);
1261 if(strpos($tempTableTestQuery, '__uw_temp') === false) {
1262 return 'Could not use a temp table to test query!';
1265 $this->query($tempTableTestQuery, false, "Preflight Failed for: {$query}");
1266 $error = $this->lastError(); // empty on no-errors
1267 $this->dropTableName("{$table}__uw_temp"); // just in case
1272 * Tests a DROP TABLE query
1273 * @param string table The table name to get DDL
1274 * @param string query The query to test.
1275 * @return string Non-empty if error found
1277 public function verifyDropTable($table, $query)
1279 return $this->verifyGenericReplaceQuery("DROP TABLE", $table, $query);
1283 * Tests an INSERT INTO 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 verifyInsertInto($table, $query)
1290 return $this->verifyGenericReplaceQuery("INSERT INTO", $table, $query);
1294 * Tests an UPDATE 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 verifyUpdate($table, $query)
1301 return $this->verifyGenericReplaceQuery("UPDATE", $table, $query);
1305 * Tests an DELETE FROM 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 verifyDeleteFrom($table, $query)
1312 return $this->verifyGenericReplaceQuery("DELETE FROM", $table, $query);
1316 * Check if certain database exists
1317 * @param string $dbname
1319 public function dbExists($dbname)
1321 $db = $this->getOne("SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = ".$this->quoted($dbname));
1327 * @param string $dbname
1329 protected function selectDb($dbname)
1331 return mysql_select_db($dbname);
1335 * Check if certain DB user exists
1336 * @param string $username
1338 public function userExists($username)
1340 $db = $this->getOne("SELECT DATABASE()");
1341 if(!$this->selectDb("mysql")) {
1344 $user = $this->getOne("select count(*) from user where user = ".$this->quoted($username));
1345 if(!$this->selectDb($db)) {
1346 $this->checkError("Cannot select database $db", true);
1348 return !empty($user);
1353 * @param string $database_name
1354 * @param string $host_name
1355 * @param string $user
1356 * @param string $password
1358 public function createDbUser($database_name, $host_name, $user, $password)
1360 $qpassword = $this->quote($password);
1361 $this->query("GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, ALTER, DROP, INDEX
1362 ON `$database_name`.*
1363 TO \"$user\"@\"$host_name\"
1364 IDENTIFIED BY '{$qpassword}';", true);
1366 $this->query("SET PASSWORD FOR \"{$user}\"@\"{$host_name}\" = password('{$qpassword}');", true);
1367 if($host_name != 'localhost') {
1368 $this->createDbUser($database_name, "localhost", $user, $password);
1374 * @param string $dbname
1376 public function createDatabase($dbname)
1378 $this->query("CREATE DATABASE `$dbname` CHARACTER SET utf8 COLLATE utf8_general_ci", true);
1381 public function preInstall()
1383 $db->query("ALTER DATABASE `{$setup_db_database_name}` DEFAULT CHARACTER SET utf8", true);
1384 $db->query("ALTER DATABASE `{$setup_db_database_name}` DEFAULT COLLATE utf8_general_ci", true);
1390 * @param string $dbname
1392 public function dropDatabase($dbname)
1394 return $this->query("DROP DATABASE IF EXISTS `$dbname`", true);
1398 * Check if this driver can be used
1401 public function valid()
1403 return function_exists("mysql_connect");
1408 * @see DBManager::canInstall()
1410 public function canInstall()
1412 $db_version = $this->version();
1413 if(empty($db_version)) {
1414 return array('ERR_DB_VERSION_FAILURE');
1416 if(version_compare($db_version, '4.1.2') < 0) {
1417 return array('ERR_DB_MYSQL_VERSION', $db_version);
1422 public function installConfig()
1425 'LBL_DBCONFIG_MSG3' => array(
1426 "setup_db_database_name" => array("label" => 'LBL_DBCONF_DB_NAME', "required" => true),
1428 'LBL_DBCONFIG_MSG2' => array(
1429 "setup_db_host_name" => array("label" => 'LBL_DBCONF_HOST_NAME', "required" => true),
1431 'LBL_DBCONF_TITLE_USER_INFO' => array(),
1432 'LBL_DBCONFIG_B_MSG1' => array(
1433 "setup_db_admin_user_name" => array("label" => 'LBL_DBCONF_DB_ADMIN_USER', "required" => true),
1434 "setup_db_admin_password" => array("label" => 'LBL_DBCONF_DB_ADMIN_PASSWORD', "type" => "password"),
1440 * Disable keys on the table
1442 * @param string $tableName
1444 public function disableKeys($tableName)
1446 return $this->query('ALTER TABLE '.$tableName.' DISABLE KEYS');
1450 * Re-enable keys on the table
1452 * @param string $tableName
1454 public function enableKeys($tableName)
1456 return $this->query('ALTER TABLE '.$tableName.' ENABLE KEYS');