sybase.php 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956
  1. <?php
  2. /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
  3. /**
  4. * The PEAR DB driver for PHP's sybase extension
  5. * for interacting with Sybase databases
  6. *
  7. * PHP version 5
  8. *
  9. * LICENSE: This source file is subject to version 3.0 of the PHP license
  10. * that is available through the world-wide-web at the following URI:
  11. * http://www.php.net/license/3_0.txt. If you did not receive a copy of
  12. * the PHP License and are unable to obtain it through the web, please
  13. * send a note to license@php.net so we can mail you a copy immediately.
  14. *
  15. * @category Database
  16. * @package DB
  17. * @author Sterling Hughes <sterling@php.net>
  18. * @author Ant�nio Carlos Ven�ncio J�nior <floripa@php.net>
  19. * @author Daniel Convissor <danielc@php.net>
  20. * @copyright 1997-2007 The PHP Group
  21. * @license http://www.php.net/license/3_0.txt PHP License 3.0
  22. * @version CVS: $Id$
  23. * @link http://pear.php.net/package/DB
  24. */
  25. /**
  26. * Obtain the DB_common class so it can be extended from
  27. */
  28. //require_once 'DB/common.php';
  29. require_once 'common.php';
  30. /**
  31. * The methods PEAR DB uses to interact with PHP's sybase extension
  32. * for interacting with Sybase databases
  33. *
  34. * These methods overload the ones declared in DB_common.
  35. *
  36. * WARNING: This driver may fail with multiple connections under the
  37. * same user/pass/host and different databases.
  38. *
  39. * @category Database
  40. * @package DB
  41. * @author Sterling Hughes <sterling@php.net>
  42. * @author Ant�nio Carlos Ven�ncio J�nior <floripa@php.net>
  43. * @author Daniel Convissor <danielc@php.net>
  44. * @copyright 1997-2007 The PHP Group
  45. * @license http://www.php.net/license/3_0.txt PHP License 3.0
  46. * @version Release: 1.9.2
  47. * @link http://pear.php.net/package/DB
  48. */
  49. class DB_sybase extends DB_common
  50. {
  51. // {{{ properties
  52. /**
  53. * The DB driver type (mysql, oci8, odbc, etc.)
  54. * @var string
  55. */
  56. public $phptype = 'sybase';
  57. /**
  58. * The database syntax variant to be used (db2, access, etc.), if any
  59. * @var string
  60. */
  61. public $dbsyntax = 'sybase';
  62. /**
  63. * The capabilities of this DB implementation
  64. *
  65. * The 'new_link' element contains the PHP version that first provided
  66. * new_link support for this DBMS. Contains false if it's unsupported.
  67. *
  68. * Meaning of the 'limit' element:
  69. * + 'emulate' = emulate with fetch row by number
  70. * + 'alter' = alter the query
  71. * + false = skip rows
  72. *
  73. * @var array
  74. */
  75. public $features = array(
  76. 'limit' => 'emulate',
  77. 'new_link' => false,
  78. 'numrows' => true,
  79. 'pconnect' => true,
  80. 'prepare' => false,
  81. 'ssl' => false,
  82. 'transactions' => true,
  83. );
  84. /**
  85. * A mapping of native error codes to DB error codes
  86. * @var array
  87. */
  88. public $errorcode_map = array();
  89. /**
  90. * The raw database connection created by PHP
  91. * @var resource
  92. */
  93. public $connection;
  94. /**
  95. * The DSN information for connecting to a database
  96. * @var array
  97. */
  98. public $dsn = array();
  99. /**
  100. * Should data manipulation queries be committed automatically?
  101. * @var bool
  102. * @access private
  103. */
  104. public $autocommit = true;
  105. /**
  106. * The quantity of transactions begun
  107. *
  108. * {@internal While this is private, it can't actually be designated
  109. * private in PHP 5 because it is directly accessed in the test suite.}}
  110. *
  111. * @var integer
  112. * @access private
  113. */
  114. public $transaction_opcount = 0;
  115. /**
  116. * The database specified in the DSN
  117. *
  118. * It's a fix to allow calls to different databases in the same script.
  119. *
  120. * @var string
  121. * @access private
  122. */
  123. public $_db = '';
  124. // }}}
  125. // {{{ constructor
  126. /**
  127. * This constructor calls <kbd>parent::__construct()</kbd>
  128. *
  129. * @return void
  130. */
  131. public function __construct()
  132. {
  133. parent::__construct();
  134. }
  135. // }}}
  136. // {{{ connect()
  137. /**
  138. * Connect to the database server, log in and open the database
  139. *
  140. * Don't call this method directly. Use DB::connect() instead.
  141. *
  142. * PEAR DB's sybase driver supports the following extra DSN options:
  143. * + appname The application name to use on this connection.
  144. * Available since PEAR DB 1.7.0.
  145. * + charset The character set to use on this connection.
  146. * Available since PEAR DB 1.7.0.
  147. *
  148. * @param array $dsn the data source name
  149. * @param bool $persistent should the connection be persistent?
  150. *
  151. * @return int|object
  152. */
  153. public function connect($dsn, $persistent = false)
  154. {
  155. if (!PEAR::loadExtension('sybase') &&
  156. !PEAR::loadExtension('sybase_ct')) {
  157. return $this->raiseError(DB_ERROR_EXTENSION_NOT_FOUND);
  158. }
  159. $this->dsn = $dsn;
  160. if ($dsn['dbsyntax']) {
  161. $this->dbsyntax = $dsn['dbsyntax'];
  162. }
  163. $dsn['hostspec'] = $dsn['hostspec'] ? $dsn['hostspec'] : 'localhost';
  164. $dsn['password'] = !empty($dsn['password']) ? $dsn['password'] : false;
  165. $dsn['charset'] = isset($dsn['charset']) ? $dsn['charset'] : false;
  166. $dsn['appname'] = isset($dsn['appname']) ? $dsn['appname'] : false;
  167. $connect_function = $persistent ? 'sybase_pconnect' : 'sybase_connect';
  168. if ($dsn['username']) {
  169. $this->connection = @$connect_function(
  170. $dsn['hostspec'],
  171. $dsn['username'],
  172. $dsn['password'],
  173. $dsn['charset'],
  174. $dsn['appname']
  175. );
  176. } else {
  177. return $this->raiseError(
  178. DB_ERROR_CONNECT_FAILED,
  179. null,
  180. null,
  181. null,
  182. 'The DSN did not contain a username.'
  183. );
  184. }
  185. if (!$this->connection) {
  186. return $this->raiseError(
  187. DB_ERROR_CONNECT_FAILED,
  188. null,
  189. null,
  190. null,
  191. @sybase_get_last_message()
  192. );
  193. }
  194. if ($dsn['database']) {
  195. if (!@sybase_select_db($dsn['database'], $this->connection)) {
  196. return $this->raiseError(
  197. DB_ERROR_NODBSELECTED,
  198. null,
  199. null,
  200. null,
  201. @sybase_get_last_message()
  202. );
  203. }
  204. $this->_db = $dsn['database'];
  205. }
  206. return DB_OK;
  207. }
  208. // }}}
  209. // {{{ disconnect()
  210. /**
  211. * Disconnects from the database server
  212. *
  213. * @return bool TRUE on success, FALSE on failure
  214. */
  215. public function disconnect()
  216. {
  217. $ret = @sybase_close($this->connection);
  218. $this->connection = null;
  219. return $ret;
  220. }
  221. // }}}
  222. // {{{ simpleQuery()
  223. /**
  224. * Sends a query to the database server
  225. *
  226. * @param string the SQL query string
  227. *
  228. * @return mixed + a PHP result resrouce for successful SELECT queries
  229. * + the DB_OK constant for other successful queries
  230. * + a DB_Error object on failure
  231. */
  232. public function simpleQuery($query)
  233. {
  234. $ismanip = $this->_checkManip($query);
  235. $this->last_query = $query;
  236. if ($this->_db && !@sybase_select_db($this->_db, $this->connection)) {
  237. return $this->sybaseRaiseError(DB_ERROR_NODBSELECTED);
  238. }
  239. $query = $this->modifyQuery($query);
  240. if (!$this->autocommit && $ismanip) {
  241. if ($this->transaction_opcount == 0) {
  242. $result = @sybase_query('BEGIN TRANSACTION', $this->connection);
  243. if (!$result) {
  244. return $this->sybaseRaiseError();
  245. }
  246. }
  247. $this->transaction_opcount++;
  248. }
  249. $result = @sybase_query($query, $this->connection);
  250. if (!$result) {
  251. return $this->sybaseRaiseError();
  252. }
  253. if (is_resource($result)) {
  254. return $result;
  255. }
  256. // Determine which queries that should return data, and which
  257. // should return an error code only.
  258. return $ismanip ? DB_OK : $result;
  259. }
  260. // }}}
  261. // {{{ nextResult()
  262. /**
  263. * Produces a DB_Error object regarding the current problem
  264. *
  265. * @param int $errno if the error is being manually raised pass a
  266. * DB_ERROR* constant here. If this isn't passed
  267. * the error information gathered from the DBMS.
  268. *
  269. * @return object the DB_Error object
  270. *
  271. * @see DB_common::raiseError(),
  272. * DB_sybase::errorNative(), DB_sybase::errorCode()
  273. */
  274. public function sybaseRaiseError($errno = null)
  275. {
  276. $native = $this->errorNative();
  277. if ($errno === null) {
  278. $errno = $this->errorCode($native);
  279. }
  280. return $this->raiseError($errno, null, null, null, $native);
  281. }
  282. // }}}
  283. // {{{ fetchInto()
  284. /**
  285. * Gets the DBMS' native error message produced by the last query
  286. *
  287. * @return string the DBMS' error message
  288. */
  289. public function errorNative()
  290. {
  291. return @sybase_get_last_message();
  292. }
  293. // }}}
  294. // {{{ freeResult()
  295. /**
  296. * Determines PEAR::DB error code from the database's text error message.
  297. *
  298. * @param string $errormsg error message returned from the database
  299. * @return integer an error number from a DB error constant
  300. */
  301. public function errorCode($errormsg)
  302. {
  303. static $error_regexps;
  304. // PHP 5.2+ prepends the function name to $php_errormsg, so we need
  305. // this hack to work around it, per bug #9599.
  306. $errormsg = preg_replace('/^sybase[a-z_]+\(\): /', '', $errormsg);
  307. if (!isset($error_regexps)) {
  308. $error_regexps = array(
  309. '/Incorrect syntax near/'
  310. => DB_ERROR_SYNTAX,
  311. '/^Unclosed quote before the character string [\"\'].*[\"\']\./'
  312. => DB_ERROR_SYNTAX,
  313. '/Implicit conversion (from datatype|of NUMERIC value)/i'
  314. => DB_ERROR_INVALID_NUMBER,
  315. '/Cannot drop the table [\"\'].+[\"\'], because it doesn\'t exist in the system catalogs\./'
  316. => DB_ERROR_NOSUCHTABLE,
  317. '/Only the owner of object [\"\'].+[\"\'] or a user with System Administrator \(SA\) role can run this command\./'
  318. => DB_ERROR_ACCESS_VIOLATION,
  319. '/^.+ permission denied on object .+, database .+, owner .+/'
  320. => DB_ERROR_ACCESS_VIOLATION,
  321. '/^.* permission denied, database .+, owner .+/'
  322. => DB_ERROR_ACCESS_VIOLATION,
  323. '/[^.*] not found\./'
  324. => DB_ERROR_NOSUCHTABLE,
  325. '/There is already an object named/'
  326. => DB_ERROR_ALREADY_EXISTS,
  327. '/Invalid column name/'
  328. => DB_ERROR_NOSUCHFIELD,
  329. '/does not allow null values/'
  330. => DB_ERROR_CONSTRAINT_NOT_NULL,
  331. '/Command has been aborted/'
  332. => DB_ERROR_CONSTRAINT,
  333. '/^Cannot drop the index .* because it doesn\'t exist/i'
  334. => DB_ERROR_NOT_FOUND,
  335. '/^There is already an index/i'
  336. => DB_ERROR_ALREADY_EXISTS,
  337. '/^There are fewer columns in the INSERT statement than values specified/i'
  338. => DB_ERROR_VALUE_COUNT_ON_ROW,
  339. '/Divide by zero/i'
  340. => DB_ERROR_DIVZERO,
  341. );
  342. }
  343. foreach ($error_regexps as $regexp => $code) {
  344. if (preg_match($regexp, $errormsg)) {
  345. return $code;
  346. }
  347. }
  348. return DB_ERROR;
  349. }
  350. // }}}
  351. // {{{ numCols()
  352. /**
  353. * Move the internal sybase result pointer to the next available result
  354. *
  355. * @param a valid sybase result resource
  356. *
  357. * @access public
  358. *
  359. * @return true if a result is available otherwise return false
  360. */
  361. public function nextResult($result)
  362. {
  363. return false;
  364. }
  365. // }}}
  366. // {{{ numRows()
  367. /**
  368. * Places a row from the result set into the given array
  369. *
  370. * Formating of the array and the data therein are configurable.
  371. * See DB_result::fetchInto() for more information.
  372. *
  373. * This method is not meant to be called directly. Use
  374. * DB_result::fetchInto() instead. It can't be declared "protected"
  375. * because DB_result is a separate object.
  376. *
  377. * @param resource $result the query result resource
  378. * @param array $arr the referenced array to put the data in
  379. * @param int $fetchmode how the resulting array should be indexed
  380. * @param int $rownum the row number to fetch (0 = first row)
  381. *
  382. * @return mixed DB_OK on success, NULL when the end of a result set is
  383. * reached or on failure
  384. *
  385. * @see DB_result::fetchInto()
  386. */
  387. public function fetchInto($result, &$arr, $fetchmode, $rownum = null)
  388. {
  389. if ($rownum !== null) {
  390. if (!@sybase_data_seek($result, $rownum)) {
  391. return null;
  392. }
  393. }
  394. if ($fetchmode & DB_FETCHMODE_ASSOC) {
  395. if (function_exists('sybase_fetch_assoc')) {
  396. $arr = @sybase_fetch_assoc($result);
  397. } else {
  398. if ($arr = @sybase_fetch_array($result)) {
  399. foreach ($arr as $key => $value) {
  400. if (is_int($key)) {
  401. unset($arr[$key]);
  402. }
  403. }
  404. }
  405. }
  406. if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE && $arr) {
  407. $arr = array_change_key_case($arr, CASE_LOWER);
  408. }
  409. } else {
  410. $arr = @sybase_fetch_row($result);
  411. }
  412. if (!$arr) {
  413. return null;
  414. }
  415. if ($this->options['portability'] & DB_PORTABILITY_RTRIM) {
  416. $this->_rtrimArrayValues($arr);
  417. }
  418. if ($this->options['portability'] & DB_PORTABILITY_NULL_TO_EMPTY) {
  419. $this->_convertNullArrayValuesToEmpty($arr);
  420. }
  421. return DB_OK;
  422. }
  423. // }}}
  424. // {{{ affectedRows()
  425. /**
  426. * Deletes the result set and frees the memory occupied by the result set
  427. *
  428. * This method is not meant to be called directly. Use
  429. * DB_result::free() instead. It can't be declared "protected"
  430. * because DB_result is a separate object.
  431. *
  432. * @param resource $result PHP's query result resource
  433. *
  434. * @return bool TRUE on success, FALSE if $result is invalid
  435. *
  436. * @see DB_result::free()
  437. */
  438. public function freeResult($result)
  439. {
  440. return is_resource($result) ? sybase_free_result($result) : false;
  441. }
  442. // }}}
  443. // {{{ nextId()
  444. /**
  445. * Gets the number of columns in a result set
  446. *
  447. * This method is not meant to be called directly. Use
  448. * DB_result::numCols() instead. It can't be declared "protected"
  449. * because DB_result is a separate object.
  450. *
  451. * @param resource $result PHP's query result resource
  452. *
  453. * @return int|object
  454. *
  455. * @see DB_result::numCols()
  456. */
  457. public function numCols($result)
  458. {
  459. $cols = @sybase_num_fields($result);
  460. if (!$cols) {
  461. return $this->sybaseRaiseError();
  462. }
  463. return $cols;
  464. }
  465. /**
  466. * Gets the number of rows in a result set
  467. *
  468. * This method is not meant to be called directly. Use
  469. * DB_result::numRows() instead. It can't be declared "protected"
  470. * because DB_result is a separate object.
  471. *
  472. * @param resource $result PHP's query result resource
  473. *
  474. * @return int|object
  475. *
  476. * @see DB_result::numRows()
  477. */
  478. public function numRows($result)
  479. {
  480. $rows = @sybase_num_rows($result);
  481. if ($rows === false) {
  482. return $this->sybaseRaiseError();
  483. }
  484. return $rows;
  485. }
  486. // }}}
  487. // {{{ dropSequence()
  488. /**
  489. * Determines the number of rows affected by a data maniuplation query
  490. *
  491. * 0 is returned for queries that don't manipulate data.
  492. *
  493. * @return int the number of rows. A DB_Error object on failure.
  494. */
  495. public function affectedRows()
  496. {
  497. if ($this->_last_query_manip) {
  498. $result = @sybase_affected_rows($this->connection);
  499. } else {
  500. $result = 0;
  501. }
  502. return $result;
  503. }
  504. // }}}
  505. // {{{ quoteFloat()
  506. /**
  507. * Returns the next free id in a sequence
  508. *
  509. * @param string $seq_name name of the sequence
  510. * @param boolean $ondemand when true, the seqence is automatically
  511. * created if it does not exist
  512. *
  513. * @return int|object
  514. * A DB_Error object on failure.
  515. *
  516. * @see DB_common::nextID(), DB_common::getSequenceName(),
  517. * DB_sybase::createSequence(), DB_sybase::dropSequence()
  518. */
  519. public function nextId($seq_name, $ondemand = true)
  520. {
  521. $seqname = $this->getSequenceName($seq_name);
  522. if ($this->_db && !@sybase_select_db($this->_db, $this->connection)) {
  523. return $this->sybaseRaiseError(DB_ERROR_NODBSELECTED);
  524. }
  525. $repeat = 0;
  526. do {
  527. $this->pushErrorHandling(PEAR_ERROR_RETURN);
  528. $result = $this->query("INSERT INTO $seqname (vapor) VALUES (0)");
  529. $this->popErrorHandling();
  530. if ($ondemand && DB::isError($result) &&
  531. ($result->getCode() == DB_ERROR || $result->getCode() == DB_ERROR_NOSUCHTABLE)) {
  532. $repeat = 1;
  533. $result = $this->createSequence($seq_name);
  534. if (DB::isError($result)) {
  535. return $this->raiseError($result);
  536. }
  537. } elseif (!DB::isError($result)) {
  538. $result = $this->query("SELECT @@IDENTITY FROM $seqname");
  539. $repeat = 0;
  540. } else {
  541. $repeat = false;
  542. }
  543. } while ($repeat);
  544. if (DB::isError($result)) {
  545. return $this->raiseError($result);
  546. }
  547. $result = $result->fetchRow(DB_FETCHMODE_ORDERED);
  548. return $result[0];
  549. }
  550. // }}}
  551. // {{{ autoCommit()
  552. /**
  553. * Creates a new sequence
  554. *
  555. * @param string $seq_name name of the new sequence
  556. *
  557. * @return int DB_OK on success. A DB_Error object on failure.
  558. *
  559. * @see DB_common::createSequence(), DB_common::getSequenceName(),
  560. * DB_sybase::nextID(), DB_sybase::dropSequence()
  561. */
  562. public function createSequence($seq_name)
  563. {
  564. return $this->query('CREATE TABLE '
  565. . $this->getSequenceName($seq_name)
  566. . ' (id numeric(10, 0) IDENTITY NOT NULL,'
  567. . ' vapor int NULL)');
  568. }
  569. // }}}
  570. // {{{ commit()
  571. /**
  572. * Deletes a sequence
  573. *
  574. * @param string $seq_name name of the sequence to be deleted
  575. *
  576. * @return int DB_OK on success. A DB_Error object on failure.
  577. *
  578. * @see DB_common::dropSequence(), DB_common::getSequenceName(),
  579. * DB_sybase::nextID(), DB_sybase::createSequence()
  580. */
  581. public function dropSequence($seq_name)
  582. {
  583. return $this->query('DROP TABLE ' . $this->getSequenceName($seq_name));
  584. }
  585. // }}}
  586. // {{{ rollback()
  587. /**
  588. * Formats a float value for use within a query in a locale-independent
  589. * manner.
  590. *
  591. * @param float the float value to be quoted.
  592. * @return string the quoted string.
  593. * @see DB_common::quoteSmart()
  594. * @since Method available since release 1.7.8.
  595. */
  596. public function quoteFloat($float)
  597. {
  598. return $this->escapeSimple(str_replace(',', '.', strval(floatval($float))));
  599. }
  600. // }}}
  601. // {{{ sybaseRaiseError()
  602. /**
  603. * Enables or disables automatic commits
  604. *
  605. * @param bool $onoff true turns it on, false turns it off
  606. *
  607. * @return int DB_OK on success. A DB_Error object if the driver
  608. * doesn't support auto-committing transactions.
  609. */
  610. public function autoCommit($onoff = false)
  611. {
  612. // XXX if $this->transaction_opcount > 0, we should probably
  613. // issue a warning here.
  614. $this->autocommit = $onoff ? true : false;
  615. return DB_OK;
  616. }
  617. // }}}
  618. // {{{ errorNative()
  619. /**
  620. * Commits the current transaction
  621. *
  622. * @return int|object
  623. */
  624. public function commit()
  625. {
  626. if ($this->transaction_opcount > 0) {
  627. if ($this->_db && !@sybase_select_db($this->_db, $this->connection)) {
  628. return $this->sybaseRaiseError(DB_ERROR_NODBSELECTED);
  629. }
  630. $result = @sybase_query('COMMIT', $this->connection);
  631. $this->transaction_opcount = 0;
  632. if (!$result) {
  633. return $this->sybaseRaiseError();
  634. }
  635. }
  636. return DB_OK;
  637. }
  638. // }}}
  639. // {{{ errorCode()
  640. /**
  641. * Reverts the current transaction
  642. *
  643. * @return int|object
  644. */
  645. public function rollback()
  646. {
  647. if ($this->transaction_opcount > 0) {
  648. if ($this->_db && !@sybase_select_db($this->_db, $this->connection)) {
  649. return $this->sybaseRaiseError(DB_ERROR_NODBSELECTED);
  650. }
  651. $result = @sybase_query('ROLLBACK', $this->connection);
  652. $this->transaction_opcount = 0;
  653. if (!$result) {
  654. return $this->sybaseRaiseError();
  655. }
  656. }
  657. return DB_OK;
  658. }
  659. // }}}
  660. // {{{ tableInfo()
  661. /**
  662. * Returns information about a table or a result set
  663. *
  664. * NOTE: only supports 'table' and 'flags' if <var>$result</var>
  665. * is a table name.
  666. *
  667. * @param object|string $result DB_result object from a query or a
  668. * string containing the name of a table.
  669. * While this also accepts a query result
  670. * resource identifier, this behavior is
  671. * deprecated.
  672. * @param int $mode a valid tableInfo mode
  673. *
  674. * @return array|object
  675. * A DB_Error object on failure.
  676. *
  677. * @see DB_common::tableInfo()
  678. * @since Method available since Release 1.6.0
  679. */
  680. public function tableInfo($result, $mode = null)
  681. {
  682. if (is_string($result)) {
  683. /*
  684. * Probably received a table name.
  685. * Create a result resource identifier.
  686. */
  687. if ($this->_db && !@sybase_select_db($this->_db, $this->connection)) {
  688. return $this->sybaseRaiseError(DB_ERROR_NODBSELECTED);
  689. }
  690. $id = @sybase_query(
  691. "SELECT * FROM $result WHERE 1=0",
  692. $this->connection
  693. );
  694. $got_string = true;
  695. } elseif (isset($result->result)) {
  696. /*
  697. * Probably received a result object.
  698. * Extract the result resource identifier.
  699. */
  700. $id = $result->result;
  701. $got_string = false;
  702. } else {
  703. /*
  704. * Probably received a result resource identifier.
  705. * Copy it.
  706. * Deprecated. Here for compatibility only.
  707. */
  708. $id = $result;
  709. $got_string = false;
  710. }
  711. if (!is_resource($id)) {
  712. return $this->sybaseRaiseError(DB_ERROR_NEED_MORE_DATA);
  713. }
  714. if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE) {
  715. $case_func = 'strtolower';
  716. } else {
  717. $case_func = 'strval';
  718. }
  719. $count = @sybase_num_fields($id);
  720. $res = array();
  721. if ($mode) {
  722. $res['num_fields'] = $count;
  723. }
  724. for ($i = 0; $i < $count; $i++) {
  725. $f = @sybase_fetch_field($id, $i);
  726. // column_source is often blank
  727. $res[$i] = array(
  728. 'table' => $got_string
  729. ? $case_func($result)
  730. : $case_func($f->column_source),
  731. 'name' => $case_func($f->name),
  732. 'type' => $f->type,
  733. 'len' => $f->max_length,
  734. 'flags' => '',
  735. );
  736. if ($res[$i]['table']) {
  737. $res[$i]['flags'] = $this->_sybase_field_flags(
  738. $res[$i]['table'],
  739. $res[$i]['name']
  740. );
  741. }
  742. if ($mode & DB_TABLEINFO_ORDER) {
  743. $res['order'][$res[$i]['name']] = $i;
  744. }
  745. if ($mode & DB_TABLEINFO_ORDERTABLE) {
  746. $res['ordertable'][$res[$i]['table']][$res[$i]['name']] = $i;
  747. }
  748. }
  749. // free the result only if we were called on a table
  750. if ($got_string) {
  751. @sybase_free_result($id);
  752. }
  753. return $res;
  754. }
  755. // }}}
  756. // {{{ _sybase_field_flags()
  757. /**
  758. * Get the flags for a field
  759. *
  760. * Currently supports:
  761. * + <samp>unique_key</samp> (unique index, unique check or primary_key)
  762. * + <samp>multiple_key</samp> (multi-key index)
  763. *
  764. * @param string $table the table name
  765. * @param string $column the field name
  766. *
  767. * @return string space delimited string of flags. Empty string if none.
  768. *
  769. * @access private
  770. */
  771. public function _sybase_field_flags($table, $column)
  772. {
  773. static $tableName = null;
  774. static $flags = array();
  775. if ($table != $tableName) {
  776. $flags = array();
  777. $tableName = $table;
  778. /* We're running sp_helpindex directly because it doesn't exist in
  779. * older versions of ASE -- unfortunately, we can't just use
  780. * DB::isError() because the user may be using callback error
  781. * handling. */
  782. $res = @sybase_query("sp_helpindex $table", $this->connection);
  783. if ($res === false || $res === true) {
  784. // Fake a valid response for BC reasons.
  785. return '';
  786. }
  787. while (($val = sybase_fetch_assoc($res)) !== false) {
  788. if (!isset($val['index_keys'])) {
  789. /* No useful information returned. Break and be done with
  790. * it, which preserves the pre-1.7.9 behaviour. */
  791. break;
  792. }
  793. $keys = explode(', ', trim($val['index_keys']));
  794. if (sizeof($keys) > 1) {
  795. foreach ($keys as $key) {
  796. $this->_add_flag($flags[$key], 'multiple_key');
  797. }
  798. }
  799. if (strpos($val['index_description'], 'unique')) {
  800. foreach ($keys as $key) {
  801. $this->_add_flag($flags[$key], 'unique_key');
  802. }
  803. }
  804. }
  805. sybase_free_result($res);
  806. }
  807. if (array_key_exists($column, $flags)) {
  808. return (implode(' ', $flags[$column]));
  809. }
  810. return '';
  811. }
  812. // }}}
  813. // {{{ _add_flag()
  814. /**
  815. * Adds a string to the flags array if the flag is not yet in there
  816. * - if there is no flag present the array is created
  817. *
  818. * @param array $array reference of flags array to add a value to
  819. * @param mixed $value value to add to the flag array
  820. *
  821. * @return void
  822. *
  823. * @access private
  824. */
  825. public function _add_flag(&$array, $value)
  826. {
  827. if (!is_array($array)) {
  828. $array = array($value);
  829. } elseif (!in_array($value, $array)) {
  830. array_push($array, $value);
  831. }
  832. }
  833. // }}}
  834. // {{{ getSpecialQuery()
  835. /**
  836. * Obtains the query string needed for listing a given type of objects
  837. *
  838. * @param string $type the kind of objects you want to retrieve
  839. *
  840. * @return string the SQL query string or null if the driver doesn't
  841. * support the object type requested
  842. *
  843. * @access protected
  844. * @see DB_common::getListOf()
  845. */
  846. public function getSpecialQuery($type)
  847. {
  848. switch ($type) {
  849. case 'tables':
  850. return "SELECT name FROM sysobjects WHERE type = 'U'"
  851. . ' ORDER BY name';
  852. case 'views':
  853. return "SELECT name FROM sysobjects WHERE type = 'V'";
  854. default:
  855. return null;
  856. }
  857. }
  858. // }}}
  859. }
  860. /*
  861. * Local variables:
  862. * tab-width: 4
  863. * c-basic-offset: 4
  864. * End:
  865. */