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 specific
41 * to Mssql database. It is called by the DBManager class to generate various sql statements.
43 * All the functions in this class will work with any bean which implements the meta interface.
44 * Please refer the DBManager documentation for the details.
46 * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
47 * All Rights Reserved.
48 * Contributor(s): ___RPS___________________________________..
49 ********************************************************************************/
51 include_once('include/database/DBHelper.php');
53 class MssqlHelper extends DBHelper
56 * Maximum length of identifiers
58 protected $maxNameLengths = array(
66 * @see DBHelper::getColumnType()
68 public function getColumnType(
81 'short' => 'smallint',
82 'varchar' => 'varchar',
87 'relate' => 'varchar',
90 'datetime' => 'datetime',
91 'datetimecombo' => 'datetime',
94 'tinyint' => 'tinyint',
97 'longblob' => 'image',
98 'currency' => 'decimal(26,6)',
99 'decimal' => 'decimal',
100 'decimal2' => 'decimal',
101 'id' => 'varchar(36)',
103 'encrypt'=>'varchar',
111 * @see DBHelper::dropTableNameSQL()
113 public function dropTableNameSQL(
117 return "DROP TABLE ".$name;
121 * Returns the SQL Alter table statment
123 * MSSQL has a quirky T-SQL alter table syntax. Pay special attention to the
125 * @param string $action
127 * @param bool $ignorRequired
128 * @param string $tablename
130 private function alterSQLRep(
139 $f_def=$this->oneColumnSQLRep($def, $ignoreRequired,$tablename,false);
140 return "ADD " . $f_def;
143 return "DROP COLUMN " . $def['name'];
146 //You cannot specify a default value for a column for MSSQL
147 $f_def = $this->oneColumnSQLRep($def, $ignoreRequired,$tablename, true);
148 $f_stmt = "ALTER COLUMN ".$f_def['name'].' '.$f_def['colType'].' '.
149 $f_def['required'].' '.$f_def['auto_increment']."\n";
150 if (!empty( $f_def['default']))
151 $f_stmt .= " ALTER TABLE " . $tablename . " ADD ". $f_def['default'] . " FOR " . $def['name'];
160 * @see DBHelper::changeColumnSQL()
162 * MSSQL uses a different syntax than MySQL for table altering that is
163 * not quite as simplistic to implement...
165 protected function changeColumnSQL(
169 $ignoreRequired = false
173 $constraints = $this->get_field_default_constraint_name($tablename);
174 if ($this->isFieldArray($fieldDefs)) {
175 foreach ($fieldDefs as $def)
177 //if the column is being modified drop the default value
178 //constraint if it exists. alterSQLRep will add the constraint back
179 if (!empty($constraints[$def['name']])) {
180 $sql.=" ALTER TABLE " . $tablename . " DROP CONSTRAINT " . $constraints[$def['name']];
182 //check to see if we need to drop related indexes before the alter
183 $indices = $this->get_indices($tablename);
184 foreach ( $indices as $index ) {
185 if ( in_array($def['name'],$index['fields']) ) {
186 $sql .= ' ' . $this->add_drop_constraint($tablename,$index,true).' ';
187 $sql2 .= ' ' . $this->add_drop_constraint($tablename,$index,false).' ';
191 $columns[] = $this->alterSQLRep($action, $def, $ignoreRequired,$tablename);
195 //if the column is being modified drop the default value
196 //constraint if it exists. alterSQLRep will add the constraint back
197 if (!empty($constraints[$fieldDefs['name']])) {
198 $sql.=" ALTER TABLE " . $tablename . " DROP CONSTRAINT " . $constraints[$fieldDefs['name']];
200 //check to see if we need to drop related indexes before the alter
201 $indices = $this->get_indices($tablename);
202 foreach ( $indices as $index ) {
203 if ( in_array($fieldDefs['name'],$index['fields']) ) {
204 $sql .= ' ' . $this->add_drop_constraint($tablename,$index,true).' ';
205 $sql2 .= ' ' . $this->add_drop_constraint($tablename,$index,false).' ';
210 $columns[] = $this->alterSQLRep($action, $fieldDefs, $ignoreRequired,$tablename);
213 $columns = implode(", ", $columns);
214 $sql .= " ALTER TABLE $tablename $columns " . $sql2;
220 * @see DBHelper::deleteColumnSQL()
222 public function deleteColumnSQL(
227 if ($this->isFieldArray($fieldDefs))
228 foreach ($fieldDefs as $fieldDef)
229 $columns[] = $fieldDef['name'];
231 $columns[] = $fieldDefs['name'];
233 return "ALTER TABLE ".$bean->getTableName()." DROP COLUMN ".implode(", DROP COLUMN ", $columns);
237 * returns an alter table statement to build the list of indices
239 * @param string $tableName
240 * @param array $fieldDefs
241 * @param array $indices
242 * @return string SQL statement
244 public function indexSQL(
250 // check if the passed value is an array of fields.
251 // if not, convert it into an array
252 if (!$this->isFieldArray($indices))
253 $indices[] = $indices;
256 foreach ($indices as $index) {
257 if(!empty($index['db']) && $index['db'] != 'mssql')
259 if (isset($index['source']) && $index['source'] != 'db')
262 $type = $index['type'];
263 $name = $index['name'];
265 if (is_array($index['fields']))
266 $fields = implode(", ", $index['fields']);
268 $fields = $index['fields'];
272 // SQL server requires primary key constraints to be created with
273 // key word "PRIMARY KEY". Cannot default to index as synonym
274 $columns[] = "ALTER TABLE $tableName ADD CONSTRAINT pk_$tableName PRIMARY KEY ($fields)";
277 $columns[] = "ALTER TABLE $tableName ADD CONSTRAINT " . $index['name'] . " UNIQUE ($fields)";
280 $columns[] = "CREATE CLUSTERED INDEX $name ON $tableName ( $fields )";
283 case 'alternate_key':
285 $columns[] = "CREATE INDEX $name ON $tableName ( $fields )";
288 if ($this->full_text_indexing_enabled()) {
289 $catalog_name="sugar_fts_catalog";
290 if ( isset($index['catalog_name'])
291 && $index['catalog_name'] != 'default')
292 $catalog_name = $index['catalog_name'];
294 $language = "Language 1033";
295 if (isset($index['language']) && !empty($index['language']))
296 $language = "Language " . $index['language'];
298 $key_index = $index['key_index'];;
300 $change_tracking = "auto";
301 if (isset($index['change_tracking'])
302 && !empty($index['change_tracking']))
303 $change_tracking = $index['change_tracking'];
305 $columns[] = " CREATE FULLTEXT INDEX ON $tableName($fields $language) KEY INDEX $key_index ON $catalog_name WITH CHANGE_TRACKING $change_tracking" ;
311 $columns = implode(" ", $columns);
316 protected function setAutoIncrement(
321 return "identity(1,1)";
325 * @see DBHelper::setAutoIncrementStart()
327 public function setAutoIncrementStart(
335 $this->db->query("DBCC CHECKIDENT ('$table', RESEED, $start_value)");
340 * @see DBHelper::getAutoIncrement()
342 public function getAutoIncrement(
349 $result = $this->db->query("select IDENT_CURRENT('$table') + IDENT_INCR ( '$table' ) as 'Auto_increment'");
350 $row = $this->db->fetchByAssoc($result);
351 if (!empty($row['Auto_increment']))
352 return $row['Auto_increment'];
358 * @see DBHelper::createTableSQLParams()
360 public function createTableSQLParams(
367 if (empty($tablename) || empty($fieldDefs))
371 $columns = $this->columnSQLRep($fieldDefs, false, $tablename);
375 return "CREATE TABLE $tablename ($columns ) " .
376 $this->indexSQL($tablename, $fieldDefs, $indices);
380 * @see DBHelper::get_indices()
382 public function get_indices(
386 //find all unique indexes and primary keys.
388 SELECT LEFT(so.[name], 30) TableName,
389 LEFT(si.[name], 50) 'Key_name',
390 LEFT(sik.[keyno], 30) Sequence,
391 LEFT(sc.[name], 30) Column_name,
393 WHEN si.status & 2 = 2 AND so.xtype != 'PK' THEN 1
397 INNER JOIN sysindexkeys sik
398 ON (si.[id] = sik.[id] AND si.indid = sik.indid)
399 INNER JOIN sysobjects so
401 INNER JOIN syscolumns sc
402 ON (so.[id] = sc.[id] AND sik.colid = sc.colid)
403 INNER JOIN sysfilegroups sfg
404 ON si.groupid = sfg.groupid
405 WHERE so.[name] = '$tablename'
406 ORDER BY Key_name, Sequence, Column_name
408 $result = $this->db->query($query);
411 while (($row=$this->db->fetchByAssoc($result)) != null) {
412 $index_type = 'index';
413 if ($row['Key_name'] == 'PRIMARY')
414 $index_type = 'primary';
415 elseif ($row['isunique'] == 1 )
416 $index_type = 'unique';
417 $name = strtolower($row['Key_name']);
418 $indices[$name]['name'] = $name;
419 $indices[$name]['type'] = $index_type;
420 $indices[$name]['fields'][] = strtolower($row['Column_name']);
426 * @see DBHelper::get_columns()
428 public function get_columns(
432 //find all unique indexes and primary keys.
433 $result = $this->db->query("sp_columns $tablename");
436 while (($row=$this->db->fetchByAssoc($result)) !=null) {
437 $column_name = strtolower($row['COLUMN_NAME']);
438 $columns[$column_name]['name']=$column_name;
439 $columns[$column_name]['type']=strtolower($row['TYPE_NAME']);
440 if ( $row['TYPE_NAME'] == 'decimal' ) {
441 $columns[$column_name]['len']=strtolower($row['PRECISION']);
442 $columns[$column_name]['len'].=','.strtolower($row['SCALE']);
444 elseif ( in_array($row['TYPE_NAME'],array('nchar','nvarchar')) )
445 $columns[$column_name]['len']=strtolower($row['PRECISION']);
446 elseif ( !in_array($row['TYPE_NAME'],array('datetime','text','bit')) )
447 $columns[$column_name]['len']=strtolower($row['LENGTH']);
448 if ( stristr($row['TYPE_NAME'],'identity') ) {
449 $columns[$column_name]['auto_increment'] = '1';
450 $columns[$column_name]['type']=str_replace(' identity','',strtolower($row['TYPE_NAME']));
453 if (!empty($row['IS_NULLABLE']) && $row['IS_NULLABLE'] == 'NO' && (empty($row['KEY']) || !stristr($row['KEY'],'PRI')))
454 $columns[strtolower($row['COLUMN_NAME'])]['required'] = 'true';
457 if ( strtolower($tablename) == 'relationships' ) {
458 $column_def = $this->db->getOne("select cdefault from syscolumns where id = object_id('relationships') and name = '$column_name'");
460 if ( $column_def != 0 ) {
462 $row['COLUMN_DEF'] = html_entity_decode($row['COLUMN_DEF'],ENT_QUOTES);
463 if ( preg_match("/\([\(|'](.*)[\)|']\)/i",$row['COLUMN_DEF'],$matches) )
464 $columns[$column_name]['default'] = $matches[1];
465 elseif ( preg_match("/\(N'(.*)'\)/i",$row['COLUMN_DEF'],$matches) )
466 $columns[$column_name]['default'] = $matches[1];
468 $columns[$column_name]['default'] = $row['COLUMN_DEF'];
475 * @see DBHelper::add_drop_constraint()
477 public function add_drop_constraint(
483 $type = $definition['type'];
484 $fields = implode(',',$definition['fields']);
485 $name = $definition['name'];
486 $foreignTable = isset($definition['foreignTable']) ? $definition['foreignTable'] : array();
492 case 'alternate_key':
494 $sql = "DROP INDEX {$name} ON {$table}";
496 $sql = "CREATE INDEX {$name} ON {$table} ({$fields})";
498 // constraints as indices
501 $sql = "ALTER TABLE {$table} DROP CONSTRAINT $name";
503 $sql = "ALTER TABLE {$table} ADD CONSTRAINT {$name} UNIQUE ({$fields})";
507 $sql = "ALTER TABLE {$table} DROP PRIMARY KEY";
509 $sql = "ALTER TABLE {$table} ADD CONSTRAINT {$name} PRIMARY KEY ({$fields})";
513 $sql = "ALTER TABLE {$table} DROP FOREIGN KEY ({$fields})";
515 $sql = "ALTER TABLE {$table} ADD CONSTRAINT {$name} FOREIGN KEY ({$fields}) REFERENCES {$foreignTable}({$foreignfields})";
518 if ($this->full_text_indexing_enabled() && $drop)
519 $sql = "DROP FULLTEXT INDEX ON {$table}";
520 elseif ($this->full_text_indexing_enabled()) {
521 $catalog_name="sugar_fts_catalog";
522 if ( isset($index['catalog_name']) && $index['catalog_name'] != 'default')
523 $catalog_name = $index['catalog_name'];
525 $language = "Language 1033";
526 if (isset($index['language']) && !empty($index['language']))
527 $language = "Language " . $index['language'];
529 $key_index = $index['key_index'];
531 $change_tracking = "auto";
532 if (isset($index['change_tracking']) && !empty($index['change_tracking']))
533 $change_tracking = $index['change_tracking'];
535 $columns[] = " CREATE FULLTEXT INDEX ON $table ($fields $language) KEY INDEX $key_index ON $catalog_name WITH CHANGE_TRACKING $change_tracking" ;
543 * @see DBHelper::number_of_columns()
545 public function number_of_columns(
549 $def_query = <<<EOSQL
550 SELECT count(*) as cols
551 FROM sys.columns col join sys.types col_type
552 on col.user_type_id=col_type.user_type_id
553 where col.object_id = (
554 select object_id(sys.schemas.name + '.' + sys.tables.name)
555 from sys.tables join sys.schemas
556 on sys.schemas.schema_id = sys.tables.schema_id
557 where sys.tables.name='$table_name'
561 * @TODO test the similarities of the above the query against all system tables vs the query below against
562 * the information_schema view in terms of results and efficiency. suspician is provided the two produce
563 * the same information the latter will be slightly faster.
566 * $def_query = "SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='$table_name'";
571 $result = $this->db->query($def_query);
572 $row = $this->db->fetchByAssoc($result);
580 * Returns true if Full Text Search is installed
584 protected function full_text_indexing_installed()
586 $ftsChckRes = $this->db->query(
587 "SELECT FULLTEXTSERVICEPROPERTY('IsFulltextInstalled') as fts");
588 $row = $this->db->fetchByAssoc($ftsChckRes);
590 return (isset($row) && isset($row['fts']) && ($row['fts'] == 1 || $row['fts'] == '1'));
594 * @see DBHelper::full_text_indexing_enabled()
596 protected function full_text_indexing_enabled(
600 // check to see if we already have install setting in session
601 if(!isset($_SESSION['IsFulltextInstalled']))
602 $_SESSION['IsFulltextInstalled'] = $this->full_text_indexing_installed();
604 // check to see if FTS Indexing service is installed
605 if(empty($_SESSION['IsFulltextInstalled'])
606 || $_SESSION['IsFulltextInstalled'] === false)
609 // grab the dbname if it was not passed through
610 if (empty($dbname)) {
611 global $sugar_config;
612 $dbname = $sugar_config['dbconfig']['db_name'];
614 //we already know that Indexing service is installed, now check
615 //to see if it is enabled
616 $res = $this->db->query(
617 "SELECT DATABASEPROPERTY('$dbname', 'IsFulltextEnabled') ftext");
618 $row = $GLOBALS['db']->fetchByAssoc($res);
620 return (isset($row['ftext']) && $row['ftext'] == 1);
624 * Creates default full text catalog
626 public function create_default_full_text_catalog()
628 if ($this->full_text_indexing_enabled()) {
629 $GLOBALS['log']->debug('Creating the default catalog for full-text indexing, sugar_fts_catalog');
631 //drop catalog if exists.
632 $ret = $this->db->query("
635 from sys.fulltext_catalogs
636 where name ='sugar_fts_catalog'
638 CREATE FULLTEXT CATALOG sugar_fts_catalog");
641 $GLOBALS['log']->error('Error creating default full-text catalog, sugar_fts_catalog');
647 * Function returns name of the constraint automatically generated by sql-server.
648 * We request this for default, primary key, required
650 * @param string $table
651 * @param string $column
654 private function get_field_default_constraint_name(
659 static $results = array();
661 if ( empty($column) && isset($results[$table]) )
662 return $results[$table];
665 select s.name, o.name, c.name dtrt, d.name ctrt
666 from sys.default_constraints as d
667 join sys.objects as o
668 on o.object_id = d.parent_object_id
669 join sys.columns as c
670 on c.object_id = o.object_id and c.column_id = d.parent_column_id
671 join sys.schemas as s
672 on s.schema_id = o.schema_id
673 where o.name = '$table'
675 if ( !empty($column) )
676 $query .= " and c.name = '$column'";
677 $res = $this->db->query($query);
678 if ( !empty($column) ) {
679 $row = $this->db->fetchByAssoc($res);
684 $returnResult = array();
685 while ( $row = $this->db->fetchByAssoc($res) )
686 $returnResult[$row['dtrt']] = $row['ctrt'];
687 $results[$table] = $returnResult;
688 return $returnResult;
695 * @see DBHelper::massageFieldDef()
697 public function massageFieldDef(
702 parent::massageFieldDef($fieldDef,$tablename);
704 if ($fieldDef['type'] == 'int')
705 $fieldDef['len'] = '4';
706 if ($fieldDef['type'] == 'bit' && empty($fieldDef['len']) )
707 $fieldDef['len'] = '1';
708 if ($fieldDef['type'] == 'bool' && empty($fieldDef['len']) )
709 $fieldDef['len'] = '1';
710 if ($fieldDef['type'] == 'float' && empty($fieldDef['len']) )
711 $fieldDef['len'] = '8';
712 if ($fieldDef['type'] == 'varchar' && empty($fieldDef['len']) )
713 $fieldDef['len'] = '255';
714 if ($fieldDef['type'] == 'nvarchar' && empty($fieldDef['len']) )
715 $fieldDef['len'] = '255';
716 if ($fieldDef['type'] == 'bit' && empty($fieldDef['default']) )
717 $fieldDef['default'] = '0';
718 if ($fieldDef['type'] == 'bool' && empty($fieldDef['default']) )
719 $fieldDef['default'] = '0';
720 if ($fieldDef['type'] == 'image' && empty($fieldDef['len']) )
721 $fieldDef['len'] = '2147483647';
722 if ($fieldDef['type'] == 'ntext' && empty($fieldDef['len']) )
723 $fieldDef['len'] = '2147483646';
724 if ($fieldDef['type'] == 'smallint' && empty($fieldDef['len']) )
725 $fieldDef['len'] = '2';
726 if (isset($fieldDef['required']) && $fieldDef['required'] && !isset($fieldDef['default']) )
727 $fieldDef['default'] = '';
731 * @see DBHelper::oneColumnSQLRep()
733 protected function oneColumnSQLRep(
735 $ignoreRequired = false,
737 $return_as_array = false
741 if(isset($fieldDef['name'])){
742 $name = $fieldDef['name'];
743 $type = $this->getFieldType($fieldDef);
744 $colType = $this->getColumnType($type, $name, $table);
745 if(stristr($colType, 'decimal')){
746 $fieldDef['len'] = isset($fieldDef['len'])? min($fieldDef['len'],38) : 38;
748 //bug: 39690 float(8) is interpreted as real and this generates a diff when doing repair
749 if(stristr($colType, 'float')){
750 if(isset($fieldDef['len']) && $fieldDef['len'] == 8){
751 unset($fieldDef['len']);
756 $ref = parent::oneColumnSQLRep($fieldDef, $ignoreRequired, $table, true);
758 // Bug 24307 - Don't add precision for float fields.
759 if ( stristr($ref['colType'],'float') )
760 $ref['colType'] = preg_replace('/(,\d+)/','',$ref['colType']);
762 if ( $return_as_array )
765 return "{$ref['name']} {$ref['colType']} {$ref['default']} {$ref['required']} {$ref['auto_increment']}";
769 * Saves changes to module's audit table
771 * @param object $bean Sugarbean instance
772 * @param array $changes changes
773 * @see DBHelper::getDataChanges()
775 public function save_audit_records(
780 //Bug 25078 fixed by Martin Hu: sqlserver haven't 'date' type, trim extra "00:00:00"
781 if($changes['data_type'] == 'date'){
782 $changes['before'] = str_replace(' 00:00:00','',$changes['before']);
784 parent::save_audit_records($bean,$changes);