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

/lib/ext/adodb_5.18a/drivers/adodb-oci8.inc.php

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