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-2005 The PHP Group
22 * @license http://www.php.net/license/3_0.txt PHP License 3.0
23 * @version CVS: $Id: mssql.php 12 2005-10-02 11:36:35Z sparc $
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.
40 * @author Sterling Hughes <sterling@php.net>
41 * @author Daniel Convissor <danielc@php.net>
42 * @copyright 1997-2005 The PHP Group
43 * @license http://www.php.net/license/3_0.txt PHP License 3.0
44 * @version Release: @package_version@
45 * @link http://pear.php.net/package/DB
47 class DB_mssql extends DB_common
52 * The DB driver type (mysql, oci8, odbc, etc.)
55 var $phptype = 'mssql';
58 * The database syntax variant to be used (db2, access, etc.), if any
61 var $dbsyntax = 'mssql';
64 * The capabilities of this DB implementation
66 * The 'new_link' element contains the PHP version that first provided
67 * new_link support for this DBMS. Contains false if it's unsupported.
69 * Meaning of the 'limit' element:
70 * + 'emulate' = emulate with fetch row by number
71 * + 'alter' = alter the query
76 var $features = array(
83 'transactions' => true,
87 * A mapping of native error codes to DB error codes
90 // XXX Add here error codes ie: 'S100E' => DB_ERROR_SYNTAX
91 var $errorcode_map = array(
92 110 => DB_ERROR_VALUE_COUNT_ON_ROW,
93 155 => DB_ERROR_NOSUCHFIELD,
94 170 => DB_ERROR_SYNTAX,
95 207 => DB_ERROR_NOSUCHFIELD,
96 208 => DB_ERROR_NOSUCHTABLE,
97 245 => DB_ERROR_INVALID_NUMBER,
98 515 => DB_ERROR_CONSTRAINT_NOT_NULL,
99 547 => DB_ERROR_CONSTRAINT,
100 1913 => DB_ERROR_ALREADY_EXISTS,
101 2627 => DB_ERROR_CONSTRAINT,
102 2714 => DB_ERROR_ALREADY_EXISTS,
103 3701 => DB_ERROR_NOSUCHTABLE,
104 8134 => DB_ERROR_DIVZERO,
108 * The raw database connection created by PHP
114 * The DSN information for connecting to a database
121 * Should data manipulation queries be committed automatically?
125 var $autocommit = true;
128 * The quantity of transactions begun
130 * {@internal While this is private, it can't actually be designated
131 * private in PHP 5 because it is directly accessed in the test suite.}}
136 var $transaction_opcount = 0;
139 * The database specified in the DSN
141 * It's a fix to allow calls to different databases in the same script.
153 * This constructor calls <kbd>$this->DB_common()</kbd>
166 * Connect to the database server, log in and open the database
168 * Don't call this method directly. Use DB::connect() instead.
170 * @param array $dsn the data source name
171 * @param bool $persistent should the connection be persistent?
173 * @return int DB_OK on success. A DB_Error object on failure.
175 function connect($dsn, $persistent = false)
177 if (!PEAR::loadExtension('mssql') && !PEAR::loadExtension('sybase')
178 && !PEAR::loadExtension('sybase_ct'))
180 return $this->raiseError(DB_ERROR_EXTENSION_NOT_FOUND);
184 if ($dsn['dbsyntax']) {
185 $this->dbsyntax = $dsn['dbsyntax'];
189 $dsn['hostspec'] ? $dsn['hostspec'] : 'localhost',
190 $dsn['username'] ? $dsn['username'] : null,
191 $dsn['password'] ? $dsn['password'] : null,
194 $params[0] .= ((substr(PHP_OS, 0, 3) == 'WIN') ? ',' : ':')
198 $connect_function = $persistent ? 'mssql_pconnect' : 'mssql_connect';
200 $this->connection = @call_user_func_array($connect_function, $params);
202 if (!$this->connection) {
203 return $this->raiseError(DB_ERROR_CONNECT_FAILED,
205 @mssql_get_last_message());
207 if ($dsn['database']) {
208 if (!@mssql_select_db($dsn['database'], $this->connection)) {
209 return $this->raiseError(DB_ERROR_NODBSELECTED,
211 @mssql_get_last_message());
213 $this->_db = $dsn['database'];
222 * Disconnects from the database server
224 * @return bool TRUE on success, FALSE on failure
226 function disconnect()
228 $ret = @mssql_close($this->connection);
229 $this->connection = null;
237 * Sends a query to the database server
239 * @param string the SQL query string
241 * @return mixed + a PHP result resrouce for successful SELECT queries
242 * + the DB_OK constant for other successful queries
243 * + a DB_Error object on failure
245 function simpleQuery($query)
247 $ismanip = DB::isManip($query);
248 $this->last_query = $query;
249 if (!@mssql_select_db($this->_db, $this->connection)) {
250 return $this->mssqlRaiseError(DB_ERROR_NODBSELECTED);
252 $query = $this->modifyQuery($query);
253 if (!$this->autocommit && $ismanip) {
254 if ($this->transaction_opcount == 0) {
255 $result = @mssql_query('BEGIN TRAN', $this->connection);
257 return $this->mssqlRaiseError();
260 $this->transaction_opcount++;
262 $result = @mssql_query($query, $this->connection);
264 return $this->mssqlRaiseError();
266 // Determine which queries that should return data, and which
267 // should return an error code only.
268 return $ismanip ? DB_OK : $result;
275 * Move the internal mssql result pointer to the next available result
277 * @param a valid fbsql result resource
281 * @return true if a result is available otherwise return false
283 function nextResult($result)
285 return @mssql_next_result($result);
292 * Places a row from the result set into the given array
294 * Formating of the array and the data therein are configurable.
295 * See DB_result::fetchInto() for more information.
297 * This method is not meant to be called directly. Use
298 * DB_result::fetchInto() instead. It can't be declared "protected"
299 * because DB_result is a separate object.
301 * @param resource $result the query result resource
302 * @param array $arr the referenced array to put the data in
303 * @param int $fetchmode how the resulting array should be indexed
304 * @param int $rownum the row number to fetch (0 = first row)
306 * @return mixed DB_OK on success, NULL when the end of a result set is
307 * reached or on failure
309 * @see DB_result::fetchInto()
311 function fetchInto($result, &$arr, $fetchmode, $rownum = null)
313 if ($rownum !== null) {
314 if (!@mssql_data_seek($result, $rownum)) {
318 if ($fetchmode & DB_FETCHMODE_ASSOC) {
319 $arr = @mssql_fetch_array($result, MSSQL_ASSOC);
320 if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE && $arr) {
321 $arr = array_change_key_case($arr, CASE_LOWER);
324 $arr = @mssql_fetch_row($result);
329 if ($this->options['portability'] & DB_PORTABILITY_RTRIM) {
330 $this->_rtrimArrayValues($arr);
332 if ($this->options['portability'] & DB_PORTABILITY_NULL_TO_EMPTY) {
333 $this->_convertNullArrayValuesToEmpty($arr);
342 * Deletes the result set and frees the memory occupied by the result set
344 * This method is not meant to be called directly. Use
345 * DB_result::free() instead. It can't be declared "protected"
346 * because DB_result is a separate object.
348 * @param resource $result PHP's query result resource
350 * @return bool TRUE on success, FALSE if $result is invalid
352 * @see DB_result::free()
354 function freeResult($result)
356 return @mssql_free_result($result);
363 * Gets the number of columns in a result set
365 * This method is not meant to be called directly. Use
366 * DB_result::numCols() instead. It can't be declared "protected"
367 * because DB_result is a separate object.
369 * @param resource $result PHP's query result resource
371 * @return int the number of columns. A DB_Error object on failure.
373 * @see DB_result::numCols()
375 function numCols($result)
377 $cols = @mssql_num_fields($result);
379 return $this->mssqlRaiseError();
388 * Gets the number of rows in a result set
390 * This method is not meant to be called directly. Use
391 * DB_result::numRows() instead. It can't be declared "protected"
392 * because DB_result is a separate object.
394 * @param resource $result PHP's query result resource
396 * @return int the number of rows. A DB_Error object on failure.
398 * @see DB_result::numRows()
400 function numRows($result)
402 $rows = @mssql_num_rows($result);
403 if ($rows === false) {
404 return $this->mssqlRaiseError();
413 * Enables or disables automatic commits
415 * @param bool $onoff true turns it on, false turns it off
417 * @return int DB_OK on success. A DB_Error object if the driver
418 * doesn't support auto-committing transactions.
420 function autoCommit($onoff = false)
422 // XXX if $this->transaction_opcount > 0, we should probably
423 // issue a warning here.
424 $this->autocommit = $onoff ? true : false;
432 * Commits the current transaction
434 * @return int DB_OK on success. A DB_Error object on failure.
438 if ($this->transaction_opcount > 0) {
439 if (!@mssql_select_db($this->_db, $this->connection)) {
440 return $this->mssqlRaiseError(DB_ERROR_NODBSELECTED);
442 $result = @mssql_query('COMMIT TRAN', $this->connection);
443 $this->transaction_opcount = 0;
445 return $this->mssqlRaiseError();
455 * Reverts the current transaction
457 * @return int DB_OK on success. A DB_Error object on failure.
461 if ($this->transaction_opcount > 0) {
462 if (!@mssql_select_db($this->_db, $this->connection)) {
463 return $this->mssqlRaiseError(DB_ERROR_NODBSELECTED);
465 $result = @mssql_query('ROLLBACK TRAN', $this->connection);
466 $this->transaction_opcount = 0;
468 return $this->mssqlRaiseError();
475 // {{{ affectedRows()
478 * Determines the number of rows affected by a data maniuplation query
480 * 0 is returned for queries that don't manipulate data.
482 * @return int the number of rows. A DB_Error object on failure.
484 function affectedRows()
486 if (DB::isManip($this->last_query)) {
487 $res = @mssql_query('select @@rowcount', $this->connection);
489 return $this->mssqlRaiseError();
491 $ar = @mssql_fetch_row($res);
495 @mssql_free_result($res);
508 * Returns the next free id in a sequence
510 * @param string $seq_name name of the sequence
511 * @param boolean $ondemand when true, the seqence is automatically
512 * created if it does not exist
514 * @return int the next id number in the sequence.
515 * A DB_Error object on failure.
517 * @see DB_common::nextID(), DB_common::getSequenceName(),
518 * DB_mssql::createSequence(), DB_mssql::dropSequence()
520 function nextId($seq_name, $ondemand = true)
522 $seqname = $this->getSequenceName($seq_name);
523 if (!@mssql_select_db($this->_db, $this->connection)) {
524 return $this->mssqlRaiseError(DB_ERROR_NODBSELECTED);
528 $this->pushErrorHandling(PEAR_ERROR_RETURN);
529 $result = $this->query("INSERT INTO $seqname (vapor) VALUES (0)");
530 $this->popErrorHandling();
531 if ($ondemand && DB::isError($result) &&
532 ($result->getCode() == DB_ERROR || $result->getCode() == DB_ERROR_NOSUCHTABLE))
535 $result = $this->createSequence($seq_name);
536 if (DB::isError($result)) {
537 return $this->raiseError($result);
539 } elseif (!DB::isError($result)) {
540 $result =& $this->query("SELECT @@IDENTITY FROM $seqname");
546 if (DB::isError($result)) {
547 return $this->raiseError($result);
549 $result = $result->fetchRow(DB_FETCHMODE_ORDERED);
554 * Creates a new sequence
556 * @param string $seq_name name of the new sequence
558 * @return int DB_OK on success. A DB_Error object on failure.
560 * @see DB_common::createSequence(), DB_common::getSequenceName(),
561 * DB_mssql::nextID(), DB_mssql::dropSequence()
563 function createSequence($seq_name)
565 return $this->query('CREATE TABLE '
566 . $this->getSequenceName($seq_name)
567 . ' ([id] [int] IDENTITY (1, 1) NOT NULL,'
568 . ' [vapor] [int] NULL)');
572 // {{{ dropSequence()
577 * @param string $seq_name name of the sequence to be deleted
579 * @return int DB_OK on success. A DB_Error object on failure.
581 * @see DB_common::dropSequence(), DB_common::getSequenceName(),
582 * DB_mssql::nextID(), DB_mssql::createSequence()
584 function dropSequence($seq_name)
586 return $this->query('DROP TABLE ' . $this->getSequenceName($seq_name));
590 // {{{ quoteIdentifier()
593 * Quotes a string so it can be safely used as a table or column name
595 * @param string $str identifier name to be quoted
597 * @return string quoted identifier string
599 * @see DB_common::quoteIdentifier()
600 * @since Method available since Release 1.6.0
602 function quoteIdentifier($str)
604 return '[' . str_replace(']', ']]', $str) . ']';
608 // {{{ mssqlRaiseError()
611 * Produces a DB_Error object regarding the current problem
613 * @param int $errno if the error is being manually raised pass a
614 * DB_ERROR* constant here. If this isn't passed
615 * the error information gathered from the DBMS.
617 * @return object the DB_Error object
619 * @see DB_common::raiseError(),
620 * DB_mssql::errorNative(), DB_mssql::errorCode()
622 function mssqlRaiseError($code = null)
624 $message = @mssql_get_last_message();
626 $code = $this->errorNative();
628 return $this->raiseError($this->errorCode($code, $message),
629 null, null, null, "$code - $message");
636 * Gets the DBMS' native error code produced by the last query
638 * @return int the DBMS' error code
640 function errorNative()
642 $res = @mssql_query('select @@ERROR as ErrorCode', $this->connection);
646 $row = @mssql_fetch_row($res);
654 * Determines PEAR::DB error code from mssql's native codes.
656 * If <var>$nativecode</var> isn't known yet, it will be looked up.
658 * @param mixed $nativecode mssql error code, if known
659 * @return integer an error number from a DB error constant
662 function errorCode($nativecode = null, $msg = '')
665 $nativecode = $this->errorNative();
667 if (isset($this->errorcode_map[$nativecode])) {
668 if ($nativecode == 3701
669 && preg_match('/Cannot drop the index/i', $msg))
671 return DB_ERROR_NOT_FOUND;
673 return $this->errorcode_map[$nativecode];
683 * Returns information about a table or a result set
685 * NOTE: only supports 'table' and 'flags' if <var>$result</var>
688 * @param object|string $result DB_result object from a query or a
689 * string containing the name of a table.
690 * While this also accepts a query result
691 * resource identifier, this behavior is
693 * @param int $mode a valid tableInfo mode
695 * @return array an associative array with the information requested.
696 * A DB_Error object on failure.
698 * @see DB_common::tableInfo()
700 function tableInfo($result, $mode = null)
702 if (is_string($result)) {
704 * Probably received a table name.
705 * Create a result resource identifier.
707 if (!@mssql_select_db($this->_db, $this->connection)) {
708 return $this->mssqlRaiseError(DB_ERROR_NODBSELECTED);
710 $id = @mssql_query("SELECT * FROM $result WHERE 1=0",
713 } elseif (isset($result->result)) {
715 * Probably received a result object.
716 * Extract the result resource identifier.
718 $id = $result->result;
722 * Probably received a result resource identifier.
724 * Deprecated. Here for compatibility only.
730 if (!is_resource($id)) {
731 return $this->mssqlRaiseError(DB_ERROR_NEED_MORE_DATA);
734 if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE) {
735 $case_func = 'strtolower';
737 $case_func = 'strval';
740 $count = @mssql_num_fields($id);
744 $res['num_fields'] = $count;
747 for ($i = 0; $i < $count; $i++) {
749 'table' => $got_string ? $case_func($result) : '',
750 'name' => $case_func(@mssql_field_name($id, $i)),
751 'type' => @mssql_field_type($id, $i),
752 'len' => @mssql_field_length($id, $i),
753 // We only support flags for table
754 'flags' => $got_string
755 ? $this->_mssql_field_flags($result,
756 @mssql_field_name($id, $i))
759 if ($mode & DB_TABLEINFO_ORDER) {
760 $res['order'][$res[$i]['name']] = $i;
762 if ($mode & DB_TABLEINFO_ORDERTABLE) {
763 $res['ordertable'][$res[$i]['table']][$res[$i]['name']] = $i;
767 // free the result only if we were called on a table
769 @mssql_free_result($id);
775 // {{{ _mssql_field_flags()
778 * Get a column's flags
780 * Supports "not_null", "primary_key",
781 * "auto_increment" (mssql identity), "timestamp" (mssql timestamp),
782 * "unique_key" (mssql unique index, unique check or primary_key) and
783 * "multiple_key" (multikey index)
785 * mssql timestamp is NOT similar to the mysql timestamp so this is maybe
786 * not useful at all - is the behaviour of mysql_field_flags that primary
787 * keys are alway unique? is the interpretation of multiple_key correct?
789 * @param string $table the table name
790 * @param string $column the field name
792 * @return string the flags
795 * @author Joern Barthel <j_barthel@web.de>
797 function _mssql_field_flags($table, $column)
799 static $tableName = null;
800 static $flags = array();
802 if ($table != $tableName) {
807 // get unique and primary keys
808 $res = $this->getAll("EXEC SP_HELPINDEX[$table]", DB_FETCHMODE_ASSOC);
810 foreach ($res as $val) {
811 $keys = explode(', ', $val['index_keys']);
813 if (sizeof($keys) > 1) {
814 foreach ($keys as $key) {
815 $this->_add_flag($flags[$key], 'multiple_key');
819 if (strpos($val['index_description'], 'primary key')) {
820 foreach ($keys as $key) {
821 $this->_add_flag($flags[$key], 'primary_key');
823 } elseif (strpos($val['index_description'], 'unique')) {
824 foreach ($keys as $key) {
825 $this->_add_flag($flags[$key], 'unique_key');
830 // get auto_increment, not_null and timestamp
831 $res = $this->getAll("EXEC SP_COLUMNS[$table]", DB_FETCHMODE_ASSOC);
833 foreach ($res as $val) {
834 $val = array_change_key_case($val, CASE_LOWER);
835 if ($val['nullable'] == '0') {
836 $this->_add_flag($flags[$val['column_name']], 'not_null');
838 if (strpos($val['type_name'], 'identity')) {
839 $this->_add_flag($flags[$val['column_name']], 'auto_increment');
841 if (strpos($val['type_name'], 'timestamp')) {
842 $this->_add_flag($flags[$val['column_name']], 'timestamp');
847 if (array_key_exists($column, $flags)) {
848 return(implode(' ', $flags[$column]));
857 * Adds a string to the flags array if the flag is not yet in there
858 * - if there is no flag present the array is created
860 * @param array &$array the reference to the flag-array
861 * @param string $value the flag value
866 * @author Joern Barthel <j_barthel@web.de>
868 function _add_flag(&$array, $value)
870 if (!is_array($array)) {
871 $array = array($value);
872 } elseif (!in_array($value, $array)) {
873 array_push($array, $value);
878 // {{{ getSpecialQuery()
881 * Obtains the query string needed for listing a given type of objects
883 * @param string $type the kind of objects you want to retrieve
885 * @return string the SQL query string or null if the driver doesn't
886 * support the object type requested
889 * @see DB_common::getListOf()
891 function getSpecialQuery($type)
895 return "SELECT name FROM sysobjects WHERE type = 'U'"
898 return "SELECT name FROM sysobjects WHERE type = 'V'";