1 <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
5 * An open source application development framework for PHP 4.3.2 or newer
8 * @author ExpressionEngine Dev Team
9 * @copyright Copyright (c) 2008 - 2009, 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 // Access the CI object
265 $CI =& get_instance();
267 // Escape single quotes
268 $str = str_replace("'", "''", $CI->input->_remove_invisible_characters($str));
270 // escape LIKE condition wildcards
273 $str = str_replace( array('%', '_', $this->_like_escape_chr),
274 array($this->_like_escape_chr.'%', $this->_like_escape_chr.'_', $this->_like_escape_chr.$this->_like_escape_chr),
281 // --------------------------------------------------------------------
289 function affected_rows()
291 return @mssql_rows_affected($this->conn_id);
294 // --------------------------------------------------------------------
299 * Returns the last id created in the Identity column.
306 $ver = self::_parse_major_version($this->version());
307 $sql = ($ver >= 8 ? "SELECT SCOPE_IDENTITY() AS last_id" : "SELECT @@IDENTITY AS last_id");
308 $query = $this->query($sql);
309 $row = $query->row();
310 return $row->last_id;
313 // --------------------------------------------------------------------
316 * Parse major version
318 * Grabs the major version number from the
319 * database server version string passed in.
322 * @param string $version
323 * @return int16 major version number
325 function _parse_major_version($version)
327 preg_match('/([0-9]+)\.([0-9]+)\.([0-9]+)/', $version, $ver_info);
328 return $ver_info[1]; // return the major version b/c that's all we're interested in.
331 // --------------------------------------------------------------------
334 * Version number query string
341 return "SELECT @@VERSION AS ver";
344 // --------------------------------------------------------------------
349 * Generates a platform-specific query string that counts all records in
350 * the specified database
356 function count_all($table = '')
363 $query = $this->query($this->_count_string . $this->_protect_identifiers('numrows') . " FROM " . $this->_protect_identifiers($table, TRUE, NULL, FALSE));
365 if ($query->num_rows() == 0)
370 $row = $query->row();
371 return (int) $row->numrows;
374 // --------------------------------------------------------------------
379 * Generates a platform-specific query string so that the table names can be fetched
385 function _list_tables($prefix_limit = FALSE)
387 $sql = "SELECT name FROM sysobjects WHERE type = 'U' ORDER BY name";
389 // for future compatibility
390 if ($prefix_limit !== FALSE AND $this->dbprefix != '')
392 //$sql .= " LIKE '".$this->escape_like_str($this->dbprefix)."%' ".sprintf($this->_like_escape_str, $this->_like_escape_char);
393 return FALSE; // not currently supported
399 // --------------------------------------------------------------------
404 * Generates a platform-specific query string so that the column names can be fetched
407 * @param string the table name
410 function _list_columns($table = '')
412 return "SELECT * FROM INFORMATION_SCHEMA.Columns WHERE TABLE_NAME = '".$table."'";
415 // --------------------------------------------------------------------
420 * Generates a platform-specific query so that the column data can be retrieved
423 * @param string the table name
426 function _field_data($table)
428 return "SELECT TOP 1 * FROM ".$table;
431 // --------------------------------------------------------------------
434 * The error message string
439 function _error_message()
441 return mssql_get_last_message();
444 // --------------------------------------------------------------------
447 * The error message number
452 function _error_number()
454 // Are error numbers supported?
458 // --------------------------------------------------------------------
461 * Escape the SQL Identifiers
463 * This function escapes column and table names
469 function _escape_identifiers($item)
471 if ($this->_escape_char == '')
476 foreach ($this->_reserved_identifiers as $id)
478 if (strpos($item, '.'.$id) !== FALSE)
480 $str = $this->_escape_char. str_replace('.', $this->_escape_char.'.', $item);
482 // remove duplicates if the user already included the escape
483 return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $str);
487 if (strpos($item, '.') !== FALSE)
489 $str = $this->_escape_char.str_replace('.', $this->_escape_char.'.'.$this->_escape_char, $item).$this->_escape_char;
493 $str = $this->_escape_char.$item.$this->_escape_char;
496 // remove duplicates if the user already included the escape
497 return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $str);
500 // --------------------------------------------------------------------
505 * This function implicitly groups FROM tables so there is no confusion
506 * about operator precedence in harmony with SQL standards
512 function _from_tables($tables)
514 if ( ! is_array($tables))
516 $tables = array($tables);
519 return implode(', ', $tables);
522 // --------------------------------------------------------------------
527 * Generates a platform-specific insert string from the supplied data
530 * @param string the table name
531 * @param array the insert keys
532 * @param array the insert values
535 function _insert($table, $keys, $values)
537 return "INSERT INTO ".$table." (".implode(', ', $keys).") VALUES (".implode(', ', $values).")";
540 // --------------------------------------------------------------------
545 * Generates a platform-specific update string from the supplied data
548 * @param string the table name
549 * @param array the update data
550 * @param array the where clause
551 * @param array the orderby clause
552 * @param array the limit clause
555 function _update($table, $values, $where, $orderby = array(), $limit = FALSE)
557 foreach($values as $key => $val)
559 $valstr[] = $key." = ".$val;
562 $limit = ( ! $limit) ? '' : ' LIMIT '.$limit;
564 $orderby = (count($orderby) >= 1)?' ORDER BY '.implode(", ", $orderby):'';
566 $sql = "UPDATE ".$table." SET ".implode(', ', $valstr);
568 $sql .= ($where != '' AND count($where) >=1) ? " WHERE ".implode(" ", $where) : '';
570 $sql .= $orderby.$limit;
576 // --------------------------------------------------------------------
581 * Generates a platform-specific truncate string from the supplied data
582 * If the database does not support the truncate() command
583 * This function maps to "DELETE FROM table"
586 * @param string the table name
589 function _truncate($table)
591 return "TRUNCATE ".$table;
594 // --------------------------------------------------------------------
599 * Generates a platform-specific delete string from the supplied data
602 * @param string the table name
603 * @param array the where clause
604 * @param string the limit clause
607 function _delete($table, $where = array(), $like = array(), $limit = FALSE)
611 if (count($where) > 0 OR count($like) > 0)
613 $conditions = "\nWHERE ";
614 $conditions .= implode("\n", $this->ar_where);
616 if (count($where) > 0 && count($like) > 0)
618 $conditions .= " AND ";
620 $conditions .= implode("\n", $like);
623 $limit = ( ! $limit) ? '' : ' LIMIT '.$limit;
625 return "DELETE FROM ".$table.$conditions.$limit;
628 // --------------------------------------------------------------------
633 * Generates a platform-specific LIMIT clause
636 * @param string the sql query string
637 * @param integer the number of rows to limit the query to
638 * @param integer the offset value
641 function _limit($sql, $limit, $offset)
643 $i = $limit + $offset;
645 return preg_replace('/(^\SELECT (DISTINCT)?)/i','\\1 TOP '.$i.' ', $sql);
648 // --------------------------------------------------------------------
651 * Close DB Connection
657 function _close($conn_id)
659 @mssql_close($conn_id);
666 /* End of file mssql_driver.php */
667 /* Location: ./system/database/drivers/mssql/mssql_driver.php */