oci8.php 36 KB

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