]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - include/database/DBManager.php
Release 6.1.4
[Github/sugarcrm.git] / include / database / DBManager.php
1 <?php
2 if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
3 /*********************************************************************************
4  * SugarCRM 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
93
94 abstract class DBManager
95 {
96     /**
97      * DBHelper object instance for this class
98      */
99     public $helper;
100
101     /**
102      * Name of database table we are dealing with
103      */
104     protected $tableName;
105
106     /**
107      * Name of database
108      */
109     public $database = null;
110
111     /**
112      * Indicates whether we should die when we get an error from the DB
113      */
114     protected $dieOnError = false;
115
116     /**
117      * Indicates whether we should html encode the results from a query by default
118      */
119     protected $encode = true;
120
121     /**
122      * Records the execution time of the last query
123      */
124     protected $query_time = 0;
125
126     /**
127      * Number of the last row fetched from the query result set
128      */
129     protected $lastmysqlrow = -1;
130
131     /**
132      * Last error message from the DB backend
133      */
134     protected $last_error = '';
135
136     /**
137      * Registry of available result sets
138      */
139     protected $lastResult = array();
140
141     /**
142      * Current query count
143      */
144     private static $queryCount = 0;
145
146     /**
147      * Query threshold limit
148      */
149     private static $queryLimit = 0;
150
151     /**
152      * Array of common backend functions and what the PHP they map to is
153      */
154     protected $backendFunctions = array();
155
156     /**
157      * Array of prepared statements and their correspoding parsed tokens
158      */
159     protected $preparedTokens = array();
160
161     /**
162      * Wrapper for those trying to access the private and protected class members directly
163      */
164     public function __get($p)
165     {
166         $GLOBALS['log']->info('call to DBManagerFactory::$'.$p.' is deprecated');
167         return $this->$p;
168     }
169
170     public function __construct()
171     {
172     }
173
174     /**
175      * Returns the current tablename
176      *
177      * @return string
178      */
179     public function getTableName()
180     {
181         return $this->tableName;
182     }
183
184     /**
185      * Returns the current database handle
186      *
187      * @return resource
188      */
189     public function getDatabase()
190     {
191         $this->checkConnection();
192         return $this->database;
193     }
194
195     /**
196      * Returns this instance's DBHelper
197      *
198      * @return object DBHelper instance
199      */
200     public function getHelper()
201     {
202         if ( !($this->helper instanceof DBHelper) ) {
203             global $sugar_config;
204
205             switch ( $sugar_config['dbconfig']['db_type'] ) {
206             case "mysql":
207                 $my_db_helper = 'MysqlHelper';
208                 if ( (!isset($sugar_config['mysqli_disabled'])
209                             || $sugar_config['mysqli_disabled'] == false)
210                         && function_exists('mysqli_connect') )
211                     $my_db_helper = 'MysqliHelper';
212                 break;
213             case "mssql":
214                 if ( function_exists('sqlsrv_connect')
215                         && (empty($config['db_mssql_force_driver']) || $config['db_mssql_force_driver'] == 'sqlsrv' ))
216                     $my_db_helper = 'SqlsrvHelper';
217                 elseif (is_freetds()
218                         && (empty($config['db_mssql_force_driver']) || $config['db_mssql_force_driver'] == 'freetds' ))
219                     $my_db_helper = 'FreeTDSHelper';
220                 else
221                     $my_db_helper = 'MssqlHelper';
222                 break;
223             default:
224                 $my_db_helper = 'MysqlHelper';
225             }
226             $GLOBALS['log']->info("using $my_db_helper DBHelper backend");
227             require_once("include/database/{$my_db_helper}.php");
228             $this->helper = new $my_db_helper();
229             $this->helper->db = $this;
230         }
231
232         return $this->helper;
233     }
234
235     /**
236      * Checks for database not being connected
237      *
238      * @param  string $msg        message to prepend to the error message
239      * @param  bool   $dieOnError true if we want to die immediately on error
240      * @return bool
241      */
242     public function checkError(
243         $msg = '',
244         $dieOnError = false)
245     {
246         $userMsg = inDeveloperMode()?"$msg: ":"";
247
248         if (!isset($this->database)) {
249             $GLOBALS['log']->error("Database Is Not Connected");
250             if($this->dieOnError || $dieOnError)
251                 sugar_die ($userMsg."Database Is Not Connected");
252             else
253                 $this->last_error = $userMsg."Database Is Not Connected";
254             return true;
255         }
256         return false;
257     }
258
259     /**
260      * This method is called by every method that runs a query.
261      * If slow query dumping is turned on and the query time is beyond
262      * the time limit, we will log the query. This function may do
263      * additional reporting or log in a different area in the future.
264      *
265      * @param  string  $query query to log
266      * @return boolean true if the query was logged, false otherwise
267      */
268     protected function dump_slow_queries(
269         $query
270         )
271     {
272         global $sugar_config;
273
274         $do_the_dump = isset($sugar_config['dump_slow_queries'])
275             ? $sugar_config['dump_slow_queries'] : false;
276         $slow_query_time_msec = isset($sugar_config['slow_query_time_msec'])
277             ? $sugar_config['slow_query_time_msec'] : 5000;
278
279         if($do_the_dump) {
280             if($slow_query_time_msec < ($this->query_time * 1000)) {
281                 // Then log both the query and the query time
282                 $GLOBALS['log']->fatal('Slow Query (time:'.$this->query_time."\n".$query);
283                 return true;
284             }
285         }
286         return false;
287     }
288
289    /**
290     * Scans order by to ensure that any field being ordered by is.
291     *
292     * It will throw a warning error to the log file - fatal if slow query logging is enabled
293     *
294     * @param  string $sql         query to be run
295     * @param  bool   $object_name optional, object to look up indices in
296     * @return bool   true if an index is found false otherwise
297     */
298    protected function checkQuery(
299        $sql,
300        $object_name = false
301        )
302    {
303        $match = array();
304        preg_match_all("'.* FROM ([^ ]*).* ORDER BY (.*)'is", $sql, $match);
305        $indices = false;
306        if (!empty($match[1][0]))
307            $table = $match[1][0];
308        else
309            return false;
310
311        if (!empty($object_name) && !empty($GLOBALS['dictionary'][$object_name]))
312            $indices = $GLOBALS['dictionary'][$object_name]['indices'];
313
314        if (empty($indices)) {
315            foreach ( $GLOBALS['dictionary'] as $current ) {
316                if ($current['table'] == $table){
317                    $indices = $current['indices'];
318                    break;
319                }
320            }
321        }
322        if (empty($indices)) {
323            $GLOBALS['log']->warn('CHECK QUERY: Could not find index definitions for table ' . $table);
324            return false;
325        }
326        if (!empty($match[2][0])) {
327            $orderBys = explode(' ', $match[2][0]);
328            foreach ($orderBys as $orderBy){
329                $orderBy = trim($orderBy);
330                if (empty($orderBy))
331                    continue;
332                $orderBy = strtolower($orderBy);
333                if ($orderBy == 'asc' || $orderBy == 'desc')
334                    continue;
335
336                $orderBy = str_replace(array($table . '.', ','), '', $orderBy);
337
338                foreach ($indices as $index)
339                    if (empty($index['db']) || $index['db'] == $this->dbType)
340                        foreach ($index['fields'] as $field)
341                            if ($field == $orderBy)
342                                return true;
343
344                $warning = 'Missing Index For Order By Table: ' . $table . ' Order By:' . $orderBy ;
345                if (!empty($GLOBALS['sugar_config']['dump_slow_queries']))
346                    $GLOBALS['log']->fatal('CHECK QUERY:' .$warning);
347                else
348                    $GLOBALS['log']->warn('CHECK QUERY:' .$warning);
349
350            }
351        }
352        return false;
353     }
354
355     /**
356      * Returns the time the last query took to execute
357      *
358      * @return int
359      */
360     public function getQueryTime()
361     {
362         return $this->query_time;
363     }
364
365     /**
366      * Checks the current connection; if it is not connected then reconnect
367      */
368     public function checkConnection()
369     {
370         $this->last_error = '';
371         if (!isset($this->database))
372             $this->connect();
373     }
374
375     /**
376      * Sets the dieOnError value
377      *
378      * @param bool $value
379      */
380     public function setDieOnError(
381         $value
382         )
383     {
384         $this->dieOnError = $value;
385     }
386
387     /**
388          * Implements a generic insert for any bean.
389          *
390          * @param object $bean SugarBean instance
391          */
392     public function insert(
393         SugarBean $bean
394         )
395     {
396         $sql = $this->getHelper()->insertSQL($bean);
397         $this->tableName = $bean->getTableName();
398         $msg = "Error inserting into table: ".$this->tableName;
399         $this->query($sql,true,$msg);
400     }
401
402     /**
403      * Implements a generic update for any bean
404      *
405      * @param object $bean  Sugarbean instance
406      * @param array  $where values with the keys as names of fields.
407      * If we want to pass multiple values for a name, pass it as an array
408      * If where is not passed, it defaults to id of table
409      */
410     public function update(
411         SugarBean $bean,
412         array $where = array()
413         )
414     {
415         $sql = $this->getHelper()->updateSQL($bean, $where);
416         $this->tableName = $bean->getTableName();
417         $msg = "Error updating table: ".$this->tableName. ":";
418         $this->query($sql,true,$msg);
419     }
420
421     /**
422          * Implements a generic delete for any bean identified by id
423      *
424      * @param object $bean  Sugarbean instance
425      * @param array  $where values with the keys as names of fields.
426          * If we want to pass multiple values for a name, pass it as an array
427          * If where is not passed, it defaults to id of table
428          */
429     public function delete(
430         SugarBean $bean,
431         array $where = array()
432         )
433     {
434         $sql = $this->getHelper()->deleteSQL($bean, $where);
435         $this->tableName = $bean->getTableName();
436         $msg = "Error deleting from table: ".$this->tableName. ":";
437         $this->query($sql,true,$msg);
438     }
439
440     /**
441      * Implements a generic retrieve for any bean identified by id
442      *
443      * If we want to pass multiple values for a name, pass it as an array
444      * If where is not passed, it defaults to id of table
445      *
446      * @param  object   $bean  Sugarbean instance
447      * @param  array    $where values with the keys as names of fields.
448      * @return resource result from the query
449      */
450     public function retrieve(
451         SugarBean $bean,
452         array $where = array()
453         )
454     {
455         $sql = $this->getHelper()->retrieveSQL($bean, $where);
456         $this->tableName = $bean->getTableName();
457         $msg = "Error retriving values from table:".$this->tableName. ":";
458         return $this->query($sql,true,$msg);
459     }
460
461     /**
462      * Implements a generic retrieve for a collection of beans.
463      *
464      * These beans will be joined in the sql by the key attribute of field defs.
465      * Currently, this function does support outer joins.
466      *
467      * @param  array $beans Sugarbean instance(s)
468      * @param  array $cols  columns to be returned with the keys as names of bean as identified by
469      * get_class of bean. Values of this array is the array of fieldDefs to be returned for a bean.
470      * If an empty array is passed, all columns are selected.
471      * @param  array $where  values with the keys as names of bean as identified by get_class of bean
472      * Each value at the first level is an array of values for that bean identified by name of fields.
473      * If we want to pass multiple values for a name, pass it as an array
474      * If where is not passed, all the rows will be returned.
475      * @return resource
476      */
477     public function retrieveView(
478         array $beans,
479         array $cols = array(),
480         array $where = array()
481         )
482     {
483         $sql = $this->getHelper()->retrieveViewSQL($beans, $cols, $where);
484         $this->tableName = "View Collection"; // just use this string for msg
485         $msg = "Error retriving values from table:".$this->tableName. ":";
486         $this->query($sql,true,$msg);
487     }
488
489
490     /**
491          * Implements creation of a db table for a bean.
492          *
493      * @param object $bean  Sugarbean instance
494      */
495     public function createTable(
496         SugarBean $bean
497         )
498     {
499         $sql = $this->getHelper()->createTableSQL($bean);
500         $this->tableName = $bean->getTableName();
501         $msg = "Error creating table: ".$this->tableName. ":";
502         $this->query($sql,true,$msg);
503     }
504
505     /**
506      * Implements creation of a db table
507      *
508      * @param string $tablename
509      * @param array  $fieldDefs
510      * @param array  $indices
511      * @param string $engine    MySQL engine to use
512      */
513     public function createTableParams(
514         $tablename,
515         $fieldDefs,
516         $indices,
517         $engine = null
518         )
519     {
520         if (!empty($fieldDefs)) {
521             $sql = $this->getHelper()
522                         ->createTableSQLParams($tablename, $fieldDefs, $indices,$engine);
523             $this->tableName = $tablename;
524             if ($sql) {
525                 $msg = "Error creating table: ".$this->tableName. ":";
526                 $this->query($sql,true,$msg);
527             }
528         }
529     }
530
531     /**
532          * Implements repair of a db table for a bean.
533          *
534          * @param  object $bean    SugarBean instance
535      * @param  bool   $execute true if we want the action to take place, false if we just want the sql returned
536          * @return string SQL statement or empty string, depending upon $execute
537          */
538     public function repairTable(SugarBean $bean, $execute = true)
539     {
540         $indices   = $bean->getIndices();
541         $fielddefs = $bean->getFieldDefinitions();
542         $tablename = $bean->getTableName();
543
544                 //Clean the indicies to prevent duplicate definitions
545                 $new_Indecies = array();
546                 foreach($indices as $ind_def){
547                         $new_Indecies[$ind_def['name']] = $ind_def;
548                 }
549                 //jc: added this for beans that do not actually have a table, namely
550                 //ForecastOpportunities
551         if($tablename == 'does_not_exist' || $tablename == '')
552                 return '';
553
554         global $dictionary;
555         $engine=null;
556         if (isset($dictionary[$bean->getObjectName()]['engine']) && !empty($dictionary[$bean->getObjectName()]['engine']) )
557             $engine = $dictionary[$bean->getObjectName()]['engine'];
558
559         return $this->repairTableParams($tablename, $fielddefs,$new_Indecies,$execute,$engine);
560     }
561
562     /**
563      * Builds the SQL commands that repair a table structure
564      *
565      * @param  string $tablename
566      * @param  array  $fielddefs
567      * @param  array  $indices
568      * @param  bool   $execute   optional, true if we want the queries executed instead of returned
569      * @param  string $engine    optional, MySQL engine
570      */
571     public function repairTableParams(
572         $tablename,
573         $fielddefs,
574         $indices,
575         $execute = true,
576         $engine = null
577         )
578     {
579         global $table_descriptions;
580
581                 //jc: had a bug when running the repair if the tablename is blank the repair will
582                 //fail when it tries to create a repair table
583         if ($tablename == '')
584             return '';
585         if (empty($fielddefs))
586             return '';
587
588         //if the table does not exist create it and we are done
589         $sql = "/* Table : $tablename */\n";
590         if (!$this->tableExists($tablename)){
591
592             $createtablesql = $this->getHelper()
593                                     ->createTableSQLParams($tablename,$fielddefs,$indices,$engine);
594             if($execute && $createtablesql){
595                 $this->createTableParams($tablename,$fielddefs,$indices,$engine);
596             }
597
598             $sql .= "/* MISSING TABLE: {$tablename} */\n";
599             $sql .= $createtablesql . "\n";
600             return $sql;
601         }
602
603         $compareFieldDefs = $this->getHelper()->get_columns($tablename);
604         $compareIndices = $this->getHelper()->get_indices($tablename);
605
606         $take_action = false;
607
608         // do column comparisions
609         $sql .= "/*COLUMNS*/\n";
610         foreach ($fielddefs as $value) {
611             if (isset($value['source']) && $value['source'] != 'db')
612                 continue;
613
614             $name = $value['name'];
615             // add or fix the field defs per what the DB is expected to give us back
616             $this->getHelper()->massageFieldDef($value,$tablename);
617
618             $ignorerequired=false;
619
620                         //Do not track requiredness in the DB, auto_increment, ID, and deleted fields are always required in the DB, so don't force those
621             if (empty($value['auto_increment']) && (empty($value['type']) || $value['type'] != 'id')
622                     && (empty($value['dbType']) || $value['dbType'] != 'id')
623                                         && (empty($value['name']) || ($value['name'] != 'id' && $value['name'] != 'deleted'))
624                         ){
625                             $value['required'] = false;
626                         }
627                         //Should match the conditions in DBHelper::oneColumnSQLRep for DB required fields, type='id' fields will sometimes
628                         //come into this function as 'type' = 'char', 'dbType' = 'id' without required set in $value. Assume they are correct and leave them alone.
629                         else if (($name == 'id' || $value['type'] == 'id' || (isset($value['dbType']) && $value['dbType'] == 'id'))
630                 && (!isset($value['required']) && isset($compareFieldDefs[$name]['required'])))
631                         {
632                                 $value['required'] = $compareFieldDefs[$name]['required'];
633                         }
634
635             if ( !isset($compareFieldDefs[$name]) ) {
636                 // ok we need this field lets create it
637                 $sql .= "/*MISSING IN DATABASE - $name -  ROW*/\n";
638                 $sql .= $this->getHelper()->addColumnSQL($tablename, $value) .  "\n";
639                 if ($execute)
640                     $this->addColumn($tablename, $value);
641                 $take_action = true;
642             }
643             elseif ( !$this->compareVarDefs($compareFieldDefs[$name],$value)) {
644                 //fields are different lets alter it
645                 $sql .= "/*MISMATCH WITH DATABASE - $name -  ROW ";
646                 foreach($compareFieldDefs[$name] as $rKey => $rValue)
647                     $sql .=     "[$rKey] => '$rValue'  ";
648                 $sql .= "*/\n";
649                 $sql .= "/* VARDEF - $name -  ROW";
650                 foreach($value as $rKey => $rValue)
651                     $sql .=     "[$rKey] => '$rValue'  ";
652                 $sql .= "*/\n";
653
654                 //jc: oracle will complain if you try to execute a statement that sets a column to (not) null
655                 //when it is already (not) null
656                 if ( isset($value['isnull']) && isset($compareFieldDefs[$name]['isnull']) ) {
657                     if ($value['isnull'] === $compareFieldDefs[$name]['isnull']) {
658                         unset($value['required']);
659                         $ignorerequired=true;
660                     }
661                 }
662
663                 //dwheeler: Once a column has been defined as null, we cannot try to force it back to !null
664                 if ((isset($value['required']) && ($value['required'] === true || $value['required'] == 'true' || $value['required'] === 1))
665                                     && (empty($compareFieldDefs[$name]['required']) || $compareFieldDefs[$name]['required'] != 'true'))
666                             {
667                                     $ignorerequired = true;
668                             }
669
670                 $sql .= $this->getHelper()->alterColumnSQL($tablename, $value,$ignorerequired) .  "\n";
671                 if($execute){
672                     $this->alterColumn($tablename, $value,$ignorerequired);
673                 }
674                 $take_action = true;
675             }
676         }
677
678         // do index comparisions
679         $sql .= "/* INDEXES */\n";
680         $correctedIndexs = array();
681         foreach ($indices as $value) {
682             if (isset($value['source']) && $value['source'] != 'db')
683                 continue;
684
685             $name = $value['name'];
686
687                         //Don't attempt to fix the same index twice in one pass;
688                         if (isset($correctedIndexs[$name]))
689                                 continue;
690
691             //don't bother checking primary nothing we can do about them
692             if (isset($value['type']) && $value['type'] == 'primary')
693                 continue;
694
695             //database helpers do not know how to handle full text indices
696             if ($value['type']=='fulltext')
697                 continue;
698
699             if ( in_array($value['type'],array('alternate_key','foreign')) )
700                 $value['type'] = 'index';
701
702             if ( !isset($compareIndices[$name]) ) {
703                 // ok we need this field lets create it
704                 $sql .=  "/*MISSING INDEX IN DATABASE - $name -{$value['type']}  ROW */\n";
705                 $sql .= $this->addIndexes($tablename,array($value), $execute) .  "\n";
706                 $take_action = true;
707                                 $correctedIndexs[$name] = true;
708             }
709             elseif ( !$this->compareVarDefs($compareIndices[$name],$value) ) {
710                 // fields are different lets alter it
711                 $sql .= "/*INDEX MISMATCH WITH DATABASE - $name -  ROW ";
712                 foreach ($compareIndices[$name] as $n1 => $t1) {
713                     $sql .=      "<$n1>";
714                     if ( $n1 == 'fields' )
715                         foreach($t1 as $rKey => $rValue)
716                             $sql .= "[$rKey] => '$rValue'  ";
717                     else
718                         $sql .= " $t1 ";
719                 }
720                 $sql .= "*/\n";
721                 $sql .= "/* VARDEF - $name -  ROW";
722                 foreach ($value as $n1 => $t1) {
723                     $sql .=     "<$n1>";
724                     if ( $n1 == 'fields' )
725                         foreach ($t1 as $rKey => $rValue)
726                             $sql .=     "[$rKey] => '$rValue'  ";
727                     else
728                         $sql .= " $t1 ";
729                 }
730                 $sql .= "*/\n";
731                 $sql .= $this->modifyIndexes($tablename,array($value), $execute) .  "\n";
732                 $take_action = true;
733                                 $correctedIndexs[$name] = true;
734             }
735         }
736
737         return ($take_action === true) ? $sql : "";
738     }
739
740     /**
741      * Compares two vardefs
742      *
743      * @param  array  $fielddef1
744      * @param  array  $fielddef2
745      * @return bool   true if they match, false if they don't
746      */
747     public function compareVarDefs(
748         $fielddef1,
749         $fielddef2
750         )
751     {
752         foreach ( $fielddef1 as $key => $value ) {
753             if ( $key == 'name' && ( strtolower($fielddef1[$key]) == strtolower($fielddef2[$key]) ) )
754                 continue;
755             if ( isset($fielddef2[$key]) && $fielddef1[$key] == $fielddef2[$key] )
756                 continue;
757             return false;
758         }
759
760         return true;
761     }
762
763     /**
764      * Compare a field in two tables
765      *
766      * @param  string $name   field name
767      * @param  string $table1
768      * @param  string $table2
769      * @return array  array with keys 'msg','table1','table2'
770      */
771     public function compareFieldInTables(
772         $name,
773         $table1,
774         $table2
775         )
776     {
777         $row1 = $this->describeField($name, $table1);
778         $row2 = $this->describeField($name, $table2);
779         $returnArray = array(
780             'table1' => $row1,
781             'table2' => $row2,
782             'msg'    => 'error',
783             );
784
785         $ignore_filter = array('Key'=>1);
786         if ($row1) {
787             if (!$row2) {
788                 // Exists on table1 but not table2
789                 $returnArray['msg'] = 'not_exists_table2';
790             }
791             else {
792                 if (sizeof($row1) != sizeof($row2)) {
793                     $returnArray['msg'] = 'no_match';
794                 }
795                 else {
796                     $returnArray['msg'] = 'match';
797                     foreach($row1 as $key => $value){
798                         //ignore keys when checking we will check them when we do the index check
799                         if( !isset($ignore_filter[$key]) && $row1[$key] !== $row2[$key]){
800                             $returnArray['msg'] = 'no_match';
801                         }
802                     }
803                 }
804             }
805         }
806         else {
807             $returnArray['msg'] = 'not_exists_table1';
808         }
809
810         return $returnArray;
811     }
812
813     /**
814      * Compare an index in two different tables
815      *
816      * @param  string $name   index name
817      * @param  string $table1
818      * @param  string $table2
819      * @return array  array with keys 'msg','table1','table2'
820      */
821     public function compareIndexInTables(
822         $name,
823         $table1,
824         $table2
825         )
826     {
827         $row1 = $this->describeIndex($name, $table1);
828         $row2 = $this->describeIndex($name, $table2);
829         $returnArray = array(
830             'table1' => $row1,
831             'table2' => $row2,
832             'msg'    => 'error',
833             );
834         $ignore_filter = array('Table'=>1, 'Seq_in_index'=>1,'Cardinality'=>1, 'Sub_part'=>1, 'Packed'=>1, 'Comment'=>1);
835
836         if ($row1) {
837             if (!$row2) {
838                 //Exists on table1 but not table2
839                 $returnArray['msg'] = 'not_exists_table2';
840             }
841             else {
842                 if (sizeof($row1) != sizeof($row2)) {
843                     $returnArray['msg'] = 'no_match';
844                 }
845                 else {
846                     $returnArray['msg'] = 'match';
847                     foreach ($row1 as $fname => $fvalue) {
848                         if (!isset($row2[$fname])) {
849                             $returnArray['msg'] = 'no_match';
850                         }
851                         foreach($fvalue as $key => $value) {
852                             //ignore keys when checking we will check them when we do the index check
853                             if(!isset($ignore_filter[$key]) && $row1[$fname][$key] != $row2[$fname][$key]){
854                                 $returnArray['msg'] = 'no_match';
855                             }
856                         }
857                     }
858                 }
859             }
860         }
861         else {
862             $returnArray['msg'] = 'not_exists_table1';
863         }
864
865         return $returnArray;
866     }
867
868
869     /**
870          * Creates an index identified by name on the given fields.
871          *
872      * @param object $bean      SugarBean instance
873      * @param array  $fieldDefs
874      * @param string $name      index name
875      * @param bool   $unique    optional, true if we want to create an unique index
876          */
877     public function createIndex(
878         SugarBean $bean,
879         $fieldDefs,
880         $name,
881         $unique = true
882         )
883     {
884         $sql = $this->getHelper()->createIndexSQL($bean, $fieldDefs, $name, $unique);
885         $this->tableName = $bean->getTableName();
886         $msg = "Error creating index $name on table: ".$this->tableName. ":";
887         $this->query($sql,true,$msg);
888     }
889
890     /**
891      * Adds a new indexes
892      *
893      * @param  string $tablename
894      * @param  array  $indexes   indexes to add
895      * @param  bool   $execute   true if we want to execute the returned sql statement
896      * @return string SQL statement
897      */
898     public function addIndexes(
899         $tablename,
900         $indexes,
901         $execute = true
902         )
903     {
904         $alters = $this->getHelper()->keysSQL($indexes,true,'ADD');
905         $sql = "ALTER TABLE $tablename $alters";
906         if ($execute)
907             $this->query($sql);
908         return $sql;
909     }
910
911     /**
912      * Drops indexes
913      *
914      * @param  string $tablename
915      * @param  array  $indexes   indexes to drop
916      * @param  bool   $execute   true if we want to execute the returned sql statement
917      * @return string SQL statement
918      */
919     public function dropIndexes(
920         $tablename,
921         $indexes,
922         $execute = true
923         )
924     {
925         $sql = '';
926         foreach ($indexes as $index) {
927             $name =$index['name'];
928             if($execute)
929                 unset($GLOBALS['table_descriptions'][$tablename]['indexes'][$name]);
930             if ($index['type'] == 'primary')
931                 $name = 'PRIMARY KEY';
932             else
933                 $name = "INDEX $name";
934             if (empty($sql))
935                 $sql .= " DROP $name ";
936             else
937                 $sql .= ", DROP $name ";
938         }
939         if (!empty($sql)) {
940             $sql = "ALTER TABLE $tablename $sql";
941             if($execute)
942                 $this->query($sql);
943         }
944         return $sql;
945     }
946
947     /**
948      * Modifies indexes
949      *
950      * @param  string $tablename
951      * @param  array  $indexes   indexes to modify
952      * @param  bool   $execute   true if we want to execute the returned sql statement
953      * @return string SQL statement
954      */
955     public function modifyIndexes(
956         $tablename,
957         $indexes,
958         $execute = true
959         )
960     {
961         return $this->dropIndexes($tablename, $indexes, $execute)."\n".
962             $this->addIndexes($tablename, $indexes, $execute);
963     }
964
965     /**
966          * Adds a column to table identified by field def.
967          *
968          * @param string $tablename
969          * @param array  $fieldDefs
970          */
971     public function addColumn(
972         $tablename,
973         $fieldDefs
974         )
975     {
976         $this->tableName = $tablename;
977         $sql = $this->getHelper()->addColumnSQL($this->tableName, $fieldDefs);
978         if ($this->getHelper()->isFieldArray($fieldDefs)){
979             foreach ($fieldDefs as $fieldDef) $columns[] = $fieldDef['name'];
980             $columns = implode(",", $columns);
981         }
982         else
983             $columns = $fieldDefs['name'];
984
985         $msg = "Error adding column(s) ".$columns." on table: ".$this->tableName. ":";
986         $this->query($sql,true,$msg);
987     }
988
989     /**
990          * Alters old column identified by oldFieldDef to new fieldDef.
991          *
992          * @param string $tablename
993      * @param array  $newFieldDef
994      * @param bool   $ignoreRequired optional, true if we are ignoring this being a required field
995          */
996     public function alterColumn(
997         $tablename,
998         $newFieldDef,
999         $ignoreRequired = false
1000         )
1001     {
1002         $this->tableName = $tablename;
1003         $sql = $this->getHelper()->alterColumnSQL($this->tableName, $newFieldDef,$ignoreRequired);
1004         if ($this->getHelper()->isFieldArray($newFieldDef)){
1005             foreach ($newFieldDef as $fieldDef) {
1006                 unset($GLOBALS['table_descriptions'][$tablename][$fieldDef['name']]);
1007                 $columns[] = $fieldDef['name'];
1008             }
1009             $columns = implode(",", $columns);
1010         }
1011         else {
1012             unset($GLOBALS['table_descriptions'][$tablename][$newFieldDef['name']]);
1013             $columns = $newFieldDef['name'];
1014         }
1015
1016         $msg = "Error altering column(s) ".$columns." on table: ".$this->tableName. ":";
1017         $this->query($sql,true,$msg);
1018     }
1019
1020     /**
1021      * Drops the table associated with a bean
1022      *
1023      * @param object $bean SugarBean instance
1024      */
1025     public function dropTable(
1026         SugarBean $bean
1027         )
1028     {
1029         $this->tableName =  $bean->getTableName();
1030         $this->dropTableName( $this->tableName);
1031     }
1032
1033     /**
1034      * Drops the table by name
1035      *
1036      * @param string $name SugarBean instance
1037      */
1038     public function dropTableName(
1039         $name
1040         )
1041     {
1042         $sql = $this->getHelper()->dropTableNameSQL($name);
1043         $msg = "Error dropping table ".$this->tableName. ":";
1044         $this->query($sql,true,$msg);
1045     }
1046
1047     /**
1048      * Deletes a column identified by fieldDef.
1049      *
1050      * @param string $name      SugarBean instance
1051      * @param array  $fieldDefs
1052      */
1053     public function deleteColumn(
1054         SugarBean $bean,
1055         $fieldDefs
1056         )
1057     {
1058         $sql = $this->getHelper()->deleteColumnSQL($bean, $fieldDefs);
1059         $this->tableName = $bean->getTableName();
1060         $msg = "Error deleting column(s) ".$columns." on table: ".$this->tableName. ":";
1061         $this->query($sql,true,$msg);
1062     }
1063
1064     /**
1065          * Fetches all the rows for a select query. Returns FALSE if query failed and
1066          * DB_OK for all other queries
1067      *
1068      * @deprecated
1069      *
1070      * @param  resource $result
1071      * @return array    All rows in result set
1072      */
1073     private function setResult(
1074         $result
1075         )
1076     {
1077         $GLOBALS['log']->info('call to DBManager::setResult() is deprecated');
1078         if (PEAR::isError($result) === true) {
1079             $GLOBALS['log']->error($msg);
1080             $result = FALSE;
1081         }
1082         elseif ($result != DB_OK) {
1083             // must be a result
1084             $GLOBALS['log']->fatal("setResult:".print_r($result,true));
1085             $row = array();
1086             $rows = array();
1087             while (ocifetchinto($result, $row, OCI_ASSOC|OCI_RETURN_NULLS|OCI_RETURN_LOBS)){
1088                 $err = ocierror($result);
1089                 if ($err == false) $rows[] = $row;
1090                 else print_r($err);
1091             }
1092             $result = $rows;
1093         }
1094         $GLOBALS['log']->fatal("setResult: returning rows from setResult");
1095         return $result;
1096     }
1097
1098     /**
1099      * Private function to handle most of the sql statements which go as queries
1100      *
1101      * @deprecated
1102      *
1103      * @param  string   $sql
1104      * @param  int      $start
1105      * @param  int      $count
1106      * @param  boolean  $dieOnError
1107      * @param  string   $msg
1108      * @return array    All rows in result set
1109      */
1110     public function executeLimitQuery(
1111         $query,
1112         $start,
1113         $count,
1114         $dieOnError = false,
1115         $msg = '')
1116     {
1117         $GLOBALS['log']->info('call to DBManager::executeLimitQuery() is deprecated');
1118         $result = $this->limitQuery($query,$start,$count, $dieOnError, $msg);
1119         return $this->setResult($result);
1120     }
1121
1122     /**
1123      * Private function to handle most of the sql statements which go as queries
1124      *
1125      * @deprecated
1126      *
1127      * @param  string $query
1128      * @param  string $msg
1129      * @param  bool   $getRows
1130      * @return array  All rows in result set
1131          */
1132     public function executeQuery(
1133         $query,
1134         $msg,
1135         $getRows = false
1136         )
1137     {
1138         $GLOBALS['log']->info('call to DBManager::executeQuery() is deprecated');
1139         $result = $this->query($query,true,$msg);
1140         if ($getRows)
1141             return $this->setResult($result);
1142         // dd not get rows. Simply go on.
1143         }
1144
1145     /**
1146      * Given a db_type return the correct DBHelper
1147      *
1148      * @deprecated
1149      *
1150      * @param  string $db_type the type of database being used
1151      * @return object DBHelper instance corresponding to the db_type
1152     */
1153     private function configureHelper(
1154         $db_type
1155         )
1156     {
1157         $GLOBALS['log']->info('call to DBManager::configureHelper() is deprecated');
1158         global $sugar_config;
1159
1160         $my_db_helper = 'MysqlHelper';
1161         if( $sugar_config['dbconfig']['db_type'] == "mysql" ) {
1162             if (!isset($sugar_config['mysqli_disabled']) or $sugar_config['mysqli_disabled']==false) {
1163                 if (function_exists('mysqli_connect')) {
1164                     $my_db_helper = 'MysqliHelper';
1165                 }
1166             }
1167         }
1168
1169         if($db_type == "oci8" ){
1170         }else if($db_type == "mssql"){
1171             require_once('include/database/MssqlHelper.php');
1172             $my_db_helper = 'MssqlHelper';
1173         }
1174         if($my_db_helper == 'MysqlHelper'){
1175             require_once('include/database/MysqlHelper.php');
1176         }
1177         return new $my_db_helper();
1178     }
1179
1180     /**
1181      * Generate a set of Insert statements based on the bean given
1182      *
1183      * @deprecated
1184      *
1185      * @param  object $bean         the bean from which table we will generate insert stmts
1186      * @param  string $select_query the query which will give us the set of objects we want to place into our insert statement
1187      * @param  int    $start        the first row to query
1188      * @param  int    $count        the number of rows to query
1189      * @param  string $table        the table to query from
1190      * @param  string $db_type      the client db type
1191      * @return string SQL insert statement
1192      */
1193         public function generateInsertSQL(
1194         SugarBean $bean,
1195         $select_query,
1196         $start,
1197         $count = -1,
1198         $table,
1199         $db_type,
1200         $is_related_query = false
1201         )
1202     {
1203         $GLOBALS['log']->info('call to DBManager::generateInsertSQL() is deprecated');
1204         global $sugar_config;
1205
1206         $count_query = $bean->create_list_count_query($select_query);
1207                 if(!empty($count_query))
1208                 {
1209                         // We have a count query.  Run it and get the results.
1210                         $result = $this->query($count_query, true, "Error running count query for $this->object_name List: ");
1211                         $assoc = $this->fetchByAssoc($result);
1212                         if(!empty($assoc['c']))
1213                         {
1214                                 $rows_found = $assoc['c'];
1215                         }
1216                 }
1217                 if($count == -1){
1218                         $count  = $sugar_config['list_max_entries_per_page'];
1219                 }
1220                 $next_offset = $start + $count;
1221
1222                 $result = $this->limitQuery($select_query, $start, $count);
1223                 $row_count = $this->getRowCount($result);
1224                 // get basic insert
1225                 $sql = "INSERT INTO ".$table;
1226                 $custom_sql = "INSERT INTO ".$table."_cstm";
1227
1228                 // get field definitions
1229                 $fields = $bean->getFieldDefinitions();
1230                 $custom_fields = array();
1231
1232                 if($bean->hasCustomFields()){
1233                         foreach ($fields as $fieldDef){
1234                                 if($fieldDef['source'] == 'custom_fields'){
1235                                         $custom_fields[$fieldDef['name']] = $fieldDef['name'];
1236                                 }
1237                         }
1238                         if(!empty($custom_fields)){
1239                                 $custom_fields['id_c'] = 'id_c';
1240                                 $id_field = array('name' => 'id_c', custom_type => 'id',);
1241                                 $fields[] = $id_field;
1242                         }
1243                 }
1244
1245                 // get column names and values
1246                 $row_array = array();
1247                 $columns = array();
1248                 $cstm_row_array = array();
1249                 $cstm_columns = array();
1250                 $built_columns = false;
1251         //configure client helper
1252         $dbHelper = $this->configureHelper($db_type);
1253                 while(($row = $this->fetchByAssoc($result)) != null)
1254                 {
1255                         $values = array();
1256                         $cstm_values = array();
1257             if(!$is_related_query){
1258                         foreach ($fields as $fieldDef)
1259                         {
1260                                 if(isset($fieldDef['source']) && $fieldDef['source'] != 'db' && $fieldDef['source'] != 'custom_fields') continue;
1261                                 $val = $row[$fieldDef['name']];
1262
1263                                 //handle auto increment values here only need to do this on insert not create
1264                         if ($fieldDef['name'] == 'deleted'){
1265                                          $values['deleted'] = $val;
1266                                          if(!$built_columns){
1267                                         $columns[] = 'deleted';
1268                                 }
1269                                 }
1270                         else
1271                                 {
1272                                         $type = $fieldDef['type'];
1273                                                 if(!empty($fieldDef['custom_type'])){
1274                                                         $type = $fieldDef['custom_type'];
1275                                                 }
1276                                  // need to do some thing about types of values
1277                                                  if($db_type == 'mysql' && $val == '' && ($type == 'datetime' ||  $type == 'date' || $type == 'int' || $type == 'currency' || $type == 'decimal')){
1278                                                         if(!empty($custom_fields[$fieldDef['name']]))
1279                                                                 $cstm_values[$fieldDef['name']] = 'null';
1280                                                         else
1281                                                                 $values[$fieldDef['name']] = 'null';
1282                                                  }else{
1283                                          if(isset($type) && $type=='int') {
1284                                 if(!empty($custom_fields[$fieldDef['name']]))
1285                                         $cstm_values[$fieldDef['name']] = $GLOBALS['db']->quote(from_html($val));
1286                                                 else
1287                                         $values[$fieldDef['name']] = $GLOBALS['db']->quote(from_html($val));
1288                              } else {
1289                                 if(!empty($custom_fields[$fieldDef['name']]))
1290                                         $cstm_values[$fieldDef['name']] = "'".$GLOBALS['db']->quote(from_html($val))."'";
1291                                 else
1292                                         $values[$fieldDef['name']] = "'".$GLOBALS['db']->quote(from_html($val))."'";
1293                              }
1294                                                  }
1295                                 if(!$built_columns){
1296                                         if(!empty($custom_fields[$fieldDef['name']]))
1297                                                                 $cstm_columns[] = $fieldDef['name'];
1298                                                         else
1299                                                 $columns[] = $fieldDef['name'];
1300                                 }
1301                                 }
1302
1303                         }
1304             }else{
1305                foreach ($row as $key=>$val)
1306                {
1307                         if($key != 'orc_row'){
1308                             $values[$key] = "'$val'";
1309                             if(!$built_columns){
1310                                 $columns[] = $key;
1311                             }
1312                         }
1313                }
1314             }
1315                         $built_columns = true;
1316                         if(!empty($values)){
1317                                 $row_array[] = $values;
1318                         }
1319                         if(!empty($cstm_values) && !empty($cstm_values['id_c']) && (strlen($cstm_values['id_c']) > 7)){
1320                                 $cstm_row_array[] = $cstm_values;
1321                         }
1322                 }
1323
1324                 //if (sizeof ($values) == 0) return ""; // no columns set
1325
1326                 // get the entire sql
1327                 $sql .= "(".implode(",", $columns).") ";
1328                 $sql .= "VALUES";
1329                 for($i = 0; $i < count($row_array); $i++){
1330                         $sql .= " (".implode(",", $row_array[$i]).")";
1331                         if($i < (count($row_array) - 1)){
1332                                 $sql .= ", ";
1333                         }
1334                 }
1335                 //custom
1336                 // get the entire sql
1337                 $custom_sql .= "(".implode(",", $cstm_columns).") ";
1338                 $custom_sql .= "VALUES";
1339
1340                 for($i = 0; $i < count($cstm_row_array); $i++){
1341                         $custom_sql .= " (".implode(",", $cstm_row_array[$i]).")";
1342                         if($i < (count($cstm_row_array) - 1)){
1343                                 $custom_sql .= ", ";
1344                         }
1345                 }
1346                 return array('data' => $sql, 'cstm_sql' => $custom_sql, 'result_count' => $row_count, 'total_count' => $rows_found, 'next_offset' => $next_offset);
1347         }
1348
1349     /**
1350      * Disconnects all instances
1351      */
1352     public function disconnectAll()
1353     {
1354         global $dbinstances;
1355
1356         if (!empty($dbinstances)) {
1357             $cur = current($dbinstances);
1358             while ($cur) {
1359                 $cur->disconnect();
1360                 $cur = next($dbinstances);
1361             }
1362         }
1363
1364     }
1365
1366     /**
1367      * This function sets the query threshold limit
1368      *
1369      * @param int $limit value of query threshold limit
1370      */
1371     public static function setQueryLimit($limit){
1372                 //reset the queryCount
1373                 self::$queryCount = 0;
1374
1375                 self::$queryLimit = $limit;
1376     }
1377
1378     /**
1379      * Returns the static queryCount value
1380      *
1381      * @return int value of the queryCount static variable
1382      */
1383     public static function getQueryCount()
1384     {
1385         return self::$queryCount;
1386     }
1387
1388
1389     /**
1390      * Resets the queryCount value to 0
1391      *
1392      */
1393     public static function resetQueryCount() {
1394         self::$queryCount = 0;
1395     }
1396
1397     /**
1398      * This function increments the global $sql_queries variable
1399      *
1400      * @param $sql The SQL statement being counted
1401      */
1402     public function countQuery(
1403         $sql
1404         )
1405     {
1406                 if (self::$queryLimit != 0 && ++self::$queryCount > self::$queryLimit
1407             &&(empty($GLOBALS['current_user']) || !is_admin($GLOBALS['current_user']))) {
1408                    require_once('include/resource/ResourceManager.php');
1409                    $resourceManager = ResourceManager::getInstance();
1410                    $resourceManager->notifyObservers('ERR_QUERY_LIMIT');
1411                 }
1412     }
1413
1414     /**
1415      * Returns a string properly quoted for this database
1416      *
1417      * @param string $string
1418      * @param bool   $isLike
1419      */
1420     public function quote(
1421         $string,
1422         $isLike = true
1423         )
1424     {
1425         return from_html($string);
1426     }
1427
1428     /**
1429      * Returns a string properly quoted for this database that is an email
1430      *
1431      * @param string $string
1432      * @param bool   $isLike
1433      */
1434     abstract public function quoteforEmail(
1435         $string,
1436         $isLike = true
1437         );
1438
1439     /**
1440      * Quote the strings of the passed in array
1441      *
1442      * The array must only contain strings
1443      *
1444      * @param array $array
1445      * @param bool  $isLike
1446      */
1447     public function arrayQuote(
1448         array &$array,
1449         $isLike = true
1450         )
1451     {
1452         for($i = 0; $i < count($array); $i++){
1453             $array[$i] = $this->quote($array[$i], $isLike);
1454         }
1455     }
1456     /**
1457      * Parses and runs queries
1458      *
1459      * @param  string   $sql        SQL Statement to execute
1460      * @param  bool     $dieOnError True if we want to call die if the query returns errors
1461      * @param  string   $msg        Message to log if error occurs
1462      * @param  bool     $suppress   Flag to suppress all error output unless in debug logging mode.
1463      * @return resource result set
1464      */
1465     abstract public function query(
1466         $sql,
1467         $dieOnError = false,
1468         $msg = '',
1469         $suppress = false
1470         );
1471
1472     /**
1473      * Runs a limit query: one where we specify where to start getting records and how many to get
1474      *
1475      * @param  string   $sql
1476      * @param  int      $start
1477      * @param  int      $count
1478      * @param  boolean  $dieOnError
1479      * @param  string   $msg
1480      * @return resource query result
1481      */
1482     abstract function limitQuery(
1483         $sql,
1484         $start,
1485         $count,
1486         $dieOnError = false,
1487         $msg = '');
1488
1489     /**
1490      * Frees out previous results
1491      *
1492      * @param resource $result optional, pass if you want to free a single result instead of all results
1493      */
1494     protected function freeResult(
1495         $result = false
1496         )
1497     {
1498         $free_result = $this->backendFunctions['free_result'];
1499         if(!$result && $this->lastResult){
1500             $result = current($this->lastResult);
1501             while($result){
1502                 $free_result($result);
1503                 $result = next($this->lastResult);
1504             }
1505             $this->lastResult = array();
1506         }
1507         if($result){
1508             $free_result($result);
1509         }
1510     }
1511
1512     /**
1513      * Runs a query and returns a single row
1514      *
1515      * @param  string   $sql        SQL Statement to execute
1516      * @param  bool     $dieOnError True if we want to call die if the query returns errors
1517      * @param  string   $msg        Message to log if error occurs
1518      * @param  bool     $suppress   Message to log if error occurs
1519      * @return array    single row from the query
1520      */
1521     public function getOne(
1522         $sql,
1523         $dieOnError = false,
1524         $msg = '',
1525         $suppress = false
1526         )
1527     {
1528         $GLOBALS['log']->info("Get One: . |$sql|");
1529         $this->checkConnection();
1530         if(!($this instanceof MysqlManager) || stripos($sql, ' LIMIT ') === false) {
1531             $queryresult = $this->limitQuery($sql, 0, 1, $dieOnError, $msg);
1532         } else {
1533             // backward compatibility with queries having LIMIT
1534             $queryresult = $this->query($sql, $dieOnError, $msg);
1535         }
1536         if (!$queryresult)
1537             return false;
1538
1539         $row = $this->fetchByAssoc($queryresult);
1540         if ( !$row )
1541             return false;
1542
1543         $this->checkError($msg.' Get One Failed:' . $sql, $dieOnError);
1544
1545         $this->freeResult($queryresult);
1546         return array_shift($row);
1547     }
1548
1549  /**
1550      * will return the associative array of the row for a query or false if more than one row was returned
1551      *
1552      * @deprecated
1553      *
1554      * @param  string $sql
1555      * @param  bool   $dieonerror
1556      * @param  string $msg
1557      * @param  bool   $encode
1558      * @return array  associative array of the row or false
1559      */
1560     public function requireSingleRow(
1561         $sql,
1562         $dieOnError = false,
1563         $msg = '',
1564         $encode = true
1565         )
1566     {
1567         $GLOBALS['log']->info('call to DBManager::requireSingleRow() is deprecated');
1568         $result = $this->limitQuery($sql,0,2, $dieOnError, $msg);
1569         $count = 0;
1570         $firstRow = false;
1571         while ($row = $this->fetchByAssoc($result)){
1572                 if(!$firstRow)$firstRow = $row;
1573             $count++;
1574         }
1575
1576         if ($count > 1)
1577             return false;
1578
1579         return $firstRow;
1580     }
1581
1582     /**
1583      * Returns the description of fields based on the result
1584      *
1585      * @param  resource $result
1586      * @param  boolean  $make_lower_case
1587      * @return array field array
1588      */
1589     abstract public function getFieldsArray(
1590         &$result,
1591         $make_lower_case = false);
1592
1593     /**
1594      * Returns the number of rows returned by the result
1595      *
1596      * @param  resource $result
1597      * @return int
1598      */
1599     public function getRowCount(
1600         &$result
1601         )
1602     {
1603         $row_count = $this->backendFunctions['row_count'];
1604         if(isset($result) && !empty($result)){
1605             return $row_count($result);
1606                 }
1607                 return 0;
1608         }
1609
1610     /**
1611      * Returns the number of rows affected by the last query
1612      *
1613      * @return int
1614      */
1615     public function getAffectedRowCount()
1616     {
1617         $affected_row_count = $this->backendFunctions['affected_row_count'];
1618         return $affected_row_count($this->getDatabase());
1619     }
1620
1621     /**
1622      * Fetches the next row in the query result into an associative array
1623      *
1624      * @param  resource $result
1625      * @param  int      $rowNum optional, specify a certain row to return
1626      * @param  bool     $encode optional, true if we want html encode the resulting array
1627      * @return array    returns false if there are no more rows available to fetch
1628      */
1629     abstract public function fetchByAssoc(
1630         &$result,
1631         $rowNum = -1,
1632         $encode = true);
1633
1634     /**
1635      * Connects to the database backend
1636      *
1637      * Takes in the database settings and opens a database connection based on those
1638      * will open either a persistent or non-persistent connection.
1639      * If a persistent connection is desired but not available it will defualt to non-persistent
1640      *
1641      * configOptions must include
1642      * db_host_name - server ip
1643      * db_user_name - database user name
1644      * db_password - database password
1645      *
1646      * @param array   $configOptions
1647      * @param boolean $dieOnError
1648      */
1649     abstract public function connect(
1650          array $configOptions = null,
1651          $dieOnError = false
1652          );
1653
1654     /**
1655      * Disconnects from the database
1656      *
1657      * Also handles any cleanup needed
1658      */
1659     public function disconnect()
1660     {
1661         $GLOBALS['log']->debug('Calling DBManager::disconnect()');
1662         $close = $this->backendFunctions['close'];
1663         if(isset($this->database)){
1664             $this->freeResult();
1665             if ( is_resource($this->database) || is_object($this->database) )
1666                                 $close($this->database);
1667             unset($this->database);
1668         }
1669     }
1670
1671     /**
1672      * Returns the field description for a given field in table
1673      *
1674      * @param  string $name
1675      * @param  string $tablename
1676      * @return array
1677      */
1678     protected function describeField(
1679         $name,
1680         $tablename
1681         )
1682     {
1683         global $table_descriptions;
1684         if(isset($table_descriptions[$tablename])
1685                 && isset($table_descriptions[$tablename][$name]))
1686             return      $table_descriptions[$tablename][$name];
1687
1688         $table_descriptions[$tablename] = array();
1689         $table_descriptions[$tablename][$name] = $this->helper->get_columns($tablename);
1690
1691         if(isset($table_descriptions[$tablename][$name]))
1692             return      $table_descriptions[$tablename][$name];
1693
1694         return array();
1695     }
1696
1697     /**
1698      * Returns the index description for a given index in table
1699      *
1700      * @param  string $name
1701      * @param  string $tablename
1702      * @return array
1703      */
1704     protected function describeIndex(
1705         $name,
1706         $tablename
1707         )
1708     {
1709         global $table_descriptions;
1710         if(isset($table_descriptions[$tablename]) && isset($table_descriptions[$tablename]['indexes']) && isset($table_descriptions[$tablename]['indexes'][$name])){
1711             return      $table_descriptions[$tablename]['indexes'][$name];
1712         }
1713
1714         $table_descriptions[$tablename]['indexes'] = array();
1715
1716         $result = $this->helper->get_indices($tablename);
1717
1718                 foreach($result as $index_name => $row) {
1719             if(!isset($table_descriptions[$tablename]['indexes'][$index_name])){
1720                 $table_descriptions[$tablename]['indexes'][$index_name] = array();
1721             }
1722             $table_descriptions[$tablename]['indexes'][$index_name]['Column_name'] = $row;
1723                 }
1724
1725         if(isset($table_descriptions[$tablename]['indexes'][$name])){
1726             return      $table_descriptions[$tablename]['indexes'][$name];
1727         }
1728
1729         return array();
1730     }
1731
1732     /**
1733      * Returns an array of table for this database
1734      *
1735      * @return  $tables         an array of with table names
1736      * @return  false           if no tables found
1737      */
1738     abstract public function getTablesArray();
1739
1740     /**
1741      * Return's the version of the database
1742      *
1743      * @return string
1744      */
1745     abstract public function version();
1746
1747     /**
1748      * Checks if a table with the name $tableName exists
1749      * and returns true if it does or false otherwise
1750      *
1751      * @param  string $tableName
1752      * @return bool
1753      */
1754     abstract public function tableExists($tableName);
1755
1756     /**
1757      * Truncates a string to a given length
1758      *
1759      * @param string $string
1760      * @param int    $len    length to trim to
1761      * @param string
1762      */
1763     public function truncate(
1764         $string,
1765         $len
1766         )
1767     {
1768         if ( is_numeric($len) && $len > 0)
1769         {
1770             $string = mb_substr($string,0,(int) $len, "UTF-8");
1771         }
1772         return $string;
1773     }
1774
1775
1776         /**
1777      * Given a sql stmt attempt to parse it into the sql and the tokens. Then return the index of this prepared statement
1778      * Tokens can come in the following forms:
1779      * ? - a scalar which will be quoted
1780      * ! - a literal which will not be quoted
1781      * & - binary data to read from a file
1782      *
1783      * @param  string   $sql        The sql to parse
1784      * @return int index of the prepared statement to be used with execute
1785      */
1786     public function prepareQuery($sql){
1787         //parse out the tokens
1788         $tokens = preg_split('/((?<!\\\)[&?!])/', $sql, -1, PREG_SPLIT_DELIM_CAPTURE);
1789
1790         //maintain a count of the actual tokens for quick reference in execute
1791         $count = 0;
1792
1793         $sqlStr = '';
1794             foreach ($tokens as $key => $val) {
1795                 switch ($val) {
1796                     case '?' :
1797                     case '!' :
1798                     case '&' :
1799                         $count++;
1800                         $sqlStr .= '?';
1801                         break;
1802
1803                     default :
1804                         //escape any special characters
1805                         $tokens[$key] = preg_replace('/\\\([&?!])/', "\\1", $val);
1806                         $sqlStr .= $tokens[$key];
1807                         break;
1808                 } // switch
1809             } // foreach
1810
1811             $this->preparedTokens[] = array('tokens' => $tokens, 'tokenCount' => $count, 'sqlString' => $sqlStr);
1812             end($this->preparedTokens);
1813             return key($this->preparedTokens);
1814     }
1815
1816     /**
1817      * Takes a prepared stmt index and the data to replace and creates the query and runs it.
1818      *
1819      * @param  int              $stmt       The index of the prepared statement from preparedTokens
1820      * @param  array    $data           The array of data to replace the tokens with.
1821      * @return resource result set or false on error
1822      */
1823     public function executePreparedQuery($stmt, $data = array()){
1824         if(!empty($this->preparedTokens[$stmt])){
1825                 if(!is_array($data)){
1826                                 $data = array($data);
1827                         }
1828
1829                 $pTokens = $this->preparedTokens[$stmt];
1830
1831                 //ensure that the number of data elements matches the number of replacement tokens
1832                 //we found in prepare().
1833                 if(count($data) != $pTokens['tokenCount']){
1834                         //error the data count did not match the token count
1835                         return false;
1836                 }
1837
1838                 $query = '';
1839                 $dataIndex = 0;
1840                 $tokens = $pTokens['tokens'];
1841                 foreach ($tokens as $val) {
1842                 switch ($val) {
1843                         case '?':
1844                                 $query .= $this->quote($data[$dataIndex++]);
1845                                 break;
1846                         case '&':
1847                                 $filename = $data[$dataIndex++];
1848                                         $query .= sugar_file_get_contents($filename);
1849                                 break;
1850                         case '!':
1851                                 $query .= $data[$dataIndex++];
1852                                 break;
1853                         default:
1854                                 $query .= $val;
1855                                 break;
1856                 }//switch
1857                 }//foreach
1858                 return $this->query($query);
1859         }else{
1860                 return false;
1861         }
1862     }
1863
1864     /**
1865      * Run both prepare and execute without the client having to run both individually.
1866      *
1867      * @param  string   $sql        The sql to parse
1868      * @param  array    $data           The array of data to replace the tokens with.
1869      * @return resource result set or false on error
1870      */
1871     public function pQuery($sql, $data = array()){
1872         $stmt = $this->prepareQuery($sql);
1873         return $this->executePreparedQuery($stmt, $data);
1874     }
1875
1876     /**
1877      * Use when you need to convert a database string to a different value; this function does it in a
1878      * database-backend aware way
1879      *
1880      * @param string $string database string to convert
1881      * @param string $type type of conversion to do
1882      * @param array  $additional_parameters optional, additional parameters to pass to the db function
1883      * @param array  $additional_parameters_oracle_only optional, additional parameters to pass to the db function on oracle only
1884      * @return string
1885      */
1886     public function convert(
1887         $string,
1888         $type,
1889         array $additional_parameters = array(),
1890         array $additional_parameters_oracle_only = array()
1891         )
1892     {
1893         return "$string";
1894     }
1895
1896     /**
1897      * Returns the database string needed for concatinating multiple database strings together
1898      *
1899      * @param string $table table name of the database fields to concat
1900      * @param array $fields fields in the table to concat together
1901      * @return string
1902      */
1903     abstract public function concat(
1904         $table,
1905         array $fields
1906         );
1907
1908     /**
1909      * Undoes database conversion
1910      *
1911      * @param string $string database string to convert
1912      * @param string $type type of conversion to do
1913      * @return string
1914      */
1915     public function fromConvert(
1916         $string,
1917         $type)
1918     {
1919         return $string;
1920     }
1921 }
1922
1923 ?>