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