2 if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
3 /*********************************************************************************
4 * SugarCRM Community Edition is a customer relationship management program developed by
5 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
7 * This program is free software; you can redistribute it and/or modify it under
8 * the terms of the GNU Affero General Public License version 3 as published by the
9 * Free Software Foundation with the addition of the following permission added
10 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
11 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
12 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
14 * This program is distributed in the hope that it will be useful, but WITHOUT
15 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
16 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
19 * You should have received a copy of the GNU Affero General Public License along with
20 * this program; if not, see http://www.gnu.org/licenses or write to the Free
21 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
24 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
25 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
27 * The interactive user interfaces in modified source and object code versions
28 * of this program must display Appropriate Legal Notices, as required under
29 * Section 5 of the GNU Affero General Public License version 3.
31 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
32 * these Appropriate Legal Notices must retain the display of the "Powered by
33 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
34 * technical reasons, the Appropriate Legal Notices must display the words
35 * "Powered by SugarCRM".
36 ********************************************************************************/
38 /*********************************************************************************
40 * Description: This file handles the Data base functionality for the application.
41 * It acts as the DB abstraction layer for the application. It depends on helper classes
42 * which generate the necessary SQL. This sql is then passed to PEAR DB classes.
43 * The helper class is chosen in DBManagerFactory, which is driven by 'db_type' in 'dbconfig' under config.php.
45 * All the functions in this class will work with any bean which implements the meta interface.
46 * The passed bean is passed to helper class which uses these functions to generate correct sql.
48 * The meta interface has the following functions:
49 * getTableName() Returns table name of the object.
50 * getFieldDefinitions() Returns a collection of field definitions in order.
51 * getFieldDefintion(name) Return field definition for the field.
52 * getFieldValue(name) Returns the value of the field identified by name.
53 * If the field is not set, the function will return boolean FALSE.
54 * getPrimaryFieldDefinition() Returns the field definition for primary key
56 * The field definition is an array with the following keys:
58 * name This represents name of the field. This is a required field.
59 * type This represents type of the field. This is a required field and valid values are:
73 * length This is used only when the type is varchar and denotes the length of the string.
74 * The max value is 255.
75 * enumvals This is a list of valid values for an enum separated by "|".
76 * It is used only if the type is ?enum?;
77 * required This field dictates whether it is a required value.
78 * The default value is ?FALSE?.
79 * isPrimary This field identifies the primary key of the table.
80 * If none of the fields have this flag set to ?TRUE?,
81 * the first field definition is assume to be the primary key.
82 * Default value for this field is ?FALSE?.
83 * default This field sets the default value for the field definition.
86 * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
87 * All Rights Reserved.
88 * Contributor(s): ______________________________________..
89 ********************************************************************************/
92 * SQL Server (mssql) manager
94 class MssqlManager extends DBManager
97 * @see DBManager::$dbType
99 public $dbType = 'mssql';
100 public $dbName = 'MsSQL';
101 public $variant = 'mssql';
102 public $label = 'LBL_MSSQL';
104 protected $capabilities = array(
105 "affected_rows" => true,
106 "select_rows" => true,
108 'limit_subquery' => true,
109 "fix:expandDatabase" => true, // Support expandDatabase fix
110 "create_user" => true,
115 * Maximum length of identifiers
117 protected $maxNameLengths = array(
124 protected $type_map = array(
131 'short' => 'smallint',
132 'varchar' => 'varchar',
134 'longtext' => 'text',
135 'date' => 'datetime',
137 'relate' => 'varchar',
138 'multienum'=> 'text',
140 'datetime' => 'datetime',
141 'datetimecombo' => 'datetime',
142 'time' => 'datetime',
144 'tinyint' => 'tinyint',
147 'longblob' => 'image',
148 'currency' => 'decimal(26,6)',
149 'decimal' => 'decimal',
150 'decimal2' => 'decimal',
151 'id' => 'varchar(36)',
153 'encrypt' => 'varchar',
155 'decimal_tpl' => 'decimal(%d, %d)',
158 protected $connectOptions = null;
161 * @see DBManager::connect()
163 public function connect(array $configOptions = null, $dieOnError = false)
165 global $sugar_config;
167 if (is_null($configOptions))
168 $configOptions = $sugar_config['dbconfig'];
170 //SET DATEFORMAT to 'YYYY-MM-DD''
171 ini_set('mssql.datetimeconvert', '0');
173 //set the text size and textlimit to max number so that blob columns are not truncated
174 ini_set('mssql.textlimit','2147483647');
175 ini_set('mssql.textsize','2147483647');
176 ini_set('mssql.charset','UTF-8');
178 if(!empty($configOptions['db_host_instance'])) {
179 $configOptions['db_host_instance'] = trim($configOptions['db_host_instance']);
181 //set the connections parameters
182 if (empty($configOptions['db_host_instance'])) {
183 $connect_param = $configOptions['db_host_name'];
185 $connect_param = $configOptions['db_host_name']."\\".$configOptions['db_host_instance'];
188 //create persistent connection
189 if ($this->getOption('persistent')) {
190 $this->database =@mssql_pconnect(
192 $configOptions['db_user_name'],
193 $configOptions['db_password']
196 //if no persistent connection created, then create regular connection
197 if(!$this->database){
198 $this->database = mssql_connect(
200 $configOptions['db_user_name'],
201 $configOptions['db_password']
203 if(!$this->database){
204 $GLOBALS['log']->fatal("Could not connect to server ".$configOptions['db_host_name'].
205 " as ".$configOptions['db_user_name'].".");
207 sugar_die($GLOBALS['app_strings']['ERR_NO_DB']);
212 if($this->database && $this->getOption('persistent')){
213 $_SESSION['administrator_error'] = "<B>Severe Performance Degradation: Persistent Database Connections "
214 . "not working. Please set \$sugar_config['dbconfigoption']['persistent'] to false in your "
215 . "config.php file</B>";
218 //make sure connection exists
219 if(!$this->database) {
221 sugar_die($GLOBALS['app_strings']['ERR_NO_DB']);
229 //Adding sleep and retry for mssql connection. We have come across scenarios when
230 //an error is thrown.' Unable to select database'. Following will try to connect to
231 //mssql db maximum number of 5 times at the interval of .2 second. If can not connect
232 //it will throw an Unable to select database message.
234 if(!@mssql_select_db($configOptions['db_name'], $this->database)){
238 if(@mssql_select_db($configOptions['db_name'], $this->database)){
244 $GLOBALS['log']->fatal( "Unable to select database {$configOptions['db_name']}");
246 if(isset($GLOBALS['app_strings']['ERR_NO_DB'])) {
247 sugar_die($GLOBALS['app_strings']['ERR_NO_DB']);
249 sugar_die("Could not connect to the database. Please refer to sugarcrm.log for details.");
257 if(!$this->checkError('Could Not Connect', $dieOnError))
258 $GLOBALS['log']->info("connected to db");
260 $this->connectOptions = $configOptions;
262 $GLOBALS['log']->info("Connect:".$this->database);
267 * @see DBManager::version()
269 public function version()
271 return $this->getOne("SELECT @@VERSION as version");
275 * @see DBManager::query()
277 public function query($sql, $dieOnError = false, $msg = '', $suppress = false, $keepResult = false)
280 return $this->queryArray($sql, $dieOnError, $msg, $suppress);
282 // Flag if there are odd number of single quotes
283 if ((substr_count($sql, "'") & 1))
284 $GLOBALS['log']->error("SQL statement[" . $sql . "] has odd number of single quotes.");
286 $sql = $this->_appendN($sql);
288 $GLOBALS['log']->info('Query:' . $sql);
289 $this->checkConnection();
290 $this->countQuery($sql);
291 $this->query_time = microtime(true);
293 // Bug 34892 - Clear out previous error message by checking the @@ERROR global variable
294 $errorNumber = $this->getOne("SELECT @@ERROR");
296 $result = $suppress?@mssql_query($sql, $this->database):mssql_query($sql, $this->database);
299 // awu Bug 10657: ignoring mssql error message 'Changed database context to' - an intermittent
300 // and difficult to reproduce error. The message is only a warning, and does
301 // not affect the functionality of the query
302 $sqlmsg = mssql_get_last_message();
303 $sqlpos = strpos($sqlmsg, 'Changed database context to');
304 $sqlpos2 = strpos($sqlmsg, 'Warning:');
305 $sqlpos3 = strpos($sqlmsg, 'Checking identity information:');
307 if ($sqlpos !== false || $sqlpos2 !== false || $sqlpos3 !== false) // if sqlmsg has 'Changed database context to', just log it
308 $GLOBALS['log']->debug($sqlmsg . ": " . $sql );
310 $GLOBALS['log']->fatal($sqlmsg . ": " . $sql );
312 sugar_die('SQL Error : ' . $sqlmsg);
314 echo 'SQL Error : ' . $sqlmsg;
318 $this->query_time = microtime(true) - $this->query_time;
319 $GLOBALS['log']->info('Query Execution Time:'.$this->query_time);
322 $this->checkError($msg.' Query Failed: ' . $sql, $dieOnError);
328 * This function take in the sql for a union query, the start and offset,
329 * and wraps it around an "mssql friendly" limit query
332 * @param int $start record to start at
333 * @param int $count number of records to retrieve
334 * @return string SQL statement
336 private function handleUnionLimitQuery($sql, $start, $count)
338 //set the start to 0, no negs
342 $GLOBALS['log']->debug(print_r(func_get_args(),true));
344 $this->lastsql = $sql;
346 //change the casing to lower for easier string comparison, and trim whitespaces
347 $sql = strtolower(trim($sql)) ;
350 $limitUnionSQL = $sql;
351 $order_by_str = 'order by';
353 //make array of order by's. substring approach was proving too inconsistent
354 $orderByArray = explode($order_by_str, $sql);
358 //count the number of array elements
359 $unionOrderByCount = count($orderByArray);
362 //process if there are elements
363 if ($unionOrderByCount){
364 //we really want the last ordery by, so reconstruct string
365 //adding a 1 to count, as we dont wish to process the last element
367 while ($unionOrderByCount>$arr_count+1) {
368 $unionsql .= $orderByArray[$arr_count];
369 $arr_count = $arr_count+1;
370 //add an "order by" string back if we are coming into loop again
371 //remember they were taken out when array was created
372 if ($unionOrderByCount>$arr_count+1) {
373 $unionsql .= "order by";
376 //grab the last order by element, set both order by's'
377 $unionOrderBy = $orderByArray[$arr_count];
378 $rowNumOrderBy = $unionOrderBy;
380 //if last element contains a "select", then this is part of the union query,
381 //and there is no order by to use
382 if (strpos($unionOrderBy, "select")) {
384 //with no guidance on what to use for required order by in rownumber function,
385 //resort to using name column.
386 $rowNumOrderBy = 'id';
391 //there are no order by elements, so just pass back string
393 //with no guidance on what to use for required order by in rownumber function,
394 //resort to using name column.
395 $rowNumOrderBy = 'id';
398 //Unions need the column name being sorted on to match acroos all queries in Union statement
399 //so we do not want to strip the alias like in other queries. Just add the "order by" string and
400 //pass column name as is
401 if ($unionOrderBy != '') {
402 $unionOrderBy = ' order by ' . $unionOrderBy;
405 //if start is 0, then just use a top query
407 $limitUnionSQL = "SELECT TOP $count * FROM (" .$unionsql .") as top_count ".$unionOrderBy;
409 //if start is more than 0, then use top query in conjunction
410 //with rownumber() function to create limit query.
411 $limitUnionSQL = "SELECT TOP $count * FROM( select ROW_NUMBER() OVER ( order by "
412 .$rowNumOrderBy.") AS row_number, * FROM ("
413 .$unionsql .") As numbered) "
414 . "As top_count_limit WHERE row_number > $start "
418 return $limitUnionSQL;
422 * FIXME: verify and thoroughly test this code, these regexps look fishy
423 * @see DBManager::limitQuery()
425 public function limitQuery($sql, $start, $count, $dieOnError = false, $msg = '', $execute = true)
427 $start = (int)$start;
428 $count = (int)$count;
430 $distinctSQLARRAY = array();
431 if (strpos($sql, "UNION") && !preg_match("/(')(UNION).?(')/i", $sql))
432 $newSQL = $this->handleUnionLimitQuery($sql,$start,$count);
436 $GLOBALS['log']->debug(print_r(func_get_args(),true));
437 $this->lastsql = $sql;
439 preg_match('/^(.*SELECT )(.*?FROM.*WHERE)(.*)$/isU',$sql, $matches);
440 if (!empty($matches[3])) {
442 $match_two = strtolower($matches[2]);
443 if (!strpos($match_two, "distinct")> 0 && strpos($match_two, "distinct") !==0) {
445 $newSQL = $matches[1] . " TOP $count " . $matches[2] . $matches[3];
448 $distinct_o = strpos($match_two, "distinct");
449 $up_to_distinct_str = substr($match_two, 0, $distinct_o);
450 //check to see if the distinct is within a function, if so, then proceed as normal
451 if (strpos($up_to_distinct_str,"(")) {
453 $newSQL = $matches[1] . " TOP $count " . $matches[2] . $matches[3];
456 //if distinct is not within a function, then parse
457 //string contains distinct clause, "TOP needs to come after Distinct"
458 //get position of distinct
459 $match_zero = strtolower($matches[0]);
460 $distinct_pos = strpos($match_zero , "distinct");
461 //get position of where
462 $where_pos = strpos($match_zero, "where");
463 //parse through string
464 $beg = substr($matches[0], 0, $distinct_pos+9 );
465 $mid = substr($matches[0], strlen($beg), ($where_pos+5) - (strlen($beg)));
466 $end = substr($matches[0], strlen($beg) + strlen($mid) );
467 //repopulate matches array
468 $matches[1] = $beg; $matches[2] = $mid; $matches[3] = $end;
470 $newSQL = $matches[1] . " TOP $count " . $matches[2] . $matches[3];
474 $orderByMatch = array();
475 preg_match('/^(.*)(ORDER BY)(.*)$/is',$matches[3], $orderByMatch);
477 //if there is a distinct clause, parse sql string as we will have to insert the rownumber
478 //for paging, AFTER the distinct clause
480 $hasDistinct = strpos(strtolower($matches[0]), "distinct");
482 $matches_sql = strtolower($matches[0]);
483 //remove reference to distinct and select keywords, as we will use a group by instead
484 //we need to use group by because we are introducing rownumber column which would make every row unique
486 //take out the select and distinct from string so we can reuse in group by
487 $dist_str = ' distinct ';
488 $distinct_pos = strpos($matches_sql, $dist_str);
489 $matches_sql = substr($matches_sql,$distinct_pos+ strlen($dist_str));
490 //get the position of where and from for further processing
491 $from_pos = strpos($matches_sql , " from ");
492 $where_pos = strpos($matches_sql, "where");
493 //split the sql into a string before and after the from clause
494 //we will use the columns being selected to construct the group by clause
496 $distinctSQLARRAY[0] = substr($matches_sql,0, $from_pos+1);
497 $distinctSQLARRAY[1] = substr($matches_sql,$from_pos+1);
498 //get position of order by (if it exists) so we can strip it from the string
499 $ob_pos = strpos($distinctSQLARRAY[1], "order by");
501 $distinctSQLARRAY[1] = substr($distinctSQLARRAY[1],0,$ob_pos);
504 // strip off last closing parathese from the where clause
505 $distinctSQLARRAY[1] = preg_replace('/\)\s$/',' ',$distinctSQLARRAY[1]);
508 //place group by string into array
509 $grpByArr = explode(',', $distinctSQLARRAY[0]);
511 //remove the aliases for each group by element, sql server doesnt like these in group by.
512 foreach ($grpByArr as $gb) {
515 //clean out the extra stuff added if we are concating first_name and last_name together
516 //this way both fields are added in correctly to the group by
517 $gb = str_replace("isnull(","",$gb);
518 $gb = str_replace("'') + ' ' + ","",$gb);
520 //remove outer reference if they exist
521 if (strpos($gb,"'")!==false){
524 //if there is a space, then an alias exists, remove alias
525 if (strpos($gb,' ')){
526 $gb = substr( $gb, 0,strpos($gb,' '));
529 //if resulting string is not empty then add to new group by string
535 $grpByStr .= ", $gb";
541 if (!empty($orderByMatch[3])) {
542 //if there is a distinct clause, form query with rownumber after distinct
544 $newSQL = "SELECT TOP $count * FROM
547 OVER (ORDER BY ".$this->returnOrderBy($sql, $orderByMatch[3]).") AS row_number,
548 count(*) counter, " . $distinctSQLARRAY[0] . "
549 " . $distinctSQLARRAY[1] . "
550 group by " . $grpByStr . "
552 WHERE row_number > $start";
555 $newSQL = "SELECT TOP $count * FROM
557 " . $matches[1] . " ROW_NUMBER()
558 OVER (ORDER BY " . $this->returnOrderBy($sql, $orderByMatch[3]) . ") AS row_number,
559 " . $matches[2] . $orderByMatch[1]. "
561 WHERE row_number > $start";
564 //bug: 22231 Records in campaigns' subpanel may not come from
565 //table of $_REQUEST['module']. Get it directly from query
566 $upperQuery = strtoupper($matches[2]);
567 if (!strpos($upperQuery,"JOIN")){
568 $from_pos = strpos($upperQuery , "FROM") + 4;
569 $where_pos = strpos($upperQuery, "WHERE");
570 $tablename = trim(substr($upperQuery,$from_pos, $where_pos - $from_pos));
572 // FIXME: this looks really bad. Probably source for tons of bug
573 // needs to be removed
574 $tablename = $this->getTableNameFromModuleName($_REQUEST['module'],$sql);
576 //if there is a distinct clause, form query with rownumber after distinct
578 $newSQL = "SELECT TOP $count * FROM
580 SELECT ROW_NUMBER() OVER (ORDER BY ".$tablename.".id) AS row_number, count(*) counter, " . $distinctSQLARRAY[0] . "
581 " . $distinctSQLARRAY[1] . "
582 group by " . $grpByStr . "
585 WHERE row_number > $start";
588 $newSQL = "SELECT TOP $count * FROM
590 " . $matches[1] . " ROW_NUMBER() OVER (ORDER BY ".$tablename.".id) AS row_number, " . $matches[2] . $matches[3]. "
593 WHERE row_number > $start";
600 $GLOBALS['log']->debug('Limit Query: ' . $newSQL);
602 $result = $this->query($newSQL, $dieOnError, $msg);
603 $this->dump_slow_queries($newSQL);
612 * Searches for begginning and ending characters. It places contents into
613 * an array and replaces contents in original string. This is used to account for use of
614 * nested functions while aliasing column names
616 * @param string $p_sql SQL statement
617 * @param string $strip_beg Beginning character
618 * @param string $strip_end Ending character
619 * @param string $patt Optional, pattern to
621 private function removePatternFromSQL($p_sql, $strip_beg, $strip_end, $patt = 'patt')
623 //strip all single quotes out
624 $count = substr_count ( $p_sql, $strip_beg);
626 if ($strip_beg != $strip_end)
631 $strip_array = array();
632 while ($i<$count && $offset<strlen($p_sql)) {
633 if ($offset > strlen($p_sql))
638 $beg_sin = strpos($p_sql, $strip_beg, $offset);
643 $sec_sin = strpos($p_sql, $strip_end, $beg_sin+1);
644 $strip_array[$patt.$i] = substr($p_sql, $beg_sin, $sec_sin - $beg_sin +1);
645 if ($increment > 1) {
646 //we are in here because beginning and end patterns are not identical, so search for nesting
647 $exists = strpos($strip_array[$patt.$i], $strip_beg );
649 $nested_pos = (strrpos($strip_array[$patt.$i], $strip_beg ));
650 $strip_array[$patt.$i] = substr($p_sql,$nested_pos+$beg_sin,$sec_sin - ($nested_pos+$beg_sin)+1);
651 $p_sql = substr($p_sql, 0, $nested_pos+$beg_sin) . " ##". $patt.$i."## " . substr($p_sql, $sec_sin+1);
656 $p_sql = substr($p_sql, 0, $beg_sin) . " ##". $patt.$i."## " . substr($p_sql, $sec_sin+1);
658 $offset = $sec_sin+1;
662 $strip_array['sql_string'] = $p_sql;
670 * @param string $token
671 * @param array $pattern_array
674 private function addPatternToSQL($token, array $pattern_array)
676 //strip all single quotes out
677 $pattern_array = array_reverse($pattern_array);
679 foreach ($pattern_array as $key => $replace) {
680 $token = str_replace( "##".$key."##", $replace,$token);
687 * gets an alias from the sql statement
690 * @param string $alias
693 private function getAliasFromSQL($sql, $alias)
696 preg_match('/^(.*SELECT)(.*?FROM.*WHERE)(.*)$/isU',$sql, $matches);
697 //parse all single and double quotes out of array
698 $sin_array = $this->removePatternFromSQL($matches[2], "'", "'","sin_");
699 $new_sql = array_pop($sin_array);
700 $dub_array = $this->removePatternFromSQL($new_sql, "\"", "\"","dub_");
701 $new_sql = array_pop($dub_array);
703 //search for parenthesis
704 $paren_array = $this->removePatternFromSQL($new_sql, "(", ")", "par_");
705 $new_sql = array_pop($paren_array);
707 //all functions should be removed now, so split the array on comma's
708 $mstr_sql_array = explode(",", $new_sql);
709 foreach($mstr_sql_array as $token ) {
710 if (strpos($token, $alias)) {
711 //found token, add back comments
712 $token = $this->addPatternToSQL($token, $paren_array);
713 $token = $this->addPatternToSQL($token, $dub_array);
714 $token = $this->addPatternToSQL($token, $sin_array);
716 //log and break out of this function
725 * Finds the alias of the order by column, and then return the preceding column name
728 * @param string $orderMatch
731 private function findColumnByAlias($sql, $orderMatch)
733 //change case to lowercase
734 $sql = strtolower($sql);
735 $patt = '/\s+'.trim($orderMatch).'\s*,/';
737 //check for the alias, it should contain comma, may contain space, \n, or \t
739 preg_match($patt, $sql, $matches, PREG_OFFSET_CAPTURE);
740 $found_in_sql = isset($matches[0][1]) ? $matches[0][1] : false;
743 //set default for found variable
744 $found = $found_in_sql;
746 //if still no match found, then we need to parse through the string
748 //get count of how many times the match exists in string
749 $found_count = substr_count($sql, $orderMatch);
752 $len = strlen($orderMatch);
753 //loop through string as many times as there is a match
754 while ($found_count > $i) {
755 //get the first match
756 $found_in_sql = strpos($sql, $orderMatch,$first_);
757 //make sure there was a match
759 //grab the next 2 individual characters
760 $str_plusone = substr($sql,$found_in_sql + $len,1);
761 $str_plustwo = substr($sql,$found_in_sql + $len+1,1);
762 //if one of those characters is a comma, then we have our alias
763 if ($str_plusone === "," || $str_plustwo === ","){
764 //keep track of this position
765 $found = $found_in_sql;
768 //set the offset and increase the iteration counter
769 $first_ = $found_in_sql+$len;
773 //return $found, defaults have been set, so if no match was found it will be a negative number
779 * Return the order by string to use in case the column has been aliased
782 * @param string $orig_order_match
785 private function returnOrderBy($sql, $orig_order_match)
787 $sql = strtolower($sql);
788 $orig_order_match = trim($orig_order_match);
789 if (strpos($orig_order_match, ".") != 0)
790 //this has a tablename defined, pass in the order match
791 return $orig_order_match;
793 //grab first space in order by
794 $firstSpace = strpos($orig_order_match, " ");
796 //split order by into column name and ascending/descending
797 $orderMatch = " " . strtolower(substr($orig_order_match, 0, $firstSpace));
798 $asc_desc = substr($orig_order_match,$firstSpace);
800 //look for column name as an alias in sql string
801 $found_in_sql = $this->findColumnByAlias($sql, $orderMatch);
803 if (!$found_in_sql) {
804 //check if this column needs the tablename prefixed to it
805 $orderMatch = ".".trim($orderMatch);
806 $colMatchPos = strpos($sql, $orderMatch);
807 if ($colMatchPos !== false) {
808 //grab sub string up to column name
809 $containsColStr = substr($sql,0, $colMatchPos);
810 //get position of first space, so we can grab table name
811 $lastSpacePos = strrpos($containsColStr, " ");
812 //use positions of column name, space before name, and length of column to find the correct column name
813 $col_name = substr($sql, $lastSpacePos, $colMatchPos-$lastSpacePos+strlen($orderMatch));
814 //bug 25485. When sorting by a custom field in Account List and then pressing NEXT >, system gives an error
815 $containsCommaPos = strpos($col_name, ",");
816 if($containsCommaPos !== false) {
817 $col_name = substr($col_name, $containsCommaPos+1);
822 //break out of here, log this
823 $GLOBALS['log']->debug("No match was found for order by, pass string back untouched as: $orig_order_match");
824 return $orig_order_match;
827 //if found, then parse and return
828 //grab string up to the aliased column
829 $GLOBALS['log']->debug("order by found, process sql string");
831 $psql = (trim($this->getAliasFromSQL($sql, $orderMatch )));
833 $psql = trim(substr($sql, 0, $found_in_sql));
835 //grab the last comma before the alias
836 $comma_pos = strrpos($psql, " ");
837 //substring between the comma and the alias to find the joined_table alias and column name
838 $col_name = substr($psql,0, $comma_pos);
840 //make sure the string does not have an end parenthesis
841 //and is not part of a function (i.e. "ISNULL(leads.last_name,'') as name" )
842 //this is especially true for unified search from home screen
845 if(strpos($psql, " as "))
846 $alias_beg_pos = strpos($psql, " as ");
848 // Bug # 44923 - This breaks the query and does not properly filter isnull
849 // as there are other functions such as ltrim and rtrim.
850 /* else if (strncasecmp($psql, 'isnull', 6) != 0)
851 $alias_beg_pos = strpos($psql, " "); */
853 if ($alias_beg_pos > 0) {
854 $col_name = substr($psql,0, $alias_beg_pos );
856 //add the "asc/desc" order back
857 $col_name = $col_name. " ". $asc_desc;
859 //pass in new order by
860 $GLOBALS['log']->debug("order by being returned is " . $col_name);
866 * Take in a string of the module and retrieve the correspondent table name
868 * @param string $module_str module name
869 * @param string $sql SQL statement
870 * @return string table name
872 private function getTableNameFromModuleName($module_str, $sql)
875 global $beanList, $beanFiles;
876 $GLOBALS['log']->debug("Module being processed is " . $module_str);
877 //get the right module files
878 //the module string exists in bean list, then process bean for correct table name
879 //note that we exempt the reports module from this, as queries from reporting module should be parsed for
880 //correct table name.
881 if (($module_str != 'Reports' && $module_str != 'SavedReport') && isset($beanList[$module_str]) && isset($beanFiles[$beanList[$module_str]])){
882 //if the class is not already loaded, then load files
883 if (!class_exists($beanList[$module_str]))
884 require_once($beanFiles[$beanList[$module_str]]);
886 //instantiate new bean
887 $module_bean = new $beanList[$module_str]();
888 //get table name from bean
889 $tbl_name = $module_bean->table_name;
890 //make sure table name is not just a blank space, or empty
891 $tbl_name = trim($tbl_name);
893 if(empty($tbl_name)){
894 $GLOBALS['log']->debug("Could not find table name for module $module_str. ");
895 $tbl_name = $module_str;
899 //since the module does NOT exist in beanlist, then we have to parse the string
900 //and grab the table name from the passed in sql
901 $GLOBALS['log']->debug("Could not find table name from module in request, retrieve from passed in sql");
902 $tbl_name = $module_str;
903 $sql = strtolower($sql);
905 //look for the location of the "from" in sql string
906 $fromLoc = strpos($sql," from " );
908 //found from, substring from the " FROM " string in sql to end
909 $tableEnd = substr($sql, $fromLoc+6);
910 //We know that tablename will be next parameter after from, so
911 //grab the next space after table name.
912 // MFH BUG #14009: Also check to see if there are any carriage returns before the next space so that we don't grab any arbitrary joins or other tables.
913 $carriage_ret = strpos($tableEnd,"\n");
914 $next_space = strpos($tableEnd," " );
915 if ($carriage_ret < $next_space)
916 $next_space = $carriage_ret;
917 if ($next_space > 0) {
918 $tbl_name= substr($tableEnd,0, $next_space);
919 if(empty($tbl_name)){
920 $GLOBALS['log']->debug("Could not find table name sql either, return $module_str. ");
921 $tbl_name = $module_str;
925 //grab the table, to see if it is aliased
926 $aliasTableEnd = trim(substr($tableEnd, $next_space));
927 $alias_space = strpos ($aliasTableEnd, " " );
928 if ($alias_space > 0){
929 $alias_tbl_name= substr($aliasTableEnd,0, $alias_space);
930 strtolower($alias_tbl_name);
931 if(empty($alias_tbl_name)
932 || $alias_tbl_name == "where"
933 || $alias_tbl_name == "inner"
934 || $alias_tbl_name == "left"
935 || $alias_tbl_name == "join"
936 || $alias_tbl_name == "outer"
937 || $alias_tbl_name == "right") {
938 //not aliased, do nothing
940 elseif ($alias_tbl_name == "as") {
941 //the next word is the table name
942 $aliasTableEnd = trim(substr($aliasTableEnd, $alias_space));
943 $alias_space = strpos ($aliasTableEnd, " " );
944 if ($alias_space > 0) {
945 $alias_tbl_name= trim(substr($aliasTableEnd,0, $alias_space));
946 if (!empty($alias_tbl_name))
947 $tbl_name = $alias_tbl_name;
951 //this is table alias
952 $tbl_name = $alias_tbl_name;
958 $GLOBALS['log']->debug("Table name for module $module_str is: ".$tbl_name);
964 * @see DBManager::getFieldsArray()
966 public function getFieldsArray($result, $make_lower_case = false)
968 $field_array = array();
970 if(! isset($result) || empty($result))
974 while ($i < mssql_num_fields($result)) {
975 $meta = mssql_fetch_field($result, $i);
978 if($make_lower_case==true)
979 $meta->name = strtolower($meta->name);
981 $field_array[] = $meta->name;
990 * @see DBManager::getAffectedRowCount()
992 public function getAffectedRowCount()
994 return $this->getOne("SELECT @@ROWCOUNT");
998 * @see DBManager::fetchRow()
1000 public function fetchRow($result)
1002 if (empty($result)) return false;
1004 $row = mssql_fetch_assoc($result);
1005 //MSSQL returns a space " " when a varchar column is empty ("") and not null.
1006 //We need to iterate through the returned row array and strip empty spaces
1008 foreach($row as $key => $column) {
1009 //notice we only strip if one space is returned. we do not want to strip
1010 //strings with intentional spaces (" foo ")
1011 if (!empty($column) && $column ==" ") {
1020 * @see DBManager::quote()
1022 public function quote($string)
1024 if(is_array($string)) {
1025 return $this->arrayQuote($string);
1027 return str_replace("'","''", $this->quoteInternal($string));
1031 * @see DBManager::tableExists()
1033 public function tableExists($tableName)
1035 $GLOBALS['log']->info("tableExists: $tableName");
1037 $this->checkConnection();
1038 $result = $this->getOne(
1039 "SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE' AND TABLE_NAME=".$this->quoted($tableName));
1041 return !empty($result);
1045 * Get tables like expression
1046 * @param $like string
1049 public function tablesLike($like)
1051 if ($this->getDatabase()) {
1053 $r = $this->query('SELECT TABLE_NAME tn FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE=\'BASE TABLE\' AND TABLE_NAME LIKE '.$this->quoted($like));
1055 while ($a = $this->fetchByAssoc($r)) {
1056 $row = array_values($a);
1066 * @see DBManager::getTablesArray()
1068 public function getTablesArray()
1070 $GLOBALS['log']->debug('MSSQL fetching table list');
1072 if($this->getDatabase()) {
1074 $r = $this->query('SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES');
1075 if (is_resource($r)) {
1076 while ($a = $this->fetchByAssoc($r))
1077 $tables[] = $a['TABLE_NAME'];
1083 return false; // no database available
1088 * This call is meant to be used during install, when Full Text Search is enabled
1089 * Indexing would always occur after a fresh sql server install, so this code creates
1090 * a catalog and table with full text index.
1092 public function full_text_indexing_setup()
1094 $GLOBALS['log']->debug('MSSQL about to wakeup FTS');
1096 if($this->getDatabase()) {
1097 //create wakup catalog
1098 $FTSqry[] = "if not exists( select * from sys.fulltext_catalogs where name ='wakeup_catalog' )
1099 CREATE FULLTEXT CATALOG wakeup_catalog
1102 //drop wakeup table if it exists
1103 $FTSqry[] = "IF EXISTS(SELECT 'fts_wakeup' FROM sysobjects WHERE name = 'fts_wakeup' AND xtype='U')
1104 DROP TABLE fts_wakeup
1106 //create wakeup table
1107 $FTSqry[] = "CREATE TABLE fts_wakeup(
1108 id varchar(36) NOT NULL CONSTRAINT pk_fts_wakeup_id PRIMARY KEY CLUSTERED (id ASC ),
1110 kb_index int IDENTITY(1,1) NOT NULL CONSTRAINT wakeup_fts_unique_idx UNIQUE NONCLUSTERED
1113 //create full text index
1114 $FTSqry[] = "CREATE FULLTEXT INDEX ON fts_wakeup
1119 KEY INDEX wakeup_fts_unique_idx ON wakeup_catalog
1120 WITH CHANGE_TRACKING AUTO
1124 $FTSqry[] = "INSERT INTO fts_wakeup (id ,body)
1125 VALUES ('".create_guid()."', 'SugarCRM Rocks' )";
1128 //create queries to stop and restart indexing
1129 $FTSqry[] = 'ALTER FULLTEXT INDEX ON fts_wakeup STOP POPULATION';
1130 $FTSqry[] = 'ALTER FULLTEXT INDEX ON fts_wakeup DISABLE';
1131 $FTSqry[] = 'ALTER FULLTEXT INDEX ON fts_wakeup ENABLE';
1132 $FTSqry[] = 'ALTER FULLTEXT INDEX ON fts_wakeup SET CHANGE_TRACKING MANUAL';
1133 $FTSqry[] = 'ALTER FULLTEXT INDEX ON fts_wakeup START FULL POPULATION';
1134 $FTSqry[] = 'ALTER FULLTEXT INDEX ON fts_wakeup SET CHANGE_TRACKING AUTO';
1136 foreach($FTSqry as $q){
1140 $this->create_default_full_text_catalog();
1143 return false; // no database available
1146 protected $date_formats = array(
1153 * @see DBManager::convert()
1155 public function convert($string, $type, array $additional_parameters = array())
1157 // convert the parameters array into a comma delimited string
1158 if (!empty($additional_parameters)) {
1159 $additional_parameters_string = ','.implode(',',$additional_parameters);
1161 $additional_parameters_string = '';
1163 $all_parameters = $additional_parameters;
1164 if(is_array($string)) {
1165 $all_parameters = array_merge($string, $all_parameters);
1166 } elseif (!is_null($string)) {
1167 array_unshift($all_parameters, $string);
1170 switch (strtolower($type)) {
1174 return "LEFT($string$additional_parameters_string)";
1176 if(!empty($additional_parameters[0]) && $additional_parameters[0][0] == "'") {
1177 $additional_parameters[0] = trim($additional_parameters[0], "'");
1179 if(!empty($additional_parameters) && isset($this->date_formats[$additional_parameters[0]])) {
1180 $len = $this->date_formats[$additional_parameters[0]];
1181 return "LEFT(CONVERT(varchar($len),". $string . ",120),$len)";
1183 return "LEFT(CONVERT(varchar(10),". $string . ",120),10)";
1186 if(empty($additional_parameters_string)) {
1187 $additional_parameters_string = ",''";
1189 return "ISNULL($string$additional_parameters_string)";
1191 return implode("+",$all_parameters);
1193 return "CAST($string AS varchar(8000))";
1195 return "DATEPART(quarter, $string)";
1197 return "LEN($string)";
1199 return "MONTH($string)";
1201 return "DATEADD({$additional_parameters[1]},{$additional_parameters[0]},$string)";
1203 return "DATEADD(hh, {$additional_parameters[0]}, DATEADD(mi, {$additional_parameters[1]}, $string))";
1210 * @see DBManager::fromConvert()
1212 public function fromConvert($string, $type)
1215 case 'datetimecombo':
1216 case 'datetime': return substr($string, 0,19);
1217 case 'date': return substr($string, 0, 10);
1218 case 'time': return substr($string, 11);
1224 * @see DBManager::createTableSQLParams()
1226 public function createTableSQLParams($tablename, $fieldDefs, $indices)
1228 if (empty($tablename) || empty($fieldDefs))
1231 $columns = $this->columnSQLRep($fieldDefs, false, $tablename);
1232 if (empty($columns))
1235 return "CREATE TABLE $tablename ($columns)";
1239 * Does this type represent text (i.e., non-varchar) value?
1240 * @param string $type
1242 public function isTextType($type)
1244 $type = strtolower($type);
1245 return in_array($this->type_map[$type], array('ntext','text','image'));
1249 * Return representation of an empty value depending on type
1250 * @param string $type
1252 public function emptyValue($type)
1254 $ctype = $this->getColumnType($type);
1255 if($ctype == "datetime") {
1256 return $this->convert($this->quoted("1970-01-01 00:00:00"), "datetime");
1258 if($ctype == "date") {
1259 return $this->convert($this->quoted("1970-01-01"), "datetime");
1261 if($ctype == "time") {
1262 return $this->convert($this->quoted("00:00:00"), "time");
1264 return parent::emptyValue($type);
1267 public function renameColumnSQL($tablename, $column, $newname)
1269 return "SP_RENAME '$tablename.$column', '$newname', 'COLUMN'";
1273 * Returns the SQL Alter table statment
1275 * MSSQL has a quirky T-SQL alter table syntax. Pay special attention to the
1277 * @param string $action
1279 * @param bool $ignorRequired
1280 * @param string $tablename
1282 protected function alterSQLRep($action, array $def, $ignoreRequired, $tablename)
1286 $f_def=$this->oneColumnSQLRep($def, $ignoreRequired,$tablename,false);
1287 return "ADD " . $f_def;
1290 return "DROP COLUMN " . $def['name'];
1293 //You cannot specify a default value for a column for MSSQL
1294 $f_def = $this->oneColumnSQLRep($def, $ignoreRequired,$tablename, true);
1295 $f_stmt = "ALTER COLUMN ".$f_def['name'].' '.$f_def['colType'].' '.
1296 $f_def['required'].' '.$f_def['auto_increment']."\n";
1297 if (!empty( $f_def['default']))
1298 $f_stmt .= " ALTER TABLE " . $tablename . " ADD ". $f_def['default'] . " FOR " . $def['name'];
1307 * @see DBManager::changeColumnSQL()
1309 * MSSQL uses a different syntax than MySQL for table altering that is
1310 * not quite as simplistic to implement...
1312 protected function changeColumnSQL($tablename, $fieldDefs, $action, $ignoreRequired = false)
1315 $constraints = $this->get_field_default_constraint_name($tablename);
1317 if ($this->isFieldArray($fieldDefs)) {
1318 foreach ($fieldDefs as $def)
1320 //if the column is being modified drop the default value
1321 //constraint if it exists. alterSQLRep will add the constraint back
1322 if (!empty($constraints[$def['name']])) {
1323 $sql.=" ALTER TABLE " . $tablename . " DROP CONSTRAINT " . $constraints[$def['name']];
1325 //check to see if we need to drop related indexes before the alter
1326 $indices = $this->get_indices($tablename);
1327 foreach ( $indices as $index ) {
1328 if ( in_array($def['name'],$index['fields']) ) {
1329 $sql .= ' ' . $this->add_drop_constraint($tablename,$index,true).' ';
1330 $sql2 .= ' ' . $this->add_drop_constraint($tablename,$index,false).' ';
1334 $columns[] = $this->alterSQLRep($action, $def, $ignoreRequired,$tablename);
1338 //if the column is being modified drop the default value
1339 //constraint if it exists. alterSQLRep will add the constraint back
1340 if (!empty($constraints[$fieldDefs['name']])) {
1341 $sql.=" ALTER TABLE " . $tablename . " DROP CONSTRAINT " . $constraints[$fieldDefs['name']];
1343 //check to see if we need to drop related indexes before the alter
1344 $indices = $this->get_indices($tablename);
1345 foreach ( $indices as $index ) {
1346 if ( in_array($fieldDefs['name'],$index['fields']) ) {
1347 $sql .= ' ' . $this->add_drop_constraint($tablename,$index,true).' ';
1348 $sql2 .= ' ' . $this->add_drop_constraint($tablename,$index,false).' ';
1353 $columns[] = $this->alterSQLRep($action, $fieldDefs, $ignoreRequired,$tablename);
1356 $columns = implode(", ", $columns);
1357 $sql .= " ALTER TABLE $tablename $columns " . $sql2;
1362 protected function setAutoIncrement($table, $field_name)
1364 return "identity(1,1)";
1368 * @see DBManager::setAutoIncrementStart()
1370 public function setAutoIncrementStart($table, $field_name, $start_value)
1372 if($start_value > 1)
1374 $this->query("DBCC CHECKIDENT ('$table', RESEED, $start_value)");
1379 * @see DBManager::getAutoIncrement()
1381 public function getAutoIncrement($table, $field_name)
1383 $result = $this->getOne("select IDENT_CURRENT('$table') + IDENT_INCR ( '$table' ) as 'Auto_increment'");
1388 * @see DBManager::get_indices()
1390 public function get_indices($tablename)
1392 //find all unique indexes and primary keys.
1394 SELECT LEFT(so.[name], 30) TableName,
1395 LEFT(si.[name], 50) 'Key_name',
1396 LEFT(sik.[keyno], 30) Sequence,
1397 LEFT(sc.[name], 30) Column_name,
1399 WHEN si.status & 2 = 2 AND so.xtype != 'PK' THEN 1
1403 INNER JOIN sysindexkeys sik
1404 ON (si.[id] = sik.[id] AND si.indid = sik.indid)
1405 INNER JOIN sysobjects so
1406 ON si.[id] = so.[id]
1407 INNER JOIN syscolumns sc
1408 ON (so.[id] = sc.[id] AND sik.colid = sc.colid)
1409 INNER JOIN sysfilegroups sfg
1410 ON si.groupid = sfg.groupid
1411 WHERE so.[name] = '$tablename'
1412 ORDER BY Key_name, Sequence, Column_name
1414 $result = $this->query($query);
1417 while (($row=$this->fetchByAssoc($result)) != null) {
1418 $index_type = 'index';
1419 if ($row['Key_name'] == 'PRIMARY')
1420 $index_type = 'primary';
1421 elseif ($row['isunique'] == 1 )
1422 $index_type = 'unique';
1423 $name = strtolower($row['Key_name']);
1424 $indices[$name]['name'] = $name;
1425 $indices[$name]['type'] = $index_type;
1426 $indices[$name]['fields'][] = strtolower($row['Column_name']);
1432 * @see DBManager::get_columns()
1434 public function get_columns($tablename)
1436 //find all unique indexes and primary keys.
1437 $result = $this->query("sp_columns $tablename");
1440 while (($row=$this->fetchByAssoc($result)) !=null) {
1441 $column_name = strtolower($row['COLUMN_NAME']);
1442 $columns[$column_name]['name']=$column_name;
1443 $columns[$column_name]['type']=strtolower($row['TYPE_NAME']);
1444 if ( $row['TYPE_NAME'] == 'decimal' ) {
1445 $columns[$column_name]['len']=strtolower($row['PRECISION']);
1446 $columns[$column_name]['len'].=','.strtolower($row['SCALE']);
1448 elseif ( in_array($row['TYPE_NAME'],array('nchar','nvarchar')) )
1449 $columns[$column_name]['len']=strtolower($row['PRECISION']);
1450 elseif ( !in_array($row['TYPE_NAME'],array('datetime','text')) )
1451 $columns[$column_name]['len']=strtolower($row['LENGTH']);
1452 if ( stristr($row['TYPE_NAME'],'identity') ) {
1453 $columns[$column_name]['auto_increment'] = '1';
1454 $columns[$column_name]['type']=str_replace(' identity','',strtolower($row['TYPE_NAME']));
1457 if (!empty($row['IS_NULLABLE']) && $row['IS_NULLABLE'] == 'NO' && (empty($row['KEY']) || !stristr($row['KEY'],'PRI')))
1458 $columns[strtolower($row['COLUMN_NAME'])]['required'] = 'true';
1461 if ( strtolower($tablename) == 'relationships' ) {
1462 $column_def = $this->getOne("select cdefault from syscolumns where id = object_id('relationships') and name = '$column_name'");
1464 if ( $column_def != 0 && ($row['COLUMN_DEF'] != null)) { // NOTE Not using !empty as an empty string may be a viable default value.
1466 $row['COLUMN_DEF'] = html_entity_decode($row['COLUMN_DEF'],ENT_QUOTES);
1467 if ( preg_match('/\([\(|\'](.*)[\)|\']\)/i',$row['COLUMN_DEF'],$matches) )
1468 $columns[$column_name]['default'] = $matches[1];
1469 elseif ( preg_match('/\(N\'(.*)\'\)/i',$row['COLUMN_DEF'],$matches) )
1470 $columns[$column_name]['default'] = $matches[1];
1472 $columns[$column_name]['default'] = $row['COLUMN_DEF'];
1480 * Get FTS catalog name for current DB
1482 protected function ftsCatalogName()
1484 if(isset($this->connectOptions['db_name'])) {
1485 return $this->connectOptions['db_name']."_fts_catalog";
1487 return 'sugar_fts_catalog';
1491 * @see DBManager::add_drop_constraint()
1493 public function add_drop_constraint($table, $definition, $drop = false)
1495 $type = $definition['type'];
1496 $fields = is_array($definition['fields'])?implode(',',$definition['fields']):$definition['fields'];
1497 $name = $definition['name'];
1503 case 'alternate_key':
1505 $sql = "DROP INDEX {$name} ON {$table}";
1507 $sql = "CREATE INDEX {$name} ON {$table} ({$fields})";
1511 $sql = "DROP INDEX {$name} ON {$table}";
1513 $sql = "CREATE CLUSTERED INDEX $name ON $table ($fields)";
1515 // constraints as indices
1518 $sql = "ALTER TABLE {$table} DROP CONSTRAINT $name";
1520 $sql = "ALTER TABLE {$table} ADD CONSTRAINT {$name} UNIQUE ({$fields})";
1524 $sql = "ALTER TABLE {$table} DROP PRIMARY KEY";
1526 $sql = "ALTER TABLE {$table} ADD CONSTRAINT {$name} PRIMARY KEY ({$fields})";
1530 $sql = "ALTER TABLE {$table} DROP FOREIGN KEY ({$fields})";
1532 $sql = "ALTER TABLE {$table} ADD CONSTRAINT {$name} FOREIGN KEY ({$fields}) REFERENCES {$definition['foreignTable']}({$definition['foreignFields']})";
1535 if ($this->full_text_indexing_enabled() && $drop) {
1536 $sql = "DROP FULLTEXT INDEX ON {$table}";
1537 } elseif ($this->full_text_indexing_enabled()) {
1538 $catalog_name=$this->ftsCatalogName();
1539 if ( isset($definition['catalog_name']) && $definition['catalog_name'] != 'default')
1540 $catalog_name = $definition['catalog_name'];
1542 $language = "Language 1033";
1543 if (isset($definition['language']) && !empty($definition['language']))
1544 $language = "Language " . $definition['language'];
1546 $key_index = $definition['key_index'];
1548 $change_tracking = "auto";
1549 if (isset($definition['change_tracking']) && !empty($definition['change_tracking']))
1550 $change_tracking = $definition['change_tracking'];
1552 $sql = " CREATE FULLTEXT INDEX ON $table ($fields $language) KEY INDEX $key_index ON $catalog_name WITH CHANGE_TRACKING $change_tracking" ;
1560 * Returns true if Full Text Search is installed
1564 public function full_text_indexing_installed()
1566 $ftsChckRes = $this->getOne("SELECT FULLTEXTSERVICEPROPERTY('IsFulltextInstalled') as fts");
1567 return !empty($ftsChckRes);
1571 * @see DBManager::full_text_indexing_enabled()
1573 protected function full_text_indexing_enabled($dbname = null)
1575 // check to see if we already have install setting in session
1576 if(!isset($_SESSION['IsFulltextInstalled']))
1577 $_SESSION['IsFulltextInstalled'] = $this->full_text_indexing_installed();
1579 // check to see if FTS Indexing service is installed
1580 if(empty($_SESSION['IsFulltextInstalled']))
1583 // grab the dbname if it was not passed through
1584 if (empty($dbname)) {
1585 global $sugar_config;
1586 $dbname = $sugar_config['dbconfig']['db_name'];
1588 //we already know that Indexing service is installed, now check
1589 //to see if it is enabled
1590 $res = $this->getOne("SELECT DATABASEPROPERTY('$dbname', 'IsFulltextEnabled') ftext");
1591 return !empty($res);
1595 * Creates default full text catalog
1597 protected function create_default_full_text_catalog()
1599 if ($this->full_text_indexing_enabled()) {
1600 $catalog = $this->ftsCatalogName();
1601 $GLOBALS['log']->debug("Creating the default catalog for full-text indexing, $catalog");
1603 //drop catalog if exists.
1604 $ret = $this->query("
1607 from sys.fulltext_catalogs
1608 where name ='$catalog'
1610 CREATE FULLTEXT CATALOG $catalog");
1613 $GLOBALS['log']->error("Error creating default full-text catalog, $catalog");
1619 * Function returns name of the constraint automatically generated by sql-server.
1620 * We request this for default, primary key, required
1622 * @param string $table
1623 * @param string $column
1626 private function get_field_default_constraint_name($table, $column = null)
1628 static $results = array();
1630 if ( empty($column) && isset($results[$table]) )
1631 return $results[$table];
1634 select s.name, o.name, c.name dtrt, d.name ctrt
1635 from sys.default_constraints as d
1636 join sys.objects as o
1637 on o.object_id = d.parent_object_id
1638 join sys.columns as c
1639 on c.object_id = o.object_id and c.column_id = d.parent_column_id
1640 join sys.schemas as s
1641 on s.schema_id = o.schema_id
1642 where o.name = '$table'
1644 if ( !empty($column) )
1645 $query .= " and c.name = '$column'";
1646 $res = $this->query($query);
1647 if ( !empty($column) ) {
1648 $row = $this->fetchByAssoc($res);
1650 return $row['ctrt'];
1653 $returnResult = array();
1654 while ( $row = $this->fetchByAssoc($res) )
1655 $returnResult[$row['dtrt']] = $row['ctrt'];
1656 $results[$table] = $returnResult;
1657 return $returnResult;
1664 * @see DBManager::massageFieldDef()
1666 public function massageFieldDef(&$fieldDef, $tablename)
1668 parent::massageFieldDef($fieldDef,$tablename);
1670 if ($fieldDef['type'] == 'int')
1671 $fieldDef['len'] = '4';
1673 if(empty($fieldDef['len']))
1675 switch($fieldDef['type']) {
1677 case 'bool' : $fieldDef['len'] = '1'; break;
1678 case 'smallint' : $fieldDef['len'] = '2'; break;
1679 case 'float' : $fieldDef['len'] = '8'; break;
1681 case 'nvarchar' : if(!in_array($fieldDef['dbType'],array('text','ntext')))
1682 $fieldDef['len'] = '255';
1684 $fieldDef['len'] = 'max'; // text or ntext
1686 case 'image' : $fieldDef['len'] = '2147483647'; break;
1687 case 'ntext' : $fieldDef['len'] = '2147483646'; break; // Note: this is from legacy code, don't know if this is correct
1690 if($fieldDef['type'] == 'decimal'
1691 && empty($fieldDef['precision'])
1692 && !strpos($fieldDef['len'], ','))
1694 $fieldDef['len'] .= ',0'; // Adding 0 precision if it is not specified
1697 if(empty($fieldDef['default'])
1698 && in_array($fieldDef['type'],array('bit','bool')))
1700 $fieldDef['default'] = '0';
1702 if (isset($fieldDef['required']) && $fieldDef['required'] && !isset($fieldDef['default']) )
1703 $fieldDef['default'] = '';
1704 // if ($fieldDef['type'] == 'bit' && empty($fieldDef['len']) )
1705 // $fieldDef['len'] = '1';
1706 // if ($fieldDef['type'] == 'bool' && empty($fieldDef['len']) )
1707 // $fieldDef['len'] = '1';
1708 // if ($fieldDef['type'] == 'float' && empty($fieldDef['len']) )
1709 // $fieldDef['len'] = '8';
1710 // if ($fieldDef['type'] == 'varchar' && empty($fieldDef['len']) )
1711 // $fieldDef['len'] = '255';
1712 // if ($fieldDef['type'] == 'nvarchar' && empty($fieldDef['len']) )
1713 // $fieldDef['len'] = '255';
1714 // if ($fieldDef['type'] == 'image' && empty($fieldDef['len']) )
1715 // $fieldDef['len'] = '2147483647';
1716 // if ($fieldDef['type'] == 'ntext' && empty($fieldDef['len']) )
1717 // $fieldDef['len'] = '2147483646';
1718 // if ($fieldDef['type'] == 'smallint' && empty($fieldDef['len']) )
1719 // $fieldDef['len'] = '2';
1720 // if ($fieldDef['type'] == 'bit' && empty($fieldDef['default']) )
1721 // $fieldDef['default'] = '0';
1722 // if ($fieldDef['type'] == 'bool' && empty($fieldDef['default']) )
1723 // $fieldDef['default'] = '0';
1728 * @see DBManager::oneColumnSQLRep()
1730 protected function oneColumnSQLRep($fieldDef, $ignoreRequired = false, $table = '', $return_as_array = false)
1733 if(isset($fieldDef['name'])){
1734 $colType = $this->getFieldType($fieldDef);
1735 if(stristr($this->getFieldType($fieldDef), 'decimal') && isset($fieldDef['len'])){
1736 $fieldDef['len'] = min($fieldDef['len'],38);
1738 //bug: 39690 float(8) is interpreted as real and this generates a diff when doing repair
1739 if(stristr($colType, 'float') && isset($fieldDef['len']) && $fieldDef['len'] == 8){
1740 unset($fieldDef['len']);
1744 // always return as array for post-processing
1745 $ref = parent::oneColumnSQLRep($fieldDef, $ignoreRequired, $table, true);
1747 // Bug 24307 - Don't add precision for float fields.
1748 if ( stristr($ref['colType'],'float') )
1749 $ref['colType'] = preg_replace('/(,\d+)/','',$ref['colType']);
1751 if ( $return_as_array )
1754 return "{$ref['name']} {$ref['colType']} {$ref['default']} {$ref['required']} {$ref['auto_increment']}";
1758 * Saves changes to module's audit table
1760 * @param object $bean Sugarbean instance
1761 * @param array $changes changes
1763 public function save_audit_records(SugarBean $bean, $changes)
1765 //Bug 25078 fixed by Martin Hu: sqlserver haven't 'date' type, trim extra "00:00:00"
1766 if($changes['data_type'] == 'date'){
1767 $changes['before'] = str_replace(' 00:00:00','',$changes['before']);
1769 parent::save_audit_records($bean,$changes);
1773 * Disconnects from the database
1775 * Also handles any cleanup needed
1777 public function disconnect()
1779 $GLOBALS['log']->debug('Calling Mssql::disconnect()');
1780 if(!empty($this->database)){
1781 $this->freeResult();
1782 mssql_close($this->database);
1783 $this->database = null;
1788 * @see DBManager::freeDbResult()
1790 protected function freeDbResult($dbResult)
1792 if(!empty($dbResult))
1793 mssql_free_result($dbResult);
1798 * @see DBManager::lastDbError()
1800 public function lastDbError()
1802 $sqlmsg = mssql_get_last_message();
1803 if(empty($sqlmsg)) return false;
1804 global $app_strings;
1805 if (empty($app_strings)
1806 or !isset($app_strings['ERR_MSSQL_DB_CONTEXT'])
1807 or !isset($app_strings['ERR_MSSQL_WARNING']) ) {
1808 //ignore the message from sql-server if $app_strings array is empty. This will happen
1809 //only if connection if made before languge is set.
1813 $sqlpos = strpos($sqlmsg, 'Changed database context to');
1814 $sqlpos2 = strpos($sqlmsg, 'Warning:');
1815 $sqlpos3 = strpos($sqlmsg, 'Checking identity information:');
1816 if ( $sqlpos !== false || $sqlpos2 !== false || $sqlpos3 !== false ) {
1819 global $app_strings;
1820 //ERR_MSSQL_DB_CONTEXT: localized version of 'Changed database context to' message
1821 if (empty($app_strings) or !isset($app_strings['ERR_MSSQL_DB_CONTEXT'])) {
1822 //ignore the message from sql-server if $app_strings array is empty. This will happen
1823 //only if connection if made before languge is set.
1824 $GLOBALS['log']->debug("Ignoring this database message: " . $sqlmsg);
1828 $sqlpos = strpos($sqlmsg, $app_strings['ERR_MSSQL_DB_CONTEXT']);
1829 if ( $sqlpos !== false )
1834 if ( strlen($sqlmsg) > 2 ) {
1835 return "SQL Server error: " . $sqlmsg;
1843 * @see DBManager::getDbInfo()
1845 public function getDbInfo()
1847 return array("version" => $this->version());
1852 * @see DBManager::validateQuery()
1854 public function validateQuery($query)
1856 if(!$this->isSelect($query)) {
1859 $this->query("SET SHOWPLAN_TEXT ON");
1860 $res = $this->getOne($query);
1861 $this->query("SET SHOWPLAN_TEXT OFF");
1862 return !empty($res);
1866 * This is a utility function to prepend the "N" character in front of SQL values that are
1867 * surrounded by single quotes.
1869 * @param $sql string SQL statement
1870 * @return string SQL statement with single quote values prepended with "N" character for nvarchar columns
1872 protected function _appendN($sql)
1874 // If there are no single quotes, don't bother, will just assume there is no character data
1875 if (strpos($sql, "'") === false)
1878 // Flag if there are odd number of single quotes, just continue w/o trying to append N
1879 if ((substr_count($sql, "'") & 1)) {
1880 $GLOBALS['log']->error("SQL statement[" . $sql . "] has odd number of single quotes.");
1884 //The only location of three subsequent ' will be at the begning or end of a value.
1885 $sql = preg_replace('/(?<!\')(\'{3})(?!\')/', "'<@#@#@PAIR@#@#@>", $sql);
1887 // Remove any remaining '' and do not parse... replace later (hopefully we don't even have any)
1889 $regexp = '/(\'{2})/';
1890 $pair_matches = array();
1891 preg_match_all($regexp, $sql, $pair_matches);
1892 if ($pair_matches) {
1893 foreach (array_unique($pair_matches[0]) as $key=>$value) {
1894 $pairs['<@PAIR-'.$key.'@>'] = $value;
1896 if (!empty($pairs)) {
1897 $sql = str_replace($pairs, array_keys($pairs), $sql);
1901 $regexp = "/(N?'.+?')/is";
1903 preg_match_all($regexp, $sql, $matches);
1905 if (!empty($matches)) {
1906 foreach ($matches[0] as $value) {
1907 // We are assuming that all nvarchar columns are no more than 200 characters in length
1908 // One problem we face is the image column type in reports which cannot accept nvarchar data
1909 if (!empty($value) && !is_numeric(trim(str_replace(array("'", ","), "", $value))) && !preg_match('/^\'[\,]\'$/', $value)) {
1910 $replace[$value] = 'N' . trim($value, "N");
1915 if (!empty($replace))
1916 $sql = str_replace(array_keys($replace), $replace, $sql);
1919 $sql = str_replace(array_keys($pairs), $pairs, $sql);
1921 if(strpos($sql, "<@#@#@PAIR@#@#@>"))
1922 $sql = str_replace(array('<@#@#@PAIR@#@#@>'), array("''"), $sql);
1928 * Quote SQL Server search term
1929 * @param string $term
1932 protected function quoteTerm($term)
1934 $term = str_replace("%", "*", $term); // Mssql wildcard is *
1935 return '"'.$term.'"';
1939 * Generate fulltext query from set of terms
1940 * @param string $fields Field to search against
1941 * @param array $terms Search terms that may be or not be in the result
1942 * @param array $must_terms Search terms that have to be in the result
1943 * @param array $exclude_terms Search terms that have to be not in the result
1945 public function getFulltextQuery($field, $terms, $must_terms = array(), $exclude_terms = array())
1947 $condition = $or_condition = array();
1948 foreach($must_terms as $term) {
1949 $condition[] = $this->quoteTerm($term);
1952 foreach($terms as $term) {
1953 $or_condition[] = $this->quoteTerm($term);
1956 if(!empty($or_condition)) {
1957 $condition[] = "(".join(" | ", $or_condition).")";
1960 foreach($exclude_terms as $term) {
1961 $condition[] = " NOT ".$this->quoteTerm($term);
1963 $condition = $this->quoted(join(" AND ",$condition));
1964 return "CONTAINS($field, $condition)";
1968 * Check if certain database exists
1969 * @param string $dbname
1971 public function dbExists($dbname)
1973 $db = $this->getOne("SELECT name FROM master..sysdatabases WHERE name = N".$this->quoted($dbname));
1979 * @param string $dbname
1981 protected function selectDb($dbname)
1983 return mssql_select_db($dbname);
1987 * Check if certain DB user exists
1988 * @param string $username
1990 public function userExists($username)
1992 $this->selectDb("master");
1993 $user = $this->getOne("select count(*) from sys.sql_logins where name =".$this->quoted($username));
1994 // FIXME: go back to the original DB
1995 return !empty($user);
2000 * @param string $database_name
2001 * @param string $host_name
2002 * @param string $user
2003 * @param string $password
2005 public function createDbUser($database_name, $host_name, $user, $password)
2007 $qpassword = $this->quote($password);
2008 $this->selectDb($database_name);
2009 $this->query("CREATE LOGIN $user WITH PASSWORD = '$qpassword'", true);
2010 $this->query("CREATE USER $user FOR LOGIN $user", true);
2011 $this->query("EXEC sp_addRoleMember 'db_ddladmin ', '$user'", true);
2012 $this->query("EXEC sp_addRoleMember 'db_datareader','$user'", true);
2013 $this->query("EXEC sp_addRoleMember 'db_datawriter','$user'", true);
2018 * @param string $dbname
2020 public function createDatabase($dbname)
2022 return $this->query("CREATE DATABASE $dbname", true);
2027 * @param string $dbname
2029 public function dropDatabase($dbname)
2031 return $this->query("DROP DATABASE $dbname", true);
2035 * Check if this driver can be used
2038 public function valid()
2040 return function_exists("mssql_connect");
2044 * Check if this DB name is valid
2046 * @param string $name
2049 public function isDatabaseNameValid($name)
2051 // No funny chars, does not begin with number
2052 return preg_match('/^[0-9#@]+|[\"\'\*\/\\?\:\\<\>\-\ \&\!\(\)\[\]\{\}\;\,\.\`\~\|\\\\]+/', $name)==0;
2055 public function installConfig()
2058 'LBL_DBCONFIG_MSG3' => array(
2059 "setup_db_database_name" => array("label" => 'LBL_DBCONF_DB_NAME', "required" => true),
2061 'LBL_DBCONFIG_MSG2' => array(
2062 "setup_db_host_name" => array("label" => 'LBL_DBCONF_HOST_NAME', "required" => true),
2063 "setup_db_host_instance" => array("label" => 'LBL_DBCONF_HOST_INSTANCE'),
2065 'LBL_DBCONF_TITLE_USER_INFO' => array(),
2066 'LBL_DBCONFIG_B_MSG1' => array(
2067 "setup_db_admin_user_name" => array("label" => 'LBL_DBCONF_DB_ADMIN_USER', "required" => true),
2068 "setup_db_admin_password" => array("label" => 'LBL_DBCONF_DB_ADMIN_PASSWORD', "type" => "password"),