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
// +----------------------------------------------------------------------+
21
// $Id: sybase.php 6184 2008-08-22 10:33:41Z vargenau $
25
// - This driver may fail with multiple connections under the same
26
// user/pass/host and different databases
29
require_once 'DB/common.php';
32
* Database independent query interface definition for PHP's Sybase
36
* @version $Id: sybase.php 6184 2008-08-22 10:33:41Z vargenau $
38
* @author Sterling Hughes <sterling@php.net>
39
* @author Ant�nio Carlos Ven�ncio J�nior <floripa@php.net>
41
class DB_sybase extends DB_common
46
var $phptype, $dbsyntax;
47
var $prepare_tokens = array();
48
var $prepare_types = array();
49
var $transaction_opcount = 0;
50
var $autocommit = true;
56
* DB_sybase constructor.
63
$this->phptype = 'sybase';
64
$this->dbsyntax = 'sybase';
65
$this->features = array(
68
'transactions' => false,
71
$this->errorcode_map = array(
79
* Connect to a database and log in as the specified user.
81
* @param $dsn the data source name (see DB::parseDSN for syntax)
82
* @param $persistent (optional) whether the connection should
85
* @return int DB_OK on success, a DB error on failure
87
function connect($dsninfo, $persistent = false)
89
if (!DB::assertExtension('sybase') &&
90
!DB::assertExtension('sybase_ct'))
92
return $this->raiseError(DB_ERROR_EXTENSION_NOT_FOUND);
95
$this->dsn = $dsninfo;
97
$interface = $dsninfo['hostspec'] ? $dsninfo['hostspec'] : 'localhost';
98
$connect_function = $persistent ? 'sybase_pconnect' : 'sybase_connect';
100
if ($interface && $dsninfo['username'] && $dsninfo['password']) {
101
$conn = @$connect_function($interface, $dsninfo['username'],
102
$dsninfo['password']);
103
} elseif ($interface && $dsninfo['username']) {
105
* Using false for pw as a workaround to avoid segfault.
108
$conn = @$connect_function($interface, $dsninfo['username'],
115
return $this->raiseError(DB_ERROR_CONNECT_FAILED);
118
if ($dsninfo['database']) {
119
if (!@sybase_select_db($dsninfo['database'], $conn)) {
120
return $this->raiseError(DB_ERROR_NODBSELECTED, null,
121
null, null, @sybase_get_last_message());
123
$this->_db = $dsninfo['database'];
126
$this->connection = $conn;
134
* Log out and disconnect from the database.
138
* @return bool true on success, false if not connected.
140
function disconnect()
142
$ret = @sybase_close($this->connection);
143
$this->connection = null;
151
* Get the last server error messge (if any)
153
* @return string sybase last error message
155
function errorNative()
157
return @sybase_get_last_message();
164
* Determine PEAR::DB error code from the database's text error message.
166
* @param string $errormsg error message returned from the database
167
* @return integer an error number from a DB error constant
169
function errorCode($errormsg)
171
static $error_regexps;
172
if (!isset($error_regexps)) {
173
$error_regexps = array(
174
'/Incorrect syntax near/'
176
'/^Unclosed quote before the character string [\"\'].*[\"\']\./'
178
'/Implicit conversion from datatype [\"\'].+[\"\'] to [\"\'].+[\"\'] is not allowed\./'
179
=> DB_ERROR_INVALID_NUMBER,
180
'/Cannot drop the table [\"\'].+[\"\'], because it doesn\'t exist in the system catalogs\./'
181
=> DB_ERROR_NOSUCHTABLE,
182
'/Only the owner of object [\"\'].+[\"\'] or a user with System Administrator \(SA\) role can run this command\./'
183
=> DB_ERROR_ACCESS_VIOLATION,
184
'/^.+ permission denied on object .+, database .+, owner .+/'
185
=> DB_ERROR_ACCESS_VIOLATION,
186
'/^.* permission denied, database .+, owner .+/'
187
=> DB_ERROR_ACCESS_VIOLATION,
188
'/[^.*] not found\./'
189
=> DB_ERROR_NOSUCHTABLE,
190
'/There is already an object named/'
191
=> DB_ERROR_ALREADY_EXISTS,
192
'/Invalid column name/'
193
=> DB_ERROR_NOSUCHFIELD,
194
'/does not allow null values/'
195
=> DB_ERROR_CONSTRAINT_NOT_NULL,
196
'/Command has been aborted/'
197
=> DB_ERROR_CONSTRAINT,
201
foreach ($error_regexps as $regexp => $code) {
202
if (preg_match($regexp, $errormsg)) {
210
// {{{ sybaseRaiseError()
213
* Gather information about an error, then use that info to create a
214
* DB error object and finally return that object.
216
* @param integer $errno PEAR error number (usually a DB constant) if
217
* manually raising an error
218
* @return object DB error object
221
* @see DB_common::raiseError()
223
function sybaseRaiseError($errno = null)
225
$native = $this->errorNative();
226
if ($errno === null) {
227
$errno = $this->errorCode($native);
229
return $this->raiseError($errno, null, null, null, $native);
236
* Send a query to Sybase and return the results as a Sybase resource
239
* @param the SQL query
243
* @return mixed returns a valid Sybase result for successful SELECT
244
* queries, DB_OK for other successful queries. A DB error is
245
* returned on failure.
247
function simpleQuery($query)
249
$ismanip = DB::isManip($query);
250
$this->last_query = $query;
251
if (!@sybase_select_db($this->_db, $this->connection)) {
252
return $this->sybaseRaiseError(DB_ERROR_NODBSELECTED);
254
$query = $this->modifyQuery($query);
255
if (!$this->autocommit && $ismanip) {
256
if ($this->transaction_opcount == 0) {
257
$result = @sybase_query('BEGIN TRANSACTION', $this->connection);
259
return $this->sybaseRaiseError();
262
$this->transaction_opcount++;
264
$result = @sybase_query($query, $this->connection);
266
return $this->sybaseRaiseError();
268
if (is_resource($result)) {
269
$numrows = $this->numRows($result);
270
if (is_object($numrows)) {
273
$this->num_rows[(int)$result] = $numrows;
276
// Determine which queries that should return data, and which
277
// should return an error code only.
278
return $ismanip ? DB_OK : $result;
285
* Move the internal sybase result pointer to the next available result
287
* @param a valid sybase result resource
291
* @return true if a result is available otherwise return false
293
function nextResult($result)
302
* Fetch a row and insert the data into an existing array.
304
* Formating of the array and the data therein are configurable.
305
* See DB_result::fetchInto() for more information.
307
* @param resource $result query result identifier
308
* @param array $arr (reference) array where data from the row
310
* @param int $fetchmode how the resulting array should be indexed
311
* @param int $rownum the row number to fetch
313
* @return mixed DB_OK on success, null when end of result set is
314
* reached or on failure
316
* @see DB_result::fetchInto()
319
function fetchInto($result, &$arr, $fetchmode, $rownum=null)
321
if ($rownum !== null) {
322
if (!@sybase_data_seek($result, $rownum)) {
326
if ($fetchmode & DB_FETCHMODE_ASSOC) {
327
if (function_exists('sybase_fetch_assoc')) {
328
$arr = @sybase_fetch_assoc($result);
330
if ($arr = @sybase_fetch_array($result)) {
331
foreach ($arr as $key => $value) {
338
if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE && $arr) {
339
$arr = array_change_key_case($arr, CASE_LOWER);
342
$arr = @sybase_fetch_row($result);
345
// reported not work as seems that sybase_get_last_message()
346
// always return a message here
347
//if ($errmsg = @sybase_get_last_message()) {
348
// return $this->sybaseRaiseError($errmsg);
353
if ($this->options['portability'] & DB_PORTABILITY_RTRIM) {
354
$this->_rtrimArrayValues($arr);
356
if ($this->options['portability'] & DB_PORTABILITY_NULL_TO_EMPTY) {
357
$this->_convertNullArrayValuesToEmpty($arr);
366
* Free the internal resources associated with $result.
368
* @param $result Sybase result identifier
372
* @return bool true on success, false if $result is invalid
374
function freeResult($result)
376
unset($this->num_rows[(int)$result]);
377
return @sybase_free_result($result);
384
* Get the number of columns in a result set.
386
* @param $result Sybase result identifier
390
* @return int the number of columns per row in $result
392
function numCols($result)
394
$cols = @sybase_num_fields($result);
396
return $this->sybaseRaiseError();
405
* Get the number of rows in a result set.
407
* @param $result Sybase result identifier
411
* @return int the number of rows in $result
413
function numRows($result)
415
$rows = @sybase_num_rows($result);
416
if ($rows === false) {
417
return $this->sybaseRaiseError();
423
// {{{ affectedRows()
426
* Gets the number of rows affected by the data manipulation
427
* query. For other queries, this function returns 0.
429
* @return number of rows affected by the last query
431
function affectedRows()
433
if (DB::isManip($this->last_query)) {
434
$result = @sybase_affected_rows($this->connection);
445
* Returns the next free id in a sequence
447
* @param string $seq_name name of the sequence
448
* @param boolean $ondemand when true, the seqence is automatically
449
* created if it does not exist
451
* @return int the next id number in the sequence. DB_Error if problem.
454
* @see DB_common::nextID()
457
function nextId($seq_name, $ondemand = true)
459
$seqname = $this->getSequenceName($seq_name);
460
if (!@sybase_select_db($this->_db, $this->connection)) {
461
return $this->sybaseRaiseError(DB_ERROR_NODBSELECTED);
465
$this->pushErrorHandling(PEAR_ERROR_RETURN);
466
$result = $this->query("INSERT INTO $seqname (vapor) VALUES (0)");
467
$this->popErrorHandling();
468
if ($ondemand && DB::isError($result) &&
469
($result->getCode() == DB_ERROR || $result->getCode() == DB_ERROR_NOSUCHTABLE))
472
$result = $this->createSequence($seq_name);
473
if (DB::isError($result)) {
474
return $this->raiseError($result);
476
} elseif (!DB::isError($result)) {
477
$result =& $this->query("SELECT @@IDENTITY FROM $seqname");
483
if (DB::isError($result)) {
484
return $this->raiseError($result);
486
$result = $result->fetchRow(DB_FETCHMODE_ORDERED);
491
* Creates a new sequence
493
* @param string $seq_name name of the new sequence
495
* @return int DB_OK on success. A DB_Error object is returned if
499
* @see DB_common::createSequence()
502
function createSequence($seq_name)
504
$seqname = $this->getSequenceName($seq_name);
505
return $this->query("CREATE TABLE $seqname ".
506
'(id numeric(10,0) IDENTITY NOT NULL ,' .
511
// {{{ dropSequence()
516
* @param string $seq_name name of the sequence to be deleted
518
* @return int DB_OK on success. DB_Error if problems.
521
* @see DB_common::dropSequence()
524
function dropSequence($seq_name)
526
$seqname = $this->getSequenceName($seq_name);
527
return $this->query("DROP TABLE $seqname");
531
// {{{ getSpecialQuery()
534
* Returns the query needed to get some backend info
535
* @param string $type What kind of info you want to retrieve
536
* @return string The SQL query string
538
function getSpecialQuery($type)
542
return "select name from sysobjects where type = 'U' order by name";
544
return "select name from sysobjects where type = 'V'";
554
* Enable/disable automatic commits
556
function autoCommit($onoff = false)
558
// XXX if $this->transaction_opcount > 0, we should probably
559
// issue a warning here.
560
$this->autocommit = $onoff ? true : false;
568
* Commit the current transaction.
572
if ($this->transaction_opcount > 0) {
573
if (!@sybase_select_db($this->_db, $this->connection)) {
574
return $this->sybaseRaiseError(DB_ERROR_NODBSELECTED);
576
$result = @sybase_query('COMMIT', $this->connection);
577
$this->transaction_opcount = 0;
579
return $this->sybaseRaiseError();
589
* Roll back (undo) the current transaction.
593
if ($this->transaction_opcount > 0) {
594
if (!@sybase_select_db($this->_db, $this->connection)) {
595
return $this->sybaseRaiseError(DB_ERROR_NODBSELECTED);
597
$result = @sybase_query('ROLLBACK', $this->connection);
598
$this->transaction_opcount = 0;
600
return $this->sybaseRaiseError();
610
* Returns information about a table or a result set.
612
* NOTE: only supports 'table' and 'flags' if <var>$result</var>
615
* @param object|string $result DB_result object from a query or a
616
* string containing the name of a table
617
* @param int $mode a valid tableInfo mode
618
* @return array an associative array with the information requested
619
* or an error object if something is wrong
623
* @see DB_common::tableInfo()
625
function tableInfo($result, $mode = null)
627
if (isset($result->result)) {
629
* Probably received a result object.
630
* Extract the result resource identifier.
632
$id = $result->result;
634
} elseif (is_string($result)) {
636
* Probably received a table name.
637
* Create a result resource identifier.
639
if (!@sybase_select_db($this->_db, $this->connection)) {
640
return $this->sybaseRaiseError(DB_ERROR_NODBSELECTED);
642
$id = @sybase_query("SELECT * FROM $result WHERE 1=0",
647
* Probably received a result resource identifier.
649
* Depricated. Here for compatibility only.
655
if (!is_resource($id)) {
656
return $this->sybaseRaiseError(DB_ERROR_NEED_MORE_DATA);
659
if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE) {
660
$case_func = 'strtolower';
662
$case_func = 'strval';
665
$count = @sybase_num_fields($id);
667
// made this IF due to performance (one if is faster than $count if's)
670
for ($i=0; $i<$count; $i++) {
671
$f = @sybase_fetch_field($id, $i);
673
// column_source is often blank
675
$res[$i]['table'] = $case_func($result);
677
$res[$i]['table'] = $case_func($f->column_source);
679
$res[$i]['name'] = $case_func($f->name);
680
$res[$i]['type'] = $f->type;
681
$res[$i]['len'] = $f->max_length;
682
if ($res[$i]['table']) {
683
$res[$i]['flags'] = $this->_sybase_field_flags(
684
$res[$i]['table'], $res[$i]['name']);
686
$res[$i]['flags'] = '';
693
$res['num_fields'] = $count;
695
for ($i=0; $i<$count; $i++) {
696
$f = @sybase_fetch_field($id, $i);
698
// column_source is often blank
700
$res[$i]['table'] = $case_func($result);
702
$res[$i]['table'] = $case_func($f->column_source);
704
$res[$i]['name'] = $case_func($f->name);
705
$res[$i]['type'] = $f->type;
706
$res[$i]['len'] = $f->max_length;
707
if ($res[$i]['table']) {
708
$res[$i]['flags'] = $this->_sybase_field_flags(
709
$res[$i]['table'], $res[$i]['name']);
711
$res[$i]['flags'] = '';
714
if ($mode & DB_TABLEINFO_ORDER) {
715
$res['order'][$res[$i]['name']] = $i;
717
if ($mode & DB_TABLEINFO_ORDERTABLE) {
718
$res['ordertable'][$res[$i]['table']][$res[$i]['name']] = $i;
723
// free the result only if we were called on a table
725
@sybase_free_result($id);
731
// {{{ _sybase_field_flags()
734
* Get the flags for a field.
736
* Currently supports:
737
* + <samp>unique_key</samp> (unique index, unique check or primary_key)
738
* + <samp>multiple_key</samp> (multi-key index)
740
* @param string $table table name
741
* @param string $column field name
742
* @return string space delimited string of flags. Empty string if none.
745
function _sybase_field_flags($table, $column)
747
static $tableName = null;
748
static $flags = array();
750
if ($table != $tableName) {
754
// get unique/primary keys
755
$res = $this->getAll("sp_helpindex $table", DB_FETCHMODE_ASSOC);
757
if (!isset($res[0]['index_description'])) {
761
foreach ($res as $val) {
762
$keys = explode(', ', trim($val['index_keys']));
764
if (sizeof($keys) > 1) {
765
foreach ($keys as $key) {
766
$this->_add_flag($flags[$key], 'multiple_key');
770
if (strpos($val['index_description'], 'unique')) {
771
foreach ($keys as $key) {
772
$this->_add_flag($flags[$key], 'unique_key');
779
if (array_key_exists($column, $flags)) {
780
return(implode(' ', $flags[$column]));
790
* Adds a string to the flags array if the flag is not yet in there
791
* - if there is no flag present the array is created.
793
* @param array $array reference of flags array to add a value to
794
* @param mixed $value value to add to the flag array
797
function _add_flag(&$array, $value)
799
if (!is_array($array)) {
800
$array = array($value);
801
} elseif (!in_array($value, $array)) {
802
array_push($array, $value);
807
// {{{ quoteIdentifier()
810
* Quote a string so it can be safely used as a table / column name
812
* Quoting style depends on which database driver is being used.
814
* @param string $str identifier name to be quoted
816
* @return string quoted identifier string
821
function quoteIdentifier($str)
823
return '[' . str_replace(']', ']]', $str) . ']';