-
Notifications
You must be signed in to change notification settings - Fork 269
/
adodb-oci8.inc.php
1886 lines (1655 loc) · 47.5 KB
/
adodb-oci8.inc.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* FileDescription
*
* This file is part of ADOdb, a Database Abstraction Layer library for PHP.
*
* @package ADOdb
* @link https://adodb.org Project's web site and documentation
* @link https://github.com/ADOdb/ADOdb Source code and issue tracker
*
* The ADOdb Library is dual-licensed, released under both the BSD 3-Clause
* and the GNU Lesser General Public Licence (LGPL) v2.1 or, at your option,
* any later version. This means you can use it in proprietary products.
* See the LICENSE.md file distributed with this source code for details.
* @license BSD-3-Clause
* @license LGPL-2.1-or-later
*
* @copyright 2000-2013 John Lim
* @copyright 2014 Damien Regad, Mark Newnham and the ADOdb community
* @author John Lim
* @author George Fourlanos <fou@infomap.gr>
*/
// security - hide paths
if (!defined('ADODB_DIR')) die();
/*
NLS_Date_Format
Allows you to use a date format other than the Oracle Lite default. When a literal
character string appears where a date value is expected, the Oracle Lite database
tests the string to see if it matches the formats of Oracle, SQL-92, or the value
specified for this parameter in the POLITE.INI file. Setting this parameter also
defines the default format used in the TO_CHAR or TO_DATE functions when no
other format string is supplied.
For Oracle the default is dd-mon-yy or dd-mon-yyyy, and for SQL-92 the default is
yy-mm-dd or yyyy-mm-dd.
Using 'RR' in the format forces two-digit years less than or equal to 49 to be
interpreted as years in the 21st century (2000-2049), and years over 50 as years in
the 20th century (1950-1999). Setting the RR format as the default for all two-digit
year entries allows you to become year-2000 compliant. For example:
NLS_DATE_FORMAT='RR-MM-DD'
You can also modify the date format using the ALTER SESSION command.
*/
# define the LOB descriptor type for the given type
# returns false if no LOB descriptor
function oci_lob_desc($type) {
switch ($type) {
case OCI_B_BFILE: return OCI_D_FILE;
case OCI_B_CFILEE: return OCI_D_FILE;
case OCI_B_CLOB: return OCI_D_LOB;
case OCI_B_BLOB: return OCI_D_LOB;
case OCI_B_ROWID: return OCI_D_ROWID;
}
return false;
}
class ADODB_oci8 extends ADOConnection {
var $databaseType = 'oci8';
var $dataProvider = 'oci8';
var $replaceQuote = "''"; // string to use to replace quotes
var $concat_operator='||';
var $sysDate = "TRUNC(SYSDATE)";
var $sysTimeStamp = 'SYSDATE'; // requires oracle 9 or later, otherwise use SYSDATE
var $metaDatabasesSQL = "SELECT USERNAME FROM ALL_USERS WHERE USERNAME NOT IN ('SYS','SYSTEM','DBSNMP','OUTLN') ORDER BY 1";
var $_stmt;
var $_commit = OCI_COMMIT_ON_SUCCESS;
var $_initdate = true; // init date to YYYY-MM-DD
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
var $metaColumnsSQL = "select cname,coltype,width, SCALE, PRECISION, NULLS, DEFAULTVAL from col where tname='%s' order by colno"; //changed by smondino@users.sourceforge. net
var $metaColumnsSQL2 = "select column_name,data_type,data_length, data_scale, data_precision,
case when nullable = 'Y' then 'NULL'
else 'NOT NULL' end as nulls,
data_default from all_tab_cols
where owner='%s' and table_name='%s' order by column_id"; // when there is a schema
var $_bindInputArray = true;
var $hasGenID = true;
var $_genIDSQL = "SELECT (%s.nextval) FROM DUAL";
var $_genSeqSQL = "
DECLARE
PRAGMA AUTONOMOUS_TRANSACTION;
BEGIN
execute immediate 'CREATE SEQUENCE %s START WITH %s';
END;
";
var $_dropSeqSQL = "DROP SEQUENCE %s";
var $hasAffectedRows = true;
var $random = "abs(mod(DBMS_RANDOM.RANDOM,10000001)/10000000)";
var $noNullStrings = false;
var $connectSID = false;
var $_bind = false;
var $_nestedSQL = true;
var $_getarray = false; // currently not working
var $leftOuter = ''; // oracle wierdness, $col = $value (+) for LEFT OUTER, $col (+)= $value for RIGHT OUTER
var $session_sharing_force_blob = false; // alter session on updateblob if set to true
var $firstrows = true; // enable first rows optimization on SelectLimit()
var $selectOffsetAlg1 = 1000; // when to use 1st algorithm of selectlimit.
var $NLS_DATE_FORMAT = 'YYYY-MM-DD'; // To include time, use 'RRRR-MM-DD HH24:MI:SS'
var $dateformat = 'YYYY-MM-DD'; // DBDate format
var $useDBDateFormatForTextInput=false;
var $datetime = false; // MetaType('DATE') returns 'D' (datetime==false) or 'T' (datetime == true)
var $_refLOBs = array();
// var $ansiOuter = true; // if oracle9
/*
* Legacy compatibility for sequence names for emulated auto-increments
*/
public $useCompactAutoIncrements = false;
/*
* Defines the schema name for emulated auto-increment columns
*/
public $schema = false;
/*
* Defines the prefix for emulated auto-increment columns
*/
public $seqPrefix = 'SEQ_';
/* function MetaColumns($table, $normalize=true) added by smondino@users.sourceforge.net*/
function MetaColumns($table, $normalize=true)
{
global $ADODB_FETCH_MODE;
$schema = '';
$this->_findschema($table, $schema);
$save = $ADODB_FETCH_MODE;
$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
if ($this->fetchMode !== false) {
$savem = $this->SetFetchMode(false);
}
if ($schema){
$rs = $this->Execute(sprintf($this->metaColumnsSQL2, strtoupper($schema), strtoupper($table)));
}
else {
$rs = $this->Execute(sprintf($this->metaColumnsSQL,strtoupper($table)));
}
if (isset($savem)) {
$this->SetFetchMode($savem);
}
$ADODB_FETCH_MODE = $save;
if (!$rs) {
return false;
}
$retarr = array();
while (!$rs->EOF) {
$fld = new ADOFieldObject();
$fld->name = $rs->fields[0];
$fld->type = $rs->fields[1];
$fld->max_length = $rs->fields[2];
$fld->scale = $rs->fields[3];
if ($rs->fields[1] == 'NUMBER') {
if ($rs->fields[3] == 0) {
$fld->type = 'INT';
}
$fld->max_length = $rs->fields[4];
}
$fld->not_null = (strncmp($rs->fields[5], 'NOT',3) === 0);
$fld->binary = (strpos($fld->type,'BLOB') !== false);
$fld->default_value = $rs->fields[6];
if ($ADODB_FETCH_MODE == ADODB_FETCH_NUM) {
$retarr[] = $fld;
}
else {
$retarr[strtoupper($fld->name)] = $fld;
}
$rs->MoveNext();
}
$rs->Close();
if (empty($retarr)) {
return false;
}
return $retarr;
}
function Time()
{
$rs = $this->Execute("select TO_CHAR($this->sysTimeStamp,'YYYY-MM-DD HH24:MI:SS') from dual");
if ($rs && !$rs->EOF) {
return $this->UnixTimeStamp(reset($rs->fields));
}
return false;
}
/**
* Multiple modes of connection are supported:
*
* a. Local Database
* $conn->Connect(false,'scott','tiger');
*
* b. From tnsnames.ora
* $conn->Connect($tnsname,'scott','tiger');
* $conn->Connect(false,'scott','tiger',$tnsname);
*
* c. Server + service name
* $conn->Connect($serveraddress,'scott,'tiger',$service_name);
*
* d. Server + SID
* $conn->connectSID = true;
* $conn->Connect($serveraddress,'scott,'tiger',$SID);
*
* @param string|false $argHostname DB server hostname or TNS name
* @param string $argUsername
* @param string $argPassword
* @param string $argDatabasename Service name, SID (defaults to null)
* @param int $mode Connection mode, defaults to 0
* (0 = non-persistent, 1 = persistent, 2 = force new connection)
*
* @return bool
*/
function _connect($argHostname, $argUsername, $argPassword, $argDatabasename=null, $mode=0)
{
if (!function_exists('oci_pconnect')) {
return null;
}
#adodb_backtrace();
$this->_errorMsg = false;
$this->_errorCode = false;
if($argHostname) { // added by Jorma Tuomainen <jorma.tuomainen@ppoy.fi>
if (empty($argDatabasename)) {
$argDatabasename = $argHostname;
}
else {
if(strpos($argHostname,":")) {
$argHostinfo=explode(":",$argHostname);
$argHostname=$argHostinfo[0];
$argHostport=$argHostinfo[1];
} else {
$argHostport = empty($this->port)? "1521" : $this->port;
}
if (strncasecmp($argDatabasename,'SID=',4) == 0) {
$argDatabasename = substr($argDatabasename,4);
$this->connectSID = true;
}
if ($this->connectSID) {
$argDatabasename="(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=".$argHostname
.")(PORT=$argHostport))(CONNECT_DATA=(SID=$argDatabasename)))";
} else
$argDatabasename="(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=".$argHostname
.")(PORT=$argHostport))(CONNECT_DATA=(SERVICE_NAME=$argDatabasename)))";
}
}
//if ($argHostname) print "<p>Connect: 1st argument should be left blank for $this->databaseType</p>";
if ($mode==1) {
$this->_connectionID = ($this->charSet)
? oci_pconnect($argUsername,$argPassword, $argDatabasename,$this->charSet)
: oci_pconnect($argUsername,$argPassword, $argDatabasename);
if ($this->_connectionID && $this->autoRollback) {
oci_rollback($this->_connectionID);
}
} else if ($mode==2) {
$this->_connectionID = ($this->charSet)
? oci_new_connect($argUsername,$argPassword, $argDatabasename,$this->charSet)
: oci_new_connect($argUsername,$argPassword, $argDatabasename);
} else {
$this->_connectionID = ($this->charSet)
? oci_connect($argUsername,$argPassword, $argDatabasename,$this->charSet)
: oci_connect($argUsername,$argPassword, $argDatabasename);
}
if (!$this->_connectionID) {
return false;
}
if ($this->_initdate) {
$this->Execute("ALTER SESSION SET NLS_DATE_FORMAT='".$this->NLS_DATE_FORMAT."'");
}
// looks like:
// Oracle8i Enterprise Edition Release 8.1.7.0.0 - Production With the Partitioning option JServer Release 8.1.7.0.0 - Production
// $vers = oci_server_version($this->_connectionID);
// if (strpos($vers,'8i') !== false) $this->ansiOuter = true;
return true;
}
function ServerInfo()
{
$arr['compat'] = $this->GetOne('select value from sys.database_compatible_level');
$arr['description'] = @oci_server_version($this->_connectionID);
$arr['version'] = ADOConnection::_findvers($arr['description']);
return $arr;
}
// returns true or false
function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename)
{
return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabasename,1);
}
// returns true or false
function _nconnect($argHostname, $argUsername, $argPassword, $argDatabasename)
{
return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabasename,2);
}
function _affectedrows()
{
if (is_resource($this->_stmt)) {
return @oci_num_rows($this->_stmt);
}
return 0;
}
function IfNull( $field, $ifNull )
{
return " NVL($field, $ifNull) "; // if Oracle
}
protected function _insertID($table = '', $column = '')
{
if ($this->schema)
{
$t = strpos($table,'.');
if ($t !== false)
$tab = substr($table,$t+1);
else
$tab = $table;
if ($this->useCompactAutoIncrements)
$tab = sprintf('%u',crc32(strtolower($tab)));
$seqname = $this->schema.'.'.$this->seqPrefix.$tab;
}
else
{
if ($this->useCompactAutoIncrements)
$table = sprintf('%u',crc32(strtolower($table)));
$seqname = $this->seqPrefix.$table;
}
if (strlen($seqname) > 30)
/*
* We cannot successfully identify the sequence
*/
return false;
return $this->getOne("SELECT $seqname.currval FROM dual");
}
// format and return date string in database date format
function DBDate($d,$isfld=false)
{
if (empty($d) && $d !== 0) {
return 'null';
}
if ($isfld) {
$d = _adodb_safedate($d);
return 'TO_DATE('.$d.",'".$this->dateformat."')";
}
if (is_string($d)) {
$d = ADORecordSet::UnixDate($d);
}
if (is_object($d)) {
$ds = $d->format($this->fmtDate);
}
else {
$ds = adodb_date($this->fmtDate,$d);
}
return "TO_DATE(".$ds.",'".$this->dateformat."')";
}
function BindDate($d)
{
$d = ADOConnection::DBDate($d);
if (strncmp($d, "'", 1)) {
return $d;
}
return substr($d, 1, strlen($d)-2);
}
function BindTimeStamp($ts)
{
if (empty($ts) && $ts !== 0) {
return 'null';
}
if (is_string($ts)) {
$ts = ADORecordSet::UnixTimeStamp($ts);
}
if (is_object($ts)) {
$tss = $ts->format("'Y-m-d H:i:s'");
}
else {
$tss = adodb_date("'Y-m-d H:i:s'",$ts);
}
return $tss;
}
// format and return date string in database timestamp format
function DBTimeStamp($ts,$isfld=false)
{
if (empty($ts) && $ts !== 0) {
return 'null';
}
if ($isfld) {
return 'TO_DATE(substr('.$ts.",1,19),'RRRR-MM-DD, HH24:MI:SS')";
}
if (is_string($ts)) {
$ts = ADORecordSet::UnixTimeStamp($ts);
}
if (is_object($ts)) {
$tss = $ts->format("'Y-m-d H:i:s'");
}
else {
$tss = date("'Y-m-d H:i:s'",$ts);
}
return 'TO_DATE('.$tss.",'RRRR-MM-DD, HH24:MI:SS')";
}
function RowLock($tables,$where,$col='1 as adodbignore')
{
if ($this->autoCommit) {
$this->BeginTrans();
}
return $this->GetOne("select $col from $tables where $where for update");
}
function MetaTables($ttype=false,$showSchema=false,$mask=false)
{
if ($mask) {
$save = $this->metaTablesSQL;
$mask = $this->qstr(strtoupper($mask));
$this->metaTablesSQL .= " AND upper(table_name) like $mask";
}
$ret = ADOConnection::MetaTables($ttype,$showSchema);
if ($mask) {
$this->metaTablesSQL = $save;
}
return $ret;
}
// Mark Newnham
function MetaIndexes ($table, $primary = FALSE, $owner=false)
{
// save old fetch mode
global $ADODB_FETCH_MODE;
$save = $ADODB_FETCH_MODE;
$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
if ($this->fetchMode !== FALSE) {
$savem = $this->SetFetchMode(FALSE);
}
// get index details
$table = strtoupper($table);
// get Primary index
$primary_key = '';
$rs = $this->Execute(sprintf("SELECT * FROM ALL_CONSTRAINTS WHERE UPPER(TABLE_NAME)='%s' AND CONSTRAINT_TYPE='P'",$table));
if (!is_object($rs)) {
if (isset($savem)) {
$this->SetFetchMode($savem);
}
$ADODB_FETCH_MODE = $save;
return false;
}
if ($row = $rs->FetchRow()) {
$primary_key = $row[1]; //constraint_name
}
if ($primary==TRUE && $primary_key=='') {
if (isset($savem)) {
$this->SetFetchMode($savem);
}
$ADODB_FETCH_MODE = $save;
return false; //There is no primary key
}
$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));
if (!is_object($rs)) {
if (isset($savem)) {
$this->SetFetchMode($savem);
}
$ADODB_FETCH_MODE = $save;
return false;
}
$indexes = array ();
// parse index data into array
while ($row = $rs->FetchRow()) {
if ($primary && $row[0] != $primary_key) {
continue;
}
if (!isset($indexes[$row[0]])) {
$indexes[$row[0]] = array(
'unique' => ($row[1] == 'UNIQUE'),
'columns' => array()
);
}
$indexes[$row[0]]['columns'][$row[2] - 1] = $row[3];
}
// sort columns by order in the index
foreach ( array_keys ($indexes) as $index ) {
ksort ($indexes[$index]['columns']);
}
if (isset($savem)) {
$this->SetFetchMode($savem);
$ADODB_FETCH_MODE = $save;
}
return $indexes;
}
function BeginTrans()
{
if ($this->transOff) {
return true;
}
$this->transCnt += 1;
$this->autoCommit = false;
$this->_commit = OCI_DEFAULT;
if ($this->_transmode) {
$ok = $this->Execute("SET TRANSACTION ".$this->_transmode);
}
else {
$ok = true;
}
return $ok ? true : false;
}
function CommitTrans($ok=true)
{
if ($this->transOff) {
return true;
}
if (!$ok) {
return $this->RollbackTrans();
}
if ($this->transCnt) {
$this->transCnt -= 1;
}
$ret = oci_commit($this->_connectionID);
$this->_commit = OCI_COMMIT_ON_SUCCESS;
$this->autoCommit = true;
return $ret;
}
function RollbackTrans()
{
if ($this->transOff) {
return true;
}
if ($this->transCnt) {
$this->transCnt -= 1;
}
$ret = oci_rollback($this->_connectionID);
$this->_commit = OCI_COMMIT_ON_SUCCESS;
$this->autoCommit = true;
return $ret;
}
function SelectDB($dbName)
{
return false;
}
function ErrorMsg()
{
if ($this->_errorMsg !== false) {
return $this->_errorMsg;
}
if (is_resource($this->_stmt)) {
$arr = @oci_error($this->_stmt);
}
if (empty($arr)) {
if (is_resource($this->_connectionID)) {
$arr = @oci_error($this->_connectionID);
}
else {
$arr = @oci_error();
}
if ($arr === false) {
return '';
}
}
$this->_errorMsg = $arr['message'];
$this->_errorCode = $arr['code'];
return $this->_errorMsg;
}
function ErrorNo()
{
if ($this->_errorCode !== false) {
return $this->_errorCode;
}
if (is_resource($this->_stmt)) {
$arr = @oci_error($this->_stmt);
}
if (empty($arr)) {
$arr = @oci_error($this->_connectionID);
if ($arr == false) {
$arr = @oci_error();
}
if ($arr == false) {
return '';
}
}
$this->_errorMsg = $arr['message'];
$this->_errorCode = $arr['code'];
return $arr['code'];
}
/**
* Format date column in sql string given an input format that understands Y M D
*/
function SQLDate($fmt, $col=false)
{
if (!$col) {
$col = $this->sysTimeStamp;
}
$s = 'TO_CHAR('.$col.",'";
$len = strlen($fmt);
for ($i=0; $i < $len; $i++) {
$ch = $fmt[$i];
switch($ch) {
case 'Y':
case 'y':
$s .= 'YYYY';
break;
case 'Q':
case 'q':
$s .= 'Q';
break;
case 'M':
$s .= 'Mon';
break;
case 'm':
$s .= 'MM';
break;
case 'D':
case 'd':
$s .= 'DD';
break;
case 'H':
$s.= 'HH24';
break;
case 'h':
$s .= 'HH';
break;
case 'i':
$s .= 'MI';
break;
case 's':
$s .= 'SS';
break;
case 'a':
case 'A':
$s .= 'AM';
break;
case 'w':
$s .= 'D';
break;
case 'l':
$s .= 'DAY';
break;
case 'W':
$s .= 'WW';
break;
default:
// handle escape characters...
if ($ch == '\\') {
$i++;
$ch = substr($fmt,$i,1);
}
if (strpos('-/.:;, ',$ch) !== false) {
$s .= $ch;
}
else {
$s .= '"'.$ch.'"';
}
}
}
return $s. "')";
}
function GetRandRow($sql, $arr = false)
{
$sql = "SELECT * FROM ($sql ORDER BY dbms_random.value) WHERE rownum = 1";
return $this->GetRow($sql,$arr);
}
/**
* This algorithm makes use of
*
* a. FIRST_ROWS hint
* The FIRST_ROWS hint explicitly chooses the approach to optimize response
* time, that is, minimum resource usage to return the first row. Results
* will be returned as soon as they are identified.
*
* b. Uses rownum tricks to obtain only the required rows from a given offset.
* As this uses complicated sql statements, we only use this if $offset >= 100.
* This idea by Tomas V V Cox.
*
* This implementation does not appear to work with oracle 8.0.5 or earlier.
* Comment out this function then, and the slower SelectLimit() in the base
* class will be used.
*
* Note: FIRST_ROWS hinting is only used if $sql is a string; when
* processing a prepared statement's handle, no hinting is performed.
*/
function SelectLimit($sql,$nrows=-1,$offset=-1, $inputarr=false,$secs2cache=0)
{
$nrows = (int) $nrows;
$offset = (int) $offset;
// Since the methods used to limit the number of returned rows rely
// on modifying the provided SQL query, we can't work with prepared
// statements so we just extract the SQL string.
if(is_array($sql)) {
$sql = $sql[0];
}
// seems that oracle only supports 1 hint comment in 8i
if ($this->firstrows) {
if ($nrows > 500 && $nrows < 1000) {
$hint = "FIRST_ROWS($nrows)";
}
else {
$hint = 'FIRST_ROWS';
}
if (strpos($sql,'/*+') !== false) {
$sql = str_replace('/*+ ',"/*+$hint ",$sql);
}
else {
$sql = preg_replace('/^[ \t\n]*select/i',"SELECT /*+$hint*/",$sql);
}
$hint = "/*+ $hint */";
} else {
$hint = '';
}
if ($offset == -1 || ($offset < $this->selectOffsetAlg1 && 0 < $nrows && $nrows < 1000)) {
if ($nrows > 0) {
if ($offset > 0) {
$nrows += $offset;
}
$sql = "select * from (".$sql.") where rownum <= :adodb_offset";
// If non-bound statement, $inputarr is false
if (!$inputarr) {
$inputarr = array();
}
$inputarr['adodb_offset'] = $nrows;
$nrows = -1;
}
// note that $nrows = 0 still has to work ==> no rows returned
return ADOConnection::SelectLimit($sql, $nrows, $offset, $inputarr, $secs2cache);
} else {
// Algorithm by Tomas V V Cox, from PEAR DB oci8.php
// Let Oracle return the name of the columns
$q_fields = "SELECT * FROM (".$sql.") WHERE NULL = NULL";
if (! $stmt_arr = $this->Prepare($q_fields)) {
return false;
}
$stmt = $stmt_arr[1];
if (is_array($inputarr)) {
foreach($inputarr as $k => $v) {
$i=0;
if ($this->databaseType == 'oci8po') {
$bv_name = ":".$i++;
} else {
$bv_name = ":".$k;
}
if (is_array($v)) {
// suggested by g.giunta@libero.
if (sizeof($v) == 2) {
oci_bind_by_name($stmt,$bv_name,$inputarr[$k][0],$v[1]);
}
else {
oci_bind_by_name($stmt,$bv_name,$inputarr[$k][0],$v[1],$v[2]);
}
} else {
$len = -1;
if ($v === ' ') {
$len = 1;
}
if (isset($bindarr)) { // is prepared sql, so no need to oci_bind_by_name again
$bindarr[$k] = $v;
} else { // dynamic sql, so rebind every time
oci_bind_by_name($stmt,$bv_name,$inputarr[$k],$len);
}
}
}
}
if (!oci_execute($stmt, OCI_DEFAULT)) {
oci_free_statement($stmt);
return false;
}
$ncols = oci_num_fields($stmt);
for ( $i = 1; $i <= $ncols; $i++ ) {
$cols[] = '"'.oci_field_name($stmt, $i).'"';
}
$result = false;
oci_free_statement($stmt);
$fields = implode(',', $cols);
if ($nrows <= 0) {
$nrows = 999999999999;
}
else {
$nrows += $offset;
}
$offset += 1; // in Oracle rownum starts at 1
$sql = "SELECT $hint $fields FROM".
"(SELECT rownum as adodb_rownum, $fields FROM".
" ($sql) WHERE rownum <= :adodb_nrows".
") WHERE adodb_rownum >= :adodb_offset";
$inputarr['adodb_nrows'] = $nrows;
$inputarr['adodb_offset'] = $offset;
if ($secs2cache > 0) {
$rs = $this->CacheExecute($secs2cache, $sql,$inputarr);
}
else {
$rs = $this->Execute($sql, $inputarr);
}
return $rs;
}
}
/**
* Usage:
* Store BLOBs and CLOBs
*
* Example: to store $var in a blob
* $conn->Execute('insert into TABLE (id,ablob) values(12,empty_blob())');
* $conn->UpdateBlob('TABLE', 'ablob', $varHoldingBlob, 'ID=12', 'BLOB');
*
* $blobtype supports 'BLOB' and 'CLOB', but you need to change to 'empty_clob()'.
*
* to get length of LOB:
* select DBMS_LOB.GETLENGTH(ablob) from TABLE
*
* If you are using CURSOR_SHARING = force, it appears this will case a segfault
* under oracle 8.1.7.0. Run:
* $db->Execute('ALTER SESSION SET CURSOR_SHARING=EXACT');
* before UpdateBlob() then...
*/
function UpdateBlob($table,$column,$val,$where,$blobtype='BLOB')
{
//if (strlen($val) < 4000) return $this->Execute("UPDATE $table SET $column=:blob WHERE $where",array('blob'=>$val)) != false;
switch(strtoupper($blobtype)) {
default: ADOConnection::outp("<b>UpdateBlob</b>: Unknown blobtype=$blobtype"); return false;
case 'BLOB': $type = OCI_B_BLOB; break;
case 'CLOB': $type = OCI_B_CLOB; break;
}
if ($this->databaseType == 'oci8po')
$sql = "UPDATE $table set $column=EMPTY_{$blobtype}() WHERE $where RETURNING $column INTO ?";
else
$sql = "UPDATE $table set $column=EMPTY_{$blobtype}() WHERE $where RETURNING $column INTO :blob";
$desc = oci_new_descriptor($this->_connectionID, OCI_D_LOB);
$arr['blob'] = array($desc,-1,$type);
if ($this->session_sharing_force_blob) {
$this->Execute('ALTER SESSION SET CURSOR_SHARING=EXACT');
}
$commit = $this->autoCommit;
if ($commit) {
$this->BeginTrans();
}
$rs = $this->_Execute($sql,$arr);
if ($rez = !empty($rs)) {
$desc->save($val);
}
$desc->free();
if ($commit) {
$this->CommitTrans();
}
if ($this->session_sharing_force_blob) {
$this->Execute('ALTER SESSION SET CURSOR_SHARING=FORCE');
}
if ($rez) {
$rs->Close();
}
return $rez;
}
/**
* Usage: store file pointed to by $val in a blob
*/
function UpdateBlobFile($table,$column,$val,$where,$blobtype='BLOB')
{
switch(strtoupper($blobtype)) {
default: ADOConnection::outp( "<b>UpdateBlob</b>: Unknown blobtype=$blobtype"); return false;
case 'BLOB': $type = OCI_B_BLOB; break;
case 'CLOB': $type = OCI_B_CLOB; break;
}
if ($this->databaseType == 'oci8po')
$sql = "UPDATE $table set $column=EMPTY_{$blobtype}() WHERE $where RETURNING $column INTO ?";
else
$sql = "UPDATE $table set $column=EMPTY_{$blobtype}() WHERE $where RETURNING $column INTO :blob";
$desc = oci_new_descriptor($this->_connectionID, OCI_D_LOB);
$arr['blob'] = array($desc,-1,$type);
$this->BeginTrans();
$rs = ADODB_oci8::Execute($sql,$arr);
if ($rez = !empty($rs)) {
$desc->savefile($val);
}
$desc->free();
$this->CommitTrans();
if ($rez) {
$rs->Close();
}
return $rez;
}
function Execute($sql,$inputarr=false)
{
if ($this->fnExecute) {
$fn = $this->fnExecute;
$ret = $fn($this,$sql,$inputarr);
if (isset($ret)) {
return $ret;
}
}
if ($inputarr !== false) {
if (!is_array($inputarr)) {
$inputarr = array($inputarr);
}
$element0 = reset($inputarr);
$array2d = $this->bulkBind && is_array($element0) && !is_object(reset($element0));
# see PHPLens Issue No: 18786
if ($array2d || !$this->_bindInputArray) {
# is_object check because oci8 descriptors can be passed in
if ($array2d && $this->_bindInputArray) {
if (is_string($sql)) {
$stmt = $this->Prepare($sql);
} else {
$stmt = $sql;
}