PageRenderTime 48ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/external_lib/DB/oci8.php

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