]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - include/database/MysqlManager.php
Release 6.4.0beta3
[Github/sugarcrm.git] / include / database / MysqlManager.php
1 <?php
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.
6  * 
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.
13  * 
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
17  * details.
18  * 
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
22  * 02110-1301 USA.
23  * 
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.
26  * 
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.
30  * 
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  ********************************************************************************/
37
38 /*********************************************************************************
39
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.
44 *
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.
47 *
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
55 *
56 * The field definition is an array with the following keys:
57 *
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:
60 *           �   int
61 *           �   long
62 *           �   varchar
63 *           �   text
64 *           �   date
65 *           �   datetime
66 *           �   double
67 *           �   float
68 *           �   uint
69 *           �   ulong
70 *           �   time
71 *           �   short
72 *           �   enum
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.
84 *
85 *
86 * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
87 * All Rights Reserved.
88 * Contributor(s): ______________________________________..
89 ********************************************************************************/
90
91 /**
92  * MySQL manager implementation for mysql extension
93  */
94 class MysqlManager extends DBManager
95 {
96         /**
97          * @see DBManager::$dbType
98          */
99         public $dbType = 'mysql';
100         public $variant = 'mysql';
101         public $dbName = 'MySQL';
102         public $label = 'LBL_MYSQL';
103
104         protected $maxNameLengths = array(
105                 'table' => 64,
106                 'column' => 64,
107                 'index' => 64,
108                 'alias' => 256
109         );
110
111         protected $type_map = array(
112                         'int'      => 'int',
113                         'double'   => 'double',
114                         'float'    => 'float',
115                         'uint'     => 'int unsigned',
116                         'ulong'    => 'bigint unsigned',
117                         'long'     => 'bigint',
118                         'short'    => 'smallint',
119                         'varchar'  => 'varchar',
120                         'text'     => 'text',
121                         'longtext' => 'longtext',
122                         'date'     => 'date',
123                         'enum'     => 'varchar',
124                         'relate'   => 'varchar',
125                         'multienum'=> 'text',
126                         'html'     => 'text',
127                         'datetime' => 'datetime',
128                         'datetimecombo' => 'datetime',
129                         'time'     => 'time',
130                         'bool'     => 'bool',
131                         'tinyint'  => 'tinyint',
132                         'char'     => 'char',
133                         'blob'     => 'blob',
134                         'longblob' => 'longblob',
135                         'currency' => 'decimal(26,6)',
136                         'decimal'  => 'decimal',
137                         'decimal2' => 'decimal',
138                         'id'       => 'char(36)',
139                         'url'      => 'varchar',
140                         'encrypt'  => 'varchar',
141                         'file'     => 'varchar',
142                         'decimal_tpl' => 'decimal(%d, %d)',
143
144         );
145
146         protected $capabilities = array(
147                 "affected_rows" => true,
148                 "select_rows" => true,
149                 "inline_keys" => true,
150                 "create_user" => true,
151                 "fulltext" => true,
152             "collation" => true,
153             "create_db" => true,
154             "disable_keys" => true,
155         );
156
157         /**
158          * Parses and runs queries
159          *
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
166          */
167         public function query($sql, $dieOnError = false, $msg = '', $suppress = false, $keepResult = false)
168         {
169                 if(is_array($sql)) {
170                         return $this->queryArray($sql, $dieOnError, $msg, $suppress);
171                 }
172
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);
179
180                 $this->query_time = microtime(true) - $this->query_time;
181                 $GLOBALS['log']->info('Query Execution Time:'.$this->query_time);
182
183
184                 if($keepResult)
185                         $this->lastResult = $result;
186
187                 $this->checkError($msg.' Query Failed:' . $sql . '::', $dieOnError);
188                 return $result;
189         }
190
191     /**
192      * Returns the number of rows affected by the last query
193      * @param $result
194      * @return int
195      */
196         public function getAffectedRowCount($result)
197         {
198                 return mysql_affected_rows($this->getDatabase());
199         }
200
201         /**
202          * Returns the number of rows returned by the result
203          *
204          * This function can't be reliably implemented on most DB, do not use it.
205          * @abstract
206          * @deprecated
207          * @param  resource $result
208          * @return int
209          */
210         public function getRowCount($result)
211         {
212             return mysql_num_rows($result);
213         }
214
215         /**
216          * Disconnects from the database
217          *
218          * Also handles any cleanup needed
219          */
220         public function disconnect()
221         {
222                 $GLOBALS['log']->debug('Calling MySQL::disconnect()');
223                 if(!empty($this->database)){
224                         $this->freeResult();
225                         mysql_close($this->database);
226                         $this->database = null;
227                 }
228         }
229
230         /**
231          * @see DBManager::freeDbResult()
232          */
233         protected function freeDbResult($dbResult)
234         {
235                 if(!empty($dbResult))
236                         mysql_free_result($dbResult);
237         }
238
239
240         /**
241          * @see DBManager::limitQuery()
242          */
243         public function limitQuery($sql, $start, $count, $dieOnError = false, $msg = '', $execute = true)
244         {
245                 if ($start < 0)
246                         $start = 0;
247                 $GLOBALS['log']->debug('Limit Query:' . $sql. ' Start: ' .$start . ' count: ' . $count);
248
249             $sql = "$sql LIMIT $start,$count";
250                 $this->lastsql = $sql;
251
252                 if(!empty($GLOBALS['sugar_config']['check_query'])){
253                         $this->checkQuery($sql);
254                 }
255                 if(!$execute) {
256                         return $sql;
257                 }
258
259                 return $this->query($sql, $dieOnError, $msg);
260         }
261
262
263         /**
264          * @see DBManager::checkQuery()
265          */
266         protected function checkQuery($sql)
267         {
268                 $result   = $this->query('EXPLAIN ' . $sql);
269                 $badQuery = array();
270                 while ($row = $this->fetchByAssoc($result)) {
271                         if (empty($row['table']))
272                                 continue;
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;';
282                 }
283
284                 if ( empty($badQuery) )
285                         return true;
286
287                 foreach($badQuery as $table=>$data ){
288                         if(!empty($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);
293                                 }
294                                 else{
295                                         $GLOBALS['log']->warn('CHECK QUERY:' .$warning);
296                                 }
297                         }
298                 }
299
300                 return false;
301         }
302
303         /**
304          * @see DBManager::get_columns()
305          */
306         public function get_columns($tablename)
307         {
308                 //find all unique indexes and primary keys.
309                 $result = $this->query("DESCRIBE $tablename");
310
311                 $columns = array();
312                 while (($row=$this->fetchByAssoc($result)) !=null) {
313                         $name = strtolower($row['Field']);
314                         $columns[$name]['name']=$name;
315                         $matches = array();
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'];
326                 }
327                 return $columns;
328         }
329
330         /**
331          * @see DBManager::getFieldsArray()
332          */
333         public function getFieldsArray($result, $make_lower_case=false)
334         {
335                 $field_array = array();
336
337                 if(empty($result))
338                         return 0;
339
340                 $fields = mysql_num_fields($result);
341                 for ($i=0; $i < $fields; $i++) {
342                         $meta = mysql_fetch_field($result, $i);
343                         if (!$meta)
344                                 return array();
345
346                         if($make_lower_case == true)
347                                 $meta->name = strtolower($meta->name);
348
349                         $field_array[] = $meta->name;
350                 }
351
352                 return $field_array;
353         }
354
355         /**
356          * @see DBManager::fetchRow()
357          */
358         public function fetchRow($result)
359         {
360                 if (empty($result))     return false;
361
362                 return mysql_fetch_assoc($result);
363         }
364
365         /**
366          * @see DBManager::getTablesArray()
367          */
368         public function getTablesArray()
369         {
370                 $this->log->debug('Fetching table list');
371
372                 if ($this->getDatabase()) {
373                         $tables = array();
374                         $r = $this->query('SHOW TABLES');
375                         if (!empty($r)) {
376                                 while ($a = $this->fetchByAssoc($r)) {
377                                         $row = array_values($a);
378                                         $tables[]=$row[0];
379                                 }
380                                 return $tables;
381                         }
382                 }
383
384                 return false; // no database available
385         }
386
387         /**
388          * @see DBManager::version()
389          */
390         public function version()
391         {
392                 return $this->getOne("SELECT version() version");
393         }
394
395         /**
396          * @see DBManager::tableExists()
397          */
398         public function tableExists($tableName)
399         {
400                 $this->log->info("tableExists: $tableName");
401
402                 if ($this->getDatabase()) {
403                         $result = $this->getOne("SHOW TABLES LIKE ".$this->quoted($tableName));
404                         return !empty($result);
405                 }
406
407                 return false;
408         }
409
410         /**
411          * Get tables like expression
412          * @param $like string
413          * @return array
414          */
415         public function tablesLike($like)
416         {
417                 if ($this->getDatabase()) {
418                         $tables = array();
419                         $r = $this->query('SHOW TABLES LIKE '.$this->quoted($like));
420                         if (!empty($r)) {
421                                 while ($a = $this->fetchByAssoc($r)) {
422                                         $row = array_values($a);
423                                         $tables[]=$row[0];
424                                 }
425                                 return $tables;
426                         }
427                 }
428                 return false;
429         }
430
431         /**
432          * @see DBManager::quote()
433          */
434         public function quote($string)
435         {
436                 if(is_array($string)) {
437                         return $this->arrayQuote($string);
438                 }
439                 return mysql_real_escape_string($this->quoteInternal($string), $this->getDatabase());
440         }
441
442         /**
443          * @see DBManager::connect()
444          */
445         public function connect(array $configOptions = null, $dieOnError = false)
446         {
447                 global $sugar_config;
448
449                 if(is_null($configOptions))
450                         $configOptions = $sugar_config['dbconfig'];
451
452                 if ($this->getOption('persistent')) {
453                         $this->database = @mysql_pconnect(
454                                 $configOptions['db_host_name'],
455                                 $configOptions['db_user_name'],
456                                 $configOptions['db_password']
457                                 );
458                 }
459
460                 if (!$this->database) {
461                         $this->database = mysql_connect(
462                                         $configOptions['db_host_name'],
463                                         $configOptions['db_user_name'],
464                                         $configOptions['db_password']
465                                         );
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());
468                                 if($dieOnError) {
469                                         if(isset($GLOBALS['app_strings']['ERR_NO_DB'])) {
470                                                 sugar_die($GLOBALS['app_strings']['ERR_NO_DB']);
471                                         } else {
472                                                 sugar_die("Could not connect to the database. Please refer to sugarcrm.log for details.");
473                                         }
474                                 } else {
475                                         return false;
476                                 }
477                         }
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>";
483                         }
484                 }
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));
487                         if($dieOnError) {
488                                 sugar_die($GLOBALS['app_strings']['ERR_NO_DB']);
489                         } else {
490                                 return false;
491                         }
492                 }
493
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'";
500                 }
501             mysql_query($names, $this->database);
502
503                 if(!$this->checkError('Could Not Connect:', $dieOnError))
504                         $GLOBALS['log']->info("connected to db");
505                 $this->connectOptions = $configOptions;
506
507                 $GLOBALS['log']->info("Connect:".$this->database);
508                 return true;
509         }
510
511         /**
512          * @see DBManager::repairTableParams()
513          *
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.
516          */
517         public function repairTableParams($tablename, $fielddefs, $indices, $execute = true, $engine = null)
518         {
519                 $sql = parent::repairTableParams($tablename,$fielddefs,$indices,false,$engine);
520
521                 if ( $sql == '' )
522                         return '';
523
524                 if ( stristr($sql,'create table') )
525                 {
526                         if ($execute) {
527                                 $msg = "Error creating table: ".$tablename. ":";
528                                 $this->query($sql,true,$msg);
529                         }
530                         return $sql;
531                 }
532
533                 // first, parse out all the comments
534                 $match = array();
535                 preg_match_all('!/\*.*?\*/!is', $sql, $match);
536                 $commentBlocks = $match[0];
537                 $sql = preg_replace('!/\*.*?\*/!is','', $sql);
538
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);
542
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";
548
549                 if ( $execute )
550                         $this->query($sql,'Error with MySQL repair table');
551
552                 // and re-add the comments at the beginning
553                 $sql = implode("\n",$commentBlocks) . "\n". $sql . "\n";
554
555                 return $sql;
556         }
557
558         /**
559          * @see DBManager::convert()
560          */
561         public function convert($string, $type, array $additional_parameters = array())
562         {
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);
568                 }
569                 $all_strings = implode(',', $all_parameters);
570
571                 switch (strtolower($type)) {
572                         case 'today':
573                                 return "CURDATE()";
574                         case 'left':
575                                 return "LEFT($all_strings)";
576                         case 'date_format':
577                                 if(empty($additional_parameters)) {
578                                         return "DATE_FORMAT($string,'%Y-%m-%d')";
579                                 } else {
580                                         $format = $additional_parameters[0];
581                                         if($format[0] != "'") {
582                                                 $format = $this->quoted($format);
583                                         }
584                                         return "DATE_FORMAT($string,$format)";
585                                 }
586                         case 'ifnull':
587                                 if(empty($additional_parameters) && !strstr($all_strings, ",")) {
588                                         $all_strings .= ",''";
589                                 }
590                                 return "IFNULL($all_strings)";
591                         case 'concat':
592                                 return "CONCAT($all_strings)";
593                         case 'quarter':
594                                         return "QUARTER($string)";
595                         case "length":
596                                         return "LENGTH($string)";
597                         case 'month':
598                                         return "MONTH($string)";
599                         case 'add_date':
600                                         return "DATE_ADD($string, INTERVAL {$additional_parameters[0]} {$additional_parameters[1]})";
601                         case 'add_time':
602                                         return "DATE_ADD($string, INTERVAL + CONCAT({$additional_parameters[0]}, ':', {$additional_parameters[1]}) HOUR_MINUTE)";
603                 }
604
605                 return $string;
606         }
607
608         /**
609          * (non-PHPdoc)
610          * @see DBManager::fromConvert()
611          */
612         public function fromConvert($string, $type)
613         {
614                 return $string;
615         }
616
617         /**
618          * Returns the name of the engine to use or null if we are to use the default
619          *
620          * @param  object $bean SugarBean instance
621          * @return string
622          */
623         protected function getEngine($bean)
624         {
625                 global $dictionary;
626                 $engine = null;
627                 if (isset($dictionary[$bean->getObjectName()]['engine'])) {
628                         $engine = $dictionary[$bean->getObjectName()]['engine'];
629                 }
630                 return $engine;
631         }
632
633         /**
634          * Returns true if the engine given is enabled in the backend
635          *
636          * @param  string $engine
637          * @return bool
638          */
639         protected function isEngineEnabled($engine)
640         {
641                 $engine = strtoupper($engine);
642
643                 $r = $this->query("SHOW ENGINES");
644
645                 while ( $row = $this->fetchByAssoc($r) )
646                         if ( strtoupper($row['Engine']) == $engine )
647                                 return ($row['Support']=='YES' || $row['Support']=='DEFAULT');
648
649                 return false;
650         }
651
652         /**
653          * @see DBManager::createTableSQL()
654          */
655         public function createTableSQL(SugarBean $bean)
656         {
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);
662         }
663
664         /**
665          * Generates sql for create table statement for a bean.
666          *
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
672         */
673         public function createTableSQLParams($tablename, $fieldDefs, $indices, $engine = null)
674         {
675                 if ( empty($engine) && isset($fieldDefs['engine']))
676                         $engine = $fieldDefs['engine'];
677                 if ( !$this->isEngineEnabled($engine) )
678                         $engine = '';
679
680                 $columns = $this->columnSQLRep($fieldDefs, false, $tablename);
681                 if (empty($columns))
682                         return false;
683
684                 $keys = $this->keysSQL($indices);
685                 if (!empty($keys))
686                         $keys = ",$keys";
687
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';
692                 }
693                 $sql = "CREATE TABLE $tablename ($columns $keys) CHARACTER SET utf8 COLLATE $collation";
694
695                 if (!empty($engine))
696                         $sql.= " ENGINE=$engine";
697
698                 return $sql;
699         }
700
701         /**
702          * @see DBManager::oneColumnSQLRep()
703          */
704         protected function oneColumnSQLRep($fieldDef, $ignoreRequired = false, $table = '', $return_as_array = false)
705         {
706                 // always return as array for post-processing
707                 $ref = parent::oneColumnSQLRep($fieldDef, $ignoreRequired, $table, true);
708
709                 if ( $ref['colType'] == 'int' && !empty($fieldDef['len']) ) {
710                         $ref['colType'] .= "(".$fieldDef['len'].")";
711                 }
712
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'] = '';
718
719                 if ( $return_as_array )
720                         return $ref;
721                 else
722                         return "{$ref['name']} {$ref['colType']} {$ref['default']} {$ref['required']} {$ref['auto_increment']}";
723         }
724
725         /**
726          * @see DBManager::changeColumnSQL()
727          */
728         protected function changeColumnSQL($tablename, $fieldDefs, $action, $ignoreRequired = false)
729         {
730                 $columns = array();
731                 if ($this->isFieldArray($fieldDefs)){
732                         foreach ($fieldDefs as $def){
733                                 if ($action == 'drop')
734                                         $columns[] = $def['name'];
735                                 else
736                                         $columns[] = $this->oneColumnSQLRep($def, $ignoreRequired);
737                         }
738                 } else {
739                         if ($action == 'drop')
740                                 $columns[] = $fieldDefs['name'];
741                 else
742                         $columns[] = $this->oneColumnSQLRep($fieldDefs);
743                 }
744
745                 return "ALTER TABLE $tablename $action COLUMN ".implode(",$action column ", $columns);
746         }
747
748         /**
749          * Generates SQL for key specification inside CREATE TABLE statement
750          *
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
754          *
755          * @param  array  $indices
756          * @param  bool   $alter_table
757          * @param  string $alter_action
758          * @return string SQL Statement
759          */
760         protected function keysSQL($indices, $alter_table = false, $alter_action = '')
761         {
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;
766
767         $columns = array();
768         foreach ($indices as $index) {
769                 if(!empty($index['db']) && $index['db'] != $this->dbType)
770                         continue;
771                 if (isset($index['source']) && $index['source'] != 'db')
772                         continue;
773
774                 $type = $index['type'];
775                 $name = $index['name'];
776
777                 if (is_array($index['fields']))
778                         $fields = implode(", ", $index['fields']);
779                 else
780                         $fields = $index['fields'];
781
782                 switch ($type) {
783                 case 'unique':
784                         $columns[] = " UNIQUE $name ($fields)";
785                         break;
786                 case 'primary':
787                         $columns[] = " PRIMARY KEY ($fields)";
788                         break;
789                 case 'index':
790                 case 'foreign':
791                 case 'clustered':
792                 case 'alternate_key':
793                         /**
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
798                                 */
799                         if ( $alter_table )
800                                 $columns[] = " INDEX $name ($fields)";
801                         else
802                                 $columns[] = " KEY $name ($fields)";
803                         break;
804                 case 'fulltext':
805                         if ($this->full_text_indexing_installed())
806                                 $columns[] = " FULLTEXT ($fields)";
807                         else
808                                 $GLOBALS['log']->debug('MYISAM engine is not available/enabled, full-text indexes will be skipped. Skipping:',$name);
809                         break;
810                 }
811         }
812         $columns = implode(", $alter_action ", $columns);
813         if(!empty($alter_action)){
814                 $columns = $alter_action . ' '. $columns;
815         }
816         return $columns;
817         }
818
819         /**
820          * @see DBManager::setAutoIncrement()
821          */
822         protected function setAutoIncrement($table, $field_name)
823         {
824                 return "auto_increment";
825         }
826
827         /**
828          * Sets the next auto-increment value of a column to a specific value.
829          *
830          * @param  string $table tablename
831          * @param  string $field_name
832          */
833         public function setAutoIncrementStart($table, $field_name, $start_value)
834         {
835                 $start_value = (int)$start_value;
836                 return $this->query( "ALTER TABLE $table AUTO_INCREMENT = $start_value;");
837         }
838
839         /**
840          * Returns the next value for an auto increment
841          *
842          * @param  string $table tablename
843          * @param  string $field_name
844          * @return string
845          */
846         public function getAutoIncrement($table, $field_name)
847         {
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'];
852
853                 return "";
854         }
855
856         /**
857          * @see DBManager::get_indices()
858          */
859         public function get_indices($tablename)
860         {
861                 //find all unique indexes and primary keys.
862                 $result = $this->query("SHOW INDEX FROM $tablename");
863
864                 $indices = array();
865                 while (($row=$this->fetchByAssoc($result)) !=null) {
866                         $index_type='index';
867                         if ($row['Key_name'] =='PRIMARY') {
868                                 $index_type='primary';
869                         }
870                         elseif ( $row['Non_unique'] == '0' ) {
871                                 $index_type='unique';
872                         }
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']);
877                 }
878                 return $indices;
879         }
880
881         /**
882          * @see DBManager::add_drop_constraint()
883          */
884         public function add_drop_constraint($table, $definition, $drop = false)
885         {
886                 $type         = $definition['type'];
887                 $fields       = implode(',',$definition['fields']);
888                 $name         = $definition['name'];
889                 $sql          = '';
890
891                 switch ($type){
892                 // generic indices
893                 case 'index':
894                 case 'alternate_key':
895                 case 'clustered':
896                         if ($drop)
897                                 $sql = "ALTER TABLE {$table} DROP INDEX {$name} ";
898                         else
899                                 $sql = "ALTER TABLE {$table} ADD INDEX {$name} ({$fields})";
900                         break;
901                 // constraints as indices
902                 case 'unique':
903                         if ($drop)
904                                 $sql = "ALTER TABLE {$table} DROP INDEX $name";
905                         else
906                                 $sql = "ALTER TABLE {$table} ADD CONSTRAINT UNIQUE {$name} ({$fields})";
907                         break;
908                 case 'primary':
909                         if ($drop)
910                                 $sql = "ALTER TABLE {$table} DROP PRIMARY KEY";
911                         else
912                                 $sql = "ALTER TABLE {$table} ADD CONSTRAINT PRIMARY KEY ({$fields})";
913                         break;
914                 case 'foreign':
915                         if ($drop)
916                                 $sql = "ALTER TABLE {$table} DROP FOREIGN KEY ({$fields})";
917                         else
918                                 $sql = "ALTER TABLE {$table} ADD CONSTRAINT FOREIGN KEY {$name} ({$fields}) REFERENCES {$definition['foreignTable']}({$definition['foreignField']})";
919                         break;
920                 }
921                 return $sql;
922         }
923
924         /**
925          * Runs a query and returns a single row
926          *
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
932          */
933         public function fetchOne($sql, $dieOnError = false, $msg = '', $suppress = false)
934         {
935                 if(stripos($sql, ' LIMIT ') === false) {
936                         // little optimization to just fetch one row
937                         $sql .= " LIMIT 0,1";
938                 }
939                 return parent::fetchOne($sql, $dieOnError, $msg, $suppress);
940         }
941
942         /**
943          * @see DBManager::full_text_indexing_installed()
944          */
945         public function full_text_indexing_installed($dbname = null)
946         {
947                 return $this->isEngineEnabled('MyISAM');
948         }
949
950         /**
951          * @see DBManager::massageFieldDef()
952          */
953         public function massageFieldDef(&$fieldDef, $tablename)
954         {
955                 parent::massageFieldDef($fieldDef,$tablename);
956
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';
977
978                 if($fieldDef['dbType'] == 'decimal') {
979                         if(isset($fieldDef['len'])) {
980                                 if(strstr($fieldDef['len'], ",") === false) {
981                                         $fieldDef['len'] .= ",0";
982                                 }
983                         } else {
984                                 $fieldDef['len']  = '10,0';
985                         }
986                 }
987         }
988
989         /**
990          * Generates SQL for dropping a table.
991          *
992          * @param  string $name table name
993          * @return string SQL statement
994          */
995         public function dropTableNameSQL($name)
996         {
997                 return "DROP TABLE IF EXISTS ".$name;
998         }
999
1000         public function dropIndexes($tablename, $indexes, $execute = true)
1001         {
1002                 $sql = array();
1003                 foreach ($indexes as $index) {
1004                         $name =$index['name'];
1005                         if($execute) {
1006                         unset(self::$index_descriptions[$tablename][$name]);
1007                         }
1008                         if ($index['type'] == 'primary') {
1009                                 $sql[] = 'DROP PRIMARY KEY';
1010                         } else {
1011                                 $sql[] = "DROP INDEX $name";
1012                         }
1013                 }
1014                 if (!empty($sql)) {
1015                         $sql = "ALTER TABLE $tablename ".join(",", $sql);
1016                         if($execute)
1017                                 $this->query($sql);
1018                 } else {
1019                         $sql = '';
1020                 }
1021                 return $sql;
1022         }
1023
1024         /**
1025          * List of available collation settings
1026          * @return string
1027          */
1028         public function getDefaultCollation()
1029         {
1030                 return "utf8_general_ci";
1031         }
1032
1033         /**
1034          * List of available collation settings
1035          * @return array
1036          */
1037         public function getCollationList()
1038         {
1039                 $q = "SHOW COLLATION LIKE 'utf8%'";
1040                 $r = $this->query($q);
1041                 $res = array();
1042                 while($a = $this->fetchByAssoc($r)) {
1043                         $res[] = $a['Collation'];
1044                 }
1045                 return $res;
1046         }
1047
1048         /**
1049          * (non-PHPdoc)
1050          * @see DBManager::renameColumnSQL()
1051          */
1052         public function renameColumnSQL($tablename, $column, $newname)
1053         {
1054                 $field = $this->describeField($column, $tablename);
1055                 $field['name'] = $newname;
1056                 return "ALTER TABLE $tablename CHANGE COLUMN $column ".$this->oneColumnSQLRep($field);
1057         }
1058
1059         public function emptyValue($type)
1060         {
1061                 $ctype = $this->getColumnType($type);
1062                 if($ctype == "datetime") {
1063                         return $this->convert($this->quoted("0000-00-00 00:00:00"), "datetime");
1064                 }
1065                 if($ctype == "date") {
1066                         return $this->convert($this->quoted("0000-00-00"), "date");
1067                 }
1068                 if($ctype == "time") {
1069                         return $this->convert($this->quoted("00:00:00"), "time");
1070                 }
1071                 return parent::emptyValue($type);
1072         }
1073
1074         /**
1075          * (non-PHPdoc)
1076          * @see DBManager::lastDbError()
1077          */
1078         public function lastDbError()
1079         {
1080                 if($this->database) {
1081                     if(mysql_errno($this->database)) {
1082                             return "MySQL error ".mysql_errno($this->database).": ".mysql_error($this->database);
1083                     }
1084                 } else {
1085                         $err =  mysql_error();
1086                         if($err) {
1087                             return $err;
1088                         }
1089                 }
1090         return false;
1091     }
1092
1093         /**
1094          * Quote MySQL search term
1095          * @param unknown_type $term
1096          */
1097         protected function quoteTerm($term)
1098         {
1099                 if(strpos($term, ' ') !== false) {
1100                         return '"'.$term.'"';
1101                 }
1102                 return $term;
1103         }
1104
1105         /**
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
1111          */
1112         public function getFulltextQuery($field, $terms, $must_terms = array(), $exclude_terms = array())
1113         {
1114                 $condition = array();
1115                 foreach($terms as $term) {
1116                         $condition[] = $this->quoteTerm($term);
1117                 }
1118                 foreach($must_terms as $term) {
1119                         $condition[] = "+".$this->quoteTerm($term);
1120                 }
1121                 foreach($exclude_terms as $term) {
1122                         $condition[] = "-".$this->quoteTerm($term);
1123                 }
1124                 $condition = $this->quoted(join(" ",$condition));
1125                 return "MATCH($field) AGAINST($condition IN BOOLEAN MODE)";
1126         }
1127
1128         /**
1129          * Get list of all defined charsets
1130          * @return array
1131          */
1132         protected function getCharsetInfo()
1133         {
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'];
1138                 }
1139                 return $charsets;
1140         }
1141
1142         public function getDbInfo()
1143         {
1144                 $charsets = $this->getCharsetInfo();
1145                 $charset_str = array();
1146                 foreach($charsets as $name => $value) {
1147                         $charset_str[] = "$name = $value";
1148                 }
1149                 return array(
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),
1155                 );
1156         }
1157
1158         public function validateQuery($query)
1159         {
1160                 $res = $this->getOne("EXPLAIN $query");
1161                 return !empty($res);
1162         }
1163
1164         protected function makeTempTableCopy($table)
1165         {
1166                 $this->log->debug("creating temp table for [$table]...");
1167                 $create = $this->getOne("SHOW CREATE TABLE {$table}");
1168                 if(empty($create)) {
1169                         return false;
1170                 }
1171                 // rewrite DDL with _temp name
1172                 $tempTableQuery = str_replace("CREATE TABLE `{$table}`", "CREATE TABLE `{$table}__uw_temp`", $create);
1173                 $r2 = $this->query($tempTableQuery);
1174                 if(empty($r2)) {
1175                         return false;
1176                 }
1177
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}");
1182                 return true;
1183         }
1184
1185         /**
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
1190          */
1191         protected function verifyAlterTable($table, $query)
1192         {
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");
1198                         return '';
1199                 }
1200                 if(!$this->makeTempTableCopy($table)) {
1201                         return 'Could not create temp table copy';
1202                 }
1203
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!';
1210                         }
1211
1212                         $this->log->debug('testing query on temp table: ['.$tempTableTestQuery.']');
1213                         $this->query($tempTableTestQuery, false, "Preflight Failed for: {$query}");
1214                 } else {
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}");
1219                 }
1220                 $mysqlError = $this->getL();
1221                 if(!empty($mysqlError)) {
1222                         return $mysqlError;
1223                 }
1224                 $this->dropTableName("{$table}__uw_temp");
1225
1226                 return '';
1227         }
1228
1229         protected function verifyGenericReplaceQuery($querytype, $table, $query)
1230         {
1231                 $this->log->debug("verifying $querytype statement");
1232
1233                 if(!$this->makeTempTableCopy($table)) {
1234                         return 'Could not create temp table copy';
1235                 }
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!';
1241                 }
1242
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
1246                 return $error;
1247         }
1248
1249         /**
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
1254          */
1255         public function verifyDropTable($table, $query)
1256         {
1257                 return $this->verifyGenericReplaceQuery("DROP TABLE", $table, $query);
1258         }
1259
1260         /**
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
1265          */
1266         public function verifyInsertInto($table, $query)
1267         {
1268                 return $this->verifyGenericReplaceQuery("INSERT INTO", $table, $query);
1269         }
1270
1271         /**
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
1276          */
1277         public function verifyUpdate($table, $query)
1278         {
1279                 return $this->verifyGenericReplaceQuery("UPDATE", $table, $query);
1280         }
1281
1282         /**
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
1287          */
1288         public function verifyDeleteFrom($table, $query)
1289         {
1290                 return $this->verifyGenericReplaceQuery("DELETE FROM", $table, $query);
1291         }
1292
1293         /**
1294          * Check if certain database exists
1295          * @param string $dbname
1296          */
1297         public function dbExists($dbname)
1298         {
1299                 $db = $this->getOne("SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = ".$this->quoted($dbname));
1300                 return !empty($db);
1301         }
1302
1303         /**
1304          * Select database
1305          * @param string $dbname
1306          */
1307         protected function selectDb($dbname)
1308         {
1309                 return mysql_select_db($dbname);
1310         }
1311
1312         /**
1313          * Check if certain DB user exists
1314          * @param string $username
1315          */
1316         public function userExists($username)
1317         {
1318                 $db = $this->getOne("SELECT DATABASE()");
1319                 if(!$this->selectDb("mysql")) {
1320                         return false;
1321                 }
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);
1325                 }
1326                 return !empty($user);
1327         }
1328
1329         /**
1330          * Create DB user
1331          * @param string $database_name
1332          * @param string $host_name
1333          * @param string $user
1334          * @param string $password
1335          */
1336         public function createDbUser($database_name, $host_name, $user, $password)
1337         {
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);
1343
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);
1347                 }
1348         }
1349
1350         /**
1351          * Create a database
1352          * @param string $dbname
1353          */
1354         public function createDatabase($dbname)
1355         {
1356                 $this->query("CREATE DATABASE `$dbname` CHARACTER SET utf8 COLLATE utf8_general_ci", true);
1357         }
1358
1359         public function preInstall()
1360         {
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);
1363
1364         }
1365
1366         /**
1367          * Drop a database
1368          * @param string $dbname
1369          */
1370         public function dropDatabase($dbname)
1371         {
1372                 return $this->query("DROP DATABASE IF EXISTS `$dbname`", true);
1373         }
1374
1375         /**
1376          * Check if this driver can be used
1377          * @return bool
1378          */
1379         public function valid()
1380         {
1381                 return function_exists("mysql_connect");
1382         }
1383
1384         /**
1385          * Check DB version
1386          * @see DBManager::canInstall()
1387          */
1388         public function canInstall()
1389         {
1390                 $db_version = $this->version();
1391                 if(empty($db_version)) {
1392                         return array('ERR_DB_VERSION_FAILURE');
1393                 }
1394                 if(version_compare($db_version, '4.1.2') < 0) {
1395                         return array('ERR_DB_MYSQL_VERSION', $db_version);
1396                 }
1397                 return true;
1398         }
1399
1400         public function installConfig()
1401         {
1402                 return array(
1403                         'LBL_DBCONFIG_MSG3' =>  array(
1404                                 "setup_db_database_name" => array("label" => 'LBL_DBCONF_DB_NAME', "required" => true),
1405                         ),
1406                         'LBL_DBCONFIG_MSG2' =>  array(
1407                                 "setup_db_host_name" => array("label" => 'LBL_DBCONF_HOST_NAME', "required" => true),
1408                         ),
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"),
1413                         )
1414                 );
1415         }
1416
1417         /**
1418          * Disable keys on the table
1419          * @abstract
1420          * @param string $tableName
1421          */
1422         public function disableKeys($tableName)
1423         {
1424             return $this->query('ALTER TABLE '.$tableName.' DISABLE KEYS');
1425         }
1426
1427         /**
1428          * Re-enable keys on the table
1429          * @abstract
1430          * @param string $tableName
1431          */
1432         public function enableKeys($tableName)
1433         {
1434             return $this->query('ALTER TABLE '.$tableName.' ENABLE KEYS');
1435         }
1436 }