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.
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);
241 * @see DBManager::limitQuery()
243 public function limitQuery($sql, $start, $count, $dieOnError = false, $msg = '', $execute = true)
247 $GLOBALS['log']->debug('Limit Query:' . $sql. ' Start: ' .$start . ' count: ' . $count);
249 $sql = "$sql LIMIT $start,$count";
250 $this->lastsql = $sql;
252 if(!empty($GLOBALS['sugar_config']['check_query'])){
253 $this->checkQuery($sql);
259 return $this->query($sql, $dieOnError, $msg);
264 * @see DBManager::checkQuery()
266 protected function checkQuery($sql)
268 $result = $this->query('EXPLAIN ' . $sql);
270 while ($row = $this->fetchByAssoc($result)) {
271 if (empty($row['table']))
273 $badQuery[$row['table']] = '';
274 if (strtoupper($row['type']) == 'ALL')
275 $badQuery[$row['table']] .= ' Full Table Scan;';
276 if (empty($row['key']))
277 $badQuery[$row['table']] .= ' No Index Key Used;';
278 if (!empty($row['Extra']) && substr_count($row['Extra'], 'Using filesort') > 0)
279 $badQuery[$row['table']] .= ' Using FileSort;';
280 if (!empty($row['Extra']) && substr_count($row['Extra'], 'Using temporary') > 0)
281 $badQuery[$row['table']] .= ' Using Temporary Table;';
284 if ( empty($badQuery) )
287 foreach($badQuery as $table=>$data ){
289 $warning = ' Table:' . $table . ' Data:' . $data;
290 if(!empty($GLOBALS['sugar_config']['check_query_log'])){
291 $GLOBALS['log']->fatal($sql);
292 $GLOBALS['log']->fatal('CHECK QUERY:' .$warning);
295 $GLOBALS['log']->warn('CHECK QUERY:' .$warning);
304 * @see DBManager::get_columns()
306 public function get_columns($tablename)
308 //find all unique indexes and primary keys.
309 $result = $this->query("DESCRIBE $tablename");
312 while (($row=$this->fetchByAssoc($result)) !=null) {
313 $name = strtolower($row['Field']);
314 $columns[$name]['name']=$name;
316 preg_match_all('/(\w+)(?:\(([0-9]+,?[0-9]*)\)|)( unsigned)?/i', $row['Type'], $matches);
317 $columns[$name]['type']=strtolower($matches[1][0]);
318 if ( isset($matches[2][0]) && in_array(strtolower($matches[1][0]),array('varchar','char','varchar2','int','decimal','float')) )
319 $columns[$name]['len']=strtolower($matches[2][0]);
320 if ( stristr($row['Extra'],'auto_increment') )
321 $columns[$name]['auto_increment'] = '1';
322 if ($row['Null'] == 'NO' && !stristr($row['Key'],'PRI'))
323 $columns[$name]['required'] = 'true';
324 if (!empty($row['Default']) )
325 $columns[$name]['default'] = $row['Default'];
331 * @see DBManager::getFieldsArray()
333 public function getFieldsArray($result, $make_lower_case=false)
335 $field_array = array();
340 $fields = mysql_num_fields($result);
341 for ($i=0; $i < $fields; $i++) {
342 $meta = mysql_fetch_field($result, $i);
346 if($make_lower_case == true)
347 $meta->name = strtolower($meta->name);
349 $field_array[] = $meta->name;
356 * @see DBManager::fetchRow()
358 public function fetchRow($result)
360 if (empty($result)) return false;
362 return mysql_fetch_assoc($result);
366 * @see DBManager::getTablesArray()
368 public function getTablesArray()
370 $this->log->debug('Fetching table list');
372 if ($this->getDatabase()) {
374 $r = $this->query('SHOW TABLES');
376 while ($a = $this->fetchByAssoc($r)) {
377 $row = array_values($a);
384 return false; // no database available
388 * @see DBManager::version()
390 public function version()
392 return $this->getOne("SELECT version() version");
396 * @see DBManager::tableExists()
398 public function tableExists($tableName)
400 $this->log->info("tableExists: $tableName");
402 if ($this->getDatabase()) {
403 $result = $this->getOne("SHOW TABLES LIKE ".$this->quoted($tableName));
404 return !empty($result);
411 * Get tables like expression
412 * @param $like string
415 public function tablesLike($like)
417 if ($this->getDatabase()) {
419 $r = $this->query('SHOW TABLES LIKE '.$this->quoted($like));
421 while ($a = $this->fetchByAssoc($r)) {
422 $row = array_values($a);
432 * @see DBManager::quote()
434 public function quote($string)
436 if(is_array($string)) {
437 return $this->arrayQuote($string);
439 return mysql_real_escape_string($this->quoteInternal($string), $this->getDatabase());
443 * @see DBManager::connect()
445 public function connect(array $configOptions = null, $dieOnError = false)
447 global $sugar_config;
449 if(is_null($configOptions))
450 $configOptions = $sugar_config['dbconfig'];
452 if ($this->getOption('persistent')) {
453 $this->database = @mysql_pconnect(
454 $configOptions['db_host_name'],
455 $configOptions['db_user_name'],
456 $configOptions['db_password']
460 if (!$this->database) {
461 $this->database = mysql_connect(
462 $configOptions['db_host_name'],
463 $configOptions['db_user_name'],
464 $configOptions['db_password']
466 if(empty($this->database)) {
467 $GLOBALS['log']->fatal("Could not connect to server ".$configOptions['db_host_name']." as ".$configOptions['db_user_name'].":".mysql_error());
469 if(isset($GLOBALS['app_strings']['ERR_NO_DB'])) {
470 sugar_die($GLOBALS['app_strings']['ERR_NO_DB']);
472 sugar_die("Could not connect to the database. Please refer to sugarcrm.log for details.");
478 // Do not pass connection information because we have not connected yet
479 if($this->database && $this->getOption('persistent')){
480 $_SESSION['administrator_error'] = "<b>Severe Performance Degradation: Persistent Database Connections "
481 . "not working. Please set \$sugar_config['dbconfigoption']['persistent'] to false "
482 . "in your config.php file</b>";
485 if(!empty($configOptions['db_name']) && !@mysql_select_db($configOptions['db_name'])) {
486 $GLOBALS['log']->fatal( "Unable to select database {$configOptions['db_name']}: " . mysql_error($this->database));
488 sugar_die($GLOBALS['app_strings']['ERR_NO_DB']);
494 // cn: using direct calls to prevent this from spamming the Logs
495 mysql_query("SET CHARACTER SET utf8", $this->database);
496 $names = "SET NAMES 'utf8'";
497 $collation = $this->getOption('collation');
498 if(!empty($collation)) {
499 $names .= " COLLATE '$collation'";
501 mysql_query($names, $this->database);
503 if(!$this->checkError('Could Not Connect:', $dieOnError))
504 $GLOBALS['log']->info("connected to db");
505 $this->connectOptions = $configOptions;
507 $GLOBALS['log']->info("Connect:".$this->database);
512 * @see DBManager::repairTableParams()
514 * For MySQL, we can write the ALTER TABLE statement all in one line, which speeds things
515 * up quite a bit. So here, we'll parse the returned SQL into a single ALTER TABLE command.
517 public function repairTableParams($tablename, $fielddefs, $indices, $execute = true, $engine = null)
519 $sql = parent::repairTableParams($tablename,$fielddefs,$indices,false,$engine);
524 if ( stristr($sql,'create table') )
527 $msg = "Error creating table: ".$tablename. ":";
528 $this->query($sql,true,$msg);
533 // first, parse out all the comments
535 preg_match_all('!/\*.*?\*/!is', $sql, $match);
536 $commentBlocks = $match[0];
537 $sql = preg_replace('!/\*.*?\*/!is','', $sql);
539 // now, we should only have alter table statements
540 // let's replace the 'alter table name' part with a comma
541 $sql = preg_replace("!alter table $tablename!is",', ', $sql);
543 // re-add it at the beginning
544 $sql = substr_replace($sql,'',strpos($sql,','),1);
545 $sql = str_replace(";","",$sql);
546 $sql = str_replace("\n","",$sql);
547 $sql = "ALTER TABLE $tablename $sql";
550 $this->query($sql,'Error with MySQL repair table');
552 // and re-add the comments at the beginning
553 $sql = implode("\n",$commentBlocks) . "\n". $sql . "\n";
559 * @see DBManager::convert()
561 public function convert($string, $type, array $additional_parameters = array())
563 $all_parameters = $additional_parameters;
564 if(is_array($string)) {
565 $all_parameters = array_merge($string, $all_parameters);
566 } elseif (!is_null($string)) {
567 array_unshift($all_parameters, $string);
569 $all_strings = implode(',', $all_parameters);
571 switch (strtolower($type)) {
575 return "LEFT($all_strings)";
577 if(empty($additional_parameters)) {
578 return "DATE_FORMAT($string,'%Y-%m-%d')";
580 $format = $additional_parameters[0];
581 if($format[0] != "'") {
582 $format = $this->quoted($format);
584 return "DATE_FORMAT($string,$format)";
587 if(empty($additional_parameters) && !strstr($all_strings, ",")) {
588 $all_strings .= ",''";
590 return "IFNULL($all_strings)";
592 return "CONCAT($all_strings)";
594 return "QUARTER($string)";
596 return "LENGTH($string)";
598 return "MONTH($string)";
600 return "DATE_ADD($string, INTERVAL {$additional_parameters[0]} {$additional_parameters[1]})";
602 return "DATE_ADD($string, INTERVAL + CONCAT({$additional_parameters[0]}, ':', {$additional_parameters[1]}) HOUR_MINUTE)";
610 * @see DBManager::fromConvert()
612 public function fromConvert($string, $type)
618 * Returns the name of the engine to use or null if we are to use the default
620 * @param object $bean SugarBean instance
623 protected function getEngine($bean)
627 if (isset($dictionary[$bean->getObjectName()]['engine'])) {
628 $engine = $dictionary[$bean->getObjectName()]['engine'];
634 * Returns true if the engine given is enabled in the backend
636 * @param string $engine
639 protected function isEngineEnabled($engine)
641 $engine = strtoupper($engine);
643 $r = $this->query("SHOW ENGINES");
645 while ( $row = $this->fetchByAssoc($r) )
646 if ( strtoupper($row['Engine']) == $engine )
647 return ($row['Support']=='YES' || $row['Support']=='DEFAULT');
653 * @see DBManager::createTableSQL()
655 public function createTableSQL(SugarBean $bean)
657 $tablename = $bean->getTableName();
658 $fieldDefs = $bean->getFieldDefinitions();
659 $indices = $bean->getIndices();
660 $engine = $this->getEngine($bean);
661 return $this->createTableSQLParams($tablename, $fieldDefs, $indices, $engine);
665 * Generates sql for create table statement for a bean.
667 * @param string $tablename
668 * @param array $fieldDefs
669 * @param array $indices
670 * @param string $engine optional, MySQL engine to use
671 * @return string SQL Create Table statement
673 public function createTableSQLParams($tablename, $fieldDefs, $indices, $engine = null)
675 if ( empty($engine) && isset($fieldDefs['engine']))
676 $engine = $fieldDefs['engine'];
677 if ( !$this->isEngineEnabled($engine) )
680 $columns = $this->columnSQLRep($fieldDefs, false, $tablename);
684 $keys = $this->keysSQL($indices);
688 // cn: bug 9873 - module tables do not get created in utf8 with assoc collation
689 $collation = $this->getOption('collation');
690 if(empty($collation)) {
691 $collation = 'utf8_general_ci';
693 $sql = "CREATE TABLE $tablename ($columns $keys) CHARACTER SET utf8 COLLATE $collation";
696 $sql.= " ENGINE=$engine";
702 * @see DBManager::oneColumnSQLRep()
704 protected function oneColumnSQLRep($fieldDef, $ignoreRequired = false, $table = '', $return_as_array = false)
706 // always return as array for post-processing
707 $ref = parent::oneColumnSQLRep($fieldDef, $ignoreRequired, $table, true);
709 if ( $ref['colType'] == 'int' && !empty($fieldDef['len']) ) {
710 $ref['colType'] .= "(".$fieldDef['len'].")";
713 // bug 22338 - don't set a default value on text or blob fields
714 if ( isset($ref['default']) &&
715 ($ref['colType'] == 'text' || $ref['colType'] == 'blob'
716 || $ref['colType'] == 'longtext' || $ref['colType'] == 'longblob' ))
717 $ref['default'] = '';
719 if ( $return_as_array )
722 return "{$ref['name']} {$ref['colType']} {$ref['default']} {$ref['required']} {$ref['auto_increment']}";
726 * @see DBManager::changeColumnSQL()
728 protected function changeColumnSQL($tablename, $fieldDefs, $action, $ignoreRequired = false)
731 if ($this->isFieldArray($fieldDefs)){
732 foreach ($fieldDefs as $def){
733 if ($action == 'drop')
734 $columns[] = $def['name'];
736 $columns[] = $this->oneColumnSQLRep($def, $ignoreRequired);
739 if ($action == 'drop')
740 $columns[] = $fieldDefs['name'];
742 $columns[] = $this->oneColumnSQLRep($fieldDefs);
745 return "ALTER TABLE $tablename $action COLUMN ".implode(",$action column ", $columns);
749 * Generates SQL for key specification inside CREATE TABLE statement
751 * The passes array is an array of field definitions or a field definition
752 * itself. The keys generated will be either primary, foreign, unique, index
753 * or none at all depending on the setting of the "key" parameter of a field definition
755 * @param array $indices
756 * @param bool $alter_table
757 * @param string $alter_action
758 * @return string SQL Statement
760 protected function keysSQL($indices, $alter_table = false, $alter_action = '')
762 // check if the passed value is an array of fields.
763 // if not, convert it into an array
764 if (!$this->isFieldArray($indices))
765 $indices[] = $indices;
768 foreach ($indices as $index) {
769 if(!empty($index['db']) && $index['db'] != $this->dbType)
771 if (isset($index['source']) && $index['source'] != 'db')
774 $type = $index['type'];
775 $name = $index['name'];
777 if (is_array($index['fields']))
778 $fields = implode(", ", $index['fields']);
780 $fields = $index['fields'];
784 $columns[] = " UNIQUE $name ($fields)";
787 $columns[] = " PRIMARY KEY ($fields)";
792 case 'alternate_key':
794 * @todo here it is assumed that the primary key of the foreign
795 * table will always be named 'id'. It must be noted though
796 * that this can easily be fixed by referring to db dictionary
797 * to find the correct primary field name
800 $columns[] = " INDEX $name ($fields)";
802 $columns[] = " KEY $name ($fields)";
805 if ($this->full_text_indexing_installed())
806 $columns[] = " FULLTEXT ($fields)";
808 $GLOBALS['log']->debug('MYISAM engine is not available/enabled, full-text indexes will be skipped. Skipping:',$name);
812 $columns = implode(", $alter_action ", $columns);
813 if(!empty($alter_action)){
814 $columns = $alter_action . ' '. $columns;
820 * @see DBManager::setAutoIncrement()
822 protected function setAutoIncrement($table, $field_name)
824 return "auto_increment";
828 * Sets the next auto-increment value of a column to a specific value.
830 * @param string $table tablename
831 * @param string $field_name
833 public function setAutoIncrementStart($table, $field_name, $start_value)
835 $start_value = (int)$start_value;
836 return $this->query( "ALTER TABLE $table AUTO_INCREMENT = $start_value;");
840 * Returns the next value for an auto increment
842 * @param string $table tablename
843 * @param string $field_name
846 public function getAutoIncrement($table, $field_name)
848 $result = $this->query("SHOW TABLE STATUS LIKE '$table'");
849 $row = $this->fetchByAssoc($result);
850 if (!empty($row['Auto_increment']))
851 return $row['Auto_increment'];
857 * @see DBManager::get_indices()
859 public function get_indices($tablename)
861 //find all unique indexes and primary keys.
862 $result = $this->query("SHOW INDEX FROM $tablename");
865 while (($row=$this->fetchByAssoc($result)) !=null) {
867 if ($row['Key_name'] =='PRIMARY') {
868 $index_type='primary';
870 elseif ( $row['Non_unique'] == '0' ) {
871 $index_type='unique';
873 $name = strtolower($row['Key_name']);
874 $indices[$name]['name']=$name;
875 $indices[$name]['type']=$index_type;
876 $indices[$name]['fields'][]=strtolower($row['Column_name']);
882 * @see DBManager::add_drop_constraint()
884 public function add_drop_constraint($table, $definition, $drop = false)
886 $type = $definition['type'];
887 $fields = implode(',',$definition['fields']);
888 $name = $definition['name'];
894 case 'alternate_key':
897 $sql = "ALTER TABLE {$table} DROP INDEX {$name} ";
899 $sql = "ALTER TABLE {$table} ADD INDEX {$name} ({$fields})";
901 // constraints as indices
904 $sql = "ALTER TABLE {$table} DROP INDEX $name";
906 $sql = "ALTER TABLE {$table} ADD CONSTRAINT UNIQUE {$name} ({$fields})";
910 $sql = "ALTER TABLE {$table} DROP PRIMARY KEY";
912 $sql = "ALTER TABLE {$table} ADD CONSTRAINT PRIMARY KEY ({$fields})";
916 $sql = "ALTER TABLE {$table} DROP FOREIGN KEY ({$fields})";
918 $sql = "ALTER TABLE {$table} ADD CONSTRAINT FOREIGN KEY {$name} ({$fields}) REFERENCES {$definition['foreignTable']}({$definition['foreignField']})";
925 * Runs a query and returns a single row
927 * @param string $sql SQL Statement to execute
928 * @param bool $dieOnError True if we want to call die if the query returns errors
929 * @param string $msg Message to log if error occurs
930 * @param bool $suppress Message to log if error occurs
931 * @return array single row from the query
933 public function fetchOne($sql, $dieOnError = false, $msg = '', $suppress = false)
935 if(stripos($sql, ' LIMIT ') === false) {
936 // little optimization to just fetch one row
937 $sql .= " LIMIT 0,1";
939 return parent::fetchOne($sql, $dieOnError, $msg, $suppress);
943 * @see DBManager::full_text_indexing_installed()
945 public function full_text_indexing_installed($dbname = null)
947 return $this->isEngineEnabled('MyISAM');
951 * @see DBManager::massageFieldDef()
953 public function massageFieldDef(&$fieldDef, $tablename)
955 parent::massageFieldDef($fieldDef,$tablename);
957 if ( isset($fieldDef['default']) &&
958 ($fieldDef['dbType'] == 'text'
959 || $fieldDef['dbType'] == 'blob'
960 || $fieldDef['dbType'] == 'longtext'
961 || $fieldDef['dbType'] == 'longblob' ))
962 unset($fieldDef['default']);
963 if ($fieldDef['dbType'] == 'uint')
964 $fieldDef['len'] = '10';
965 if ($fieldDef['dbType'] == 'ulong')
966 $fieldDef['len'] = '20';
967 if ($fieldDef['dbType'] == 'bool')
968 $fieldDef['type'] = 'tinyint';
969 if ($fieldDef['dbType'] == 'bool' && empty($fieldDef['default']) )
970 $fieldDef['default'] = '0';
971 if (($fieldDef['dbType'] == 'varchar' || $fieldDef['dbType'] == 'enum') && empty($fieldDef['len']) )
972 $fieldDef['len'] = '255';
973 if ($fieldDef['dbType'] == 'uint')
974 $fieldDef['len'] = '10';
975 if ($fieldDef['dbType'] == 'int' && empty($fieldDef['len']) )
976 $fieldDef['len'] = '11';
978 if($fieldDef['dbType'] == 'decimal') {
979 if(isset($fieldDef['len'])) {
980 if(strstr($fieldDef['len'], ",") === false) {
981 $fieldDef['len'] .= ",0";
984 $fieldDef['len'] = '10,0';
990 * Generates SQL for dropping a table.
992 * @param string $name table name
993 * @return string SQL statement
995 public function dropTableNameSQL($name)
997 return "DROP TABLE IF EXISTS ".$name;
1000 public function dropIndexes($tablename, $indexes, $execute = true)
1003 foreach ($indexes as $index) {
1004 $name =$index['name'];
1006 unset(self::$index_descriptions[$tablename][$name]);
1008 if ($index['type'] == 'primary') {
1009 $sql[] = 'DROP PRIMARY KEY';
1011 $sql[] = "DROP INDEX $name";
1015 $sql = "ALTER TABLE $tablename ".join(",", $sql);
1025 * List of available collation settings
1028 public function getDefaultCollation()
1030 return "utf8_general_ci";
1034 * List of available collation settings
1037 public function getCollationList()
1039 $q = "SHOW COLLATION LIKE 'utf8%'";
1040 $r = $this->query($q);
1042 while($a = $this->fetchByAssoc($r)) {
1043 $res[] = $a['Collation'];
1050 * @see DBManager::renameColumnSQL()
1052 public function renameColumnSQL($tablename, $column, $newname)
1054 $field = $this->describeField($column, $tablename);
1055 $field['name'] = $newname;
1056 return "ALTER TABLE $tablename CHANGE COLUMN $column ".$this->oneColumnSQLRep($field);
1059 public function emptyValue($type)
1061 $ctype = $this->getColumnType($type);
1062 if($ctype == "datetime") {
1063 return $this->convert($this->quoted("0000-00-00 00:00:00"), "datetime");
1065 if($ctype == "date") {
1066 return $this->convert($this->quoted("0000-00-00"), "date");
1068 if($ctype == "time") {
1069 return $this->convert($this->quoted("00:00:00"), "time");
1071 return parent::emptyValue($type);
1076 * @see DBManager::lastDbError()
1078 public function lastDbError()
1080 if($this->database) {
1081 if(mysql_errno($this->database)) {
1082 return "MySQL error ".mysql_errno($this->database).": ".mysql_error($this->database);
1085 $err = mysql_error();
1094 * Quote MySQL search term
1095 * @param unknown_type $term
1097 protected function quoteTerm($term)
1099 if(strpos($term, ' ') !== false) {
1100 return '"'.$term.'"';
1106 * Generate fulltext query from set of terms
1107 * @param string $fields Field to search against
1108 * @param array $terms Search terms that may be or not be in the result
1109 * @param array $must_terms Search terms that have to be in the result
1110 * @param array $exclude_terms Search terms that have to be not in the result
1112 public function getFulltextQuery($field, $terms, $must_terms = array(), $exclude_terms = array())
1114 $condition = array();
1115 foreach($terms as $term) {
1116 $condition[] = $this->quoteTerm($term);
1118 foreach($must_terms as $term) {
1119 $condition[] = "+".$this->quoteTerm($term);
1121 foreach($exclude_terms as $term) {
1122 $condition[] = "-".$this->quoteTerm($term);
1124 $condition = $this->quoted(join(" ",$condition));
1125 return "MATCH($field) AGAINST($condition IN BOOLEAN MODE)";
1129 * Get list of all defined charsets
1132 protected function getCharsetInfo()
1134 $charsets = array();
1135 $res = $this->query("show variables like 'character\\_set\\_%'");
1136 while($row = $this->fetchByAssoc($res)) {
1137 $charsets[$row['Variable_name']] = $row['Value'];
1142 public function getDbInfo()
1144 $charsets = $this->getCharsetInfo();
1145 $charset_str = array();
1146 foreach($charsets as $name => $value) {
1147 $charset_str[] = "$name = $value";
1150 "MySQL Version" => @mysql_get_client_info(),
1151 "MySQL Host Info" => @mysql_get_host_info($this->database),
1152 "MySQL Server Info" => @mysql_get_server_info($this->database),
1153 "MySQL Client Encoding" => @mysql_client_encoding($this->database),
1154 "MySQL Character Set Settings" => join(", ", $charset_str),
1158 public function validateQuery($query)
1160 $res = $this->getOne("EXPLAIN $query");
1161 return !empty($res);
1164 protected function makeTempTableCopy($table)
1166 $this->log->debug("creating temp table for [$table]...");
1167 $create = $this->getOne("SHOW CREATE TABLE {$table}");
1168 if(empty($create)) {
1171 // rewrite DDL with _temp name
1172 $tempTableQuery = str_replace("CREATE TABLE `{$table}`", "CREATE TABLE `{$table}__uw_temp`", $create);
1173 $r2 = $this->query($tempTableQuery);
1178 // get sample data into the temp table to test for data/constraint conflicts
1179 $this->log->debug('inserting temp dataset...');
1180 $q3 = "INSERT INTO `{$table}__uw_temp` SELECT * FROM `{$table}` LIMIT 10";
1181 $this->query($q3, false, "Preflight Failed for: {$q3}");
1186 * Tests an ALTER TABLE query
1187 * @param string table The table name to get DDL
1188 * @param string query The query to test.
1189 * @return string Non-empty if error found
1191 protected function verifyAlterTable($table, $query)
1193 $this->log->debug("verifying ALTER TABLE");
1194 // Skipping ALTER TABLE [table] DROP PRIMARY KEY because primary keys are not being copied
1195 // over to the temp tables
1196 if(strpos(strtoupper($query), 'DROP PRIMARY KEY') !== false) {
1197 $this->log->debug("Skipping DROP PRIMARY KEY");
1200 if(!$this->makeTempTableCopy($table)) {
1201 return 'Could not create temp table copy';
1204 // test the query on the test table
1205 $this->log->debug('testing query: ['.$query.']');
1206 $tempTableTestQuery = str_replace("ALTER TABLE `{$table}`", "ALTER TABLE `{$table}__uw_temp`", $query);
1207 if (strpos($tempTableTestQuery, 'idx') === false) {
1208 if(strpos($tempTableTestQuery, '__uw_temp') === false) {
1209 return 'Could not use a temp table to test query!';
1212 $this->log->debug('testing query on temp table: ['.$tempTableTestQuery.']');
1213 $this->query($tempTableTestQuery, false, "Preflight Failed for: {$query}");
1215 // test insertion of an index on a table
1216 $tempTableTestQuery_idx = str_replace("ADD INDEX `idx_", "ADD INDEX `temp_idx_", $tempTableTestQuery);
1217 $this->log->debug('testing query on temp table: ['.$tempTableTestQuery_idx.']');
1218 $this->query($tempTableTestQuery_idx, false, "Preflight Failed for: {$query}");
1220 $mysqlError = $this->getL();
1221 if(!empty($mysqlError)) {
1224 $this->dropTableName("{$table}__uw_temp");
1229 protected function verifyGenericReplaceQuery($querytype, $table, $query)
1231 $this->log->debug("verifying $querytype statement");
1233 if(!$this->makeTempTableCopy($table)) {
1234 return 'Could not create temp table copy';
1236 // test the query on the test table
1237 $this->log->debug('testing query: ['.$query.']');
1238 $tempTableTestQuery = str_replace("$querytype `{$table}`", "$querytype `{$table}__uw_temp`", $query);
1239 if(strpos($tempTableTestQuery, '__uw_temp') === false) {
1240 return 'Could not use a temp table to test query!';
1243 $this->query($tempTableTestQuery, false, "Preflight Failed for: {$query}");
1244 $error = $this->lastError(); // empty on no-errors
1245 $this->dropTableName("{$table}__uw_temp"); // just in case
1250 * Tests a DROP TABLE query
1251 * @param string table The table name to get DDL
1252 * @param string query The query to test.
1253 * @return string Non-empty if error found
1255 public function verifyDropTable($table, $query)
1257 return $this->verifyGenericReplaceQuery("DROP TABLE", $table, $query);
1261 * Tests an INSERT INTO query
1262 * @param string table The table name to get DDL
1263 * @param string query The query to test.
1264 * @return string Non-empty if error found
1266 public function verifyInsertInto($table, $query)
1268 return $this->verifyGenericReplaceQuery("INSERT INTO", $table, $query);
1272 * Tests an UPDATE 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 verifyUpdate($table, $query)
1279 return $this->verifyGenericReplaceQuery("UPDATE", $table, $query);
1283 * Tests an DELETE FROM 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 verifyDeleteFrom($table, $query)
1290 return $this->verifyGenericReplaceQuery("DELETE FROM", $table, $query);
1294 * Check if certain database exists
1295 * @param string $dbname
1297 public function dbExists($dbname)
1299 $db = $this->getOne("SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = ".$this->quoted($dbname));
1305 * @param string $dbname
1307 protected function selectDb($dbname)
1309 return mysql_select_db($dbname);
1313 * Check if certain DB user exists
1314 * @param string $username
1316 public function userExists($username)
1318 $db = $this->getOne("SELECT DATABASE()");
1319 if(!$this->selectDb("mysql")) {
1322 $user = $this->getOne("select count(*) from user where user = ".$this->quoted($username));
1323 if(!$this->selectDb($db)) {
1324 $this->checkError("Cannot select database $db", true);
1326 return !empty($user);
1331 * @param string $database_name
1332 * @param string $host_name
1333 * @param string $user
1334 * @param string $password
1336 public function createDbUser($database_name, $host_name, $user, $password)
1338 $qpassword = $this->quote($password);
1339 $this->query("GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, ALTER, DROP, INDEX
1340 ON `$database_name`.*
1341 TO \"$user\"@\"$host_name\"
1342 IDENTIFIED BY '{$qpassword}';", true);
1344 $this->query("SET PASSWORD FOR \"{$user}\"@\"{$host_name}\" = old_password('{$qpassword}');", true);
1345 if($host_name != 'localhost') {
1346 $this->createDbUser($database_name, "localhost", $user, $password);
1352 * @param string $dbname
1354 public function createDatabase($dbname)
1356 $this->query("CREATE DATABASE `$dbname` CHARACTER SET utf8 COLLATE utf8_general_ci", true);
1359 public function preInstall()
1361 $db->query("ALTER DATABASE `{$setup_db_database_name}` DEFAULT CHARACTER SET utf8", true);
1362 $db->query("ALTER DATABASE `{$setup_db_database_name}` DEFAULT COLLATE utf8_general_ci", true);
1368 * @param string $dbname
1370 public function dropDatabase($dbname)
1372 return $this->query("DROP DATABASE IF EXISTS `$dbname`", true);
1376 * Check if this driver can be used
1379 public function valid()
1381 return function_exists("mysql_connect");
1386 * @see DBManager::canInstall()
1388 public function canInstall()
1390 $db_version = $this->version();
1391 if(empty($db_version)) {
1392 return array('ERR_DB_VERSION_FAILURE');
1394 if(version_compare($db_version, '4.1.2') < 0) {
1395 return array('ERR_DB_MYSQL_VERSION', $db_version);
1400 public function installConfig()
1403 'LBL_DBCONFIG_MSG3' => array(
1404 "setup_db_database_name" => array("label" => 'LBL_DBCONF_DB_NAME', "required" => true),
1406 'LBL_DBCONFIG_MSG2' => array(
1407 "setup_db_host_name" => array("label" => 'LBL_DBCONF_HOST_NAME', "required" => true),
1409 'LBL_DBCONF_TITLE_USER_INFO' => array(),
1410 'LBL_DBCONFIG_B_MSG1' => array(
1411 "setup_db_admin_user_name" => array("label" => 'LBL_DBCONF_DB_ADMIN_USER', "required" => true),
1412 "setup_db_admin_password" => array("label" => 'LBL_DBCONF_DB_ADMIN_PASSWORD', "type" => "password"),
1418 * Disable keys on the table
1420 * @param string $tableName
1422 public function disableKeys($tableName)
1424 return $this->query('ALTER TABLE '.$tableName.' DISABLE KEYS');
1428 * Re-enable keys on the table
1430 * @param string $tableName
1432 public function enableKeys($tableName)
1434 return $this->query('ALTER TABLE '.$tableName.' ENABLE KEYS');