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-2013 SugarCRM Inc.
7 * This program is free software; you can redistribute it and/or modify it under
8 * the terms of the GNU Affero General Public License version 3 as published by the
9 * Free Software Foundation with the addition of the following permission added
10 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
11 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
12 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
14 * This program is distributed in the hope that it will be useful, but WITHOUT
15 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
16 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
19 * You should have received a copy of the GNU Affero General Public License along with
20 * this program; if not, see http://www.gnu.org/licenses or write to the Free
21 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
24 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
25 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
27 * The interactive user interfaces in modified source and object code versions
28 * of this program must display Appropriate Legal Notices, as required under
29 * Section 5 of the GNU Affero General Public License version 3.
31 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
32 * these Appropriate Legal Notices must retain the display of the "Powered by
33 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
34 * technical reasons, the Appropriate Legal Notices must display the words
35 * "Powered by SugarCRM".
36 ********************************************************************************/
38 /*********************************************************************************
40 * Description: This file handles the Data base functionality for the application.
41 * It acts as the DB abstraction layer for the application. It depends on helper classes
42 * which generate the necessary SQL. This sql is then passed to PEAR DB classes.
43 * The helper class is chosen in DBManagerFactory, which is driven by 'db_type' in 'dbconfig' under config.php.
45 * All the functions in this class will work with any bean which implements the meta interface.
46 * The passed bean is passed to helper class which uses these functions to generate correct sql.
48 * The meta interface has the following functions:
49 * getTableName() Returns table name of the object.
50 * getFieldDefinitions() Returns a collection of field definitions in order.
51 * getFieldDefintion(name) Return field definition for the field.
52 * getFieldValue(name) Returns the value of the field identified by name.
53 * If the field is not set, the function will return boolean FALSE.
54 * getPrimaryFieldDefinition() Returns the field definition for primary key
56 * The field definition is an array with the following keys:
58 * name This represents name of the field. This is a required field.
59 * type This represents type of the field. This is a required field and valid values are:
73 * length This is used only when the type is varchar and denotes the length of the string.
74 * The max value is 255.
75 * enumvals This is a list of valid values for an enum separated by "|".
76 * It is used only if the type is �enum�;
77 * required This field dictates whether it is a required value.
78 * The default value is �FALSE�.
79 * isPrimary This field identifies the primary key of the table.
80 * If none of the fields have this flag set to �TRUE�,
81 * the first field definition is assume to be the primary key.
82 * Default value for this field is �FALSE�.
83 * default This field sets the default value for the field definition.
86 * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
87 * All Rights Reserved.
88 * Contributor(s): ______________________________________..
89 ********************************************************************************/
92 * Base database driver implementation
95 abstract class DBManager
101 public $database = null;
104 * Indicates whether we should die when we get an error from the DB
106 protected $dieOnError = false;
109 * Indicates whether we should html encode the results from a query by default
111 protected $encode = true;
114 * Records the execution time of the last query
116 protected $query_time = 0;
119 * Last error message from the DB backend
121 protected $last_error = false;
124 * Registry of available result sets
126 protected $lastResult;
129 * Current query count
131 private static $queryCount = 0;
134 * Query threshold limit
136 private static $queryLimit = 0;
139 * Array of prepared statements and their correspoding parsed tokens
141 protected $preparedTokens = array();
159 protected static $table_descriptions = array();
165 protected static $index_descriptions = array();
168 * Maximum length of identifiers
172 protected $maxNameLengths = array(
181 * Higher priority drivers override lower priority ones
184 public $priority = 0;
187 * Driver name label, for install
198 protected $type_map = array();
201 * Type classification into:
209 protected $type_class = array(
218 'datetime' => 'date',
219 'datetimecombo' => 'date',
223 'currency' => 'float',
224 'decimal' => 'float',
225 'decimal2' => 'float',
229 * Capabilities this DB supports. Supported list:
230 * affected_rows Can report query affected rows for UPDATE/DELETE
231 * implement getAffectedRowCount()
232 * select_rows Can report row count for SELECT
233 * implement getRowCount()
234 * case_sensitive Supports case-sensitive text columns
235 * fulltext Supports fulltext search indexes
236 * inline_keys Supports defining keys together with the table
237 * auto_increment_sequence Autoincrement support implemented as sequence
238 * limit_subquery Supports LIMIT clauses in subqueries
239 * create_user Can create users for Sugar
240 * create_db Can create databases
241 * collation Supports setting collations
242 * disable_keys Supports temporarily disabling keys (for upgrades, etc.)
246 * fix:expandDatabase - needs expandDatabase fix, see expandDatabase.php
247 * TODO: verify if we need these cases
249 protected $capabilities = array();
255 protected $options = array();
260 public function __construct()
262 $this->timedate = TimeDate::getInstance();
263 $this->log = $GLOBALS['log'];
264 $this->helper = $this; // compatibility
268 * Wrapper for those trying to access the private and protected class members directly
269 * @param string $p var name
272 public function __get($p)
274 $this->log->info('Call to DBManager::$'.$p.' is deprecated');
279 * Returns the current database handle
282 public function getDatabase()
284 $this->checkConnection();
285 return $this->database;
289 * Returns this instance's DBHelper
290 * Actually now returns $this
294 public function getHelper()
300 * Checks for error happening in the database
302 * @param string $msg message to prepend to the error message
303 * @param bool $dieOnError true if we want to die immediately on error
304 * @return bool True if there was an error
306 public function checkError($msg = '', $dieOnError = false)
308 if (empty($this->database)) {
309 $this->registerError($msg, "Database Is Not Connected", $dieOnError);
313 $dberror = $this->lastDbError();
314 if($dberror === false) {
315 $this->last_error = false;
318 $this->registerError($msg, $dberror, $dieOnError);
323 * Register database error
324 * If die-on-error flag is set, logs the message and dies,
325 * otherwise sets last_error to the message
326 * @param string $userMessage Message from function user
327 * @param string $message Message from SQL driver
328 * @param bool $dieOnError
330 protected function registerError($userMessage, $message, $dieOnError = false)
332 if(!empty($message)) {
333 if(!empty($userMessage)) {
334 $message = "$userMessage: $message";
336 if(empty($message)) {
337 $message = "Database error";
339 $this->log->fatal($message);
340 if ($dieOnError || $this->dieOnError) {
341 if(isset($GLOBALS['app_strings']['ERR_DB_FAIL'])) {
342 sugar_die($GLOBALS['app_strings']['ERR_DB_FAIL']);
344 sugar_die("Database error. Please check sugarcrm.log for details.");
347 $this->last_error = $message;
353 * Return DB error message for the last query executed
354 * @return string Last error message
356 public function lastError()
358 return $this->last_error;
362 * This method is called by every method that runs a query.
363 * If slow query dumping is turned on and the query time is beyond
364 * the time limit, we will log the query. This function may do
365 * additional reporting or log in a different area in the future.
367 * @param string $query query to log
368 * @return boolean true if the query was logged, false otherwise
370 protected function dump_slow_queries($query)
372 global $sugar_config;
374 $do_the_dump = isset($sugar_config['dump_slow_queries'])
375 ? $sugar_config['dump_slow_queries'] : false;
376 $slow_query_time_msec = isset($sugar_config['slow_query_time_msec'])
377 ? $sugar_config['slow_query_time_msec'] : 5000;
380 if($slow_query_time_msec < ($this->query_time * 1000)) {
381 // Then log both the query and the query time
382 $this->log->fatal('Slow Query (time:'.$this->query_time."\n".$query);
390 * Scans order by to ensure that any field being ordered by is.
392 * It will throw a warning error to the log file - fatal if slow query logging is enabled
394 * @param string $sql query to be run
395 * @param bool $object_name optional, object to look up indices in
396 * @return bool true if an index is found false otherwise
398 protected function checkQuery($sql, $object_name = false)
401 preg_match_all("'.* FROM ([^ ]*).* ORDER BY (.*)'is", $sql, $match);
403 if (!empty($match[1][0]))
404 $table = $match[1][0];
408 if (!empty($object_name) && !empty($GLOBALS['dictionary'][$object_name]))
409 $indices = $GLOBALS['dictionary'][$object_name]['indices'];
411 if (empty($indices)) {
412 foreach ( $GLOBALS['dictionary'] as $current ) {
413 if ($current['table'] == $table){
414 $indices = $current['indices'];
419 if (empty($indices)) {
420 $this->log->warn('CHECK QUERY: Could not find index definitions for table ' . $table);
423 if (!empty($match[2][0])) {
424 $orderBys = explode(' ', $match[2][0]);
425 foreach ($orderBys as $orderBy){
426 $orderBy = trim($orderBy);
429 $orderBy = strtolower($orderBy);
430 if ($orderBy == 'asc' || $orderBy == 'desc')
433 $orderBy = str_replace(array($table . '.', ','), '', $orderBy);
435 foreach ($indices as $index)
436 if (empty($index['db']) || $index['db'] == $this->dbType)
437 foreach ($index['fields'] as $field)
438 if ($field == $orderBy)
441 $warning = 'Missing Index For Order By Table: ' . $table . ' Order By:' . $orderBy ;
442 if (!empty($GLOBALS['sugar_config']['dump_slow_queries']))
443 $this->log->fatal('CHECK QUERY:' .$warning);
445 $this->log->warn('CHECK QUERY:' .$warning);
452 * Returns the time the last query took to execute
456 public function getQueryTime()
458 return $this->query_time;
462 * Checks the current connection; if it is not connected then reconnect
464 public function checkConnection()
466 $this->last_error = '';
467 if (!isset($this->database))
472 * Sets the dieOnError value
476 public function setDieOnError($value)
478 $this->dieOnError = $value;
482 * Implements a generic insert for any bean.
484 * @param SugarBean $bean SugarBean instance
485 * @return bool query result
488 public function insert(SugarBean $bean)
490 $sql = $this->insertSQL($bean);
491 $tablename = $bean->getTableName();
492 $msg = "Error inserting into table: $tablename:";
493 return $this->query($sql,true,$msg);
497 * Insert data into table by parameter definition
498 * @param string $table Table name
499 * @param array $field_defs Definitions in vardef-like format
500 * @param array $data Key/value to insert
501 * @param array $field_map Fields map from SugarBean
502 * @param bool $execute Execute or return query?
503 * @return bool query result
505 public function insertParams($table, $field_defs, $data, $field_map = null, $execute = true)
508 foreach ($field_defs as $field => $fieldDef)
510 if (isset($fieldDef['source']) && $fieldDef['source'] != 'db') continue;
511 //custom fields handle there save seperatley
512 if(!empty($field_map) && !empty($field_map[$field]['custom_type'])) continue;
514 if(isset($data[$field])) {
515 // clean the incoming value..
516 $val = from_html($data[$field]);
518 if(isset($fieldDef['default']) && strlen($fieldDef['default']) > 0) {
519 $val = $fieldDef['default'];
525 //handle auto increment values here - we may have to do something like nextval for oracle
526 if (!empty($fieldDef['auto_increment'])) {
527 $auto = $this->getAutoIncrementSQL($table, $fieldDef['name']);
529 $values[$field] = $auto;
531 } elseif ($fieldDef['name'] == 'deleted') {
532 $values['deleted'] = (int)$val;
534 // need to do some thing about types of values
535 if(!is_null($val) || !empty($fieldDef['required'])) {
536 $values[$field] = $this->massageValue($val, $fieldDef);
542 return $execute?true:''; // no columns set
544 // get the entire sql
545 $query = "INSERT INTO $table (".implode(",", array_keys($values)).")
546 VALUES (".implode(",", $values).")";
547 return $execute?$this->query($query):$query;
551 * Implements a generic update for any bean
553 * @param SugarBean $bean Sugarbean instance
554 * @param array $where values with the keys as names of fields.
555 * If we want to pass multiple values for a name, pass it as an array
556 * If where is not passed, it defaults to id of table
557 * @return bool query result
560 public function update(SugarBean $bean, array $where = array())
562 $sql = $this->updateSQL($bean, $where);
563 $tablename = $bean->getTableName();
564 $msg = "Error updating table: $tablename:";
565 return $this->query($sql,true,$msg);
569 * Implements a generic delete for any bean identified by id
571 * @param SugarBean $bean Sugarbean instance
572 * @param array $where values with the keys as names of fields.
573 * If we want to pass multiple values for a name, pass it as an array
574 * If where is not passed, it defaults to id of table
575 * @return bool query result
577 public function delete(SugarBean $bean, array $where = array())
579 $sql = $this->deleteSQL($bean, $where);
580 $tableName = $bean->getTableName();
581 $msg = "Error deleting from table: ".$tableName. ":";
582 return $this->query($sql,true,$msg);
586 * Implements a generic retrieve for any bean identified by id
588 * If we want to pass multiple values for a name, pass it as an array
589 * If where is not passed, it defaults to id of table
591 * @param SugarBean $bean Sugarbean instance
592 * @param array $where values with the keys as names of fields.
593 * @return resource result from the query
595 public function retrieve(SugarBean $bean, array $where = array())
597 $sql = $this->retrieveSQL($bean, $where);
598 $tableName = $bean->getTableName();
599 $msg = "Error retriving values from table:".$tableName. ":";
600 return $this->query($sql,true,$msg);
604 * Implements a generic retrieve for a collection of beans.
606 * These beans will be joined in the sql by the key attribute of field defs.
607 * Currently, this function does support outer joins.
609 * @param array $beans Sugarbean instance(s)
610 * @param array $cols columns to be returned with the keys as names of bean as identified by
611 * get_class of bean. Values of this array is the array of fieldDefs to be returned for a bean.
612 * If an empty array is passed, all columns are selected.
613 * @param array $where values with the keys as names of bean as identified by get_class of bean
614 * Each value at the first level is an array of values for that bean identified by name of fields.
615 * If we want to pass multiple values for a name, pass it as an array
616 * If where is not passed, all the rows will be returned.
619 public function retrieveView(array $beans, array $cols = array(), array $where = array())
621 $sql = $this->retrieveViewSQL($beans, $cols, $where);
622 $msg = "Error retriving values from View Collection:";
623 return $this->query($sql,true,$msg);
628 * Implements creation of a db table for a bean.
630 * NOTE: does not handle out-of-table constraints, use createConstraintSQL for that
631 * @param SugarBean $bean Sugarbean instance
633 public function createTable(SugarBean $bean)
635 $sql = $this->createTableSQL($bean);
636 $tablename = $bean->getTableName();
637 $msg = "Error creating table: $tablename:";
638 $this->query($sql,true,$msg);
639 if(!$this->supports("inline_keys")) {
640 // handle constraints and indices
641 $indicesArr = $this->createConstraintSql($bean);
642 if (count($indicesArr) > 0)
643 foreach ($indicesArr as $indexSql)
644 $this->query($indexSql, true, $msg);
649 * returns SQL to create constraints or indices
651 * @param SugarBean $bean SugarBean instance
652 * @return array list of SQL statements
654 protected function createConstraintSql(SugarBean $bean)
656 return $this->getConstraintSql($bean->getIndices(), $bean->getTableName());
660 * Implements creation of a db table
662 * @param string $tablename
663 * @param array $fieldDefs Field definitions, in vardef format
664 * @param array $indices Index definitions, in vardef format
665 * @param string $engine Engine parameter, used for MySQL engine so far
666 * @todo: refactor engine param to be more generic
667 * @return bool success value
669 public function createTableParams($tablename, $fieldDefs, $indices, $engine = null)
671 if (!empty($fieldDefs)) {
672 $sql = $this->createTableSQLParams($tablename, $fieldDefs, $indices, $engine);
675 $msg = "Error creating table: $tablename";
676 $res = ($res and $this->query($sql,true,$msg));
678 if(!$this->supports("inline_keys")) {
679 // handle constraints and indices
680 $indicesArr = $this->getConstraintSql($indices, $tablename);
681 if (count($indicesArr) > 0)
682 foreach ($indicesArr as $indexSql)
683 $res = ($res and $this->query($indexSql, true, "Error creating indexes"));
691 * Implements repair of a db table for a bean.
693 * @param SugarBean $bean SugarBean instance
694 * @param bool $execute true if we want the action to take place, false if we just want the sql returned
695 * @return string SQL statement or empty string, depending upon $execute
697 public function repairTable(SugarBean $bean, $execute = true)
699 $indices = $bean->getIndices();
700 $fielddefs = $bean->getFieldDefinitions();
701 $tablename = $bean->getTableName();
703 //Clean the indexes to prevent duplicate definitions
704 $new_index = array();
705 foreach($indices as $ind_def){
706 $new_index[$ind_def['name']] = $ind_def;
708 //jc: added this for beans that do not actually have a table, namely
709 //ForecastOpportunities
710 if($tablename == 'does_not_exist' || $tablename == '')
715 if (isset($dictionary[$bean->getObjectName()]['engine']) && !empty($dictionary[$bean->getObjectName()]['engine']) )
716 $engine = $dictionary[$bean->getObjectName()]['engine'];
718 return $this->repairTableParams($tablename, $fielddefs,$new_index,$execute,$engine);
722 * Can this field be null?
723 * Auto-increment and ID fields can not be null
724 * @param array $vardef
727 protected function isNullable($vardef)
730 if(isset($vardef['isnull']) && (strtolower($vardef['isnull']) == 'false' || $vardef['isnull'] === false)
731 && !empty($vardef['required'])) {
732 /* required + is_null=false => not null */
735 if(empty($vardef['auto_increment']) && (empty($vardef['type']) || $vardef['type'] != 'id')
736 && (empty($vardef['dbType']) || $vardef['dbType'] != 'id')
737 && (empty($vardef['name']) || ($vardef['name'] != 'id' && $vardef['name'] != 'deleted'))
746 * Builds the SQL commands that repair a table structure
748 * @param string $tablename
749 * @param array $fielddefs Field definitions, in vardef format
750 * @param array $indices Index definitions, in vardef format
751 * @param bool $execute optional, true if we want the queries executed instead of returned
752 * @param string $engine optional, MySQL engine
753 * @todo: refactor engine param to be more generic
756 public function repairTableParams($tablename, $fielddefs, $indices, $execute = true, $engine = null)
758 //jc: had a bug when running the repair if the tablename is blank the repair will
759 //fail when it tries to create a repair table
760 if ($tablename == '' || empty($fielddefs))
763 //if the table does not exist create it and we are done
764 $sql = "/* Table : $tablename */\n";
765 if (!$this->tableExists($tablename)) {
766 $createtablesql = $this->createTableSQLParams($tablename,$fielddefs,$indices,$engine);
767 if($execute && $createtablesql){
768 $this->createTableParams($tablename,$fielddefs,$indices,$engine);
771 $sql .= "/* MISSING TABLE: {$tablename} */\n";
772 $sql .= $createtablesql . "\n";
776 $compareFieldDefs = $this->get_columns($tablename);
777 $compareIndices = $this->get_indices($tablename);
779 $take_action = false;
781 // do column comparisons
782 $sql .= "/*COLUMNS*/\n";
783 foreach ($fielddefs as $name => $value) {
784 if (isset($value['source']) && $value['source'] != 'db')
787 // Bug #42406. Skipping breaked vardef without type or name
788 if (isset($value['name']) == false || $value['name'] == false)
790 $sql .= "/* NAME IS MISSING IN VARDEF $tablename::$name */\n";
793 else if (isset($value['type']) == false || $value['type'] == false)
795 $sql .= "/* TYPE IS MISSING IN VARDEF $tablename::$name */\n";
799 $name = strtolower($value['name']);
800 // add or fix the field defs per what the DB is expected to give us back
801 $this->massageFieldDef($value,$tablename);
803 $ignorerequired=false;
805 //Do not track requiredness in the DB, auto_increment, ID,
806 // and deleted fields are always required in the DB, so don't force those
807 if ($this->isNullable($value)) {
808 $value['required'] = false;
810 //Should match the conditions in DBManager::oneColumnSQLRep for DB required fields, type='id' fields will sometimes
812 //come into this function as 'type' = 'char', 'dbType' = 'id' without required set in $value. Assume they are correct and leave them alone.
813 else if (($name == 'id' || $value['type'] == 'id' || (isset($value['dbType']) && $value['dbType'] == 'id'))
814 && (!isset($value['required']) && isset($compareFieldDefs[$name]['required'])))
816 $value['required'] = $compareFieldDefs[$name]['required'];
819 if ( !isset($compareFieldDefs[$name]) ) {
820 // ok we need this field lets create it
821 $sql .= "/*MISSING IN DATABASE - $name - ROW*/\n";
822 $sql .= $this->addColumnSQL($tablename, $value) . "\n";
824 $this->addColumn($tablename, $value);
826 } elseif ( !$this->compareVarDefs($compareFieldDefs[$name],$value)) {
827 //fields are different lets alter it
828 $sql .= "/*MISMATCH WITH DATABASE - $name - ROW ";
829 foreach($compareFieldDefs[$name] as $rKey => $rValue) {
830 $sql .= "[$rKey] => '$rValue' ";
833 $sql .= "/* VARDEF - $name - ROW";
834 foreach($value as $rKey => $rValue) {
835 $sql .= "[$rKey] => '$rValue' ";
839 //jc: oracle will complain if you try to execute a statement that sets a column to (not) null
840 //when it is already (not) null
841 if ( isset($value['isnull']) && isset($compareFieldDefs[$name]['isnull']) &&
842 $value['isnull'] === $compareFieldDefs[$name]['isnull']) {
843 unset($value['required']);
844 $ignorerequired=true;
847 //dwheeler: Once a column has been defined as null, we cannot try to force it back to !null
848 if ((isset($value['required']) && ($value['required'] === true || $value['required'] == 'true' || $value['required'] === 1))
849 && (empty($compareFieldDefs[$name]['required']) || $compareFieldDefs[$name]['required'] != 'true'))
851 $ignorerequired = true;
853 $altersql = $this->alterColumnSQL($tablename, $value,$ignorerequired);
854 if(is_array($altersql)) {
855 $altersql = join("\n", $altersql);
857 $sql .= $altersql . "\n";
859 $this->alterColumn($tablename, $value, $ignorerequired);
865 // do index comparisons
866 $sql .= "/* INDEXES */\n";
867 $correctedIndexs = array();
869 $compareIndices_case_insensitive = array();
871 // do indices comparisons case-insensitive
872 foreach($compareIndices as $k => $value){
873 $value['name'] = strtolower($value['name']);
874 $compareIndices_case_insensitive[strtolower($k)] = $value;
876 $compareIndices = $compareIndices_case_insensitive;
877 unset($compareIndices_case_insensitive);
879 foreach ($indices as $value) {
880 if (isset($value['source']) && $value['source'] != 'db')
884 $validDBName = $this->getValidDBName($value['name'], true, 'index', true);
885 if (isset($compareIndices[$validDBName])) {
886 $value['name'] = $validDBName;
888 $name = strtolower($value['name']);
890 //Don't attempt to fix the same index twice in one pass;
891 if (isset($correctedIndexs[$name]))
894 //don't bother checking primary nothing we can do about them
895 if (isset($value['type']) && $value['type'] == 'primary')
898 //database helpers do not know how to handle full text indices
899 if ($value['type']=='fulltext')
902 if ( in_array($value['type'],array('alternate_key','foreign')) )
903 $value['type'] = 'index';
905 if ( !isset($compareIndices[$name]) ) {
906 //First check if an index exists that doesn't match our name, if so, try to rename it
908 foreach ($compareIndices as $ex_name => $ex_value) {
909 if($this->compareVarDefs($ex_value, $value, true)) {
915 $sql .= "/*MISSNAMED INDEX IN DATABASE - $name - $ex_name */\n";
916 $rename = $this->renameIndexDefs($ex_value, $value, $tablename);
918 $this->query($rename, true, "Cannot rename index");
920 $sql .= is_array($rename)?join("\n", $rename). "\n":$rename."\n";
923 // ok we need this field lets create it
924 $sql .= "/*MISSING INDEX IN DATABASE - $name -{$value['type']} ROW */\n";
925 $sql .= $this->addIndexes($tablename,array($value), $execute) . "\n";
928 $correctedIndexs[$name] = true;
929 } elseif ( !$this->compareVarDefs($compareIndices[$name],$value) ) {
930 // fields are different lets alter it
931 $sql .= "/*INDEX MISMATCH WITH DATABASE - $name - ROW ";
932 foreach ($compareIndices[$name] as $n1 => $t1) {
934 if ( $n1 == 'fields' )
935 foreach($t1 as $rKey => $rValue)
936 $sql .= "[$rKey] => '$rValue' ";
941 $sql .= "/* VARDEF - $name - ROW";
942 foreach ($value as $n1 => $t1) {
944 if ( $n1 == 'fields' )
945 foreach ($t1 as $rKey => $rValue)
946 $sql .= "[$rKey] => '$rValue' ";
951 $sql .= $this->modifyIndexes($tablename,array($value), $execute) . "\n";
953 $correctedIndexs[$name] = true;
957 return ($take_action === true) ? $sql : '';
961 * Compares two vardefs
963 * @param array $fielddef1 This is from the database
964 * @param array $fielddef2 This is from the vardef
965 * @param bool $ignoreName Ignore name-only differences?
966 * @return bool true if they match, false if they don't
968 public function compareVarDefs($fielddef1, $fielddef2, $ignoreName = false)
970 foreach ( $fielddef1 as $key => $value ) {
971 if ( $key == 'name' && ( strtolower($fielddef1[$key]) == strtolower($fielddef2[$key]) || $ignoreName) )
973 if ( isset($fielddef2[$key]) && $fielddef1[$key] == $fielddef2[$key] )
975 //Ignore len if its not set in the vardef
976 if ($key == 'len' && empty($fielddef2[$key]))
978 // if the length in db is greather than the vardef, ignore it
979 if ($key == 'len' && ($fielddef1[$key] >= $fielddef2[$key])) {
989 * Compare a field in two tables
991 * @param string $name field name
992 * @param string $table1
993 * @param string $table2
994 * @return array array with keys 'msg','table1','table2'
996 public function compareFieldInTables($name, $table1, $table2)
998 $row1 = $this->describeField($name, $table1);
999 $row2 = $this->describeField($name, $table2);
1000 $returnArray = array(
1006 $ignore_filter = array('Key'=>1);
1009 // Exists on table1 but not table2
1010 $returnArray['msg'] = 'not_exists_table2';
1013 if (sizeof($row1) != sizeof($row2)) {
1014 $returnArray['msg'] = 'no_match';
1017 $returnArray['msg'] = 'match';
1018 foreach($row1 as $key => $value){
1019 //ignore keys when checking we will check them when we do the index check
1020 if( !isset($ignore_filter[$key]) && (!isset($row2[$key]) || $row1[$key] !== $row2[$key])){
1021 $returnArray['msg'] = 'no_match';
1028 $returnArray['msg'] = 'not_exists_table1';
1031 return $returnArray;
1035 // * Compare an index in two different tables
1037 // * @param string $name index name
1038 // * @param string $table1
1039 // * @param string $table2
1040 // * @return array array with keys 'msg','table1','table2'
1042 // public function compareIndexInTables($name, $table1, $table2)
1044 // $row1 = $this->describeIndex($name, $table1);
1045 // $row2 = $this->describeIndex($name, $table2);
1046 // $returnArray = array(
1047 // 'table1' => $row1,
1048 // 'table2' => $row2,
1049 // 'msg' => 'error',
1051 // $ignore_filter = array('Table'=>1, 'Seq_in_index'=>1,'Cardinality'=>1, 'Sub_part'=>1, 'Packed'=>1, 'Comment'=>1);
1055 // //Exists on table1 but not table2
1056 // $returnArray['msg'] = 'not_exists_table2';
1059 // if (sizeof($row1) != sizeof($row2)) {
1060 // $returnArray['msg'] = 'no_match';
1063 // $returnArray['msg'] = 'match';
1064 // foreach ($row1 as $fname => $fvalue) {
1065 // if (!isset($row2[$fname])) {
1066 // $returnArray['msg'] = 'no_match';
1068 // if(!isset($ignore_filter[$fname]) && $row1[$fname] != $row2[$fname]){
1069 // $returnArray['msg'] = 'no_match';
1075 // $returnArray['msg'] = 'not_exists_table1';
1078 // return $returnArray;
1083 * Creates an index identified by name on the given fields.
1085 * @param SugarBean $bean SugarBean instance
1086 * @param array $fieldDefs Field definitions, in vardef format
1087 * @param string $name index name
1088 * @param bool $unique optional, true if we want to create an unique index
1089 * @return bool query result
1091 public function createIndex(SugarBean $bean, $fieldDefs, $name, $unique = true)
1093 $sql = $this->createIndexSQL($bean, $fieldDefs, $name, $unique);
1094 $tablename = $bean->getTableName();
1095 $msg = "Error creating index $name on table: $tablename:";
1096 return $this->query($sql,true,$msg);
1100 * returns a SQL query that creates the indices as defined in metadata
1101 * @param array $indices Assoc array with index definitions from vardefs
1102 * @param string $table Focus table
1103 * @return array Array of SQL queries to generate indices
1105 public function getConstraintSql($indices, $table)
1107 if (!$this->isFieldArray($indices))
1108 $indices = array($indices);
1112 foreach ($indices as $index) {
1113 if(!empty($index['db']) && $index['db'] != $this->dbType)
1115 if (isset($index['source']) && $index['source'] != 'db')
1118 $sql = $this->add_drop_constraint($table, $index);
1129 * Adds a new indexes
1131 * @param string $tablename
1132 * @param array $indexes indexes to add
1133 * @param bool $execute true if we want to execute the returned sql statement
1134 * @return string SQL statement
1136 public function addIndexes($tablename, $indexes, $execute = true)
1138 $alters = $this->getConstraintSql($indexes, $tablename);
1140 foreach($alters as $sql) {
1141 $this->query($sql, true, "Error adding index: ");
1144 if(!empty($alters)) {
1145 $sql = join(";\n", $alters).";\n";
1155 * @param string $tablename
1156 * @param array $indexes indexes to drop
1157 * @param bool $execute true if we want to execute the returned sql statement
1158 * @return string SQL statement
1160 public function dropIndexes($tablename, $indexes, $execute = true)
1163 foreach ($indexes as $index) {
1164 $name =$index['name'];
1165 $sqls[$name] = $this->add_drop_constraint($tablename,$index,true);
1167 if (!empty($sqls) && $execute) {
1168 foreach($sqls as $name => $sql) {
1169 unset(self::$index_descriptions[$tablename][$name]);
1174 return join(";\n",$sqls).";";
1183 * @param string $tablename
1184 * @param array $indexes indexes to modify
1185 * @param bool $execute true if we want to execute the returned sql statement
1186 * @return string SQL statement
1188 public function modifyIndexes($tablename, $indexes, $execute = true)
1190 return $this->dropIndexes($tablename, $indexes, $execute)."\n".
1191 $this->addIndexes($tablename, $indexes, $execute);
1195 * Adds a column to table identified by field def.
1197 * @param string $tablename
1198 * @param array $fieldDefs
1199 * @return bool query result
1201 public function addColumn($tablename, $fieldDefs)
1203 $sql = $this->addColumnSQL($tablename, $fieldDefs);
1204 if ($this->isFieldArray($fieldDefs)){
1206 foreach ($fieldDefs as $fieldDef)
1207 $columns[] = $fieldDef['name'];
1208 $columns = implode(",", $columns);
1211 $columns = $fieldDefs['name'];
1213 $msg = "Error adding column(s) $columns on table: $tablename:";
1214 return $this->query($sql,true,$msg);
1218 * Alters old column identified by oldFieldDef to new fieldDef.
1220 * @param string $tablename
1221 * @param array $newFieldDef
1222 * @param bool $ignoreRequired optional, true if we are ignoring this being a required field
1223 * @return bool query result
1225 public function alterColumn($tablename, $newFieldDef, $ignoreRequired = false)
1227 $sql = $this->alterColumnSQL($tablename, $newFieldDef,$ignoreRequired);
1228 if ($this->isFieldArray($newFieldDef)){
1230 foreach ($newFieldDef as $fieldDef) {
1231 $columns[] = $fieldDef['name'];
1233 $columns = implode(",", $columns);
1236 $columns = $newFieldDef['name'];
1239 $msg = "Error altering column(s) $columns on table: $tablename:";
1240 $res = $this->query($sql,true,$msg);
1242 $this->getTableDescription($tablename, true); // reload table description after altering
1248 * Drops the table associated with a bean
1250 * @param SugarBean $bean SugarBean instance
1251 * @return bool query result
1253 public function dropTable(SugarBean $bean)
1255 return $this->dropTableName($bean->getTableName());
1259 * Drops the table by name
1261 * @param string $name Table name
1262 * @return bool query result
1264 public function dropTableName($name)
1266 $sql = $this->dropTableNameSQL($name);
1267 return $this->query($sql,true,"Error dropping table $name:");
1271 * Deletes a column identified by fieldDef.
1273 * @param SugarBean $bean SugarBean containing the field
1274 * @param array $fieldDefs Vardef definition of the field
1275 * @return bool query result
1277 public function deleteColumn(SugarBean $bean, $fieldDefs)
1279 $tablename = $bean->getTableName();
1280 $sql = $this->dropColumnSQL($tablename, $fieldDefs);
1281 $msg = "Error deleting column(s) on table: $tablename:";
1282 return $this->query($sql,true,$msg);
1286 * Generate a set of Insert statements based on the bean given
1290 * @param SugarBean $bean the bean from which table we will generate insert stmts
1291 * @param string $select_query the query which will give us the set of objects we want to place into our insert statement
1292 * @param int $start the first row to query
1293 * @param int $count the number of rows to query
1294 * @param string $table the table to query from
1295 * @param bool $is_related_query
1296 * @return string SQL insert statement
1298 public function generateInsertSQL(SugarBean $bean, $select_query, $start, $count = -1, $table, $is_related_query = false)
1300 $this->log->info('call to DBManager::generateInsertSQL() is deprecated');
1301 global $sugar_config;
1304 $count_query = $bean->create_list_count_query($select_query);
1305 if(!empty($count_query))
1307 // We have a count query. Run it and get the results.
1308 $result = $this->query($count_query, true, "Error running count query for $this->object_name List: ");
1309 $assoc = $this->fetchByAssoc($result);
1310 if(!empty($assoc['c']))
1312 $rows_found = $assoc['c'];
1316 $count = $sugar_config['list_max_entries_per_page'];
1318 $next_offset = $start + $count;
1320 $result = $this->limitQuery($select_query, $start, $count);
1322 $sql = "INSERT INTO ".$table;
1323 $custom_sql = "INSERT INTO ".$table."_cstm";
1325 // get field definitions
1326 $fields = $bean->getFieldDefinitions();
1327 $custom_fields = array();
1329 if($bean->hasCustomFields()){
1330 foreach ($fields as $fieldDef){
1331 if($fieldDef['source'] == 'custom_fields'){
1332 $custom_fields[$fieldDef['name']] = $fieldDef['name'];
1335 if(!empty($custom_fields)){
1336 $custom_fields['id_c'] = 'id_c';
1337 $id_field = array('name' => 'id_c', 'custom_type' => 'id',);
1338 $fields[] = $id_field;
1342 // get column names and values
1343 $row_array = array();
1345 $cstm_row_array = array();
1346 $cstm_columns = array();
1347 $built_columns = false;
1348 while(($row = $this->fetchByAssoc($result)) != null)
1351 $cstm_values = array();
1352 if(!$is_related_query){
1353 foreach ($fields as $fieldDef)
1355 if(isset($fieldDef['source']) && $fieldDef['source'] != 'db' && $fieldDef['source'] != 'custom_fields') continue;
1356 $val = $row[$fieldDef['name']];
1358 //handle auto increment values here only need to do this on insert not create
1359 if ($fieldDef['name'] == 'deleted'){
1360 $values['deleted'] = $val;
1361 if(!$built_columns){
1362 $columns[] = 'deleted';
1367 $type = $fieldDef['type'];
1368 if(!empty($fieldDef['custom_type'])){
1369 $type = $fieldDef['custom_type'];
1371 // need to do some thing about types of values
1372 if($this->dbType == 'mysql' && $val == '' && ($type == 'datetime' || $type == 'date' || $type == 'int' || $type == 'currency' || $type == 'decimal')){
1373 if(!empty($custom_fields[$fieldDef['name']]))
1374 $cstm_values[$fieldDef['name']] = 'null';
1376 $values[$fieldDef['name']] = 'null';
1378 if(isset($type) && $type=='int') {
1379 if(!empty($custom_fields[$fieldDef['name']]))
1380 $cstm_values[$fieldDef['name']] = $GLOBALS['db']->quote(from_html($val));
1382 $values[$fieldDef['name']] = $GLOBALS['db']->quote(from_html($val));
1384 if(!empty($custom_fields[$fieldDef['name']]))
1385 $cstm_values[$fieldDef['name']] = "'".$GLOBALS['db']->quote(from_html($val))."'";
1387 $values[$fieldDef['name']] = "'".$GLOBALS['db']->quote(from_html($val))."'";
1390 if(!$built_columns){
1391 if(!empty($custom_fields[$fieldDef['name']]))
1392 $cstm_columns[] = $fieldDef['name'];
1394 $columns[] = $fieldDef['name'];
1400 foreach ($row as $key=>$val)
1402 if($key != 'orc_row'){
1403 $values[$key] = "'$val'";
1404 if(!$built_columns){
1410 $built_columns = true;
1411 if(!empty($values)){
1412 $row_array[] = $values;
1414 if(!empty($cstm_values) && !empty($cstm_values['id_c']) && (strlen($cstm_values['id_c']) > 7)){
1415 $cstm_row_array[] = $cstm_values;
1419 //if (sizeof ($values) == 0) return ""; // no columns set
1421 // get the entire sql
1422 $sql .= "(".implode(",", $columns).") ";
1424 for($i = 0; $i < count($row_array); $i++){
1425 $sql .= " (".implode(",", $row_array[$i]).")";
1426 if($i < (count($row_array) - 1)){
1431 // get the entire sql
1432 $custom_sql .= "(".implode(",", $cstm_columns).") ";
1433 $custom_sql .= "VALUES";
1435 for($i = 0; $i < count($cstm_row_array); $i++){
1436 $custom_sql .= " (".implode(",", $cstm_row_array[$i]).")";
1437 if($i < (count($cstm_row_array) - 1)){
1438 $custom_sql .= ", ";
1441 return array('data' => $sql, 'cstm_sql' => $custom_sql, /*'result_count' => $row_count, */ 'total_count' => $rows_found, 'next_offset' => $next_offset);
1446 * Disconnects all instances
1448 public function disconnectAll()
1450 DBManagerFactory::disconnectAll();
1454 * This function sets the query threshold limit
1456 * @param int $limit value of query threshold limit
1458 public static function setQueryLimit($limit)
1460 //reset the queryCount
1461 self::$queryCount = 0;
1462 self::$queryLimit = $limit;
1466 * Returns the static queryCount value
1468 * @return int value of the queryCount static variable
1470 public static function getQueryCount()
1472 return self::$queryCount;
1477 * Resets the queryCount value to 0
1480 public static function resetQueryCount()
1482 self::$queryCount = 0;
1486 * This function increments the global $sql_queries variable
1488 public function countQuery()
1490 if (self::$queryLimit != 0 && ++self::$queryCount > self::$queryLimit
1491 &&(empty($GLOBALS['current_user']) || !is_admin($GLOBALS['current_user']))) {
1492 require_once('include/resource/ResourceManager.php');
1493 $resourceManager = ResourceManager::getInstance();
1494 $resourceManager->notifyObservers('ERR_QUERY_LIMIT');
1499 * Pre-process string for quoting
1501 * @param string $string
1504 protected function quoteInternal($string)
1506 return from_html($string);
1510 * Return string properly quoted with ''
1511 * @param string $string
1514 public function quoted($string)
1516 return "'".$this->quote($string)."'";
1520 * Quote value according to type
1521 * Numerics aren't quoted
1522 * Dates are converted and quoted
1523 * Rest is just quoted
1524 * @param string $type
1525 * @param string $value
1526 * @return string Quoted value
1528 public function quoteType($type, $value)
1530 if($type == 'date') {
1531 return $this->convert($this->quoted($value), "date");
1533 if($type == 'time') {
1534 return $this->convert($this->quoted($value), "time");
1536 if(isset($this->type_class[$type]) && $this->type_class[$type] == "date") {
1537 return $this->convert($this->quoted($value), "datetime");
1539 if($this->isNumericType($type)) {
1540 return 0+$value; // ensure it's numeric
1543 return $this->quoted($value);
1547 * Quote the strings of the passed in array
1549 * The array must only contain strings
1551 * @param array $array
1552 * @return array Quoted strings
1554 public function arrayQuote(array &$array)
1556 foreach($array as &$val) {
1557 $val = $this->quote($val);
1563 * Frees out previous results
1565 * @param resource|bool $result optional, pass if you want to free a single result instead of all results
1567 protected function freeResult($result = false)
1570 $this->freeDbResult($result);
1572 if($this->lastResult) {
1573 $this->freeDbResult($this->lastResult);
1574 $this->lastResult = null;
1580 * Check if query has LIMIT clause
1581 * Relevant for now only for Mysql
1582 * @param string $sql
1585 protected function hasLimit($sql)
1591 * Runs a query and returns a single row containing single value
1593 * @param string $sql SQL Statement to execute
1594 * @param bool $dieOnError True if we want to call die if the query returns errors
1595 * @param string $msg Message to log if error occurs
1596 * @return array single value from the query
1598 public function getOne($sql, $dieOnError = false, $msg = '')
1600 $this->log->info("Get One: |$sql|");
1601 if(!$this->hasLimit($sql)) {
1602 $queryresult = $this->limitQuery($sql, 0, 1, $dieOnError, $msg);
1604 // support old code that passes LIMIT to sql
1605 // works only for mysql, so do not rely on this
1606 $queryresult = $this->query($sql, $dieOnError, $msg);
1608 $this->checkError($msg.' Get One Failed:' . $sql, $dieOnError);
1609 if (!$queryresult) return false;
1610 $row = $this->fetchByAssoc($queryresult);
1612 return array_shift($row);
1618 * Runs a query and returns a single row
1620 * @param string $sql SQL Statement to execute
1621 * @param bool $dieOnError True if we want to call die if the query returns errors
1622 * @param string $msg Message to log if error occurs
1623 * @param bool $suppress Message to log if error occurs
1624 * @return array single row from the query
1626 public function fetchOne($sql, $dieOnError = false, $msg = '', $suppress = false)
1628 $this->log->info("Fetch One: |$sql|");
1629 $this->checkConnection();
1630 $queryresult = $this->query($sql, $dieOnError, $msg);
1631 $this->checkError($msg.' Fetch One Failed:' . $sql, $dieOnError);
1633 if (!$queryresult) return false;
1635 $row = $this->fetchByAssoc($queryresult);
1636 if ( !$row ) return false;
1638 $this->freeResult($queryresult);
1643 * Returns the number of rows affected by the last query
1645 * See also affected_rows capability, will return 0 unless the DB supports it
1646 * @param resource $result query result resource
1649 public function getAffectedRowCount($result)
1655 * Returns the number of rows returned by the result
1657 * This function can't be reliably implemented on most DB, do not use it.
1660 * @param resource $result
1663 public function getRowCount($result)
1669 * Get table description
1670 * @param string $tablename
1671 * @param bool $reload true means load from DB, false allows using cache
1672 * @return array Vardef-format table description
1675 public function getTableDescription($tablename, $reload = false)
1677 if($reload || empty(self::$table_descriptions[$tablename])) {
1678 self::$table_descriptions[$tablename] = $this->get_columns($tablename);
1680 return self::$table_descriptions[$tablename];
1684 * Returns the field description for a given field in table
1686 * @param string $name
1687 * @param string $tablename
1690 protected function describeField($name, $tablename)
1692 $table = $this->getTableDescription($tablename);
1693 if(!empty($table) && isset($table[$name]))
1694 return $table[$name];
1696 $table = $this->getTableDescription($tablename, true);
1698 if(isset($table[$name]))
1699 return $table[$name];
1705 * Returns the index description for a given index in table
1707 * @param string $name
1708 * @param string $tablename
1711 protected function describeIndex($name, $tablename)
1713 if(isset(self::$index_descriptions[$tablename]) && isset(self::$index_descriptions[$tablename]) && isset(self::$index_descriptions[$tablename][$name])){
1714 return self::$index_descriptions[$tablename][$name];
1717 self::$index_descriptions[$tablename] = $this->get_indices($tablename);
1719 if(isset(self::$index_descriptions[$tablename][$name])){
1720 return self::$index_descriptions[$tablename][$name];
1727 * Truncates a string to a given length
1729 * @param string $string
1730 * @param int $len length to trim to
1734 public function truncate($string, $len)
1736 if ( is_numeric($len) && $len > 0)
1738 $string = mb_substr($string,0,(int) $len, "UTF-8");
1744 * Returns the database string needed for concatinating multiple database strings together
1746 * @param string $table table name of the database fields to concat
1747 * @param array $fields fields in the table to concat together
1748 * @param string $space Separator between strings, default is single space
1751 public function concat($table, array $fields, $space = ' ')
1753 if(empty($fields)) return '';
1755 $space = $this->quoted($space);
1756 foreach ( $fields as $field ) {
1757 if(!empty($elems)) $elems[] = $space;
1758 $elems[] = $this->convert("$table.$field", 'IFNULL', array("''"));
1760 $first = array_shift($elems);
1761 return "LTRIM(RTRIM(".$this->convert($first, 'CONCAT', $elems)."))";
1765 * Given a sql stmt attempt to parse it into the sql and the tokens. Then return the index of this prepared statement
1766 * Tokens can come in the following forms:
1767 * ? - a scalar which will be quoted
1768 * ! - a literal which will not be quoted
1769 * & - binary data to read from a file
1771 * @param string $sql The sql to parse
1772 * @return int index of the prepared statement to be used with execute
1774 public function prepareQuery($sql)
1776 //parse out the tokens
1777 $tokens = preg_split('/((?<!\\\)[&?!])/', $sql, -1, PREG_SPLIT_DELIM_CAPTURE);
1779 //maintain a count of the actual tokens for quick reference in execute
1783 foreach ($tokens as $key => $val) {
1793 //escape any special characters
1794 $tokens[$key] = preg_replace('/\\\([&?!])/', "\\1", $val);
1795 $sqlStr .= $tokens[$key];
1800 $this->preparedTokens[] = array('tokens' => $tokens, 'tokenCount' => $count, 'sqlString' => $sqlStr);
1801 end($this->preparedTokens);
1802 return key($this->preparedTokens);
1806 * Takes a prepared stmt index and the data to replace and creates the query and runs it.
1808 * @param int $stmt The index of the prepared statement from preparedTokens
1809 * @param array $data The array of data to replace the tokens with.
1810 * @return resource result set or false on error
1812 public function executePreparedQuery($stmt, $data = array())
1814 if(!empty($this->preparedTokens[$stmt])){
1815 if(!is_array($data)){
1816 $data = array($data);
1819 $pTokens = $this->preparedTokens[$stmt];
1821 //ensure that the number of data elements matches the number of replacement tokens
1822 //we found in prepare().
1823 if(count($data) != $pTokens['tokenCount']){
1824 //error the data count did not match the token count
1830 $tokens = $pTokens['tokens'];
1831 foreach ($tokens as $val) {
1834 $query .= $this->quote($data[$dataIndex++]);
1837 $filename = $data[$dataIndex++];
1838 $query .= file_get_contents($filename);
1841 $query .= $data[$dataIndex++];
1848 return $this->query($query);
1855 * Run both prepare and execute without the client having to run both individually.
1857 * @param string $sql The sql to parse
1858 * @param array $data The array of data to replace the tokens with.
1859 * @return resource result set or false on error
1861 public function pQuery($sql, $data = array())
1863 $stmt = $this->prepareQuery($sql);
1864 return $this->executePreparedQuery($stmt, $data);
1867 /********************** SQL FUNCTIONS ****************************/
1869 * Generates sql for create table statement for a bean.
1871 * NOTE: does not handle out-of-table constraints, use createConstraintSQL for that
1872 * @param SugarBean $bean SugarBean instance
1873 * @return string SQL Create Table statement
1875 public function createTableSQL(SugarBean $bean)
1877 $tablename = $bean->getTableName();
1878 $fieldDefs = $bean->getFieldDefinitions();
1879 $indices = $bean->getIndices();
1880 return $this->createTableSQLParams($tablename, $fieldDefs, $indices);
1884 * Generates SQL for insert statement.
1886 * @param SugarBean $bean SugarBean instance
1887 * @return string SQL Create Table statement
1889 public function insertSQL(SugarBean $bean)
1891 // get column names and values
1892 $sql = $this->insertParams($bean->getTableName(), $bean->getFieldDefinitions(), get_object_vars($bean),
1893 isset($bean->field_name_map)?$bean->field_name_map:null, false);
1898 * Generates SQL for update statement.
1900 * @param SugarBean $bean SugarBean instance
1901 * @param array $where Optional, where conditions in an array
1902 * @return string SQL Create Table statement
1904 public function updateSQL(SugarBean $bean, array $where = array())
1906 $primaryField = $bean->getPrimaryFieldDefinition();
1908 $fields = $bean->getFieldDefinitions();
1909 // get column names and values
1910 foreach ($fields as $field => $fieldDef) {
1911 if (isset($fieldDef['source']) && $fieldDef['source'] != 'db') continue;
1912 // Do not write out the id field on the update statement.
1913 // We are not allowed to change ids.
1914 if ($fieldDef['name'] == $primaryField['name']) continue;
1916 // If the field is an auto_increment field, then we shouldn't be setting it. This was added
1917 // specially for Bugs and Cases which have a number associated with them.
1918 if (!empty($bean->field_name_map[$field]['auto_increment'])) continue;
1920 //custom fields handle their save separately
1921 if(isset($bean->field_name_map) && !empty($bean->field_name_map[$field]['custom_type'])) continue;
1923 // no need to clear deleted since we only update not deleted records anyway
1924 if($fieldDef['name'] == 'deleted' && empty($bean->deleted)) continue;
1926 if(isset($bean->$field)) {
1927 $val = from_html($bean->$field);
1932 if(!empty($fieldDef['type']) && $fieldDef['type'] == 'bool'){
1933 $val = $bean->getFieldValue($field);
1936 if(strlen($val) == 0) {
1937 if(isset($fieldDef['default']) && strlen($fieldDef['default']) > 0) {
1938 $val = $fieldDef['default'];
1944 if(!empty($val) && !empty($fieldDef['len']) && strlen($val) > $fieldDef['len']) {
1945 $val = $this->truncate($val, $fieldDef['len']);
1948 if(!is_null($val) || !empty($fieldDef['required'])) {
1949 $columns[] = "{$fieldDef['name']}=".$this->massageValue($val, $fieldDef);
1950 } elseif($this->isNullable($fieldDef)) {
1951 $columns[] = "{$fieldDef['name']}=NULL";
1953 $columns[] = "{$fieldDef['name']}=".$this->emptyValue($fieldDef['type']);
1957 if ( sizeof($columns) == 0 )
1958 return ""; // no columns set
1960 // build where clause
1961 $where = $this->getWhereClause($bean, $this->updateWhereArray($bean, $where));
1962 if(isset($fields['deleted'])) {
1963 $where .= " AND deleted=0";
1966 return "UPDATE ".$bean->getTableName()."
1967 SET ".implode(",", $columns)."
1972 * This method returns a where array so that it has id entry if
1973 * where is not an array or is empty
1975 * @param SugarBean $bean SugarBean instance
1976 * @param array $where Optional, where conditions in an array
1979 protected function updateWhereArray(SugarBean $bean, array $where = array())
1981 if (count($where) == 0) {
1982 $fieldDef = $bean->getPrimaryFieldDefinition();
1983 $primaryColumn = $fieldDef['name'];
1985 $val = $bean->getFieldValue($fieldDef['name']);
1987 $where[$primaryColumn] = $val;
1995 * Returns a where clause without the 'where' key word
1997 * The clause returned does not have an 'and' at the beginning and the columns
1998 * are joined by 'and'.
2000 * @param string $table table name
2001 * @param array $whereArray Optional, where conditions in an array
2004 protected function getColumnWhereClause($table, array $whereArray = array())
2007 foreach ($whereArray as $name => $val) {
2009 if (is_array($val)) {
2012 foreach ($val as $tval){
2013 $temp[] = $this->quoted($tval);
2015 $val = implode(",", $temp);
2018 $val = $this->quoted($val);
2021 $where[] = " $table.$name $op $val";
2025 return implode(" AND ", $where);
2031 * This method returns a complete where clause built from the
2032 * where values specified.
2034 * @param SugarBean $bean SugarBean that describes the table
2035 * @param array $whereArray Optional, where conditions in an array
2038 protected function getWhereClause(SugarBean $bean, array $whereArray=array())
2040 return " WHERE " . $this->getColumnWhereClause($bean->getTableName(), $whereArray);
2044 * Outputs a correct string for the sql statement according to value
2047 * @param array $fieldDef field definition
2050 public function massageValue($val, $fieldDef)
2052 $type = $this->getFieldType($fieldDef);
2054 if(isset($this->type_class[$type])) {
2055 // handle some known types
2056 switch($this->type_class[$type]) {
2059 if (!empty($fieldDef['required']) && $val == ''){
2060 if (isset($fieldDef['default'])){
2061 return $fieldDef['default'];
2065 return intval($val);
2068 if (!empty($fieldDef['required']) && $val == false){
2069 if (isset($fieldDef['default'])){
2070 return $fieldDef['default'];
2076 if (!empty($fieldDef['required']) && $val == ''){
2077 if (isset($fieldDef['default'])){
2078 return $fieldDef['default'];
2082 return floatval($val);
2085 // empty date can't be '', so convert it to either NULL or empty date value
2087 if (!empty($fieldDef['required'])) {
2088 if (isset($fieldDef['default'])) {
2089 return $fieldDef['default'];
2091 return $this->emptyValue($type);
2098 if(!empty($val) && !empty($fieldDef['len']) && strlen($val) > $fieldDef['len']) {
2099 $val = $this->truncate($val, $fieldDef['len']);
2103 if ( is_null($val) ) {
2104 if(!empty($fieldDef['required'])) {
2105 if (isset($fieldDef['default'])){
2106 return $fieldDef['default'];
2108 return $this->emptyValue($type);
2113 if($type == "datetimecombo") {
2116 return $this->convert($this->quoted($val), $type);
2120 * Massages the field defintions to fill in anything else the DB backend may add
2122 * @param array $fieldDef
2123 * @param string $tablename
2126 public function massageFieldDef(&$fieldDef, $tablename)
2128 if ( !isset($fieldDef['dbType']) ) {
2129 if ( isset($fieldDef['dbtype']) )
2130 $fieldDef['dbType'] = $fieldDef['dbtype'];
2132 $fieldDef['dbType'] = $fieldDef['type'];
2134 $type = $this->getColumnType($fieldDef['dbType'],$fieldDef['name'],$tablename);
2136 // len can be a number or a string like 'max', for example, nvarchar(max)
2137 preg_match_all('/(\w+)(?:\(([0-9]+,?[0-9]*|\w+)\)|)/i', $type, $matches);
2138 if ( isset($matches[1][0]) )
2139 $fieldDef['type'] = $matches[1][0];
2140 if ( isset($matches[2][0]) && empty($fieldDef['len']) )
2141 $fieldDef['len'] = $matches[2][0];
2142 if ( !empty($fieldDef['precision']) && is_numeric($fieldDef['precision']) && !strstr($fieldDef['len'],',') )
2143 $fieldDef['len'] .= ",{$fieldDef['precision']}";
2144 if (!empty($fieldDef['required']) || ($fieldDef['name'] == 'id' && !isset($fieldDef['required'])) ) {
2145 $fieldDef['required'] = 'true';
2150 * Take an SQL statement and produce a list of fields used in that select
2151 * @param string $selectStatement
2154 public function getSelectFieldsFromQuery($selectStatement)
2156 $selectStatement = trim($selectStatement);
2157 if (strtoupper(substr($selectStatement, 0, 6)) == "SELECT")
2158 $selectStatement = trim(substr($selectStatement, 6));
2160 //Due to sql functions existing in many selects, we can't use php explode
2164 $strLen = strlen($selectStatement);
2165 for($i = 0; $i < $strLen; $i++)
2167 $char = $selectStatement[$i];
2169 if ($char == "," && $level == 0)
2171 $field = $this->getFieldNameFromSelect(trim($selectField));
2172 $fields[$field] = $selectField;
2175 else if ($char == "("){
2177 $selectField .= $char;
2179 else if($char == ")"){
2181 $selectField .= $char;
2185 $selectField .= $char;
2189 $fields[$this->getFieldNameFromSelect($selectField)] = $selectField;
2194 * returns the field name used in a select
2195 * @param string $string SELECT query
2198 protected function getFieldNameFromSelect($string)
2200 if(strncasecmp($string, "DISTINCT ", 9) == 0) {
2201 $string = substr($string, 9);
2203 if (stripos($string, " as ") !== false)
2204 //"as" used for an alias
2205 return trim(substr($string, strripos($string, " as ") + 4));
2206 else if (strrpos($string, " ") != 0)
2207 //Space used as a delimiter for an alias
2208 return trim(substr($string, strrpos($string, " ")));
2209 else if (strpos($string, ".") !== false)
2210 //No alias, but a table.field format was used
2211 return substr($string, strpos($string, ".") + 1);
2213 //Give up and assume the whole thing is the field name
2218 * Generates SQL for delete statement identified by id.
2220 * @param SugarBean $bean SugarBean instance
2221 * @param array $where where conditions in an array
2222 * @return string SQL Update Statement
2224 public function deleteSQL(SugarBean $bean, array $where)
2226 $where = $this->getWhereClause($bean, $this->updateWhereArray($bean, $where));
2227 return "UPDATE ".$bean->getTableName()." SET deleted=1 $where";
2231 * Generates SQL for select statement for any bean identified by id.
2233 * @param SugarBean $bean SugarBean instance
2234 * @param array $where where conditions in an array
2235 * @return string SQL Select Statement
2237 public function retrieveSQL(SugarBean $bean, array $where)
2239 $where = $this->getWhereClause($bean, $this->updateWhereArray($bean, $where));
2240 return "SELECT * FROM ".$bean->getTableName()." $where AND deleted=0";
2244 * This method implements a generic sql for a collection of beans.
2246 * Currently, this function does not support outer joins.
2248 * @param array $beans Array of values returned by get_class method as the keys and a bean as
2249 * the value for that key. These beans will be joined in the sql by the key
2250 * attribute of field defs.
2251 * @param array $cols Optional, columns to be returned with the keys as names of bean
2252 * as identified by get_class of bean. Values of this array is the array of fieldDefs
2253 * to be returned for a bean. If an empty array is passed, all columns are selected.
2254 * @param array $whereClause Optional, values with the keys as names of bean as identified
2255 * by get_class of bean. Each value at the first level is an array of values for that
2256 * bean identified by name of fields. If we want to pass multiple values for a name,
2257 * pass it as an array. If where is not passed, all the rows will be returned.
2259 * @return string SQL Select Statement
2261 public function retrieveViewSQL(array $beans, array $cols = array(), array $whereClause = array())
2263 $relations = array(); // stores relations between tables as they are discovered
2264 $where = $select = array();
2265 foreach ($beans as $beanID => $bean) {
2266 $tableName = $bean->getTableName();
2267 $beanTables[$beanID] = $tableName;
2270 $tables[$table] = $tableName;
2271 $aliases[$tableName][] = $table;
2273 // build part of select for this table
2274 if (is_array($cols[$beanID]))
2275 foreach ($cols[$beanID] as $def) $select[] = $table.".".$def['name'];
2277 // build part of where clause
2278 if (is_array($whereClause[$beanID])){
2279 $where[] = $this->getColumnWhereClause($table, $whereClause[$beanID]);
2281 // initialize so that it can be used properly in form clause generation
2282 $table_used_in_from[$table] = false;
2284 $indices = $bean->getIndices();
2285 foreach ($indices as $index){
2286 if ($index['type'] == 'foreign') {
2287 $relationship[$table][] = array('foreignTable'=> $index['foreignTable']
2288 ,'foreignColumn'=>$index['foreignField']
2289 ,'localColumn'=> $index['fields']
2293 $where[] = " $table.deleted = 0";
2296 // join these clauses
2297 $select = !empty($select) ? implode(",", $select) : "*";
2298 $where = implode(" AND ", $where);
2300 // generate the from clause. Use relations array to generate outer joins
2301 // all the rest of the tables will be used as a simple from
2302 // relations table define relations between table1 and table2 through column on table 1
2303 // table2 is assumed to joining through primary key called id
2305 $from = ''; $table_used_in_from = array();
2306 foreach ($relations as $table1 => $rightsidearray){
2307 if ($table_used_in_from[$table1]) continue; // table has been joined
2309 $from .= $separator." ".$table1;
2310 $table_used_in_from[$table1] = true;
2311 foreach ($rightsidearray as $tablearray){
2312 $table2 = $tablearray['foreignTable']; // get foreign table
2313 $tableAlias = $aliases[$table2]; // get a list of aliases for this table
2314 foreach ($tableAlias as $table2) {
2315 //choose first alias that does not match
2316 // we are doing this because of self joins.
2317 // in case of self joins, the same table will have many aliases.
2318 if ($table2 != $table1) break;
2321 $col = $tablearray['foreingColumn'];
2322 $name = $tablearray['localColumn'];
2323 $from .= " LEFT JOIN $table on ($table1.$name = $table2.$col)";
2324 $table_used_in_from[$table2] = true;
2329 return "SELECT $select FROM $from WHERE $where";
2333 * Generates SQL for create index statement for a bean.
2335 * @param SugarBean $bean SugarBean instance
2336 * @param array $fields fields used in the index
2337 * @param string $name index name
2338 * @param bool $unique Optional, set to true if this is an unique index
2339 * @return string SQL Select Statement
2341 public function createIndexSQL(SugarBean $bean, array $fields, $name, $unique = true)
2343 $unique = ($unique) ? "unique" : "";
2344 $tablename = $bean->getTableName();
2347 foreach ($fields as $fieldDef)
2348 $columns[] = $fieldDef['name'];
2350 if (empty($columns))
2353 $columns = implode(",", $columns);
2355 return "CREATE $unique INDEX $name ON $tablename ($columns)";
2359 * Returns the type of the variable in the field
2361 * @param array $fieldDef Vardef-format field def
2364 public function getFieldType($fieldDef)
2366 // get the type for db type. if that is not set,
2367 // get it from type. This is done so that
2368 // we do not have change a lot of existing code
2369 // and add dbtype where type is being used for some special
2370 // purposes like referring to foreign table etc.
2371 if(!empty($fieldDef['dbType']))
2372 return $fieldDef['dbType'];
2373 if(!empty($fieldDef['dbtype']))
2374 return $fieldDef['dbtype'];
2375 if (!empty($fieldDef['type']))
2376 return $fieldDef['type'];
2377 if (!empty($fieldDef['Type']))
2378 return $fieldDef['Type'];
2379 if (!empty($fieldDef['data_type']))
2380 return $fieldDef['data_type'];
2386 * retrieves the different components from the passed column type as it is used in the type mapping and vardefs
2387 * type format: <baseType>[(<len>[,<scale>])]
2388 * @param string $type Column type
2389 * @return array|bool array containing the different components of the passed in type or false in case the type contains illegal characters
2391 public function getTypeParts($type)
2393 if(preg_match("#(?P<type>\w+)\s*(?P<arg>\((?P<len>\w+)\s*(,\s*(?P<scale>\d+))*\))*#", $type, $matches))
2395 $return = array(); // Not returning matches array as such as we don't want to expose the regex make up on the interface
2396 $return['baseType'] = $matches['type'];
2397 if( isset($matches['arg'])) {
2398 $return['arg'] = $matches['arg'];
2400 if( isset($matches['len'])) {
2401 $return['len'] = $matches['len'];
2403 if( isset($matches['scale'])) {
2404 $return['scale'] = $matches['scale'];
2413 * Returns the defintion for a single column
2415 * @param array $fieldDef Vardef-format field def
2416 * @param bool $ignoreRequired Optional, true if we should ignore this being a required field
2417 * @param string $table Optional, table name
2418 * @param bool $return_as_array Optional, true if we should return the result as an array instead of sql
2419 * @return string or array if $return_as_array is true
2421 protected function oneColumnSQLRep($fieldDef, $ignoreRequired = false, $table = '', $return_as_array = false)
2423 $name = $fieldDef['name'];
2424 $type = $this->getFieldType($fieldDef);
2425 $colType = $this->getColumnType($type);
2427 if($parts = $this->getTypeParts($colType))
2429 $colBaseType = $parts['baseType'];
2430 $defLen = isset($parts['len']) ? $parts['len'] : '255'; // Use the mappings length (precision) as default if it exists
2433 if(!empty($fieldDef['len'])) {
2434 if (in_array($colBaseType, array( 'nvarchar', 'nchar', 'varchar', 'varchar2', 'char',
2435 'clob', 'blob', 'text'))) {
2436 $colType = "$colBaseType(${fieldDef['len']})";
2437 } elseif(($colBaseType == 'decimal' || $colBaseType == 'float')){
2438 if(!empty($fieldDef['precision']) && is_numeric($fieldDef['precision']))
2439 if(strpos($fieldDef['len'],',') === false){
2440 $colType = $colBaseType . "(".$fieldDef['len'].",".$fieldDef['precision'].")";
2442 $colType = $colBaseType . "(".$fieldDef['len'].")";
2445 $colType = $colBaseType . "(".$fieldDef['len'].")";
2448 if (in_array($colBaseType, array( 'nvarchar', 'nchar', 'varchar', 'varchar2', 'char'))) {
2449 $colType = "$colBaseType($defLen)";
2455 // Bug #52610 We should have ability don't add DEFAULT part to query for boolean fields
2456 if (!empty($fieldDef['no_default']))
2460 elseif (isset($fieldDef['default']) && strlen($fieldDef['default']) > 0)
2462 $default = " DEFAULT ".$this->quoted($fieldDef['default']);
2464 elseif (!isset($default) && $type == 'bool')
2466 $default = " DEFAULT 0 ";
2469 $auto_increment = '';
2470 if(!empty($fieldDef['auto_increment']) && $fieldDef['auto_increment'])
2471 $auto_increment = $this->setAutoIncrement($table , $fieldDef['name']);
2473 $required = 'NULL'; // MySQL defaults to NULL, SQL Server defaults to NOT NULL -- must specify
2474 //Starting in 6.0, only ID and auto_increment fields will be NOT NULL in the DB.
2475 if ((empty($fieldDef['isnull']) || strtolower($fieldDef['isnull']) == 'false') &&
2476 (!empty($auto_increment) || $name == 'id' || ($fieldDef['type'] == 'id' && !empty($fieldDef['required'])))) {
2477 $required = "NOT NULL";
2479 // If the field is marked both required & isnull=>false - alwqys make it not null
2480 // Use this to ensure primary key fields never defined as null
2481 if(isset($fieldDef['isnull']) && (strtolower($fieldDef['isnull']) == 'false' || $fieldDef['isnull'] === false)
2482 && !empty($fieldDef['required'])) {
2483 $required = "NOT NULL";
2485 if ($ignoreRequired)
2488 if ( $return_as_array ) {
2491 'colType' => $colType,
2492 'colBaseType' => $colBaseType, // Adding base type for easier processing in derived classes
2493 'default' => $default,
2494 'required' => $required,
2495 'auto_increment' => $auto_increment,
2496 'full' => "$name $colType $default $required $auto_increment",
2499 return "$name $colType $default $required $auto_increment";
2504 * Returns SQL defintions for all columns in a table
2506 * @param array $fieldDefs Vardef-format field def
2507 * @param bool $ignoreRequired Optional, true if we should ignor this being a required field
2508 * @param string $tablename Optional, table name
2509 * @return string SQL column definitions
2511 protected function columnSQLRep($fieldDefs, $ignoreRequired = false, $tablename)
2515 if ($this->isFieldArray($fieldDefs)) {
2516 foreach ($fieldDefs as $fieldDef) {
2517 if(!isset($fieldDef['source']) || $fieldDef['source'] == 'db') {
2518 $columns[] = $this->oneColumnSQLRep($fieldDef,false, $tablename);
2521 $columns = implode(",", $columns);
2524 $columns = $this->oneColumnSQLRep($fieldDefs,$ignoreRequired, $tablename);
2531 * Returns the next value for an auto increment
2533 * @param string $table Table name
2534 * @param string $field_name Field name
2537 public function getAutoIncrement($table, $field_name)
2543 * Returns the sql for the next value in a sequence
2545 * @param string $table Table name
2546 * @param string $field_name Field name
2549 public function getAutoIncrementSQL($table, $field_name)
2555 * Either creates an auto increment through queries or returns sql for auto increment
2556 * that can be appended to the end of column defination (mysql)
2558 * @param string $table Table name
2559 * @param string $field_name Field name
2562 protected function setAutoIncrement($table, $field_name)
2564 $this->deleteAutoIncrement($table, $field_name);
2569 * Sets the next auto-increment value of a column to a specific value.
2571 * @param string $table Table name
2572 * @param string $field_name Field name
2573 * @param int $start_value Starting autoincrement value
2577 public function setAutoIncrementStart($table, $field_name, $start_value)
2583 * Deletes an auto increment
2585 * @param string $table tablename
2586 * @param string $field_name
2588 public function deleteAutoIncrement($table, $field_name)
2594 * This method generates sql for adding a column to table identified by field def.
2596 * @param string $tablename
2597 * @param array $fieldDefs
2598 * @return string SQL statement
2600 public function addColumnSQL($tablename, $fieldDefs)
2602 return $this->changeColumnSQL($tablename, $fieldDefs, 'add');
2606 * This method genrates sql for altering old column identified by oldFieldDef to new fieldDef.
2608 * @param string $tablename
2609 * @param array $newFieldDefs
2610 * @param bool $ignorerequired Optional, true if we should ignor this being a required field
2611 * @return string|array SQL statement(s)
2613 public function alterColumnSQL($tablename, $newFieldDefs, $ignorerequired = false)
2615 return $this->changeColumnSQL($tablename, $newFieldDefs, 'modify', $ignorerequired);
2619 * Generates SQL for dropping a table.
2621 * @param SugarBean $bean Sugarbean instance
2622 * @return string SQL statement
2624 public function dropTableSQL(SugarBean $bean)
2626 return $this->dropTableNameSQL($bean->getTableName());
2630 * Generates SQL for dropping a table.
2632 * @param string $name table name
2633 * @return string SQL statement
2635 public function dropTableNameSQL($name)
2637 return "DROP TABLE ".$name;
2641 * Generates SQL for truncating a table.
2642 * @param string $name table name
2645 public function truncateTableSQL($name)
2647 return "TRUNCATE $name";
2651 * This method generates sql that deletes a column identified by fieldDef.
2653 * @param SugarBean $bean Sugarbean instance
2654 * @param array $fieldDefs
2655 * @return string SQL statement
2657 public function deleteColumnSQL(SugarBean $bean, $fieldDefs)
2659 return $this->dropColumnSQL($bean->getTableName(), $fieldDefs);
2663 * This method generates sql that drops a column identified by fieldDef.
2664 * Designed to work like the other addColumnSQL() and alterColumnSQL() functions
2666 * @param string $tablename
2667 * @param array $fieldDefs
2668 * @return string SQL statement
2670 public function dropColumnSQL($tablename, $fieldDefs)
2672 return $this->changeColumnSQL($tablename, $fieldDefs, 'drop');
2676 * Return a version of $proposed that can be used as a column name in any of our supported databases
2677 * Practically this means no longer than 25 characters as the smallest identifier length for our supported DBs is 30 chars for Oracle plus we add on at least four characters in some places (for indicies for example)
2678 * @param string|array $name Proposed name for the column
2679 * @param bool|string $ensureUnique Ensure the name is unique
2680 * @param string $type Name type (table, column)
2681 * @param bool $force Force new name
2682 * @return string|array Valid column name trimmed to right length and with invalid characters removed
2684 public function getValidDBName($name, $ensureUnique = false, $type = 'column', $force = false)
2686 if(is_array($name)) {
2688 foreach($name as $field) {
2689 $result[] = $this->getValidDBName($field, $ensureUnique, $type);
2693 if(strchr($name, ".")) {
2694 // this is a compound name with dots, handle separately
2695 $parts = explode(".", $name);
2696 if(count($parts) > 2) {
2697 // some weird name, cut to table.name
2698 array_splice($parts, 0, count($parts)-2);
2700 $parts = $this->getValidDBName($parts, $ensureUnique, $type, $force);
2701 return join(".", $parts);
2703 // first strip any invalid characters - all but word chars (which is alphanumeric and _)
2704 $name = preg_replace( '/[^\w]+/i', '', $name ) ;
2705 $len = strlen( $name ) ;
2706 $maxLen = empty($this->maxNameLengths[$type]) ? $this->maxNameLengths[$type]['column'] : $this->maxNameLengths[$type];
2707 if ($len <= $maxLen && !$force) {
2708 return strtolower($name);
2710 if ($ensureUnique) {
2711 $md5str = md5($name);
2712 $tail = substr ( $name, -11) ;
2713 $temp = substr($md5str , strlen($md5str)-4 );
2714 $result = substr( $name, 0, 10) . $temp . $tail ;
2716 $result = substr( $name, 0, 11) . substr( $name, 11 - $maxLen);
2719 return strtolower( $result ) ;
2724 * Returns the valid type for a column given the type in fieldDef
2726 * @param string $type field type
2727 * @return string valid type for the given field
2729 public function getColumnType($type)
2731 return isset($this->type_map[$type])?$this->type_map[$type]:$type;
2735 * Checks to see if passed array is truely an array of defitions
2737 * Such an array may have type as a key but it will point to an array
2738 * for a true array of definitions an to a col type for a definition only
2740 * @param mixed $defArray
2743 public function isFieldArray($defArray)
2745 if ( !is_array($defArray) )
2748 if ( isset($defArray['type']) ){
2749 // type key exists. May be an array of defs or a simple definition
2750 return is_array($defArray['type']); // type is not an array => definition else array
2753 // type does not exist. Must be array of definitions
2758 * returns true if the type can be mapped to a valid column type
2760 * @param string $type
2763 protected function validColumnType($type)
2765 $type = $this->getColumnType($type);
2766 return !empty($type);
2770 * Generate query for audit table
2771 * @param SugarBean $bean SugarBean that was changed
2772 * @param array $changes List of changes, contains 'before' and 'after'
2773 * @return string Audit table INSERT query
2775 protected function auditSQL(SugarBean $bean, $changes)
2777 global $current_user;
2778 $sql = "INSERT INTO ".$bean->get_audit_table_name();
2779 //get field defs for the audit table.
2780 require('metadata/audit_templateMetaData.php');
2781 $fieldDefs = $dictionary['audit']['fields'];
2784 $values['id'] = $this->massageValue(create_guid(), $fieldDefs['id']);
2785 $values['parent_id']= $this->massageValue($bean->id, $fieldDefs['parent_id']);
2786 $values['field_name']= $this->massageValue($changes['field_name'], $fieldDefs['field_name']);
2787 $values['data_type'] = $this->massageValue($changes['data_type'], $fieldDefs['data_type']);
2788 if ($changes['data_type']=='text') {
2789 $values['before_value_text'] = $this->massageValue($changes['before'], $fieldDefs['before_value_text']);
2790 $values['after_value_text'] = $this->massageValue($changes['after'], $fieldDefs['after_value_text']);
2792 $values['before_value_string'] = $this->massageValue($changes['before'], $fieldDefs['before_value_string']);
2793 $values['after_value_string'] = $this->massageValue($changes['after'], $fieldDefs['after_value_string']);
2795 $values['date_created'] = $this->massageValue(TimeDate::getInstance()->nowDb(), $fieldDefs['date_created'] );
2796 $values['created_by'] = $this->massageValue($current_user->id, $fieldDefs['created_by']);
2798 $sql .= "(".implode(",", array_keys($values)).") ";
2799 $sql .= "VALUES(".implode(",", $values).")";
2804 * Saves changes to module's audit table
2806 * @param SugarBean $bean Sugarbean instance that was changed
2807 * @param array $changes List of changes, contains 'before' and 'after'
2808 * @return bool query result
2811 public function save_audit_records(SugarBean $bean, $changes)
2813 return $this->query($this->auditSQL($bean, $changes));
2817 * Finds fields whose value has changed.
2818 * The before and after values are stored in the bean.
2819 * Uses $bean->fetched_row && $bean->fetched_rel_row to compare
2821 * @param SugarBean $bean Sugarbean instance that was changed
2822 * @param array|null $field_filter Array of filter names to be inspected (NULL means all fields)
2825 public function getDataChanges(SugarBean &$bean, array $field_filter = null)
2827 $changed_values=array();
2829 $fetched_row = array();
2830 if (is_array($bean->fetched_row))
2832 $fetched_row = array_merge($bean->fetched_row, $bean->fetched_rel_row);
2837 $field_defs = $bean->field_defs;
2839 if (is_array($field_filter)) {
2840 $field_defs = array_intersect_key($field_defs, array_flip($field_filter));
2843 // remove fields which do not present in fetched row
2844 $field_defs = array_intersect_key($field_defs, $fetched_row);
2846 // remove fields which do not exist as bean property
2847 $field_defs = array_intersect_key($field_defs, (array) $bean);
2849 foreach ($field_defs as $field => $properties) {
2850 $before_value = $fetched_row[$field];
2851 $after_value=$bean->$field;
2852 if (isset($properties['type'])) {
2853 $field_type=$properties['type'];
2855 if (isset($properties['dbType'])) {
2856 $field_type=$properties['dbType'];
2858 else if(isset($properties['data_type'])) {
2859 $field_type=$properties['data_type'];
2862 $field_type=$properties['dbtype'];
2866 //Because of bug #25078(sqlserver haven't 'date' type, trim extra "00:00:00" when insert into *_cstm table).
2867 // so when we read the audit datetime field from sqlserver, we have to replace the extra "00:00:00" again.
2868 if(!empty($field_type) && $field_type == 'date'){
2869 $before_value = $this->fromConvert($before_value , $field_type);
2871 //if the type and values match, do nothing.
2872 if (!($this->_emptyValue($before_value,$field_type) && $this->_emptyValue($after_value,$field_type))) {
2873 if (trim($before_value) !== trim($after_value)) {
2874 // Bug #42475: Don't directly compare numeric values, instead do the subtract and see if the comparison comes out to be "close enough", it is necessary for floating point numbers.
2875 // Manual merge of fix 95727f2eed44852f1b6bce9a9eccbe065fe6249f from DBHelper
2876 // This fix also fixes Bug #44624 in a more generic way and therefore eliminates the need for fix 0a55125b281c4bee87eb347709af462715f33d2d in DBHelper
2877 if (!($this->isNumericType($field_type) &&
2879 2*((trim($before_value)+0)-(trim($after_value)+0))/((trim($before_value)+0)+(trim($after_value)+0)) // Using relative difference so that it also works for other numerical types besides currencies
2880 )<0.0000000001)) { // Smaller than 10E-10
2881 if (!($this->isBooleanType($field_type) && ($this->_getBooleanValue($before_value)== $this->_getBooleanValue($after_value)))) {
2882 $changed_values[$field]=array('field_name'=>$field,
2883 'data_type'=>$field_type,
2884 'before'=>$before_value,
2885 'after'=>$after_value);
2892 return $changed_values;
2896 * Uses the audit enabled fields array to find fields whose value has changed.
2897 * The before and after values are stored in the bean.
2898 * Uses $bean->fetched_row && $bean->fetched_rel_row to compare
2900 * @param SugarBean $bean Sugarbean instance that was changed
2903 public function getAuditDataChanges(SugarBean $bean)
2905 $audit_fields = $bean->getAuditEnabledFieldDefinitions();
2906 return $this->getDataChanges($bean, array_keys($audit_fields));
2913 public function full_text_indexing_setup()
2915 // Most DBs have nothing to setup, so provide default empty function
2919 * Quotes a string for storing in the database
2921 * Return value will be not surrounded by quotes
2923 * @param string $string
2926 public function escape_quote($string)
2928 return $this->quote($string);
2932 * Quotes a string for storing in the database
2934 * Return value will be not surrounded by quotes
2936 * @param string $string
2939 public function quoteFormEmail($string)
2941 return $this->quote($string);
2945 * Renames an index using fields definition
2947 * @param array $old_definition
2948 * @param array $new_definition
2949 * @param string $table_name
2950 * @return string SQL statement
2952 public function renameIndexDefs($old_definition, $new_definition, $table_name)
2954 return array($this->add_drop_constraint($table_name,$old_definition,true),
2955 $this->add_drop_constraint($table_name,$new_definition), false);
2959 * Check if type is boolean
2960 * @param string $type
2963 public function isBooleanType($type)
2965 return 'bool' == $type;
2969 * Get truth value for boolean type
2970 * Allows 'off' to mean false, along with all 'empty' values
2974 protected function _getBooleanValue($val)
2976 //need to put the === sign here otherwise true == 'non empty string'
2977 if (empty($val) or $val==='off')
2984 * Check if type is a number
2985 * @param string $type
2988 public function isNumericType($type)
2990 if(isset($this->type_class[$type]) && ($this->type_class[$type] == 'int' || $this->type_class[$type] == 'float')) {
2997 * Check if the value is empty value for this type
2998 * @param mixed $val Value
2999 * @param string $type Type (one of vardef types)
3000 * @return bool true if the value if empty
3002 protected function _emptyValue($val, $type)
3007 if($this->emptyValue($type) == $val) {
3022 if ($val == '0000-00-00')
3034 * Does this type represent text (i.e., non-varchar) value?
3035 * @param string $type
3038 public function isTextType($type)
3044 * Check if this DB supports certain capability
3045 * See $this->capabilities for the list
3046 * @param string $cap
3049 public function supports($cap)
3051 return !empty($this->capabilities[$cap]);
3055 * Create ORDER BY clause for ENUM type field
3056 * @param string $order_by Field name
3057 * @param array $values Possible enum value
3058 * @param string $order_dir Order direction, ASC or DESC
3061 public function orderByEnum($order_by, $values, $order_dir)
3064 $order_by_arr = array();
3065 foreach ($values as $key => $value) {
3067 $order_by_arr[] = "WHEN ($order_by='' OR $order_by IS NULL) THEN $i";
3069 $order_by_arr[] = "WHEN $order_by=".$this->quoted($key)." THEN $i";
3073 return "CASE ".implode("\n", $order_by_arr)." ELSE $i END $order_dir\n";
3077 * Return representation of an empty value depending on type
3078 * The value is fully quoted, converted, etc.
3079 * @param string $type
3080 * @return mixed Empty value
3082 public function emptyValue($type)
3084 if(isset($this->type_class[$type]) && ($this->type_class[$type] == 'bool' || $this->type_class[$type] == 'int' || $this->type_class[$type] == 'float')) {
3092 * List of available collation settings
3096 public function getDefaultCollation()
3102 * List of available collation settings
3106 public function getCollationList()
3112 * Returns the number of columns in a table
3114 * @param string $table_name
3117 public function number_of_columns($table_name)
3119 $table = $this->getTableDescription($table_name);
3120 return count($table);
3124 * Return limit query based on given query
3125 * @param string $sql
3128 * @param bool $dieOnError
3129 * @param string $msg
3130 * @return resource|bool query result
3131 * @see DBManager::limitQuery()
3133 public function limitQuerySql($sql, $start, $count, $dieOnError=false, $msg='')
3135 return $this->limitQuery($sql,$start,$count,$dieOnError,$msg,false);
3139 * Return current time in format fit for insertion into DB (with quotes)
3142 public function now()
3144 return $this->convert($this->quoted(TimeDate::getInstance()->nowDb()), "datetime");
3148 * Check if connecting user has certain privilege
3149 * @param string $privilege
3150 * @return bool Privilege allowed?
3152 public function checkPrivilege($privilege)
3154 switch($privilege) {
3155 case "CREATE TABLE":
3156 $this->query("CREATE TABLE temp (id varchar(36))");
3159 $sql = $this->dropTableNameSQL("temp");
3163 $this->query("INSERT INTO temp (id) VALUES ('abcdef0123456789abcdef0123456789abcd')");
3166 $this->query("UPDATE temp SET id = '100000000000000000000000000000000000' WHERE id = 'abcdef0123456789abcdef0123456789abcd'");
3169 return $this->getOne('SELECT id FROM temp WHERE id=\'100000000000000000000000000000000000\'', false);
3171 $this->query("DELETE FROM temp WHERE id = '100000000000000000000000000000000000'");
3174 $test = array("test" => array("name" => "test", "type" => "varchar", "len" => 50));
3175 $sql = $this->changeColumnSQL("temp", $test, "add");
3178 case "CHANGE COLUMN":
3179 $test = array("test" => array("name" => "test", "type" => "varchar", "len" => 100));
3180 $sql = $this->changeColumnSQL("temp", $test, "modify");
3184 $test = array("test" => array("name" => "test", "type" => "varchar", "len" => 100));
3185 $sql = $this->changeColumnSQL("temp", $test, "drop");
3191 if($this->checkError("Checking privileges")) {
3198 * Check if the query is a select query
3199 * @param string $query
3200 * @return bool Is query SELECT?
3202 protected function isSelect($query)
3204 $query = trim($query);
3205 $select_check = strpos(strtolower($query), strtolower("SELECT"));
3206 //Checks to see if there is union select which is valid
3207 $select_check2 = strpos(strtolower($query), strtolower("(SELECT"));
3208 if($select_check==0 || $select_check2==0){
3209 //Returning false means query is ok!
3216 * Parse fulltext search query with mysql syntax:
3217 * terms quoted by ""
3218 * + means the term must be included
3219 * - means the term must be excluded
3220 * * or % at the end means wildcard
3221 * @param string $query
3222 * @return array of 3 elements - query terms, mandatory terms and excluded terms
3224 public function parseFulltextQuery($query)
3226 /* split on space or comma, double quotes with \ for escape */
3227 if(strpbrk($query, " ,")) {
3228 // ("([^"]*?)"|[^" ,]+)((, )+)?
3229 // '/([^" ,]+|".*?[^\\\\]")(,|\s)\s*/'
3230 if(!preg_match_all('/("([^"]*?)"|[^"\s,]+)((,\s)+)?/', $query, $m)) {
3235 $qterms = array($query);
3237 $terms = $must_terms = $not_terms = array();
3238 foreach($qterms as $item) {
3239 if($item[0] == '"') {
3240 $item = trim($item, '"');
3242 if($item[0] == '+') {
3243 if (strlen($item) > 1) {
3244 $must_terms[] = substr($item, 1);
3248 if($item[0] == '-') {
3249 if (strlen($item) > 1) {
3250 $not_terms[] = substr($item, 1);
3256 return array($terms, $must_terms, $not_terms);
3259 // Methods to check respective queries
3260 protected $standardQueries = array(
3261 'ALTER TABLE' => 'verifyAlterTable',
3262 'DROP TABLE' => 'verifyDropTable',
3263 'CREATE TABLE' => 'verifyCreateTable',
3264 'INSERT INTO' => 'verifyInsertInto',
3265 'UPDATE' => 'verifyUpdate',
3266 'DELETE FROM' => 'verifyDeleteFrom',
3271 * Extract table name from a query
3272 * @param string $query SQL query
3275 protected function extractTableName($query)
3277 $query = preg_replace('/[^A-Za-z0-9_\s]/', "", $query);
3278 $query = trim(str_replace(array_keys($this->standardQueries), '', $query));
3280 $firstSpc = strpos($query, " ");
3281 $end = ($firstSpc > 0) ? $firstSpc : strlen($query);
3282 $table = substr($query, 0, $end);
3288 * Verify SQl statement using per-DB verification function
3289 * provided the function exists
3290 * @param string $query Query to verify
3291 * @param array $skipTables List of blacklisted tables that aren't checked
3294 public function verifySQLStatement($query, $skipTables)
3296 $query = trim($query);
3297 foreach($this->standardQueries as $qstart => $check) {
3298 if(strncasecmp($qstart, $query, strlen($qstart)) == 0) {
3299 if(is_callable(array($this, $check))) {
3300 $table = $this->extractTableName($query);
3301 if(!in_array($table, $skipTables)) {
3302 return call_user_func(array($this, $check), $table, $query);
3304 $this->log->debug("Skipping table $table as blacklisted");
3307 $this->log->debug("No verification for $qstart on {$this->dbType}");
3316 * Tests an CREATE TABLE query
3317 * @param string $table The table name to get DDL
3318 * @param string $query The query to test.
3319 * @return string Non-empty if error found
3321 protected function verifyCreateTable($table, $query)
3323 $this->log->debug('verifying CREATE statement...');
3325 // rewrite DDL with _temp name
3326 $this->log->debug('testing query: ['.$query.']');
3327 $tempname = $table."__uw_temp";
3328 $tempTableQuery = str_replace("CREATE TABLE {$table}", "CREATE TABLE $tempname", $query);
3330 if(strpos($tempTableQuery, '__uw_temp') === false) {
3331 return 'Could not use a temp table to test query!';
3334 $this->query($tempTableQuery, false, "Preflight Failed for: {$query}");
3336 $error = $this->lastError(); // empty on no-errors
3337 if(!empty($error)) {
3341 // check if table exists
3342 $this->log->debug('testing for table: '.$table);
3343 if(!$this->tableExists($tempname)) {
3344 return "Failed to create temp table!";
3347 $this->dropTableName($tempname);
3352 * Execute multiple queries one after another
3353 * @param array $sqls Queries
3354 * @param bool $dieOnError Die on error, passed to query()
3355 * @param string $msg Error message, passed to query()
3356 * @param bool $suppress Supress errors, passed to query()
3357 * @return resource|bool result set or success/failure bool
3359 public function queryArray(array $sqls, $dieOnError = false, $msg = '', $suppress = false)
3362 foreach($sqls as $sql) {
3363 if(!($last = $this->query($sql, $dieOnError, $msg, $suppress))) {
3371 * Fetches the next row in the query result into an associative array
3373 * @param resource $result
3374 * @param bool $encode Need to HTML-encode the result?
3375 * @return array returns false if there are no more rows available to fetch
3377 public function fetchByAssoc($result, $encode = true)
3379 if (empty($result)) return false;
3381 if(is_int($encode) && func_num_args() == 3) {
3382 // old API: $result, $rowNum, $encode
3383 $GLOBALS['log']->deprecated("Using row number in fetchByAssoc is not portable and no longer supported. Please fix your code.");
3384 $encode = func_get_arg(2);
3386 $row = $this->fetchRow($result);
3387 if (!empty($row) && $encode && $this->encode) {
3388 return array_map('to_html', $row);
3395 * Get DB driver name used for install/upgrade scripts
3398 public function getScriptName()
3400 // Usually the same name as dbType
3401 return $this->dbType;
3405 * Set database options
3406 * Options are usually db-dependant and derive from $config['dbconfigoption']
3407 * @param array $options
3410 public function setOptions($options)
3412 $this->options = $options;
3420 public function getOptions()
3422 return $this->options;
3426 * Get DB option by name
3427 * @param string $option Option name
3428 * @return mixed Option value or null if doesn't exist
3430 public function getOption($option)
3432 if(isset($this->options[$option])) {
3433 return $this->options[$option];
3439 * Commits pending changes to the database when the driver is setup to support transactions.
3440 * Note that the default implementation is applicable for transaction-less or auto commit scenarios.
3442 * @return bool true if commit succeeded, false if it failed
3444 public function commit()
3446 $this->log->info("DBManager.commit() stub");
3451 * Rollsback pending changes to the database when the driver is setup to support transactions.
3452 * Note that the default implementation is applicable for transaction-less or auto commit scenarios.
3453 * Since rollbacks cannot be done, this implementation always returns false.
3455 * @return bool true if rollback succeeded, false if it failed
3457 public function rollback()
3459 $this->log->info("DBManager.rollback() stub");
3464 * Check if this DB name is valid
3466 * @param string $name
3469 public function isDatabaseNameValid($name)
3471 // Generic case - no slashes, no dots
3472 return preg_match('#[/.\\\\]#', $name)==0;
3476 * Check special requirements for DB installation.
3478 * If everything is OK, return true.
3479 * If something's wrong, return array of error code and parameters
3482 public function canInstall()
3489 * Code run on new database before installing
3491 public function preInstall()
3497 * Code run on new database after installing
3499 public function postInstall()
3504 * Disable keys on the table
3506 * @param string $tableName
3508 public function disableKeys($tableName)
3513 * Re-enable keys on the table
3515 * @param string $tableName
3517 public function enableKeys($tableName)
3522 * Quote string in DB-specific manner
3523 * @param string $string
3526 abstract public function quote($string);
3529 * Use when you need to convert a database string to a different value; this function does it in a
3530 * database-backend aware way
3531 * Supported conversions:
3532 * today return current date
3533 * left Take substring from the left
3534 * date_format Format date as string, supports %Y-%m-%d, %Y-%m, %Y
3535 * time_format Format time as string
3536 * date Convert date string to datetime value
3537 * time Convert time string to datetime value
3538 * datetime Convert datetime string to datetime value
3539 * ifnull If var is null, use default value
3540 * concat Concatenate strings
3541 * quarter Quarter number of the date
3542 * length Length of string
3543 * month Month number of the date
3544 * add_date Add specified interval to a date
3545 * add_time Add time interval to a date
3546 * text2char Convert text field to varchar
3548 * @param string $string database string to convert
3549 * @param string $type type of conversion to do
3550 * @param array $additional_parameters optional, additional parameters to pass to the db function
3553 abstract public function convert($string, $type, array $additional_parameters = array());
3556 * Converts from Database data to app data
3565 * @param string $string database string to convert
3566 * @param string $type type of conversion to do
3569 abstract public function fromConvert($string, $type);
3572 * Parses and runs queries
3574 * @param string $sql SQL Statement to execute
3575 * @param bool $dieOnError True if we want to call die if the query returns errors
3576 * @param string $msg Message to log if error occurs
3577 * @param bool $suppress Flag to suppress all error output unless in debug logging mode.
3578 * @param bool $keepResult Keep query result in the object?
3579 * @return resource|bool result set or success/failure bool
3581 abstract public function query($sql, $dieOnError = false, $msg = '', $suppress = false, $keepResult = false);
3584 * Runs a limit query: one where we specify where to start getting records and how many to get
3586 * @param string $sql SELECT query
3587 * @param int $start Starting row
3588 * @param int $count How many rows
3589 * @param boolean $dieOnError True if we want to call die if the query returns errors
3590 * @param string $msg Message to log if error occurs
3591 * @param bool $execute Execute or return SQL?
3592 * @return resource query result
3594 abstract function limitQuery($sql, $start, $count, $dieOnError = false, $msg = '', $execute = true);
3598 * Free Database result
3599 * @param resource $dbResult
3601 abstract protected function freeDbResult($dbResult);
3604 * Rename column in the DB
3605 * @param string $tablename
3606 * @param string $column
3607 * @param string $newname
3609 abstract function renameColumnSQL($tablename, $column, $newname);
3612 * Returns definitions of all indies for passed table.
3614 * return will is a multi-dimensional array that
3615 * categorizes the index definition by types, unique, primary and index.
3619 * 'index1'=> array (
3620 * 'name' => 'index1',
3621 * 'type' => 'primary',
3622 * 'fields' => array('field1','field2')
3627 * This format is similar to how indicies are defined in vardef file.
3629 * @param string $tablename
3632 abstract public function get_indices($tablename);
3635 * Returns definitions of all indies for passed table.
3637 * return will is a multi-dimensional array that
3638 * categorizes the index definition by types, unique, primary and index.
3642 * 'field1'=> array (
3643 * 'name' => 'field1',
3644 * 'type' => 'varchar',
3650 * This format is similar to how indicies are defined in vardef file.
3652 * @param string $tablename
3655 abstract public function get_columns($tablename);
3658 * Generates alter constraint statement given a table name and vardef definition.
3660 * Supports both adding and droping a constraint.
3662 * @param string $table tablename
3663 * @param array $definition field definition
3664 * @param bool $drop true if we are dropping the constraint, false if we are adding it
3665 * @return string SQL statement
3667 abstract public function add_drop_constraint($table, $definition, $drop = false);
3670 * Returns the description of fields based on the result
3672 * @param resource $result
3673 * @param boolean $make_lower_case
3674 * @return array field array
3676 abstract public function getFieldsArray($result, $make_lower_case = false);
3679 * Returns an array of tables for this database
3681 * @return array|false an array of with table names, false if no tables found
3683 abstract public function getTablesArray();
3686 * Return's the version of the database
3690 abstract public function version();
3693 * Checks if a table with the name $tableName exists
3694 * and returns true if it does or false otherwise
3696 * @param string $tableName
3699 abstract public function tableExists($tableName);
3702 * Fetches the next row in the query result into an associative array
3704 * @param resource $result
3705 * @return array returns false if there are no more rows available to fetch
3707 abstract public function fetchRow($result);
3710 * Connects to the database backend
3712 * Takes in the database settings and opens a database connection based on those
3713 * will open either a persistent or non-persistent connection.
3714 * If a persistent connection is desired but not available it will defualt to non-persistent
3716 * configOptions must include
3717 * db_host_name - server ip
3718 * db_user_name - database user name
3719 * db_password - database password
3721 * @param array $configOptions
3722 * @param boolean $dieOnError
3724 abstract public function connect(array $configOptions = null, $dieOnError = false);
3727 * Generates sql for create table statement for a bean.
3729 * @param string $tablename
3730 * @param array $fieldDefs
3731 * @param array $indices
3732 * @return string SQL Create Table statement
3734 abstract public function createTableSQLParams($tablename, $fieldDefs, $indices);
3737 * Generates the SQL for changing columns
3739 * @param string $tablename
3740 * @param array $fieldDefs
3741 * @param string $action
3742 * @param bool $ignoreRequired Optional, true if we should ignor this being a required field
3743 * @return string|array
3745 abstract protected function changeColumnSQL($tablename, $fieldDefs, $action, $ignoreRequired = false);
3748 * Disconnects from the database
3750 * Also handles any cleanup needed
3752 abstract public function disconnect();
3755 * Get last database error
3756 * This function should return last error as reported by DB driver
3757 * and should return false if no error condition happened
3758 * @return string|false Error message or false if no error happened
3760 abstract public function lastDbError();
3763 * Check if this query is valid
3764 * Validates only SELECT queries
3765 * @param string $query
3768 abstract public function validateQuery($query);
3771 * Check if this driver can be used
3774 abstract public function valid();
3777 * Check if certain database exists
3778 * @param string $dbname
3780 abstract public function dbExists($dbname);
3783 * Get tables like expression
3784 * @param string $like Expression describing tables
3787 abstract public function tablesLike($like);
3791 * @param string $dbname
3793 abstract public function createDatabase($dbname);
3797 * @param string $dbname
3799 abstract public function dropDatabase($dbname);
3802 * Get database configuration information (DB-dependent)
3803 * @return array|null
3805 abstract public function getDbInfo();
3808 * Check if certain DB user exists
3809 * @param string $username
3811 abstract public function userExists($username);
3815 * @param string $database_name
3816 * @param string $host_name
3817 * @param string $user
3818 * @param string $password
3820 abstract public function createDbUser($database_name, $host_name, $user, $password);
3823 * Check if the database supports fulltext indexing
3824 * Note that database driver can be capable of supporting FT (see supports('fulltext))
3825 * but particular instance can still have it disabled
3828 abstract public function full_text_indexing_installed();
3831 * Generate fulltext query from set of terms
3832 * @param string $field Field to search against
3833 * @param array $terms Search terms that may be or not be in the result
3834 * @param array $must_terms Search terms that have to be in the result
3835 * @param array $exclude_terms Search terms that have to be not in the result
3837 abstract public function getFulltextQuery($field, $terms, $must_terms = array(), $exclude_terms = array());
3840 * Get install configuration for this DB
3843 abstract public function installConfig();
3846 * Returns a DB specific FROM clause which can be used to select against functions.
3847 * Note that depending on the database that this may also be an empty string.
3851 abstract public function getFromDummyTable();
3854 * Returns a DB specific piece of SQL which will generate GUID (UUID)
3855 * This string can be used in dynamic SQL to do multiple inserts with a single query.
3856 * I.e. generate a unique Sugar id in a sub select of an insert statement.
3860 abstract public function getGuidSQL();