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 // +----------------------------------------------------------------------+
24 // - This driver may fail with multiple connections under the same
25 // user/pass/host and different databases
27 require_once 'DB/common.php';
30 * Database independent query interface definition for PHP's Sybase
36 * @author Sterling Hughes <sterling@php.net>
37 * @author Antônio Carlos Venâncio Júnior <floripa@php.net>
39 class DB_sybase extends DB_common
44 var $phptype, $dbsyntax;
45 var $prepare_tokens = array();
46 var $prepare_types = array();
47 var $transaction_opcount = 0;
48 var $autocommit = true;
54 * DB_sybase constructor.
61 $this->phptype = 'sybase';
62 $this->dbsyntax = 'sybase';
63 $this->features = array(
66 'transactions' => false,
69 $this->errorcode_map = array(
77 * Connect to a database and log in as the specified user.
79 * @param $dsn the data source name (see DB::parseDSN for syntax)
80 * @param $persistent (optional) whether the connection should
83 * @return int DB_OK on success, a DB error on failure
85 function connect($dsninfo, $persistent = false)
87 if (!DB::assertExtension('sybase') &&
88 !DB::assertExtension('sybase_ct'))
90 return $this->raiseError(DB_ERROR_EXTENSION_NOT_FOUND);
93 $this->dsn = $dsninfo;
95 $interface = $dsninfo['hostspec'] ? $dsninfo['hostspec'] : 'localhost';
96 $connect_function = $persistent ? 'sybase_pconnect' : 'sybase_connect';
98 if ($interface && $dsninfo['username'] && $dsninfo['password']) {
99 $conn = @$connect_function($interface, $dsninfo['username'],
100 $dsninfo['password']);
101 } elseif ($interface && $dsninfo['username']) {
103 * Using false for pw as a workaround to avoid segfault.
106 $conn = @$connect_function($interface, $dsninfo['username'],
113 return $this->raiseError(DB_ERROR_CONNECT_FAILED);
116 if ($dsninfo['database']) {
117 if (!@sybase_select_db($dsninfo['database'], $conn)) {
118 return $this->raiseError(DB_ERROR_NODBSELECTED, null,
119 null, null, @sybase_get_last_message());
121 $this->_db = $dsninfo['database'];
124 $this->connection = $conn;
132 * Log out and disconnect from the database.
136 * @return bool true on success, false if not connected.
138 function disconnect()
140 $ret = @sybase_close($this->connection);
141 $this->connection = null;
149 * Get the last server error messge (if any)
151 * @return string sybase last error message
153 function errorNative()
155 return @sybase_get_last_message();
162 * Determine PEAR::DB error code from the database's text error message.
164 * @param string $errormsg error message returned from the database
165 * @return integer an error number from a DB error constant
167 function errorCode($errormsg)
169 static $error_regexps;
170 if (!isset($error_regexps)) {
171 $error_regexps = array(
172 '/Incorrect syntax near/'
174 '/^Unclosed quote before the character string [\"\'].*[\"\']\./'
176 '/Implicit conversion from datatype [\"\'].+[\"\'] to [\"\'].+[\"\'] is not allowed\./'
177 => DB_ERROR_INVALID_NUMBER,
178 '/Cannot drop the table [\"\'].+[\"\'], because it doesn\'t exist in the system catalogs\./'
179 => DB_ERROR_NOSUCHTABLE,
180 '/Only the owner of object [\"\'].+[\"\'] or a user with System Administrator \(SA\) role can run this command\./'
181 => DB_ERROR_ACCESS_VIOLATION,
182 '/^.+ permission denied on object .+, database .+, owner .+/'
183 => DB_ERROR_ACCESS_VIOLATION,
184 '/^.* permission denied, database .+, owner .+/'
185 => DB_ERROR_ACCESS_VIOLATION,
186 '/[^.*] not found\./'
187 => DB_ERROR_NOSUCHTABLE,
188 '/There is already an object named/'
189 => DB_ERROR_ALREADY_EXISTS,
190 '/Invalid column name/'
191 => DB_ERROR_NOSUCHFIELD,
192 '/does not allow null values/'
193 => DB_ERROR_CONSTRAINT_NOT_NULL,
194 '/Command has been aborted/'
195 => DB_ERROR_CONSTRAINT,
199 foreach ($error_regexps as $regexp => $code) {
200 if (preg_match($regexp, $errormsg)) {
208 // {{{ sybaseRaiseError()
211 * Gather information about an error, then use that info to create a
212 * DB error object and finally return that object.
214 * @param integer $errno PEAR error number (usually a DB constant) if
215 * manually raising an error
216 * @return object DB error object
219 * @see DB_common::raiseError()
221 function sybaseRaiseError($errno = null)
223 $native = $this->errorNative();
224 if ($errno === null) {
225 $errno = $this->errorCode($native);
227 return $this->raiseError($errno, null, null, null, $native);
234 * Send a query to Sybase and return the results as a Sybase resource
237 * @param the SQL query
241 * @return mixed returns a valid Sybase result for successful SELECT
242 * queries, DB_OK for other successful queries. A DB error is
243 * returned on failure.
245 function simpleQuery($query)
247 $ismanip = DB::isManip($query);
248 $this->last_query = $query;
249 if (!@sybase_select_db($this->_db, $this->connection)) {
250 return $this->sybaseRaiseError(DB_ERROR_NODBSELECTED);
252 $query = $this->modifyQuery($query);
253 if (!$this->autocommit && $ismanip) {
254 if ($this->transaction_opcount == 0) {
255 $result = @sybase_query('BEGIN TRANSACTION', $this->connection);
257 return $this->sybaseRaiseError();
260 $this->transaction_opcount++;
262 $result = @sybase_query($query, $this->connection);
264 return $this->sybaseRaiseError();
266 if (is_resource($result)) {
267 $numrows = $this->numRows($result);
268 if (is_object($numrows)) {
271 $this->num_rows[(int)$result] = $numrows;
274 // Determine which queries that should return data, and which
275 // should return an error code only.
276 return $ismanip ? DB_OK : $result;
283 * Move the internal sybase result pointer to the next available result
285 * @param a valid sybase result resource
289 * @return true if a result is available otherwise return false
291 function nextResult($result)
300 * Fetch a row and insert the data into an existing array.
302 * Formating of the array and the data therein are configurable.
303 * See DB_result::fetchInto() for more information.
305 * @param resource $result query result identifier
306 * @param array $arr (reference) array where data from the row
308 * @param int $fetchmode how the resulting array should be indexed
309 * @param int $rownum the row number to fetch
311 * @return mixed DB_OK on success, null when end of result set is
312 * reached or on failure
314 * @see DB_result::fetchInto()
317 function fetchInto($result, &$arr, $fetchmode, $rownum=null)
319 if ($rownum !== null) {
320 if (!@sybase_data_seek($result, $rownum)) {
324 if ($fetchmode & DB_FETCHMODE_ASSOC) {
325 if (function_exists('sybase_fetch_assoc')) {
326 $arr = @sybase_fetch_assoc($result);
328 if ($arr = @sybase_fetch_array($result)) {
329 foreach ($arr as $key => $value) {
336 if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE && $arr) {
337 $arr = array_change_key_case($arr, CASE_LOWER);
340 $arr = @sybase_fetch_row($result);
343 // reported not work as seems that sybase_get_last_message()
344 // always return a message here
345 //if ($errmsg = @sybase_get_last_message()) {
346 // return $this->sybaseRaiseError($errmsg);
351 if ($this->options['portability'] & DB_PORTABILITY_RTRIM) {
352 $this->_rtrimArrayValues($arr);
354 if ($this->options['portability'] & DB_PORTABILITY_NULL_TO_EMPTY) {
355 $this->_convertNullArrayValuesToEmpty($arr);
364 * Free the internal resources associated with $result.
366 * @param $result Sybase result identifier
370 * @return bool true on success, false if $result is invalid
372 function freeResult($result)
374 unset($this->num_rows[(int)$result]);
375 return @sybase_free_result($result);
382 * Get the number of columns in a result set.
384 * @param $result Sybase result identifier
388 * @return int the number of columns per row in $result
390 function numCols($result)
392 $cols = @sybase_num_fields($result);
394 return $this->sybaseRaiseError();
403 * Get the number of rows in a result set.
405 * @param $result Sybase result identifier
409 * @return int the number of rows in $result
411 function numRows($result)
413 $rows = @sybase_num_rows($result);
414 if ($rows === false) {
415 return $this->sybaseRaiseError();
421 // {{{ affectedRows()
424 * Gets the number of rows affected by the data manipulation
425 * query. For other queries, this function returns 0.
427 * @return number of rows affected by the last query
429 function affectedRows()
431 if (DB::isManip($this->last_query)) {
432 $result = @sybase_affected_rows($this->connection);
443 * Returns the next free id in a sequence
445 * @param string $seq_name name of the sequence
446 * @param boolean $ondemand when true, the seqence is automatically
447 * created if it does not exist
449 * @return int the next id number in the sequence. DB_Error if problem.
452 * @see DB_common::nextID()
455 function nextId($seq_name, $ondemand = true)
457 $seqname = $this->getSequenceName($seq_name);
458 if (!@sybase_select_db($this->_db, $this->connection)) {
459 return $this->sybaseRaiseError(DB_ERROR_NODBSELECTED);
463 $this->pushErrorHandling(PEAR_ERROR_RETURN);
464 $result = $this->query("INSERT INTO $seqname (vapor) VALUES (0)");
465 $this->popErrorHandling();
466 if ($ondemand && DB::isError($result) &&
467 ($result->getCode() == DB_ERROR || $result->getCode() == DB_ERROR_NOSUCHTABLE))
470 $result = $this->createSequence($seq_name);
471 if (DB::isError($result)) {
472 return $this->raiseError($result);
474 } elseif (!DB::isError($result)) {
475 $result =& $this->query("SELECT @@IDENTITY FROM $seqname");
481 if (DB::isError($result)) {
482 return $this->raiseError($result);
484 $result = $result->fetchRow(DB_FETCHMODE_ORDERED);
489 * Creates a new sequence
491 * @param string $seq_name name of the new sequence
493 * @return int DB_OK on success. A DB_Error object is returned if
497 * @see DB_common::createSequence()
500 function createSequence($seq_name)
502 $seqname = $this->getSequenceName($seq_name);
503 return $this->query("CREATE TABLE $seqname ".
504 '(id numeric(10,0) IDENTITY NOT NULL ,' .
509 // {{{ dropSequence()
514 * @param string $seq_name name of the sequence to be deleted
516 * @return int DB_OK on success. DB_Error if problems.
519 * @see DB_common::dropSequence()
522 function dropSequence($seq_name)
524 $seqname = $this->getSequenceName($seq_name);
525 return $this->query("DROP TABLE $seqname");
529 // {{{ getSpecialQuery()
532 * Returns the query needed to get some backend info
533 * @param string $type What kind of info you want to retrieve
534 * @return string The SQL query string
536 function getSpecialQuery($type)
540 return "select name from sysobjects where type = 'U' order by name";
542 return "select name from sysobjects where type = 'V'";
552 * Enable/disable automatic commits
554 function autoCommit($onoff = false)
556 // XXX if $this->transaction_opcount > 0, we should probably
557 // issue a warning here.
558 $this->autocommit = $onoff ? true : false;
566 * Commit the current transaction.
570 if ($this->transaction_opcount > 0) {
571 if (!@sybase_select_db($this->_db, $this->connection)) {
572 return $this->sybaseRaiseError(DB_ERROR_NODBSELECTED);
574 $result = @sybase_query('COMMIT', $this->connection);
575 $this->transaction_opcount = 0;
577 return $this->sybaseRaiseError();
587 * Roll back (undo) the current transaction.
591 if ($this->transaction_opcount > 0) {
592 if (!@sybase_select_db($this->_db, $this->connection)) {
593 return $this->sybaseRaiseError(DB_ERROR_NODBSELECTED);
595 $result = @sybase_query('ROLLBACK', $this->connection);
596 $this->transaction_opcount = 0;
598 return $this->sybaseRaiseError();
608 * Returns information about a table or a result set.
610 * NOTE: only supports 'table' and 'flags' if <var>$result</var>
613 * @param object|string $result DB_result object from a query or a
614 * string containing the name of a table
615 * @param int $mode a valid tableInfo mode
616 * @return array an associative array with the information requested
617 * or an error object if something is wrong
621 * @see DB_common::tableInfo()
623 function tableInfo($result, $mode = null)
625 if (isset($result->result)) {
627 * Probably received a result object.
628 * Extract the result resource identifier.
630 $id = $result->result;
632 } elseif (is_string($result)) {
634 * Probably received a table name.
635 * Create a result resource identifier.
637 if (!@sybase_select_db($this->_db, $this->connection)) {
638 return $this->sybaseRaiseError(DB_ERROR_NODBSELECTED);
640 $id = @sybase_query("SELECT * FROM $result WHERE 1=0",
645 * Probably received a result resource identifier.
647 * Depricated. Here for compatibility only.
653 if (!is_resource($id)) {
654 return $this->sybaseRaiseError(DB_ERROR_NEED_MORE_DATA);
657 if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE) {
658 $case_func = 'strtolower';
660 $case_func = 'strval';
663 $count = @sybase_num_fields($id);
665 // made this IF due to performance (one if is faster than $count if's)
668 for ($i=0; $i<$count; $i++) {
669 $f = @sybase_fetch_field($id, $i);
671 // column_source is often blank
673 $res[$i]['table'] = $case_func($result);
675 $res[$i]['table'] = $case_func($f->column_source);
677 $res[$i]['name'] = $case_func($f->name);
678 $res[$i]['type'] = $f->type;
679 $res[$i]['len'] = $f->max_length;
680 if ($res[$i]['table']) {
681 $res[$i]['flags'] = $this->_sybase_field_flags(
682 $res[$i]['table'], $res[$i]['name']);
684 $res[$i]['flags'] = '';
691 $res['num_fields'] = $count;
693 for ($i=0; $i<$count; $i++) {
694 $f = @sybase_fetch_field($id, $i);
696 // column_source is often blank
698 $res[$i]['table'] = $case_func($result);
700 $res[$i]['table'] = $case_func($f->column_source);
702 $res[$i]['name'] = $case_func($f->name);
703 $res[$i]['type'] = $f->type;
704 $res[$i]['len'] = $f->max_length;
705 if ($res[$i]['table']) {
706 $res[$i]['flags'] = $this->_sybase_field_flags(
707 $res[$i]['table'], $res[$i]['name']);
709 $res[$i]['flags'] = '';
712 if ($mode & DB_TABLEINFO_ORDER) {
713 $res['order'][$res[$i]['name']] = $i;
715 if ($mode & DB_TABLEINFO_ORDERTABLE) {
716 $res['ordertable'][$res[$i]['table']][$res[$i]['name']] = $i;
721 // free the result only if we were called on a table
723 @sybase_free_result($id);
729 // {{{ _sybase_field_flags()
732 * Get the flags for a field.
734 * Currently supports:
735 * + <samp>unique_key</samp> (unique index, unique check or primary_key)
736 * + <samp>multiple_key</samp> (multi-key index)
738 * @param string $table table name
739 * @param string $column field name
740 * @return string space delimited string of flags. Empty string if none.
743 function _sybase_field_flags($table, $column)
745 static $tableName = null;
746 static $flags = array();
748 if ($table != $tableName) {
752 // get unique/primary keys
753 $res = $this->getAll("sp_helpindex $table", DB_FETCHMODE_ASSOC);
755 if (!isset($res[0]['index_description'])) {
759 foreach ($res as $val) {
760 $keys = explode(', ', trim($val['index_keys']));
762 if (sizeof($keys) > 1) {
763 foreach ($keys as $key) {
764 $this->_add_flag($flags[$key], 'multiple_key');
768 if (strpos($val['index_description'], 'unique')) {
769 foreach ($keys as $key) {
770 $this->_add_flag($flags[$key], 'unique_key');
777 if (array_key_exists($column, $flags)) {
778 return(implode(' ', $flags[$column]));
788 * Adds a string to the flags array if the flag is not yet in there
789 * - if there is no flag present the array is created.
791 * @param array $array reference of flags array to add a value to
792 * @param mixed $value value to add to the flag array
795 function _add_flag(&$array, $value)
797 if (!is_array($array)) {
798 $array = array($value);
799 } elseif (!in_array($value, $array)) {
800 array_push($array, $value);
805 // {{{ quoteIdentifier()
808 * Quote a string so it can be safely used as a table / column name
810 * Quoting style depends on which database driver is being used.
812 * @param string $str identifier name to be quoted
814 * @return string quoted identifier string
819 function quoteIdentifier($str)
821 return '[' . str_replace(']', ']]', $str) . ']';