PageRenderTime 61ms CodeModel.GetById 17ms RepoModel.GetById 1ms app.codeStats 0ms

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

https://github.com/Fusion/lenses
PHP | 1566 lines | 1294 code | 112 blank | 160 comment | 120 complexity | ecd87488f748dee3125af7018f3ec31c MD5 | raw file
Possible License(s): BSD-3-Clause
  1. <?php
  2. /*
  3. version V5.04a 25 Mar 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'; // DBDate format
  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. if (!$this->_bindInputArray) {
  635. # is_object check because oci8 descriptors can be passed in
  636. if (is_array($element0) && !is_object(reset($element0))) {
  637. if (is_string($sql))
  638. $stmt = $this->Prepare($sql);
  639. else
  640. $stmt = $sql;
  641. foreach($inputarr as $arr) {
  642. $ret = $this->_Execute($stmt,$arr);
  643. if (!$ret) return $ret;
  644. }
  645. } else {
  646. $sqlarr = explode(':',$sql);
  647. $sql = '';
  648. $lastnomatch = -2;
  649. #var_dump($sqlarr);echo "<hr>";var_dump($inputarr);echo"<hr>";
  650. foreach($sqlarr as $k => $str) {
  651. if ($k == 0) { $sql = $str; continue; }
  652. // we need $lastnomatch because of the following datetime,
  653. // eg. '10:10:01', which causes code to think that there is bind param :10 and :1
  654. $ok = preg_match('/^([0-9]*)/', $str, $arr);
  655. if (!$ok) $sql .= $str;
  656. else {
  657. $at = $arr[1];
  658. if (isset($inputarr[$at]) || is_null($inputarr[$at])) {
  659. if ((strlen($at) == strlen($str) && $k < sizeof($arr)-1)) {
  660. $sql .= ':'.$str;
  661. $lastnomatch = $k;
  662. } else if ($lastnomatch == $k-1) {
  663. $sql .= ':'.$str;
  664. } else {
  665. if (is_null($inputarr[$at])) $sql .= 'null';
  666. else $sql .= $this->qstr($inputarr[$at]);
  667. $sql .= substr($str, strlen($at));
  668. }
  669. } else {
  670. $sql .= ':'.$str;
  671. }
  672. }
  673. }
  674. $inputarr = false;
  675. }
  676. }
  677. $ret = $this->_Execute($sql,$inputarr);
  678. } else {
  679. $ret = $this->_Execute($sql,false);
  680. }
  681. return $ret;
  682. }
  683. /*
  684. Example of usage:
  685. $stmt = $this->Prepare('insert into emp (empno, ename) values (:empno, :ename)');
  686. */
  687. function Prepare($sql,$cursor=false)
  688. {
  689. static $BINDNUM = 0;
  690. $stmt = OCIParse($this->_connectionID,$sql);
  691. if (!$stmt) {
  692. $this->_errorMsg = false;
  693. $this->_errorCode = false;
  694. $arr = @OCIError($this->_connectionID);
  695. if ($arr === false) return false;
  696. $this->_errorMsg = $arr['message'];
  697. $this->_errorCode = $arr['code'];
  698. return false;
  699. }
  700. $BINDNUM += 1;
  701. $sttype = @OCIStatementType($stmt);
  702. if ($sttype == 'BEGIN' || $sttype == 'DECLARE') {
  703. return array($sql,$stmt,0,$BINDNUM, ($cursor) ? OCINewCursor($this->_connectionID) : false);
  704. }
  705. return array($sql,$stmt,0,$BINDNUM);
  706. }
  707. /*
  708. Call an oracle stored procedure and returns a cursor variable as a recordset.
  709. Concept by Robert Tuttle robert@ud.com
  710. Example:
  711. Note: we return a cursor variable in :RS2
  712. $rs = $db->ExecuteCursor("BEGIN adodb.open_tab(:RS2); END;",'RS2');
  713. $rs = $db->ExecuteCursor(
  714. "BEGIN :RS2 = adodb.getdata(:VAR1); END;",
  715. 'RS2',
  716. array('VAR1' => 'Mr Bean'));
  717. */
  718. function ExecuteCursor($sql,$cursorName='rs',$params=false)
  719. {
  720. if (is_array($sql)) $stmt = $sql;
  721. else $stmt = ADODB_oci8::Prepare($sql,true); # true to allocate OCINewCursor
  722. if (is_array($stmt) && sizeof($stmt) >= 5) {
  723. $hasref = true;
  724. $ignoreCur = false;
  725. $this->Parameter($stmt, $ignoreCur, $cursorName, false, -1, OCI_B_CURSOR);
  726. if ($params) {
  727. foreach($params as $k => $v) {
  728. $this->Parameter($stmt,$params[$k], $k);
  729. }
  730. }
  731. } else
  732. $hasref = false;
  733. $rs = $this->Execute($stmt);
  734. if ($rs) {
  735. if ($rs->databaseType == 'array') OCIFreeCursor($stmt[4]);
  736. else if ($hasref) $rs->_refcursor = $stmt[4];
  737. }
  738. return $rs;
  739. }
  740. /*
  741. Bind a variable -- very, very fast for executing repeated statements in oracle.
  742. Better than using
  743. for ($i = 0; $i < $max; $i++) {
  744. $p1 = ?; $p2 = ?; $p3 = ?;
  745. $this->Execute("insert into table (col0, col1, col2) values (:0, :1, :2)",
  746. array($p1,$p2,$p3));
  747. }
  748. Usage:
  749. $stmt = $DB->Prepare("insert into table (col0, col1, col2) values (:0, :1, :2)");
  750. $DB->Bind($stmt, $p1);
  751. $DB->Bind($stmt, $p2);
  752. $DB->Bind($stmt, $p3);
  753. for ($i = 0; $i < $max; $i++) {
  754. $p1 = ?; $p2 = ?; $p3 = ?;
  755. $DB->Execute($stmt);
  756. }
  757. Some timings:
  758. ** Test table has 3 cols, and 1 index. Test to insert 1000 records
  759. Time 0.6081s (1644.60 inserts/sec) with direct OCIParse/OCIExecute
  760. Time 0.6341s (1577.16 inserts/sec) with ADOdb Prepare/Bind/Execute
  761. Time 1.5533s ( 643.77 inserts/sec) with pure SQL using Execute
  762. Now if PHP only had batch/bulk updating like Java or PL/SQL...
  763. Note that the order of parameters differs from OCIBindByName,
  764. because we default the names to :0, :1, :2
  765. */
  766. function Bind(&$stmt,&$var,$size=4000,$type=false,$name=false,$isOutput=false)
  767. {
  768. if (!is_array($stmt)) return false;
  769. if (($type == OCI_B_CURSOR) && sizeof($stmt) >= 5) {
  770. return OCIBindByName($stmt[1],":".$name,$stmt[4],$size,$type);
  771. }
  772. if ($name == false) {
  773. if ($type !== false) $rez = OCIBindByName($stmt[1],":".$stmt[2],$var,$size,$type);
  774. else $rez = OCIBindByName($stmt[1],":".$stmt[2],$var,$size); // +1 byte for null terminator
  775. $stmt[2] += 1;
  776. } else if (oci_lob_desc($type)) {
  777. if ($this->debug) {
  778. ADOConnection::outp("<b>Bind</b>: name = $name");
  779. }
  780. //we have to create a new Descriptor here
  781. $numlob = count($this->_refLOBs);
  782. $this->_refLOBs[$numlob]['LOB'] = OCINewDescriptor($this->_connectionID, oci_lob_desc($type));
  783. $this->_refLOBs[$numlob]['TYPE'] = $isOutput;
  784. $tmp = $this->_refLOBs[$numlob]['LOB'];
  785. $rez = OCIBindByName($stmt[1], ":".$name, $tmp, -1, $type);
  786. if ($this->debug) {
  787. ADOConnection::outp("<b>Bind</b>: descriptor has been allocated, var (".$name.") binded");
  788. }
  789. // if type is input then write data to lob now
  790. if ($isOutput == false) {
  791. $var = $this->BlobEncode($var);
  792. $tmp->WriteTemporary($var);
  793. $this->_refLOBs[$numlob]['VAR'] = $var;
  794. if ($this->debug) {
  795. ADOConnection::outp("<b>Bind</b>: LOB has been written to temp");
  796. }
  797. } else {
  798. $this->_refLOBs[$numlob]['VAR'] = $var;
  799. }
  800. $rez = $tmp;
  801. } else {
  802. if ($this->debug)
  803. ADOConnection::outp("<b>Bind</b>: name = $name");
  804. if ($type !== false) $rez = OCIBindByName($stmt[1],":".$name,$var,$size,$type);
  805. else $rez = OCIBindByName($stmt[1],":".$name,$var,$size); // +1 byte for null terminator
  806. }
  807. return $rez;
  808. }
  809. function Param($name,$type=false)
  810. {
  811. return ':'.$name;
  812. }
  813. /*
  814. Usage:
  815. $stmt = $db->Prepare('select * from table where id =:myid and group=:group');
  816. $db->Parameter($stmt,$id,'myid');
  817. $db->Parameter($stmt,$group,'group');
  818. $db->Execute($stmt);
  819. @param $stmt Statement returned by Prepare() or PrepareSP().
  820. @param $var PHP variable to bind to
  821. @param $name Name of stored procedure variable name to bind to.
  822. @param [$isOutput] Indicates direction of parameter 0/false=IN 1=OUT 2= IN/OUT. This is ignored in oci8.
  823. @param [$maxLen] Holds an maximum length of the variable.
  824. @param [$type] The data type of $var. Legal values depend on driver.
  825. See OCIBindByName documentation at php.net.
  826. */
  827. function Parameter(&$stmt,&$var,$name,$isOutput=false,$maxLen=4000,$type=false)
  828. {
  829. if ($this->debug) {
  830. $prefix = ($isOutput) ? 'Out' : 'In';
  831. $ztype = (empty($type)) ? 'false' : $type;
  832. ADOConnection::outp( "{$prefix}Parameter(\$stmt, \$php_var='$var', \$name='$name', \$maxLen=$maxLen, \$type=$ztype);");
  833. }
  834. return $this->Bind($stmt,$var,$maxLen,$type,$name,$isOutput);
  835. }
  836. /*
  837. returns query ID if successful, otherwise false
  838. this version supports:
  839. 1. $db->execute('select * from table');
  840. 2. $db->prepare('insert into table (a,b,c) values (:0,:1,:2)');
  841. $db->execute($prepared_statement, array(1,2,3));
  842. 3. $db->execute('insert into table (a,b,c) values (:a,:b,:c)',array('a'=>1,'b'=>2,'c'=>3));
  843. 4. $db->prepare('insert into table (a,b,c) values (:0,:1,:2)');
  844. $db->bind($stmt,1); $db->bind($stmt,2); $db->bind($stmt,3);
  845. $db->execute($stmt);
  846. */
  847. function _query($sql,$inputarr)
  848. {
  849. if (is_array($sql)) { // is prepared sql
  850. $stmt = $sql[1];
  851. // we try to bind to permanent array, so that OCIBindByName is persistent
  852. // and carried out once only - note that max array element size is 4000 chars
  853. if (is_array($inputarr)) {
  854. $bindpos = $sql[3];
  855. if (isset($this->_bind[$bindpos])) {
  856. // all tied up already
  857. $bindarr = $this->_bind[$bindpos];
  858. } else {
  859. // one statement to bind them all
  860. $bindarr = array();
  861. foreach($inputarr as $k => $v) {
  862. $bindarr[$k] = $v;
  863. OCIBindByName($stmt,":$k",$bindarr[$k],is_string($v) && strlen($v)>4000 ? -1 : 4000);
  864. }
  865. $this->_bind[$bindpos] = $bindarr;
  866. }
  867. }
  868. } else {
  869. $stmt=OCIParse($this->_connectionID,$sql);
  870. }
  871. $this->_stmt = $stmt;
  872. if (!$stmt) return false;
  873. if (defined('ADODB_PREFETCH_ROWS')) @OCISetPrefetch($stmt,ADODB_PREFETCH_ROWS);
  874. if (is_array($inputarr)) {
  875. foreach($inputarr as $k => $v) {
  876. if (is_array($v)) {
  877. if (sizeof($v) == 2) // suggested by g.giunta@libero.
  878. OCIBindByName($stmt,":$k",$inputarr[$k][0],$v[1]);
  879. else
  880. OCIBindByName($stmt,":$k",$inputarr[$k][0],$v[1],$v[2]);
  881. if ($this->debug==99) {
  882. if (is_object($v[0]))
  883. echo "name=:$k",' len='.$v[1],' type='.$v[2],'<br>';
  884. else
  885. echo "name=:$k",' var='.$inputarr[$k][0],' len='.$v[1],' type='.$v[2],'<br>';
  886. }
  887. } else {
  888. $len = -1;
  889. if ($v === ' ') $len = 1;
  890. if (isset($bindarr)) { // is prepared sql, so no need to ocibindbyname again
  891. $bindarr[$k] = $v;
  892. } else { // dynamic sql, so rebind every time
  893. OCIBindByName($stmt,":$k",$inputarr[$k],$len);
  894. }
  895. }
  896. }
  897. }
  898. $this->_errorMsg = false;
  899. $this->_errorCode = false;
  900. if (OCIExecute($stmt,$this->_commit)) {
  901. //OCIInternalDebug(1);
  902. if (count($this -> _refLOBs) > 0) {
  903. foreach ($this -> _refLOBs as $key => $value) {
  904. if ($this -> _refLOBs[$key]['TYPE'] == true) {
  905. $tmp = $this -> _refLOBs[$key]['LOB'] -> load();
  906. if ($this -> debug) {
  907. ADOConnection::outp("<b>OUT LOB</b>: LOB has been loaded. <br>");
  908. }
  909. //$_GLOBALS[$this -> _refLOBs[$key]['VAR']] = $tmp;
  910. $this -> _refLOBs[$key]['VAR'] = $tmp;
  911. } else {
  912. $this->_refLOBs[$key]['LOB']->save($this->_refLOBs[$key]['VAR']);
  913. $this -> _refLOBs[$key]['LOB']->free();
  914. unset($this -> _refLOBs[$key]);
  915. if ($this->debug) {
  916. ADOConnection::outp("<b>IN LOB</b>: LOB has been saved. <br>");
  917. }
  918. }
  919. }
  920. }
  921. switch (@OCIStatementType($stmt)) {
  922. case "SELECT":
  923. return $stmt;
  924. case 'DECLARE':
  925. case "BEGIN":
  926. if (is_array($sql) && !empty($sql[4])) {
  927. $cursor = $sql[4];
  928. if (is_resource($cursor)) {
  929. $ok = OCIExecute($cursor);
  930. return $cursor;
  931. }
  932. return $stmt;
  933. } else {
  934. if (is_resource($stmt)) {
  935. OCIFreeStatement($stmt);
  936. return true;
  937. }
  938. return $stmt;
  939. }
  940. break;
  941. default :
  942. // ociclose -- no because it could be used in a LOB?
  943. return true;
  944. }
  945. }
  946. return false;
  947. }
  948. // returns true or false
  949. function _close()
  950. {
  951. if (!$this->_connectionID) return;
  952. if (!$this->autoCommit) OCIRollback($this->_connectionID);
  953. if (count($this->_refLOBs) > 0) {
  954. foreach ($this ->_refLOBs as $key => $value) {
  955. $this->_refLOBs[$key]['LOB']->free();
  956. unset($this->_refLOBs[$key]);
  957. }
  958. }
  959. OCILogoff($this->_connectionID);
  960. $this->_stmt = false;
  961. $this->_connectionID = false;
  962. }
  963. function MetaPrimaryKeys($table, $owner=false,$internalKey=false)
  964. {
  965. if ($internalKey) return array('ROWID');
  966. // tested with oracle 8.1.7
  967. $table = strtoupper($table);
  968. if ($owner) {
  969. $owner_clause = "AND ((a.OWNER = b.OWNER) AND (a.OWNER = UPPER('$owner')))";
  970. $ptab = 'ALL_';
  971. } else {
  972. $owner_clause = '';
  973. $ptab = 'USER_';
  974. }
  975. $sql = "
  976. SELECT /*+ RULE */ distinct b.column_name
  977. FROM {$ptab}CONSTRAINTS a
  978. , {$ptab}CONS_COLUMNS b
  979. WHERE ( UPPER(b.table_name) = ('$table'))
  980. AND (UPPER(a.table_name) = ('$table') and a.constraint_type = 'P')
  981. $owner_clause
  982. AND (a.constraint_name = b.constraint_name)";
  983. $rs = $this->Execute($sql);
  984. if ($rs && !$rs->EOF) {
  985. $arr = $rs->GetArray();
  986. $a = array();
  987. foreach($arr as $v) {
  988. $a[] = reset($v);
  989. }
  990. return $a;
  991. }
  992. else return false;
  993. }
  994. // http://gis.mit.edu/classes/11.521/sqlnotes/referential_integrity.html
  995. function MetaForeignKeys($table, $owner=false)
  996. {
  997. global $ADODB_FETCH_MODE;
  998. $save = $ADODB_FETCH_MODE;
  999. $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
  1000. $table = $this->qstr(strtoupper($table));
  1001. if (!$owner) {
  1002. $owner = $this->user;
  1003. $tabp = 'user_';
  1004. } else
  1005. $tabp = 'all_';
  1006. $owner = ' and owner='.$this->qstr(strtoupper($owner));
  1007. $sql =
  1008. "select constraint_name,r_owner,r_constraint_name
  1009. from {$tabp}constraints
  1010. where constraint_type = 'R' and table_name = $table $owner";
  1011. $constraints = $this->GetArray($sql);
  1012. $arr = false;
  1013. foreach($constraints as $constr) {
  1014. $cons = $this->qstr($constr[0]);
  1015. $rowner = $this->qstr($constr[1]);
  1016. $rcons = $this->qstr($constr[2]);
  1017. $cols = $this->GetArray("select column_name from {$tabp}cons_columns where constraint_name=$cons $owner order by position");
  1018. $tabcol = $this->GetArray("select table_name,column_name from {$tabp}cons_columns where owner=$rowner and constraint_name=$rcons order by position");
  1019. if ($cols && $tabcol)
  1020. for ($i=0, $max=sizeof($cols); $i < $max; $i++) {
  1021. $arr[$tabcol[$i][0]] = $cols[$i][0].'='.$tabcol[$i][1];
  1022. }
  1023. }
  1024. $ADODB_FETCH_MODE = $save;
  1025. return $arr;
  1026. }
  1027. function CharMax()
  1028. {
  1029. return 4000;
  1030. }
  1031. function TextMax()
  1032. {
  1033. return 4000;
  1034. }
  1035. /**
  1036. * Quotes a string.
  1037. * An example is $db->qstr("Don't bother",magic_quotes_runtime());
  1038. *
  1039. * @param s the string to quote
  1040. * @param [magic_quotes] if $s is GET/POST var, set to get_magic_quotes_gpc().
  1041. * This undoes the stupidity of magic quotes for GPC.
  1042. *
  1043. * @return quoted string to be sent back to database
  1044. */
  1045. function qstr($s,$magic_quotes=false)
  1046. {
  1047. //$nofixquotes=false;
  1048. if ($this->noNullStrings && strlen($s)==0)$s = ' ';
  1049. if (!$magic_quotes) {
  1050. if ($this->replaceQuote[0] == '\\'){
  1051. $s = str_replace('\\','\\\\',$s);
  1052. }
  1053. return "'".str_replace("'",$this->replaceQuote,$s)."'";
  1054. }
  1055. // undo magic quotes for "
  1056. $s = str_replace('\\"','"',$s);
  1057. $s = str_replace('\\\\','\\',$s);
  1058. return "'".str_replace("\\'",$this->replaceQuote,$s)."'";
  1059. }
  1060. }
  1061. /*--------------------------------------------------------------------------------------
  1062. Class Name: Recordset
  1063. --------------------------------------------------------------------------------------*/
  1064. class ADORecordset_oci8 extends ADORecordSet {
  1065. var $databaseType = 'oci8';
  1066. var $bind=false;
  1067. var $_fieldobjs;
  1068. //var $_arr = false;
  1069. function ADORecordset_oci8($queryID,$mode=false)
  1070. {
  1071. if ($mode === false) {
  1072. global $ADODB_FETCH_MODE;
  1073. $mode = $ADODB_FETCH_MODE;
  1074. }
  1075. switch ($mode)
  1076. {
  1077. case ADODB_FETCH_ASSOC:$this->fetchMode = OCI_ASSOC+OCI_RETURN_NULLS+OCI_RETURN_LOBS; break;
  1078. case ADODB_FETCH_DEFAULT:
  1079. case ADODB_FETCH_BOTH:$this->fetchMode = OCI_NUM+OCI_ASSOC+OCI_RETURN_NULLS+OCI_RETURN_LOBS; break;
  1080. case ADODB_FETCH_NUM:
  1081. default:
  1082. $this->fetchMode = OCI_NUM+OCI_RETURN_NULLS+OCI_RETURN_LOBS; break;
  1083. }
  1084. $this->adodbFetchMode = $mode;
  1085. $this->_queryID = $queryID;
  1086. }
  1087. function Init()
  1088. {
  1089. if ($this->_inited) return;
  1090. $this->_inited = true;
  1091. if ($this->_queryID) {
  1092. $this->_currentRow = 0;
  1093. @$this->_initrs();
  1094. $this->EOF = !$this->_fetch();
  1095. /*
  1096. // based on idea by Gaetano Giunta to detect unusual oracle errors
  1097. // see http://phplens.com/lens/lensforum/msgs.php?id=6771
  1098. $err = OCIError($this->_queryID);
  1099. if ($err && $this->connection->debug) ADOConnection::outp($err);
  1100. */
  1101. if (!is_array($this->fields)) {
  1102. $this->_numOfRows = 0;
  1103. $this->fields = array();
  1104. }
  1105. } else {
  1106. $this->fields = array();
  1107. $this->_numOfRows = 0;
  1108. $this->_numOfFields = 0;
  1109. $this->EOF = true;
  1110. }
  1111. }
  1112. function _initrs()
  1113. {
  1114. $this->_numOfRows = -1;
  1115. $this->_numOfFields = OCInumcols($this->_queryID);
  1116. if ($this->_numOfFields>0) {
  1117. $this->_fieldobjs = array();
  1118. $max = $this->_numOfFields;
  1119. for ($i=0;$i<$max; $i++) $this->_fieldobjs[] = $this->_FetchField($i);
  1120. }
  1121. }
  1122. /* Returns: an object containing field information.
  1123. Get column information in the Recordset object. fetchField() can be used in order to obtain information about
  1124. fields in a certain query result. If the field offset isn't specified, the next field that wasn't yet retrieved by
  1125. fetchField() is retrieved. */
  1126. function _FetchField($fieldOffset = -1)
  1127. {
  1128. $fld = new ADOFieldObject;
  1129. $fieldOffset += 1;
  1130. $fld->name =OCIcolumnname($this->_queryID, $fieldOffset);
  1131. $fld->type = OCIcolumntype($this->_queryID, $fieldOffset);
  1132. $fld->max_length = OCIcolumnsize($this->_queryID, $fieldOffset);
  1133. switch($fld->type) {
  1134. case 'NUMBER':
  1135. $p = OCIColumnPrecision($this->_queryID, $fieldOffset);
  1136. $sc = OCIColumnScale($this->_queryID, $fieldOffset);
  1137. if ($p != 0 && $sc == 0) $fld->type = 'INT';
  1138. break;
  1139. case 'CLOB':
  1140. case 'NCLOB':
  1141. case 'BLOB':
  1142. $fld->max_length = -1;
  1143. break;
  1144. }
  1145. return $fld;
  1146. }
  1147. /* For some reason, OCIcolumnname fails when called after _initrs() so we cache it */
  1148. function FetchField($fieldOffset = -1)
  1149. {
  1150. return $this->_fieldobjs[$fieldOffset];
  1151. }
  1152. /*
  1153. // 10% speedup to move MoveNext to child class
  1154. function _MoveNext()
  1155. {
  1156. //global $ADODB_EXTENSION;if ($ADODB_EXTENSION) return @adodb_movenext($this);
  1157. if ($this->EOF) return false;
  1158. $this->_currentRow++;
  1159. if(@OCIfetchinto($this->_queryID,$this->fields,$this->fetchMode))
  1160. return true;
  1161. $this->EOF = true;
  1162. return false;
  1163. } */
  1164. function MoveNext()
  1165. {
  1166. if (@OCIfetchinto($this->_queryID,$this->fields,$this->fetchMode)) {
  1167. $this->_currentRow += 1;
  1168. return true;
  1169. }
  1170. if (!$this->EOF) {
  1171. $this->_currentRow += 1;
  1172. $this->EOF = true;
  1173. }
  1174. return false;
  1175. }
  1176. /*
  1177. # does not work as first record is retrieved in _initrs(), so is not included in GetArray()
  1178. function GetArray($nRows = -1)
  1179. {
  1180. global $ADODB_OCI8_GETARRAY;
  1181. if (true || !empty($ADODB_OCI8_GETARRAY)) {
  1182. # does not support $ADODB_ANSI_PADDING_OFF
  1183. //OCI_RETURN_NULLS and OCI_RETURN_LOBS is set by OCIfetchstatement
  1184. switch($this->adodbFetchMode) {
  1185. case ADODB_FETCH_NUM:
  1186. $ncols = @OCIfetchstatement($this->_queryID, $results, 0, $nRows, OCI_FETCHSTATEMENT_BY_ROW+OCI_NUM);
  1187. $results = array_merge(array($this->fields),$results);
  1188. return $results;
  1189. case ADODB_FETCH_ASSOC:
  1190. if (ADODB_ASSOC_CASE != 2 || $this->databaseType != 'oci8') break;
  1191. $ncols = @OCIfetchstatement($this->_queryID, $assoc, 0, $nRows, OCI_FETCHSTATEMENT_BY_ROW);
  1192. $results = array_merge(array($this->fields),$assoc);
  1193. return $results;
  1194. default:
  1195. break;
  1196. }
  1197. }
  1198. $results = ADORecordSet::GetArray($nRows);
  1199. return $results;
  1200. } */
  1201. /* Optimize SelectLimit() by using OCIFetch() instead of OCIFetchInto() */
  1202. function GetArrayLimit($nrows,$offset=-1)
  1203. {
  1204. if ($offset <= 0) {
  1205. $arr = $this->GetArray($nrows);
  1206. return $arr;
  1207. }
  1208. $arr = array();
  1209. for ($i=1; $i < $offset; $i++)
  1210. if (!@OCIFetch($this->_queryID)) return $arr;
  1211. if (!@OCIfetchinto($this->_queryID,$this->fields,$this->fetchMode)) return $arr;;
  1212. $results = array();
  1213. $cnt = 0;
  1214. while (!$this->EOF && $nrows != $cnt) {
  1215. $results[$cnt++] = $this->fields;
  1216. $this->MoveNext();
  1217. }
  1218. return $results;
  1219. }
  1220. /* Use associative array to get fields array */
  1221. function Fields($colname)
  1222. {
  1223. if (!$this->bind) {
  1224. $this->bind = array();
  1225. for ($i=0; $i < $this->_numOfFields; $i++) {
  1226. $o = $this->FetchField($i);
  1227. $this->bind[strtoupper($o->name)] = $i;
  1228. }
  1229. }
  1230. return $this->fields[$this->bind[strtoupper($colname)]];
  1231. }
  1232. function _seek($row)
  1233. {
  1234. return false;
  1235. }
  1236. function _fetch()
  1237. {
  1238. return @OCIfetchinto($this->_queryID,$this->fields,$this->fetchMode);
  1239. }
  1240. /* close() only needs to be called if you are worried about using too much memory while your script
  1241. is running. All associated result memory for the specified result identifier will automatically be freed. */
  1242. function _close()
  1243. {
  1244. if ($this->connection->_stmt === $this->_queryID) $this->connection->_stmt = false;
  1245. if (!empty($this->_refcursor)) {
  1246. OCIFreeCursor($this->_refcursor);
  1247. $this->_refcursor = false;
  1248. }
  1249. @OCIFreeStatement($this->_queryID);
  1250. $this->_queryID = false;
  1251. }
  1252. function MetaType($t,$len=-1)
  1253. {
  1254. if (is_object($t)) {
  1255. $fieldobj = $t;
  1256. $t = $fieldobj->type;
  1257. $len = $fieldobj->max_length;
  1258. }
  1259. switch (strtoupper($t)) {
  1260. case 'VARCHAR':
  1261. case 'VARCHAR2':
  1262. case 'CHAR':
  1263. case 'VARBINARY':
  1264. case 'BINARY':
  1265. case 'NCHAR':
  1266. case 'NVARCHAR':
  1267. case 'NVARCHAR2':
  1268. if (isset($this) && $len <= $this->blobSize) return 'C';
  1269. case 'NCLOB':
  1270. case 'LONG':
  1271. case 'LONG VARCHAR':
  1272. case 'CLOB':
  1273. return 'X';
  1274. case 'LONG RAW':
  1275. case 'LONG VARBINARY':
  1276. case 'BLOB':
  1277. return 'B';
  1278. case 'DATE':
  1279. return ($this->connection->datetime) ? 'T' : 'D';
  1280. case 'TIMESTAMP': return 'T';
  1281. case 'INT':
  1282. case 'SMALLINT':
  1283. case 'INTEGER':
  1284. return 'I';
  1285. default: return 'N';
  1286. }
  1287. }
  1288. }
  1289. class ADORecordSet_ext_oci8 extends ADORecordSet_oci8 {
  1290. function ADORecordSet_ext_oci8($queryID,$mode=false)
  1291. {
  1292. if ($mode === false) {
  1293. global $ADODB_FETCH_MODE;
  1294. $mode = $ADODB_FETCH_MODE;
  1295. }
  1296. switch ($mode)
  1297. {
  1298. case ADODB_FETCH_ASSOC:$this->fetchMode = OCI_ASSOC+OCI_RETURN_NULLS+OCI_RETURN_LOBS; break;
  1299. case ADODB_FETCH_DEFAULT:
  1300. case ADODB_FETCH_BOTH:$this->fetchMode = OCI_NUM+OCI_ASSOC+OCI_RETURN_NULLS+OCI_RETURN_LOBS; break;
  1301. case ADODB_FETCH_NUM:
  1302. default: $this->fetchMode = OCI_NUM+OCI_RETURN_NULLS+OCI_RETURN_LOBS; break;
  1303. }
  1304. $this->adodbFetchMode = $mode;
  1305. $this->_queryID = $queryID;
  1306. }
  1307. function MoveNext()
  1308. {
  1309. return adodb_movenext($this);
  1310. }
  1311. }
  1312. ?>