PageRenderTime 58ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/php/DB/oci8.php

https://bitbucket.org/adarshj/convenient_website
PHP | 1117 lines | 535 code | 90 blank | 492 comment | 91 complexity | 1ae9b0c26e976bdb70e3eb1c37b6733c MD5 | raw file
Possible License(s): Apache-2.0, MPL-2.0-no-copyleft-exception, LGPL-2.1, BSD-2-Clause, GPL-2.0, LGPL-3.0
  1. <?php
  2. /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
  3. /**
  4. * The PEAR DB driver for PHP's oci8 extension
  5. * for interacting with Oracle databases
  6. *
  7. * PHP versions 4 and 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 James L. Pine <jlp@valinux.com>
  18. * @author Daniel Convissor <danielc@php.net>
  19. * @copyright 1997-2005 The PHP Group
  20. * @license http://www.php.net/license/3_0.txt PHP License 3.0
  21. * @version CVS: $Id: oci8.php,v 1.103 2005/04/11 15:10:22 danielc Exp $
  22. * @link http://pear.php.net/package/DB
  23. */
  24. /**
  25. * Obtain the DB_common class so it can be extended from
  26. */
  27. require_once 'DB/common.php';
  28. /**
  29. * The methods PEAR DB uses to interact with PHP's oci8 extension
  30. * for interacting with Oracle databases
  31. *
  32. * Definitely works with versions 8 and 9 of Oracle.
  33. *
  34. * These methods overload the ones declared in DB_common.
  35. *
  36. * Be aware... OCIError() only appears to return anything when given a
  37. * statement, so functions return the generic DB_ERROR instead of more
  38. * useful errors that have to do with feedback from the database.
  39. *
  40. * @category Database
  41. * @package DB
  42. * @author James L. Pine <jlp@valinux.com>
  43. * @author Daniel Convissor <danielc@php.net>
  44. * @copyright 1997-2005 The PHP Group
  45. * @license http://www.php.net/license/3_0.txt PHP License 3.0
  46. * @version Release: 1.7.6
  47. * @link http://pear.php.net/package/DB
  48. */
  49. class DB_oci8 extends DB_common
  50. {
  51. // {{{ properties
  52. /**
  53. * The DB driver type (mysql, oci8, odbc, etc.)
  54. * @var string
  55. */
  56. var $phptype = 'oci8';
  57. /**
  58. * The database syntax variant to be used (db2, access, etc.), if any
  59. * @var string
  60. */
  61. var $dbsyntax = 'oci8';
  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. var $features = array(
  76. 'limit' => 'alter',
  77. 'new_link' => '5.0.0',
  78. 'numrows' => 'subquery',
  79. 'pconnect' => true,
  80. 'prepare' => true,
  81. 'ssl' => false,
  82. 'transactions' => true,
  83. );
  84. /**
  85. * A mapping of native error codes to DB error codes
  86. * @var array
  87. */
  88. var $errorcode_map = array(
  89. 1 => DB_ERROR_CONSTRAINT,
  90. 900 => DB_ERROR_SYNTAX,
  91. 904 => DB_ERROR_NOSUCHFIELD,
  92. 913 => DB_ERROR_VALUE_COUNT_ON_ROW,
  93. 921 => DB_ERROR_SYNTAX,
  94. 923 => DB_ERROR_SYNTAX,
  95. 942 => DB_ERROR_NOSUCHTABLE,
  96. 955 => DB_ERROR_ALREADY_EXISTS,
  97. 1400 => DB_ERROR_CONSTRAINT_NOT_NULL,
  98. 1401 => DB_ERROR_INVALID,
  99. 1407 => DB_ERROR_CONSTRAINT_NOT_NULL,
  100. 1418 => DB_ERROR_NOT_FOUND,
  101. 1476 => DB_ERROR_DIVZERO,
  102. 1722 => DB_ERROR_INVALID_NUMBER,
  103. 2289 => DB_ERROR_NOSUCHTABLE,
  104. 2291 => DB_ERROR_CONSTRAINT,
  105. 2292 => DB_ERROR_CONSTRAINT,
  106. 2449 => DB_ERROR_CONSTRAINT,
  107. );
  108. /**
  109. * The raw database connection created by PHP
  110. * @var resource
  111. */
  112. var $connection;
  113. /**
  114. * The DSN information for connecting to a database
  115. * @var array
  116. */
  117. var $dsn = array();
  118. /**
  119. * Should data manipulation queries be committed automatically?
  120. * @var bool
  121. * @access private
  122. */
  123. var $autocommit = true;
  124. /**
  125. * Stores the $data passed to execute() in the oci8 driver
  126. *
  127. * Gets reset to array() when simpleQuery() is run.
  128. *
  129. * Needed in case user wants to call numRows() after prepare/execute
  130. * was used.
  131. *
  132. * @var array
  133. * @access private
  134. */
  135. var $_data = array();
  136. /**
  137. * The result or statement handle from the most recently executed query
  138. * @var resource
  139. */
  140. var $last_stmt;
  141. /**
  142. * Is the given prepared statement a data manipulation query?
  143. * @var array
  144. * @access private
  145. */
  146. var $manip_query = array();
  147. // }}}
  148. // {{{ constructor
  149. /**
  150. * This constructor calls <kbd>$this->DB_common()</kbd>
  151. *
  152. * @return void
  153. */
  154. function DB_oci8()
  155. {
  156. $this->DB_common();
  157. }
  158. // }}}
  159. // {{{ connect()
  160. /**
  161. * Connect to the database server, log in and open the database
  162. *
  163. * Don't call this method directly. Use DB::connect() instead.
  164. *
  165. * If PHP is at version 5.0.0 or greater:
  166. * + Generally, oci_connect() or oci_pconnect() are used.
  167. * + But if the new_link DSN option is set to true, oci_new_connect()
  168. * is used.
  169. *
  170. * When using PHP version 4.x, OCILogon() or OCIPLogon() are used.
  171. *
  172. * PEAR DB's oci8 driver supports the following extra DSN options:
  173. * + charset The character set to be used on the connection.
  174. * Only used if PHP is at version 5.0.0 or greater
  175. * and the Oracle server is at 9.2 or greater.
  176. * Available since PEAR DB 1.7.0.
  177. * + new_link If set to true, causes subsequent calls to
  178. * connect() to return a new connection link
  179. * instead of the existing one. WARNING: this is
  180. * not portable to other DBMS's.
  181. * Available since PEAR DB 1.7.0.
  182. *
  183. * @param array $dsn the data source name
  184. * @param bool $persistent should the connection be persistent?
  185. *
  186. * @return int DB_OK on success. A DB_Error object on failure.
  187. */
  188. function connect($dsn, $persistent = false)
  189. {
  190. if (!PEAR::loadExtension('oci8')) {
  191. return $this->raiseError(DB_ERROR_EXTENSION_NOT_FOUND);
  192. }
  193. $this->dsn = $dsn;
  194. if ($dsn['dbsyntax']) {
  195. $this->dbsyntax = $dsn['dbsyntax'];
  196. }
  197. if (function_exists('oci_connect')) {
  198. if (isset($dsn['new_link'])
  199. && ($dsn['new_link'] == 'true' || $dsn['new_link'] === true))
  200. {
  201. $connect_function = 'oci_new_connect';
  202. } else {
  203. $connect_function = $persistent ? 'oci_pconnect'
  204. : 'oci_connect';
  205. }
  206. // Backwards compatibility with DB < 1.7.0
  207. if (empty($dsn['database']) && !empty($dsn['hostspec'])) {
  208. $db = $dsn['hostspec'];
  209. } else {
  210. $db = $dsn['database'];
  211. }
  212. $char = empty($dsn['charset']) ? null : $dsn['charset'];
  213. $this->connection = @$connect_function($dsn['username'],
  214. $dsn['password'],
  215. $db,
  216. $char);
  217. $error = OCIError();
  218. if (!empty($error) && $error['code'] == 12541) {
  219. // Couldn't find TNS listener. Try direct connection.
  220. $this->connection = @$connect_function($dsn['username'],
  221. $dsn['password'],
  222. null,
  223. $char);
  224. }
  225. } else {
  226. $connect_function = $persistent ? 'OCIPLogon' : 'OCILogon';
  227. if ($dsn['hostspec']) {
  228. $this->connection = @$connect_function($dsn['username'],
  229. $dsn['password'],
  230. $dsn['hostspec']);
  231. } elseif ($dsn['username'] || $dsn['password']) {
  232. $this->connection = @$connect_function($dsn['username'],
  233. $dsn['password']);
  234. }
  235. }
  236. if (!$this->connection) {
  237. $error = OCIError();
  238. $error = (is_array($error)) ? $error['message'] : null;
  239. return $this->raiseError(DB_ERROR_CONNECT_FAILED,
  240. null, null, null,
  241. $error);
  242. }
  243. return DB_OK;
  244. }
  245. // }}}
  246. // {{{ disconnect()
  247. /**
  248. * Disconnects from the database server
  249. *
  250. * @return bool TRUE on success, FALSE on failure
  251. */
  252. function disconnect()
  253. {
  254. if (function_exists('oci_close')) {
  255. $ret = @oci_close($this->connection);
  256. } else {
  257. $ret = @OCILogOff($this->connection);
  258. }
  259. $this->connection = null;
  260. return $ret;
  261. }
  262. // }}}
  263. // {{{ simpleQuery()
  264. /**
  265. * Sends a query to the database server
  266. *
  267. * To determine how many rows of a result set get buffered using
  268. * ocisetprefetch(), see the "result_buffering" option in setOptions().
  269. * This option was added in Release 1.7.0.
  270. *
  271. * @param string the SQL query string
  272. *
  273. * @return mixed + a PHP result resrouce for successful SELECT queries
  274. * + the DB_OK constant for other successful queries
  275. * + a DB_Error object on failure
  276. */
  277. function simpleQuery($query)
  278. {
  279. $this->_data = array();
  280. $this->last_parameters = array();
  281. $this->last_query = $query;
  282. $query = $this->modifyQuery($query);
  283. $result = @OCIParse($this->connection, $query);
  284. if (!$result) {
  285. return $this->oci8RaiseError();
  286. }
  287. if ($this->autocommit) {
  288. $success = @OCIExecute($result,OCI_COMMIT_ON_SUCCESS);
  289. } else {
  290. $success = @OCIExecute($result,OCI_DEFAULT);
  291. }
  292. if (!$success) {
  293. return $this->oci8RaiseError($result);
  294. }
  295. $this->last_stmt = $result;
  296. if (DB::isManip($query)) {
  297. return DB_OK;
  298. } else {
  299. @ocisetprefetch($result, $this->options['result_buffering']);
  300. return $result;
  301. }
  302. }
  303. // }}}
  304. // {{{ nextResult()
  305. /**
  306. * Move the internal oracle result pointer to the next available result
  307. *
  308. * @param a valid oci8 result resource
  309. *
  310. * @access public
  311. *
  312. * @return true if a result is available otherwise return false
  313. */
  314. function nextResult($result)
  315. {
  316. return false;
  317. }
  318. // }}}
  319. // {{{ fetchInto()
  320. /**
  321. * Places a row from the result set into the given array
  322. *
  323. * Formating of the array and the data therein are configurable.
  324. * See DB_result::fetchInto() for more information.
  325. *
  326. * This method is not meant to be called directly. Use
  327. * DB_result::fetchInto() instead. It can't be declared "protected"
  328. * because DB_result is a separate object.
  329. *
  330. * @param resource $result the query result resource
  331. * @param array $arr the referenced array to put the data in
  332. * @param int $fetchmode how the resulting array should be indexed
  333. * @param int $rownum the row number to fetch (0 = first row)
  334. *
  335. * @return mixed DB_OK on success, NULL when the end of a result set is
  336. * reached or on failure
  337. *
  338. * @see DB_result::fetchInto()
  339. */
  340. function fetchInto($result, &$arr, $fetchmode, $rownum = null)
  341. {
  342. if ($rownum !== null) {
  343. return $this->raiseError(DB_ERROR_NOT_CAPABLE);
  344. }
  345. if ($fetchmode & DB_FETCHMODE_ASSOC) {
  346. $moredata = @OCIFetchInto($result,$arr,OCI_ASSOC+OCI_RETURN_NULLS+OCI_RETURN_LOBS);
  347. if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE &&
  348. $moredata)
  349. {
  350. $arr = array_change_key_case($arr, CASE_LOWER);
  351. }
  352. } else {
  353. $moredata = OCIFetchInto($result,$arr,OCI_RETURN_NULLS+OCI_RETURN_LOBS);
  354. }
  355. if (!$moredata) {
  356. return null;
  357. }
  358. if ($this->options['portability'] & DB_PORTABILITY_RTRIM) {
  359. $this->_rtrimArrayValues($arr);
  360. }
  361. if ($this->options['portability'] & DB_PORTABILITY_NULL_TO_EMPTY) {
  362. $this->_convertNullArrayValuesToEmpty($arr);
  363. }
  364. return DB_OK;
  365. }
  366. // }}}
  367. // {{{ freeResult()
  368. /**
  369. * Deletes the result set and frees the memory occupied by the result set
  370. *
  371. * This method is not meant to be called directly. Use
  372. * DB_result::free() instead. It can't be declared "protected"
  373. * because DB_result is a separate object.
  374. *
  375. * @param resource $result PHP's query result resource
  376. *
  377. * @return bool TRUE on success, FALSE if $result is invalid
  378. *
  379. * @see DB_result::free()
  380. */
  381. function freeResult($result)
  382. {
  383. return @OCIFreeStatement($result);
  384. }
  385. /**
  386. * Frees the internal resources associated with a prepared query
  387. *
  388. * @param resource $stmt the prepared statement's resource
  389. * @param bool $free_resource should the PHP resource be freed too?
  390. * Use false if you need to get data
  391. * from the result set later.
  392. *
  393. * @return bool TRUE on success, FALSE if $result is invalid
  394. *
  395. * @see DB_oci8::prepare()
  396. */
  397. function freePrepared($stmt, $free_resource = true)
  398. {
  399. if (!is_resource($stmt)) {
  400. return false;
  401. }
  402. if ($free_resource) {
  403. @ocifreestatement($stmt);
  404. }
  405. if (isset($this->prepare_types[(int)$stmt])) {
  406. unset($this->prepare_types[(int)$stmt]);
  407. unset($this->manip_query[(int)$stmt]);
  408. } else {
  409. return false;
  410. }
  411. return true;
  412. }
  413. // }}}
  414. // {{{ numRows()
  415. /**
  416. * Gets the number of rows in a result set
  417. *
  418. * Only works if the DB_PORTABILITY_NUMROWS portability option
  419. * is turned on.
  420. *
  421. * This method is not meant to be called directly. Use
  422. * DB_result::numRows() instead. It can't be declared "protected"
  423. * because DB_result is a separate object.
  424. *
  425. * @param resource $result PHP's query result resource
  426. *
  427. * @return int the number of rows. A DB_Error object on failure.
  428. *
  429. * @see DB_result::numRows(), DB_common::setOption()
  430. */
  431. function numRows($result)
  432. {
  433. // emulate numRows for Oracle. yuck.
  434. if ($this->options['portability'] & DB_PORTABILITY_NUMROWS &&
  435. $result === $this->last_stmt)
  436. {
  437. $countquery = 'SELECT COUNT(*) FROM ('.$this->last_query.')';
  438. $save_query = $this->last_query;
  439. $save_stmt = $this->last_stmt;
  440. if (count($this->_data)) {
  441. $smt = $this->prepare('SELECT COUNT(*) FROM ('.$this->last_query.')');
  442. $count = $this->execute($smt, $this->_data);
  443. } else {
  444. $count =& $this->query($countquery);
  445. }
  446. if (DB::isError($count) ||
  447. DB::isError($row = $count->fetchRow(DB_FETCHMODE_ORDERED)))
  448. {
  449. $this->last_query = $save_query;
  450. $this->last_stmt = $save_stmt;
  451. return $this->raiseError(DB_ERROR_NOT_CAPABLE);
  452. }
  453. return $row[0];
  454. }
  455. return $this->raiseError(DB_ERROR_NOT_CAPABLE);
  456. }
  457. // }}}
  458. // {{{ numCols()
  459. /**
  460. * Gets the number of columns in a result set
  461. *
  462. * This method is not meant to be called directly. Use
  463. * DB_result::numCols() instead. It can't be declared "protected"
  464. * because DB_result is a separate object.
  465. *
  466. * @param resource $result PHP's query result resource
  467. *
  468. * @return int the number of columns. A DB_Error object on failure.
  469. *
  470. * @see DB_result::numCols()
  471. */
  472. function numCols($result)
  473. {
  474. $cols = @OCINumCols($result);
  475. if (!$cols) {
  476. return $this->oci8RaiseError($result);
  477. }
  478. return $cols;
  479. }
  480. // }}}
  481. // {{{ prepare()
  482. /**
  483. * Prepares a query for multiple execution with execute().
  484. *
  485. * With oci8, this is emulated.
  486. *
  487. * prepare() requires a generic query as string like <code>
  488. * INSERT INTO numbers VALUES (?, ?, ?)
  489. * </code>. The <kbd>?</kbd> characters are placeholders.
  490. *
  491. * Three types of placeholders can be used:
  492. * + <kbd>?</kbd> a quoted scalar value, i.e. strings, integers
  493. * + <kbd>!</kbd> value is inserted 'as is'
  494. * + <kbd>&</kbd> requires a file name. The file's contents get
  495. * inserted into the query (i.e. saving binary
  496. * data in a db)
  497. *
  498. * Use backslashes to escape placeholder characters if you don't want
  499. * them to be interpreted as placeholders. Example: <code>
  500. * "UPDATE foo SET col=? WHERE col='over \& under'"
  501. * </code>
  502. *
  503. * @param string $query the query to be prepared
  504. *
  505. * @return mixed DB statement resource on success. DB_Error on failure.
  506. *
  507. * @see DB_oci8::execute()
  508. */
  509. function prepare($query)
  510. {
  511. $tokens = preg_split('/((?<!\\\)[&?!])/', $query, -1,
  512. PREG_SPLIT_DELIM_CAPTURE);
  513. $binds = count($tokens) - 1;
  514. $token = 0;
  515. $types = array();
  516. $newquery = '';
  517. foreach ($tokens as $key => $val) {
  518. switch ($val) {
  519. case '?':
  520. $types[$token++] = DB_PARAM_SCALAR;
  521. unset($tokens[$key]);
  522. break;
  523. case '&':
  524. $types[$token++] = DB_PARAM_OPAQUE;
  525. unset($tokens[$key]);
  526. break;
  527. case '!':
  528. $types[$token++] = DB_PARAM_MISC;
  529. unset($tokens[$key]);
  530. break;
  531. default:
  532. $tokens[$key] = preg_replace('/\\\([&?!])/', "\\1", $val);
  533. if ($key != $binds) {
  534. $newquery .= $tokens[$key] . ':bind' . $token;
  535. } else {
  536. $newquery .= $tokens[$key];
  537. }
  538. }
  539. }
  540. $this->last_query = $query;
  541. $newquery = $this->modifyQuery($newquery);
  542. if (!$stmt = @OCIParse($this->connection, $newquery)) {
  543. return $this->oci8RaiseError();
  544. }
  545. $this->prepare_types[(int)$stmt] = $types;
  546. $this->manip_query[(int)$stmt] = DB::isManip($query);
  547. return $stmt;
  548. }
  549. // }}}
  550. // {{{ execute()
  551. /**
  552. * Executes a DB statement prepared with prepare().
  553. *
  554. * To determine how many rows of a result set get buffered using
  555. * ocisetprefetch(), see the "result_buffering" option in setOptions().
  556. * This option was added in Release 1.7.0.
  557. *
  558. * @param resource $stmt a DB statement resource returned from prepare()
  559. * @param mixed $data array, string or numeric data to be used in
  560. * execution of the statement. Quantity of items
  561. * passed must match quantity of placeholders in
  562. * query: meaning 1 for non-array items or the
  563. * quantity of elements in the array.
  564. *
  565. * @return mixed returns an oic8 result resource for successful SELECT
  566. * queries, DB_OK for other successful queries.
  567. * A DB error object is returned on failure.
  568. *
  569. * @see DB_oci8::prepare()
  570. */
  571. function &execute($stmt, $data = array())
  572. {
  573. $data = (array)$data;
  574. $this->last_parameters = $data;
  575. $this->_data = $data;
  576. $types =& $this->prepare_types[(int)$stmt];
  577. if (count($types) != count($data)) {
  578. $tmp =& $this->raiseError(DB_ERROR_MISMATCH);
  579. return $tmp;
  580. }
  581. $i = 0;
  582. foreach ($data as $key => $value) {
  583. if ($types[$i] == DB_PARAM_MISC) {
  584. /*
  585. * Oracle doesn't seem to have the ability to pass a
  586. * parameter along unchanged, so strip off quotes from start
  587. * and end, plus turn two single quotes to one single quote,
  588. * in order to avoid the quotes getting escaped by
  589. * Oracle and ending up in the database.
  590. */
  591. $data[$key] = preg_replace("/^'(.*)'$/", "\\1", $data[$key]);
  592. $data[$key] = str_replace("''", "'", $data[$key]);
  593. } elseif ($types[$i] == DB_PARAM_OPAQUE) {
  594. $fp = @fopen($data[$key], 'rb');
  595. if (!$fp) {
  596. $tmp =& $this->raiseError(DB_ERROR_ACCESS_VIOLATION);
  597. return $tmp;
  598. }
  599. $data[$key] = fread($fp, filesize($data[$key]));
  600. fclose($fp);
  601. }
  602. if (!@OCIBindByName($stmt, ':bind' . $i, $data[$key], -1)) {
  603. $tmp = $this->oci8RaiseError($stmt);
  604. return $tmp;
  605. }
  606. $i++;
  607. }
  608. if ($this->autocommit) {
  609. $success = @OCIExecute($stmt, OCI_COMMIT_ON_SUCCESS);
  610. } else {
  611. $success = @OCIExecute($stmt, OCI_DEFAULT);
  612. }
  613. if (!$success) {
  614. $tmp = $this->oci8RaiseError($stmt);
  615. return $tmp;
  616. }
  617. $this->last_stmt = $stmt;
  618. if ($this->manip_query[(int)$stmt]) {
  619. $tmp = DB_OK;
  620. } else {
  621. @ocisetprefetch($stmt, $this->options['result_buffering']);
  622. $tmp =& new DB_result($this, $stmt);
  623. }
  624. return $tmp;
  625. }
  626. // }}}
  627. // {{{ autoCommit()
  628. /**
  629. * Enables or disables automatic commits
  630. *
  631. * @param bool $onoff true turns it on, false turns it off
  632. *
  633. * @return int DB_OK on success. A DB_Error object if the driver
  634. * doesn't support auto-committing transactions.
  635. */
  636. function autoCommit($onoff = false)
  637. {
  638. $this->autocommit = (bool)$onoff;;
  639. return DB_OK;
  640. }
  641. // }}}
  642. // {{{ commit()
  643. /**
  644. * Commits the current transaction
  645. *
  646. * @return int DB_OK on success. A DB_Error object on failure.
  647. */
  648. function commit()
  649. {
  650. $result = @OCICommit($this->connection);
  651. if (!$result) {
  652. return $this->oci8RaiseError();
  653. }
  654. return DB_OK;
  655. }
  656. // }}}
  657. // {{{ rollback()
  658. /**
  659. * Reverts the current transaction
  660. *
  661. * @return int DB_OK on success. A DB_Error object on failure.
  662. */
  663. function rollback()
  664. {
  665. $result = @OCIRollback($this->connection);
  666. if (!$result) {
  667. return $this->oci8RaiseError();
  668. }
  669. return DB_OK;
  670. }
  671. // }}}
  672. // {{{ affectedRows()
  673. /**
  674. * Determines the number of rows affected by a data maniuplation query
  675. *
  676. * 0 is returned for queries that don't manipulate data.
  677. *
  678. * @return int the number of rows. A DB_Error object on failure.
  679. */
  680. function affectedRows()
  681. {
  682. if ($this->last_stmt === false) {
  683. return $this->oci8RaiseError();
  684. }
  685. $result = @OCIRowCount($this->last_stmt);
  686. if ($result === false) {
  687. return $this->oci8RaiseError($this->last_stmt);
  688. }
  689. return $result;
  690. }
  691. // }}}
  692. // {{{ modifyQuery()
  693. /**
  694. * Changes a query string for various DBMS specific reasons
  695. *
  696. * "SELECT 2+2" must be "SELECT 2+2 FROM dual" in Oracle.
  697. *
  698. * @param string $query the query string to modify
  699. *
  700. * @return string the modified query string
  701. *
  702. * @access protected
  703. */
  704. function modifyQuery($query)
  705. {
  706. if (preg_match('/^\s*SELECT/i', $query) &&
  707. !preg_match('/\sFROM\s/i', $query)) {
  708. $query .= ' FROM dual';
  709. }
  710. return $query;
  711. }
  712. // }}}
  713. // {{{ modifyLimitQuery()
  714. /**
  715. * Adds LIMIT clauses to a query string according to current DBMS standards
  716. *
  717. * @param string $query the query to modify
  718. * @param int $from the row to start to fetching (0 = the first row)
  719. * @param int $count the numbers of rows to fetch
  720. * @param mixed $params array, string or numeric data to be used in
  721. * execution of the statement. Quantity of items
  722. * passed must match quantity of placeholders in
  723. * query: meaning 1 placeholder for non-array
  724. * parameters or 1 placeholder per array element.
  725. *
  726. * @return string the query string with LIMIT clauses added
  727. *
  728. * @access protected
  729. */
  730. function modifyLimitQuery($query, $from, $count, $params = array())
  731. {
  732. // Let Oracle return the name of the columns instead of
  733. // coding a "home" SQL parser
  734. if (count($params)) {
  735. $result = $this->prepare("SELECT * FROM ($query) "
  736. . 'WHERE NULL = NULL');
  737. $tmp =& $this->execute($result, $params);
  738. } else {
  739. $q_fields = "SELECT * FROM ($query) WHERE NULL = NULL";
  740. if (!$result = @OCIParse($this->connection, $q_fields)) {
  741. $this->last_query = $q_fields;
  742. return $this->oci8RaiseError();
  743. }
  744. if (!@OCIExecute($result, OCI_DEFAULT)) {
  745. $this->last_query = $q_fields;
  746. return $this->oci8RaiseError($result);
  747. }
  748. }
  749. $ncols = OCINumCols($result);
  750. $cols = array();
  751. for ( $i = 1; $i <= $ncols; $i++ ) {
  752. $cols[] = '"' . OCIColumnName($result, $i) . '"';
  753. }
  754. $fields = implode(', ', $cols);
  755. // XXX Test that (tip by John Lim)
  756. //if (preg_match('/^\s*SELECT\s+/is', $query, $match)) {
  757. // // Introduce the FIRST_ROWS Oracle query optimizer
  758. // $query = substr($query, strlen($match[0]), strlen($query));
  759. // $query = "SELECT /* +FIRST_ROWS */ " . $query;
  760. //}
  761. // Construct the query
  762. // more at: http://marc.theaimsgroup.com/?l=php-db&m=99831958101212&w=2
  763. // Perhaps this could be optimized with the use of Unions
  764. $query = "SELECT $fields FROM".
  765. " (SELECT rownum as linenum, $fields FROM".
  766. " ($query)".
  767. ' WHERE rownum <= '. ($from + $count) .
  768. ') WHERE linenum >= ' . ++$from;
  769. return $query;
  770. }
  771. // }}}
  772. // {{{ nextId()
  773. /**
  774. * Returns the next free id in a sequence
  775. *
  776. * @param string $seq_name name of the sequence
  777. * @param boolean $ondemand when true, the seqence is automatically
  778. * created if it does not exist
  779. *
  780. * @return int the next id number in the sequence.
  781. * A DB_Error object on failure.
  782. *
  783. * @see DB_common::nextID(), DB_common::getSequenceName(),
  784. * DB_oci8::createSequence(), DB_oci8::dropSequence()
  785. */
  786. function nextId($seq_name, $ondemand = true)
  787. {
  788. $seqname = $this->getSequenceName($seq_name);
  789. $repeat = 0;
  790. do {
  791. $this->expectError(DB_ERROR_NOSUCHTABLE);
  792. $result =& $this->query("SELECT ${seqname}.nextval FROM dual");
  793. $this->popExpect();
  794. if ($ondemand && DB::isError($result) &&
  795. $result->getCode() == DB_ERROR_NOSUCHTABLE) {
  796. $repeat = 1;
  797. $result = $this->createSequence($seq_name);
  798. if (DB::isError($result)) {
  799. return $this->raiseError($result);
  800. }
  801. } else {
  802. $repeat = 0;
  803. }
  804. } while ($repeat);
  805. if (DB::isError($result)) {
  806. return $this->raiseError($result);
  807. }
  808. $arr = $result->fetchRow(DB_FETCHMODE_ORDERED);
  809. return $arr[0];
  810. }
  811. /**
  812. * Creates a new sequence
  813. *
  814. * @param string $seq_name name of the new sequence
  815. *
  816. * @return int DB_OK on success. A DB_Error object on failure.
  817. *
  818. * @see DB_common::createSequence(), DB_common::getSequenceName(),
  819. * DB_oci8::nextID(), DB_oci8::dropSequence()
  820. */
  821. function createSequence($seq_name)
  822. {
  823. return $this->query('CREATE SEQUENCE '
  824. . $this->getSequenceName($seq_name));
  825. }
  826. // }}}
  827. // {{{ dropSequence()
  828. /**
  829. * Deletes a sequence
  830. *
  831. * @param string $seq_name name of the sequence to be deleted
  832. *
  833. * @return int DB_OK on success. A DB_Error object on failure.
  834. *
  835. * @see DB_common::dropSequence(), DB_common::getSequenceName(),
  836. * DB_oci8::nextID(), DB_oci8::createSequence()
  837. */
  838. function dropSequence($seq_name)
  839. {
  840. return $this->query('DROP SEQUENCE '
  841. . $this->getSequenceName($seq_name));
  842. }
  843. // }}}
  844. // {{{ oci8RaiseError()
  845. /**
  846. * Produces a DB_Error object regarding the current problem
  847. *
  848. * @param int $errno if the error is being manually raised pass a
  849. * DB_ERROR* constant here. If this isn't passed
  850. * the error information gathered from the DBMS.
  851. *
  852. * @return object the DB_Error object
  853. *
  854. * @see DB_common::raiseError(),
  855. * DB_oci8::errorNative(), DB_oci8::errorCode()
  856. */
  857. function oci8RaiseError($errno = null)
  858. {
  859. if ($errno === null) {
  860. $error = @OCIError($this->connection);
  861. return $this->raiseError($this->errorCode($error['code']),
  862. null, null, null, $error['message']);
  863. } elseif (is_resource($errno)) {
  864. $error = @OCIError($errno);
  865. return $this->raiseError($this->errorCode($error['code']),
  866. null, null, null, $error['message']);
  867. }
  868. return $this->raiseError($this->errorCode($errno));
  869. }
  870. // }}}
  871. // {{{ errorNative()
  872. /**
  873. * Gets the DBMS' native error code produced by the last query
  874. *
  875. * @return int the DBMS' error code. FALSE if the code could not be
  876. * determined
  877. */
  878. function errorNative()
  879. {
  880. if (is_resource($this->last_stmt)) {
  881. $error = @OCIError($this->last_stmt);
  882. } else {
  883. $error = @OCIError($this->connection);
  884. }
  885. if (is_array($error)) {
  886. return $error['code'];
  887. }
  888. return false;
  889. }
  890. // }}}
  891. // {{{ tableInfo()
  892. /**
  893. * Returns information about a table or a result set
  894. *
  895. * NOTE: only supports 'table' and 'flags' if <var>$result</var>
  896. * is a table name.
  897. *
  898. * NOTE: flags won't contain index information.
  899. *
  900. * @param object|string $result DB_result object from a query or a
  901. * string containing the name of a table.
  902. * While this also accepts a query result
  903. * resource identifier, this behavior is
  904. * deprecated.
  905. * @param int $mode a valid tableInfo mode
  906. *
  907. * @return array an associative array with the information requested.
  908. * A DB_Error object on failure.
  909. *
  910. * @see DB_common::tableInfo()
  911. */
  912. function tableInfo($result, $mode = null)
  913. {
  914. if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE) {
  915. $case_func = 'strtolower';
  916. } else {
  917. $case_func = 'strval';
  918. }
  919. $res = array();
  920. if (is_string($result)) {
  921. /*
  922. * Probably received a table name.
  923. * Create a result resource identifier.
  924. */
  925. $result = strtoupper($result);
  926. $q_fields = 'SELECT column_name, data_type, data_length, '
  927. . 'nullable '
  928. . 'FROM user_tab_columns '
  929. . "WHERE table_name='$result' ORDER BY column_id";
  930. $this->last_query = $q_fields;
  931. if (!$stmt = @OCIParse($this->connection, $q_fields)) {
  932. return $this->oci8RaiseError(DB_ERROR_NEED_MORE_DATA);
  933. }
  934. if (!@OCIExecute($stmt, OCI_DEFAULT)) {
  935. return $this->oci8RaiseError($stmt);
  936. }
  937. $i = 0;
  938. while (@OCIFetch($stmt)) {
  939. $res[$i] = array(
  940. 'table' => $case_func($result),
  941. 'name' => $case_func(@OCIResult($stmt, 1)),
  942. 'type' => @OCIResult($stmt, 2),
  943. 'len' => @OCIResult($stmt, 3),
  944. 'flags' => (@OCIResult($stmt, 4) == 'N') ? 'not_null' : '',
  945. );
  946. if ($mode & DB_TABLEINFO_ORDER) {
  947. $res['order'][$res[$i]['name']] = $i;
  948. }
  949. if ($mode & DB_TABLEINFO_ORDERTABLE) {
  950. $res['ordertable'][$res[$i]['table']][$res[$i]['name']] = $i;
  951. }
  952. $i++;
  953. }
  954. if ($mode) {
  955. $res['num_fields'] = $i;
  956. }
  957. @OCIFreeStatement($stmt);
  958. } else {
  959. if (isset($result->result)) {
  960. /*
  961. * Probably received a result object.
  962. * Extract the result resource identifier.
  963. */
  964. $result = $result->result;
  965. }
  966. $res = array();
  967. if ($result === $this->last_stmt) {
  968. $count = @OCINumCols($result);
  969. if ($mode) {
  970. $res['num_fields'] = $count;
  971. }
  972. for ($i = 0; $i < $count; $i++) {
  973. $res[$i] = array(
  974. 'table' => '',
  975. 'name' => $case_func(@OCIColumnName($result, $i+1)),
  976. 'type' => @OCIColumnType($result, $i+1),
  977. 'len' => @OCIColumnSize($result, $i+1),
  978. 'flags' => '',
  979. );
  980. if ($mode & DB_TABLEINFO_ORDER) {
  981. $res['order'][$res[$i]['name']] = $i;
  982. }
  983. if ($mode & DB_TABLEINFO_ORDERTABLE) {
  984. $res['ordertable'][$res[$i]['table']][$res[$i]['name']] = $i;
  985. }
  986. }
  987. } else {
  988. return $this->raiseError(DB_ERROR_NOT_CAPABLE);
  989. }
  990. }
  991. return $res;
  992. }
  993. // }}}
  994. // {{{ getSpecialQuery()
  995. /**
  996. * Obtains the query string needed for listing a given type of objects
  997. *
  998. * @param string $type the kind of objects you want to retrieve
  999. *
  1000. * @return string the SQL query string or null if the driver doesn't
  1001. * support the object type requested
  1002. *
  1003. * @access protected
  1004. * @see DB_common::getListOf()
  1005. */
  1006. function getSpecialQuery($type)
  1007. {
  1008. switch ($type) {
  1009. case 'tables':
  1010. return 'SELECT table_name FROM user_tables';
  1011. case 'synonyms':
  1012. return 'SELECT synonym_name FROM user_synonyms';
  1013. default:
  1014. return null;
  1015. }
  1016. }
  1017. // }}}
  1018. }
  1019. /*
  1020. * Local variables:
  1021. * tab-width: 4
  1022. * c-basic-offset: 4
  1023. * End:
  1024. */
  1025. ?>