]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/WikiDB/adodb/drivers/adodb-ibase.inc.php
No tabs
[SourceForge/phpwiki.git] / lib / WikiDB / adodb / drivers / adodb-ibase.inc.php
1 <?php
2 /*
3 V4.22 15 Apr 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). 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
8   Latest version is available at http://php.weblogs.com/
9
10   Interbase data driver. Requires interbase client. Works on Windows and Unix.
11
12   3 Jan 2002 -- suggestions by Hans-Peter Oeri <kampfcaspar75@oeri.ch>
13       changed transaction handling and added experimental blob stuff
14
15   Docs to interbase at the website
16    http://www.synectics.co.za/php3/tutorial/IB_PHP3_API.html
17
18   To use gen_id(), see
19    http://www.volny.cz/iprenosil/interbase/ip_ib_code.htm#_code_creategen
20
21    $rs = $conn->Execute('select gen_id(adodb,1) from rdb$database');
22    $id = $rs->fields[0];
23    $conn->Execute("insert into table (id, col1,...) values ($id, $val1,...)");
24 */
25
26
27 class ADODB_ibase extends ADOConnection {
28     var $databaseType = "ibase";
29     var $dataProvider = "ibase";
30     var $replaceQuote = "''"; // string to use to replace quotes
31     var $ibase_timefmt = '%Y-%m-%d'; // For hours,mins,secs change to '%Y-%m-%d %H:%M:%S';
32     var $fmtDate = "'Y-m-d'";
33     var $fmtTimeStamp = "'Y-m-d, H:i:s'";
34     var $concat_operator='||';
35     var $_transactionID;
36     var $metaTablesSQL = "select rdb\$relation_name from rdb\$relations where rdb\$relation_name not like 'RDB\$%'";
37     //OPN STUFF start
38     var $metaColumnsSQL = "select a.rdb\$field_name, a.rdb\$null_flag, a.rdb\$default_source, b.rdb\$field_length, b.rdb\$field_scale, b.rdb\$field_sub_type, b.rdb\$field_precision, b.rdb\$field_type from rdb\$relation_fields a, rdb\$fields b where a.rdb\$field_source = b.rdb\$field_name and a.rdb\$relation_name = '%s' order by a.rdb\$field_position asc";
39     //OPN STUFF end
40     var $ibasetrans;
41     var $hasGenID = true;
42     var $_bindInputArray = true;
43     var $buffers = 0;
44     var $dialect = 1;
45     var $sysDate = "cast('TODAY' as date)";
46     var $sysTimeStamp = "cast('NOW' as timestamp)";
47     var $ansiOuter = true;
48     var $hasAffectedRows = false;
49     var $poorAffectedRows = true;
50     var $blobEncodeType = 'C';
51
52     function ADODB_ibase()
53     {
54          if (defined('IBASE_DEFAULT')) $this->ibasetrans = IBASE_DEFAULT;
55       }
56
57     function MetaPrimaryKeys($table,$owner_notused=false,$internalKey=false)
58     {
59         if ($internalKey) return array('RDB$DB_KEY');
60
61         $table = strtoupper($table);
62
63         $sql = 'SELECT S.RDB$FIELD_NAME AFIELDNAME
64     FROM RDB$INDICES I JOIN RDB$INDEX_SEGMENTS S ON I.RDB$INDEX_NAME=S.RDB$INDEX_NAME
65     WHERE I.RDB$RELATION_NAME=\''.$table.'\' and I.RDB$INDEX_NAME like \'RDB$PRIMARY%\'
66     ORDER BY I.RDB$INDEX_NAME,S.RDB$FIELD_POSITION';
67
68         $a = $this->GetCol($sql,false,true);
69         if ($a && sizeof($a)>0) return $a;
70         return false;
71     }
72
73     function ServerInfo()
74     {
75         $arr['dialect'] = $this->dialect;
76         switch($arr['dialect']) {
77         case '':
78         case '1': $s = 'Interbase 5.5 or earlier'; break;
79         case '2': $s = 'Interbase 5.6'; break;
80         default:
81         case '3': $s = 'Interbase 6.0'; break;
82         }
83         $arr['version'] = ADOConnection::_findvers($s);
84         $arr['description'] = $s;
85         return $arr;
86     }
87
88     function BeginTrans()
89     {
90         if ($this->transOff) return true;
91         $this->transCnt += 1;
92         $this->autoCommit = false;
93          $this->_transactionID = $this->_connectionID;//ibase_trans($this->ibasetrans, $this->_connectionID);
94         return $this->_transactionID;
95     }
96
97     function CommitTrans($ok=true)
98     {
99         if (!$ok) return $this->RollbackTrans();
100         if ($this->transOff) return true;
101         if ($this->transCnt) $this->transCnt -= 1;
102         $ret = false;
103         $this->autoCommit = true;
104         if ($this->_transactionID) {
105                        //print ' commit ';
106             $ret = ibase_commit($this->_transactionID);
107         }
108         $this->_transactionID = false;
109         return $ret;
110     }
111
112     function RollbackTrans()
113     {
114         if ($this->transOff) return true;
115         if ($this->transCnt) $this->transCnt -= 1;
116         $ret = false;
117         $this->autoCommit = true;
118         if ($this->_transactionID)
119                   $ret = ibase_rollback($this->_transactionID);
120         $this->_transactionID = false;
121
122         return $ret;
123     }
124
125     function &MetaIndexes ($table, $primary = FALSE, $owner=false)
126     {
127         // save old fetch mode
128         global $ADODB_FETCH_MODE;
129
130         $save = $ADODB_FETCH_MODE;
131         $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
132         if ($this->fetchMode !== FALSE) {
133                $savem = $this->SetFetchMode(FALSE);
134         }
135         $table = strtoupper($table);
136         $sql = "SELECT * FROM RDB\$INDICES WHERE RDB\$RELATION_NAME = '".$table."'";
137         if (!$primary) {
138             $sql .= " AND RDB\$INDEX_NAME NOT LIKE 'RDB\$%'";
139         } else {
140             $sql .= " AND RDB\$INDEX_NAME NOT LIKE 'RDB\$FOREIGN%'";
141         }
142         // get index details
143         $rs = $this->Execute($sql);
144         if (!is_object($rs)) {
145             // restore fetchmode
146             if (isset($savem)) {
147                 $this->SetFetchMode($savem);
148             }
149             $ADODB_FETCH_MODE = $save;
150             return FALSE;
151         }
152
153         $indexes = array ();
154         while ($row = $rs->FetchRow()) {
155             $index = $row[0];
156              if (!isset($indexes[$index])) {
157                      if (is_null($row[3])) {$row[3] = 0;}
158                      $indexes[$index] = array(
159                              'unique' => ($row[3] == 1),
160                              'columns' => array()
161                      );
162              }
163             $sql = "SELECT * FROM RDB\$INDEX_SEGMENTS WHERE RDB\$INDEX_NAME = '".$name."' ORDER BY RDB\$FIELD_POSITION ASC";
164             $rs1 = $this->Execute($sql);
165             while ($row1 = $rs1->FetchRow()) {
166                  $indexes[$index]['columns'][$row1[2]] = $row1[1];
167             }
168         }
169         // restore fetchmode
170         if (isset($savem)) {
171             $this->SetFetchMode($savem);
172         }
173         $ADODB_FETCH_MODE = $save;
174
175         return $indexes;
176     }
177
178
179     // See http://community.borland.com/article/0,1410,25844,00.html
180     function RowLock($tables,$where,$col)
181     {
182         if ($this->autoCommit) $this->BeginTrans();
183         $this->Execute("UPDATE $table SET $col=$col WHERE $where "); // is this correct - jlim?
184         return 1;
185     }
186
187
188     function CreateSequence($seqname,$startID=1)
189     {
190         $ok = $this->Execute(("INSERT INTO RDB\$GENERATORS (RDB\$GENERATOR_NAME) VALUES (UPPER('$seqname'))" ));
191         if (!$ok) return false;
192         return $this->Execute("SET GENERATOR $seqname TO ".($startID-1).';');
193     }
194
195     function DropSequence($seqname)
196     {
197         $seqname = strtoupper($seqname);
198         $this->Execute("delete from RDB\$GENERATORS where RDB\$GENERATOR_NAME='$seqname'");
199     }
200
201     function GenID($seqname='adodbseq',$startID=1)
202     {
203         $getnext = ("SELECT Gen_ID($seqname,1) FROM RDB\$DATABASE");
204         $rs = @$this->Execute($getnext);
205         if (!$rs) {
206             $this->Execute(("INSERT INTO RDB\$GENERATORS (RDB\$GENERATOR_NAME) VALUES (UPPER('$seqname'))" ));
207             $this->Execute("SET GENERATOR $seqname TO ".($startID-1).';');
208             $rs = $this->Execute($getnext);
209         }
210         if ($rs && !$rs->EOF) $this->genID = (integer) reset($rs->fields);
211         else $this->genID = 0; // false
212
213         if ($rs) $rs->Close();
214
215         return $this->genID;
216     }
217
218     function SelectDB($dbName)
219     {
220            return false;
221     }
222
223     function _handleerror()
224     {
225         $this->_errorMsg = ibase_errmsg();
226     }
227
228     function ErrorNo()
229     {
230         if (preg_match('/error code = ([\-0-9]*)/i', $this->_errorMsg,$arr)) return (integer) $arr[1];
231         else return 0;
232     }
233
234     function ErrorMsg()
235     {
236             return $this->_errorMsg;
237     }
238
239        // returns true or false
240     function _connect($argHostname, $argUsername, $argPassword, $argDatabasename)
241     {
242         if (!function_exists('ibase_pconnect')) return false;
243         if ($argDatabasename) $argHostname .= ':'.$argDatabasename;
244         $this->_connectionID = ibase_connect($argHostname,$argUsername,$argPassword,$this->charSet,$this->buffers,$this->dialect);
245          if ($this->dialect != 1) { // http://www.ibphoenix.com/ibp_60_del_id_ds.html
246             $this->replaceQuote = "''";
247         }
248         if ($this->_connectionID === false) {
249             $this->_handleerror();
250             return false;
251         }
252
253         ibase_timefmt($this->ibase_timefmt);
254         return true;
255     }
256        // returns true or false
257     function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename)
258     {
259         if (!function_exists('ibase_pconnect')) return false;
260         if ($argDatabasename) $argHostname .= ':'.$argDatabasename;
261         $this->_connectionID = ibase_pconnect($argHostname,$argUsername,$argPassword,$this->charSet,$this->buffers,$this->dialect);
262         if ($this->dialect != 1) { // http://www.ibphoenix.com/ibp_60_del_id_ds.html
263             $this->replaceQuote = "''";
264         }
265         if ($this->_connectionID === false) {
266             $this->_handleerror();
267             return false;
268         }
269
270         ibase_timefmt($this->ibase_timefmt);
271         return true;
272     }
273
274     function Prepare($sql)
275     {
276         $stmt = ibase_prepare($this->_connectionID,$sql);
277         if (!$stmt) return false;
278         return array($sql,$stmt);
279     }
280
281        // returns query ID if successful, otherwise false
282        // there have been reports of problems with nested queries - the code is probably not re-entrant?
283     function _query($sql,$iarr=false)
284     {
285
286         if (!$this->autoCommit && $this->_transactionID) {
287             $conn = $this->_transactionID;
288             $docommit = false;
289         } else {
290             $conn = $this->_connectionID;
291             $docommit = true;
292         }
293         if (is_array($sql)) {
294             $fn = 'ibase_execute';
295             $sql = $sql[1];
296
297             if (is_array($iarr)) {
298                 if  (ADODB_PHPVER >= 0x4050) { // actually 4.0.4
299                     if ( !isset($iarr[0]) ) $iarr[0] = ''; // PHP5 compat hack
300                     $fnarr =& array_merge( array($sql) , $iarr);
301                     $ret = call_user_func_array($fn,$fnarr);
302                 } else {
303                     switch(sizeof($iarr)) {
304                     case 1: $ret = $fn($sql,$iarr[0]); break;
305                     case 2: $ret = $fn($sql,$iarr[0],$iarr[1]); break;
306                     case 3: $ret = $fn($sql,$iarr[0],$iarr[1],$iarr[2]); break;
307                     case 4: $ret = $fn($sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3]); break;
308                     case 5: $ret = $fn($sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3],$iarr[4]); break;
309                     case 6: $ret = $fn($sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3],$iarr[4],$iarr[5]); break;
310                     case 7: $ret = $fn($sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3],$iarr[4],$iarr[5],$iarr[6]); break;
311                     default: ADOConnection::outp( "Too many parameters to ibase query $sql");
312                     case 8: $ret = $fn($sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3],$iarr[4],$iarr[5],$iarr[6],$iarr[7]); break;
313                     }
314                 }
315             } else $ret = $fn($sql);
316         } else {
317             $fn = 'ibase_query';
318
319             if (is_array($iarr)) {
320                 if (ADODB_PHPVER >= 0x4050) { // actually 4.0.4
321                     if ( !isset($iarr[0]) ) $iarr[0] = ''; // PHP5 compat hack
322                     $fnarr =& array_merge( array($conn,$sql) , $iarr);
323                     $ret = call_user_func_array($fn,$fnarr);
324                 } else {
325                     switch(sizeof($iarr)) {
326                     case 1: $ret = $fn($conn,$sql,$iarr[0]); break;
327                     case 2: $ret = $fn($conn,$sql,$iarr[0],$iarr[1]); break;
328                     case 3: $ret = $fn($conn,$sql,$iarr[0],$iarr[1],$iarr[2]); break;
329                     case 4: $ret = $fn($conn,$sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3]); break;
330                     case 5: $ret = $fn($conn,$sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3],$iarr[4]); break;
331                     case 6: $ret = $fn($conn,$sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3],$iarr[4],$iarr[5]); break;
332                     case 7: $ret = $fn($conn,$sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3],$iarr[4],$iarr[5],$iarr[6]); break;
333                     default: ADOConnection::outp( "Too many parameters to ibase query $sql");
334                     case 8: $ret = $fn($conn,$sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3],$iarr[4],$iarr[5],$iarr[6],$iarr[7]); break;
335                     }
336                 }
337             } else $ret = $fn($conn,$sql);
338         }
339         if ($docommit && $ret === true) ibase_commit($this->_connectionID);
340
341         $this->_handleerror();
342         return $ret;
343     }
344
345      // returns true or false
346      function _close()
347      {
348         if (!$this->autoCommit) @ibase_rollback($this->_connectionID);
349         return @ibase_close($this->_connectionID);
350      }
351
352     //OPN STUFF start
353     function _ConvertFieldType(&$fld, $ftype, $flen, $fscale, $fsubtype, $fprecision, $isInterbase6)
354     {
355         $fscale = abs($fscale);
356         $fld->max_length = $flen;
357         $fld->scale = null;
358         switch($ftype){
359             case 7:
360             case 8:
361                 if ($isInterbase6) {
362                     switch($fsubtype){
363                         case 0:
364                             $fld->type = ($ftype == 7 ? 'smallint' : 'integer');
365                             break;
366                         case 1:
367                             $fld->type = 'numeric';
368                             $fld->max_length = $fprecision;
369                             $fld->scale = $fscale;
370                             break;
371                         case 2:
372                             $fld->type = 'decimal';
373                             $fld->max_length = $fprecision;
374                             $fld->scale = $fscale;
375                             break;
376                     } // switch
377                 } else {
378                     if ($fscale !=0) {
379                         $fld->type = 'decimal';
380                         $fld->scale = $fscale;
381                         $fld->max_length = ($ftype == 7 ? 4 : 9);
382                     } else {
383                         $fld->type = ($ftype == 7 ? 'smallint' : 'integer');
384                     }
385                 }
386                 break;
387             case 16:
388                 if ($isInterbase6) {
389                     switch($fsubtype){
390                         case 0:
391                             $fld->type = 'decimal';
392                             $fld->max_length = 18;
393                             $fld->scale = 0;
394                             break;
395                         case 1:
396                             $fld->type = 'numeric';
397                             $fld->max_length = $fprecision;
398                             $fld->scale = $fscale;
399                             break;
400                         case 2:
401                             $fld->type = 'decimal';
402                             $fld->max_length = $fprecision;
403                             $fld->scale = $fscale;
404                             break;
405                     } // switch
406                 }
407                 break;
408             case 10:
409                 $fld->type = 'float';
410                 break;
411             case 14:
412                 $fld->type = 'char';
413                 break;
414             case 27:
415                 if ($fscale !=0) {
416                     $fld->type = 'decimal';
417                     $fld->max_length = 15;
418                     $fld->scale = 5;
419                 } else {
420                     $fld->type = 'double';
421                 }
422                 break;
423             case 35:
424                 if ($isInterbase6) {
425                     $fld->type = 'timestamp';
426                 } else {
427                     $fld->type = 'date';
428                 }
429                 break;
430             case 12:
431             case 13:
432                 $fld->type = 'date';
433                 break;
434             case 37:
435                 $fld->type = 'varchar';
436                 break;
437             case 40:
438                 $fld->type = 'cstring';
439                 break;
440             case 261:
441                 $fld->type = 'blob';
442                 $fld->max_length = -1;
443                 break;
444         } // switch
445     }
446     //OPN STUFF end
447         // returns array of ADOFieldObjects for current table
448     function &MetaColumns($table)
449     {
450     global $ADODB_FETCH_MODE;
451
452         if ($this->metaColumnsSQL) {
453
454             $save = $ADODB_FETCH_MODE;
455             $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
456
457             $rs = $this->Execute(sprintf($this->metaColumnsSQL,strtoupper($table)));
458
459             $ADODB_FETCH_MODE = $save;
460             if ($rs === false) return false;
461
462             $retarr = array();
463             //OPN STUFF start
464             $isInterbase6 = ($this->dialect==3 ? true : false);
465             //OPN STUFF end
466             while (!$rs->EOF) { //print_r($rs->fields);
467                 $fld = new ADOFieldObject();
468                 $fld->name = trim($rs->fields[0]);
469                 //OPN STUFF start
470                 $this->_ConvertFieldType($fld, $rs->fields[7], $rs->fields[3], $rs->fields[4], $rs->fields[5], $rs->fields[6], $isInterbase6);
471                 if (isset($rs->fields[1]) && $rs->fields[1]) {
472                     $fld->not_null = true;
473                 }
474                 if (isset($rs->fields[2])) {
475
476                     $fld->has_default = true;
477                     $d = substr($rs->fields[2],strlen('default '));
478                     switch ($fld->type)
479                     {
480                     case 'smallint':
481                     case 'integer': $fld->default_value = (int) $d; break;
482                     case 'char':
483                     case 'blob':
484                     case 'text':
485                     case 'varchar': $fld->default_value = (string) substr($d,1,strlen($d)-2); break;
486                     case 'double':
487                     case 'float': $fld->default_value = (float) $d; break;
488                     default: $fld->default_value = $d; break;
489                     }
490             //  case 35:$tt = 'TIMESTAMP'; break;
491                 }
492                 if ((isset($rs->fields[5])) && ($fld->type == 'blob')) {
493                     $fld->sub_type = $rs->fields[5];
494                 } else {
495                     $fld->sub_type = null;
496                 }
497                 //OPN STUFF end
498                 if ($ADODB_FETCH_MODE == ADODB_FETCH_NUM) $retarr[] = $fld;
499                 else $retarr[strtoupper($fld->name)] = $fld;
500
501                 $rs->MoveNext();
502             }
503             $rs->Close();
504             return $retarr;
505         }
506         return false;
507     }
508
509     function BlobEncode( $blob )
510     {
511         $blobid = ibase_blob_create( $this->_connectionID);
512         ibase_blob_add( $blobid, $blob );
513         return ibase_blob_close( $blobid );
514     }
515
516     // since we auto-decode all blob's since 2.42,
517     // BlobDecode should not do any transforms
518     function BlobDecode($blob)
519     {
520         return $blob;
521     }
522
523
524
525
526     // old blobdecode function
527     // still used to auto-decode all blob's
528     function _BlobDecode( $blob )
529     {
530         $blobid = ibase_blob_open( $blob );
531         $realblob = ibase_blob_get( $blobid,$this->maxblobsize); // 2nd param is max size of blob -- Kevin Boillet <kevinboillet@yahoo.fr>
532         while($string = ibase_blob_get($blobid, 8192)){
533             $realblob .= $string;
534         }
535         ibase_blob_close( $blobid );
536
537         return( $realblob );
538     }
539
540     function UpdateBlobFile($table,$column,$path,$where,$blobtype='BLOB')
541     {
542         $fd = fopen($path,'rb');
543         if ($fd === false) return false;
544         $blob_id = ibase_blob_create($this->_connectionID);
545
546         /* fill with data */
547
548         while ($val = fread($fd,32768)){
549             ibase_blob_add($blob_id, $val);
550         }
551
552         /* close and get $blob_id_str for inserting into table */
553         $blob_id_str = ibase_blob_close($blob_id);
554
555         fclose($fd);
556         return $this->Execute("UPDATE $table SET $column=(?) WHERE $where",array($blob_id_str)) != false;
557     }
558
559     /*
560         Insert a null into the blob field of the table first.
561         Then use UpdateBlob to store the blob.
562
563         Usage:
564
565         $conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, null)');
566         $conn->UpdateBlob('blobtable','blobcol',$blob,'id=1');
567     */
568     function UpdateBlob($table,$column,$val,$where,$blobtype='BLOB')
569     {
570     $blob_id = ibase_blob_create($this->_connectionID);
571
572     // ibase_blob_add($blob_id, $val);
573
574     // replacement that solves the problem by which only the first modulus 64K /
575     // of $val are stored at the blob field ////////////////////////////////////
576     // Thx Abel Berenstein  aberenstein#afip.gov.ar
577     $len = strlen($val);
578     $chunk_size = 32768;
579     $tail_size = $len % $chunk_size;
580     $n_chunks = ($len - $tail_size) / $chunk_size;
581
582     for ($n = 0; $n < $n_chunks; $n++) {
583         $start = $n * $chunk_size;
584         $data = substr($val, $start, $chunk_size);
585         ibase_blob_add($blob_id, $data);
586     }
587
588     if ($tail_size) {
589         $start = $n_chunks * $chunk_size;
590         $data = substr($val, $start, $tail_size);
591         ibase_blob_add($blob_id, $data);
592     }
593     // end replacement /////////////////////////////////////////////////////////
594
595     $blob_id_str = ibase_blob_close($blob_id);
596
597     return $this->Execute("UPDATE $table SET $column=(?) WHERE $where",array($blob_id_str)) != false;
598
599     }
600
601
602     function OldUpdateBlob($table,$column,$val,$where,$blobtype='BLOB')
603     {
604         $blob_id = ibase_blob_create($this->_connectionID);
605         ibase_blob_add($blob_id, $val);
606         $blob_id_str = ibase_blob_close($blob_id);
607         return $this->Execute("UPDATE $table SET $column=(?) WHERE $where",array($blob_id_str)) != false;
608     }
609
610     // Format date column in sql string given an input format that understands Y M D
611     // Only since Interbase 6.0 - uses EXTRACT
612     // problem - does not zero-fill the day and month yet
613     function SQLDate($fmt, $col=false)
614     {
615         if (!$col) $col = $this->sysDate;
616         $s = '';
617
618         $len = strlen($fmt);
619         for ($i=0; $i < $len; $i++) {
620             if ($s) $s .= '||';
621             $ch = $fmt[$i];
622             switch($ch) {
623             case 'Y':
624             case 'y':
625                 $s .= "extract(year from $col)";
626                 break;
627             case 'M':
628             case 'm':
629                 $s .= "extract(month from $col)";
630                 break;
631             case 'Q':
632             case 'q':
633                 $s .= "cast(((extract(month from $col)+2) / 3) as integer)";
634                 break;
635             case 'D':
636             case 'd':
637                 $s .= "(extract(day from $col))";
638                 break;
639             case 'H':
640             case 'h':
641               $s .= "(extract(hour from $col))";
642               break;
643             case 'I':
644             case 'i':
645               $s .= "(extract(minute from $col))";
646               break;
647             case 'S':
648             case 's':
649               $s .= "CAST((extract(second from $col)) AS INTEGER)";
650               break;
651
652             default:
653                 if ($ch == '\\') {
654                     $i++;
655                     $ch = substr($fmt,$i,1);
656                 }
657                 $s .= $this->qstr($ch);
658                 break;
659             }
660         }
661         return $s;
662     }
663 }
664
665 /*--------------------------------------------------------------------------------------
666          Class Name: Recordset
667 --------------------------------------------------------------------------------------*/
668
669 class ADORecordset_ibase extends ADORecordSet
670 {
671
672     var $databaseType = "ibase";
673     var $bind=false;
674     var $_cacheType;
675
676     function ADORecordset_ibase($id,$mode=false)
677     {
678     global $ADODB_FETCH_MODE;
679
680             $this->fetchMode = ($mode === false) ? $ADODB_FETCH_MODE : $mode;
681             return $this->ADORecordSet($id);
682     }
683
684     /*          Returns: an object containing field information.
685             Get column information in the Recordset object. fetchField() can be used in order to obtain information about
686             fields in a certain query result. If the field offset isn't specified, the next field that wasn't yet retrieved by
687             fetchField() is retrieved.          */
688
689     function &FetchField($fieldOffset = -1)
690     {
691              $fld = new ADOFieldObject;
692              $ibf = ibase_field_info($this->_queryID,$fieldOffset);
693              $fld->name = strtolower($ibf['alias']);
694              if (empty($fld->name)) $fld->name = strtolower($ibf['name']);
695              $fld->type = $ibf['type'];
696              $fld->max_length = $ibf['length'];
697              return $fld;
698     }
699
700     function _initrs()
701     {
702             $this->_numOfRows = -1;
703             $this->_numOfFields = @ibase_num_fields($this->_queryID);
704
705             // cache types for blob decode check
706             for ($i=0, $max = $this->_numOfFields; $i < $max; $i++) {
707                 $f1 = $this->FetchField($i);
708                 $this->_cacheType[] = $f1->type;
709             }
710     }
711
712     function _seek($row)
713     {
714         return false;
715     }
716
717
718
719     function _fetch()
720     {
721         $f = @ibase_fetch_row($this->_queryID);
722         if ($f === false) {
723             $this->fields = false;
724             return false;
725         }
726         // OPN stuff start - optimized
727         // fix missing nulls and decode blobs automatically
728
729         global $ADODB_ANSI_PADDING_OFF;
730         //$ADODB_ANSI_PADDING_OFF=1;
731         $rtrim = !empty($ADODB_ANSI_PADDING_OFF);
732
733         for ($i=0, $max = $this->_numOfFields; $i < $max; $i++) {
734             if ($this->_cacheType[$i]=="BLOB") {
735                 if (isset($f[$i])) {
736                     $f[$i] = $this->connection->_BlobDecode($f[$i]);
737                 } else {
738                     $f[$i] = null;
739                 }
740             } else {
741                 if (!isset($f[$i])) {
742                     $f[$i] = null;
743                 } else if ($rtrim && is_string($f[$i])) {
744                     $f[$i] = rtrim($f[$i]);
745                 }
746             }
747         }
748         // OPN stuff end
749
750         $this->fields = $f;
751         if ($this->fetchMode == ADODB_FETCH_ASSOC) {
752             $this->fields = &$this->GetRowAssoc(ADODB_ASSOC_CASE);
753         } else if ($this->fetchMode == ADODB_FETCH_BOTH) {
754             $this->fields =& array_merge($this->fields,$this->GetRowAssoc(ADODB_ASSOC_CASE));
755         }
756         return true;
757     }
758
759     /* Use associative array to get fields array */
760     function Fields($colname)
761     {
762         if ($this->fetchMode & ADODB_FETCH_ASSOC) return $this->fields[$colname];
763         if (!$this->bind) {
764             $this->bind = array();
765             for ($i=0; $i < $this->_numOfFields; $i++) {
766                 $o = $this->FetchField($i);
767                 $this->bind[strtoupper($o->name)] = $i;
768             }
769         }
770
771          return $this->fields[$this->bind[strtoupper($colname)]];
772
773     }
774
775
776     function _close()
777     {
778             return @ibase_free_result($this->_queryID);
779     }
780
781     function MetaType($t,$len=-1,$fieldobj=false)
782     {
783         if (is_object($t)) {
784             $fieldobj = $t;
785             $t = $fieldobj->type;
786             $len = $fieldobj->max_length;
787         }
788         switch (strtoupper($t)) {
789         case 'CHAR':
790             return 'C';
791
792         case 'TEXT':
793         case 'VARCHAR':
794         case 'VARYING':
795         if ($len <= $this->blobSize) return 'C';
796             return 'X';
797         case 'BLOB':
798             return 'B';
799
800         case 'TIMESTAMP':
801         case 'DATE': return 'D';
802
803                 //case 'T': return 'T';
804
805                 //case 'L': return 'L';
806         case 'INT':
807         case 'SHORT':
808         case 'INTEGER': return 'I';
809         default: return 'N';
810         }
811     }
812
813 }
814 ?>