1 <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
5 * An open source application development framework for PHP 5.1.6 or newer
8 * @author ExpressionEngine Dev Team
9 * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc.
10 * @license http://codeigniter.com/user_guide/license.html
11 * @link http://codeigniter.com
16 // ------------------------------------------------------------------------
19 * MS SQL Database Adapter Class
21 * Note: _DB is an extender class that the app controller
22 * creates dynamically based on whether the active record
23 * class is being used or not.
25 * @package CodeIgniter
28 * @author ExpressionEngine Dev Team
29 * @link http://codeigniter.com/user_guide/database/
31 class CI_DB_mssql_driver extends CI_DB {
33 var $dbdriver = 'mssql';
35 // The character used for escaping
36 var $_escape_char = '';
38 // clause and character used for LIKE escape sequences
39 var $_like_escape_str = " ESCAPE '%s' ";
40 var $_like_escape_chr = '!';
43 * The syntax to count rows is slightly different across different
44 * database engines, so this string appears in each driver and is
45 * used for the count_all() and count_all_results() functions.
47 var $_count_string = "SELECT COUNT(*) AS ";
48 var $_random_keyword = ' ASC'; // not currently supported
51 * Non-persistent database connection
53 * @access private called by the base class
58 if ($this->port != '')
60 $this->hostname .= ','.$this->port;
63 return @mssql_connect($this->hostname, $this->username, $this->password);
66 // --------------------------------------------------------------------
69 * Persistent database connection
71 * @access private called by the base class
74 function db_pconnect()
76 if ($this->port != '')
78 $this->hostname .= ','.$this->port;
81 return @mssql_pconnect($this->hostname, $this->username, $this->password);
84 // --------------------------------------------------------------------
89 * Keep / reestablish the db connection if no queries have been
90 * sent for a length of time exceeding the server's idle timeout
97 // not implemented in MSSQL
100 // --------------------------------------------------------------------
103 * Select the database
105 * @access private called by the base class
110 // Note: The brackets are required in the event that the DB name
111 // contains reserved characters
112 return @mssql_select_db('['.$this->database.']', $this->conn_id);
115 // --------------------------------------------------------------------
118 * Set client character set
125 function db_set_charset($charset, $collation)
127 // @todo - add support if needed
131 // --------------------------------------------------------------------
136 * @access private called by the base class
137 * @param string an SQL query
140 function _execute($sql)
142 $sql = $this->_prep_query($sql);
143 return @mssql_query($sql, $this->conn_id);
146 // --------------------------------------------------------------------
151 * If needed, each database adapter can prep the query string
153 * @access private called by execute()
154 * @param string an SQL query
157 function _prep_query($sql)
162 // --------------------------------------------------------------------
170 function trans_begin($test_mode = FALSE)
172 if ( ! $this->trans_enabled)
177 // When transactions are nested we only begin/commit/rollback the outermost ones
178 if ($this->_trans_depth > 0)
183 // Reset the transaction failure flag.
184 // If the $test_mode flag is set to TRUE transactions will be rolled back
185 // even if the queries produce a successful result.
186 $this->_trans_failure = ($test_mode === TRUE) ? TRUE : FALSE;
188 $this->simple_query('BEGIN TRAN');
192 // --------------------------------------------------------------------
200 function trans_commit()
202 if ( ! $this->trans_enabled)
207 // When transactions are nested we only begin/commit/rollback the outermost ones
208 if ($this->_trans_depth > 0)
213 $this->simple_query('COMMIT TRAN');
217 // --------------------------------------------------------------------
220 * Rollback Transaction
225 function trans_rollback()
227 if ( ! $this->trans_enabled)
232 // When transactions are nested we only begin/commit/rollback the outermost ones
233 if ($this->_trans_depth > 0)
238 $this->simple_query('ROLLBACK TRAN');
242 // --------------------------------------------------------------------
249 * @param bool whether or not the string will be used in a LIKE condition
252 function escape_str($str, $like = FALSE)
256 foreach ($str as $key => $val)
258 $str[$key] = $this->escape_str($val, $like);
264 // Escape single quotes
265 $str = str_replace("'", "''", remove_invisible_characters($str));
267 // escape LIKE condition wildcards
271 array($this->_like_escape_chr, '%', '_'),
272 array($this->_like_escape_chr.$this->_like_escape_chr, $this->_like_escape_chr.'%', $this->_like_escape_chr.'_'),
280 // --------------------------------------------------------------------
288 function affected_rows()
290 return @mssql_rows_affected($this->conn_id);
293 // --------------------------------------------------------------------
298 * Returns the last id created in the Identity column.
305 $ver = self::_parse_major_version($this->version());
306 $sql = ($ver >= 8 ? "SELECT SCOPE_IDENTITY() AS last_id" : "SELECT @@IDENTITY AS last_id");
307 $query = $this->query($sql);
308 $row = $query->row();
309 return $row->last_id;
312 // --------------------------------------------------------------------
315 * Parse major version
317 * Grabs the major version number from the
318 * database server version string passed in.
321 * @param string $version
322 * @return int16 major version number
324 function _parse_major_version($version)
326 preg_match('/([0-9]+)\.([0-9]+)\.([0-9]+)/', $version, $ver_info);
327 return $ver_info[1]; // return the major version b/c that's all we're interested in.
330 // --------------------------------------------------------------------
333 * Version number query string
340 return "SELECT @@VERSION AS ver";
343 // --------------------------------------------------------------------
348 * Generates a platform-specific query string that counts all records in
349 * the specified database
355 function count_all($table = '')
362 $query = $this->query($this->_count_string . $this->_protect_identifiers('numrows') . " FROM " . $this->_protect_identifiers($table, TRUE, NULL, FALSE));
364 if ($query->num_rows() == 0)
369 $row = $query->row();
370 return (int) $row->numrows;
373 // --------------------------------------------------------------------
378 * Generates a platform-specific query string so that the table names can be fetched
384 function _list_tables($prefix_limit = FALSE)
386 $sql = "SELECT name FROM sysobjects WHERE type = 'U' ORDER BY name";
388 // for future compatibility
389 if ($prefix_limit !== FALSE AND $this->dbprefix != '')
391 //$sql .= " LIKE '".$this->escape_like_str($this->dbprefix)."%' ".sprintf($this->_like_escape_str, $this->_like_escape_chr);
392 return FALSE; // not currently supported
398 // --------------------------------------------------------------------
403 * Generates a platform-specific query string so that the column names can be fetched
406 * @param string the table name
409 function _list_columns($table = '')
411 return "SELECT * FROM INFORMATION_SCHEMA.Columns WHERE TABLE_NAME = '".$table."'";
414 // --------------------------------------------------------------------
419 * Generates a platform-specific query so that the column data can be retrieved
422 * @param string the table name
425 function _field_data($table)
427 return "SELECT TOP 1 * FROM ".$table;
430 // --------------------------------------------------------------------
433 * The error message string
438 function _error_message()
440 return mssql_get_last_message();
443 // --------------------------------------------------------------------
446 * The error message number
451 function _error_number()
453 // Are error numbers supported?
457 // --------------------------------------------------------------------
460 * Escape the SQL Identifiers
462 * This function escapes column and table names
468 function _escape_identifiers($item)
470 if ($this->_escape_char == '')
475 foreach ($this->_reserved_identifiers as $id)
477 if (strpos($item, '.'.$id) !== FALSE)
479 $str = $this->_escape_char. str_replace('.', $this->_escape_char.'.', $item);
481 // remove duplicates if the user already included the escape
482 return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $str);
486 if (strpos($item, '.') !== FALSE)
488 $str = $this->_escape_char.str_replace('.', $this->_escape_char.'.'.$this->_escape_char, $item).$this->_escape_char;
492 $str = $this->_escape_char.$item.$this->_escape_char;
495 // remove duplicates if the user already included the escape
496 return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $str);
499 // --------------------------------------------------------------------
504 * This function implicitly groups FROM tables so there is no confusion
505 * about operator precedence in harmony with SQL standards
511 function _from_tables($tables)
513 if ( ! is_array($tables))
515 $tables = array($tables);
518 return implode(', ', $tables);
521 // --------------------------------------------------------------------
526 * Generates a platform-specific insert string from the supplied data
529 * @param string the table name
530 * @param array the insert keys
531 * @param array the insert values
534 function _insert($table, $keys, $values)
536 return "INSERT INTO ".$table." (".implode(', ', $keys).") VALUES (".implode(', ', $values).")";
539 // --------------------------------------------------------------------
544 * Generates a platform-specific update string from the supplied data
547 * @param string the table name
548 * @param array the update data
549 * @param array the where clause
550 * @param array the orderby clause
551 * @param array the limit clause
554 function _update($table, $values, $where, $orderby = array(), $limit = FALSE)
556 foreach ($values as $key => $val)
558 $valstr[] = $key." = ".$val;
561 $limit = ( ! $limit) ? '' : ' LIMIT '.$limit;
563 $orderby = (count($orderby) >= 1)?' ORDER BY '.implode(", ", $orderby):'';
565 $sql = "UPDATE ".$table." SET ".implode(', ', $valstr);
567 $sql .= ($where != '' AND count($where) >=1) ? " WHERE ".implode(" ", $where) : '';
569 $sql .= $orderby.$limit;
575 // --------------------------------------------------------------------
580 * Generates a platform-specific truncate string from the supplied data
581 * If the database does not support the truncate() command
582 * This function maps to "DELETE FROM table"
585 * @param string the table name
588 function _truncate($table)
590 return "TRUNCATE ".$table;
593 // --------------------------------------------------------------------
598 * Generates a platform-specific delete string from the supplied data
601 * @param string the table name
602 * @param array the where clause
603 * @param string the limit clause
606 function _delete($table, $where = array(), $like = array(), $limit = FALSE)
610 if (count($where) > 0 OR count($like) > 0)
612 $conditions = "\nWHERE ";
613 $conditions .= implode("\n", $this->ar_where);
615 if (count($where) > 0 && count($like) > 0)
617 $conditions .= " AND ";
619 $conditions .= implode("\n", $like);
622 $limit = ( ! $limit) ? '' : ' LIMIT '.$limit;
624 return "DELETE FROM ".$table.$conditions.$limit;
627 // --------------------------------------------------------------------
632 * Generates a platform-specific LIMIT clause
635 * @param string the sql query string
636 * @param integer the number of rows to limit the query to
637 * @param integer the offset value
640 function _limit($sql, $limit, $offset)
642 $i = $limit + $offset;
644 return preg_replace('/(^\SELECT (DISTINCT)?)/i','\\1 TOP '.$i.' ', $sql);
647 // --------------------------------------------------------------------
650 * Close DB Connection
656 function _close($conn_id)
658 @mssql_close($conn_id);
665 /* End of file mssql_driver.php */
666 /* Location: ./system/database/drivers/mssql/mssql_driver.php */