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

/include/adodb/drivers/adodb-oci8.inc.php

https://github.com/radicaldesigns/amp
PHP | 1502 lines | 1230 code | 111 blank | 161 comment | 121 complexity | 00c46d6b00c380746fca8caca6cc82f3 MD5 | raw file
Possible License(s): LGPL-2.1, GPL-2.0, BSD-3-Clause, LGPL-2.0, CC-BY-SA-3.0, AGPL-1.0
  1. <?php
  2. /*
  3. version V4.92a 29 Aug 2006 (c) 2000-2006 John Lim. All rights reserved.
  4. Released under both BSD license and Lesser GPL library license.
  5. Whenever there is any discrepancy between the two licenses,
  6. the BSD license will take precedence.
  7. Latest version is available at http://adodb.sourceforge.net
  8. Code contributed by George Fourlanos <fou@infomap.gr>
  9. 13 Nov 2000 jlim - removed all ora_* references.
  10. */
  11. // security - hide paths
  12. if (!defined('ADODB_DIR')) die();
  13. /*
  14. NLS_Date_Format
  15. Allows you to use a date format other than the Oracle Lite default. When a literal
  16. character string appears where a date value is expected, the Oracle Lite database
  17. tests the string to see if it matches the formats of Oracle, SQL-92, or the value
  18. specified for this parameter in the POLITE.INI file. Setting this parameter also
  19. defines the default format used in the TO_CHAR or TO_DATE functions when no
  20. other format string is supplied.
  21. For Oracle the default is dd-mon-yy or dd-mon-yyyy, and for SQL-92 the default is
  22. yy-mm-dd or yyyy-mm-dd.
  23. Using 'RR' in the format forces two-digit years less than or equal to 49 to be
  24. interpreted as years in the 21st century (2000–2049), and years over 50 as years in
  25. the 20th century (1950–1999). Setting the RR format as the default for all two-digit
  26. year entries allows you to become year-2000 compliant. For example:
  27. NLS_DATE_FORMAT='RR-MM-DD'
  28. You can also modify the date format using the ALTER SESSION command.
  29. */
  30. # define the LOB descriptor type for the given type
  31. # returns false if no LOB descriptor
  32. function oci_lob_desc($type) {
  33. switch ($type) {
  34. case OCI_B_BFILE: $result = OCI_D_FILE; break;
  35. case OCI_B_CFILEE: $result = OCI_D_FILE; break;
  36. case OCI_B_CLOB: $result = OCI_D_LOB; break;
  37. case OCI_B_BLOB: $result = OCI_D_LOB; break;
  38. case OCI_B_ROWID: $result = OCI_D_ROWID; break;
  39. default: $result = false; break;
  40. }
  41. return $result;
  42. }
  43. class ADODB_oci8 extends ADOConnection {
  44. var $databaseType = 'oci8';
  45. var $dataProvider = 'oci8';
  46. var $replaceQuote = "''"; // string to use to replace quotes
  47. var $concat_operator='||';
  48. var $sysDate = "TRUNC(SYSDATE)";
  49. var $sysTimeStamp = 'SYSDATE';
  50. var $metaDatabasesSQL = "SELECT USERNAME FROM ALL_USERS WHERE USERNAME NOT IN ('SYS','SYSTEM','DBSNMP','OUTLN') ORDER BY 1";
  51. var $_stmt;
  52. var $_commit = OCI_COMMIT_ON_SUCCESS;
  53. var $_initdate = true; // init date to YYYY-MM-DD
  54. var $metaTablesSQL = "select table_name,table_type from cat where table_type in ('TABLE','VIEW')";
  55. var $metaColumnsSQL = "select cname,coltype,width, SCALE, PRECISION, NULLS, DEFAULTVAL from col where tname='%s' order by colno"; //changed by smondino@users.sourceforge. net
  56. var $_bindInputArray = true;
  57. var $hasGenID = true;
  58. var $_genIDSQL = "SELECT (%s.nextval) FROM DUAL";
  59. var $_genSeqSQL = "CREATE SEQUENCE %s START WITH %s";
  60. var $_dropSeqSQL = "DROP SEQUENCE %s";
  61. var $hasAffectedRows = true;
  62. var $random = "abs(mod(DBMS_RANDOM.RANDOM,10000001)/10000000)";
  63. var $noNullStrings = false;
  64. var $connectSID = false;
  65. var $_bind = false;
  66. var $_nestedSQL = true;
  67. var $_hasOCIFetchStatement = false;
  68. var $_getarray = false; // currently not working
  69. var $leftOuter = ''; // oracle wierdness, $col = $value (+) for LEFT OUTER, $col (+)= $value for RIGHT OUTER
  70. var $session_sharing_force_blob = false; // alter session on updateblob if set to true
  71. var $firstrows = true; // enable first rows optimization on SelectLimit()
  72. var $selectOffsetAlg1 = 100; // when to use 1st algorithm of selectlimit.
  73. var $NLS_DATE_FORMAT = 'YYYY-MM-DD'; // To include time, use 'RRRR-MM-DD HH24:MI:SS'
  74. var $useDBDateFormatForTextInput=false;
  75. var $datetime = false; // MetaType('DATE') returns 'D' (datetime==false) or 'T' (datetime == true)
  76. var $_refLOBs = array();
  77. // var $ansiOuter = true; // if oracle9
  78. function ADODB_oci8()
  79. {
  80. $this->_hasOCIFetchStatement = ADODB_PHPVER >= 0x4200;
  81. if (defined('ADODB_EXTENSION')) $this->rsPrefix .= 'ext_';
  82. }
  83. /* Function &MetaColumns($table) added by smondino@users.sourceforge.net*/
  84. function &MetaColumns($table)
  85. {
  86. global $ADODB_FETCH_MODE;
  87. $false = false;
  88. $save = $ADODB_FETCH_MODE;
  89. $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
  90. if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);
  91. $rs = $this->Execute(sprintf($this->metaColumnsSQL,strtoupper($table)));
  92. if (isset($savem)) $this->SetFetchMode($savem);
  93. $ADODB_FETCH_MODE = $save;
  94. if (!$rs) {
  95. return $false;
  96. }
  97. $retarr = array();
  98. while (!$rs->EOF) { //print_r($rs->fields);
  99. $fld = new ADOFieldObject();
  100. $fld->name = $rs->fields[0];
  101. $fld->type = $rs->fields[1];
  102. $fld->max_length = $rs->fields[2];
  103. $fld->scale = $rs->fields[3];
  104. if ($rs->fields[1] == 'NUMBER' && $rs->fields[3] == 0) {
  105. $fld->type ='INT';
  106. $fld->max_length = $rs->fields[4];
  107. }
  108. $fld->not_null = (strncmp($rs->fields[5], 'NOT',3) === 0);
  109. $fld->binary = (strpos($fld->type,'BLOB') !== false);
  110. $fld->default_value = $rs->fields[6];
  111. if ($ADODB_FETCH_MODE == ADODB_FETCH_NUM) $retarr[] = $fld;
  112. else $retarr[strtoupper($fld->name)] = $fld;
  113. $rs->MoveNext();
  114. }
  115. $rs->Close();
  116. if (empty($retarr))
  117. return $false;
  118. else
  119. return $retarr;
  120. }
  121. function Time()
  122. {
  123. $rs = $this->Execute("select TO_CHAR($this->sysTimeStamp,'YYYY-MM-DD HH24:MI:SS') from dual");
  124. if ($rs && !$rs->EOF) return $this->UnixTimeStamp(reset($rs->fields));
  125. return false;
  126. }
  127. /*
  128. Multiple modes of connection are supported:
  129. a. Local Database
  130. $conn->Connect(false,'scott','tiger');
  131. b. From tnsnames.ora
  132. $conn->Connect(false,'scott','tiger',$tnsname);
  133. $conn->Connect($tnsname,'scott','tiger');
  134. c. Server + service name
  135. $conn->Connect($serveraddress,'scott,'tiger',$service_name);
  136. d. Server + SID
  137. $conn->connectSID = true;
  138. $conn->Connect($serveraddress,'scott,'tiger',$SID);
  139. Example TNSName:
  140. ---------------
  141. NATSOFT.DOMAIN =
  142. (DESCRIPTION =
  143. (ADDRESS_LIST =
  144. (ADDRESS = (PROTOCOL = TCP)(HOST = kermit)(PORT = 1523))
  145. )
  146. (CONNECT_DATA =
  147. (SERVICE_NAME = natsoft.domain)
  148. )
  149. )
  150. There are 3 connection modes, 0 = non-persistent, 1 = persistent, 2 = force new connection
  151. */
  152. function _connect($argHostname, $argUsername, $argPassword, $argDatabasename,$mode=0)
  153. {
  154. if (!function_exists('OCIPLogon')) return null;
  155. $this->_errorMsg = false;
  156. $this->_errorCode = false;
  157. if($argHostname) { // added by Jorma Tuomainen <jorma.tuomainen@ppoy.fi>
  158. if (empty($argDatabasename)) $argDatabasename = $argHostname;
  159. else {
  160. if(strpos($argHostname,":")) {
  161. $argHostinfo=explode(":",$argHostname);
  162. $argHostname=$argHostinfo[0];
  163. $argHostport=$argHostinfo[1];
  164. } else {
  165. $argHostport = empty($this->port)? "1521" : $this->port;
  166. }
  167. if ($this->connectSID) {
  168. $argDatabasename="(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=".$argHostname
  169. .")(PORT=$argHostport))(CONNECT_DATA=(SID=$argDatabasename)))";
  170. } else
  171. $argDatabasename="(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=".$argHostname
  172. .")(PORT=$argHostport))(CONNECT_DATA=(SERVICE_NAME=$argDatabasename)))";
  173. }
  174. }
  175. //if ($argHostname) print "<p>Connect: 1st argument should be left blank for $this->databaseType</p>";
  176. if ($mode==1) {
  177. $this->_connectionID = ($this->charSet) ?
  178. OCIPLogon($argUsername,$argPassword, $argDatabasename)
  179. :
  180. OCIPLogon($argUsername,$argPassword, $argDatabasename, $this->charSet)
  181. ;
  182. if ($this->_connectionID && $this->autoRollback) OCIrollback($this->_connectionID);
  183. } else if ($mode==2) {
  184. $this->_connectionID = ($this->charSet) ?
  185. OCINLogon($argUsername,$argPassword, $argDatabasename)
  186. :
  187. OCINLogon($argUsername,$argPassword, $argDatabasename, $this->charSet);
  188. } else {
  189. $this->_connectionID = ($this->charSet) ?
  190. OCILogon($argUsername,$argPassword, $argDatabasename)
  191. :
  192. OCILogon($argUsername,$argPassword, $argDatabasename,$this->charSet);
  193. }
  194. if (!$this->_connectionID) return false;
  195. if ($this->_initdate) {
  196. $this->Execute("ALTER SESSION SET NLS_DATE_FORMAT='".$this->NLS_DATE_FORMAT."'");
  197. }
  198. // looks like:
  199. // Oracle8i Enterprise Edition Release 8.1.7.0.0 - Production With the Partitioning option JServer Release 8.1.7.0.0 - Production
  200. // $vers = OCIServerVersion($this->_connectionID);
  201. // if (strpos($vers,'8i') !== false) $this->ansiOuter = true;
  202. return true;
  203. }
  204. function ServerInfo()
  205. {
  206. $arr['compat'] = $this->GetOne('select value from sys.database_compatible_level');
  207. $arr['description'] = @OCIServerVersion($this->_connectionID);
  208. $arr['version'] = ADOConnection::_findvers($arr['description']);
  209. return $arr;
  210. }
  211. // returns true or false
  212. function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename)
  213. {
  214. return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabasename,1);
  215. }
  216. // returns true or false
  217. function _nconnect($argHostname, $argUsername, $argPassword, $argDatabasename)
  218. {
  219. return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabasename,2);
  220. }
  221. function _affectedrows()
  222. {
  223. if (is_resource($this->_stmt)) return @OCIRowCount($this->_stmt);
  224. return 0;
  225. }
  226. function IfNull( $field, $ifNull )
  227. {
  228. return " NVL($field, $ifNull) "; // if Oracle
  229. }
  230. // format and return date string in database date format
  231. function DBDate($d)
  232. {
  233. if (empty($d) && $d !== 0) return 'null';
  234. if (is_string($d)) $d = ADORecordSet::UnixDate($d);
  235. return "TO_DATE(".adodb_date($this->fmtDate,$d).",'".$this->NLS_DATE_FORMAT."')";
  236. }
  237. function BindDate($d)
  238. {
  239. $d = ADOConnection::DBDate($d);
  240. if (strncmp($d,"'",1)) return $d;
  241. return substr($d,1,strlen($d)-2);
  242. }
  243. function BindTimeStamp($d)
  244. {
  245. $d = ADOConnection::DBTimeStamp($d);
  246. if (strncmp($d,"'",1)) return $d;
  247. return substr($d,1,strlen($d)-2);
  248. }
  249. // format and return date string in database timestamp format
  250. function DBTimeStamp($ts)
  251. {
  252. if (empty($ts) && $ts !== 0) return 'null';
  253. if (is_string($ts)) $ts = ADORecordSet::UnixTimeStamp($ts);
  254. return 'TO_DATE('.adodb_date($this->fmtTimeStamp,$ts).",'RRRR-MM-DD, HH:MI:SS AM')";
  255. }
  256. function RowLock($tables,$where,$flds='1 as ignore')
  257. {
  258. if ($this->autoCommit) $this->BeginTrans();
  259. return $this->GetOne("select $flds from $tables where $where for update");
  260. }
  261. function &MetaTables($ttype=false,$showSchema=false,$mask=false)
  262. {
  263. if ($mask) {
  264. $save = $this->metaTablesSQL;
  265. $mask = $this->qstr(strtoupper($mask));
  266. $this->metaTablesSQL .= " AND upper(table_name) like $mask";
  267. }
  268. $ret = ADOConnection::MetaTables($ttype,$showSchema);
  269. if ($mask) {
  270. $this->metaTablesSQL = $save;
  271. }
  272. return $ret;
  273. }
  274. // Mark Newnham
  275. function &MetaIndexes ($table, $primary = FALSE, $owner=false)
  276. {
  277. // save old fetch mode
  278. global $ADODB_FETCH_MODE;
  279. $save = $ADODB_FETCH_MODE;
  280. $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
  281. if ($this->fetchMode !== FALSE) {
  282. $savem = $this->SetFetchMode(FALSE);
  283. }
  284. // get index details
  285. $table = strtoupper($table);
  286. // get Primary index
  287. $primary_key = '';
  288. $false = false;
  289. $rs = $this->Execute(sprintf("SELECT * FROM ALL_CONSTRAINTS WHERE UPPER(TABLE_NAME)='%s' AND CONSTRAINT_TYPE='P'",$table));
  290. if ($row = $rs->FetchRow())
  291. $primary_key = $row[1]; //constraint_name
  292. if ($primary==TRUE && $primary_key=='') {
  293. if (isset($savem))
  294. $this->SetFetchMode($savem);
  295. $ADODB_FETCH_MODE = $save;
  296. return $false; //There is no primary key
  297. }
  298. $rs = $this->Execute(sprintf("SELECT ALL_INDEXES.INDEX_NAME, ALL_INDEXES.UNIQUENESS, ALL_IND_COLUMNS.COLUMN_POSITION, ALL_IND_COLUMNS.COLUMN_NAME FROM ALL_INDEXES,ALL_IND_COLUMNS WHERE UPPER(ALL_INDEXES.TABLE_NAME)='%s' AND ALL_IND_COLUMNS.INDEX_NAME=ALL_INDEXES.INDEX_NAME",$table));
  299. if (!is_object($rs)) {
  300. if (isset($savem))
  301. $this->SetFetchMode($savem);
  302. $ADODB_FETCH_MODE = $save;
  303. return $false;
  304. }
  305. $indexes = array ();
  306. // parse index data into array
  307. while ($row = $rs->FetchRow()) {
  308. if ($primary && $row[0] != $primary_key) continue;
  309. if (!isset($indexes[$row[0]])) {
  310. $indexes[$row[0]] = array(
  311. 'unique' => ($row[1] == 'UNIQUE'),
  312. 'columns' => array()
  313. );
  314. }
  315. $indexes[$row[0]]['columns'][$row[2] - 1] = $row[3];
  316. }
  317. // sort columns by order in the index
  318. foreach ( array_keys ($indexes) as $index ) {
  319. ksort ($indexes[$index]['columns']);
  320. }
  321. if (isset($savem)) {
  322. $this->SetFetchMode($savem);
  323. $ADODB_FETCH_MODE = $save;
  324. }
  325. return $indexes;
  326. }
  327. function BeginTrans()
  328. {
  329. if ($this->transOff) return true;
  330. $this->transCnt += 1;
  331. $this->autoCommit = false;
  332. $this->_commit = OCI_DEFAULT;
  333. if ($this->_transmode) $this->Execute("SET TRANSACTION ".$this->_transmode);
  334. return true;
  335. }
  336. function CommitTrans($ok=true)
  337. {
  338. if ($this->transOff) return true;
  339. if (!$ok) return $this->RollbackTrans();
  340. if ($this->transCnt) $this->transCnt -= 1;
  341. $ret = OCIcommit($this->_connectionID);
  342. $this->_commit = OCI_COMMIT_ON_SUCCESS;
  343. $this->autoCommit = true;
  344. return $ret;
  345. }
  346. function RollbackTrans()
  347. {
  348. if ($this->transOff) return true;
  349. if ($this->transCnt) $this->transCnt -= 1;
  350. $ret = OCIrollback($this->_connectionID);
  351. $this->_commit = OCI_COMMIT_ON_SUCCESS;
  352. $this->autoCommit = true;
  353. return $ret;
  354. }
  355. function SelectDB($dbName)
  356. {
  357. return false;
  358. }
  359. function ErrorMsg()
  360. {
  361. if ($this->_errorMsg !== false) return $this->_errorMsg;
  362. if (is_resource($this->_stmt)) $arr = @OCIerror($this->_stmt);
  363. if (empty($arr)) {
  364. $arr = @OCIerror($this->_connectionID);
  365. if ($arr === false) $arr = @OCIError();
  366. if ($arr === false) return '';
  367. }
  368. $this->_errorMsg = $arr['message'];
  369. $this->_errorCode = $arr['code'];
  370. return $this->_errorMsg;
  371. }
  372. function ErrorNo()
  373. {
  374. if ($this->_errorCode !== false) return $this->_errorCode;
  375. if (is_resource($this->_stmt)) $arr = @OCIError($this->_stmt);
  376. if (empty($arr)) {
  377. $arr = @OCIError($this->_connectionID);
  378. if ($arr == false) $arr = @OCIError();
  379. if ($arr == false) return '';
  380. }
  381. $this->_errorMsg = $arr['message'];
  382. $this->_errorCode = $arr['code'];
  383. return $arr['code'];
  384. }
  385. // Format date column in sql string given an input format that understands Y M D
  386. function SQLDate($fmt, $col=false)
  387. {
  388. if (!$col) $col = $this->sysTimeStamp;
  389. $s = 'TO_CHAR('.$col.",'";
  390. $len = strlen($fmt);
  391. for ($i=0; $i < $len; $i++) {
  392. $ch = $fmt[$i];
  393. switch($ch) {
  394. case 'Y':
  395. case 'y':
  396. $s .= 'YYYY';
  397. break;
  398. case 'Q':
  399. case 'q':
  400. $s .= 'Q';
  401. break;
  402. case 'M':
  403. $s .= 'Mon';
  404. break;
  405. case 'm':
  406. $s .= 'MM';
  407. break;
  408. case 'D':
  409. case 'd':
  410. $s .= 'DD';
  411. break;
  412. case 'H':
  413. $s.= 'HH24';
  414. break;
  415. case 'h':
  416. $s .= 'HH';
  417. break;
  418. case 'i':
  419. $s .= 'MI';
  420. break;
  421. case 's':
  422. $s .= 'SS';
  423. break;
  424. case 'a':
  425. case 'A':
  426. $s .= 'AM';
  427. break;
  428. case 'w':
  429. $s .= 'D';
  430. break;
  431. case 'l':
  432. $s .= 'DAY';
  433. break;
  434. case 'W':
  435. $s .= 'WW';
  436. break;
  437. default:
  438. // handle escape characters...
  439. if ($ch == '\\') {
  440. $i++;
  441. $ch = substr($fmt,$i,1);
  442. }
  443. if (strpos('-/.:;, ',$ch) !== false) $s .= $ch;
  444. else $s .= '"'.$ch.'"';
  445. }
  446. }
  447. return $s. "')";
  448. }
  449. /*
  450. This algorithm makes use of
  451. a. FIRST_ROWS hint
  452. The FIRST_ROWS hint explicitly chooses the approach to optimize response time,
  453. that is, minimum resource usage to return the first row. Results will be returned
  454. as soon as they are identified.
  455. b. Uses rownum tricks to obtain only the required rows from a given offset.
  456. As this uses complicated sql statements, we only use this if the $offset >= 100.
  457. This idea by Tomas V V Cox.
  458. This implementation does not appear to work with oracle 8.0.5 or earlier. Comment
  459. out this function then, and the slower SelectLimit() in the base class will be used.
  460. */
  461. function &SelectLimit($sql,$nrows=-1,$offset=-1, $inputarr=false,$secs2cache=0)
  462. {
  463. // seems that oracle only supports 1 hint comment in 8i
  464. if ($this->firstrows) {
  465. if (strpos($sql,'/*+') !== false)
  466. $sql = str_replace('/*+ ','/*+FIRST_ROWS ',$sql);
  467. else
  468. $sql = preg_replace('/^[ \t\n]*select/i','SELECT /*+FIRST_ROWS*/',$sql);
  469. }
  470. if ($offset < $this->selectOffsetAlg1) {
  471. if ($nrows > 0) {
  472. if ($offset > 0) $nrows += $offset;
  473. //$inputarr['adodb_rownum'] = $nrows;
  474. if ($this->databaseType == 'oci8po') {
  475. $sql = "select * from (".$sql.") where rownum <= ?";
  476. } else {
  477. $sql = "select * from (".$sql.") where rownum <= :adodb_offset";
  478. }
  479. $inputarr['adodb_offset'] = $nrows;
  480. $nrows = -1;
  481. }
  482. // note that $nrows = 0 still has to work ==> no rows returned
  483. $rs = ADOConnection::SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache);
  484. return $rs;
  485. } else {
  486. // Algorithm by Tomas V V Cox, from PEAR DB oci8.php
  487. // Let Oracle return the name of the columns
  488. $q_fields = "SELECT * FROM (".$sql.") WHERE NULL = NULL";
  489. $false = false;
  490. if (! $stmt_arr = $this->Prepare($q_fields)) {
  491. return $false;
  492. }
  493. $stmt = $stmt_arr[1];
  494. if (is_array($inputarr)) {
  495. foreach($inputarr as $k => $v) {
  496. if (is_array($v)) {
  497. if (sizeof($v) == 2) // suggested by g.giunta@libero.
  498. OCIBindByName($stmt,":$k",$inputarr[$k][0],$v[1]);
  499. else
  500. OCIBindByName($stmt,":$k",$inputarr[$k][0],$v[1],$v[2]);
  501. } else {
  502. $len = -1;
  503. if ($v === ' ') $len = 1;
  504. if (isset($bindarr)) { // is prepared sql, so no need to ocibindbyname again
  505. $bindarr[$k] = $v;
  506. } else { // dynamic sql, so rebind every time
  507. OCIBindByName($stmt,":$k",$inputarr[$k],$len);
  508. }
  509. }
  510. }
  511. }
  512. if (!OCIExecute($stmt, OCI_DEFAULT)) {
  513. OCIFreeStatement($stmt);
  514. return $false;
  515. }
  516. $ncols = OCINumCols($stmt);
  517. for ( $i = 1; $i <= $ncols; $i++ ) {
  518. $cols[] = '"'.OCIColumnName($stmt, $i).'"';
  519. }
  520. $result = false;
  521. OCIFreeStatement($stmt);
  522. $fields = implode(',', $cols);
  523. $nrows += $offset;
  524. $offset += 1; // in Oracle rownum starts at 1
  525. if ($this->databaseType == 'oci8po') {
  526. $sql = "SELECT $fields FROM".
  527. "(SELECT rownum as adodb_rownum, $fields FROM".
  528. " ($sql) WHERE rownum <= ?".
  529. ") WHERE adodb_rownum >= ?";
  530. } else {
  531. $sql = "SELECT $fields FROM".
  532. "(SELECT rownum as adodb_rownum, $fields FROM".
  533. " ($sql) WHERE rownum <= :adodb_nrows".
  534. ") WHERE adodb_rownum >= :adodb_offset";
  535. }
  536. $inputarr['adodb_nrows'] = $nrows;
  537. $inputarr['adodb_offset'] = $offset;
  538. if ($secs2cache>0) $rs = $this->CacheExecute($secs2cache, $sql,$inputarr);
  539. else $rs = $this->Execute($sql,$inputarr);
  540. return $rs;
  541. }
  542. }
  543. /**
  544. * Usage:
  545. * Store BLOBs and CLOBs
  546. *
  547. * Example: to store $var in a blob
  548. *
  549. * $conn->Execute('insert into TABLE (id,ablob) values(12,empty_blob())');
  550. * $conn->UpdateBlob('TABLE', 'ablob', $varHoldingBlob, 'ID=12', 'BLOB');
  551. *
  552. * $blobtype supports 'BLOB' and 'CLOB', but you need to change to 'empty_clob()'.
  553. *
  554. * to get length of LOB:
  555. * select DBMS_LOB.GETLENGTH(ablob) from TABLE
  556. *
  557. * If you are using CURSOR_SHARING = force, it appears this will case a segfault
  558. * under oracle 8.1.7.0. Run:
  559. * $db->Execute('ALTER SESSION SET CURSOR_SHARING=EXACT');
  560. * before UpdateBlob() then...
  561. */
  562. function UpdateBlob($table,$column,$val,$where,$blobtype='BLOB')
  563. {
  564. //if (strlen($val) < 4000) return $this->Execute("UPDATE $table SET $column=:blob WHERE $where",array('blob'=>$val)) != false;
  565. switch(strtoupper($blobtype)) {
  566. default: ADOConnection::outp("<b>UpdateBlob</b>: Unknown blobtype=$blobtype"); return false;
  567. case 'BLOB': $type = OCI_B_BLOB; break;
  568. case 'CLOB': $type = OCI_B_CLOB; break;
  569. }
  570. if ($this->databaseType == 'oci8po')
  571. $sql = "UPDATE $table set $column=EMPTY_{$blobtype}() WHERE $where RETURNING $column INTO ?";
  572. else
  573. $sql = "UPDATE $table set $column=EMPTY_{$blobtype}() WHERE $where RETURNING $column INTO :blob";
  574. $desc = OCINewDescriptor($this->_connectionID, OCI_D_LOB);
  575. $arr['blob'] = array($desc,-1,$type);
  576. if ($this->session_sharing_force_blob) $this->Execute('ALTER SESSION SET CURSOR_SHARING=EXACT');
  577. $commit = $this->autoCommit;
  578. if ($commit) $this->BeginTrans();
  579. $rs = $this->_Execute($sql,$arr);
  580. if ($rez = !empty($rs)) $desc->save($val);
  581. $desc->free();
  582. if ($commit) $this->CommitTrans();
  583. if ($this->session_sharing_force_blob) $this->Execute('ALTER SESSION SET CURSOR_SHARING=FORCE');
  584. if ($rez) $rs->Close();
  585. return $rez;
  586. }
  587. /**
  588. * Usage: store file pointed to by $var in a blob
  589. */
  590. function UpdateBlobFile($table,$column,$val,$where,$blobtype='BLOB')
  591. {
  592. switch(strtoupper($blobtype)) {
  593. default: ADOConnection::outp( "<b>UpdateBlob</b>: Unknown blobtype=$blobtype"); return false;
  594. case 'BLOB': $type = OCI_B_BLOB; break;
  595. case 'CLOB': $type = OCI_B_CLOB; break;
  596. }
  597. if ($this->databaseType == 'oci8po')
  598. $sql = "UPDATE $table set $column=EMPTY_{$blobtype}() WHERE $where RETURNING $column INTO ?";
  599. else
  600. $sql = "UPDATE $table set $column=EMPTY_{$blobtype}() WHERE $where RETURNING $column INTO :blob";
  601. $desc = OCINewDescriptor($this->_connectionID, OCI_D_LOB);
  602. $arr['blob'] = array($desc,-1,$type);
  603. $this->BeginTrans();
  604. $rs = ADODB_oci8::Execute($sql,$arr);
  605. if ($rez = !empty($rs)) $desc->savefile($val);
  606. $desc->free();
  607. $this->CommitTrans();
  608. if ($rez) $rs->Close();
  609. return $rez;
  610. }
  611. /**
  612. * Execute SQL
  613. *
  614. * @param sql SQL statement to execute, or possibly an array holding prepared statement ($sql[0] will hold sql text)
  615. * @param [inputarr] holds the input data to bind to. Null elements will be set to null.
  616. * @return RecordSet or false
  617. */
  618. function &Execute($sql,$inputarr=false)
  619. {
  620. if ($this->fnExecute) {
  621. $fn = $this->fnExecute;
  622. $ret = $fn($this,$sql,$inputarr);
  623. if (isset($ret)) return $ret;
  624. }
  625. if ($inputarr) {
  626. #if (!is_array($inputarr)) $inputarr = array($inputarr);
  627. $element0 = reset($inputarr);
  628. # is_object check because oci8 descriptors can be passed in
  629. if (is_array($element0) && !is_object(reset($element0))) {
  630. if (is_string($sql))
  631. $stmt = $this->Prepare($sql);
  632. else
  633. $stmt = $sql;
  634. foreach($inputarr as $arr) {
  635. $ret = $this->_Execute($stmt,$arr);
  636. if (!$ret) return $ret;
  637. }
  638. } else {
  639. $ret = $this->_Execute($sql,$inputarr);
  640. }
  641. } else {
  642. $ret = $this->_Execute($sql,false);
  643. }
  644. return $ret;
  645. }
  646. /*
  647. Example of usage:
  648. $stmt = $this->Prepare('insert into emp (empno, ename) values (:empno, :ename)');
  649. */
  650. function Prepare($sql,$cursor=false)
  651. {
  652. static $BINDNUM = 0;
  653. $stmt = OCIParse($this->_connectionID,$sql);
  654. if (!$stmt) return false;
  655. $BINDNUM += 1;
  656. $sttype = @OCIStatementType($stmt);
  657. if ($sttype == 'BEGIN' || $sttype == 'DECLARE') {
  658. return array($sql,$stmt,0,$BINDNUM, ($cursor) ? OCINewCursor($this->_connectionID) : false);
  659. }
  660. return array($sql,$stmt,0,$BINDNUM);
  661. }
  662. /*
  663. Call an oracle stored procedure and returns a cursor variable as a recordset.
  664. Concept by Robert Tuttle robert@ud.com
  665. Example:
  666. Note: we return a cursor variable in :RS2
  667. $rs = $db->ExecuteCursor("BEGIN adodb.open_tab(:RS2); END;",'RS2');
  668. $rs = $db->ExecuteCursor(
  669. "BEGIN :RS2 = adodb.getdata(:VAR1); END;",
  670. 'RS2',
  671. array('VAR1' => 'Mr Bean'));
  672. */
  673. function &ExecuteCursor($sql,$cursorName='rs',$params=false)
  674. {
  675. if (is_array($sql)) $stmt = $sql;
  676. else $stmt = ADODB_oci8::Prepare($sql,true); # true to allocate OCINewCursor
  677. if (is_array($stmt) && sizeof($stmt) >= 5) {
  678. $hasref = true;
  679. $ignoreCur = false;
  680. $this->Parameter($stmt, $ignoreCur, $cursorName, false, -1, OCI_B_CURSOR);
  681. if ($params) {
  682. foreach($params as $k => $v) {
  683. $this->Parameter($stmt,$params[$k], $k);
  684. }
  685. }
  686. } else
  687. $hasref = false;
  688. $rs = $this->Execute($stmt);
  689. if ($rs) {
  690. if ($rs->databaseType == 'array') OCIFreeCursor($stmt[4]);
  691. else if ($hasref) $rs->_refcursor = $stmt[4];
  692. }
  693. return $rs;
  694. }
  695. /*
  696. Bind a variable -- very, very fast for executing repeated statements in oracle.
  697. Better than using
  698. for ($i = 0; $i < $max; $i++) {
  699. $p1 = ?; $p2 = ?; $p3 = ?;
  700. $this->Execute("insert into table (col0, col1, col2) values (:0, :1, :2)",
  701. array($p1,$p2,$p3));
  702. }
  703. Usage:
  704. $stmt = $DB->Prepare("insert into table (col0, col1, col2) values (:0, :1, :2)");
  705. $DB->Bind($stmt, $p1);
  706. $DB->Bind($stmt, $p2);
  707. $DB->Bind($stmt, $p3);
  708. for ($i = 0; $i < $max; $i++) {
  709. $p1 = ?; $p2 = ?; $p3 = ?;
  710. $DB->Execute($stmt);
  711. }
  712. Some timings:
  713. ** Test table has 3 cols, and 1 index. Test to insert 1000 records
  714. Time 0.6081s (1644.60 inserts/sec) with direct OCIParse/OCIExecute
  715. Time 0.6341s (1577.16 inserts/sec) with ADOdb Prepare/Bind/Execute
  716. Time 1.5533s ( 643.77 inserts/sec) with pure SQL using Execute
  717. Now if PHP only had batch/bulk updating like Java or PL/SQL...
  718. Note that the order of parameters differs from OCIBindByName,
  719. because we default the names to :0, :1, :2
  720. */
  721. function Bind(&$stmt,&$var,$size=4000,$type=false,$name=false,$isOutput=false)
  722. {
  723. if (!is_array($stmt)) return false;
  724. if (($type == OCI_B_CURSOR) && sizeof($stmt) >= 5) {
  725. return OCIBindByName($stmt[1],":".$name,$stmt[4],$size,$type);
  726. }
  727. if ($name == false) {
  728. if ($type !== false) $rez = OCIBindByName($stmt[1],":".$stmt[2],$var,$size,$type);
  729. else $rez = OCIBindByName($stmt[1],":".$stmt[2],$var,$size); // +1 byte for null terminator
  730. $stmt[2] += 1;
  731. } else if (oci_lob_desc($type)) {
  732. if ($this->debug) {
  733. ADOConnection::outp("<b>Bind</b>: name = $name");
  734. }
  735. //we have to create a new Descriptor here
  736. $numlob = count($this->_refLOBs);
  737. $this->_refLOBs[$numlob]['LOB'] = OCINewDescriptor($this->_connectionID, oci_lob_desc($type));
  738. $this->_refLOBs[$numlob]['TYPE'] = $isOutput;
  739. $tmp = &$this->_refLOBs[$numlob]['LOB'];
  740. $rez = OCIBindByName($stmt[1], ":".$name, $tmp, -1, $type);
  741. if ($this->debug) {
  742. ADOConnection::outp("<b>Bind</b>: descriptor has been allocated, var (".$name.") binded");
  743. }
  744. // if type is input then write data to lob now
  745. if ($isOutput == false) {
  746. $var = $this->BlobEncode($var);
  747. $tmp->WriteTemporary($var);
  748. $this->_refLOBs[$numlob]['VAR'] = &$var;
  749. if ($this->debug) {
  750. ADOConnection::outp("<b>Bind</b>: LOB has been written to temp");
  751. }
  752. } else {
  753. $this->_refLOBs[$numlob]['VAR'] = &$var;
  754. }
  755. $rez = $tmp;
  756. } else {
  757. if ($this->debug)
  758. ADOConnection::outp("<b>Bind</b>: name = $name");
  759. if ($type !== false) $rez = OCIBindByName($stmt[1],":".$name,$var,$size,$type);
  760. else $rez = OCIBindByName($stmt[1],":".$name,$var,$size); // +1 byte for null terminator
  761. }
  762. return $rez;
  763. }
  764. function Param($name,$type=false)
  765. {
  766. return ':'.$name;
  767. }
  768. /*
  769. Usage:
  770. $stmt = $db->Prepare('select * from table where id =:myid and group=:group');
  771. $db->Parameter($stmt,$id,'myid');
  772. $db->Parameter($stmt,$group,'group');
  773. $db->Execute($stmt);
  774. @param $stmt Statement returned by Prepare() or PrepareSP().
  775. @param $var PHP variable to bind to
  776. @param $name Name of stored procedure variable name to bind to.
  777. @param [$isOutput] Indicates direction of parameter 0/false=IN 1=OUT 2= IN/OUT. This is ignored in oci8.
  778. @param [$maxLen] Holds an maximum length of the variable.
  779. @param [$type] The data type of $var. Legal values depend on driver.
  780. See OCIBindByName documentation at php.net.
  781. */
  782. function Parameter(&$stmt,&$var,$name,$isOutput=false,$maxLen=4000,$type=false)
  783. {
  784. if ($this->debug) {
  785. $prefix = ($isOutput) ? 'Out' : 'In';
  786. $ztype = (empty($type)) ? 'false' : $type;
  787. ADOConnection::outp( "{$prefix}Parameter(\$stmt, \$php_var='$var', \$name='$name', \$maxLen=$maxLen, \$type=$ztype);");
  788. }
  789. return $this->Bind($stmt,$var,$maxLen,$type,$name,$isOutput);
  790. }
  791. /*
  792. returns query ID if successful, otherwise false
  793. this version supports:
  794. 1. $db->execute('select * from table');
  795. 2. $db->prepare('insert into table (a,b,c) values (:0,:1,:2)');
  796. $db->execute($prepared_statement, array(1,2,3));
  797. 3. $db->execute('insert into table (a,b,c) values (:a,:b,:c)',array('a'=>1,'b'=>2,'c'=>3));
  798. 4. $db->prepare('insert into table (a,b,c) values (:0,:1,:2)');
  799. $db->bind($stmt,1); $db->bind($stmt,2); $db->bind($stmt,3);
  800. $db->execute($stmt);
  801. */
  802. function _query($sql,$inputarr)
  803. {
  804. if (is_array($sql)) { // is prepared sql
  805. $stmt = $sql[1];
  806. // we try to bind to permanent array, so that OCIBindByName is persistent
  807. // and carried out once only - note that max array element size is 4000 chars
  808. if (is_array($inputarr)) {
  809. $bindpos = $sql[3];
  810. if (isset($this->_bind[$bindpos])) {
  811. // all tied up already
  812. $bindarr = &$this->_bind[$bindpos];
  813. } else {
  814. // one statement to bind them all
  815. $bindarr = array();
  816. foreach($inputarr as $k => $v) {
  817. $bindarr[$k] = $v;
  818. OCIBindByName($stmt,":$k",$bindarr[$k],is_string($v) && strlen($v)>4000 ? -1 : 4000);
  819. }
  820. $this->_bind[$bindpos] = &$bindarr;
  821. }
  822. }
  823. } else {
  824. $stmt=OCIParse($this->_connectionID,$sql);
  825. }
  826. $this->_stmt = $stmt;
  827. if (!$stmt) return false;
  828. if (defined('ADODB_PREFETCH_ROWS')) @OCISetPrefetch($stmt,ADODB_PREFETCH_ROWS);
  829. if (is_array($inputarr)) {
  830. foreach($inputarr as $k => $v) {
  831. if (is_array($v)) {
  832. if (sizeof($v) == 2) // suggested by g.giunta@libero.
  833. OCIBindByName($stmt,":$k",$inputarr[$k][0],$v[1]);
  834. else
  835. OCIBindByName($stmt,":$k",$inputarr[$k][0],$v[1],$v[2]);
  836. if ($this->debug==99) echo "name=:$k",' var='.$inputarr[$k][0],' len='.$v[1],' type='.$v[2],'<br>';
  837. } else {
  838. $len = -1;
  839. if ($v === ' ') $len = 1;
  840. if (isset($bindarr)) { // is prepared sql, so no need to ocibindbyname again
  841. $bindarr[$k] = $v;
  842. } else { // dynamic sql, so rebind every time
  843. OCIBindByName($stmt,":$k",$inputarr[$k],$len);
  844. }
  845. }
  846. }
  847. }
  848. $this->_errorMsg = false;
  849. $this->_errorCode = false;
  850. if (OCIExecute($stmt,$this->_commit)) {
  851. //OCIInternalDebug(1);
  852. if (count($this -> _refLOBs) > 0) {
  853. foreach ($this -> _refLOBs as $key => $value) {
  854. if ($this -> _refLOBs[$key]['TYPE'] == true) {
  855. $tmp = $this -> _refLOBs[$key]['LOB'] -> load();
  856. if ($this -> debug) {
  857. ADOConnection::outp("<b>OUT LOB</b>: LOB has been loaded. <br>");
  858. }
  859. //$_GLOBALS[$this -> _refLOBs[$key]['VAR']] = $tmp;
  860. $this -> _refLOBs[$key]['VAR'] = $tmp;
  861. } else {
  862. $this->_refLOBs[$key]['LOB']->save($this->_refLOBs[$key]['VAR']);
  863. $this -> _refLOBs[$key]['LOB']->free();
  864. unset($this -> _refLOBs[$key]);
  865. if ($this->debug) {
  866. ADOConnection::outp("<b>IN LOB</b>: LOB has been saved. <br>");
  867. }
  868. }
  869. }
  870. }
  871. switch (@OCIStatementType($stmt)) {
  872. case "SELECT":
  873. return $stmt;
  874. case 'DECLARE':
  875. case "BEGIN":
  876. if (is_array($sql) && !empty($sql[4])) {
  877. $cursor = $sql[4];
  878. if (is_resource($cursor)) {
  879. $ok = OCIExecute($cursor);
  880. return $cursor;
  881. }
  882. return $stmt;
  883. } else {
  884. if (is_resource($stmt)) {
  885. OCIFreeStatement($stmt);
  886. return true;
  887. }
  888. return $stmt;
  889. }
  890. break;
  891. default :
  892. // ociclose -- no because it could be used in a LOB?
  893. return true;
  894. }
  895. }
  896. return false;
  897. }
  898. // returns true or false
  899. function _close()
  900. {
  901. if (!$this->_connectionID) return;
  902. if (!$this->autoCommit) OCIRollback($this->_connectionID);
  903. if (count($this->_refLOBs) > 0) {
  904. foreach ($this ->_refLOBs as $key => $value) {
  905. $this->_refLOBs[$key]['LOB']->free();
  906. unset($this->_refLOBs[$key]);
  907. }
  908. }
  909. OCILogoff($this->_connectionID);
  910. $this->_stmt = false;
  911. $this->_connectionID = false;
  912. }
  913. function MetaPrimaryKeys($table, $owner=false,$internalKey=false)
  914. {
  915. if ($internalKey) return array('ROWID');
  916. // tested with oracle 8.1.7
  917. $table = strtoupper($table);
  918. if ($owner) {
  919. $owner_clause = "AND ((a.OWNER = b.OWNER) AND (a.OWNER = UPPER('$owner')))";
  920. $ptab = 'ALL_';
  921. } else {
  922. $owner_clause = '';
  923. $ptab = 'USER_';
  924. }
  925. $sql = "
  926. SELECT /*+ RULE */ distinct b.column_name
  927. FROM {$ptab}CONSTRAINTS a
  928. , {$ptab}CONS_COLUMNS b
  929. WHERE ( UPPER(b.table_name) = ('$table'))
  930. AND (UPPER(a.table_name) = ('$table') and a.constraint_type = 'P')
  931. $owner_clause
  932. AND (a.constraint_name = b.constraint_name)";
  933. $rs = $this->Execute($sql);
  934. if ($rs && !$rs->EOF) {
  935. $arr = $rs->GetArray();
  936. $a = array();
  937. foreach($arr as $v) {
  938. $a[] = reset($v);
  939. }
  940. return $a;
  941. }
  942. else return false;
  943. }
  944. // http://gis.mit.edu/classes/11.521/sqlnotes/referential_integrity.html
  945. function MetaForeignKeys($table, $owner=false)
  946. {
  947. global $ADODB_FETCH_MODE;
  948. $save = $ADODB_FETCH_MODE;
  949. $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
  950. $table = $this->qstr(strtoupper($table));
  951. if (!$owner) {
  952. $owner = $this->user;
  953. $tabp = 'user_';
  954. } else
  955. $tabp = 'all_';
  956. $owner = ' and owner='.$this->qstr(strtoupper($owner));
  957. $sql =
  958. "select constraint_name,r_owner,r_constraint_name
  959. from {$tabp}constraints
  960. where constraint_type = 'R' and table_name = $table $owner";
  961. $constraints = $this->GetArray($sql);
  962. $arr = false;
  963. foreach($constraints as $constr) {
  964. $cons = $this->qstr($constr[0]);
  965. $rowner = $this->qstr($constr[1]);
  966. $rcons = $this->qstr($constr[2]);
  967. $cols = $this->GetArray("select column_name from {$tabp}cons_columns where constraint_name=$cons $owner order by position");
  968. $tabcol = $this->GetArray("select table_name,column_name from {$tabp}cons_columns where owner=$rowner and constraint_name=$rcons order by position");
  969. if ($cols && $tabcol)
  970. for ($i=0, $max=sizeof($cols); $i < $max; $i++) {
  971. $arr[$tabcol[$i][0]] = $cols[$i][0].'='.$tabcol[$i][1];
  972. }
  973. }
  974. $ADODB_FETCH_MODE = $save;
  975. return $arr;
  976. }
  977. function CharMax()
  978. {
  979. return 4000;
  980. }
  981. function TextMax()
  982. {
  983. return 4000;
  984. }
  985. /**
  986. * Quotes a string.
  987. * An example is $db->qstr("Don't bother",magic_quotes_runtime());
  988. *
  989. * @param s the string to quote
  990. * @param [magic_quotes] if $s is GET/POST var, set to get_magic_quotes_gpc().
  991. * This undoes the stupidity of magic quotes for GPC.
  992. *
  993. * @return quoted string to be sent back to database
  994. */
  995. function qstr($s,$magic_quotes=false)
  996. {
  997. //$nofixquotes=false;
  998. if ($this->noNullStrings && strlen($s)==0)$s = ' ';
  999. if (!$magic_quotes) {
  1000. if ($this->replaceQuote[0] == '\\'){
  1001. $s = str_replace('\\','\\\\',$s);
  1002. }
  1003. return "'".str_replace("'",$this->replaceQuote,$s)."'";
  1004. }
  1005. // undo magic quotes for "
  1006. $s = str_replace('\\"','"',$s);
  1007. $s = str_replace('\\\\','\\',$s);
  1008. return "'".str_replace("\\'",$this->replaceQuote,$s)."'";
  1009. }
  1010. }
  1011. /*--------------------------------------------------------------------------------------
  1012. Class Name: Recordset
  1013. --------------------------------------------------------------------------------------*/
  1014. class ADORecordset_oci8 extends ADORecordSet {
  1015. var $databaseType = 'oci8';
  1016. var $bind=false;
  1017. var $_fieldobjs;
  1018. //var $_arr = false;
  1019. function ADORecordset_oci8($queryID,$mode=false)
  1020. {
  1021. if ($mode === false) {
  1022. global $ADODB_FETCH_MODE;
  1023. $mode = $ADODB_FETCH_MODE;
  1024. }
  1025. switch ($mode)
  1026. {
  1027. case ADODB_FETCH_ASSOC:$this->fetchMode = OCI_ASSOC+OCI_RETURN_NULLS+OCI_RETURN_LOBS; break;
  1028. case ADODB_FETCH_DEFAULT:
  1029. case ADODB_FETCH_BOTH:$this->fetchMode = OCI_NUM+OCI_ASSOC+OCI_RETURN_NULLS+OCI_RETURN_LOBS; break;
  1030. case ADODB_FETCH_NUM:
  1031. default:
  1032. $this->fetchMode = OCI_NUM+OCI_RETURN_NULLS+OCI_RETURN_LOBS; break;
  1033. }
  1034. $this->adodbFetchMode = $mode;
  1035. $this->_queryID = $queryID;
  1036. }
  1037. function Init()
  1038. {
  1039. if ($this->_inited) return;
  1040. $this->_inited = true;
  1041. if ($this->_queryID) {
  1042. $this->_currentRow = 0;
  1043. @$this->_initrs();
  1044. $this->EOF = !$this->_fetch();
  1045. /*
  1046. // based on idea by Gaetano Giunta to detect unusual oracle errors
  1047. // see http://phplens.com/lens/lensforum/msgs.php?id=6771
  1048. $err = OCIError($this->_queryID);
  1049. if ($err && $this->connection->debug) ADOConnection::outp($err);
  1050. */
  1051. if (!is_array($this->fields)) {
  1052. $this->_numOfRows = 0;
  1053. $this->fields = array();
  1054. }
  1055. } else {
  1056. $this->fields = array();
  1057. $this->_numOfRows = 0;
  1058. $this->_numOfFields = 0;
  1059. $this->EOF = true;
  1060. }
  1061. }
  1062. function _initrs()
  1063. {
  1064. $this->_numOfRows = -1;
  1065. $this->_numOfFields = OCInumcols($this->_queryID);
  1066. if ($this->_numOfFields>0) {
  1067. $this->_fieldobjs = array();
  1068. $max = $this->_numOfFields;
  1069. for ($i=0;$i<$max; $i++) $this->_fieldobjs[] = $this->_FetchField($i);
  1070. }
  1071. }
  1072. /* Returns: an object containing field information.
  1073. Get column information in the Recordset object. fetchField() can be used in order to obtain information about
  1074. fields in a certain query result. If the field offset isn't specified, the next field that wasn't yet retrieved by
  1075. fetchField() is retrieved. */
  1076. function &_FetchField($fieldOffset = -1)
  1077. {
  1078. $fld = new ADOFieldObject;
  1079. $fieldOffset += 1;
  1080. $fld->name =OCIcolumnname($this->_queryID, $fieldOffset);
  1081. $fld->type = OCIcolumntype($this->_queryID, $fieldOffset);
  1082. $fld->max_length = OCIcolumnsize($this->_queryID, $fieldOffset);
  1083. if ($fld->type == 'NUMBER') {
  1084. $p = OCIColumnPrecision($this->_queryID, $fieldOffset);
  1085. $sc = OCIColumnScale($this->_queryID, $fieldOffset);
  1086. if ($p != 0 && $sc == 0) $fld->type = 'INT';
  1087. //echo " $this->name ($p.$sc) ";
  1088. }
  1089. return $fld;
  1090. }
  1091. /* For some reason, OCIcolumnname fails when called after _initrs() so we cache it */
  1092. function &FetchField($fieldOffset = -1)
  1093. {
  1094. return $this->_fieldobjs[$fieldOffset];
  1095. }
  1096. /*
  1097. // 10% speedup to move MoveNext to child class
  1098. function _MoveNext()
  1099. {
  1100. //global $ADODB_EXTENSION;if ($ADODB_EXTENSION) return @adodb_movenext($this);
  1101. if ($this->EOF) return false;
  1102. $this->_currentRow++;
  1103. if(@OCIfetchinto($this->_queryID,$this->fields,$this->fetchMode))
  1104. return true;
  1105. $this->EOF = true;
  1106. return false;
  1107. } */
  1108. function MoveNext()
  1109. {
  1110. if (@OCIfetchinto($this->_queryID,$this->fields,$this->fetchMode)) {
  1111. $this->_currentRow += 1;
  1112. return true;
  1113. }
  1114. if (!$this->EOF) {
  1115. $this->_currentRow += 1;
  1116. $this->EOF = true;
  1117. }
  1118. return false;
  1119. }
  1120. /*
  1121. # does not work as first record is retrieved in _initrs(), so is not included in GetArray()
  1122. function &GetArray($nRows = -1)
  1123. {
  1124. global $ADODB_OCI8_GETARRAY;
  1125. if (true || !empty($ADODB_OCI8_GETARRAY)) {
  1126. # does not support $ADODB_ANSI_PADDING_OFF
  1127. //OCI_RETURN_NULLS and OCI_RETURN_LOBS is set by OCIfetchstatement
  1128. switch($this->adodbFetchMode) {
  1129. case ADODB_FETCH_NUM:
  1130. $ncols = @OCIfetchstatement($this->_queryID, $results, 0, $nRows, OCI_FETCHSTATEMENT_BY_ROW+OCI_NUM);
  1131. $results = array_merge(array($this->fields),$results);
  1132. return $results;
  1133. case ADODB_FETCH_ASSOC:
  1134. if (ADODB_ASSOC_CASE != 2 || $this->databaseType != 'oci8') break;
  1135. $ncols = @OCIfetchstatement($this->_queryID, $assoc, 0, $nRows, OCI_FETCHSTATEMENT_BY_ROW);
  1136. $results = array_merge(array($this->fields),$assoc);
  1137. return $results;
  1138. default:
  1139. break;
  1140. }
  1141. }
  1142. $results = ADORecordSet::GetArray($nRows);
  1143. return $results;
  1144. } */
  1145. /* Optimize SelectLimit() by using OCIFetch() instead of OCIFetchInto() */
  1146. function &GetArrayLimit($nrows,$offset=-1)
  1147. {
  1148. if ($offset <= 0) {
  1149. $arr = $this->GetArray($nrows);
  1150. return $arr;
  1151. }
  1152. for ($i=1; $i < $offset; $i++)
  1153. if (!@OCIFetch($this->_queryID)) return array();
  1154. if (!@OCIfetchinto($this->_queryID,$this->fields,$this->fetchMode)) return array();
  1155. $results = array();
  1156. $cnt = 0;
  1157. while (!$this->EOF && $nrows != $cnt) {
  1158. $results[$cnt++] = $this->fields;
  1159. $this->MoveNext();
  1160. }
  1161. return $results;
  1162. }
  1163. /* Use associative array to get fields array */
  1164. function Fields($colname)
  1165. {
  1166. if (!$this->bind) {
  1167. $this->bind = array();
  1168. for ($i=0; $i < $this->_numOfFields; $i++) {
  1169. $o = $this->FetchField($i);
  1170. $this->bind[strtoupper($o->name)] = $i;
  1171. }
  1172. }
  1173. return $this->fields[$this->bind[strtoupper($colname)]];
  1174. }
  1175. function _seek($row)
  1176. {
  1177. return false;
  1178. }
  1179. function _fetch()
  1180. {
  1181. return @OCIfetchinto($this->_queryID,$this->fields,$this->fetchMode);
  1182. }
  1183. /* close() only needs to be called if you are worried about using too much memory while your script
  1184. is running. All associated result memory for the specified result identifier will automatically be freed. */
  1185. function _close()
  1186. {
  1187. if ($this->connection->_stmt === $this->_queryID) $this->connection->_stmt = false;
  1188. if (!empty($this->_refcursor)) {
  1189. OCIFreeCursor($this->_refcursor);
  1190. $this->_refcursor = false;
  1191. }
  1192. @OCIFreeStatement($this->_queryID);
  1193. $this->_queryID = false;
  1194. }
  1195. function MetaType($t,$len=-1)
  1196. {
  1197. if (is_object($t)) {
  1198. $fieldobj = $t;
  1199. $t = $fieldobj->type;
  1200. $len = $fieldobj->max_length;
  1201. }
  1202. switch (strtoupper($t)) {
  1203. case 'VARCHAR':
  1204. case 'VARCHAR2':
  1205. case 'CHAR':
  1206. case 'VARBINARY':
  1207. case 'BINARY':
  1208. case 'NCHAR':
  1209. case 'NVARCHAR':
  1210. case 'NVARCHAR2':
  1211. if (isset($this) && $len <= $this->blobSize) return 'C';
  1212. case 'NCLOB':
  1213. case 'LONG':
  1214. case 'LONG VARCHAR':
  1215. case 'CLOB':
  1216. return 'X';
  1217. case 'LONG RAW':
  1218. case 'LONG VARBINARY':
  1219. case 'BLOB':
  1220. return 'B';
  1221. case 'DATE':
  1222. return ($this->connection->datetime) ? 'T' : 'D';
  1223. case 'TIMESTAMP': return 'T';
  1224. case 'INT':
  1225. case 'SMALLINT':
  1226. case 'INTEGER':
  1227. return 'I';
  1228. default: return 'N';
  1229. }
  1230. }
  1231. }
  1232. class ADORecordSet_ext_oci8 extends ADORecordSet_oci8 {
  1233. function ADORecordSet_ext_oci8($queryID,$mode=false)
  1234. {
  1235. if ($mode === false) {
  1236. global $ADODB_FETCH_MODE;
  1237. $mode = $ADODB_FETCH_MODE;
  1238. }
  1239. switch ($mode)
  1240. {
  1241. case ADODB_FETCH_ASSOC:$this->fetchMode = OCI_ASSOC+OCI_RETURN_NULLS+OCI_RETURN_LOBS; break;
  1242. case ADODB_FETCH_DEFAULT:
  1243. case ADODB_FETCH_BOTH:$this->fetchMode = OCI_NUM+OCI_ASSOC+OCI_RETURN_NULLS+OCI_RETURN_LOBS; break;
  1244. case ADODB_FETCH_NUM:
  1245. default: $this->fetchMode = OCI_NUM+OCI_RETURN_NULLS+OCI_RETURN_LOBS; break;
  1246. }
  1247. $this->adodbFetchMode = $mode;
  1248. $this->_queryID = $queryID;
  1249. }
  1250. function MoveNext()
  1251. {
  1252. return adodb_movenext($this);
  1253. }
  1254. }
  1255. ?>