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

/concreteOLD/libraries/3rdparty/adodb/drivers/adodb-oci8.inc.php

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