]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - include/database/MysqlHelper.php
Release 6.2.0
[Github/sugarcrm.git] / include / database / MysqlHelper.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 specific
41 * to oracle database. It is called by the DBManager class to generate various sql statements.
42 *
43 * All the functions in this class will work with any bean which implements the meta interface.
44 * Please refer the DBManager documentation for the details.
45 *
46 * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
47 * All Rights Reserved.
48 * Contributor(s): ______________________________________..
49 ********************************************************************************/
50 require_once('include/database/DBHelper.php');
51
52 class MysqlHelper extends DBHelper
53 {
54     /**
55      * @see DBHelper::createTableSQL()
56      */
57     public function createTableSQL(
58         SugarBean $bean
59         )
60     {
61         $tablename = $bean->getTableName();
62         $fieldDefs = $bean->getFieldDefinitions();
63         $indices   = $bean->getIndices();
64         $engine    = $this->getEngine($bean);
65         return $this->createTableSQLParams($tablename, $fieldDefs, $indices, $engine);
66         }
67
68     /**
69      * Generates sql for create table statement for a bean.
70      *
71      * @param  string $tablename
72      * @param  array  $fieldDefs
73      * @param  array  $indices
74      * @param  string $engine optional, MySQL engine to use
75      * @return string SQL Create Table statement
76     */
77     public function createTableSQLParams(
78         $tablename,
79         $fieldDefs,
80         $indices,
81         $engine = null
82         )
83     {
84                 if ( empty($engine) && isset($fieldDefs['engine']))
85             $engine = $fieldDefs['engine'];
86         if ( !$this->isEngineEnabled($engine) )
87             $engine = '';
88
89         $sql = parent::createTableSQLParams($tablename,$fieldDefs,$indices);
90         if (!empty($engine))
91             $sql.= " ENGINE=$engine";
92
93         return $sql;
94         }
95
96     /**
97      * Returns the name of the engine to use or null if we are to use the default
98      *
99      * @param  object $bean SugarBean instance
100      * @return string
101      */
102     private function getEngine($bean)
103     {
104         global $dictionary;
105         $engine = null;
106         if (isset($dictionary[$bean->getObjectName()]['engine'])) {
107                         $engine = $dictionary[$bean->getObjectName()]['engine'];
108                 }
109         return $engine;
110     }
111
112     /**
113      * Returns true if the engine given is enabled in the backend
114      *
115      * @param  string $engine
116      * @return bool
117      */
118     private function isEngineEnabled(
119         $engine
120         )
121     {
122         $engine = strtoupper($engine);
123
124         $r = $this->db->query("SHOW ENGINES");
125
126         while ( $row = $this->db->fetchByAssoc($r) )
127             if ( strtoupper($row['Engine']) == $engine )
128                 return ($row['Support']=='YES' || $row['Support']=='DEFAULT');
129
130         return false;
131     }
132
133     /**
134      * @see DBHelper::getColumnType()
135      */
136     public function getColumnType(
137         $type,
138         $name = '',
139         $table = ''
140         )
141     {
142         $map = array(
143             'int'      => 'int',
144             'double'   => 'double',
145             'float'    => 'float',
146             'uint'     => 'int unsigned',
147             'ulong'    => 'bigint unsigned',
148             'long'     => 'bigint',
149             'short'    => 'smallint',
150             'varchar'  => 'varchar',
151             'text'     => 'text',
152             'longtext' => 'longtext',
153             'date'     => 'date',
154             'enum'     => 'varchar',
155             'relate'   => 'varchar',
156             'multienum'=> 'text',
157             'html'     => 'text',
158             'datetime' => 'datetime',
159             'datetimecombo' => 'datetime',
160             'time'     => 'time',
161             'bool'     => 'bool',
162             'tinyint'  => 'tinyint',
163             'char'     => 'char',
164             'blob'     => 'blob',
165             'longblob' => 'longblob',
166             'currency' => 'decimal(26,6)',
167             'decimal'  => 'decimal',
168             'decimal2' => 'decimal',
169             'id'       => 'char(36)',
170            'url'=>'varchar',
171            'encrypt'=>'varchar',
172            'file'      => 'varchar',
173             );
174
175         return $map[$type];
176     }
177
178     /**
179      * @see DBHelper::oneColumnSQLRep()
180      */
181         protected function oneColumnSQLRep(
182         $fieldDef,
183         $ignoreRequired = false,
184         $table = '',
185         $return_as_array = false
186         )
187     {
188         $ref = parent::oneColumnSQLRep($fieldDef, $ignoreRequired, $table, true);
189
190         if ( $ref['colType'] == 'int'
191                 && !empty($fieldDef['len']) )
192             $ref['colType'] .= "(".$fieldDef['len'].")";
193
194         // bug 22338 - don't set a default value on text or blob fields
195         if ( isset($ref['default']) &&
196             ($ref['colType'] == 'text' || $ref['colType'] == 'blob'
197                 || $ref['colType'] == 'longtext' || $ref['colType'] == 'longblob' ))
198             $ref['default'] = '';
199             
200         if ( $return_as_array )
201             return $ref;
202         else
203             return "{$ref['name']} {$ref['colType']} {$ref['default']} {$ref['required']} {$ref['auto_increment']}";
204     }
205
206     /**
207      * @see DBHelper::changeColumnSQL()
208      */
209     protected function changeColumnSQL(
210         $tablename,
211         $fieldDefs,
212         $action,
213         $ignoreRequired = false
214         )
215     {
216         if ($this->isFieldArray($fieldDefs)){
217             foreach ($fieldDefs as $def){
218                 if ($action == 'drop')
219                     $columns[] = $def['name'];
220                 else
221                 $columns[] = $this->oneColumnSQLRep($def, $ignoreRequired);
222             }
223         }else{
224             if ($action == 'drop')
225                 $columns[] = $fieldDefs['name'];
226         else
227             $columns[] = $this->oneColumnSQLRep($fieldDefs);
228         }
229
230         return "alter table $tablename $action column ".implode(",$action column ", $columns);
231     }
232
233     /**
234      * @see DBHelper::deleteColumnSQL()
235      */
236     public function deleteColumnSQL(
237         SugarBean $bean,
238         $fieldDefs
239         )
240     {
241         if ($this->isFieldArray($fieldDefs))
242             foreach ($fieldDefs as $fieldDef)
243                 $columns[] = $fieldDef['name'];
244         else
245             $columns[] = $fieldDefs['name'];
246
247         return "alter table ".$bean->getTableName()." drop column ".implode(", drop column ", $columns);
248     }
249
250     /**
251      * @see DBHelper::keysSQL
252      */
253     public function keysSQL(
254         $indices,
255         $alter_table = false,
256         $alter_action = ''
257         )
258         {
259        // check if the passed value is an array of fields.
260        // if not, convert it into an array
261        if (!$this->isFieldArray($indices))
262            $indices[] = $indices;
263
264        $columns = array();
265        foreach ($indices as $index) {
266            if(!empty($index['db']) && $index['db'] != 'mysql')
267                continue;
268            if (isset($index['source']) && $index['source'] != 'db')
269                continue;
270            
271            $type = $index['type'];
272            $name = $index['name'];
273
274            if (is_array($index['fields']))
275                $fields = implode(", ", $index['fields']);
276            else
277                $fields = $index['fields'];
278
279            switch ($type) {
280            case 'unique':
281                $columns[] = " UNIQUE $name ($fields)";
282                break;
283            case 'primary':
284                $columns[] = " PRIMARY KEY ($fields)";
285                break;
286            case 'index':
287            case 'foreign':
288            case 'clustered':
289            case 'alternate_key':
290                /**
291                 * @todo here it is assumed that the primary key of the foreign
292                 * table will always be named 'id'. It must be noted though
293                 * that this can easily be fixed by referring to db dictionary
294                 * to find the correct primary field name
295                 */
296                if ( $alter_table )
297                    $columns[] = " INDEX $name ($fields)";
298                else
299                    $columns[] = " KEY $name ($fields)";
300                break;
301            case 'fulltext':
302                if ($this->full_text_indexing_enabled())
303                    $columns[] = " FULLTEXT ($fields)";
304                else
305                    $GLOBALS['log']->debug('MYISAM engine is not available/enabled, full-text indexes will be skipped. Skipping:',$name);
306                break;
307           }
308        }
309        $columns = implode(", $alter_action ", $columns);
310        if(!empty($alter_action)){
311            $columns = $alter_action . ' '. $columns;
312        }
313        return $columns;
314     }
315
316     /**
317      * @see DBHelper::setAutoIncrement()
318      */
319         protected function setAutoIncrement(
320         $table,
321         $field_name
322         )
323     {
324                 return "auto_increment";
325         }
326
327         /**
328      * Sets the next auto-increment value of a column to a specific value.
329      *
330      * @param  string $table tablename
331      * @param  string $field_name
332      */
333     public function setAutoIncrementStart(
334         $table,
335         $field_name,
336         $start_value
337         )
338     {
339         $this->db->query( "ALTER TABLE $table AUTO_INCREMENT = $start_value;");
340
341         return true;
342     }
343
344     /**
345      * Returns the next value for an auto increment
346      *
347      * @param  string $table tablename
348      * @param  string $field_name
349      * @return string
350      */
351     public function getAutoIncrement(
352         $table,
353         $field_name
354         )
355     {
356
357         $result = $this->db->query("SHOW TABLE STATUS LIKE '$table'");
358         $row = $this->db->fetchByAssoc($result);
359         if (!empty($row['Auto_increment']))
360             return $row['Auto_increment'];
361
362         return "";
363     }
364
365         /**
366      * @see DBHelper::get_indices()
367      */
368     public function get_indices(
369         $tablename
370         )
371     {
372         //find all unique indexes and primary keys.
373         $result = $this->db->query("SHOW INDEX FROM $tablename");
374
375         $indices = array();
376         while (($row=$this->db->fetchByAssoc($result)) !=null) {
377             $index_type='index';
378             if ($row['Key_name'] =='PRIMARY') {
379                 $index_type='primary';
380             }
381             elseif ( $row['Non_unique'] == '0' ) {
382                 $index_type='unique';
383             }
384             $name = strtolower($row['Key_name']);
385             $indices[$name]['name']=$name;
386             $indices[$name]['type']=$index_type;
387             $indices[$name]['fields'][]=strtolower($row['Column_name']);
388         }
389         return $indices;
390     }
391
392         /**
393      * @see DBHelper::get_columns()
394      */
395     public function get_columns(
396         $tablename
397         )
398     {
399         //find all unique indexes and primary keys.
400         $result = $this->db->query("DESCRIBE $tablename");
401
402         $columns = array();
403         while (($row=$this->db->fetchByAssoc($result)) !=null) {
404             $name = strtolower($row['Field']);
405             $columns[$name]['name']=$name;
406             $matches = array();
407             preg_match_all("/(\w+)(?:\(([0-9]+,?[0-9]*)\)|)( unsigned)?/i", $row['Type'], $matches);
408             $columns[$name]['type']=strtolower($matches[1][0]);
409             if ( isset($matches[2][0]) && in_array(strtolower($matches[1][0]),array('varchar','char','varchar2','int','decimal','float')) )
410                 $columns[$name]['len']=strtolower($matches[2][0]);
411             if ( stristr($row['Extra'],'auto_increment') )
412                 $columns[$name]['auto_increment'] = '1';
413             if ($row['Null'] == 'NO' && !stristr($row['Key'],'PRI'))
414                 $columns[$name]['required'] = 'true';
415             if (!empty($row['Default']) )
416                 $columns[$name]['default'] = $row['Default'];
417         }
418         return $columns;
419     }
420
421     /**
422      * @see DBHelper::add_drop_constraint()
423      */
424     public function add_drop_constraint(
425         $table,
426         $definition,
427         $drop = false
428         )
429     {
430         $type         = $definition['type'];
431         $fields       = implode(',',$definition['fields']);
432         $name         = $definition['name'];
433         $foreignTable = isset($definition['foreignTable']) ? $definition['foreignTable'] : array();
434         $sql          = '';
435
436         switch ($type){
437         // generic indices
438         case 'index':
439         case 'alternate_key':
440             if ($drop)
441                 $sql = "DROP INDEX {$name} ";
442             else
443                 $sql = "CREATE INDEX {$name} ON {$table} ({$fields})";
444             break;
445         // constraints as indices
446         case 'unique':
447             if ($drop)
448                 $sql = "ALTER TABLE {$table} DROP INDEX $name";
449             else
450                 $sql = "ALTER TABLE {$table} ADD CONSTRAINT UNIQUE {$name} ({$fields})";
451             break;
452         case 'primary':
453             if ($drop)
454                 $sql = "ALTER TABLE {$table} DROP PRIMARY KEY";
455             else
456                 $sql = "ALTER TABLE {$table} ADD CONSTRAINT PRIMARY KEY ({$fields})";
457             break;
458         case 'foreign':
459             if ($drop)
460                 $sql = "ALTER TABLE {$table} DROP FOREIGN KEY ({$fields})";
461             else
462                 $sql = "ALTER TABLE {$table} ADD CONSTRAINT FOREIGN KEY {$name} ({$fields}) REFERENCES {$foreignTable}({$foreignfields})";
463             break;
464         }
465         return $sql;
466     }
467
468     /**
469      * @see DBHelper::number_of_columns()
470      */
471     public function number_of_columns(
472         $table_name
473         )
474     {
475         $result = $this->db->query("DESCRIBE $table_name");
476
477         return ($this->db->getRowCount($result));
478     }
479
480         /**
481      * @see DBHelper::full_text_indexing_enabled()
482      */
483     protected function full_text_indexing_enabled(
484         $dbname = null
485         )
486     {
487                 return $this->isEngineEnabled('MyISAM');
488         }
489
490     /**
491      * @see DBHelper::massageFieldDef()
492      */
493     public function massageFieldDef(
494         &$fieldDef,
495         $tablename
496         )
497     {
498         DBHelper::massageFieldDef($fieldDef,$tablename);
499
500         if ( isset($fieldDef['default']) &&
501             ($fieldDef['dbType'] == 'text'
502                 || $fieldDef['dbType'] == 'blob'
503                 || $fieldDef['dbType'] == 'longtext'
504                 || $fieldDef['dbType'] == 'longblob' ))
505             unset($fieldDef['default']);
506         if ($fieldDef['dbType'] == 'uint')
507             $fieldDef['len'] = '10';
508         if ($fieldDef['dbType'] == 'ulong')
509             $fieldDef['len'] = '20';
510         if ($fieldDef['dbType'] == 'bool')
511             $fieldDef['type'] = 'tinyint';
512         if ($fieldDef['dbType'] == 'bool' && empty($fieldDef['default']) )
513             $fieldDef['default'] = '0';
514         if (($fieldDef['dbType'] == 'varchar' || $fieldDef['dbType'] == 'enum') && empty($fieldDef['len']) )
515             $fieldDef['len'] = '255';
516         if ($fieldDef['dbType'] == 'uint')
517             $fieldDef['len'] = '10';
518         if ($fieldDef['dbType'] == 'int' && empty($fieldDef['len']) )
519             $fieldDef['len'] = '11';
520     }
521 }
522 ?>