thomascube
2005-11-08 583f1c8d80c42195d0ee41f30a885e13d777b79f
commit | author | age
c9462d 1 <?php
S 2 // vim: set et ts=4 sw=4 fdm=marker:
3 // +----------------------------------------------------------------------+
4 // | PHP versions 4 and 5                                                 |
5 // +----------------------------------------------------------------------+
6 // | Copyright (c) 1998-2004 Manuel Lemos, Tomas V.V.Cox,                 |
7 // | Stig. S. Bakken, Lukas Smith                                         |
8 // | All rights reserved.                                                 |
9 // +----------------------------------------------------------------------+
10 // | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB  |
11 // | API as well as database abstraction for PHP applications.            |
12 // | This LICENSE is in the BSD license style.                            |
13 // |                                                                      |
14 // | Redistribution and use in source and binary forms, with or without   |
15 // | modification, are permitted provided that the following conditions   |
16 // | are met:                                                             |
17 // |                                                                      |
18 // | Redistributions of source code must retain the above copyright       |
19 // | notice, this list of conditions and the following disclaimer.        |
20 // |                                                                      |
21 // | Redistributions in binary form must reproduce the above copyright    |
22 // | notice, this list of conditions and the following disclaimer in the  |
23 // | documentation and/or other materials provided with the distribution. |
24 // |                                                                      |
25 // | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken,    |
26 // | Lukas Smith nor the names of his contributors may be used to endorse |
27 // | or promote products derived from this software without specific prior|
28 // | written permission.                                                  |
29 // |                                                                      |
30 // | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS  |
31 // | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT    |
32 // | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS    |
33 // | FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE      |
34 // | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,          |
35 // | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
36 // | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
37 // |  OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED  |
38 // | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT          |
39 // | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
40 // | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE          |
41 // | POSSIBILITY OF SUCH DAMAGE.                                          |
42 // +----------------------------------------------------------------------+
43 // | Author: Lukas Smith <smith@pooteeweet.org>                           |
44 // +----------------------------------------------------------------------+
45
46 // $Id$
47
48 /**
49  * MDB2 OCI8 driver
50  *
51  * @package MDB2
52  * @category Database
53  * @author Lukas Smith <smith@pooteeweet.org>
54  */
55 class MDB2_Driver_oci8 extends MDB2_Driver_Common
56 {
57     // {{{ properties
58     var $escape_quotes = "'";
59
60     var $uncommitedqueries = 0;
61
62     // }}}
63     // {{{ constructor
64
65     /**
66      * Constructor
67      */
68     function __construct()
69     {
70         parent::__construct();
71
72         $this->phptype = 'oci8';
73         $this->dbsyntax = 'oci8';
74
75         $this->supported['sequences'] = true;
76         $this->supported['indexes'] = true;
77         $this->supported['summary_functions'] = true;
78         $this->supported['order_by_text'] = true;
79         $this->supported['current_id'] = true;
80         $this->supported['affected_rows'] = true;
81         $this->supported['transactions'] = true;
82         $this->supported['limit_queries'] = 'emulated';
83         $this->supported['LOBs'] = true;
84         $this->supported['replace'] = 'emulated';
85         $this->supported['sub_selects'] = true;
86         $this->supported['auto_increment'] = false; // not implemented
87         $this->supported['primary_key'] =  false; // not implemented
88
89         $this->options['DBA_username'] = false;
90         $this->options['DBA_password'] = false;
91         $this->options['database_name_prefix'] = false;
92         $this->options['emulate_database'] = true;
93         $this->options['default_tablespace'] = false;
94         $this->options['default_text_field_length'] = 4000;
95     }
96
97     // }}}
98     // {{{ errorInfo()
99
100     /**
101      * This method is used to collect information about an error
102      *
103      * @param integer $error
104      * @return array
105      * @access public
106      */
107     function errorInfo($error = null)
108     {
109         if (is_resource($error)) {
110             $error_data = @OCIError($error);
111             $error = null;
112         } elseif ($this->connection) {
113             $error_data = @OCIError($this->connection);
114         } else {
115             $error_data = @OCIError();
116         }
117         $native_code = $error_data['code'];
118         $native_msg  = $error_data['message'];
119         if (is_null($error)) {
120             static $ecode_map;
121             if (empty($ecode_map)) {
122                 $ecode_map = array(
123                     1    => MDB2_ERROR_CONSTRAINT,
124                     900  => MDB2_ERROR_SYNTAX,
125                     904  => MDB2_ERROR_NOSUCHFIELD,
126                     913  => MDB2_ERROR_VALUE_COUNT_ON_ROW,
127                     921  => MDB2_ERROR_SYNTAX,
128                     923  => MDB2_ERROR_SYNTAX,
129                     942  => MDB2_ERROR_NOSUCHTABLE,
130                     955  => MDB2_ERROR_ALREADY_EXISTS,
131                     1400 => MDB2_ERROR_CONSTRAINT_NOT_NULL,
132                     1401 => MDB2_ERROR_INVALID,
133                     1407 => MDB2_ERROR_CONSTRAINT_NOT_NULL,
134                     1418 => MDB2_ERROR_NOT_FOUND,
135                     1476 => MDB2_ERROR_DIVZERO,
136                     1722 => MDB2_ERROR_INVALID_NUMBER,
137                     2289 => MDB2_ERROR_NOSUCHTABLE,
138                     2291 => MDB2_ERROR_CONSTRAINT,
139                     2292 => MDB2_ERROR_CONSTRAINT,
140                     2449 => MDB2_ERROR_CONSTRAINT,
141                 );
142             }
143             if (isset($ecode_map[$native_code])) {
144                 $error = $ecode_map[$native_code];
145             }
146         }
147         return array($error, $native_code, $native_msg);
148     }
149
150     // }}}
151     // {{{ beginTransaction()
152
153     /**
154      * Start a transaction.
155      *
156      * @return mixed MDB2_OK on success, a MDB2 error on failure
157      * @access public
158      */
159     function beginTransaction()
160     {
161         $this->debug('starting transaction', 'beginTransaction');
162         if ($this->in_transaction) {
163             return MDB2_OK;  //nothing to do
164         }
165         if (!$this->destructor_registered && $this->opened_persistent) {
166             $this->destructor_registered = true;
167             register_shutdown_function('MDB2_closeOpenTransactions');
168         }
169         $this->in_transaction = true;
170         ++$this->uncommitedqueries;
171         return MDB2_OK;
172     }
173
174     // }}}
175     // {{{ commit()
176
177     /**
178      * Commit the database changes done during a transaction that is in
179      * progress.
180      *
181      * @return mixed MDB2_OK on success, a MDB2 error on failure
182      * @access public
183      */
184     function commit()
185     {
186         $this->debug('commit transaction', 'commit');
187         if (!$this->in_transaction) {
188             return $this->raiseError(MDB2_ERROR, null, null,
189                 'commit: transaction changes are being auto committed');
190         }
191         if ($this->uncommitedqueries) {
192             if (!@OCICommit($this->connection)) {
193                 return $this->raiseError();
194             }
195             $this->uncommitedqueries = 0;
196         }
197         $this->in_transaction = false;
198         return MDB2_OK;
199     }
200
201     // }}}
202     // {{{ rollback()
203
204     /**
205      * Cancel any database changes done during a transaction that is in
206      * progress.
207      *
208      * @return mixed MDB2_OK on success, a MDB2 error on failure
209      * @access public
210      */
211     function rollback()
212     {
213         $this->debug('rolling back transaction', 'rollback');
214         if (!$this->in_transaction) {
215             return $this->raiseError(MDB2_ERROR, null, null,
216                 'rollback: transactions can not be rolled back when changes are auto committed');
217         }
218         if ($this->uncommitedqueries) {
219             if (!@OCIRollback($this->connection)) {
220                 return $this->raiseError();
221             }
222             $this->uncommitedqueries = 0;
223         }
224         $this->in_transaction = false;
225         return MDB2_OK;
226     }
227
228     // }}}
229     // {{{ _doConnect()
230
231     /**
232      * do the grunt work of the connect
233      *
234      * @return connection on success or MDB2 Error Object on failure
235      * @access protected
236      */
237     function _doConnect($username, $password, $persistent = false)
238     {
239         if (!PEAR::loadExtension($this->phptype)) {
240             return $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
241                 'extension '.$this->phptype.' is not compiled into PHP');
242         }
243
244         if (isset($this->dsn['hostspec'])) {
245             $sid = $this->dsn['hostspec'];
246         } else {
247             $sid = getenv('ORACLE_SID');
248         }
249         if (empty($sid)) {
250             return $this->raiseError(MDB2_ERROR, null, null,
251                 'it was not specified a valid Oracle Service Identifier (SID)');
252         }
253
254         if (function_exists('oci_connect')) {
255             if (isset($this->dsn['new_link'])
256                 && ($this->dsn['new_link'] == 'true' || $this->dsn['new_link'] === true)
257             ) {
258                 $connect_function = 'oci_new_connect';
259             } else {
260                 $connect_function = $persistent ? 'oci_pconnect' : 'oci_connect';
261             }
262
263             $charset = empty($this->dsn['charset']) ? null : $this->dsn['charset'];
264             $connection = @$connect_function($username, $password, $sid, $charset);
265             $error = @OCIError();
266             if (isset($error['code']) && $error['code'] == 12541) {
267                 // Couldn't find TNS listener.  Try direct connection.
268                 $connection = @$connect_function($username, $password, null, $charset);
269             }
270         } else {
271             $connect_function = $persistent ? 'OCIPLogon' : 'OCILogon';
272             $connection = @$connect_function($username, $password, $sid);
273         }
274
275         if (!$connection) {
276             return $this->raiseError(MDB2_ERROR_CONNECT_FAILED);
277         }
278
279         return $connection;
280     }
281
282     // }}}
283     // {{{ connect()
284
285     /**
286      * Connect to the database
287      *
288      * @return MDB2_OK on success, MDB2 Error Object on failure
289      * @access public
290      */
291     function connect()
292     {
293         if ($this->database_name && $this->options['emulate_database']) {
294              $this->dsn['username'] = $this->options['database_name_prefix'].$this->database_name;
295         }
296         if (is_resource($this->connection)) {
297             if (count(array_diff($this->connected_dsn, $this->dsn)) == 0
298                 && $this->opened_persistent == $this->options['persistent']
299             ) {
300                 return MDB2_OK;
301             }
302             $this->disconnect(false);
303         }
304
305         $connection = $this->_doConnect(
306             $this->dsn['username'],
307             $this->dsn['password'],
308             $this->options['persistent']
309         );
310         if (PEAR::isError($connection)) {
311             return $connection;
312         }
313         $this->connection = $connection;
314         $this->connected_dsn = $this->dsn;
315         $this->opened_persistent = $this->options['persistent'];
316         $this->dbsyntax = $this->dsn['dbsyntax'] ? $this->dsn['dbsyntax'] : $this->phptype;
317
318         $query = "ALTER SESSION SET NLS_DATE_FORMAT='YYYY-MM-DD HH24:MI:SS'";
319         $err = $this->_doQuery($query, true);
320         if (PEAR::isError($err)) {
321             $this->disconnect(false);
322             return $err;
323         }
324
325         $query = "ALTER SESSION SET NLS_NUMERIC_CHARACTERS='. '";
326         $err = $this->_doQuery($query, true);
327         if (PEAR::isError($err)) {
328             $this->disconnect(false);
329             return $err;
330         }
331
332         return MDB2_OK;
333     }
334
335     // }}}
336     // {{{ disconnect()
337
338     /**
339      * Log out and disconnect from the database.
340      *
341      * @return mixed true on success, false if not connected and error
342      *                object on error
343      * @access public
344      */
345     function disconnect($force = true)
346     {
347         if (is_resource($this->connection)) {
348             if (!$this->opened_persistent || $force) {
349                 if (function_exists('oci_close')) {
350                     @oci_close($this->connection);
351                 } else {
352                     @OCILogOff($this->connection);
353                 }
354             }
355             $this->connection = 0;
356             $this->uncommitedqueries = 0;
357         }
358         return MDB2_OK;
359     }
360
361     // }}}
362     // {{{ standaloneQuery()
363
364    /**
365      * execute a query as DBA
366      *
367      * @param string $query the SQL query
368      * @param mixed   $types  array that contains the types of the columns in
369      *                        the result set
370      * @return mixed MDB2_OK on success, a MDB2 error on failure
371      * @access public
372      */
373     function &standaloneQuery($query, $types = null)
374     {
375         $connection = $this->_doConnect(
376             $this->options['DBA_username'],
377             $this->options['DBA_password'],
378             $this->options['persistent']
379         );
380         if (PEAR::isError($connection)) {
381             return $connection;
382         }
383
384         $isManip = MDB2::isManip($query);
385         $offset = $this->row_offset;
386         $limit = $this->row_limit;
387         $this->row_offset = $this->row_limit = 0;
388         $query = $this->_modifyQuery($query, $isManip, $limit, $offset);
389
390         $result = $this->_doQuery($query, $isManip, $connection, false);
391
392         @OCILogOff($connection);
393         if (PEAR::isError($result)) {
394             return $result;
395         }
396
397         if ($isManip) {
398             return $result;
399         }
400         $return =& $this->_wrapResult($result, $types, true, false, $limit, $offset);
401         return $return;
402     }
403
404     // }}}
405     // {{{ _modifyQuery()
406
407     /**
408      * Changes a query string for various DBMS specific reasons
409      *
410      * @param string $query  query to modify
411      * @return the new (modified) query
412      * @access protected
413      */
414     function _modifyQuery($query)
415     {
416         // "SELECT 2+2" must be "SELECT 2+2 FROM dual" in Oracle
417         if (preg_match('/^\s*SELECT/i', $query)
418             && !preg_match('/\sFROM\s/i', $query)
419         ) {
420             $query.= " FROM dual";
421         }
422         return $query;
423     }
424
425     // }}}
426     // {{{ _doQuery()
427
428     /**
429      * Execute a query
430      * @param string $query  query
431      * @param boolean $isManip  if the query is a manipulation query
432      * @param resource $connection
433      * @param string $database_name
434      * @return result or error object
435      * @access protected
436      */
437     function _doQuery($query, $isManip = false, $connection = null, $database_name = null)
438     {
439         $this->last_query = $query;
440         $this->debug($query, 'query');
441         if ($this->getOption('disable_query')) {
442             if ($isManip) {
443                 return 0;
444             }
445             return null;
446         }
447
448         if (is_null($connection)) {
449             $err = $this->connect();
450             if (PEAR::isError($err)) {
451                 return $err;
452             }
453             $connection = $this->connection;
454         }
455
456         $result = @OCIParse($connection, $query);
457         if (!$result) {
458             return $this->raiseError(MDB2_ERROR, null, null,
459                 'Could not create statement');
460         }
461
462         $mode = $this->in_transaction ? OCI_DEFAULT : OCI_COMMIT_ON_SUCCESS;
463         if (!@OCIExecute($result, $mode)) {
464             return $this->raiseError($result);
465         }
466
467         if ($isManip) {
468             return @OCIRowCount($result);
469         }
470
471         if (is_numeric($this->options['result_buffering'])) {
472             @ocisetprefetch($result, $this->options['result_buffering']);
473         }
474         return $result;
475     }
476
477     // }}}
478     // {{{ prepare()
479
480     /**
481      * Prepares a query for multiple execution with execute().
482      * With some database backends, this is emulated.
483      * prepare() requires a generic query as string like
484      * 'INSERT INTO numbers VALUES(?,?)' or
485      * 'INSERT INTO numbers VALUES(:foo,:bar)'.
486      * The ? and :[a-zA-Z] and  are placeholders which can be set using
487      * bindParam() and the query can be send off using the execute() method.
488      *
489      * @param string $query the query to prepare
490      * @param mixed   $types  array that contains the types of the placeholders
491      * @param mixed   $result_types  array that contains the types of the columns in
492      *                        the result set
493      * @return mixed resource handle for the prepared query on success, a MDB2
494      *        error on failure
495      * @access public
496      * @see bindParam, execute
497      */
498     function &prepare($query, $types = null, $result_types = null)
499     {
500         $this->debug($query, 'prepare');
501         $query = $this->_modifyQuery($query);
502         $contains_lobs = false;
503         if (is_array($types)) {
504             $columns = $variables = '';
505             foreach ($types as $parameter => $type) {
506                 if ($type == 'clob' || $type == 'blob') {
507                     $contains_lobs = true;
508                     $columns.= ($columns ? ', ' : ' RETURNING ').$parameter;
509                     $variables.= ($variables ? ', ' : ' INTO ').':'.$parameter;
510                 }
511             }
512         }
513         $placeholder_type_guess = $placeholder_type = null;
514         $question = '?';
515         $colon = ':';
516         $position = 0;
517         $parameter = -1;
518         while ($position < strlen($query)) {
519             $q_position = strpos($query, $question, $position);
520             $c_position = strpos($query, $colon, $position);
521             if ($q_position && $c_position) {
522                 $p_position = min($q_position, $c_position);
523             } elseif ($q_position) {
524                 $p_position = $q_position;
525             } elseif ($c_position) {
526                 $p_position = $c_position;
527             } else {
528                 break;
529             }
530             if (is_null($placeholder_type)) {
531                 $placeholder_type_guess = $query[$p_position];
532             }
533             if (is_int($quote = strpos($query, "'", $position)) && $quote < $p_position) {
534                 if (!is_int($end_quote = strpos($query, "'", $quote + 1))) {
535                     $err =& $this->raiseError(MDB2_ERROR_SYNTAX, null, null,
536                         'prepare: query with an unterminated text string specified');
537                     return $err;
538                 }
539                 switch ($this->escape_quotes) {
540                 case '':
541                 case "'":
542                     $position = $end_quote + 1;
543                     break;
544                 default:
545                     if ($end_quote == $quote + 1) {
546                         $position = $end_quote + 1;
547                     } else {
548                         if ($query[$end_quote-1] == $this->escape_quotes) {
549                             $position = $end_quote;
550                         } else {
551                             $position = $end_quote + 1;
552                         }
553                     }
554                     break;
555                 }
556             } elseif ($query[$position] == $placeholder_type_guess) {
557                 if ($placeholder_type_guess == ':' && !$contains_lobs) {
558                     break;
559                 }
560                 if (is_null($placeholder_type)) {
561                     $placeholder_type = $query[$p_position];
562                     $question = $colon = $placeholder_type;
563                 }
564                 if ($contains_lobs) {
565                     if ($placeholder_type == ':') {
566                         $parameter = preg_replace('/^.{'.($position+1).'}([a-z0-9_]+).*$/si', '\\1', $query);
567                         if ($parameter === '') {
568                             $err =& $this->raiseError(MDB2_ERROR_SYNTAX, null, null,
569                                 'prepare: named parameter with an empty name');
570                             return $err;
571                         }
572                         $length = strlen($parameter)+1;
573                     } else {
574                         ++$parameter;
575                         $length = strlen($parameter);
576                     }
577                     if (isset($types[$parameter])
578                         && ($types[$parameter] == 'clob' || $types[$parameter] == 'blob')
579                     ) {
580                         $value = $this->quote(true, $types[$parameter]);
581                         $query = substr_replace($query, $value, $p_position, $length);
582                         $position = $p_position + strlen($value) - 1;
583                     } elseif ($placeholder_type == '?') {
584                         $query = substr_replace($query, ':'.$parameter, $p_position, 1);
585                         $position = $p_position + strlen($parameter);
586                     }
587                 } else {
588                     $query = substr_replace($query, ':'.++$parameter, $p_position, 1);
589                     $position = $p_position + strlen($parameter);
590                 }
591             } else {
592                 $position = $p_position;
593             }
594         }
595         if (is_array($types)) {
596             $query.= $columns.$variables;
597         }
598         $statement = @OCIParse($this->connection, $query);
599         if (!$statement) {
600             $err =& $this->raiseError(MDB2_ERROR, null, null,
601                 'Could not create statement');
602             return $err;
603         }
604
605         $class_name = 'MDB2_Statement_'.$this->phptype;
606         $obj =& new $class_name($this, $statement, $query, $types, $result_types, $this->row_limit, $this->row_offset);
607         return $obj;
608     }
609
610     // }}}
611     // {{{ nextID()
612
613     /**
614      * returns the next free id of a sequence
615      *
616      * @param string $seq_name name of the sequence
617      * @param boolean $ondemand when true the seqence is
618      *                           automatic created, if it
619      *                           not exists
620      * @return mixed MDB2 Error Object or id
621      * @access public
622      */
623     function nextID($seq_name, $ondemand = true)
624     {
625         $sequence_name = $this->getSequenceName($seq_name);
626         $query = "SELECT $sequence_name.nextval FROM DUAL";
627         $this->expectError(MDB2_ERROR_NOSUCHTABLE);
628         $result = $this->queryOne($query, 'integer');
629         $this->popExpect();
630         if (PEAR::isError($result)) {
631             if ($ondemand && $result->getCode() == MDB2_ERROR_NOSUCHTABLE) {
632                 $this->loadModule('Manager');
633                 $result = $this->manager->createSequence($seq_name, 1);
634                 if (PEAR::isError($result)) {
635                     return $result;
636                 }
637                 return $this->nextId($seq_name, false);
638             }
639         }
640         return $result;
641     }
642
643     // }}}
644     // {{{ currId()
645
646     /**
647      * returns the current id of a sequence
648      *
649      * @param string $seq_name name of the sequence
650      * @return mixed MDB2_Error or id
651      * @access public
652      */
653     function currId($seq_name)
654     {
655         $sequence_name = $this->getSequenceName($seq_name);
656         return $this->queryOne("SELECT $sequence_name.currval FROM DUAL");
657     }
658 }
659
660 class MDB2_Result_oci8 extends MDB2_Result_Common
661 {
662     // {{{ _skipLimitOffset()
663
664     /**
665      * Skip the first row of a result set.
666      *
667      * @param resource $result
668      * @return mixed a result handle or MDB2_OK on success, a MDB2 error on failure
669      * @access protected
670      */
671     function _skipLimitOffset()
672     {
673         if ($this->limit) {
674             if ($this->rownum > $this->limit) {
675                 return false;
676             }
677         }
678         if ($this->offset) {
679             while ($this->offset_count < $this->offset) {
680                 ++$this->offset_count;
681                 if (!@OCIFetchInto($this->result, $row, OCI_RETURN_NULLS)) {
682                     $this->offset_count = $this->offset;
683                     return false;
684                 }
685             }
686         }
687         return true;
688     }
689
690     // }}}
691     // {{{ fetchRow()
692
693     /**
694      * Fetch a row and insert the data into an existing array.
695      *
696      * @param int       $fetchmode  how the array data should be indexed
697      * @param int    $rownum    number of the row where the data can be found
698      * @return int data array on success, a MDB2 error on failure
699      * @access public
700      */
701     function &fetchRow($fetchmode = MDB2_FETCHMODE_DEFAULT, $rownum = null)
702     {
703         if (!$this->_skipLimitOffset()) {
704             $null = null;
705             return $null;
706         }
707         if (!is_null($rownum)) {
708             $seek = $this->seek($rownum);
709             if (PEAR::isError($seek)) {
710                 return $seek;
711             }
712         }
713         if ($fetchmode == MDB2_FETCHMODE_DEFAULT) {
714             $fetchmode = $this->db->fetchmode;
715         }
716         if ($fetchmode & MDB2_FETCHMODE_ASSOC) {
717             @OCIFetchInto($this->result, $row, OCI_ASSOC+OCI_RETURN_NULLS);
718             if (is_array($row)
719                 && $this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE
720             ) {
721                 $row = array_change_key_case($row, $this->db->options['field_case']);
722             }
723         } else {
724             @OCIFetchInto($this->result, $row, OCI_RETURN_NULLS);
725         }
726         if (!$row) {
727             if (is_null($this->result)) {
728                 $err =& $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
729                     'fetchRow: resultset has already been freed');
730                 return $err;
731             }
732             $null = null;
733             return $null;
734
735         }
736         if ($this->db->options['portability'] & MDB2_PORTABILITY_RTRIM) {
737             $this->db->_fixResultArrayValues($row, MDB2_PORTABILITY_RTRIM);
738         }
739         if (!empty($this->values)) {
740             $this->_assignBindColumns($row);
741         }
742         if (!empty($this->types)) {
743             $row = $this->db->datatype->convertResultRow($this->types, $row);
744         }
745         if ($fetchmode === MDB2_FETCHMODE_OBJECT) {
746             $object_class = $this->db->options['fetch_class'];
747             if ($object_class == 'stdClass') {
748                 $row = (object) $row;
749             } else {
750                 $row = &new $object_class($row);
751             }
752         }
753         ++$this->rownum;
754         return $row;
755     }
756
757     // }}}
758     // {{{ _getColumnNames()
759
760     /**
761      * Retrieve the names of columns returned by the DBMS in a query result.
762      *
763      * @return mixed associative array variable
764      *      that holds the names of columns. The indexes of the array are
765      *      the column names mapped to lower case and the values are the
766      *      respective numbers of the columns starting from 0. Some DBMS may
767      *      not return any columns when the result set does not contain any
768      *      rows.
769      * @access private
770      */
771     function _getColumnNames()
772     {
773         $columns = array();
774         $numcols = $this->numCols();
775         if (PEAR::isError($numcols)) {
776             return $numcols;
777         }
778         for ($column = 0; $column < $numcols; $column++) {
779             $column_name = @OCIColumnName($this->result, $column + 1);
780             $columns[$column_name] = $column;
781         }
782         if ($this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
783             $columns = array_change_key_case($columns, $this->db->options['field_case']);
784         }
785         return $columns;
786     }
787
788     // }}}
789     // {{{ numCols()
790
791     /**
792      * Count the number of columns returned by the DBMS in a query result.
793      *
794      * @return mixed integer value with the number of columns, a MDB2 error
795      *      on failure
796      * @access public
797      */
798     function numCols()
799     {
800         $cols = @OCINumCols($this->result);
801         if (is_null($cols)) {
802             if (is_null($this->result)) {
803                 return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
804                     'numCols: resultset has already been freed');
805             }
806             return $this->db->raiseError();
807         }
808         return $cols;
809     }
810
811     // }}}
812     // {{{ free()
813
814     /**
815      * Free the internal resources associated with $result.
816      *
817      * @return boolean true on success, false if $result is invalid
818      * @access public
819      */
820     function free()
821     {
822         $free = @OCIFreeCursor($this->result);
823         if (!$free) {
824             if (is_null($this->result)) {
825                 return MDB2_OK;
826             }
827             return $this->db->raiseError();
828         }
829         $this->result = null;
830         return MDB2_OK;
831     }
832 }
833
834 class MDB2_BufferedResult_oci8 extends MDB2_Result_oci8
835 {
836     var $buffer;
837     var $buffer_rownum = - 1;
838
839     // {{{ _fillBuffer()
840
841     /**
842      * Fill the row buffer
843      *
844      * @param int $rownum   row number upto which the buffer should be filled
845                             if the row number is null all rows are ready into the buffer
846      * @return boolean true on success, false on failure
847      * @access protected
848      */
849     function _fillBuffer($rownum = null)
850     {
851         if (isset($this->buffer) && is_array($this->buffer)) {
852             if (is_null($rownum)) {
853                 if (!end($this->buffer)) {
854                     return false;
855                 }
856             } elseif (isset($this->buffer[$rownum])) {
857                 return (bool)$this->buffer[$rownum];
858             }
859         }
860
861         if (!$this->_skipLimitOffset()) {
862             return false;
863         }
864
865         $row = true;
866         while ((is_null($rownum) || $this->buffer_rownum < $rownum)
867             && (!$this->limit || $this->buffer_rownum < $this->limit)
868             && ($row = @OCIFetchInto($this->result, $buffer, OCI_RETURN_NULLS))
869         ) {
870             ++$this->buffer_rownum;
871             $this->buffer[$this->buffer_rownum] = $buffer;
872         }
873
874         if (!$row) {
875             ++$this->buffer_rownum;
876             $this->buffer[$this->buffer_rownum] = false;
877             return false;
878         } elseif ($this->limit && $this->buffer_rownum >= $this->limit) {
879             ++$this->buffer_rownum;
880             $this->buffer[$this->buffer_rownum] = false;
881         }
882         return true;
883     }
884
885     // }}}
886     // {{{ fetchRow()
887
888     /**
889      * Fetch a row and insert the data into an existing array.
890      *
891      * @param int       $fetchmode  how the array data should be indexed
892      * @param int    $rownum    number of the row where the data can be found
893      * @return int data array on success, a MDB2 error on failure
894      * @access public
895      */
896     function &fetchRow($fetchmode = MDB2_FETCHMODE_DEFAULT, $rownum = null)
897     {
898         if (is_null($this->result)) {
899             $err =& $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
900                 'fetchRow: resultset has already been freed');
901             return $err;
902         }
903         if (!is_null($rownum)) {
904             $seek = $this->seek($rownum);
905             if (PEAR::isError($seek)) {
906                 return $seek;
907             }
908         }
909         $target_rownum = $this->rownum + 1;
910         if ($fetchmode == MDB2_FETCHMODE_DEFAULT) {
911             $fetchmode = $this->db->fetchmode;
912         }
913         if (!$this->_fillBuffer($target_rownum)) {
914             $null = null;
915             return $null;
916         }
917         $row = $this->buffer[$target_rownum];
918         if ($fetchmode & MDB2_FETCHMODE_ASSOC) {
919             $column_names = $this->getColumnNames();
920             foreach ($column_names as $name => $i) {
921                 $column_names[$name] = $row[$i];
922             }
923             $row = $column_names;
924         }
925         if (!empty($this->values)) {
926             $this->_assignBindColumns($row);
927         }
928         if (!empty($this->types)) {
929             $row = $this->db->datatype->convertResultRow($this->types, $row);
930         }
931         if ($this->db->options['portability'] & MDB2_PORTABILITY_RTRIM) {
932             $this->db->_fixResultArrayValues($row, MDB2_PORTABILITY_RTRIM);
933         }
934         if ($fetchmode === MDB2_FETCHMODE_OBJECT) {
935             $object_class = $this->db->options['fetch_class'];
936             if ($object_class == 'stdClass') {
937                 $row = (object) $row;
938             } else {
939                 $row = &new $object_class($row);
940             }
941         }
942         ++$this->rownum;
943         return $row;
944     }
945
946     // }}}
947     // {{{ seek()
948
949     /**
950     * seek to a specific row in a result set
951     *
952     * @param int    $rownum    number of the row where the data can be found
953     * @return mixed MDB2_OK on success, a MDB2 error on failure
954     * @access public
955     */
956     function seek($rownum = 0)
957     {
958         if (is_null($this->result)) {
959             return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
960                 'seek: resultset has already been freed');
961         }
962         $this->rownum = $rownum - 1;
963         return MDB2_OK;
964     }
965
966     // }}}
967     // {{{ valid()
968
969     /**
970      * check if the end of the result set has been reached
971      *
972      * @return mixed true or false on sucess, a MDB2 error on failure
973      * @access public
974      */
975     function valid()
976     {
977         if (is_null($this->result)) {
978             return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
979                 'valid: resultset has already been freed');
980         }
981         if ($this->_fillBuffer($this->rownum + 1)) {
982             return true;
983         }
984         return false;
985     }
986
987     // }}}
988     // {{{ numRows()
989
990     /**
991      * returns the number of rows in a result object
992      *
993      * @return mixed MDB2 Error Object or the number of rows
994      * @access public
995      */
996     function numRows()
997     {
998         if (is_null($this->result)) {
999             return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
1000                 'seek: resultset has already been freed');
1001         }
1002         $this->_fillBuffer();
1003         return $this->buffer_rownum;
1004     }
1005
1006     // }}}
1007     // {{{ free()
1008
1009     /**
1010      * Free the internal resources associated with $result.
1011      *
1012      * @return boolean true on success, false if $result is invalid
1013      * @access public
1014      */
1015     function free()
1016     {
1017         $this->buffer = null;
1018         $this->buffer_rownum = null;
1019         $free = parent::free();
1020     }
1021 }
1022
1023 class MDB2_Statement_oci8 extends MDB2_Statement_Common
1024 {
1025     // }}}
1026     // {{{ _execute()
1027
1028     /**
1029      * Execute a prepared query statement helper method.
1030      *
1031      * @param mixed $result_class string which specifies which result class to use
1032      * @param mixed $result_wrap_class string which specifies which class to wrap results in
1033      * @return mixed a result handle or MDB2_OK on success, a MDB2 error on failure
1034      * @access private
1035      */
1036     function &_execute($result_class = true, $result_wrap_class = false)
1037     {
1038         $isManip = MDB2::isManip($this->query);
1039         $this->db->last_query = $this->query;
1040         $this->db->debug($this->query, 'execute');
1041         if ($this->db->getOption('disable_query')) {
1042             if ($isManip) {
1043                 $return = 0;
1044                 return $return;
1045             }
1046             $null = null;
1047             return $null;
1048         }
1049
1050         $connected = $this->db->connect();
1051         if (PEAR::isError($connected)) {
1052             return $connected;
1053         }
1054
1055         $result = MDB2_OK;
1056         $lobs = $quoted_values = array();
1057         $i = 0;
1058         foreach ($this->values as $parameter => $value) {
1059             $type = array_key_exists($parameter, $this->types) ? $this->types[$parameter] : null;
1060             if ($type == 'clob' || $type == 'blob') {
1061                 $lobs[$i]['file'] = false;
1062                 if (is_resource($value)) {
1063                     $fp = $value;
1064                     $value = '';
1065                     while (!feof($fp)) {
1066                         $value.= fread($fp, 8192);
1067                     }
1068                 } elseif (preg_match('/^(\w+:\/\/)(.*)$/', $value, $match)) {
1069                     $lobs[$i]['file'] = true;
1070                     if ($match[1] == 'file://') {
1071                         $value = $match[2];
1072                     }
1073                 }
1074                 $lobs[$i]['value'] = $value;
1075                 $lobs[$i]['descriptor'] = @OCINewDescriptor($this->db->connection, OCI_D_LOB);
1076                 if (!is_object($lobs[$i]['descriptor'])) {
1077                     $result = $this->db->raiseError();
1078                     break;
1079                 }
1080                 $lob_type = ($type == 'blob' ? OCI_B_BLOB : OCI_B_CLOB);
1081                 if (!@OCIBindByName($this->statement, ':'.$parameter, $lobs[$i]['descriptor'], -1, $lob_type)) {
1082                     $result = $this->db->raiseError($this->statement);
1083                     break;
1084                 }
1085             } else {
1086                 $quoted_values[$i] = $this->db->quote($value, $type, false);
1087                 if (PEAR::isError($quoted_values[$i])) {
1088                     return $quoted_values[$i];
1089                 }
1090                 if (!@OCIBindByName($this->statement, ':'.$parameter, $quoted_values[$i])) {
1091                     $result = $this->db->raiseError($this->statement);
1092                     break;
1093                 }
1094             }
1095             ++$i;
1096         }
1097
1098         if (!PEAR::isError($result)) {
1099             $mode = (!empty($lobs) || $this->db->in_transaction) ? OCI_DEFAULT : OCI_COMMIT_ON_SUCCESS;
1100             if (!@OCIExecute($this->statement, $mode)) {
1101                 $err =& $this->db->raiseError($this->statement);
1102                 return $err;
1103             }
1104
1105             if (!empty($lobs)) {
1106                 foreach ($lobs as $i => $stream) {
1107                     if (!is_null($stream['value']) && $stream['value'] !== '') {
1108                         if ($stream['file']) {
1109                             $result = $lobs[$i]['descriptor']->savefile($stream['value']);
1110                         } else {
1111                             $result = $lobs[$i]['descriptor']->save($stream['value']);
1112                         }
1113                         if (!$result) {
1114                             $result = $this->db->raiseError();
1115                             break;
1116                         }
1117                     }
1118                 }
1119
1120                 if (!PEAR::isError($result)) {
1121                     if (!$this->db->in_transaction) {
1122                         if (!@OCICommit($this->db->connection)) {
1123                             $result = $this->db->raiseError();
1124                         }
1125                     } else {
1126                         ++$this->db->uncommitedqueries;
1127                     }
1128                 }
1129             }
1130         }
1131
1132         $keys = array_keys($lobs);
1133         foreach ($keys as $key) {
1134             $lobs[$key]['descriptor']->free();
1135         }
1136
1137         if (PEAR::isError($result)) {
1138             return $result;
1139         }
1140
1141         if ($isManip) {
1142             $return = @OCIRowCount($this->statement);
1143         } else {
1144             $return = $this->db->_wrapResult($this->statement, $isManip, $this->types,
1145                 $result_class, $result_wrap_class, $this->row_offset, $this->row_limit);
1146         }
1147         return $return;
1148     }
1149
1150     // }}}
1151     // {{{ free()
1152
1153     /**
1154      * Release resources allocated for the specified prepared query.
1155      *
1156      * @return mixed MDB2_OK on success, a MDB2 error on failure
1157      * @access public
1158      */
1159     function free()
1160     {
1161         if (!@OCIFreeStatement($this->statement)) {
1162             return $this->db->raiseError();
1163         }
1164         return MDB2_OK;
1165     }
1166 }
1167 ?>