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 * @see DBHelper::getColumnType()
58 public function getColumnType(
71 'short' => 'smallint',
72 'varchar' => 'varchar',
77 'relate' => 'varchar',
80 'datetime' => 'datetime',
81 'datetimecombo' => 'datetime',
84 'tinyint' => 'tinyint',
87 'longblob' => 'image',
88 'currency' => 'decimal(26,6)',
89 'decimal' => 'decimal',
90 'decimal2' => 'decimal',
91 'id' => 'varchar(36)',
101 * @see DBHelper::dropTableNameSQL()
103 public function dropTableNameSQL(
107 return "DROP TABLE ".$name;
111 * Returns the SQL Alter table statment
113 * MSSQL has a quirky T-SQL alter table syntax. Pay special attention to the
115 * @param string $action
117 * @param bool $ignorRequired
118 * @param string $tablename
120 private function alterSQLRep(
129 $f_def=$this->oneColumnSQLRep($def, $ignoreRequired,$tablename,false);
130 return "ADD " . $f_def;
133 return "DROP COLUMN " . $def['name'];
136 //You cannot specify a default value for a column for MSSQL
137 $f_def = $this->oneColumnSQLRep($def, $ignoreRequired,$tablename, true);
138 $f_stmt = "ALTER COLUMN ".$f_def['name'].' '.$f_def['colType'].' '.
139 $f_def['required'].' '.$f_def['auto_increment']."\n";
140 if (!empty( $f_def['default']))
141 $f_stmt .= " ALTER TABLE " . $tablename . " ADD ". $f_def['default'] . " FOR " . $def['name'];
150 * @see DBHelper::changeColumnSQL()
152 * MSSQL uses a different syntax than MySQL for table altering that is
153 * not quite as simplistic to implement...
155 protected function changeColumnSQL(
159 $ignoreRequired = false
163 $constraints = $this->get_field_default_constraint_name($tablename);
164 if ($this->isFieldArray($fieldDefs)) {
165 foreach ($fieldDefs as $def)
167 //if the column is being modified drop the default value
168 //constraint if it exists. alterSQLRep will add the constraint back
169 if (!empty($constraints[$def['name']])) {
170 $sql.=" ALTER TABLE " . $tablename . " DROP CONSTRAINT " . $constraints[$def['name']];
172 //check to see if we need to drop related indexes before the alter
173 $indices = $this->get_indices($tablename);
174 foreach ( $indices as $index ) {
175 if ( in_array($def['name'],$index['fields']) ) {
176 $sql .= ' ' . $this->add_drop_constraint($tablename,$index,true).' ';
177 $sql2 .= ' ' . $this->add_drop_constraint($tablename,$index,false).' ';
181 $columns[] = $this->alterSQLRep($action, $def, $ignoreRequired,$tablename);
185 //if the column is being modified drop the default value
186 //constraint if it exists. alterSQLRep will add the constraint back
187 if (!empty($constraints[$fieldDefs['name']])) {
188 $sql.=" ALTER TABLE " . $tablename . " DROP CONSTRAINT " . $constraints[$fieldDefs['name']];
190 //check to see if we need to drop related indexes before the alter
191 $indices = $this->get_indices($tablename);
192 foreach ( $indices as $index ) {
193 if ( in_array($fieldDefs['name'],$index['fields']) ) {
194 $sql .= ' ' . $this->add_drop_constraint($tablename,$index,true).' ';
195 $sql2 .= ' ' . $this->add_drop_constraint($tablename,$index,false).' ';
200 $columns[] = $this->alterSQLRep($action, $fieldDefs, $ignoreRequired,$tablename);
203 $columns = implode(", ", $columns);
204 $sql .= " ALTER TABLE $tablename $columns " . $sql2;
210 * @see DBHelper::deleteColumnSQL()
212 public function deleteColumnSQL(
217 if ($this->isFieldArray($fieldDefs))
218 foreach ($fieldDefs as $fieldDef)
219 $columns[] = $fieldDef['name'];
221 $columns[] = $fieldDefs['name'];
223 return "ALTER TABLE ".$bean->getTableName()." DROP COLUMN ".implode(", DROP COLUMN ", $columns);
227 * returns an alter table statement to build the list of indices
229 * @param string $tableName
230 * @param array $fieldDefs
231 * @param array $indices
232 * @return string SQL statement
234 public function indexSQL(
240 // check if the passed value is an array of fields.
241 // if not, convert it into an array
242 if (!$this->isFieldArray($indices))
243 $indices[] = $indices;
246 foreach ($indices as $index) {
247 if(!empty($index['db']) && $index['db'] != 'mssql')
249 if (isset($index['source']) && $index['source'] != 'db')
252 $type = $index['type'];
253 $name = $index['name'];
255 if (is_array($index['fields']))
256 $fields = implode(", ", $index['fields']);
258 $fields = $index['fields'];
262 // SQL server requires primary key constraints to be created with
263 // key word "PRIMARY KEY". Cannot default to index as synonym
264 $columns[] = "ALTER TABLE $tableName ADD CONSTRAINT pk_$tableName PRIMARY KEY ($fields)";
267 $columns[] = "ALTER TABLE $tableName ADD CONSTRAINT " . $index['name'] . " UNIQUE ($fields)";
270 $columns[] = "CREATE CLUSTERED INDEX $name ON $tableName ( $fields )";
273 case 'alternate_key':
275 $columns[] = "CREATE INDEX $name ON $tableName ( $fields )";
278 if ($this->full_text_indexing_enabled()) {
279 $catalog_name="sugar_fts_catalog";
280 if ( isset($index['catalog_name'])
281 && $index['catalog_name'] != 'default')
282 $catalog_name = $index['catalog_name'];
284 $language = "Language 1033";
285 if (isset($index['language']) && !empty($index['language']))
286 $language = "Language " . $index['language'];
288 $key_index = $index['key_index'];;
290 $change_tracking = "auto";
291 if (isset($index['change_tracking'])
292 && !empty($index['change_tracking']))
293 $change_tracking = $index['change_tracking'];
295 $columns[] = " CREATE FULLTEXT INDEX ON $tableName($fields $language) KEY INDEX $key_index ON $catalog_name WITH CHANGE_TRACKING $change_tracking" ;
301 $columns = implode(" ", $columns);
306 protected function setAutoIncrement(
311 return "identity(1,1)";
315 * @see DBHelper::setAutoIncrementStart()
317 public function setAutoIncrementStart(
325 $this->db->query("DBCC CHECKIDENT ('$table', RESEED, $start_value)");
330 * @see DBHelper::getAutoIncrement()
332 public function getAutoIncrement(
339 $result = $this->db->query("select IDENT_CURRENT('$table') + IDENT_INCR ( '$table' ) as 'Auto_increment'");
340 $row = $this->db->fetchByAssoc($result);
341 if (!empty($row['Auto_increment']))
342 return $row['Auto_increment'];
348 * @see DBHelper::createTableSQLParams()
350 public function createTableSQLParams(
357 if (empty($tablename) || empty($fieldDefs))
361 $columns = $this->columnSQLRep($fieldDefs, false, $tablename);
365 return "CREATE TABLE $tablename ($columns ) " .
366 $this->indexSQL($tablename, $fieldDefs, $indices);
370 * @see DBHelper::get_indices()
372 public function get_indices(
376 //find all unique indexes and primary keys.
378 SELECT LEFT(so.[name], 30) TableName,
379 LEFT(si.[name], 50) 'Key_name',
380 LEFT(sik.[keyno], 30) Sequence,
381 LEFT(sc.[name], 30) Column_name,
383 WHEN si.status & 2 = 2 AND so.xtype != 'PK' THEN 1
387 INNER JOIN sysindexkeys sik
388 ON (si.[id] = sik.[id] AND si.indid = sik.indid)
389 INNER JOIN sysobjects so
391 INNER JOIN syscolumns sc
392 ON (so.[id] = sc.[id] AND sik.colid = sc.colid)
393 INNER JOIN sysfilegroups sfg
394 ON si.groupid = sfg.groupid
395 WHERE so.[name] = '$tablename'
396 ORDER BY Key_name, Sequence, Column_name
398 $result = $this->db->query($query);
401 while (($row=$this->db->fetchByAssoc($result)) != null) {
402 $index_type = 'index';
403 if ($row['Key_name'] == 'PRIMARY')
404 $index_type = 'primary';
405 elseif ($row['isunique'] == 1 )
406 $index_type = 'unique';
407 $name = strtolower($row['Key_name']);
408 $indices[$name]['name'] = $name;
409 $indices[$name]['type'] = $index_type;
410 $indices[$name]['fields'][] = strtolower($row['Column_name']);
416 * @see DBHelper::get_columns()
418 public function get_columns(
422 //find all unique indexes and primary keys.
423 $result = $this->db->query("sp_columns $tablename");
426 while (($row=$this->db->fetchByAssoc($result)) !=null) {
427 $column_name = strtolower($row['COLUMN_NAME']);
428 $columns[$column_name]['name']=$column_name;
429 $columns[$column_name]['type']=strtolower($row['TYPE_NAME']);
430 if ( $row['TYPE_NAME'] == 'decimal' ) {
431 $columns[$column_name]['len']=strtolower($row['PRECISION']);
432 $columns[$column_name]['len'].=','.strtolower($row['SCALE']);
434 elseif ( in_array($row['TYPE_NAME'],array('nchar','nvarchar')) )
435 $columns[$column_name]['len']=strtolower($row['PRECISION']);
436 elseif ( !in_array($row['TYPE_NAME'],array('datetime','text','bit')) )
437 $columns[$column_name]['len']=strtolower($row['LENGTH']);
438 if ( stristr($row['TYPE_NAME'],'identity') ) {
439 $columns[$column_name]['auto_increment'] = '1';
440 $columns[$column_name]['type']=str_replace(' identity','',strtolower($row['TYPE_NAME']));
443 if (!empty($row['IS_NULLABLE']) && $row['IS_NULLABLE'] == 'NO' && (empty($row['KEY']) || !stristr($row['KEY'],'PRI')))
444 $columns[strtolower($row['COLUMN_NAME'])]['required'] = 'true';
447 if ( strtolower($tablename) == 'relationships' ) {
448 $column_def = $this->db->getOne("select cdefault from syscolumns where id = object_id('relationships') and name = '$column_name'");
450 if ( $column_def != 0 ) {
452 $row['COLUMN_DEF'] = html_entity_decode($row['COLUMN_DEF'],ENT_QUOTES);
453 if ( preg_match("/\([\(|'](.*)[\)|']\)/i",$row['COLUMN_DEF'],$matches) )
454 $columns[$column_name]['default'] = $matches[1];
455 elseif ( preg_match("/\(N'(.*)'\)/i",$row['COLUMN_DEF'],$matches) )
456 $columns[$column_name]['default'] = $matches[1];
458 $columns[$column_name]['default'] = $row['COLUMN_DEF'];
465 * @see DBHelper::add_drop_constraint()
467 public function add_drop_constraint(
473 $type = $definition['type'];
474 $fields = implode(',',$definition['fields']);
475 $name = $definition['name'];
476 $foreignTable = isset($definition['foreignTable']) ? $definition['foreignTable'] : array();
482 case 'alternate_key':
484 $sql = "DROP INDEX {$name} ON {$table}";
486 $sql = "CREATE INDEX {$name} ON {$table} ({$fields})";
488 // constraints as indices
491 $sql = "ALTER TABLE {$table} DROP CONSTRAINT $name";
493 $sql = "ALTER TABLE {$table} ADD CONSTRAINT {$name} UNIQUE ({$fields})";
497 $sql = "ALTER TABLE {$table} DROP PRIMARY KEY";
499 $sql = "ALTER TABLE {$table} ADD CONSTRAINT {$name} PRIMARY KEY ({$fields})";
503 $sql = "ALTER TABLE {$table} DROP FOREIGN KEY ({$fields})";
505 $sql = "ALTER TABLE {$table} ADD CONSTRAINT {$name} FOREIGN KEY ({$fields}) REFERENCES {$foreignTable}({$foreignfields})";
508 if ($this->full_text_indexing_enabled() && $drop)
509 $sql = "DROP FULLTEXT INDEX ON {$table}";
510 elseif ($this->full_text_indexing_enabled()) {
511 $catalog_name="sugar_fts_catalog";
512 if ( isset($index['catalog_name']) && $index['catalog_name'] != 'default')
513 $catalog_name = $index['catalog_name'];
515 $language = "Language 1033";
516 if (isset($index['language']) && !empty($index['language']))
517 $language = "Language " . $index['language'];
519 $key_index = $index['key_index'];
521 $change_tracking = "auto";
522 if (isset($index['change_tracking']) && !empty($index['change_tracking']))
523 $change_tracking = $index['change_tracking'];
525 $columns[] = " CREATE FULLTEXT INDEX ON $table ($fields $language) KEY INDEX $key_index ON $catalog_name WITH CHANGE_TRACKING $change_tracking" ;
533 * @see DBHelper::number_of_columns()
535 public function number_of_columns(
539 $def_query = <<<EOSQL
540 SELECT count(*) as cols
541 FROM sys.columns col join sys.types col_type
542 on col.user_type_id=col_type.user_type_id
543 where col.object_id = (
544 select object_id(sys.schemas.name + '.' + sys.tables.name)
545 from sys.tables join sys.schemas
546 on sys.schemas.schema_id = sys.tables.schema_id
547 where sys.tables.name='$table_name'
551 * @TODO test the similarities of the above the query against all system tables vs the query below against
552 * the information_schema view in terms of results and efficiency. suspician is provided the two produce
553 * the same information the latter will be slightly faster.
556 * $def_query = "SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='$table_name'";
561 $result = $this->db->query($def_query);
562 $row = $this->db->fetchByAssoc($result);
570 * Returns true if Full Text Search is installed
574 protected function full_text_indexing_installed()
576 $ftsChckRes = $this->db->query(
577 "SELECT FULLTEXTSERVICEPROPERTY('IsFulltextInstalled') as fts");
578 $row = $this->db->fetchByAssoc($ftsChckRes);
580 return (isset($row) && isset($row['fts']) && ($row['fts'] == 1 || $row['fts'] == '1'));
584 * @see DBHelper::full_text_indexing_enabled()
586 protected function full_text_indexing_enabled(
590 // check to see if we already have install setting in session
591 if(!isset($_SESSION['IsFulltextInstalled']))
592 $_SESSION['IsFulltextInstalled'] = $this->full_text_indexing_installed();
594 // check to see if FTS Indexing service is installed
595 if(empty($_SESSION['IsFulltextInstalled'])
596 || $_SESSION['IsFulltextInstalled'] === false)
599 // grab the dbname if it was not passed through
600 if (empty($dbname)) {
601 global $sugar_config;
602 $dbname = $sugar_config['dbconfig']['db_name'];
604 //we already know that Indexing service is installed, now check
605 //to see if it is enabled
606 $res = $this->db->query(
607 "SELECT DATABASEPROPERTY('$dbname', 'IsFulltextEnabled') ftext");
608 $row = $GLOBALS['db']->fetchByAssoc($res);
610 return (isset($row['ftext']) && $row['ftext'] == 1);
614 * Creates default full text catalog
616 public function create_default_full_text_catalog()
618 if ($this->full_text_indexing_enabled()) {
619 $GLOBALS['log']->debug('Creating the default catalog for full-text indexing, sugar_fts_catalog');
621 //drop catalog if exists.
622 $ret = $this->db->query("
625 from sys.fulltext_catalogs
626 where name ='sugar_fts_catalog'
628 CREATE FULLTEXT CATALOG sugar_fts_catalog");
631 $GLOBALS['log']->error('Error creating default full-text catalog, sugar_fts_catalog');
637 * Function returns name of the constraint automatically generated by sql-server.
638 * We request this for default, primary key, required
640 * @param string $table
641 * @param string $column
644 private function get_field_default_constraint_name(
649 static $results = array();
651 if ( empty($column) && isset($results[$table]) )
652 return $results[$table];
655 select s.name, o.name, c.name dtrt, d.name ctrt
656 from sys.default_constraints as d
657 join sys.objects as o
658 on o.object_id = d.parent_object_id
659 join sys.columns as c
660 on c.object_id = o.object_id and c.column_id = d.parent_column_id
661 join sys.schemas as s
662 on s.schema_id = o.schema_id
663 where o.name = '$table'
665 if ( !empty($column) )
666 $query .= " and c.name = '$column'";
667 $res = $this->db->query($query);
668 if ( !empty($column) ) {
669 $row = $this->db->fetchByAssoc($res);
674 $returnResult = array();
675 while ( $row = $this->db->fetchByAssoc($res) )
676 $returnResult[$row['dtrt']] = $row['ctrt'];
677 $results[$table] = $returnResult;
678 return $returnResult;
685 * @see DBHelper::massageFieldDef()
687 public function massageFieldDef(
692 parent::massageFieldDef($fieldDef,$tablename);
694 if ($fieldDef['type'] == 'int')
695 $fieldDef['len'] = '4';
696 if ($fieldDef['type'] == 'bit' && empty($fieldDef['len']) )
697 $fieldDef['len'] = '1';
698 if ($fieldDef['type'] == 'bool' && empty($fieldDef['len']) )
699 $fieldDef['len'] = '1';
700 if ($fieldDef['type'] == 'float' && empty($fieldDef['len']) )
701 $fieldDef['len'] = '8';
702 if ($fieldDef['type'] == 'varchar' && empty($fieldDef['len']) )
703 $fieldDef['len'] = '255';
704 if ($fieldDef['type'] == 'nvarchar' && empty($fieldDef['len']) )
705 $fieldDef['len'] = '255';
706 if ($fieldDef['type'] == 'bit' && empty($fieldDef['default']) )
707 $fieldDef['default'] = '0';
708 if ($fieldDef['type'] == 'bool' && empty($fieldDef['default']) )
709 $fieldDef['default'] = '0';
710 if ($fieldDef['type'] == 'image' && empty($fieldDef['len']) )
711 $fieldDef['len'] = '2147483647';
712 if ($fieldDef['type'] == 'ntext' && empty($fieldDef['len']) )
713 $fieldDef['len'] = '2147483646';
714 if ($fieldDef['type'] == 'smallint' && empty($fieldDef['len']) )
715 $fieldDef['len'] = '2';
716 if (isset($fieldDef['required']) && $fieldDef['required'] && !isset($fieldDef['default']) )
717 $fieldDef['default'] = '';
721 * @see DBHelper::oneColumnSQLRep()
723 protected function oneColumnSQLRep(
725 $ignoreRequired = false,
727 $return_as_array = false
731 if(isset($fieldDef['name'])){
732 $name = $fieldDef['name'];
733 $type = $this->getFieldType($fieldDef);
734 $colType = $this->getColumnType($type, $name, $table);
735 if(stristr($colType, 'decimal')){
736 $fieldDef['len'] = isset($fieldDef['len'])? min($fieldDef['len'],38) : 38;
738 //bug: 39690 float(8) is interpreted as real and this generates a diff when doing repair
739 if(stristr($colType, 'float')){
740 if(isset($fieldDef['len']) && $fieldDef['len'] == 8){
741 unset($fieldDef['len']);
746 $ref = parent::oneColumnSQLRep($fieldDef, $ignoreRequired, $table, true);
748 // Bug 24307 - Don't add precision for float fields.
749 if ( stristr($ref['colType'],'float') )
750 $ref['colType'] = preg_replace('/(,\d+)/','',$ref['colType']);
752 if ( $return_as_array )
755 return "{$ref['name']} {$ref['colType']} {$ref['default']} {$ref['required']} {$ref['auto_increment']}";
759 * Saves changes to module's audit table
761 * @param object $bean Sugarbean instance
762 * @param array $changes changes
763 * @see DBHelper::getDataChanges()
765 public function save_audit_records(
770 //Bug 25078 fixed by Martin Hu: sqlserver haven't 'date' type, trim extra "00:00:00"
771 if($changes['data_type'] == 'date'){
772 $changes['before'] = str_replace(' 00:00:00','',$changes['before']);
774 parent::save_audit_records($bean,$changes);