2 /* vim: set expandtab tabstop=4 shiftwidth=4 foldmethod=marker: */
3 // +----------------------------------------------------------------------+
5 // +----------------------------------------------------------------------+
6 // | Copyright (c) 1997-2004 The PHP Group |
7 // +----------------------------------------------------------------------+
8 // | This source file is subject to version 2.02 of the PHP license, |
9 // | that is bundled with this package in the file LICENSE, and is |
10 // | available at through the world-wide-web at |
11 // | http://www.php.net/license/2_02.txt. |
12 // | If you did not receive a copy of the PHP license and are unable to |
13 // | obtain it through the world-wide-web, please send a note to |
14 // | license@php.net so we can mail you a copy immediately. |
15 // +----------------------------------------------------------------------+
16 // | Authors: Sterling Hughes <sterling@php.net> |
17 // | Antônio Carlos Venâncio Júnior <floripa@php.net> |
18 // | Maintainer: Daniel Convissor <danielc@php.net> |
19 // +----------------------------------------------------------------------+
22 // - This driver may fail with multiple connections under the same
23 // user/pass/host and different databases
25 require_once 'DB/common.php';
28 * Database independent query interface definition for PHP's Sybase
34 * @author Sterling Hughes <sterling@php.net>
35 * @author Antônio Carlos Venâncio Júnior <floripa@php.net>
37 class DB_sybase extends DB_common
42 var $phptype, $dbsyntax;
43 var $prepare_tokens = array();
44 var $prepare_types = array();
45 var $transaction_opcount = 0;
46 var $autocommit = true;
52 * DB_sybase constructor.
59 $this->phptype = 'sybase';
60 $this->dbsyntax = 'sybase';
61 $this->features = array(
64 'transactions' => false,
67 $this->errorcode_map = array(
75 * Connect to a database and log in as the specified user.
77 * @param $dsn the data source name (see DB::parseDSN for syntax)
78 * @param $persistent (optional) whether the connection should
81 * @return int DB_OK on success, a DB error on failure
83 function connect($dsninfo, $persistent = false)
85 if (!DB::assertExtension('sybase') &&
86 !DB::assertExtension('sybase_ct'))
88 return $this->raiseError(DB_ERROR_EXTENSION_NOT_FOUND);
91 $this->dsn = $dsninfo;
93 $interface = $dsninfo['hostspec'] ? $dsninfo['hostspec'] : 'localhost';
94 $connect_function = $persistent ? 'sybase_pconnect' : 'sybase_connect';
96 if ($interface && $dsninfo['username'] && $dsninfo['password']) {
97 $conn = @$connect_function($interface, $dsninfo['username'],
98 $dsninfo['password']);
99 } elseif ($interface && $dsninfo['username']) {
101 * Using false for pw as a workaround to avoid segfault.
104 $conn = @$connect_function($interface, $dsninfo['username'],
111 return $this->raiseError(DB_ERROR_CONNECT_FAILED);
114 if ($dsninfo['database']) {
115 if (!@sybase_select_db($dsninfo['database'], $conn)) {
116 return $this->raiseError(DB_ERROR_NODBSELECTED, null,
117 null, null, @sybase_get_last_message());
119 $this->_db = $dsninfo['database'];
122 $this->connection = $conn;
130 * Log out and disconnect from the database.
134 * @return bool true on success, false if not connected.
136 function disconnect()
138 $ret = @sybase_close($this->connection);
139 $this->connection = null;
147 * Get the last server error messge (if any)
149 * @return string sybase last error message
151 function errorNative()
153 return @sybase_get_last_message();
160 * Determine PEAR::DB error code from the database's text error message.
162 * @param string $errormsg error message returned from the database
163 * @return integer an error number from a DB error constant
165 function errorCode($errormsg)
167 static $error_regexps;
168 if (!isset($error_regexps)) {
169 $error_regexps = array(
170 '/Incorrect syntax near/'
172 '/^Unclosed quote before the character string [\"\'].*[\"\']\./'
174 '/Implicit conversion from datatype [\"\'].+[\"\'] to [\"\'].+[\"\'] is not allowed\./'
175 => DB_ERROR_INVALID_NUMBER,
176 '/Cannot drop the table [\"\'].+[\"\'], because it doesn\'t exist in the system catalogs\./'
177 => DB_ERROR_NOSUCHTABLE,
178 '/Only the owner of object [\"\'].+[\"\'] or a user with System Administrator \(SA\) role can run this command\./'
179 => DB_ERROR_ACCESS_VIOLATION,
180 '/^.+ permission denied on object .+, database .+, owner .+/'
181 => DB_ERROR_ACCESS_VIOLATION,
182 '/^.* permission denied, database .+, owner .+/'
183 => DB_ERROR_ACCESS_VIOLATION,
184 '/[^.*] not found\./'
185 => DB_ERROR_NOSUCHTABLE,
186 '/There is already an object named/'
187 => DB_ERROR_ALREADY_EXISTS,
188 '/Invalid column name/'
189 => DB_ERROR_NOSUCHFIELD,
190 '/does not allow null values/'
191 => DB_ERROR_CONSTRAINT_NOT_NULL,
192 '/Command has been aborted/'
193 => DB_ERROR_CONSTRAINT,
197 foreach ($error_regexps as $regexp => $code) {
198 if (preg_match($regexp, $errormsg)) {
206 // {{{ sybaseRaiseError()
209 * Gather information about an error, then use that info to create a
210 * DB error object and finally return that object.
212 * @param integer $errno PEAR error number (usually a DB constant) if
213 * manually raising an error
214 * @return object DB error object
217 * @see DB_common::raiseError()
219 function sybaseRaiseError($errno = null)
221 $native = $this->errorNative();
222 if ($errno === null) {
223 $errno = $this->errorCode($native);
225 return $this->raiseError($errno, null, null, null, $native);
232 * Send a query to Sybase and return the results as a Sybase resource
235 * @param the SQL query
239 * @return mixed returns a valid Sybase result for successful SELECT
240 * queries, DB_OK for other successful queries. A DB error is
241 * returned on failure.
243 function simpleQuery($query)
245 $ismanip = DB::isManip($query);
246 $this->last_query = $query;
247 if (!@sybase_select_db($this->_db, $this->connection)) {
248 return $this->sybaseRaiseError(DB_ERROR_NODBSELECTED);
250 $query = $this->modifyQuery($query);
251 if (!$this->autocommit && $ismanip) {
252 if ($this->transaction_opcount == 0) {
253 $result = @sybase_query('BEGIN TRANSACTION', $this->connection);
255 return $this->sybaseRaiseError();
258 $this->transaction_opcount++;
260 $result = @sybase_query($query, $this->connection);
262 return $this->sybaseRaiseError();
264 if (is_resource($result)) {
265 $numrows = $this->numRows($result);
266 if (is_object($numrows)) {
269 $this->num_rows[(int)$result] = $numrows;
272 // Determine which queries that should return data, and which
273 // should return an error code only.
274 return $ismanip ? DB_OK : $result;
281 * Move the internal sybase result pointer to the next available result
283 * @param a valid sybase result resource
287 * @return true if a result is available otherwise return false
289 function nextResult($result)
298 * Fetch a row and insert the data into an existing array.
300 * Formating of the array and the data therein are configurable.
301 * See DB_result::fetchInto() for more information.
303 * @param resource $result query result identifier
304 * @param array $arr (reference) array where data from the row
306 * @param int $fetchmode how the resulting array should be indexed
307 * @param int $rownum the row number to fetch
309 * @return mixed DB_OK on success, null when end of result set is
310 * reached or on failure
312 * @see DB_result::fetchInto()
315 function fetchInto($result, &$arr, $fetchmode, $rownum=null)
317 if ($rownum !== null) {
318 if (!@sybase_data_seek($result, $rownum)) {
322 if ($fetchmode & DB_FETCHMODE_ASSOC) {
323 if (function_exists('sybase_fetch_assoc')) {
324 $arr = @sybase_fetch_assoc($result);
326 if ($arr = @sybase_fetch_array($result)) {
327 foreach ($arr as $key => $value) {
334 if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE && $arr) {
335 $arr = array_change_key_case($arr, CASE_LOWER);
338 $arr = @sybase_fetch_row($result);
341 // reported not work as seems that sybase_get_last_message()
342 // always return a message here
343 //if ($errmsg = @sybase_get_last_message()) {
344 // return $this->sybaseRaiseError($errmsg);
349 if ($this->options['portability'] & DB_PORTABILITY_RTRIM) {
350 $this->_rtrimArrayValues($arr);
352 if ($this->options['portability'] & DB_PORTABILITY_NULL_TO_EMPTY) {
353 $this->_convertNullArrayValuesToEmpty($arr);
362 * Free the internal resources associated with $result.
364 * @param $result Sybase result identifier
368 * @return bool true on success, false if $result is invalid
370 function freeResult($result)
372 unset($this->num_rows[(int)$result]);
373 return @sybase_free_result($result);
380 * Get the number of columns in a result set.
382 * @param $result Sybase result identifier
386 * @return int the number of columns per row in $result
388 function numCols($result)
390 $cols = @sybase_num_fields($result);
392 return $this->sybaseRaiseError();
401 * Get the number of rows in a result set.
403 * @param $result Sybase result identifier
407 * @return int the number of rows in $result
409 function numRows($result)
411 $rows = @sybase_num_rows($result);
412 if ($rows === false) {
413 return $this->sybaseRaiseError();
419 // {{{ affectedRows()
422 * Gets the number of rows affected by the data manipulation
423 * query. For other queries, this function returns 0.
425 * @return number of rows affected by the last query
427 function affectedRows()
429 if (DB::isManip($this->last_query)) {
430 $result = @sybase_affected_rows($this->connection);
441 * Returns the next free id in a sequence
443 * @param string $seq_name name of the sequence
444 * @param boolean $ondemand when true, the seqence is automatically
445 * created if it does not exist
447 * @return int the next id number in the sequence. DB_Error if problem.
450 * @see DB_common::nextID()
453 function nextId($seq_name, $ondemand = true)
455 $seqname = $this->getSequenceName($seq_name);
456 if (!@sybase_select_db($this->_db, $this->connection)) {
457 return $this->sybaseRaiseError(DB_ERROR_NODBSELECTED);
461 $this->pushErrorHandling(PEAR_ERROR_RETURN);
462 $result = $this->query("INSERT INTO $seqname (vapor) VALUES (0)");
463 $this->popErrorHandling();
464 if ($ondemand && DB::isError($result) &&
465 ($result->getCode() == DB_ERROR || $result->getCode() == DB_ERROR_NOSUCHTABLE))
468 $result = $this->createSequence($seq_name);
469 if (DB::isError($result)) {
470 return $this->raiseError($result);
472 } elseif (!DB::isError($result)) {
473 $result =& $this->query("SELECT @@IDENTITY FROM $seqname");
479 if (DB::isError($result)) {
480 return $this->raiseError($result);
482 $result = $result->fetchRow(DB_FETCHMODE_ORDERED);
487 * Creates a new sequence
489 * @param string $seq_name name of the new sequence
491 * @return int DB_OK on success. A DB_Error object is returned if
495 * @see DB_common::createSequence()
498 function createSequence($seq_name)
500 $seqname = $this->getSequenceName($seq_name);
501 return $this->query("CREATE TABLE $seqname ".
502 '(id numeric(10,0) IDENTITY NOT NULL ,' .
507 // {{{ dropSequence()
512 * @param string $seq_name name of the sequence to be deleted
514 * @return int DB_OK on success. DB_Error if problems.
517 * @see DB_common::dropSequence()
520 function dropSequence($seq_name)
522 $seqname = $this->getSequenceName($seq_name);
523 return $this->query("DROP TABLE $seqname");
527 // {{{ getSpecialQuery()
530 * Returns the query needed to get some backend info
531 * @param string $type What kind of info you want to retrieve
532 * @return string The SQL query string
534 function getSpecialQuery($type)
538 return "select name from sysobjects where type = 'U' order by name";
540 return "select name from sysobjects where type = 'V'";
550 * Enable/disable automatic commits
552 function autoCommit($onoff = false)
554 // XXX if $this->transaction_opcount > 0, we should probably
555 // issue a warning here.
556 $this->autocommit = $onoff ? true : false;
564 * Commit the current transaction.
568 if ($this->transaction_opcount > 0) {
569 if (!@sybase_select_db($this->_db, $this->connection)) {
570 return $this->sybaseRaiseError(DB_ERROR_NODBSELECTED);
572 $result = @sybase_query('COMMIT', $this->connection);
573 $this->transaction_opcount = 0;
575 return $this->sybaseRaiseError();
585 * Roll back (undo) the current transaction.
589 if ($this->transaction_opcount > 0) {
590 if (!@sybase_select_db($this->_db, $this->connection)) {
591 return $this->sybaseRaiseError(DB_ERROR_NODBSELECTED);
593 $result = @sybase_query('ROLLBACK', $this->connection);
594 $this->transaction_opcount = 0;
596 return $this->sybaseRaiseError();
606 * Returns information about a table or a result set.
608 * NOTE: only supports 'table' and 'flags' if <var>$result</var>
611 * @param object|string $result DB_result object from a query or a
612 * string containing the name of a table
613 * @param int $mode a valid tableInfo mode
614 * @return array an associative array with the information requested
615 * or an error object if something is wrong
619 * @see DB_common::tableInfo()
621 function tableInfo($result, $mode = null)
623 if (isset($result->result)) {
625 * Probably received a result object.
626 * Extract the result resource identifier.
628 $id = $result->result;
630 } elseif (is_string($result)) {
632 * Probably received a table name.
633 * Create a result resource identifier.
635 if (!@sybase_select_db($this->_db, $this->connection)) {
636 return $this->sybaseRaiseError(DB_ERROR_NODBSELECTED);
638 $id = @sybase_query("SELECT * FROM $result WHERE 1=0",
643 * Probably received a result resource identifier.
645 * Depricated. Here for compatibility only.
651 if (!is_resource($id)) {
652 return $this->sybaseRaiseError(DB_ERROR_NEED_MORE_DATA);
655 if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE) {
656 $case_func = 'strtolower';
658 $case_func = 'strval';
661 $count = @sybase_num_fields($id);
663 // made this IF due to performance (one if is faster than $count if's)
666 for ($i=0; $i<$count; $i++) {
667 $f = @sybase_fetch_field($id, $i);
669 // column_source is often blank
671 $res[$i]['table'] = $case_func($result);
673 $res[$i]['table'] = $case_func($f->column_source);
675 $res[$i]['name'] = $case_func($f->name);
676 $res[$i]['type'] = $f->type;
677 $res[$i]['len'] = $f->max_length;
678 if ($res[$i]['table']) {
679 $res[$i]['flags'] = $this->_sybase_field_flags(
680 $res[$i]['table'], $res[$i]['name']);
682 $res[$i]['flags'] = '';
689 $res['num_fields'] = $count;
691 for ($i=0; $i<$count; $i++) {
692 $f = @sybase_fetch_field($id, $i);
694 // column_source is often blank
696 $res[$i]['table'] = $case_func($result);
698 $res[$i]['table'] = $case_func($f->column_source);
700 $res[$i]['name'] = $case_func($f->name);
701 $res[$i]['type'] = $f->type;
702 $res[$i]['len'] = $f->max_length;
703 if ($res[$i]['table']) {
704 $res[$i]['flags'] = $this->_sybase_field_flags(
705 $res[$i]['table'], $res[$i]['name']);
707 $res[$i]['flags'] = '';
710 if ($mode & DB_TABLEINFO_ORDER) {
711 $res['order'][$res[$i]['name']] = $i;
713 if ($mode & DB_TABLEINFO_ORDERTABLE) {
714 $res['ordertable'][$res[$i]['table']][$res[$i]['name']] = $i;
719 // free the result only if we were called on a table
721 @sybase_free_result($id);
727 // {{{ _sybase_field_flags()
730 * Get the flags for a field.
732 * Currently supports:
733 * + <samp>unique_key</samp> (unique index, unique check or primary_key)
734 * + <samp>multiple_key</samp> (multi-key index)
736 * @param string $table table name
737 * @param string $column field name
738 * @return string space delimited string of flags. Empty string if none.
741 function _sybase_field_flags($table, $column)
743 static $tableName = null;
744 static $flags = array();
746 if ($table != $tableName) {
750 // get unique/primary keys
751 $res = $this->getAll("sp_helpindex $table", DB_FETCHMODE_ASSOC);
753 if (!isset($res[0]['index_description'])) {
757 foreach ($res as $val) {
758 $keys = explode(', ', trim($val['index_keys']));
760 if (sizeof($keys) > 1) {
761 foreach ($keys as $key) {
762 $this->_add_flag($flags[$key], 'multiple_key');
766 if (strpos($val['index_description'], 'unique')) {
767 foreach ($keys as $key) {
768 $this->_add_flag($flags[$key], 'unique_key');
775 if (array_key_exists($column, $flags)) {
776 return(implode(' ', $flags[$column]));
786 * Adds a string to the flags array if the flag is not yet in there
787 * - if there is no flag present the array is created.
789 * @param array $array reference of flags array to add a value to
790 * @param mixed $value value to add to the flag array
793 function _add_flag(&$array, $value)
795 if (!is_array($array)) {
796 $array = array($value);
797 } elseif (!in_array($value, $array)) {
798 array_push($array, $value);
803 // {{{ quoteIdentifier()
806 * Quote a string so it can be safely used as a table / column name
808 * Quoting style depends on which database driver is being used.
810 * @param string $str identifier name to be quoted
812 * @return string quoted identifier string
817 function quoteIdentifier($str)
819 return '[' . str_replace(']', ']]', $str) . ']';