sybase.php 29 KB

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