3 /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
6 * The PEAR DB driver for PHP's mssql extension
7 * for interacting with Microsoft SQL Server databases
11 * LICENSE: This source file is subject to version 3.0 of the PHP license
12 * that is available through the world-wide-web at the following URI:
13 * http://www.php.net/license/3_0.txt. If you did not receive a copy of
14 * the PHP License and are unable to obtain it through the web, please
15 * send a note to license@php.net so we can mail you a copy immediately.
19 * @author Sterling Hughes <sterling@php.net>
20 * @author Daniel Convissor <danielc@php.net>
21 * @copyright 1997-2007 The PHP Group
22 * @license http://www.php.net/license/3_0.txt PHP License 3.0
23 * @version CVS: $Id: mssql.php,v 1.92 2007/09/21 13:40:41 aharvey Exp $
24 * @link http://pear.php.net/package/DB
28 * Obtain the DB_common class so it can be extended from
30 require_once 'DB/common.php';
33 * The methods PEAR DB uses to interact with PHP's mssql extension
34 * for interacting with Microsoft SQL Server databases
36 * These methods overload the ones declared in DB_common.
38 * DB's mssql driver is only for Microsfoft SQL Server databases.
40 * If you're connecting to a Sybase database, you MUST specify "sybase"
41 * as the "phptype" in the DSN.
43 * This class only works correctly if you have compiled PHP using
44 * --with-mssql=[dir_to_FreeTDS].
48 * @author Sterling Hughes <sterling@php.net>
49 * @author Daniel Convissor <danielc@php.net>
50 * @copyright 1997-2007 The PHP Group
51 * @license http://www.php.net/license/3_0.txt PHP License 3.0
52 * @version Release: 1.7.14RC1
53 * @link http://pear.php.net/package/DB
55 class DB_mssql extends DB_common
60 * The DB driver type (mysql, oci8, odbc, etc.)
63 var $phptype = 'mssql';
66 * The database syntax variant to be used (db2, access, etc.), if any
69 var $dbsyntax = 'mssql';
72 * The capabilities of this DB implementation
74 * The 'new_link' element contains the PHP version that first provided
75 * new_link support for this DBMS. Contains false if it's unsupported.
77 * Meaning of the 'limit' element:
78 * + 'emulate' = emulate with fetch row by number
79 * + 'alter' = alter the query
84 var $features = array(
91 'transactions' => true,
95 * A mapping of native error codes to DB error codes
98 // XXX Add here error codes ie: 'S100E' => DB_ERROR_SYNTAX
99 var $errorcode_map = array(
100 102 => DB_ERROR_SYNTAX,
101 110 => DB_ERROR_VALUE_COUNT_ON_ROW,
102 155 => DB_ERROR_NOSUCHFIELD,
103 156 => DB_ERROR_SYNTAX,
104 170 => DB_ERROR_SYNTAX,
105 207 => DB_ERROR_NOSUCHFIELD,
106 208 => DB_ERROR_NOSUCHTABLE,
107 245 => DB_ERROR_INVALID_NUMBER,
108 319 => DB_ERROR_SYNTAX,
109 321 => DB_ERROR_NOSUCHFIELD,
110 325 => DB_ERROR_SYNTAX,
111 336 => DB_ERROR_SYNTAX,
112 515 => DB_ERROR_CONSTRAINT_NOT_NULL,
113 547 => DB_ERROR_CONSTRAINT,
114 1018 => DB_ERROR_SYNTAX,
115 1035 => DB_ERROR_SYNTAX,
116 1913 => DB_ERROR_ALREADY_EXISTS,
117 2209 => DB_ERROR_SYNTAX,
118 2223 => DB_ERROR_SYNTAX,
119 2248 => DB_ERROR_SYNTAX,
120 2256 => DB_ERROR_SYNTAX,
121 2257 => DB_ERROR_SYNTAX,
122 2627 => DB_ERROR_CONSTRAINT,
123 2714 => DB_ERROR_ALREADY_EXISTS,
124 3607 => DB_ERROR_DIVZERO,
125 3701 => DB_ERROR_NOSUCHTABLE,
126 7630 => DB_ERROR_SYNTAX,
127 8134 => DB_ERROR_DIVZERO,
128 9303 => DB_ERROR_SYNTAX,
129 9317 => DB_ERROR_SYNTAX,
130 9318 => DB_ERROR_SYNTAX,
131 9331 => DB_ERROR_SYNTAX,
132 9332 => DB_ERROR_SYNTAX,
133 15253 => DB_ERROR_SYNTAX,
137 * The raw database connection created by PHP
143 * The DSN information for connecting to a database
150 * Should data manipulation queries be committed automatically?
154 var $autocommit = true;
157 * The quantity of transactions begun
159 * {@internal While this is private, it can't actually be designated
160 * private in PHP 5 because it is directly accessed in the test suite.}}
165 var $transaction_opcount = 0;
168 * The database specified in the DSN
170 * It's a fix to allow calls to different databases in the same script.
182 * This constructor calls <kbd>$this->DB_common()</kbd>
195 * Connect to the database server, log in and open the database
197 * Don't call this method directly. Use DB::connect() instead.
199 * @param array $dsn the data source name
200 * @param bool $persistent should the connection be persistent?
202 * @return int DB_OK on success. A DB_Error object on failure.
204 function connect($dsn, $persistent = false)
206 if (!PEAR::loadExtension('mssql') && !PEAR::loadExtension('sybase')
207 && !PEAR::loadExtension('sybase_ct'))
209 return $this->raiseError(DB_ERROR_EXTENSION_NOT_FOUND);
213 if ($dsn['dbsyntax']) {
214 $this->dbsyntax = $dsn['dbsyntax'];
218 $dsn['hostspec'] ? $dsn['hostspec'] : 'localhost',
219 $dsn['username'] ? $dsn['username'] : null,
220 $dsn['password'] ? $dsn['password'] : null,
223 $params[0] .= ((substr(PHP_OS, 0, 3) == 'WIN') ? ',' : ':')
227 $connect_function = $persistent ? 'mssql_pconnect' : 'mssql_connect';
229 $this->connection = @call_user_func_array($connect_function, $params);
231 if (!$this->connection) {
232 return $this->raiseError(DB_ERROR_CONNECT_FAILED,
234 @mssql_get_last_message());
236 if ($dsn['database']) {
237 if (!@mssql_select_db($dsn['database'], $this->connection)) {
238 return $this->raiseError(DB_ERROR_NODBSELECTED,
240 @mssql_get_last_message());
242 $this->_db = $dsn['database'];
251 * Disconnects from the database server
253 * @return bool TRUE on success, FALSE on failure
255 function disconnect()
257 $ret = @mssql_close($this->connection);
258 $this->connection = null;
266 * Sends a query to the database server
268 * @param string the SQL query string
270 * @return mixed + a PHP result resrouce for successful SELECT queries
271 * + the DB_OK constant for other successful queries
272 * + a DB_Error object on failure
274 function simpleQuery($query)
276 $ismanip = $this->_checkManip($query);
277 $this->last_query = $query;
278 if (!@mssql_select_db($this->_db, $this->connection)) {
279 return $this->mssqlRaiseError(DB_ERROR_NODBSELECTED);
281 $query = $this->modifyQuery($query);
282 if (!$this->autocommit && $ismanip) {
283 if ($this->transaction_opcount == 0) {
284 $result = @mssql_query('BEGIN TRAN', $this->connection);
286 return $this->mssqlRaiseError();
289 $this->transaction_opcount++;
291 $result = @mssql_query($query, $this->connection);
293 return $this->mssqlRaiseError();
295 // Determine which queries that should return data, and which
296 // should return an error code only.
297 return $ismanip ? DB_OK : $result;
304 * Move the internal mssql result pointer to the next available result
306 * @param a valid fbsql result resource
310 * @return true if a result is available otherwise return false
312 function nextResult($result)
314 return @mssql_next_result($result);
321 * Places a row from the result set into the given array
323 * Formating of the array and the data therein are configurable.
324 * See DB_result::fetchInto() for more information.
326 * This method is not meant to be called directly. Use
327 * DB_result::fetchInto() instead. It can't be declared "protected"
328 * because DB_result is a separate object.
330 * @param resource $result the query result resource
331 * @param array $arr the referenced array to put the data in
332 * @param int $fetchmode how the resulting array should be indexed
333 * @param int $rownum the row number to fetch (0 = first row)
335 * @return mixed DB_OK on success, NULL when the end of a result set is
336 * reached or on failure
338 * @see DB_result::fetchInto()
340 function fetchInto($result, &$arr, $fetchmode, $rownum = null)
342 if ($rownum !== null) {
343 if (!@mssql_data_seek($result, $rownum)) {
347 if ($fetchmode & DB_FETCHMODE_ASSOC) {
348 $arr = @mssql_fetch_assoc($result);
349 if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE && $arr) {
350 $arr = array_change_key_case($arr, CASE_LOWER);
353 $arr = @mssql_fetch_row($result);
358 if ($this->options['portability'] & DB_PORTABILITY_RTRIM) {
359 $this->_rtrimArrayValues($arr);
361 if ($this->options['portability'] & DB_PORTABILITY_NULL_TO_EMPTY) {
362 $this->_convertNullArrayValuesToEmpty($arr);
371 * Deletes the result set and frees the memory occupied by the result set
373 * This method is not meant to be called directly. Use
374 * DB_result::free() instead. It can't be declared "protected"
375 * because DB_result is a separate object.
377 * @param resource $result PHP's query result resource
379 * @return bool TRUE on success, FALSE if $result is invalid
381 * @see DB_result::free()
383 function freeResult($result)
385 return is_resource($result) ? mssql_free_result($result) : false;
392 * Gets the number of columns in a result set
394 * This method is not meant to be called directly. Use
395 * DB_result::numCols() instead. It can't be declared "protected"
396 * because DB_result is a separate object.
398 * @param resource $result PHP's query result resource
400 * @return int the number of columns. A DB_Error object on failure.
402 * @see DB_result::numCols()
404 function numCols($result)
406 $cols = @mssql_num_fields($result);
408 return $this->mssqlRaiseError();
417 * Gets the number of rows in a result set
419 * This method is not meant to be called directly. Use
420 * DB_result::numRows() instead. It can't be declared "protected"
421 * because DB_result is a separate object.
423 * @param resource $result PHP's query result resource
425 * @return int the number of rows. A DB_Error object on failure.
427 * @see DB_result::numRows()
429 function numRows($result)
431 $rows = @mssql_num_rows($result);
432 if ($rows === false) {
433 return $this->mssqlRaiseError();
442 * Enables or disables automatic commits
444 * @param bool $onoff true turns it on, false turns it off
446 * @return int DB_OK on success. A DB_Error object if the driver
447 * doesn't support auto-committing transactions.
449 function autoCommit($onoff = false)
451 // XXX if $this->transaction_opcount > 0, we should probably
452 // issue a warning here.
453 $this->autocommit = $onoff ? true : false;
461 * Commits the current transaction
463 * @return int DB_OK on success. A DB_Error object on failure.
467 if ($this->transaction_opcount > 0) {
468 if (!@mssql_select_db($this->_db, $this->connection)) {
469 return $this->mssqlRaiseError(DB_ERROR_NODBSELECTED);
471 $result = @mssql_query('COMMIT TRAN', $this->connection);
472 $this->transaction_opcount = 0;
474 return $this->mssqlRaiseError();
484 * Reverts the current transaction
486 * @return int DB_OK on success. A DB_Error object on failure.
490 if ($this->transaction_opcount > 0) {
491 if (!@mssql_select_db($this->_db, $this->connection)) {
492 return $this->mssqlRaiseError(DB_ERROR_NODBSELECTED);
494 $result = @mssql_query('ROLLBACK TRAN', $this->connection);
495 $this->transaction_opcount = 0;
497 return $this->mssqlRaiseError();
504 // {{{ affectedRows()
507 * Determines the number of rows affected by a data maniuplation query
509 * 0 is returned for queries that don't manipulate data.
511 * @return int the number of rows. A DB_Error object on failure.
513 function affectedRows()
515 if ($this->_last_query_manip) {
516 $res = @mssql_query('select @@rowcount', $this->connection);
518 return $this->mssqlRaiseError();
520 $ar = @mssql_fetch_row($res);
524 @mssql_free_result($res);
537 * Returns the next free id in a sequence
539 * @param string $seq_name name of the sequence
540 * @param boolean $ondemand when true, the seqence is automatically
541 * created if it does not exist
543 * @return int the next id number in the sequence.
544 * A DB_Error object on failure.
546 * @see DB_common::nextID(), DB_common::getSequenceName(),
547 * DB_mssql::createSequence(), DB_mssql::dropSequence()
549 function nextId($seq_name, $ondemand = true)
551 $seqname = $this->getSequenceName($seq_name);
552 if (!@mssql_select_db($this->_db, $this->connection)) {
553 return $this->mssqlRaiseError(DB_ERROR_NODBSELECTED);
557 $this->pushErrorHandling(PEAR_ERROR_RETURN);
558 $result = $this->query("INSERT INTO $seqname (vapor) VALUES (0)");
559 $this->popErrorHandling();
560 if ($ondemand && DB::isError($result) &&
561 ($result->getCode() == DB_ERROR || $result->getCode() == DB_ERROR_NOSUCHTABLE))
564 $result = $this->createSequence($seq_name);
565 if (DB::isError($result)) {
566 return $this->raiseError($result);
568 } elseif (!DB::isError($result)) {
569 $result = $this->query("SELECT IDENT_CURRENT('$seqname')");
570 if (DB::isError($result)) {
571 /* Fallback code for MS SQL Server 7.0, which doesn't have
572 * IDENT_CURRENT. This is *not* safe for concurrent
573 * requests, and really, if you're using it, you're in a
574 * world of hurt. Nevertheless, it's here to ensure BC. See
575 * bug #181 for the gory details.*/
576 $result = $this->query("SELECT @@IDENTITY FROM $seqname");
583 if (DB::isError($result)) {
584 return $this->raiseError($result);
586 $result = $result->fetchRow(DB_FETCHMODE_ORDERED);
591 * Creates a new sequence
593 * @param string $seq_name name of the new sequence
595 * @return int DB_OK on success. A DB_Error object on failure.
597 * @see DB_common::createSequence(), DB_common::getSequenceName(),
598 * DB_mssql::nextID(), DB_mssql::dropSequence()
600 function createSequence($seq_name)
602 return $this->query('CREATE TABLE '
603 . $this->getSequenceName($seq_name)
604 . ' ([id] [int] IDENTITY (1, 1) NOT NULL,'
605 . ' [vapor] [int] NULL)');
609 // {{{ dropSequence()
614 * @param string $seq_name name of the sequence to be deleted
616 * @return int DB_OK on success. A DB_Error object on failure.
618 * @see DB_common::dropSequence(), DB_common::getSequenceName(),
619 * DB_mssql::nextID(), DB_mssql::createSequence()
621 function dropSequence($seq_name)
623 return $this->query('DROP TABLE ' . $this->getSequenceName($seq_name));
627 // {{{ quoteIdentifier()
630 * Quotes a string so it can be safely used as a table or column name
632 * @param string $str identifier name to be quoted
634 * @return string quoted identifier string
636 * @see DB_common::quoteIdentifier()
637 * @since Method available since Release 1.6.0
639 function quoteIdentifier($str)
641 return '[' . str_replace(']', ']]', $str) . ']';
645 // {{{ mssqlRaiseError()
648 * Produces a DB_Error object regarding the current problem
650 * @param int $errno if the error is being manually raised pass a
651 * DB_ERROR* constant here. If this isn't passed
652 * the error information gathered from the DBMS.
654 * @return object the DB_Error object
656 * @see DB_common::raiseError(),
657 * DB_mssql::errorNative(), DB_mssql::errorCode()
659 function mssqlRaiseError($code = null)
661 $message = @mssql_get_last_message();
663 $code = $this->errorNative();
665 return $this->raiseError($this->errorCode($code, $message),
666 null, null, null, "$code - $message");
673 * Gets the DBMS' native error code produced by the last query
675 * @return int the DBMS' error code
677 function errorNative()
679 $res = @mssql_query('select @@ERROR as ErrorCode', $this->connection);
683 $row = @mssql_fetch_row($res);
691 * Determines PEAR::DB error code from mssql's native codes.
693 * If <var>$nativecode</var> isn't known yet, it will be looked up.
695 * @param mixed $nativecode mssql error code, if known
696 * @return integer an error number from a DB error constant
699 function errorCode($nativecode = null, $msg = '')
702 $nativecode = $this->errorNative();
704 if (isset($this->errorcode_map[$nativecode])) {
705 if ($nativecode == 3701
706 && preg_match('/Cannot drop the index/i', $msg))
708 return DB_ERROR_NOT_FOUND;
710 return $this->errorcode_map[$nativecode];
720 * Returns information about a table or a result set
722 * NOTE: only supports 'table' and 'flags' if <var>$result</var>
725 * @param object|string $result DB_result object from a query or a
726 * string containing the name of a table.
727 * While this also accepts a query result
728 * resource identifier, this behavior is
730 * @param int $mode a valid tableInfo mode
732 * @return array an associative array with the information requested.
733 * A DB_Error object on failure.
735 * @see DB_common::tableInfo()
737 function tableInfo($result, $mode = null)
739 if (is_string($result)) {
741 * Probably received a table name.
742 * Create a result resource identifier.
744 if (!@mssql_select_db($this->_db, $this->connection)) {
745 return $this->mssqlRaiseError(DB_ERROR_NODBSELECTED);
747 $id = @mssql_query("SELECT * FROM $result WHERE 1=0",
750 } elseif (isset($result->result)) {
752 * Probably received a result object.
753 * Extract the result resource identifier.
755 $id = $result->result;
759 * Probably received a result resource identifier.
761 * Deprecated. Here for compatibility only.
767 if (!is_resource($id)) {
768 return $this->mssqlRaiseError(DB_ERROR_NEED_MORE_DATA);
771 if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE) {
772 $case_func = 'strtolower';
774 $case_func = 'strval';
777 $count = @mssql_num_fields($id);
781 $res['num_fields'] = $count;
784 for ($i = 0; $i < $count; $i++) {
786 $flags = $this->_mssql_field_flags($result,
787 @mssql_field_name($id, $i));
788 if (DB::isError($flags)) {
796 'table' => $got_string ? $case_func($result) : '',
797 'name' => $case_func(@mssql_field_name($id, $i)),
798 'type' => @mssql_field_type($id, $i),
799 'len' => @mssql_field_length($id, $i),
802 if ($mode & DB_TABLEINFO_ORDER) {
803 $res['order'][$res[$i]['name']] = $i;
805 if ($mode & DB_TABLEINFO_ORDERTABLE) {
806 $res['ordertable'][$res[$i]['table']][$res[$i]['name']] = $i;
810 // free the result only if we were called on a table
812 @mssql_free_result($id);
818 // {{{ _mssql_field_flags()
821 * Get a column's flags
823 * Supports "not_null", "primary_key",
824 * "auto_increment" (mssql identity), "timestamp" (mssql timestamp),
825 * "unique_key" (mssql unique index, unique check or primary_key) and
826 * "multiple_key" (multikey index)
828 * mssql timestamp is NOT similar to the mysql timestamp so this is maybe
829 * not useful at all - is the behaviour of mysql_field_flags that primary
830 * keys are alway unique? is the interpretation of multiple_key correct?
832 * @param string $table the table name
833 * @param string $column the field name
835 * @return string the flags
838 * @author Joern Barthel <j_barthel@web.de>
840 function _mssql_field_flags($table, $column)
842 static $tableName = null;
843 static $flags = array();
845 if ($table != $tableName) {
850 // get unique and primary keys
851 $res = $this->getAll("EXEC SP_HELPINDEX $table", DB_FETCHMODE_ASSOC);
852 if (DB::isError($res)) {
856 foreach ($res as $val) {
857 $keys = explode(', ', $val['index_keys']);
859 if (sizeof($keys) > 1) {
860 foreach ($keys as $key) {
861 $this->_add_flag($flags[$key], 'multiple_key');
865 if (strpos($val['index_description'], 'primary key')) {
866 foreach ($keys as $key) {
867 $this->_add_flag($flags[$key], 'primary_key');
869 } elseif (strpos($val['index_description'], 'unique')) {
870 foreach ($keys as $key) {
871 $this->_add_flag($flags[$key], 'unique_key');
876 // get auto_increment, not_null and timestamp
877 $res = $this->getAll("EXEC SP_COLUMNS $table", DB_FETCHMODE_ASSOC);
878 if (DB::isError($res)) {
882 foreach ($res as $val) {
883 $val = array_change_key_case($val, CASE_LOWER);
884 if ($val['nullable'] == '0') {
885 $this->_add_flag($flags[$val['column_name']], 'not_null');
887 if (strpos($val['type_name'], 'identity')) {
888 $this->_add_flag($flags[$val['column_name']], 'auto_increment');
890 if (strpos($val['type_name'], 'timestamp')) {
891 $this->_add_flag($flags[$val['column_name']], 'timestamp');
896 if (array_key_exists($column, $flags)) {
897 return(implode(' ', $flags[$column]));
906 * Adds a string to the flags array if the flag is not yet in there
907 * - if there is no flag present the array is created
909 * @param array &$array the reference to the flag-array
910 * @param string $value the flag value
915 * @author Joern Barthel <j_barthel@web.de>
917 function _add_flag(&$array, $value)
919 if (!is_array($array)) {
920 $array = array($value);
921 } elseif (!in_array($value, $array)) {
922 array_push($array, $value);
927 // {{{ getSpecialQuery()
930 * Obtains the query string needed for listing a given type of objects
932 * @param string $type the kind of objects you want to retrieve
934 * @return string the SQL query string or null if the driver doesn't
935 * support the object type requested
938 * @see DB_common::getListOf()
940 function getSpecialQuery($type)
944 return "SELECT name FROM sysobjects WHERE type = 'U'"
947 return "SELECT name FROM sysobjects WHERE type = 'V'";