oci8.php 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159
  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. /**
  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-2007 The PHP Group
  45. * @license http://www.php.net/license/3_0.txt PHP License 3.0
  46. * @version Release: 1.8.2
  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. unset($this->_prepared_queries[(int)$stmt]);
  419. } else {
  420. return false;
  421. }
  422. return true;
  423. }
  424. // }}}
  425. // {{{ numRows()
  426. /**
  427. * Gets the number of rows in a result set
  428. *
  429. * Only works if the DB_PORTABILITY_NUMROWS portability option
  430. * is turned on.
  431. *
  432. * This method is not meant to be called directly. Use
  433. * DB_result::numRows() instead. It can't be declared "protected"
  434. * because DB_result is a separate object.
  435. *
  436. * @param resource $result PHP's query result resource
  437. *
  438. * @return int the number of rows. A DB_Error object on failure.
  439. *
  440. * @see DB_result::numRows(), DB_common::setOption()
  441. */
  442. function numRows($result)
  443. {
  444. // emulate numRows for Oracle. yuck.
  445. if ($this->options['portability'] & DB_PORTABILITY_NUMROWS &&
  446. $result === $this->last_stmt)
  447. {
  448. $countquery = 'SELECT COUNT(*) FROM ('.$this->last_query.')';
  449. $save_query = $this->last_query;
  450. $save_stmt = $this->last_stmt;
  451. $count = $this->query($countquery);
  452. // Restore the last query and statement.
  453. $this->last_query = $save_query;
  454. $this->last_stmt = $save_stmt;
  455. if (DB::isError($count) ||
  456. DB::isError($row = $count->fetchRow(DB_FETCHMODE_ORDERED)))
  457. {
  458. return $this->raiseError(DB_ERROR_NOT_CAPABLE);
  459. }
  460. return $row[0];
  461. }
  462. return $this->raiseError(DB_ERROR_NOT_CAPABLE);
  463. }
  464. // }}}
  465. // {{{ numCols()
  466. /**
  467. * Gets the number of columns in a result set
  468. *
  469. * This method is not meant to be called directly. Use
  470. * DB_result::numCols() instead. It can't be declared "protected"
  471. * because DB_result is a separate object.
  472. *
  473. * @param resource $result PHP's query result resource
  474. *
  475. * @return int the number of columns. A DB_Error object on failure.
  476. *
  477. * @see DB_result::numCols()
  478. */
  479. function numCols($result)
  480. {
  481. $cols = @OCINumCols($result);
  482. if (!$cols) {
  483. return $this->oci8RaiseError($result);
  484. }
  485. return $cols;
  486. }
  487. // }}}
  488. // {{{ prepare()
  489. /**
  490. * Prepares a query for multiple execution with execute().
  491. *
  492. * With oci8, this is emulated.
  493. *
  494. * prepare() requires a generic query as string like <code>
  495. * INSERT INTO numbers VALUES (?, ?, ?)
  496. * </code>. The <kbd>?</kbd> characters are placeholders.
  497. *
  498. * Three types of placeholders can be used:
  499. * + <kbd>?</kbd> a quoted scalar value, i.e. strings, integers
  500. * + <kbd>!</kbd> value is inserted 'as is'
  501. * + <kbd>&</kbd> requires a file name. The file's contents get
  502. * inserted into the query (i.e. saving binary
  503. * data in a db)
  504. *
  505. * Use backslashes to escape placeholder characters if you don't want
  506. * them to be interpreted as placeholders. Example: <code>
  507. * "UPDATE foo SET col=? WHERE col='over \& under'"
  508. * </code>
  509. *
  510. * @param string $query the query to be prepared
  511. *
  512. * @return mixed DB statement resource on success. DB_Error on failure.
  513. *
  514. * @see DB_oci8::execute()
  515. */
  516. function prepare($query)
  517. {
  518. $tokens = preg_split('/((?<!\\\)[&?!])/', $query, -1,
  519. PREG_SPLIT_DELIM_CAPTURE);
  520. $binds = count($tokens) - 1;
  521. $token = 0;
  522. $types = array();
  523. $newquery = '';
  524. foreach ($tokens as $key => $val) {
  525. switch ($val) {
  526. case '?':
  527. $types[$token++] = DB_PARAM_SCALAR;
  528. unset($tokens[$key]);
  529. break;
  530. case '&':
  531. $types[$token++] = DB_PARAM_OPAQUE;
  532. unset($tokens[$key]);
  533. break;
  534. case '!':
  535. $types[$token++] = DB_PARAM_MISC;
  536. unset($tokens[$key]);
  537. break;
  538. default:
  539. $tokens[$key] = preg_replace('/\\\([&?!])/', "\\1", $val);
  540. if ($key != $binds) {
  541. $newquery .= $tokens[$key] . ':bind' . $token;
  542. } else {
  543. $newquery .= $tokens[$key];
  544. }
  545. }
  546. }
  547. $this->last_query = $query;
  548. $newquery = $this->modifyQuery($newquery);
  549. if (!$stmt = @OCIParse($this->connection, $newquery)) {
  550. return $this->oci8RaiseError();
  551. }
  552. $this->prepare_types[(int)$stmt] = $types;
  553. $this->manip_query[(int)$stmt] = DB::isManip($query);
  554. $this->_prepared_queries[(int)$stmt] = $newquery;
  555. return $stmt;
  556. }
  557. // }}}
  558. // {{{ execute()
  559. /**
  560. * Executes a DB statement prepared with prepare().
  561. *
  562. * To determine how many rows of a result set get buffered using
  563. * ocisetprefetch(), see the "result_buffering" option in setOptions().
  564. * This option was added in Release 1.7.0.
  565. *
  566. * @param resource $stmt a DB statement resource returned from prepare()
  567. * @param mixed $data array, string or numeric data to be used in
  568. * execution of the statement. Quantity of items
  569. * passed must match quantity of placeholders in
  570. * query: meaning 1 for non-array items or the
  571. * quantity of elements in the array.
  572. *
  573. * @return mixed returns an oic8 result resource for successful SELECT
  574. * queries, DB_OK for other successful queries.
  575. * A DB error object is returned on failure.
  576. *
  577. * @see DB_oci8::prepare()
  578. */
  579. function &execute($stmt, $data = array())
  580. {
  581. $data = (array)$data;
  582. $this->last_parameters = $data;
  583. $this->last_query = $this->_prepared_queries[(int)$stmt];
  584. $this->_data = $data;
  585. $types = $this->prepare_types[(int)$stmt];
  586. if (count($types) != count($data)) {
  587. $tmp = $this->raiseError(DB_ERROR_MISMATCH);
  588. return $tmp;
  589. }
  590. $i = 0;
  591. foreach ($data as $key => $value) {
  592. if ($types[$i] == DB_PARAM_MISC) {
  593. /*
  594. * Oracle doesn't seem to have the ability to pass a
  595. * parameter along unchanged, so strip off quotes from start
  596. * and end, plus turn two single quotes to one single quote,
  597. * in order to avoid the quotes getting escaped by
  598. * Oracle and ending up in the database.
  599. */
  600. $data[$key] = preg_replace("/^'(.*)'$/", "\\1", $data[$key]);
  601. $data[$key] = str_replace("''", "'", $data[$key]);
  602. } elseif ($types[$i] == DB_PARAM_OPAQUE) {
  603. $fp = @fopen($data[$key], 'rb');
  604. if (!$fp) {
  605. $tmp = $this->raiseError(DB_ERROR_ACCESS_VIOLATION);
  606. return $tmp;
  607. }
  608. $data[$key] = fread($fp, filesize($data[$key]));
  609. fclose($fp);
  610. } elseif ($types[$i] == DB_PARAM_SCALAR) {
  611. // Floats have to be converted to a locale-neutral
  612. // representation.
  613. if (is_float($data[$key])) {
  614. $data[$key] = $this->quoteFloat($data[$key]);
  615. }
  616. }
  617. if (!@OCIBindByName($stmt, ':bind' . $i, $data[$key], -1)) {
  618. $tmp = $this->oci8RaiseError($stmt);
  619. return $tmp;
  620. }
  621. $this->last_query = preg_replace("/:bind$i(?!\d)/",
  622. $this->quoteSmart($data[$key]), $this->last_query, 1);
  623. $i++;
  624. }
  625. if ($this->autocommit) {
  626. $success = @OCIExecute($stmt, OCI_COMMIT_ON_SUCCESS);
  627. } else {
  628. $success = @OCIExecute($stmt, OCI_DEFAULT);
  629. }
  630. if (!$success) {
  631. $tmp = $this->oci8RaiseError($stmt);
  632. return $tmp;
  633. }
  634. $this->last_stmt = $stmt;
  635. if ($this->manip_query[(int)$stmt] || $this->_next_query_manip) {
  636. $this->_last_query_manip = true;
  637. $this->_next_query_manip = false;
  638. $tmp = DB_OK;
  639. } else {
  640. $this->_last_query_manip = false;
  641. @ocisetprefetch($stmt, $this->options['result_buffering']);
  642. $tmp = new DB_result($this, $stmt);
  643. }
  644. return $tmp;
  645. }
  646. // }}}
  647. // {{{ autoCommit()
  648. /**
  649. * Enables or disables automatic commits
  650. *
  651. * @param bool $onoff true turns it on, false turns it off
  652. *
  653. * @return int DB_OK on success. A DB_Error object if the driver
  654. * doesn't support auto-committing transactions.
  655. */
  656. function autoCommit($onoff = false)
  657. {
  658. $this->autocommit = (bool)$onoff;;
  659. return DB_OK;
  660. }
  661. // }}}
  662. // {{{ commit()
  663. /**
  664. * Commits the current transaction
  665. *
  666. * @return int DB_OK on success. A DB_Error object on failure.
  667. */
  668. function commit()
  669. {
  670. $result = @OCICommit($this->connection);
  671. if (!$result) {
  672. return $this->oci8RaiseError();
  673. }
  674. return DB_OK;
  675. }
  676. // }}}
  677. // {{{ rollback()
  678. /**
  679. * Reverts the current transaction
  680. *
  681. * @return int DB_OK on success. A DB_Error object on failure.
  682. */
  683. function rollback()
  684. {
  685. $result = @OCIRollback($this->connection);
  686. if (!$result) {
  687. return $this->oci8RaiseError();
  688. }
  689. return DB_OK;
  690. }
  691. // }}}
  692. // {{{ affectedRows()
  693. /**
  694. * Determines the number of rows affected by a data maniuplation query
  695. *
  696. * 0 is returned for queries that don't manipulate data.
  697. *
  698. * @return int the number of rows. A DB_Error object on failure.
  699. */
  700. function affectedRows()
  701. {
  702. if ($this->last_stmt === false) {
  703. return $this->oci8RaiseError();
  704. }
  705. $result = @OCIRowCount($this->last_stmt);
  706. if ($result === false) {
  707. return $this->oci8RaiseError($this->last_stmt);
  708. }
  709. return $result;
  710. }
  711. // }}}
  712. // {{{ modifyQuery()
  713. /**
  714. * Changes a query string for various DBMS specific reasons
  715. *
  716. * "SELECT 2+2" must be "SELECT 2+2 FROM dual" in Oracle.
  717. *
  718. * @param string $query the query string to modify
  719. *
  720. * @return string the modified query string
  721. *
  722. * @access protected
  723. */
  724. function modifyQuery($query)
  725. {
  726. if (preg_match('/^\s*SELECT/i', $query) &&
  727. !preg_match('/\sFROM\s/i', $query)) {
  728. $query .= ' FROM dual';
  729. }
  730. return $query;
  731. }
  732. // }}}
  733. // {{{ modifyLimitQuery()
  734. /**
  735. * Adds LIMIT clauses to a query string according to current DBMS standards
  736. *
  737. * @param string $query the query to modify
  738. * @param int $from the row to start to fetching (0 = the first row)
  739. * @param int $count the numbers of rows to fetch
  740. * @param mixed $params array, string or numeric data to be used in
  741. * execution of the statement. Quantity of items
  742. * passed must match quantity of placeholders in
  743. * query: meaning 1 placeholder for non-array
  744. * parameters or 1 placeholder per array element.
  745. *
  746. * @return string the query string with LIMIT clauses added
  747. *
  748. * @access protected
  749. */
  750. function modifyLimitQuery($query, $from, $count, $params = array())
  751. {
  752. // Let Oracle return the name of the columns instead of
  753. // coding a "home" SQL parser
  754. if (count($params)) {
  755. $result = $this->prepare("SELECT * FROM ($query) "
  756. . 'WHERE NULL = NULL');
  757. $tmp = $this->execute($result, $params);
  758. } else {
  759. $q_fields = "SELECT * FROM ($query) WHERE NULL = NULL";
  760. if (!$result = @OCIParse($this->connection, $q_fields)) {
  761. $this->last_query = $q_fields;
  762. return $this->oci8RaiseError();
  763. }
  764. if (!@OCIExecute($result, OCI_DEFAULT)) {
  765. $this->last_query = $q_fields;
  766. return $this->oci8RaiseError($result);
  767. }
  768. }
  769. $ncols = OCINumCols($result);
  770. $cols = array();
  771. for ( $i = 1; $i <= $ncols; $i++ ) {
  772. $cols[] = '"' . OCIColumnName($result, $i) . '"';
  773. }
  774. $fields = implode(', ', $cols);
  775. // XXX Test that (tip by John Lim)
  776. //if (preg_match('/^\s*SELECT\s+/is', $query, $match)) {
  777. // // Introduce the FIRST_ROWS Oracle query optimizer
  778. // $query = substr($query, strlen($match[0]), strlen($query));
  779. // $query = "SELECT /* +FIRST_ROWS */ " . $query;
  780. //}
  781. // Construct the query
  782. // more at: http://marc.theaimsgroup.com/?l=php-db&m=99831958101212&w=2
  783. // Perhaps this could be optimized with the use of Unions
  784. $query = "SELECT $fields FROM".
  785. " (SELECT rownum as linenum, $fields FROM".
  786. " ($query)".
  787. ' WHERE rownum <= '. ($from + $count) .
  788. ') WHERE linenum >= ' . ++$from;
  789. return $query;
  790. }
  791. // }}}
  792. // {{{ nextId()
  793. /**
  794. * Returns the next free id in a sequence
  795. *
  796. * @param string $seq_name name of the sequence
  797. * @param boolean $ondemand when true, the seqence is automatically
  798. * created if it does not exist
  799. *
  800. * @return int the next id number in the sequence.
  801. * A DB_Error object on failure.
  802. *
  803. * @see DB_common::nextID(), DB_common::getSequenceName(),
  804. * DB_oci8::createSequence(), DB_oci8::dropSequence()
  805. */
  806. function nextId($seq_name, $ondemand = true)
  807. {
  808. $seqname = $this->getSequenceName($seq_name);
  809. $repeat = 0;
  810. do {
  811. $this->expectError(DB_ERROR_NOSUCHTABLE);
  812. $result = $this->query("SELECT ${seqname}.nextval FROM dual");
  813. $this->popExpect();
  814. if ($ondemand && DB::isError($result) &&
  815. $result->getCode() == DB_ERROR_NOSUCHTABLE) {
  816. $repeat = 1;
  817. $result = $this->createSequence($seq_name);
  818. if (DB::isError($result)) {
  819. return $this->raiseError($result);
  820. }
  821. } else {
  822. $repeat = 0;
  823. }
  824. } while ($repeat);
  825. if (DB::isError($result)) {
  826. return $this->raiseError($result);
  827. }
  828. $arr = $result->fetchRow(DB_FETCHMODE_ORDERED);
  829. return $arr[0];
  830. }
  831. /**
  832. * Creates a new sequence
  833. *
  834. * @param string $seq_name name of the new sequence
  835. *
  836. * @return int DB_OK on success. A DB_Error object on failure.
  837. *
  838. * @see DB_common::createSequence(), DB_common::getSequenceName(),
  839. * DB_oci8::nextID(), DB_oci8::dropSequence()
  840. */
  841. function createSequence($seq_name)
  842. {
  843. return $this->query('CREATE SEQUENCE '
  844. . $this->getSequenceName($seq_name));
  845. }
  846. // }}}
  847. // {{{ dropSequence()
  848. /**
  849. * Deletes a sequence
  850. *
  851. * @param string $seq_name name of the sequence to be deleted
  852. *
  853. * @return int DB_OK on success. A DB_Error object on failure.
  854. *
  855. * @see DB_common::dropSequence(), DB_common::getSequenceName(),
  856. * DB_oci8::nextID(), DB_oci8::createSequence()
  857. */
  858. function dropSequence($seq_name)
  859. {
  860. return $this->query('DROP SEQUENCE '
  861. . $this->getSequenceName($seq_name));
  862. }
  863. // }}}
  864. // {{{ oci8RaiseError()
  865. /**
  866. * Produces a DB_Error object regarding the current problem
  867. *
  868. * @param int $errno if the error is being manually raised pass a
  869. * DB_ERROR* constant here. If this isn't passed
  870. * the error information gathered from the DBMS.
  871. *
  872. * @return object the DB_Error object
  873. *
  874. * @see DB_common::raiseError(),
  875. * DB_oci8::errorNative(), DB_oci8::errorCode()
  876. */
  877. function oci8RaiseError($errno = null)
  878. {
  879. if ($errno === null) {
  880. $error = @OCIError($this->connection);
  881. return $this->raiseError($this->errorCode($error['code']),
  882. null, null, null, $error['message']);
  883. } elseif (is_resource($errno)) {
  884. $error = @OCIError($errno);
  885. return $this->raiseError($this->errorCode($error['code']),
  886. null, null, null, $error['message']);
  887. }
  888. return $this->raiseError($this->errorCode($errno));
  889. }
  890. // }}}
  891. // {{{ errorNative()
  892. /**
  893. * Gets the DBMS' native error code produced by the last query
  894. *
  895. * @return int the DBMS' error code. FALSE if the code could not be
  896. * determined
  897. */
  898. function errorNative()
  899. {
  900. if (is_resource($this->last_stmt)) {
  901. $error = @OCIError($this->last_stmt);
  902. } else {
  903. $error = @OCIError($this->connection);
  904. }
  905. if (is_array($error)) {
  906. return $error['code'];
  907. }
  908. return false;
  909. }
  910. // }}}
  911. // {{{ tableInfo()
  912. /**
  913. * Returns information about a table or a result set
  914. *
  915. * NOTE: only supports 'table' and 'flags' if <var>$result</var>
  916. * is a table name.
  917. *
  918. * NOTE: flags won't contain index information.
  919. *
  920. * @param object|string $result DB_result object from a query or a
  921. * string containing the name of a table.
  922. * While this also accepts a query result
  923. * resource identifier, this behavior is
  924. * deprecated.
  925. * @param int $mode a valid tableInfo mode
  926. *
  927. * @return array an associative array with the information requested.
  928. * A DB_Error object on failure.
  929. *
  930. * @see DB_common::tableInfo()
  931. */
  932. function tableInfo($result, $mode = null)
  933. {
  934. if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE) {
  935. $case_func = 'strtolower';
  936. } else {
  937. $case_func = 'strval';
  938. }
  939. $res = array();
  940. if (is_string($result)) {
  941. /*
  942. * Probably received a table name.
  943. * Create a result resource identifier.
  944. */
  945. $result = strtoupper($result);
  946. $q_fields = 'SELECT column_name, data_type, data_length, '
  947. . 'nullable '
  948. . 'FROM user_tab_columns '
  949. . "WHERE table_name='$result' ORDER BY column_id";
  950. $this->last_query = $q_fields;
  951. if (!$stmt = @OCIParse($this->connection, $q_fields)) {
  952. return $this->oci8RaiseError(DB_ERROR_NEED_MORE_DATA);
  953. }
  954. if (!@OCIExecute($stmt, OCI_DEFAULT)) {
  955. return $this->oci8RaiseError($stmt);
  956. }
  957. $i = 0;
  958. while (@OCIFetch($stmt)) {
  959. $res[$i] = array(
  960. 'table' => $case_func($result),
  961. 'name' => $case_func(@OCIResult($stmt, 1)),
  962. 'type' => @OCIResult($stmt, 2),
  963. 'len' => @OCIResult($stmt, 3),
  964. 'flags' => (@OCIResult($stmt, 4) == 'N') ? 'not_null' : '',
  965. );
  966. if ($mode & DB_TABLEINFO_ORDER) {
  967. $res['order'][$res[$i]['name']] = $i;
  968. }
  969. if ($mode & DB_TABLEINFO_ORDERTABLE) {
  970. $res['ordertable'][$res[$i]['table']][$res[$i]['name']] = $i;
  971. }
  972. $i++;
  973. }
  974. if ($mode) {
  975. $res['num_fields'] = $i;
  976. }
  977. @OCIFreeStatement($stmt);
  978. } else {
  979. if (isset($result->result)) {
  980. /*
  981. * Probably received a result object.
  982. * Extract the result resource identifier.
  983. */
  984. $result = $result->result;
  985. }
  986. $res = array();
  987. if ($result === $this->last_stmt) {
  988. $count = @OCINumCols($result);
  989. if ($mode) {
  990. $res['num_fields'] = $count;
  991. }
  992. for ($i = 0; $i < $count; $i++) {
  993. $res[$i] = array(
  994. 'table' => '',
  995. 'name' => $case_func(@OCIColumnName($result, $i+1)),
  996. 'type' => @OCIColumnType($result, $i+1),
  997. 'len' => @OCIColumnSize($result, $i+1),
  998. 'flags' => '',
  999. );
  1000. if ($mode & DB_TABLEINFO_ORDER) {
  1001. $res['order'][$res[$i]['name']] = $i;
  1002. }
  1003. if ($mode & DB_TABLEINFO_ORDERTABLE) {
  1004. $res['ordertable'][$res[$i]['table']][$res[$i]['name']] = $i;
  1005. }
  1006. }
  1007. } else {
  1008. return $this->raiseError(DB_ERROR_NOT_CAPABLE);
  1009. }
  1010. }
  1011. return $res;
  1012. }
  1013. // }}}
  1014. // {{{ getSpecialQuery()
  1015. /**
  1016. * Obtains the query string needed for listing a given type of objects
  1017. *
  1018. * @param string $type the kind of objects you want to retrieve
  1019. *
  1020. * @return string the SQL query string or null if the driver doesn't
  1021. * support the object type requested
  1022. *
  1023. * @access protected
  1024. * @see DB_common::getListOf()
  1025. */
  1026. function getSpecialQuery($type)
  1027. {
  1028. switch ($type) {
  1029. case 'tables':
  1030. return 'SELECT table_name FROM user_tables';
  1031. case 'synonyms':
  1032. return 'SELECT synonym_name FROM user_synonyms';
  1033. case 'views':
  1034. return 'SELECT view_name FROM user_views';
  1035. default:
  1036. return null;
  1037. }
  1038. }
  1039. // }}}
  1040. // {{{ quoteFloat()
  1041. /**
  1042. * Formats a float value for use within a query in a locale-independent
  1043. * manner.
  1044. *
  1045. * @param float the float value to be quoted.
  1046. * @return string the quoted string.
  1047. * @see DB_common::quoteSmart()
  1048. * @since Method available since release 1.7.8.
  1049. */
  1050. function quoteFloat($float) {
  1051. return $this->escapeSimple(str_replace(',', '.', strval(floatval($float))));
  1052. }
  1053. // }}}
  1054. }
  1055. /*
  1056. * Local variables:
  1057. * tab-width: 4
  1058. * c-basic-offset: 4
  1059. * End:
  1060. */
  1061. ?>