Differences Between: [Versions 310 and 400] [Versions 311 and 400] [Versions 39 and 400] [Versions 400 and 401] [Versions 400 and 402] [Versions 400 and 403]
1 <?php 2 /** 3 * FileDescription 4 * 5 * This file is part of ADOdb, a Database Abstraction Layer library for PHP. 6 * 7 * @package ADOdb 8 * @link https://adodb.org Project's web site and documentation 9 * @link https://github.com/ADOdb/ADOdb Source code and issue tracker 10 * 11 * The ADOdb Library is dual-licensed, released under both the BSD 3-Clause 12 * and the GNU Lesser General Public Licence (LGPL) v2.1 or, at your option, 13 * any later version. This means you can use it in proprietary products. 14 * See the LICENSE.md file distributed with this source code for details. 15 * @license BSD-3-Clause 16 * @license LGPL-2.1-or-later 17 * 18 * @copyright 2000-2013 John Lim 19 * @copyright 2014 Damien Regad, Mark Newnham and the ADOdb community 20 * @author John Lim 21 * @author George Fourlanos <fou@infomap.gr> 22 */ 23 24 // security - hide paths 25 if (!defined('ADODB_DIR')) die(); 26 27 /* 28 NLS_Date_Format 29 Allows you to use a date format other than the Oracle Lite default. When a literal 30 character string appears where a date value is expected, the Oracle Lite database 31 tests the string to see if it matches the formats of Oracle, SQL-92, or the value 32 specified for this parameter in the POLITE.INI file. Setting this parameter also 33 defines the default format used in the TO_CHAR or TO_DATE functions when no 34 other format string is supplied. 35 36 For Oracle the default is dd-mon-yy or dd-mon-yyyy, and for SQL-92 the default is 37 yy-mm-dd or yyyy-mm-dd. 38 39 Using 'RR' in the format forces two-digit years less than or equal to 49 to be 40 interpreted as years in the 21st century (2000-2049), and years over 50 as years in 41 the 20th century (1950-1999). Setting the RR format as the default for all two-digit 42 year entries allows you to become year-2000 compliant. For example: 43 NLS_DATE_FORMAT='RR-MM-DD' 44 45 You can also modify the date format using the ALTER SESSION command. 46 */ 47 48 # define the LOB descriptor type for the given type 49 # returns false if no LOB descriptor 50 function oci_lob_desc($type) { 51 switch ($type) { 52 case OCI_B_BFILE: return OCI_D_FILE; 53 case OCI_B_CFILEE: return OCI_D_FILE; 54 case OCI_B_CLOB: return OCI_D_LOB; 55 case OCI_B_BLOB: return OCI_D_LOB; 56 case OCI_B_ROWID: return OCI_D_ROWID; 57 } 58 return false; 59 } 60 61 class ADODB_oci8 extends ADOConnection { 62 var $databaseType = 'oci8'; 63 var $dataProvider = 'oci8'; 64 var $replaceQuote = "''"; // string to use to replace quotes 65 var $concat_operator='||'; 66 var $sysDate = "TRUNC(SYSDATE)"; 67 var $sysTimeStamp = 'SYSDATE'; // requires oracle 9 or later, otherwise use SYSDATE 68 var $metaDatabasesSQL = "SELECT USERNAME FROM ALL_USERS WHERE USERNAME NOT IN ('SYS','SYSTEM','DBSNMP','OUTLN') ORDER BY 1"; 69 var $_stmt; 70 var $_commit = OCI_COMMIT_ON_SUCCESS; 71 var $_initdate = true; // init date to YYYY-MM-DD 72 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 73 var $metaColumnsSQL = "select cname,coltype,width, SCALE, PRECISION, NULLS, DEFAULTVAL from col where tname='%s' order by colno"; //changed by smondino@users.sourceforge. net 74 var $metaColumnsSQL2 = "select column_name,data_type,data_length, data_scale, data_precision, 75 case when nullable = 'Y' then 'NULL' 76 else 'NOT NULL' end as nulls, 77 data_default from all_tab_cols 78 where owner='%s' and table_name='%s' order by column_id"; // when there is a schema 79 var $_bindInputArray = true; 80 var $hasGenID = true; 81 var $_genIDSQL = "SELECT (%s.nextval) FROM DUAL"; 82 var $_genSeqSQL = " 83 DECLARE 84 PRAGMA AUTONOMOUS_TRANSACTION; 85 BEGIN 86 execute immediate 'CREATE SEQUENCE %s START WITH %s'; 87 END; 88 "; 89 90 var $_dropSeqSQL = "DROP SEQUENCE %s"; 91 var $hasAffectedRows = true; 92 var $random = "abs(mod(DBMS_RANDOM.RANDOM,10000001)/10000000)"; 93 var $noNullStrings = false; 94 var $connectSID = false; 95 var $_bind = false; 96 var $_nestedSQL = true; 97 var $_getarray = false; // currently not working 98 var $leftOuter = ''; // oracle wierdness, $col = $value (+) for LEFT OUTER, $col (+)= $value for RIGHT OUTER 99 var $session_sharing_force_blob = false; // alter session on updateblob if set to true 100 var $firstrows = true; // enable first rows optimization on SelectLimit() 101 var $selectOffsetAlg1 = 1000; // when to use 1st algorithm of selectlimit. 102 var $NLS_DATE_FORMAT = 'YYYY-MM-DD'; // To include time, use 'RRRR-MM-DD HH24:MI:SS' 103 var $dateformat = 'YYYY-MM-DD'; // DBDate format 104 var $useDBDateFormatForTextInput=false; 105 var $datetime = false; // MetaType('DATE') returns 'D' (datetime==false) or 'T' (datetime == true) 106 var $_refLOBs = array(); 107 108 // var $ansiOuter = true; // if oracle9 109 110 /* 111 * Legacy compatibility for sequence names for emulated auto-increments 112 */ 113 public $useCompactAutoIncrements = false; 114 115 /* 116 * Defines the schema name for emulated auto-increment columns 117 */ 118 public $schema = false; 119 120 /* 121 * Defines the prefix for emulated auto-increment columns 122 */ 123 public $seqPrefix = 'SEQ_'; 124 125 /* function MetaColumns($table, $normalize=true) added by smondino@users.sourceforge.net*/ 126 function MetaColumns($table, $normalize=true) 127 { 128 global $ADODB_FETCH_MODE; 129 130 $schema = ''; 131 $this->_findschema($table, $schema); 132 133 $save = $ADODB_FETCH_MODE; 134 $ADODB_FETCH_MODE = ADODB_FETCH_NUM; 135 if ($this->fetchMode !== false) { 136 $savem = $this->SetFetchMode(false); 137 } 138 139 if ($schema){ 140 $rs = $this->Execute(sprintf($this->metaColumnsSQL2, strtoupper($schema), strtoupper($table))); 141 } 142 else { 143 $rs = $this->Execute(sprintf($this->metaColumnsSQL,strtoupper($table))); 144 } 145 146 if (isset($savem)) { 147 $this->SetFetchMode($savem); 148 } 149 $ADODB_FETCH_MODE = $save; 150 if (!$rs) { 151 return false; 152 } 153 $retarr = array(); 154 while (!$rs->EOF) { 155 $fld = new ADOFieldObject(); 156 $fld->name = $rs->fields[0]; 157 $fld->type = $rs->fields[1]; 158 $fld->max_length = $rs->fields[2]; 159 $fld->scale = $rs->fields[3]; 160 if ($rs->fields[1] == 'NUMBER') { 161 if ($rs->fields[3] == 0) { 162 $fld->type = 'INT'; 163 } 164 $fld->max_length = $rs->fields[4]; 165 } 166 $fld->not_null = (strncmp($rs->fields[5], 'NOT',3) === 0); 167 $fld->binary = (strpos($fld->type,'BLOB') !== false); 168 $fld->default_value = $rs->fields[6]; 169 170 if ($ADODB_FETCH_MODE == ADODB_FETCH_NUM) { 171 $retarr[] = $fld; 172 } 173 else { 174 $retarr[strtoupper($fld->name)] = $fld; 175 } 176 $rs->MoveNext(); 177 } 178 $rs->Close(); 179 if (empty($retarr)) { 180 return false; 181 } 182 return $retarr; 183 } 184 185 function Time() 186 { 187 $rs = $this->Execute("select TO_CHAR($this->sysTimeStamp,'YYYY-MM-DD HH24:MI:SS') from dual"); 188 if ($rs && !$rs->EOF) { 189 return $this->UnixTimeStamp(reset($rs->fields)); 190 } 191 192 return false; 193 } 194 195 /** 196 * Multiple modes of connection are supported: 197 * 198 * a. Local Database 199 * $conn->Connect(false,'scott','tiger'); 200 * 201 * b. From tnsnames.ora 202 * $conn->Connect($tnsname,'scott','tiger'); 203 * $conn->Connect(false,'scott','tiger',$tnsname); 204 * 205 * c. Server + service name 206 * $conn->Connect($serveraddress,'scott,'tiger',$service_name); 207 * 208 * d. Server + SID 209 * $conn->connectSID = true; 210 * $conn->Connect($serveraddress,'scott,'tiger',$SID); 211 * 212 * @param string|false $argHostname DB server hostname or TNS name 213 * @param string $argUsername 214 * @param string $argPassword 215 * @param string $argDatabasename Service name, SID (defaults to null) 216 * @param int $mode Connection mode, defaults to 0 217 * (0 = non-persistent, 1 = persistent, 2 = force new connection) 218 * 219 * @return bool 220 */ 221 function _connect($argHostname, $argUsername, $argPassword, $argDatabasename=null, $mode=0) 222 { 223 if (!function_exists('oci_pconnect')) { 224 return null; 225 } 226 #adodb_backtrace(); 227 228 $this->_errorMsg = false; 229 $this->_errorCode = false; 230 231 if($argHostname) { // added by Jorma Tuomainen <jorma.tuomainen@ppoy.fi> 232 if (empty($argDatabasename)) { 233 $argDatabasename = $argHostname; 234 } 235 else { 236 if(strpos($argHostname,":")) { 237 $argHostinfo=explode(":",$argHostname); 238 $argHostname=$argHostinfo[0]; 239 $argHostport=$argHostinfo[1]; 240 } else { 241 $argHostport = empty($this->port)? "1521" : $this->port; 242 } 243 244 if (strncasecmp($argDatabasename,'SID=',4) == 0) { 245 $argDatabasename = substr($argDatabasename,4); 246 $this->connectSID = true; 247 } 248 249 if ($this->connectSID) { 250 $argDatabasename="(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=".$argHostname 251 .")(PORT=$argHostport))(CONNECT_DATA=(SID=$argDatabasename)))"; 252 } else 253 $argDatabasename="(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=".$argHostname 254 .")(PORT=$argHostport))(CONNECT_DATA=(SERVICE_NAME=$argDatabasename)))"; 255 } 256 } 257 258 //if ($argHostname) print "<p>Connect: 1st argument should be left blank for $this->databaseType</p>"; 259 if ($mode==1) { 260 $this->_connectionID = ($this->charSet) 261 ? oci_pconnect($argUsername,$argPassword, $argDatabasename,$this->charSet) 262 : oci_pconnect($argUsername,$argPassword, $argDatabasename); 263 if ($this->_connectionID && $this->autoRollback) { 264 oci_rollback($this->_connectionID); 265 } 266 } else if ($mode==2) { 267 $this->_connectionID = ($this->charSet) 268 ? oci_new_connect($argUsername,$argPassword, $argDatabasename,$this->charSet) 269 : oci_new_connect($argUsername,$argPassword, $argDatabasename); 270 } else { 271 $this->_connectionID = ($this->charSet) 272 ? oci_connect($argUsername,$argPassword, $argDatabasename,$this->charSet) 273 : oci_connect($argUsername,$argPassword, $argDatabasename); 274 } 275 if (!$this->_connectionID) { 276 return false; 277 } 278 279 if ($this->_initdate) { 280 $this->Execute("ALTER SESSION SET NLS_DATE_FORMAT='".$this->NLS_DATE_FORMAT."'"); 281 } 282 283 // looks like: 284 // Oracle8i Enterprise Edition Release 8.1.7.0.0 - Production With the Partitioning option JServer Release 8.1.7.0.0 - Production 285 // $vers = oci_server_version($this->_connectionID); 286 // if (strpos($vers,'8i') !== false) $this->ansiOuter = true; 287 return true; 288 } 289 290 function ServerInfo() 291 { 292 $arr['compat'] = $this->GetOne('select value from sys.database_compatible_level'); 293 $arr['description'] = @oci_server_version($this->_connectionID); 294 $arr['version'] = ADOConnection::_findvers($arr['description']); 295 return $arr; 296 } 297 // returns true or false 298 function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename) 299 { 300 return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabasename,1); 301 } 302 303 // returns true or false 304 function _nconnect($argHostname, $argUsername, $argPassword, $argDatabasename) 305 { 306 return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabasename,2); 307 } 308 309 function _affectedrows() 310 { 311 if (is_resource($this->_stmt)) { 312 return @oci_num_rows($this->_stmt); 313 } 314 return 0; 315 } 316 317 function IfNull( $field, $ifNull ) 318 { 319 return " NVL($field, $ifNull) "; // if Oracle 320 } 321 322 protected function _insertID($table = '', $column = '') 323 { 324 325 if (!$this->seqField) 326 return false; 327 328 if ($this->schema) 329 { 330 $t = strpos($table,'.'); 331 if ($t !== false) 332 $tab = substr($table,$t+1); 333 else 334 $tab = $table; 335 336 if ($this->useCompactAutoIncrements) 337 $tab = sprintf('%u',crc32(strtolower($tab))); 338 339 $seqname = $this->schema.'.'.$this->seqPrefix.$tab; 340 } 341 else 342 { 343 if ($this->useCompactAutoIncrements) 344 $table = sprintf('%u',crc32(strtolower($table))); 345 346 $seqname = $this->seqPrefix.$table; 347 } 348 349 if (strlen($seqname) > 30) 350 /* 351 * We cannot successfully identify the sequence 352 */ 353 return false; 354 355 return $this->getOne("SELECT $seqname.currval FROM dual"); 356 } 357 358 // format and return date string in database date format 359 function DBDate($d,$isfld=false) 360 { 361 if (empty($d) && $d !== 0) { 362 return 'null'; 363 } 364 365 if ($isfld) { 366 $d = _adodb_safedate($d); 367 return 'TO_DATE('.$d.",'".$this->dateformat."')"; 368 } 369 370 if (is_string($d)) { 371 $d = ADORecordSet::UnixDate($d); 372 } 373 374 if (is_object($d)) { 375 $ds = $d->format($this->fmtDate); 376 } 377 else { 378 $ds = adodb_date($this->fmtDate,$d); 379 } 380 381 return "TO_DATE(".$ds.",'".$this->dateformat."')"; 382 } 383 384 function BindDate($d) 385 { 386 $d = ADOConnection::DBDate($d); 387 if (strncmp($d, "'", 1)) { 388 return $d; 389 } 390 391 return substr($d, 1, strlen($d)-2); 392 } 393 394 function BindTimeStamp($ts) 395 { 396 if (empty($ts) && $ts !== 0) { 397 return 'null'; 398 } 399 if (is_string($ts)) { 400 $ts = ADORecordSet::UnixTimeStamp($ts); 401 } 402 403 if (is_object($ts)) { 404 $tss = $ts->format("'Y-m-d H:i:s'"); 405 } 406 else { 407 $tss = adodb_date("'Y-m-d H:i:s'",$ts); 408 } 409 410 return $tss; 411 } 412 413 // format and return date string in database timestamp format 414 function DBTimeStamp($ts,$isfld=false) 415 { 416 if (empty($ts) && $ts !== 0) { 417 return 'null'; 418 } 419 if ($isfld) { 420 return 'TO_DATE(substr('.$ts.",1,19),'RRRR-MM-DD, HH24:MI:SS')"; 421 } 422 if (is_string($ts)) { 423 $ts = ADORecordSet::UnixTimeStamp($ts); 424 } 425 426 if (is_object($ts)) { 427 $tss = $ts->format("'Y-m-d H:i:s'"); 428 } 429 else { 430 $tss = date("'Y-m-d H:i:s'",$ts); 431 } 432 433 return 'TO_DATE('.$tss.",'RRRR-MM-DD, HH24:MI:SS')"; 434 } 435 436 function RowLock($tables,$where,$col='1 as adodbignore') 437 { 438 if ($this->autoCommit) { 439 $this->BeginTrans(); 440 } 441 return $this->GetOne("select $col from $tables where $where for update"); 442 } 443 444 function MetaTables($ttype=false,$showSchema=false,$mask=false) 445 { 446 if ($mask) { 447 $save = $this->metaTablesSQL; 448 $mask = $this->qstr(strtoupper($mask)); 449 $this->metaTablesSQL .= " AND upper(table_name) like $mask"; 450 } 451 $ret = ADOConnection::MetaTables($ttype,$showSchema); 452 453 if ($mask) { 454 $this->metaTablesSQL = $save; 455 } 456 return $ret; 457 } 458 459 // Mark Newnham 460 function MetaIndexes ($table, $primary = FALSE, $owner=false) 461 { 462 // save old fetch mode 463 global $ADODB_FETCH_MODE; 464 465 $save = $ADODB_FETCH_MODE; 466 $ADODB_FETCH_MODE = ADODB_FETCH_NUM; 467 468 if ($this->fetchMode !== FALSE) { 469 $savem = $this->SetFetchMode(FALSE); 470 } 471 472 // get index details 473 $table = strtoupper($table); 474 475 // get Primary index 476 $primary_key = ''; 477 478 $rs = $this->Execute(sprintf("SELECT * FROM ALL_CONSTRAINTS WHERE UPPER(TABLE_NAME)='%s' AND CONSTRAINT_TYPE='P'",$table)); 479 if (!is_object($rs)) { 480 if (isset($savem)) { 481 $this->SetFetchMode($savem); 482 } 483 $ADODB_FETCH_MODE = $save; 484 return false; 485 } 486 487 if ($row = $rs->FetchRow()) { 488 $primary_key = $row[1]; //constraint_name 489 } 490 491 if ($primary==TRUE && $primary_key=='') { 492 if (isset($savem)) { 493 $this->SetFetchMode($savem); 494 } 495 $ADODB_FETCH_MODE = $save; 496 return false; //There is no primary key 497 } 498 499 $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)); 500 501 502 if (!is_object($rs)) { 503 if (isset($savem)) { 504 $this->SetFetchMode($savem); 505 } 506 $ADODB_FETCH_MODE = $save; 507 return false; 508 } 509 510 $indexes = array (); 511 // parse index data into array 512 513 while ($row = $rs->FetchRow()) { 514 if ($primary && $row[0] != $primary_key) { 515 continue; 516 } 517 if (!isset($indexes[$row[0]])) { 518 $indexes[$row[0]] = array( 519 'unique' => ($row[1] == 'UNIQUE'), 520 'columns' => array() 521 ); 522 } 523 $indexes[$row[0]]['columns'][$row[2] - 1] = $row[3]; 524 } 525 526 // sort columns by order in the index 527 foreach ( array_keys ($indexes) as $index ) { 528 ksort ($indexes[$index]['columns']); 529 } 530 531 if (isset($savem)) { 532 $this->SetFetchMode($savem); 533 $ADODB_FETCH_MODE = $save; 534 } 535 return $indexes; 536 } 537 538 function BeginTrans() 539 { 540 if ($this->transOff) { 541 return true; 542 } 543 $this->transCnt += 1; 544 $this->autoCommit = false; 545 $this->_commit = OCI_DEFAULT; 546 547 if ($this->_transmode) { 548 $ok = $this->Execute("SET TRANSACTION ".$this->_transmode); 549 } 550 else { 551 $ok = true; 552 } 553 554 return $ok ? true : false; 555 } 556 557 function CommitTrans($ok=true) 558 { 559 if ($this->transOff) { 560 return true; 561 } 562 if (!$ok) { 563 return $this->RollbackTrans(); 564 } 565 566 if ($this->transCnt) { 567 $this->transCnt -= 1; 568 } 569 $ret = oci_commit($this->_connectionID); 570 $this->_commit = OCI_COMMIT_ON_SUCCESS; 571 $this->autoCommit = true; 572 return $ret; 573 } 574 575 function RollbackTrans() 576 { 577 if ($this->transOff) { 578 return true; 579 } 580 if ($this->transCnt) { 581 $this->transCnt -= 1; 582 } 583 $ret = oci_rollback($this->_connectionID); 584 $this->_commit = OCI_COMMIT_ON_SUCCESS; 585 $this->autoCommit = true; 586 return $ret; 587 } 588 589 590 function SelectDB($dbName) 591 { 592 return false; 593 } 594 595 function ErrorMsg() 596 { 597 if ($this->_errorMsg !== false) { 598 return $this->_errorMsg; 599 } 600 601 if (is_resource($this->_stmt)) { 602 $arr = @oci_error($this->_stmt); 603 } 604 if (empty($arr)) { 605 if (is_resource($this->_connectionID)) { 606 $arr = @oci_error($this->_connectionID); 607 } 608 else { 609 $arr = @oci_error(); 610 } 611 if ($arr === false) { 612 return ''; 613 } 614 } 615 $this->_errorMsg = $arr['message']; 616 $this->_errorCode = $arr['code']; 617 return $this->_errorMsg; 618 } 619 620 function ErrorNo() 621 { 622 if ($this->_errorCode !== false) { 623 return $this->_errorCode; 624 } 625 626 if (is_resource($this->_stmt)) { 627 $arr = @oci_error($this->_stmt); 628 } 629 if (empty($arr)) { 630 $arr = @oci_error($this->_connectionID); 631 if ($arr == false) { 632 $arr = @oci_error(); 633 } 634 if ($arr == false) { 635 return ''; 636 } 637 } 638 639 $this->_errorMsg = $arr['message']; 640 $this->_errorCode = $arr['code']; 641 642 return $arr['code']; 643 } 644 645 /** 646 * Format date column in sql string given an input format that understands Y M D 647 */ 648 function SQLDate($fmt, $col=false) 649 { 650 if (!$col) { 651 $col = $this->sysTimeStamp; 652 } 653 $s = 'TO_CHAR('.$col.",'"; 654 655 $len = strlen($fmt); 656 for ($i=0; $i < $len; $i++) { 657 $ch = $fmt[$i]; 658 switch($ch) { 659 case 'Y': 660 case 'y': 661 $s .= 'YYYY'; 662 break; 663 case 'Q': 664 case 'q': 665 $s .= 'Q'; 666 break; 667 668 case 'M': 669 $s .= 'Mon'; 670 break; 671 672 case 'm': 673 $s .= 'MM'; 674 break; 675 case 'D': 676 case 'd': 677 $s .= 'DD'; 678 break; 679 680 case 'H': 681 $s.= 'HH24'; 682 break; 683 684 case 'h': 685 $s .= 'HH'; 686 break; 687 688 case 'i': 689 $s .= 'MI'; 690 break; 691 692 case 's': 693 $s .= 'SS'; 694 break; 695 696 case 'a': 697 case 'A': 698 $s .= 'AM'; 699 break; 700 701 case 'w': 702 $s .= 'D'; 703 break; 704 705 case 'l': 706 $s .= 'DAY'; 707 break; 708 709 case 'W': 710 $s .= 'WW'; 711 break; 712 713 default: 714 // handle escape characters... 715 if ($ch == '\\') { 716 $i++; 717 $ch = substr($fmt,$i,1); 718 } 719 if (strpos('-/.:;, ',$ch) !== false) { 720 $s .= $ch; 721 } 722 else { 723 $s .= '"'.$ch.'"'; 724 } 725 726 } 727 } 728 return $s. "')"; 729 } 730 731 function GetRandRow($sql, $arr = false) 732 { 733 $sql = "SELECT * FROM ($sql ORDER BY dbms_random.value) WHERE rownum = 1"; 734 735 return $this->GetRow($sql,$arr); 736 } 737 738 /** 739 * This algorithm makes use of 740 * 741 * a. FIRST_ROWS hint 742 * The FIRST_ROWS hint explicitly chooses the approach to optimize response 743 * time, that is, minimum resource usage to return the first row. Results 744 * will be returned as soon as they are identified. 745 * 746 * b. Uses rownum tricks to obtain only the required rows from a given offset. 747 * As this uses complicated sql statements, we only use this if $offset >= 100. 748 * This idea by Tomas V V Cox. 749 * 750 * This implementation does not appear to work with oracle 8.0.5 or earlier. 751 * Comment out this function then, and the slower SelectLimit() in the base 752 * class will be used. 753 * 754 * Note: FIRST_ROWS hinting is only used if $sql is a string; when 755 * processing a prepared statement's handle, no hinting is performed. 756 */ 757 function SelectLimit($sql,$nrows=-1,$offset=-1, $inputarr=false,$secs2cache=0) 758 { 759 $nrows = (int) $nrows; 760 $offset = (int) $offset; 761 // Since the methods used to limit the number of returned rows rely 762 // on modifying the provided SQL query, we can't work with prepared 763 // statements so we just extract the SQL string. 764 if(is_array($sql)) { 765 $sql = $sql[0]; 766 } 767 768 // seems that oracle only supports 1 hint comment in 8i 769 if ($this->firstrows) { 770 if ($nrows > 500 && $nrows < 1000) { 771 $hint = "FIRST_ROWS($nrows)"; 772 } 773 else { 774 $hint = 'FIRST_ROWS'; 775 } 776 777 if (strpos($sql,'/*+') !== false) { 778 $sql = str_replace('/*+ ',"/*+$hint ",$sql); 779 } 780 else { 781 $sql = preg_replace('/^[ \t\n]*select/i',"SELECT /*+$hint*/",$sql); 782 } 783 $hint = "/*+ $hint */"; 784 } else { 785 $hint = ''; 786 } 787 788 if ($offset == -1 || ($offset < $this->selectOffsetAlg1 && 0 < $nrows && $nrows < 1000)) { 789 if ($nrows > 0) { 790 if ($offset > 0) { 791 $nrows += $offset; 792 } 793 $sql = "select * from (".$sql.") where rownum <= :adodb_offset"; 794 $inputarr['adodb_offset'] = $nrows; 795 $nrows = -1; 796 } 797 // note that $nrows = 0 still has to work ==> no rows returned 798 799 return ADOConnection::SelectLimit($sql, $nrows, $offset, $inputarr, $secs2cache); 800 } else { 801 // Algorithm by Tomas V V Cox, from PEAR DB oci8.php 802 803 // Let Oracle return the name of the columns 804 $q_fields = "SELECT * FROM (".$sql.") WHERE NULL = NULL"; 805 806 if (! $stmt_arr = $this->Prepare($q_fields)) { 807 return false; 808 } 809 $stmt = $stmt_arr[1]; 810 811 if (is_array($inputarr)) { 812 foreach($inputarr as $k => $v) { 813 $i=0; 814 if ($this->databaseType == 'oci8po') { 815 $bv_name = ":".$i++; 816 } else { 817 $bv_name = ":".$k; 818 } 819 if (is_array($v)) { 820 // suggested by g.giunta@libero. 821 if (sizeof($v) == 2) { 822 oci_bind_by_name($stmt,$bv_name,$inputarr[$k][0],$v[1]); 823 } 824 else { 825 oci_bind_by_name($stmt,$bv_name,$inputarr[$k][0],$v[1],$v[2]); 826 } 827 } else { 828 $len = -1; 829 if ($v === ' ') { 830 $len = 1; 831 } 832 if (isset($bindarr)) { // is prepared sql, so no need to oci_bind_by_name again 833 $bindarr[$k] = $v; 834 } else { // dynamic sql, so rebind every time 835 oci_bind_by_name($stmt,$bv_name,$inputarr[$k],$len); 836 } 837 } 838 } 839 } 840 841 if (!oci_execute($stmt, OCI_DEFAULT)) { 842 oci_free_statement($stmt); 843 return false; 844 } 845 846 $ncols = oci_num_fields($stmt); 847 for ( $i = 1; $i <= $ncols; $i++ ) { 848 $cols[] = '"'.oci_field_name($stmt, $i).'"'; 849 } 850 $result = false; 851 852 oci_free_statement($stmt); 853 $fields = implode(',', $cols); 854 if ($nrows <= 0) { 855 $nrows = 999999999999; 856 } 857 else { 858 $nrows += $offset; 859 } 860 $offset += 1; // in Oracle rownum starts at 1 861 862 $sql = "SELECT $hint $fields FROM". 863 "(SELECT rownum as adodb_rownum, $fields FROM". 864 " ($sql) WHERE rownum <= :adodb_nrows". 865 ") WHERE adodb_rownum >= :adodb_offset"; 866 $inputarr['adodb_nrows'] = $nrows; 867 $inputarr['adodb_offset'] = $offset; 868 869 if ($secs2cache > 0) { 870 $rs = $this->CacheExecute($secs2cache, $sql,$inputarr); 871 } 872 else { 873 $rs = $this->Execute($sql, $inputarr); 874 } 875 return $rs; 876 } 877 } 878 879 /** 880 * Usage: 881 * Store BLOBs and CLOBs 882 * 883 * Example: to store $var in a blob 884 * $conn->Execute('insert into TABLE (id,ablob) values(12,empty_blob())'); 885 * $conn->UpdateBlob('TABLE', 'ablob', $varHoldingBlob, 'ID=12', 'BLOB'); 886 * 887 * $blobtype supports 'BLOB' and 'CLOB', but you need to change to 'empty_clob()'. 888 * 889 * to get length of LOB: 890 * select DBMS_LOB.GETLENGTH(ablob) from TABLE 891 * 892 * If you are using CURSOR_SHARING = force, it appears this will case a segfault 893 * under oracle 8.1.7.0. Run: 894 * $db->Execute('ALTER SESSION SET CURSOR_SHARING=EXACT'); 895 * before UpdateBlob() then... 896 */ 897 function UpdateBlob($table,$column,$val,$where,$blobtype='BLOB') 898 { 899 900 //if (strlen($val) < 4000) return $this->Execute("UPDATE $table SET $column=:blob WHERE $where",array('blob'=>$val)) != false; 901 902 switch(strtoupper($blobtype)) { 903 default: ADOConnection::outp("<b>UpdateBlob</b>: Unknown blobtype=$blobtype"); return false; 904 case 'BLOB': $type = OCI_B_BLOB; break; 905 case 'CLOB': $type = OCI_B_CLOB; break; 906 } 907 908 if ($this->databaseType == 'oci8po') 909 $sql = "UPDATE $table set $column=EMPTY_{$blobtype}() WHERE $where RETURNING $column INTO ?"; 910 else 911 $sql = "UPDATE $table set $column=EMPTY_{$blobtype}() WHERE $where RETURNING $column INTO :blob"; 912 913 $desc = oci_new_descriptor($this->_connectionID, OCI_D_LOB); 914 $arr['blob'] = array($desc,-1,$type); 915 if ($this->session_sharing_force_blob) { 916 $this->Execute('ALTER SESSION SET CURSOR_SHARING=EXACT'); 917 } 918 $commit = $this->autoCommit; 919 if ($commit) { 920 $this->BeginTrans(); 921 } 922 $rs = $this->_Execute($sql,$arr); 923 if ($rez = !empty($rs)) { 924 $desc->save($val); 925 } 926 $desc->free(); 927 if ($commit) { 928 $this->CommitTrans(); 929 } 930 if ($this->session_sharing_force_blob) { 931 $this->Execute('ALTER SESSION SET CURSOR_SHARING=FORCE'); 932 } 933 934 if ($rez) { 935 $rs->Close(); 936 } 937 return $rez; 938 } 939 940 /** 941 * Usage: store file pointed to by $val in a blob 942 */ 943 function UpdateBlobFile($table,$column,$val,$where,$blobtype='BLOB') 944 { 945 switch(strtoupper($blobtype)) { 946 default: ADOConnection::outp( "<b>UpdateBlob</b>: Unknown blobtype=$blobtype"); return false; 947 case 'BLOB': $type = OCI_B_BLOB; break; 948 case 'CLOB': $type = OCI_B_CLOB; break; 949 } 950 951 if ($this->databaseType == 'oci8po') 952 $sql = "UPDATE $table set $column=EMPTY_{$blobtype}() WHERE $where RETURNING $column INTO ?"; 953 else 954 $sql = "UPDATE $table set $column=EMPTY_{$blobtype}() WHERE $where RETURNING $column INTO :blob"; 955 956 $desc = oci_new_descriptor($this->_connectionID, OCI_D_LOB); 957 $arr['blob'] = array($desc,-1,$type); 958 959 $this->BeginTrans(); 960 $rs = ADODB_oci8::Execute($sql,$arr); 961 if ($rez = !empty($rs)) { 962 $desc->savefile($val); 963 } 964 $desc->free(); 965 $this->CommitTrans(); 966 967 if ($rez) { 968 $rs->Close(); 969 } 970 return $rez; 971 } 972 973 /** 974 * Execute SQL 975 * 976 * @param sql SQL statement to execute, or possibly an array holding prepared statement ($sql[0] will hold sql text) 977 * @param [inputarr] holds the input data to bind to. Null elements will be set to null. 978 * @return RecordSet or false 979 */ 980 function Execute($sql,$inputarr=false) 981 { 982 if ($this->fnExecute) { 983 $fn = $this->fnExecute; 984 $ret = $fn($this,$sql,$inputarr); 985 if (isset($ret)) { 986 return $ret; 987 } 988 } 989 if ($inputarr !== false) { 990 if (!is_array($inputarr)) { 991 $inputarr = array($inputarr); 992 } 993 994 $element0 = reset($inputarr); 995 $array2d = $this->bulkBind && is_array($element0) && !is_object(reset($element0)); 996 997 # see PHPLens Issue No: 18786 998 if ($array2d || !$this->_bindInputArray) { 999 1000 # is_object check because oci8 descriptors can be passed in 1001 if ($array2d && $this->_bindInputArray) { 1002 if (is_string($sql)) { 1003 $stmt = $this->Prepare($sql); 1004 } else { 1005 $stmt = $sql; 1006 } 1007 1008 foreach($inputarr as $arr) { 1009 $ret = $this->_Execute($stmt,$arr); 1010 if (!$ret) { 1011 return $ret; 1012 } 1013 } 1014 return $ret; 1015 } else { 1016 $sqlarr = explode(':', $sql); 1017 $sql = ''; 1018 $lastnomatch = -2; 1019 #var_dump($sqlarr);echo "<hr>";var_dump($inputarr);echo"<hr>"; 1020 foreach($sqlarr as $k => $str) { 1021 if ($k == 0) { 1022 $sql = $str; 1023 continue; 1024 } 1025 // we need $lastnomatch because of the following datetime, 1026 // eg. '10:10:01', which causes code to think that there is bind param :10 and :1 1027 $ok = preg_match('/^([0-9]*)/', $str, $arr); 1028 1029 if (!$ok) { 1030 $sql .= $str; 1031 } else { 1032 $at = $arr[1]; 1033 if (isset($inputarr[$at]) || is_null($inputarr[$at])) { 1034 if ((strlen($at) == strlen($str) && $k < sizeof($arr)-1)) { 1035 $sql .= ':'.$str; 1036 $lastnomatch = $k; 1037 } else if ($lastnomatch == $k-1) { 1038 $sql .= ':'.$str; 1039 } else { 1040 if (is_null($inputarr[$at])) { 1041 $sql .= 'null'; 1042 } 1043 else { 1044 $sql .= $this->qstr($inputarr[$at]); 1045 } 1046 $sql .= substr($str, strlen($at)); 1047 } 1048 } else { 1049 $sql .= ':'.$str; 1050 } 1051 } 1052 } 1053 $inputarr = false; 1054 } 1055 } 1056 $ret = $this->_Execute($sql,$inputarr); 1057 1058 } else { 1059 $ret = $this->_Execute($sql,false); 1060 } 1061 1062 return $ret; 1063 } 1064 1065 /* 1066 * Example of usage: 1067 * $stmt = $this->Prepare('insert into emp (empno, ename) values (:empno, :ename)'); 1068 */ 1069 function Prepare($sql,$cursor=false) 1070 { 1071 static $BINDNUM = 0; 1072 1073 $stmt = oci_parse($this->_connectionID,$sql); 1074 1075 if (!$stmt) { 1076 $this->_errorMsg = false; 1077 $this->_errorCode = false; 1078 $arr = @oci_error($this->_connectionID); 1079 if ($arr === false) { 1080 return false; 1081 } 1082 1083 $this->_errorMsg = $arr['message']; 1084 $this->_errorCode = $arr['code']; 1085 return false; 1086 } 1087 1088 $BINDNUM += 1; 1089 1090 $sttype = @oci_statement_type($stmt); 1091 if ($sttype == 'BEGIN' || $sttype == 'DECLARE') { 1092 return array($sql,$stmt,0,$BINDNUM, ($cursor) ? oci_new_cursor($this->_connectionID) : false); 1093 } 1094 return array($sql,$stmt,0,$BINDNUM); 1095 } 1096 1097 /* 1098 Call an oracle stored procedure and returns a cursor variable as a recordset. 1099 Concept by Robert Tuttle robert@ud.com 1100 1101 Example: 1102 Note: we return a cursor variable in :RS2 1103 $rs = $db->ExecuteCursor("BEGIN adodb.open_tab(:RS2); END;",'RS2'); 1104 1105 $rs = $db->ExecuteCursor( 1106 "BEGIN :RS2 = adodb.getdata(:VAR1); END;", 1107 'RS2', 1108 array('VAR1' => 'Mr Bean')); 1109 1110 */ 1111 function ExecuteCursor($sql,$cursorName='rs',$params=false) 1112 { 1113 if (is_array($sql)) { 1114 $stmt = $sql; 1115 } 1116 else $stmt = ADODB_oci8::Prepare($sql,true); # true to allocate oci_new_cursor 1117 1118 if (is_array($stmt) && sizeof($stmt) >= 5) { 1119 $hasref = true; 1120 $ignoreCur = false; 1121 $this->Parameter($stmt, $ignoreCur, $cursorName, false, -1, OCI_B_CURSOR); 1122 if ($params) { 1123 foreach($params as $k => $v) { 1124 $this->Parameter($stmt,$params[$k], $k); 1125 } 1126 } 1127 } else 1128 $hasref = false; 1129 1130 $rs = $this->Execute($stmt); 1131 if ($rs) { 1132 if ($rs->databaseType == 'array') { 1133 oci_free_cursor($stmt[4]); 1134 } 1135 elseif ($hasref) { 1136 $rs->_refcursor = $stmt[4]; 1137 } 1138 } 1139 return $rs; 1140 } 1141 1142 /** 1143 * Bind a variable -- very, very fast for executing repeated statements in oracle. 1144 * 1145 * Better than using 1146 * for ($i = 0; $i < $max; $i++) { 1147 * $p1 = ?; $p2 = ?; $p3 = ?; 1148 * $this->Execute("insert into table (col0, col1, col2) values (:0, :1, :2)", array($p1,$p2,$p3)); 1149 * } 1150 * 1151 * Usage: 1152 * $stmt = $DB->Prepare("insert into table (col0, col1, col2) values (:0, :1, :2)"); 1153 * $DB->Bind($stmt, $p1); 1154 * $DB->Bind($stmt, $p2); 1155 * $DB->Bind($stmt, $p3); 1156 * for ($i = 0; $i < $max; $i++) { 1157 * $p1 = ?; $p2 = ?; $p3 = ?; 1158 * $DB->Execute($stmt); 1159 * } 1160 * 1161 * Some timings to insert 1000 records, test table has 3 cols, and 1 index. 1162 * - Time 0.6081s (1644.60 inserts/sec) with direct oci_parse/oci_execute 1163 * - Time 0.6341s (1577.16 inserts/sec) with ADOdb Prepare/Bind/Execute 1164 * - Time 1.5533s ( 643.77 inserts/sec) with pure SQL using Execute 1165 * 1166 * Now if PHP only had batch/bulk updating like Java or PL/SQL... 1167 * 1168 * Note that the order of parameters differs from oci_bind_by_name, 1169 * because we default the names to :0, :1, :2 1170 */ 1171 function Bind(&$stmt,&$var,$size=4000,$type=false,$name=false,$isOutput=false) 1172 { 1173 1174 if (!is_array($stmt)) { 1175 return false; 1176 } 1177 1178 if (($type == OCI_B_CURSOR) && sizeof($stmt) >= 5) { 1179 return oci_bind_by_name($stmt[1],":".$name,$stmt[4],$size,$type); 1180 } 1181 1182 if ($name == false) { 1183 if ($type !== false) { 1184 $rez = oci_bind_by_name($stmt[1],":".$stmt[2],$var,$size,$type); 1185 } 1186 else { 1187 $rez = oci_bind_by_name($stmt[1],":".$stmt[2],$var,$size); // +1 byte for null terminator 1188 } 1189 $stmt[2] += 1; 1190 } else if (oci_lob_desc($type)) { 1191 if ($this->debug) { 1192 ADOConnection::outp("<b>Bind</b>: name = $name"); 1193 } 1194 //we have to create a new Descriptor here 1195 $numlob = count($this->_refLOBs); 1196 $this->_refLOBs[$numlob]['LOB'] = oci_new_descriptor($this->_connectionID, oci_lob_desc($type)); 1197 $this->_refLOBs[$numlob]['TYPE'] = $isOutput; 1198 1199 $tmp = $this->_refLOBs[$numlob]['LOB']; 1200 $rez = oci_bind_by_name($stmt[1], ":".$name, $tmp, -1, $type); 1201 if ($this->debug) { 1202 ADOConnection::outp("<b>Bind</b>: descriptor has been allocated, var (".$name.") binded"); 1203 } 1204 1205 // if type is input then write data to lob now 1206 if ($isOutput == false) { 1207 $var = $this->BlobEncode($var); 1208 $tmp->WriteTemporary($var); 1209 $this->_refLOBs[$numlob]['VAR'] = &$var; 1210 if ($this->debug) { 1211 ADOConnection::outp("<b>Bind</b>: LOB has been written to temp"); 1212 } 1213 } else { 1214 $this->_refLOBs[$numlob]['VAR'] = &$var; 1215 } 1216 $rez = $tmp; 1217 } else { 1218 if ($this->debug) 1219 ADOConnection::outp("<b>Bind</b>: name = $name"); 1220 1221 if ($type !== false) { 1222 $rez = oci_bind_by_name($stmt[1],":".$name,$var,$size,$type); 1223 } 1224 else { 1225 $rez = oci_bind_by_name($stmt[1],":".$name,$var,$size); // +1 byte for null terminator 1226 } 1227 } 1228 1229 return $rez; 1230 } 1231 1232 function Param($name,$type='C') 1233 { 1234 return ':'.$name; 1235 } 1236 1237 /** 1238 * Usage: 1239 * $stmt = $db->Prepare('select * from table where id =:myid and group=:group'); 1240 * $db->Parameter($stmt,$id,'myid'); 1241 * $db->Parameter($stmt,$group,'group'); 1242 * $db->Execute($stmt); 1243 * 1244 * @param $stmt Statement returned by Prepare() or PrepareSP(). 1245 * @param $var PHP variable to bind to 1246 * @param $name Name of stored procedure variable name to bind to. 1247 * @param [$isOutput] Indicates direction of parameter 0/false=IN 1=OUT 2= IN/OUT. This is ignored in oci8. 1248 * @param [$maxLen] Holds an maximum length of the variable. 1249 * @param [$type] The data type of $var. Legal values depend on driver. 1250 * 1251 * @link http://php.net/oci_bind_by_name 1252 */ 1253 function Parameter(&$stmt,&$var,$name,$isOutput=false,$maxLen=4000,$type=false) 1254 { 1255 if ($this->debug) { 1256 $prefix = ($isOutput) ? 'Out' : 'In'; 1257 $ztype = (empty($type)) ? 'false' : $type; 1258 ADOConnection::outp( "{$prefix}Parameter(\$stmt, \$php_var='$var', \$name='$name', \$maxLen=$maxLen, \$type=$ztype);"); 1259 } 1260 return $this->Bind($stmt,$var,$maxLen,$type,$name,$isOutput); 1261 } 1262 1263 /** 1264 * returns query ID if successful, otherwise false 1265 * this version supports: 1266 * 1267 * 1. $db->execute('select * from table'); 1268 * 1269 * 2. $db->prepare('insert into table (a,b,c) values (:0,:1,:2)'); 1270 * $db->execute($prepared_statement, array(1,2,3)); 1271 * 1272 * 3. $db->execute('insert into table (a,b,c) values (:a,:b,:c)',array('a'=>1,'b'=>2,'c'=>3)); 1273 * 1274 * 4. $db->prepare('insert into table (a,b,c) values (:0,:1,:2)'); 1275 * $db->bind($stmt,1); $db->bind($stmt,2); $db->bind($stmt,3); 1276 * $db->execute($stmt); 1277 */ 1278 function _query($sql,$inputarr=false) 1279 { 1280 if (is_array($sql)) { // is prepared sql 1281 $stmt = $sql[1]; 1282 1283 // we try to bind to permanent array, so that oci_bind_by_name is persistent 1284 // and carried out once only - note that max array element size is 4000 chars 1285 if (is_array($inputarr)) { 1286 $bindpos = $sql[3]; 1287 if (isset($this->_bind[$bindpos])) { 1288 // all tied up already 1289 $bindarr = $this->_bind[$bindpos]; 1290 } else { 1291 // one statement to bind them all 1292 $bindarr = array(); 1293 foreach($inputarr as $k => $v) { 1294 $bindarr[$k] = $v; 1295 oci_bind_by_name($stmt,":$k",$bindarr[$k],is_string($v) && strlen($v)>4000 ? -1 : 4000); 1296 } 1297 $this->_bind[$bindpos] = $bindarr; 1298 } 1299 } 1300 } else { 1301 $stmt=oci_parse($this->_connectionID,$sql); 1302 } 1303 1304 $this->_stmt = $stmt; 1305 if (!$stmt) { 1306 return false; 1307 } 1308 1309 if (defined('ADODB_PREFETCH_ROWS')) { 1310 @oci_set_prefetch($stmt,ADODB_PREFETCH_ROWS); 1311 } 1312 1313 if (is_array($inputarr)) { 1314 foreach($inputarr as $k => $v) { 1315 if (is_array($v)) { 1316 // suggested by g.giunta@libero. 1317 if (sizeof($v) == 2) { 1318 oci_bind_by_name($stmt,":$k",$inputarr[$k][0],$v[1]); 1319 } 1320 else { 1321 oci_bind_by_name($stmt,":$k",$inputarr[$k][0],$v[1],$v[2]); 1322 } 1323 1324 if ($this->debug==99) { 1325 if (is_object($v[0])) { 1326 echo "name=:$k",' len='.$v[1],' type='.$v[2],'<br>'; 1327 } 1328 else { 1329 echo "name=:$k",' var='.$inputarr[$k][0],' len='.$v[1],' type='.$v[2],'<br>'; 1330 } 1331 1332 } 1333 } else { 1334 $len = -1; 1335 if ($v === ' ') { 1336 $len = 1; 1337 } 1338 if (isset($bindarr)) { // is prepared sql, so no need to oci_bind_by_name again 1339 $bindarr[$k] = $v; 1340 } else { // dynamic sql, so rebind every time 1341 oci_bind_by_name($stmt,":$k",$inputarr[$k],$len); 1342 } 1343 } 1344 } 1345 } 1346 1347 $this->_errorMsg = false; 1348 $this->_errorCode = false; 1349 if (oci_execute($stmt,$this->_commit)) { 1350 1351 if (count($this -> _refLOBs) > 0) { 1352 1353 foreach ($this -> _refLOBs as $key => $value) { 1354 if ($this -> _refLOBs[$key]['TYPE'] == true) { 1355 $tmp = $this -> _refLOBs[$key]['LOB'] -> load(); 1356 if ($this -> debug) { 1357 ADOConnection::outp("<b>OUT LOB</b>: LOB has been loaded. <br>"); 1358 } 1359 //$_GLOBALS[$this -> _refLOBs[$key]['VAR']] = $tmp; 1360 $this -> _refLOBs[$key]['VAR'] = $tmp; 1361 } else { 1362 $this->_refLOBs[$key]['LOB']->save($this->_refLOBs[$key]['VAR']); 1363 $this -> _refLOBs[$key]['LOB']->free(); 1364 unset($this -> _refLOBs[$key]); 1365 if ($this->debug) { 1366 ADOConnection::outp("<b>IN LOB</b>: LOB has been saved. <br>"); 1367 } 1368 } 1369 } 1370 } 1371 1372 switch (@oci_statement_type($stmt)) { 1373 case "SELECT": 1374 return $stmt; 1375 1376 case 'DECLARE': 1377 case "BEGIN": 1378 if (is_array($sql) && !empty($sql[4])) { 1379 $cursor = $sql[4]; 1380 if (is_resource($cursor)) { 1381 $ok = oci_execute($cursor); 1382 return $cursor; 1383 } 1384 return $stmt; 1385 } else { 1386 if (is_resource($stmt)) { 1387 oci_free_statement($stmt); 1388 return true; 1389 } 1390 return $stmt; 1391 } 1392 break; 1393 default : 1394 1395 return true; 1396 } 1397 } 1398 return false; 1399 } 1400 1401 // From Oracle Whitepaper: PHP Scalability and High Availability 1402 function IsConnectionError($err) 1403 { 1404 switch($err) { 1405 case 378: /* buffer pool param incorrect */ 1406 case 602: /* core dump */ 1407 case 603: /* fatal error */ 1408 case 609: /* attach failed */ 1409 case 1012: /* not logged in */ 1410 case 1033: /* init or shutdown in progress */ 1411 case 1043: /* Oracle not available */ 1412 case 1089: /* immediate shutdown in progress */ 1413 case 1090: /* shutdown in progress */ 1414 case 1092: /* instance terminated */ 1415 case 3113: /* disconnect */ 1416 case 3114: /* not connected */ 1417 case 3122: /* closing window */ 1418 case 3135: /* lost contact */ 1419 case 12153: /* TNS: not connected */ 1420 case 27146: /* fatal or instance terminated */ 1421 case 28511: /* Lost RPC */ 1422 return true; 1423 } 1424 return false; 1425 } 1426 1427 // returns true or false 1428 function _close() 1429 { 1430 if (!$this->_connectionID) { 1431 return; 1432 } 1433 1434 1435 if (!$this->autoCommit) { 1436 oci_rollback($this->_connectionID); 1437 } 1438 if (count($this->_refLOBs) > 0) { 1439 foreach ($this ->_refLOBs as $key => $value) { 1440 $this->_refLOBs[$key]['LOB']->free(); 1441 unset($this->_refLOBs[$key]); 1442 } 1443 } 1444 oci_close($this->_connectionID); 1445 1446 $this->_stmt = false; 1447 $this->_connectionID = false; 1448 } 1449 1450 function MetaPrimaryKeys($table, $owner=false,$internalKey=false) 1451 { 1452 if ($internalKey) { 1453 return array('ROWID'); 1454 } 1455 1456 // tested with oracle 8.1.7 1457 $table = strtoupper($table); 1458 if ($owner) { 1459 $owner_clause = "AND ((a.OWNER = b.OWNER) AND (a.OWNER = UPPER('$owner')))"; 1460 $ptab = 'ALL_'; 1461 } else { 1462 $owner_clause = ''; 1463 $ptab = 'USER_'; 1464 } 1465 $sql = " 1466 SELECT /*+ RULE */ distinct b.column_name 1467 FROM {$ptab}CONSTRAINTS a 1468 , {$ptab}CONS_COLUMNS b 1469 WHERE ( UPPER(b.table_name) = ('$table')) 1470 AND (UPPER(a.table_name) = ('$table') and a.constraint_type = 'P') 1471 $owner_clause 1472 AND (a.constraint_name = b.constraint_name)"; 1473 1474 $rs = $this->Execute($sql); 1475 if ($rs && !$rs->EOF) { 1476 $arr = $rs->GetArray(); 1477 $a = array(); 1478 foreach($arr as $v) { 1479 $a[] = reset($v); 1480 } 1481 return $a; 1482 } 1483 else return false; 1484 } 1485 1486 /** 1487 * returns assoc array where keys are tables, and values are foreign keys 1488 * 1489 * @param str $table 1490 * @param str $owner [optional][default=NULL] 1491 * @param bool $upper [optional][discarded] 1492 * @return mixed[] Array of foreign key information 1493 * 1494 * @link http://gis.mit.edu/classes/11.521/sqlnotes/referential_integrity.html 1495 */ 1496 function MetaForeignKeys($table, $owner=false, $upper=false) 1497 { 1498 global $ADODB_FETCH_MODE; 1499 1500 $save = $ADODB_FETCH_MODE; 1501 $ADODB_FETCH_MODE = ADODB_FETCH_NUM; 1502 $table = $this->qstr(strtoupper($table)); 1503 if (!$owner) { 1504 $owner = $this->user; 1505 $tabp = 'user_'; 1506 } else 1507 $tabp = 'all_'; 1508 1509 $owner = ' and owner='.$this->qstr(strtoupper($owner)); 1510 1511 $sql = 1512 "select constraint_name,r_owner,r_constraint_name 1513 from {$tabp}constraints 1514 where constraint_type = 'R' and table_name = $table $owner"; 1515 1516 $constraints = $this->GetArray($sql); 1517 $arr = false; 1518 foreach($constraints as $constr) { 1519 $cons = $this->qstr($constr[0]); 1520 $rowner = $this->qstr($constr[1]); 1521 $rcons = $this->qstr($constr[2]); 1522 $cols = $this->GetArray("select column_name from {$tabp}cons_columns where constraint_name=$cons $owner order by position"); 1523 $tabcol = $this->GetArray("select table_name,column_name from {$tabp}cons_columns where owner=$rowner and constraint_name=$rcons order by position"); 1524 1525 if ($cols && $tabcol) 1526 for ($i=0, $max=sizeof($cols); $i < $max; $i++) { 1527 $arr[$tabcol[$i][0]] = $cols[$i][0].'='.$tabcol[$i][1]; 1528 } 1529 } 1530 $ADODB_FETCH_MODE = $save; 1531 1532 return $arr; 1533 } 1534 1535 1536 function CharMax() 1537 { 1538 return 4000; 1539 } 1540 1541 function TextMax() 1542 { 1543 return 4000; 1544 } 1545 1546 /** 1547 * Correctly quotes a string so that all strings are escaped. 1548 * We prefix and append to the string single-quotes. 1549 * An example is $db->qstr("Don't bother"); 1550 * 1551 * @param string $s The string to quote 1552 * @param bool $magic_quotes This param is not used since 5.21.0. 1553 * It remains for backwards compatibility. 1554 * 1555 * @return string Quoted string to be sent back to database 1556 * 1557 * @noinspection PhpUnusedParameterInspection 1558 */ 1559 function qStr($s, $magic_quotes=false) 1560 { 1561 if ($this->noNullStrings && strlen($s) == 0) { 1562 $s = ' '; 1563 } 1564 if ($this->replaceQuote[0] == '\\'){ 1565 $s = str_replace('\\','\\\\',$s); 1566 } 1567 return "'" . str_replace("'", $this->replaceQuote, $s) . "'"; 1568 } 1569 1570 } 1571 1572 /*-------------------------------------------------------------------------------------- 1573 Class Name: Recordset 1574 --------------------------------------------------------------------------------------*/ 1575 1576 class ADORecordset_oci8 extends ADORecordSet { 1577 1578 var $databaseType = 'oci8'; 1579 var $bind=false; 1580 var $_fieldobjs; 1581 1582 function __construct($queryID,$mode=false) 1583 { 1584 if ($mode === false) { 1585 global $ADODB_FETCH_MODE; 1586 $mode = $ADODB_FETCH_MODE; 1587 } 1588 switch ($mode) { 1589 case ADODB_FETCH_ASSOC: 1590 $this->fetchMode = OCI_ASSOC; 1591 break; 1592 case ADODB_FETCH_DEFAULT: 1593 case ADODB_FETCH_BOTH: 1594 $this->fetchMode = OCI_NUM + OCI_ASSOC; 1595 break; 1596 case ADODB_FETCH_NUM: 1597 default: 1598 $this->fetchMode = OCI_NUM; 1599 break; 1600 } 1601 $this->fetchMode += OCI_RETURN_NULLS + OCI_RETURN_LOBS; 1602 $this->adodbFetchMode = $mode; 1603 $this->_queryID = $queryID; 1604 } 1605 1606 /** 1607 * Overrides the core destructor method as that causes problems here 1608 * 1609 * @return void 1610 */ 1611 function __destruct() {} 1612 1613 function Init() 1614 { 1615 if ($this->_inited) { 1616 return; 1617 } 1618 1619 $this->_inited = true; 1620 if ($this->_queryID) { 1621 1622 $this->_currentRow = 0; 1623 @$this->_initrs(); 1624 if ($this->_numOfFields) { 1625 $this->EOF = !$this->_fetch(); 1626 } 1627 else $this->EOF = true; 1628 1629 /* 1630 // based on idea by Gaetano Giunta to detect unusual oracle errors 1631 // see PHPLens Issue No: 6771 1632 $err = oci_error($this->_queryID); 1633 if ($err && $this->connection->debug) { 1634 ADOConnection::outp($err); 1635 } 1636 */ 1637 1638 if (!is_array($this->fields)) { 1639 $this->_numOfRows = 0; 1640 $this->fields = array(); 1641 } 1642 } else { 1643 $this->fields = array(); 1644 $this->_numOfRows = 0; 1645 $this->_numOfFields = 0; 1646 $this->EOF = true; 1647 } 1648 } 1649 1650 function _initrs() 1651 { 1652 $this->_numOfRows = -1; 1653 $this->_numOfFields = oci_num_fields($this->_queryID); 1654 if ($this->_numOfFields>0) { 1655 $this->_fieldobjs = array(); 1656 $max = $this->_numOfFields; 1657 for ($i=0;$i<$max; $i++) $this->_fieldobjs[] = $this->_FetchField($i); 1658 } 1659 } 1660 1661 /** 1662 * Get column information in the Recordset object. 1663 * fetchField() can be used in order to obtain information about fields 1664 * in a certain query result. If the field offset isn't specified, the next 1665 * field that wasn't yet retrieved by fetchField() is retrieved 1666 * 1667 * @return object containing field information 1668 */ 1669 function _FetchField($fieldOffset = -1) 1670 { 1671 $fld = new ADOFieldObject; 1672 $fieldOffset += 1; 1673 $fld->name =oci_field_name($this->_queryID, $fieldOffset); 1674 if (ADODB_ASSOC_CASE == ADODB_ASSOC_CASE_LOWER) { 1675 $fld->name = strtolower($fld->name); 1676 } 1677 $fld->type = oci_field_type($this->_queryID, $fieldOffset); 1678 $fld->max_length = oci_field_size($this->_queryID, $fieldOffset); 1679 1680 switch($fld->type) { 1681 case 'NUMBER': 1682 $p = oci_field_precision($this->_queryID, $fieldOffset); 1683 $sc = oci_field_scale($this->_queryID, $fieldOffset); 1684 if ($p != 0 && $sc == 0) { 1685 $fld->type = 'INT'; 1686 } 1687 $fld->scale = $p; 1688 break; 1689 1690 case 'CLOB': 1691 case 'NCLOB': 1692 case 'BLOB': 1693 $fld->max_length = -1; 1694 break; 1695 } 1696 return $fld; 1697 } 1698 1699 /* For some reason, oci_field_name fails when called after _initrs() so we cache it */ 1700 function FetchField($fieldOffset = -1) 1701 { 1702 return $this->_fieldobjs[$fieldOffset]; 1703 } 1704 1705 1706 function MoveNext() 1707 { 1708 if ($this->fields = @oci_fetch_array($this->_queryID,$this->fetchMode)) { 1709 $this->_currentRow += 1; 1710 $this->_updatefields(); 1711 return true; 1712 } 1713 if (!$this->EOF) { 1714 $this->_currentRow += 1; 1715 $this->EOF = true; 1716 } 1717 return false; 1718 } 1719 1720 // Optimize SelectLimit() by using oci_fetch() 1721 function GetArrayLimit($nrows,$offset=-1) 1722 { 1723 if ($offset <= 0) { 1724 $arr = $this->GetArray($nrows); 1725 return $arr; 1726 } 1727 $arr = array(); 1728 for ($i=1; $i < $offset; $i++) { 1729 if (!@oci_fetch($this->_queryID)) { 1730 return $arr; 1731 } 1732 } 1733 1734 if (!$this->fields = @oci_fetch_array($this->_queryID,$this->fetchMode)) { 1735 return $arr; 1736 } 1737 $this->_updatefields(); 1738 $results = array(); 1739 $cnt = 0; 1740 while (!$this->EOF && $nrows != $cnt) { 1741 $results[$cnt++] = $this->fields; 1742 $this->MoveNext(); 1743 } 1744 1745 return $results; 1746 } 1747 1748 1749 // Use associative array to get fields array 1750 function Fields($colname) 1751 { 1752 if (!$this->bind) { 1753 $this->bind = array(); 1754 for ($i=0; $i < $this->_numOfFields; $i++) { 1755 $o = $this->FetchField($i); 1756 $this->bind[strtoupper($o->name)] = $i; 1757 } 1758 } 1759 1760 return $this->fields[$this->bind[strtoupper($colname)]]; 1761 } 1762 1763 1764 function _seek($row) 1765 { 1766 return false; 1767 } 1768 1769 function _fetch() 1770 { 1771 $this->fields = @oci_fetch_array($this->_queryID,$this->fetchMode); 1772 $this->_updatefields(); 1773 1774 return $this->fields; 1775 } 1776 1777 /** 1778 * close() only needs to be called if you are worried about using too much 1779 * memory while your script is running. All associated result memory for the 1780 * specified result identifier will automatically be freed. 1781 */ 1782 function _close() 1783 { 1784 if ($this->connection->_stmt === $this->_queryID) { 1785 $this->connection->_stmt = false; 1786 } 1787 if (!empty($this->_refcursor)) { 1788 oci_free_cursor($this->_refcursor); 1789 $this->_refcursor = false; 1790 } 1791 if (is_resource($this->_queryID)) 1792 @oci_free_statement($this->_queryID); 1793 $this->_queryID = false; 1794 } 1795 1796 /** 1797 * not the fastest implementation - quick and dirty - jlim 1798 * for best performance, use the actual $rs->MetaType(). 1799 * 1800 * @param mixed $t 1801 * @param int $len [optional] Length of blobsize 1802 * @param bool $fieldobj [optional][discarded] 1803 * @return str The metatype of the field 1804 */ 1805 function MetaType($t, $len=-1, $fieldobj=false) 1806 { 1807 if (is_object($t)) { 1808 $fieldobj = $t; 1809 $t = $fieldobj->type; 1810 $len = $fieldobj->max_length; 1811 } 1812 1813 switch (strtoupper($t)) { 1814 case 'VARCHAR': 1815 case 'VARCHAR2': 1816 case 'CHAR': 1817 case 'VARBINARY': 1818 case 'BINARY': 1819 case 'NCHAR': 1820 case 'NVARCHAR': 1821 case 'NVARCHAR2': 1822 if ($len <= $this->blobSize) { 1823 return 'C'; 1824 } 1825 1826 case 'NCLOB': 1827 case 'LONG': 1828 case 'LONG VARCHAR': 1829 case 'CLOB': 1830 return 'X'; 1831 1832 case 'LONG RAW': 1833 case 'LONG VARBINARY': 1834 case 'BLOB': 1835 return 'B'; 1836 1837 case 'DATE': 1838 return ($this->connection->datetime) ? 'T' : 'D'; 1839 1840 1841 case 'TIMESTAMP': return 'T'; 1842 1843 case 'INT': 1844 case 'SMALLINT': 1845 case 'INTEGER': 1846 return 'I'; 1847 1848 default: 1849 return ADODB_DEFAULT_METATYPE; 1850 } 1851 } 1852 } 1853 1854 class ADORecordSet_ext_oci8 extends ADORecordSet_oci8 { 1855 1856 function MoveNext() 1857 { 1858 return adodb_movenext($this); 1859 } 1860 }
title
Description
Body
title
Description
Body
title
Description
Body
title
Body