PageRenderTime 236ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 1ms

/05_Desarrollo/lib/adodb/drivers/adodb-oci8.inc.php

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